mongoose.c 157 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966
  1. // Copyright (c) 2004-2012 Sergey Lyubka
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. #if defined(_WIN32)
  21. #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005
  22. #else
  23. #ifdef __linux__
  24. #define _XOPEN_SOURCE 600 // For flockfile() on Linux
  25. #endif
  26. #define _LARGEFILE_SOURCE // Enable 64-bit file offsets
  27. #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++
  28. #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX
  29. #endif
  30. #ifdef WIN32_LEAN_AND_MEAN
  31. #undef WIN32_LEAN_AND_MEAN // Disable WIN32_LEAN_AND_MEAN, if necessary
  32. #endif
  33. #if defined(__SYMBIAN32__)
  34. #define NO_SSL // SSL is not supported
  35. #define NO_CGI // CGI is not supported
  36. #define PATH_MAX FILENAME_MAX
  37. #endif // __SYMBIAN32__
  38. #ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE
  39. #include <sys/types.h>
  40. #include <sys/stat.h>
  41. #include <errno.h>
  42. #include <signal.h>
  43. #include <fcntl.h>
  44. #endif // !_WIN32_WCE
  45. #include <time.h>
  46. #include <stdlib.h>
  47. #include <stdarg.h>
  48. #include <assert.h>
  49. #include <string.h>
  50. #include <ctype.h>
  51. #include <limits.h>
  52. #include <stddef.h>
  53. #include <stdio.h>
  54. #if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific
  55. #define _WIN32_WINNT 0x0400 // To make it link in VS2005
  56. #include <windows.h>
  57. #include <winsock2.h>
  58. #include <ws2tcpip.h>
  59. #ifndef PATH_MAX
  60. #define PATH_MAX MAX_PATH
  61. #endif
  62. #ifndef _WIN32_WCE
  63. #include <process.h>
  64. #include <direct.h>
  65. #include <io.h>
  66. #else // _WIN32_WCE
  67. #define NO_CGI // WinCE has no pipes
  68. typedef long off_t;
  69. #define errno GetLastError()
  70. #define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
  71. #endif // _WIN32_WCE
  72. #define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
  73. ((uint64_t)((uint32_t)(hi))) << 32))
  74. #define RATE_DIFF 10000000 // 100 nsecs
  75. #define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)
  76. #define SYS2UNIX_TIME(lo, hi) \
  77. (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
  78. // Visual Studio 6 does not know __func__ or __FUNCTION__
  79. // The rest of MS compilers use __FUNCTION__, not C99 __func__
  80. // Also use _strtoui64 on modern M$ compilers
  81. #if defined(_MSC_VER) && _MSC_VER < 1300
  82. #define STRX(x) #x
  83. #define STR(x) STRX(x)
  84. #define __func__ "line " STR(__LINE__)
  85. #define strtoull(x, y, z) strtoul(x, y, z)
  86. #define strtoll(x, y, z) strtol(x, y, z)
  87. #else
  88. #define __func__ __FUNCTION__
  89. #define strtoull(x, y, z) _strtoui64(x, y, z)
  90. #define strtoll(x, y, z) _strtoi64(x, y, z)
  91. #endif // _MSC_VER
  92. #define ERRNO GetLastError()
  93. #define NO_SOCKLEN_T
  94. #define SSL_LIB "ssleay32.dll"
  95. #define CRYPTO_LIB "libeay32.dll"
  96. #define O_NONBLOCK 0
  97. #if !defined(EWOULDBLOCK)
  98. #define EWOULDBLOCK WSAEWOULDBLOCK
  99. #endif // !EWOULDBLOCK
  100. #define _POSIX_
  101. #define INT64_FMT "I64d"
  102. #define WINCDECL __cdecl
  103. #define SHUT_WR 1
  104. #define snprintf _snprintf
  105. #define vsnprintf _vsnprintf
  106. #define mg_sleep(x) Sleep(x)
  107. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  108. #define popen(x, y) _popen(x, y)
  109. #define pclose(x) _pclose(x)
  110. #define close(x) _close(x)
  111. #define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
  112. #define RTLD_LAZY 0
  113. #define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))
  114. #define fdopen(x, y) _fdopen((x), (y))
  115. #define write(x, y, z) _write((x), (y), (unsigned) z)
  116. #define read(x, y, z) _read((x), (y), (unsigned) z)
  117. #define flockfile(x) EnterCriticalSection(&global_log_file_lock)
  118. #define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)
  119. #define sleep(x) Sleep((x) * 1000)
  120. #if !defined(fileno)
  121. #define fileno(x) _fileno(x)
  122. #endif // !fileno MINGW #defines fileno
  123. typedef HANDLE pthread_mutex_t;
  124. typedef struct {HANDLE signal, broadcast;} pthread_cond_t;
  125. typedef DWORD pthread_t;
  126. #define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here.
  127. static int pthread_mutex_lock(pthread_mutex_t *);
  128. static int pthread_mutex_unlock(pthread_mutex_t *);
  129. static FILE *mg_fopen(const char *path, const char *mode);
  130. #if defined(HAVE_STDINT)
  131. #include <stdint.h>
  132. #else
  133. typedef unsigned int uint32_t;
  134. typedef unsigned short uint16_t;
  135. typedef unsigned __int64 uint64_t;
  136. typedef __int64 int64_t;
  137. #define INT64_MAX 9223372036854775807
  138. #endif // HAVE_STDINT
  139. // POSIX dirent interface
  140. struct dirent {
  141. char d_name[PATH_MAX];
  142. };
  143. typedef struct DIR {
  144. HANDLE handle;
  145. WIN32_FIND_DATAW info;
  146. struct dirent result;
  147. } DIR;
  148. // Mark required libraries
  149. #pragma comment(lib, "Ws2_32.lib")
  150. #else // UNIX specific
  151. #include <sys/wait.h>
  152. #include <sys/socket.h>
  153. #include <sys/select.h>
  154. #include <netinet/in.h>
  155. #include <arpa/inet.h>
  156. #include <sys/time.h>
  157. #include <stdint.h>
  158. #include <inttypes.h>
  159. #include <netdb.h>
  160. #include <pwd.h>
  161. #include <unistd.h>
  162. #include <dirent.h>
  163. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  164. #include <dlfcn.h>
  165. #endif
  166. #include <pthread.h>
  167. #if defined(__MACH__)
  168. #define SSL_LIB "libssl.dylib"
  169. #define CRYPTO_LIB "libcrypto.dylib"
  170. #else
  171. #if !defined(SSL_LIB)
  172. #define SSL_LIB "libssl.so"
  173. #endif
  174. #if !defined(CRYPTO_LIB)
  175. #define CRYPTO_LIB "libcrypto.so"
  176. #endif
  177. #endif
  178. #ifndef O_BINARY
  179. #define O_BINARY 0
  180. #endif // O_BINARY
  181. #define closesocket(a) close(a)
  182. #define mg_fopen(x, y) fopen(x, y)
  183. #define mg_mkdir(x, y) mkdir(x, y)
  184. #define mg_remove(x) remove(x)
  185. #define mg_rename(x, y) rename(x, y)
  186. #define mg_sleep(x) usleep((x) * 1000)
  187. #define ERRNO errno
  188. #define INVALID_SOCKET (-1)
  189. #define INT64_FMT PRId64
  190. typedef int SOCKET;
  191. #define WINCDECL
  192. #endif // End of Windows and UNIX specific includes
  193. #include "mongoose.h"
  194. #ifdef USE_LUA
  195. #include <lua.h>
  196. #include <lauxlib.h>
  197. #endif
  198. #define MONGOOSE_VERSION "3.4"
  199. #define PASSWORDS_FILE_NAME ".htpasswd"
  200. #define CGI_ENVIRONMENT_SIZE 4096
  201. #define MAX_CGI_ENVIR_VARS 64
  202. #define MG_BUF_LEN 8192
  203. #define MAX_REQUEST_SIZE 16384
  204. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  205. #ifdef _WIN32
  206. static CRITICAL_SECTION global_log_file_lock;
  207. static pthread_t pthread_self(void) {
  208. return GetCurrentThreadId();
  209. }
  210. #endif // _WIN32
  211. #ifdef DEBUG_TRACE
  212. #undef DEBUG_TRACE
  213. #define DEBUG_TRACE(x)
  214. #else
  215. #if defined(DEBUG)
  216. #define DEBUG_TRACE(x) do { \
  217. flockfile(stdout); \
  218. printf("*** %lu.%p.%s.%d: ", \
  219. (unsigned long) time(NULL), (void *) pthread_self(), \
  220. __func__, __LINE__); \
  221. printf x; \
  222. putchar('\n'); \
  223. fflush(stdout); \
  224. funlockfile(stdout); \
  225. } while (0)
  226. #else
  227. #define DEBUG_TRACE(x)
  228. #endif // DEBUG
  229. #endif // DEBUG_TRACE
  230. // Darwin prior to 7.0 and Win32 do not have socklen_t
  231. #ifdef NO_SOCKLEN_T
  232. typedef int socklen_t;
  233. #endif // NO_SOCKLEN_T
  234. #define _DARWIN_UNLIMITED_SELECT
  235. #if !defined(MSG_NOSIGNAL)
  236. #define MSG_NOSIGNAL 0
  237. #endif
  238. #if !defined(SOMAXCONN)
  239. #define SOMAXCONN 100
  240. #endif
  241. #if !defined(PATH_MAX)
  242. #define PATH_MAX 4096
  243. #endif
  244. static const char *http_500_error = "Internal Server Error";
  245. // Snatched from OpenSSL includes. I put the prototypes here to be independent
  246. // from the OpenSSL source installation. Having this, mongoose + SSL can be
  247. // built on any system with binary SSL libraries installed.
  248. typedef struct ssl_st SSL;
  249. typedef struct ssl_method_st SSL_METHOD;
  250. typedef struct ssl_ctx_st SSL_CTX;
  251. #define SSL_ERROR_WANT_READ 2
  252. #define SSL_ERROR_WANT_WRITE 3
  253. #define SSL_FILETYPE_PEM 1
  254. #define CRYPTO_LOCK 1
  255. #if defined(NO_SSL_DL)
  256. extern void SSL_free(SSL *);
  257. extern int SSL_accept(SSL *);
  258. extern int SSL_connect(SSL *);
  259. extern int SSL_read(SSL *, void *, int);
  260. extern int SSL_write(SSL *, const void *, int);
  261. extern int SSL_get_error(const SSL *, int);
  262. extern int SSL_set_fd(SSL *, int);
  263. extern SSL *SSL_new(SSL_CTX *);
  264. extern SSL_CTX *SSL_CTX_new(SSL_METHOD *);
  265. extern SSL_METHOD *SSLv23_server_method(void);
  266. extern SSL_METHOD *SSLv23_client_method(void);
  267. extern int SSL_library_init(void);
  268. extern void SSL_load_error_strings(void);
  269. extern int SSL_CTX_use_PrivateKey_file(SSL_CTX *, const char *, int);
  270. extern int SSL_CTX_use_certificate_file(SSL_CTX *, const char *, int);
  271. extern int SSL_CTX_use_certificate_chain_file(SSL_CTX *, const char *);
  272. extern void SSL_CTX_set_default_passwd_cb(SSL_CTX *, mg_callback_t);
  273. extern void SSL_CTX_free(SSL_CTX *);
  274. extern unsigned long ERR_get_error(void);
  275. extern char *ERR_error_string(unsigned long, char *);
  276. extern int CRYPTO_num_locks(void);
  277. extern void CRYPTO_set_locking_callback(void (*)(int, int, const char *, int));
  278. extern void CRYPTO_set_id_callback(unsigned long (*)(void));
  279. #else
  280. // Dynamically loaded SSL functionality
  281. struct ssl_func {
  282. const char *name; // SSL function name
  283. void (*ptr)(void); // Function pointer
  284. };
  285. #define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)
  286. #define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)
  287. #define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)
  288. #define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)
  289. #define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)
  290. #define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)
  291. #define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)
  292. #define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  293. #define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  294. #define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  295. #define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)
  296. #define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \
  297. const char *, int)) ssl_sw[11].ptr)
  298. #define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \
  299. const char *, int)) ssl_sw[12].ptr)
  300. #define SSL_CTX_set_default_passwd_cb \
  301. (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)
  302. #define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)
  303. #define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)
  304. #define SSL_CTX_use_certificate_chain_file \
  305. (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)
  306. #define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  307. #define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)
  308. #define CRYPTO_set_locking_callback \
  309. (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)
  310. #define CRYPTO_set_id_callback \
  311. (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)
  312. #define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)
  313. #define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)
  314. // set_ssl_option() function updates this array.
  315. // It loads SSL library dynamically and changes NULLs to the actual addresses
  316. // of respective functions. The macros above (like SSL_connect()) are really
  317. // just calling these functions indirectly via the pointer.
  318. static struct ssl_func ssl_sw[] = {
  319. {"SSL_free", NULL},
  320. {"SSL_accept", NULL},
  321. {"SSL_connect", NULL},
  322. {"SSL_read", NULL},
  323. {"SSL_write", NULL},
  324. {"SSL_get_error", NULL},
  325. {"SSL_set_fd", NULL},
  326. {"SSL_new", NULL},
  327. {"SSL_CTX_new", NULL},
  328. {"SSLv23_server_method", NULL},
  329. {"SSL_library_init", NULL},
  330. {"SSL_CTX_use_PrivateKey_file", NULL},
  331. {"SSL_CTX_use_certificate_file",NULL},
  332. {"SSL_CTX_set_default_passwd_cb",NULL},
  333. {"SSL_CTX_free", NULL},
  334. {"SSL_load_error_strings", NULL},
  335. {"SSL_CTX_use_certificate_chain_file", NULL},
  336. {"SSLv23_client_method", NULL},
  337. {NULL, NULL}
  338. };
  339. // Similar array as ssl_sw. These functions could be located in different lib.
  340. #if !defined(NO_SSL)
  341. static struct ssl_func crypto_sw[] = {
  342. {"CRYPTO_num_locks", NULL},
  343. {"CRYPTO_set_locking_callback", NULL},
  344. {"CRYPTO_set_id_callback", NULL},
  345. {"ERR_get_error", NULL},
  346. {"ERR_error_string", NULL},
  347. {NULL, NULL}
  348. };
  349. #endif // NO_SSL
  350. #endif // NO_SSL_DL
  351. static const char *month_names[] = {
  352. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  353. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  354. };
  355. // Unified socket address. For IPv6 support, add IPv6 address structure
  356. // in the union u.
  357. union usa {
  358. struct sockaddr sa;
  359. struct sockaddr_in sin;
  360. #if defined(USE_IPV6)
  361. struct sockaddr_in6 sin6;
  362. #endif
  363. };
  364. // Describes a string (chunk of memory).
  365. struct vec {
  366. const char *ptr;
  367. size_t len;
  368. };
  369. // Structure used by mg_stat() function. Uses 64 bit file length.
  370. struct mgstat {
  371. int is_directory; // Directory marker
  372. int64_t size; // File size
  373. time_t mtime; // Modification time
  374. };
  375. // Describes listening socket, or socket which was accept()-ed by the master
  376. // thread and queued for future handling by the worker thread.
  377. struct socket {
  378. struct socket *next; // Linkage
  379. SOCKET sock; // Listening socket
  380. union usa lsa; // Local socket address
  381. union usa rsa; // Remote socket address
  382. int is_ssl; // Is socket SSL-ed
  383. };
  384. // NOTE(lsm): this enum shoulds be in sync with the config_options below.
  385. enum {
  386. CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,
  387. PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,
  388. ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,
  389. GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,
  390. EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,
  391. NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES,
  392. NUM_OPTIONS
  393. };
  394. static const char *config_options[] = {
  395. "C", "cgi_pattern", "**.cgi$|**.pl$|**.php$",
  396. "E", "cgi_environment", NULL,
  397. "G", "put_delete_passwords_file", NULL,
  398. "I", "cgi_interpreter", NULL,
  399. "P", "protect_uri", NULL,
  400. "R", "authentication_domain", "mydomain.com",
  401. "S", "ssi_pattern", "**.shtml$|**.shtm$",
  402. "T", "throttle", NULL,
  403. "a", "access_log_file", NULL,
  404. "d", "enable_directory_listing", "yes",
  405. "e", "error_log_file", NULL,
  406. "g", "global_passwords_file", NULL,
  407. "i", "index_files", "index.html,index.htm,index.cgi,index.shtml,index.php",
  408. "k", "enable_keep_alive", "no",
  409. "l", "access_control_list", NULL,
  410. "m", "extra_mime_types", NULL,
  411. "p", "listening_ports", "8080",
  412. "r", "document_root", ".",
  413. "s", "ssl_certificate", NULL,
  414. "t", "num_threads", "20",
  415. "u", "run_as_user", NULL,
  416. "w", "url_rewrite_patterns", NULL,
  417. "x", "hide_files_patterns", NULL,
  418. NULL
  419. };
  420. #define ENTRIES_PER_CONFIG_OPTION 3
  421. struct mg_context {
  422. volatile int stop_flag; // Should we stop event loop
  423. SSL_CTX *ssl_ctx; // SSL context
  424. SSL_CTX *client_ssl_ctx; // Client SSL context
  425. char *config[NUM_OPTIONS]; // Mongoose configuration parameters
  426. mg_callback_t user_callback; // User-defined callback function
  427. void *user_data; // User-defined data
  428. struct socket *listening_sockets;
  429. volatile int num_threads; // Number of threads
  430. pthread_mutex_t mutex; // Protects (max|num)_threads
  431. pthread_cond_t cond; // Condvar for tracking workers terminations
  432. struct socket queue[20]; // Accepted sockets
  433. volatile int sq_head; // Head of the socket queue
  434. volatile int sq_tail; // Tail of the socket queue
  435. pthread_cond_t sq_full; // Signaled when socket is produced
  436. pthread_cond_t sq_empty; // Signaled when socket is consumed
  437. };
  438. struct mg_connection {
  439. struct mg_request_info request_info;
  440. struct mg_context *ctx;
  441. SSL *ssl; // SSL descriptor
  442. struct socket client; // Connected client
  443. time_t birth_time; // Time when request was received
  444. int64_t num_bytes_sent; // Total bytes sent to client
  445. int64_t content_len; // Content-Length header value
  446. int64_t consumed_content; // How many bytes of content have been read
  447. char *buf; // Buffer for received data
  448. char *path_info; // PATH_INFO part of the URL
  449. char *log_message; // Placeholder for the mongoose error log message
  450. int must_close; // 1 if connection must be closed
  451. int buf_size; // Buffer size
  452. int request_len; // Size of the request + headers in a buffer
  453. int data_len; // Total size of data in a buffer
  454. int status_code; // HTTP reply status code, e.g. 200
  455. int throttle; // Throttling, bytes/sec. <= 0 means no throttle
  456. time_t last_throttle_time; // Last time throttled data was sent
  457. int64_t last_throttle_bytes;// Bytes sent this second
  458. };
  459. const char **mg_get_valid_option_names(void) {
  460. return config_options;
  461. }
  462. static void *call_user(struct mg_connection *conn, enum mg_event event) {
  463. return conn == NULL || conn->ctx == NULL || conn->ctx->user_callback == NULL ?
  464. NULL : conn->ctx->user_callback(event, conn);
  465. }
  466. void *mg_get_user_data(struct mg_connection *conn) {
  467. return conn != NULL && conn->ctx != NULL ? conn->ctx->user_data : NULL;
  468. }
  469. const char *mg_get_log_message(const struct mg_connection *conn) {
  470. return conn == NULL ? NULL : conn->log_message;
  471. }
  472. int mg_get_reply_status_code(const struct mg_connection *conn) {
  473. return conn == NULL ? -1 : conn->status_code;
  474. }
  475. void *mg_get_ssl_context(const struct mg_connection *conn) {
  476. return conn == NULL || conn->ctx == NULL ? NULL : conn->ctx->ssl_ctx;
  477. }
  478. static int get_option_index(const char *name) {
  479. int i;
  480. for (i = 0; config_options[i] != NULL; i += ENTRIES_PER_CONFIG_OPTION) {
  481. if (strcmp(config_options[i], name) == 0 ||
  482. strcmp(config_options[i + 1], name) == 0) {
  483. return i / ENTRIES_PER_CONFIG_OPTION;
  484. }
  485. }
  486. return -1;
  487. }
  488. const char *mg_get_option(const struct mg_context *ctx, const char *name) {
  489. int i;
  490. if ((i = get_option_index(name)) == -1) {
  491. return NULL;
  492. } else if (ctx->config[i] == NULL) {
  493. return "";
  494. } else {
  495. return ctx->config[i];
  496. }
  497. }
  498. static void sockaddr_to_string(char *buf, size_t len,
  499. const union usa *usa) {
  500. buf[0] = '\0';
  501. #if defined(USE_IPV6)
  502. inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
  503. (void *) &usa->sin.sin_addr :
  504. (void *) &usa->sin6.sin6_addr, buf, len);
  505. #elif defined(_WIN32)
  506. // Only Windoze Vista (and newer) have inet_ntop()
  507. strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
  508. #else
  509. inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
  510. #endif
  511. }
  512. static void cry(struct mg_connection *conn,
  513. PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3);
  514. // Print error message to the opened error log stream.
  515. static void cry(struct mg_connection *conn, const char *fmt, ...) {
  516. char buf[MG_BUF_LEN], src_addr[20];
  517. va_list ap;
  518. FILE *fp;
  519. time_t timestamp;
  520. va_start(ap, fmt);
  521. (void) vsnprintf(buf, sizeof(buf), fmt, ap);
  522. va_end(ap);
  523. // Do not lock when getting the callback value, here and below.
  524. // I suppose this is fine, since function cannot disappear in the
  525. // same way string option can.
  526. conn->log_message = buf;
  527. if (call_user(conn, MG_EVENT_LOG) == NULL) {
  528. fp = conn->ctx == NULL || conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
  529. mg_fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  530. if (fp != NULL) {
  531. flockfile(fp);
  532. timestamp = time(NULL);
  533. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  534. fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,
  535. src_addr);
  536. if (conn->request_info.request_method != NULL) {
  537. fprintf(fp, "%s %s: ", conn->request_info.request_method,
  538. conn->request_info.uri);
  539. }
  540. (void) fprintf(fp, "%s", buf);
  541. fputc('\n', fp);
  542. funlockfile(fp);
  543. if (fp != stderr) {
  544. fclose(fp);
  545. }
  546. }
  547. }
  548. conn->log_message = NULL;
  549. }
  550. // Return fake connection structure. Used for logging, if connection
  551. // is not applicable at the moment of logging.
  552. static struct mg_connection *fc(struct mg_context *ctx) {
  553. static struct mg_connection fake_connection;
  554. fake_connection.ctx = ctx;
  555. return &fake_connection;
  556. }
  557. const char *mg_version(void) {
  558. return MONGOOSE_VERSION;
  559. }
  560. const struct mg_request_info *
  561. mg_get_request_info(const struct mg_connection *conn) {
  562. return &conn->request_info;
  563. }
  564. static void mg_strlcpy(register char *dst, register const char *src, size_t n) {
  565. for (; *src != '\0' && n > 1; n--) {
  566. *dst++ = *src++;
  567. }
  568. *dst = '\0';
  569. }
  570. static int lowercase(const char *s) {
  571. return tolower(* (const unsigned char *) s);
  572. }
  573. static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
  574. int diff = 0;
  575. if (len > 0)
  576. do {
  577. diff = lowercase(s1++) - lowercase(s2++);
  578. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  579. return diff;
  580. }
  581. static int mg_strcasecmp(const char *s1, const char *s2) {
  582. int diff;
  583. do {
  584. diff = lowercase(s1++) - lowercase(s2++);
  585. } while (diff == 0 && s1[-1] != '\0');
  586. return diff;
  587. }
  588. static char * mg_strndup(const char *ptr, size_t len) {
  589. char *p;
  590. if ((p = (char *) malloc(len + 1)) != NULL) {
  591. mg_strlcpy(p, ptr, len + 1);
  592. }
  593. return p;
  594. }
  595. static char * mg_strdup(const char *str) {
  596. return mg_strndup(str, strlen(str));
  597. }
  598. // Like snprintf(), but never returns negative value, or a value
  599. // that is larger than a supplied buffer.
  600. // Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  601. // in his audit report.
  602. static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
  603. const char *fmt, va_list ap) {
  604. int n;
  605. if (buflen == 0)
  606. return 0;
  607. n = vsnprintf(buf, buflen, fmt, ap);
  608. if (n < 0) {
  609. cry(conn, "vsnprintf error");
  610. n = 0;
  611. } else if (n >= (int) buflen) {
  612. cry(conn, "truncating vsnprintf buffer: [%.*s]",
  613. n > 200 ? 200 : n, buf);
  614. n = (int) buflen - 1;
  615. }
  616. buf[n] = '\0';
  617. return n;
  618. }
  619. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  620. PRINTF_FORMAT_STRING(const char *fmt), ...)
  621. PRINTF_ARGS(4, 5);
  622. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  623. const char *fmt, ...) {
  624. va_list ap;
  625. int n;
  626. va_start(ap, fmt);
  627. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  628. va_end(ap);
  629. return n;
  630. }
  631. // Skip the characters until one of the delimiters characters found.
  632. // 0-terminate resulting word. Skip the delimiter and following whitespaces if any.
  633. // Advance pointer to buffer to the next word. Return found 0-terminated word.
  634. // Delimiters can be quoted with quotechar.
  635. static char *skip_quoted(char **buf, const char *delimiters,
  636. const char *whitespace, char quotechar) {
  637. char *p, *begin_word, *end_word, *end_whitespace;
  638. begin_word = *buf;
  639. end_word = begin_word + strcspn(begin_word, delimiters);
  640. // Check for quotechar
  641. if (end_word > begin_word) {
  642. p = end_word - 1;
  643. while (*p == quotechar) {
  644. // If there is anything beyond end_word, copy it
  645. if (*end_word == '\0') {
  646. *p = '\0';
  647. break;
  648. } else {
  649. size_t end_off = strcspn(end_word + 1, delimiters);
  650. memmove (p, end_word, end_off + 1);
  651. p += end_off; // p must correspond to end_word - 1
  652. end_word += end_off + 1;
  653. }
  654. }
  655. for (p++; p < end_word; p++) {
  656. *p = '\0';
  657. }
  658. }
  659. if (*end_word == '\0') {
  660. *buf = end_word;
  661. } else {
  662. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  663. for (p = end_word; p < end_whitespace; p++) {
  664. *p = '\0';
  665. }
  666. *buf = end_whitespace;
  667. }
  668. return begin_word;
  669. }
  670. // Simplified version of skip_quoted without quote char
  671. // and whitespace == delimiters
  672. static char *skip(char **buf, const char *delimiters) {
  673. return skip_quoted(buf, delimiters, delimiters, 0);
  674. }
  675. // Return HTTP header value, or NULL if not found.
  676. static const char *get_header(const struct mg_request_info *ri,
  677. const char *name) {
  678. int i;
  679. for (i = 0; i < ri->num_headers; i++)
  680. if (!mg_strcasecmp(name, ri->http_headers[i].name))
  681. return ri->http_headers[i].value;
  682. return NULL;
  683. }
  684. const char *mg_get_header(const struct mg_connection *conn, const char *name) {
  685. return get_header(&conn->request_info, name);
  686. }
  687. // A helper function for traversing a comma separated list of values.
  688. // It returns a list pointer shifted to the next value, or NULL if the end
  689. // of the list found.
  690. // Value is stored in val vector. If value has form "x=y", then eq_val
  691. // vector is initialized to point to the "y" part, and val vector length
  692. // is adjusted to point only to "x".
  693. static const char *next_option(const char *list, struct vec *val,
  694. struct vec *eq_val) {
  695. if (list == NULL || *list == '\0') {
  696. // End of the list
  697. list = NULL;
  698. } else {
  699. val->ptr = list;
  700. if ((list = strchr(val->ptr, ',')) != NULL) {
  701. // Comma found. Store length and shift the list ptr
  702. val->len = list - val->ptr;
  703. list++;
  704. } else {
  705. // This value is the last one
  706. list = val->ptr + strlen(val->ptr);
  707. val->len = list - val->ptr;
  708. }
  709. if (eq_val != NULL) {
  710. // Value has form "x=y", adjust pointers and lengths
  711. // so that val points to "x", and eq_val points to "y".
  712. eq_val->len = 0;
  713. eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
  714. if (eq_val->ptr != NULL) {
  715. eq_val->ptr++; // Skip over '=' character
  716. eq_val->len = val->ptr + val->len - eq_val->ptr;
  717. val->len = (eq_val->ptr - val->ptr) - 1;
  718. }
  719. }
  720. }
  721. return list;
  722. }
  723. static int match_prefix(const char *pattern, int pattern_len, const char *str) {
  724. const char *or_str;
  725. int i, j, len, res;
  726. if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
  727. res = match_prefix(pattern, or_str - pattern, str);
  728. return res > 0 ? res :
  729. match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str);
  730. }
  731. i = j = 0;
  732. res = -1;
  733. for (; i < pattern_len; i++, j++) {
  734. if (pattern[i] == '?' && str[j] != '\0') {
  735. continue;
  736. } else if (pattern[i] == '$') {
  737. return str[j] == '\0' ? j : -1;
  738. } else if (pattern[i] == '*') {
  739. i++;
  740. if (pattern[i] == '*') {
  741. i++;
  742. len = (int) strlen(str + j);
  743. } else {
  744. len = (int) strcspn(str + j, "/");
  745. }
  746. if (i == pattern_len) {
  747. return j + len;
  748. }
  749. do {
  750. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  751. } while (res == -1 && len-- > 0);
  752. return res == -1 ? -1 : j + res + len;
  753. } else if (pattern[i] != str[j]) {
  754. return -1;
  755. }
  756. }
  757. return j;
  758. }
  759. // HTTP 1.1 assumes keep alive if "Connection:" header is not set
  760. // This function must tolerate situations when connection info is not
  761. // set up, for example if request parsing failed.
  762. static int should_keep_alive(const struct mg_connection *conn) {
  763. const char *http_version = conn->request_info.http_version;
  764. const char *header = mg_get_header(conn, "Connection");
  765. if (conn->must_close ||
  766. conn->status_code == 401 ||
  767. mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
  768. (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
  769. (header == NULL && http_version && strcmp(http_version, "1.1"))) {
  770. return 0;
  771. }
  772. return 1;
  773. }
  774. static const char *suggest_connection_header(const struct mg_connection *conn) {
  775. return should_keep_alive(conn) ? "keep-alive" : "close";
  776. }
  777. static void send_http_error(struct mg_connection *, int, const char *,
  778. PRINTF_FORMAT_STRING(const char *fmt), ...)
  779. PRINTF_ARGS(4, 5);
  780. static void send_http_error(struct mg_connection *conn, int status,
  781. const char *reason, const char *fmt, ...) {
  782. char buf[MG_BUF_LEN];
  783. va_list ap;
  784. int len;
  785. conn->status_code = status;
  786. if (call_user(conn, MG_HTTP_ERROR) == NULL) {
  787. buf[0] = '\0';
  788. len = 0;
  789. // Errors 1xx, 204 and 304 MUST NOT send a body
  790. if (status > 199 && status != 204 && status != 304) {
  791. len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);
  792. buf[len++] = '\n';
  793. va_start(ap, fmt);
  794. len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
  795. va_end(ap);
  796. }
  797. DEBUG_TRACE(("[%s]", buf));
  798. mg_printf(conn, "HTTP/1.1 %d %s\r\n"
  799. "Content-Length: %d\r\n"
  800. "Connection: %s\r\n\r\n", status, reason, len,
  801. suggest_connection_header(conn));
  802. conn->num_bytes_sent += mg_printf(conn, "%s", buf);
  803. }
  804. }
  805. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  806. static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused) {
  807. unused = NULL;
  808. *mutex = CreateMutex(NULL, FALSE, NULL);
  809. return *mutex == NULL ? -1 : 0;
  810. }
  811. static int pthread_mutex_destroy(pthread_mutex_t *mutex) {
  812. return CloseHandle(*mutex) == 0 ? -1 : 0;
  813. }
  814. static int pthread_mutex_lock(pthread_mutex_t *mutex) {
  815. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
  816. }
  817. static int pthread_mutex_unlock(pthread_mutex_t *mutex) {
  818. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  819. }
  820. static int pthread_cond_init(pthread_cond_t *cv, const void *unused) {
  821. unused = NULL;
  822. cv->signal = CreateEvent(NULL, FALSE, FALSE, NULL);
  823. cv->broadcast = CreateEvent(NULL, TRUE, FALSE, NULL);
  824. return cv->signal != NULL && cv->broadcast != NULL ? 0 : -1;
  825. }
  826. static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) {
  827. HANDLE handles[] = {cv->signal, cv->broadcast};
  828. ReleaseMutex(*mutex);
  829. WaitForMultipleObjects(2, handles, FALSE, INFINITE);
  830. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
  831. }
  832. static int pthread_cond_signal(pthread_cond_t *cv) {
  833. return SetEvent(cv->signal) == 0 ? -1 : 0;
  834. }
  835. static int pthread_cond_broadcast(pthread_cond_t *cv) {
  836. // Implementation with PulseEvent() has race condition, see
  837. // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
  838. return PulseEvent(cv->broadcast) == 0 ? -1 : 0;
  839. }
  840. static int pthread_cond_destroy(pthread_cond_t *cv) {
  841. return CloseHandle(cv->signal) && CloseHandle(cv->broadcast) ? 0 : -1;
  842. }
  843. // For Windows, change all slashes to backslashes in path names.
  844. static void change_slashes_to_backslashes(char *path) {
  845. int i;
  846. for (i = 0; path[i] != '\0'; i++) {
  847. if (path[i] == '/')
  848. path[i] = '\\';
  849. // i > 0 check is to preserve UNC paths, like \\server\file.txt
  850. if (path[i] == '\\' && i > 0)
  851. while (path[i + 1] == '\\' || path[i + 1] == '/')
  852. (void) memmove(path + i + 1,
  853. path + i + 2, strlen(path + i + 1));
  854. }
  855. }
  856. // Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  857. // wbuf and wbuf_len is a target buffer and its length.
  858. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  859. char buf[PATH_MAX], buf2[PATH_MAX], *p;
  860. mg_strlcpy(buf, path, sizeof(buf));
  861. change_slashes_to_backslashes(buf);
  862. // Point p to the end of the file name
  863. p = buf + strlen(buf) - 1;
  864. // Trim trailing backslash character
  865. while (p > buf && *p == '\\' && p[-1] != ':') {
  866. *p-- = '\0';
  867. }
  868. // Protect from CGI code disclosure.
  869. // This is very nasty hole. Windows happily opens files with
  870. // some garbage in the end of file name. So fopen("a.cgi ", "r")
  871. // actually opens "a.cgi", and does not return an error!
  872. if (*p == 0x20 || // No space at the end
  873. (*p == 0x2e && p > buf) || // No '.' but allow '.' as full path
  874. *p == 0x2b || // No '+'
  875. (*p & ~0x7f)) { // And generally no non-ASCII chars
  876. (void) fprintf(stderr, "Rejecting suspicious path: [%s]", buf);
  877. wbuf[0] = L'\0';
  878. } else {
  879. // Convert to Unicode and back. If doubly-converted string does not
  880. // match the original, something is fishy, reject.
  881. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  882. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  883. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  884. NULL, NULL);
  885. if (strcmp(buf, buf2) != 0) {
  886. wbuf[0] = L'\0';
  887. }
  888. }
  889. }
  890. #if defined(_WIN32_WCE)
  891. static time_t time(time_t *ptime) {
  892. time_t t;
  893. SYSTEMTIME st;
  894. FILETIME ft;
  895. GetSystemTime(&st);
  896. SystemTimeToFileTime(&st, &ft);
  897. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  898. if (ptime != NULL) {
  899. *ptime = t;
  900. }
  901. return t;
  902. }
  903. static struct tm *localtime(const time_t *ptime, struct tm *ptm) {
  904. int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;
  905. FILETIME ft, lft;
  906. SYSTEMTIME st;
  907. TIME_ZONE_INFORMATION tzinfo;
  908. if (ptm == NULL) {
  909. return NULL;
  910. }
  911. * (int64_t *) &ft = t;
  912. FileTimeToLocalFileTime(&ft, &lft);
  913. FileTimeToSystemTime(&lft, &st);
  914. ptm->tm_year = st.wYear - 1900;
  915. ptm->tm_mon = st.wMonth - 1;
  916. ptm->tm_wday = st.wDayOfWeek;
  917. ptm->tm_mday = st.wDay;
  918. ptm->tm_hour = st.wHour;
  919. ptm->tm_min = st.wMinute;
  920. ptm->tm_sec = st.wSecond;
  921. ptm->tm_yday = 0; // hope nobody uses this
  922. ptm->tm_isdst =
  923. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  924. return ptm;
  925. }
  926. static struct tm *gmtime(const time_t *ptime, struct tm *ptm) {
  927. // FIXME(lsm): fix this.
  928. return localtime(ptime, ptm);
  929. }
  930. static size_t strftime(char *dst, size_t dst_size, const char *fmt,
  931. const struct tm *tm) {
  932. (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
  933. return 0;
  934. }
  935. #endif
  936. static int mg_rename(const char* oldname, const char* newname) {
  937. wchar_t woldbuf[PATH_MAX];
  938. wchar_t wnewbuf[PATH_MAX];
  939. to_unicode(oldname, woldbuf, ARRAY_SIZE(woldbuf));
  940. to_unicode(newname, wnewbuf, ARRAY_SIZE(wnewbuf));
  941. return MoveFileW(woldbuf, wnewbuf) ? 0 : -1;
  942. }
  943. static FILE *mg_fopen(const char *path, const char *mode) {
  944. wchar_t wbuf[PATH_MAX], wmode[20];
  945. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  946. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  947. return _wfopen(wbuf, wmode);
  948. }
  949. static int mg_stat(const char *path, struct mgstat *stp) {
  950. int ok = -1; // Error
  951. wchar_t wbuf[PATH_MAX];
  952. WIN32_FILE_ATTRIBUTE_DATA info;
  953. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  954. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  955. stp->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  956. stp->mtime = SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  957. info.ftLastWriteTime.dwHighDateTime);
  958. stp->is_directory =
  959. info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  960. ok = 0; // Success
  961. }
  962. return ok;
  963. }
  964. static int mg_remove(const char *path) {
  965. wchar_t wbuf[PATH_MAX];
  966. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  967. return DeleteFileW(wbuf) ? 0 : -1;
  968. }
  969. static int mg_mkdir(const char *path, int mode) {
  970. char buf[PATH_MAX];
  971. wchar_t wbuf[PATH_MAX];
  972. mode = 0; // Unused
  973. mg_strlcpy(buf, path, sizeof(buf));
  974. change_slashes_to_backslashes(buf);
  975. (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, sizeof(wbuf));
  976. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  977. }
  978. // Implementation of POSIX opendir/closedir/readdir for Windows.
  979. static DIR * opendir(const char *name) {
  980. DIR *dir = NULL;
  981. wchar_t wpath[PATH_MAX];
  982. DWORD attrs;
  983. if (name == NULL) {
  984. SetLastError(ERROR_BAD_ARGUMENTS);
  985. } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
  986. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  987. } else {
  988. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  989. attrs = GetFileAttributesW(wpath);
  990. if (attrs != 0xFFFFFFFF &&
  991. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  992. (void) wcscat(wpath, L"\\*");
  993. dir->handle = FindFirstFileW(wpath, &dir->info);
  994. dir->result.d_name[0] = '\0';
  995. } else {
  996. free(dir);
  997. dir = NULL;
  998. }
  999. }
  1000. return dir;
  1001. }
  1002. static int closedir(DIR *dir) {
  1003. int result = 0;
  1004. if (dir != NULL) {
  1005. if (dir->handle != INVALID_HANDLE_VALUE)
  1006. result = FindClose(dir->handle) ? 0 : -1;
  1007. free(dir);
  1008. } else {
  1009. result = -1;
  1010. SetLastError(ERROR_BAD_ARGUMENTS);
  1011. }
  1012. return result;
  1013. }
  1014. static struct dirent *readdir(DIR *dir) {
  1015. struct dirent *result = 0;
  1016. if (dir) {
  1017. if (dir->handle != INVALID_HANDLE_VALUE) {
  1018. result = &dir->result;
  1019. (void) WideCharToMultiByte(CP_UTF8, 0,
  1020. dir->info.cFileName, -1, result->d_name,
  1021. sizeof(result->d_name), NULL, NULL);
  1022. if (!FindNextFileW(dir->handle, &dir->info)) {
  1023. (void) FindClose(dir->handle);
  1024. dir->handle = INVALID_HANDLE_VALUE;
  1025. }
  1026. } else {
  1027. SetLastError(ERROR_FILE_NOT_FOUND);
  1028. }
  1029. } else {
  1030. SetLastError(ERROR_BAD_ARGUMENTS);
  1031. }
  1032. return result;
  1033. }
  1034. #define set_close_on_exec(fd) // No FD_CLOEXEC on Windows
  1035. int mg_start_thread(mg_thread_func_t f, void *p) {
  1036. return _beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;
  1037. }
  1038. static HANDLE dlopen(const char *dll_name, int flags) {
  1039. wchar_t wbuf[PATH_MAX];
  1040. flags = 0; // Unused
  1041. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  1042. return LoadLibraryW(wbuf);
  1043. }
  1044. #if !defined(NO_CGI)
  1045. #define SIGKILL 0
  1046. static int kill(pid_t pid, int sig_num) {
  1047. (void) TerminateProcess(pid, sig_num);
  1048. (void) CloseHandle(pid);
  1049. return 0;
  1050. }
  1051. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1052. char *envblk, char *envp[], int fd_stdin,
  1053. int fd_stdout, const char *dir) {
  1054. HANDLE me;
  1055. char *p, *interp, full_interp[PATH_MAX], cmdline[PATH_MAX], buf[PATH_MAX];
  1056. FILE *fp;
  1057. STARTUPINFOA si = { sizeof(si) };
  1058. PROCESS_INFORMATION pi = { 0 };
  1059. envp = NULL; // Unused
  1060. // TODO(lsm): redirect CGI errors to the error log file
  1061. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  1062. si.wShowWindow = SW_HIDE;
  1063. me = GetCurrentProcess();
  1064. DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me,
  1065. &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1066. DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me,
  1067. &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1068. // If CGI file is a script, try to read the interpreter line
  1069. interp = conn->ctx->config[CGI_INTERPRETER];
  1070. if (interp == NULL) {
  1071. buf[0] = buf[2] = '\0';
  1072. // Read the first line of the script into the buffer
  1073. snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
  1074. if ((fp = mg_fopen(cmdline, "r")) != NULL) {
  1075. fgets(buf, sizeof(buf), fp);
  1076. fclose(fp);
  1077. buf[sizeof(buf) - 1] = '\0';
  1078. }
  1079. if (buf[0] == '#' && buf[1] == '!') {
  1080. // Trim whitespace in interpreter name
  1081. for (p = buf + 2; *p != '\0' && isspace(* (unsigned char *) p); )
  1082. p++;
  1083. *p = '\0';
  1084. }
  1085. interp = buf + 2;
  1086. }
  1087. if (interp[0] != '\0') {
  1088. GetFullPathName(interp, sizeof(full_interp), full_interp, NULL);
  1089. interp = full_interp;
  1090. }
  1091. mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s",
  1092. interp, interp[0] == '\0' ? "" : " ", prog);
  1093. DEBUG_TRACE(("Running [%s]", cmdline));
  1094. if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
  1095. CREATE_NEW_PROCESS_GROUP, envblk, dir, &si, &pi) == 0) {
  1096. cry(conn, "%s: CreateProcess(%s): %d",
  1097. __func__, cmdline, ERRNO);
  1098. pi.hProcess = (pid_t) -1;
  1099. }
  1100. // Always close these to prevent handle leakage.
  1101. (void) close(fd_stdin);
  1102. (void) close(fd_stdout);
  1103. (void) CloseHandle(si.hStdOutput);
  1104. (void) CloseHandle(si.hStdInput);
  1105. (void) CloseHandle(pi.hThread);
  1106. return (pid_t) pi.hProcess;
  1107. }
  1108. #endif // !NO_CGI
  1109. static int set_non_blocking_mode(SOCKET sock) {
  1110. unsigned long on = 1;
  1111. return ioctlsocket(sock, FIONBIO, &on);
  1112. }
  1113. #else
  1114. static int mg_stat(const char *path, struct mgstat *stp) {
  1115. struct stat st;
  1116. int ok;
  1117. if (stat(path, &st) == 0) {
  1118. ok = 0;
  1119. stp->size = st.st_size;
  1120. stp->mtime = st.st_mtime;
  1121. stp->is_directory = S_ISDIR(st.st_mode);
  1122. } else {
  1123. ok = -1;
  1124. }
  1125. return ok;
  1126. }
  1127. static void set_close_on_exec(int fd) {
  1128. (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
  1129. }
  1130. int mg_start_thread(mg_thread_func_t func, void *param) {
  1131. pthread_t thread_id;
  1132. pthread_attr_t attr;
  1133. (void) pthread_attr_init(&attr);
  1134. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  1135. // TODO(lsm): figure out why mongoose dies on Linux if next line is enabled
  1136. // (void) pthread_attr_setstacksize(&attr, sizeof(struct mg_connection) * 5);
  1137. return pthread_create(&thread_id, &attr, func, param);
  1138. }
  1139. #ifndef NO_CGI
  1140. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1141. char *envblk, char *envp[], int fd_stdin,
  1142. int fd_stdout, const char *dir) {
  1143. pid_t pid;
  1144. const char *interp;
  1145. envblk = NULL; // Unused
  1146. if ((pid = fork()) == -1) {
  1147. // Parent
  1148. send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));
  1149. } else if (pid == 0) {
  1150. // Child
  1151. if (chdir(dir) != 0) {
  1152. cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  1153. } else if (dup2(fd_stdin, 0) == -1) {
  1154. cry(conn, "%s: dup2(%d, 0): %s", __func__, fd_stdin, strerror(ERRNO));
  1155. } else if (dup2(fd_stdout, 1) == -1) {
  1156. cry(conn, "%s: dup2(%d, 1): %s", __func__, fd_stdout, strerror(ERRNO));
  1157. } else {
  1158. (void) dup2(fd_stdout, 2);
  1159. (void) close(fd_stdin);
  1160. (void) close(fd_stdout);
  1161. interp = conn->ctx->config[CGI_INTERPRETER];
  1162. if (interp == NULL) {
  1163. (void) execle(prog, prog, NULL, envp);
  1164. cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
  1165. } else {
  1166. (void) execle(interp, interp, prog, NULL, envp);
  1167. cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
  1168. strerror(ERRNO));
  1169. }
  1170. }
  1171. exit(EXIT_FAILURE);
  1172. }
  1173. // Parent. Close stdio descriptors
  1174. (void) close(fd_stdin);
  1175. (void) close(fd_stdout);
  1176. return pid;
  1177. }
  1178. #endif // !NO_CGI
  1179. static int set_non_blocking_mode(SOCKET sock) {
  1180. int flags;
  1181. flags = fcntl(sock, F_GETFL, 0);
  1182. (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  1183. return 0;
  1184. }
  1185. #endif // _WIN32
  1186. // Write data to the IO channel - opened file descriptor, socket or SSL
  1187. // descriptor. Return number of bytes written.
  1188. static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
  1189. int64_t len) {
  1190. int64_t sent;
  1191. int n, k;
  1192. sent = 0;
  1193. while (sent < len) {
  1194. // How many bytes we send in this iteration
  1195. k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
  1196. if (ssl != NULL) {
  1197. n = SSL_write(ssl, buf + sent, k);
  1198. } else if (fp != NULL) {
  1199. n = (int) fwrite(buf + sent, 1, (size_t) k, fp);
  1200. if (ferror(fp))
  1201. n = -1;
  1202. } else {
  1203. n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);
  1204. }
  1205. if (n < 0)
  1206. break;
  1207. sent += n;
  1208. }
  1209. return sent;
  1210. }
  1211. // This function is needed to prevent Mongoose to be stuck in a blocking
  1212. // socket read when user requested exit. To do that, we sleep in select
  1213. // with a timeout, and when returned, check the context for the stop flag.
  1214. // If it is set, we return 0, and this means that we must not continue
  1215. // reading, must give up and close the connection and exit serving thread.
  1216. static int wait_until_socket_is_readable(struct mg_connection *conn) {
  1217. int result;
  1218. struct timeval tv;
  1219. fd_set set;
  1220. do {
  1221. tv.tv_sec = 0;
  1222. tv.tv_usec = 300 * 1000;
  1223. FD_ZERO(&set);
  1224. FD_SET(conn->client.sock, &set);
  1225. result = select(conn->client.sock + 1, &set, NULL, NULL, &tv);
  1226. } while ((result == 0 || (result < 0 && ERRNO == EINTR)) &&
  1227. conn->ctx->stop_flag == 0);
  1228. return conn->ctx->stop_flag || result < 0 ? 0 : 1;
  1229. }
  1230. // Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  1231. // Return negative value on error, or number of bytes read on success.
  1232. static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len) {
  1233. int nread;
  1234. if (fp != NULL) {
  1235. // Use read() instead of fread(), because if we're reading from the CGI
  1236. // pipe, fread() may block until IO buffer is filled up. We cannot afford
  1237. // to block and must pass all read bytes immediately to the client.
  1238. nread = read(fileno(fp), buf, (size_t) len);
  1239. } else if (!wait_until_socket_is_readable(conn)) {
  1240. nread = -1;
  1241. } else if (conn->ssl != NULL) {
  1242. nread = SSL_read(conn->ssl, buf, len);
  1243. } else {
  1244. nread = recv(conn->client.sock, buf, (size_t) len, 0);
  1245. }
  1246. return conn->ctx->stop_flag ? -1 : nread;
  1247. }
  1248. int mg_read(struct mg_connection *conn, void *buf, size_t len) {
  1249. int n, buffered_len, nread;
  1250. const char *body;
  1251. nread = 0;
  1252. if (conn->consumed_content < conn->content_len) {
  1253. // Adjust number of bytes to read.
  1254. int64_t to_read = conn->content_len - conn->consumed_content;
  1255. if (to_read < (int64_t) len) {
  1256. len = (size_t) to_read;
  1257. }
  1258. // Return buffered data
  1259. body = conn->buf + conn->request_len + conn->consumed_content;
  1260. buffered_len = &conn->buf[conn->data_len] - body;
  1261. if (buffered_len > 0) {
  1262. if (len < (size_t) buffered_len) {
  1263. buffered_len = (int) len;
  1264. }
  1265. memcpy(buf, body, (size_t) buffered_len);
  1266. len -= buffered_len;
  1267. conn->consumed_content += buffered_len;
  1268. nread += buffered_len;
  1269. buf = (char *) buf + buffered_len;
  1270. }
  1271. // We have returned all buffered data. Read new data from the remote socket.
  1272. while (len > 0) {
  1273. n = pull(NULL, conn, (char *) buf, (int) len);
  1274. if (n < 0) {
  1275. nread = n; // Propagate the error
  1276. break;
  1277. } else if (n == 0) {
  1278. break; // No more data to read
  1279. } else {
  1280. buf = (char *) buf + n;
  1281. conn->consumed_content += n;
  1282. nread += n;
  1283. len -= n;
  1284. }
  1285. }
  1286. }
  1287. return nread;
  1288. }
  1289. int mg_write(struct mg_connection *conn, const void *buf, size_t len) {
  1290. time_t now;
  1291. int64_t n, total, allowed;
  1292. if (conn->throttle > 0) {
  1293. if ((now = time(NULL)) != conn->last_throttle_time) {
  1294. conn->last_throttle_time = now;
  1295. conn->last_throttle_bytes = 0;
  1296. }
  1297. allowed = conn->throttle - conn->last_throttle_bytes;
  1298. if (allowed > (int64_t) len) {
  1299. allowed = len;
  1300. }
  1301. if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1302. (int64_t) allowed)) == allowed) {
  1303. buf = (char *) buf + total;
  1304. conn->last_throttle_bytes += total;
  1305. while (total < (int64_t) len && conn->ctx->stop_flag == 0) {
  1306. allowed = conn->throttle > (int64_t) len - total ?
  1307. (int64_t) len - total : conn->throttle;
  1308. if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1309. (int64_t) allowed)) != allowed) {
  1310. break;
  1311. }
  1312. sleep(1);
  1313. conn->last_throttle_bytes = allowed;
  1314. conn->last_throttle_time = time(NULL);
  1315. buf = (char *) buf + n;
  1316. total += n;
  1317. }
  1318. }
  1319. } else {
  1320. total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1321. (int64_t) len);
  1322. }
  1323. return (int) total;
  1324. }
  1325. int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
  1326. char mem[MG_BUF_LEN], *buf = mem;
  1327. int len;
  1328. va_list ap;
  1329. // Print in a local buffer first, hoping that it is large enough to
  1330. // hold the whole message
  1331. va_start(ap, fmt);
  1332. len = vsnprintf(mem, sizeof(mem), fmt, ap);
  1333. va_end(ap);
  1334. if (len == 0) {
  1335. // Do nothing. mg_printf(conn, "%s", "") was called.
  1336. } else if (len < 0) {
  1337. // vsnprintf() error, give up
  1338. len = -1;
  1339. cry(conn, "%s(%s, ...): vsnprintf() error", __func__, fmt);
  1340. } else if (len > (int) sizeof(mem) && (buf = (char *) malloc(len + 1)) != NULL) {
  1341. // Local buffer is not large enough, allocate big buffer on heap
  1342. va_start(ap, fmt);
  1343. vsnprintf(buf, len + 1, fmt, ap);
  1344. va_end(ap);
  1345. len = mg_write(conn, buf, (size_t) len);
  1346. free(buf);
  1347. } else if (len > (int) sizeof(mem)) {
  1348. // Failed to allocate large enough buffer, give up
  1349. cry(conn, "%s(%s, ...): Can't allocate %d bytes, not printing anything",
  1350. __func__, fmt, len);
  1351. len = -1;
  1352. } else {
  1353. // Copy to the local buffer succeeded
  1354. len = mg_write(conn, buf, (size_t) len);
  1355. }
  1356. return len;
  1357. }
  1358. // URL-decode input buffer into destination buffer.
  1359. // 0-terminate the destination buffer. Return the length of decoded data.
  1360. // form-url-encoded data differs from URI encoding in a way that it
  1361. // uses '+' as character for space, see RFC 1866 section 8.2.1
  1362. // http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  1363. static size_t url_decode(const char *src, size_t src_len, char *dst,
  1364. size_t dst_len, int is_form_url_encoded) {
  1365. size_t i, j;
  1366. int a, b;
  1367. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  1368. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  1369. if (src[i] == '%' &&
  1370. isxdigit(* (const unsigned char *) (src + i + 1)) &&
  1371. isxdigit(* (const unsigned char *) (src + i + 2))) {
  1372. a = tolower(* (const unsigned char *) (src + i + 1));
  1373. b = tolower(* (const unsigned char *) (src + i + 2));
  1374. dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
  1375. i += 2;
  1376. } else if (is_form_url_encoded && src[i] == '+') {
  1377. dst[j] = ' ';
  1378. } else {
  1379. dst[j] = src[i];
  1380. }
  1381. }
  1382. dst[j] = '\0'; // Null-terminate the destination
  1383. return j;
  1384. }
  1385. // Scan given buffer and fetch the value of the given variable.
  1386. // It can be specified in query string, or in the POST data.
  1387. // Return -1 if the variable not found, or length of the URL-decoded value
  1388. // stored in dst. The dst buffer is guaranteed to be NUL-terminated if it
  1389. // is not NULL or zero-length. If dst is NULL or zero-length, then
  1390. // -2 is returned.
  1391. int mg_get_var(const char *buf, size_t buf_len, const char *name,
  1392. char *dst, size_t dst_len) {
  1393. const char *p, *e, *s;
  1394. size_t name_len;
  1395. int len;
  1396. if (dst == NULL || dst_len == 0) {
  1397. len = -2;
  1398. } else if (buf == NULL || name == NULL || buf_len == 0) {
  1399. len = -1;
  1400. dst[0] = '\0';
  1401. } else {
  1402. name_len = strlen(name);
  1403. e = buf + buf_len;
  1404. len = -1;
  1405. dst[0] = '\0';
  1406. // buf is "var1=val1&var2=val2...". Find variable first
  1407. for (p = buf; p + name_len < e; p++) {
  1408. if ((p == buf || p[-1] == '&') && p[name_len] == '=' &&
  1409. !mg_strncasecmp(name, p, name_len)) {
  1410. // Point p to variable value
  1411. p += name_len + 1;
  1412. // Point s to the end of the value
  1413. s = (const char *) memchr(p, '&', (size_t)(e - p));
  1414. if (s == NULL) {
  1415. s = e;
  1416. }
  1417. assert(s >= p);
  1418. // Decode variable into destination buffer
  1419. if ((size_t) (s - p) < dst_len) {
  1420. len = (int) url_decode(p, (size_t)(s - p), dst, dst_len, 1);
  1421. }
  1422. break;
  1423. }
  1424. }
  1425. }
  1426. return len;
  1427. }
  1428. int mg_get_cookie(const struct mg_connection *conn, const char *cookie_name,
  1429. char *dst, size_t dst_size) {
  1430. const char *s, *p, *end;
  1431. int name_len, len = -1;
  1432. dst[0] = '\0';
  1433. if ((s = mg_get_header(conn, "Cookie")) == NULL) {
  1434. return -1;
  1435. }
  1436. name_len = (int) strlen(cookie_name);
  1437. end = s + strlen(s);
  1438. for (; (s = strstr(s, cookie_name)) != NULL; s += name_len)
  1439. if (s[name_len] == '=') {
  1440. s += name_len + 1;
  1441. if ((p = strchr(s, ' ')) == NULL)
  1442. p = end;
  1443. if (p[-1] == ';')
  1444. p--;
  1445. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  1446. s++;
  1447. p--;
  1448. }
  1449. if ((size_t) (p - s) < dst_size) {
  1450. len = p - s;
  1451. mg_strlcpy(dst, s, (size_t) len + 1);
  1452. }
  1453. break;
  1454. }
  1455. return len;
  1456. }
  1457. static int convert_uri_to_file_name(struct mg_connection *conn, char *buf,
  1458. size_t buf_len, struct mgstat *st) {
  1459. struct vec a, b;
  1460. const char *rewrite, *uri = conn->request_info.uri;
  1461. char *p;
  1462. int match_len, stat_result;
  1463. buf_len--; // This is because memmove() for PATH_INFO may shift part
  1464. // of the path one byte on the right.
  1465. mg_snprintf(conn, buf, buf_len, "%s%s", conn->ctx->config[DOCUMENT_ROOT],
  1466. uri);
  1467. rewrite = conn->ctx->config[REWRITE];
  1468. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  1469. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  1470. mg_snprintf(conn, buf, buf_len, "%.*s%s", (int) b.len, b.ptr,
  1471. uri + match_len);
  1472. break;
  1473. }
  1474. }
  1475. if ((stat_result = mg_stat(buf, st)) != 0) {
  1476. // Support PATH_INFO for CGI scripts.
  1477. for (p = buf + strlen(buf); p > buf + 1; p--) {
  1478. if (*p == '/') {
  1479. *p = '\0';
  1480. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  1481. strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 &&
  1482. (stat_result = mg_stat(buf, st)) == 0) {
  1483. // Shift PATH_INFO block one character right, e.g.
  1484. // "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  1485. // conn->path_info is pointing to the local variable "path" declared
  1486. // in handle_request(), so PATH_INFO is not valid after
  1487. // handle_request returns.
  1488. conn->path_info = p + 1;
  1489. memmove(p + 2, p + 1, strlen(p + 1) + 1); // +1 is for trailing \0
  1490. p[1] = '/';
  1491. break;
  1492. } else {
  1493. *p = '/';
  1494. stat_result = -1;
  1495. }
  1496. }
  1497. }
  1498. }
  1499. return stat_result;
  1500. }
  1501. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *)) {
  1502. return (conn->ssl = SSL_new(s)) != NULL &&
  1503. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  1504. func(conn->ssl) == 1;
  1505. }
  1506. // Check whether full request is buffered. Return:
  1507. // -1 if request is malformed
  1508. // 0 if request is not yet fully buffered
  1509. // >0 actual request length, including last \r\n\r\n
  1510. static int get_request_len(const char *buf, int buflen) {
  1511. const char *s, *e;
  1512. int len = 0;
  1513. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  1514. // Control characters are not allowed but >=128 is.
  1515. if (!isprint(* (const unsigned char *) s) && *s != '\r' &&
  1516. *s != '\n' && * (const unsigned char *) s < 128) {
  1517. len = -1;
  1518. break; // [i_a] abort scan as soon as one malformed character is found; don't let subsequent \r\n\r\n win us over anyhow
  1519. } else if (s[0] == '\n' && s[1] == '\n') {
  1520. len = (int) (s - buf) + 2;
  1521. } else if (s[0] == '\n' && &s[1] < e &&
  1522. s[1] == '\r' && s[2] == '\n') {
  1523. len = (int) (s - buf) + 3;
  1524. }
  1525. return len;
  1526. }
  1527. // Convert month to the month number. Return -1 on error, or month number
  1528. static int get_month_index(const char *s) {
  1529. size_t i;
  1530. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  1531. if (!strcmp(s, month_names[i]))
  1532. return (int) i;
  1533. return -1;
  1534. }
  1535. static int num_leap_years(int year) {
  1536. return year / 4 - year / 100 + year / 400;
  1537. }
  1538. // Parse UTC date-time string, and return the corresponding time_t value.
  1539. static time_t parse_date_string(const char *datetime) {
  1540. static const unsigned short days_before_month[] = {
  1541. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  1542. };
  1543. char month_str[32];
  1544. int second, minute, hour, day, month, year, leap_days, days;
  1545. time_t result = (time_t) 0;
  1546. if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
  1547. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1548. (sscanf(datetime, "%d %3s %d %d:%d:%d",
  1549. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1550. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
  1551. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1552. (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
  1553. &day, month_str, &year, &hour, &minute, &second) == 6)) &&
  1554. year > 1970 &&
  1555. (month = get_month_index(month_str)) != -1) {
  1556. leap_days = num_leap_years(year) - num_leap_years(1970);
  1557. year -= 1970;
  1558. days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
  1559. result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
  1560. }
  1561. return result;
  1562. }
  1563. // Protect against directory disclosure attack by removing '..',
  1564. // excessive '/' and '\' characters
  1565. static void remove_double_dots_and_double_slashes(char *s) {
  1566. char *p = s;
  1567. while (*s != '\0') {
  1568. *p++ = *s++;
  1569. if (s[-1] == '/' || s[-1] == '\\') {
  1570. // Skip all following slashes, backslashes and double-dots
  1571. while (s[0] != '\0') {
  1572. if (s[0] == '/' || s[0] == '\\') {
  1573. s++;
  1574. } else if (s[0] == '.' && s[1] == '.') {
  1575. s += 2;
  1576. } else {
  1577. break;
  1578. }
  1579. }
  1580. }
  1581. }
  1582. *p = '\0';
  1583. }
  1584. static const struct {
  1585. const char *extension;
  1586. size_t ext_len;
  1587. const char *mime_type;
  1588. } builtin_mime_types[] = {
  1589. {".html", 5, "text/html"},
  1590. {".htm", 4, "text/html"},
  1591. {".shtm", 5, "text/html"},
  1592. {".shtml", 6, "text/html"},
  1593. {".css", 4, "text/css"},
  1594. {".js", 3, "application/x-javascript"},
  1595. {".ico", 4, "image/x-icon"},
  1596. {".gif", 4, "image/gif"},
  1597. {".jpg", 4, "image/jpeg"},
  1598. {".jpeg", 5, "image/jpeg"},
  1599. {".png", 4, "image/png"},
  1600. {".svg", 4, "image/svg+xml"},
  1601. {".txt", 4, "text/plain"},
  1602. {".torrent", 8, "application/x-bittorrent"},
  1603. {".wav", 4, "audio/x-wav"},
  1604. {".mp3", 4, "audio/x-mp3"},
  1605. {".mid", 4, "audio/mid"},
  1606. {".m3u", 4, "audio/x-mpegurl"},
  1607. {".ram", 4, "audio/x-pn-realaudio"},
  1608. {".xml", 4, "text/xml"},
  1609. {".json", 5, "text/json"},
  1610. {".xslt", 5, "application/xml"},
  1611. {".ra", 3, "audio/x-pn-realaudio"},
  1612. {".doc", 4, "application/msword"},
  1613. {".exe", 4, "application/octet-stream"},
  1614. {".zip", 4, "application/x-zip-compressed"},
  1615. {".xls", 4, "application/excel"},
  1616. {".tgz", 4, "application/x-tar-gz"},
  1617. {".tar", 4, "application/x-tar"},
  1618. {".gz", 3, "application/x-gunzip"},
  1619. {".arj", 4, "application/x-arj-compressed"},
  1620. {".rar", 4, "application/x-arj-compressed"},
  1621. {".rtf", 4, "application/rtf"},
  1622. {".pdf", 4, "application/pdf"},
  1623. {".swf", 4, "application/x-shockwave-flash"},
  1624. {".mpg", 4, "video/mpeg"},
  1625. {".webm", 5, "video/webm"},
  1626. {".mpeg", 5, "video/mpeg"},
  1627. {".mp4", 4, "video/mp4"},
  1628. {".m4v", 4, "video/x-m4v"},
  1629. {".asf", 4, "video/x-ms-asf"},
  1630. {".avi", 4, "video/x-msvideo"},
  1631. {".bmp", 4, "image/bmp"},
  1632. {NULL, 0, NULL}
  1633. };
  1634. const char *mg_get_builtin_mime_type(const char *path) {
  1635. const char *ext;
  1636. size_t i, path_len;
  1637. path_len = strlen(path);
  1638. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  1639. ext = path + (path_len - builtin_mime_types[i].ext_len);
  1640. if (path_len > builtin_mime_types[i].ext_len &&
  1641. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  1642. return builtin_mime_types[i].mime_type;
  1643. }
  1644. }
  1645. return "text/plain";
  1646. }
  1647. // Look at the "path" extension and figure what mime type it has.
  1648. // Store mime type in the vector.
  1649. static void get_mime_type(struct mg_context *ctx, const char *path,
  1650. struct vec *vec) {
  1651. struct vec ext_vec, mime_vec;
  1652. const char *list, *ext;
  1653. size_t path_len;
  1654. path_len = strlen(path);
  1655. // Scan user-defined mime types first, in case user wants to
  1656. // override default mime types.
  1657. list = ctx->config[EXTRA_MIME_TYPES];
  1658. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  1659. // ext now points to the path suffix
  1660. ext = path + path_len - ext_vec.len;
  1661. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  1662. *vec = mime_vec;
  1663. return;
  1664. }
  1665. }
  1666. vec->ptr = mg_get_builtin_mime_type(path);
  1667. vec->len = strlen(vec->ptr);
  1668. }
  1669. #ifndef HAVE_MD5
  1670. typedef struct MD5Context {
  1671. uint32_t buf[4];
  1672. uint32_t bits[2];
  1673. unsigned char in[64];
  1674. } MD5_CTX;
  1675. #if defined(__BYTE_ORDER) && (__BYTE_ORDER == 1234)
  1676. #define byteReverse(buf, len) // Do nothing
  1677. #else
  1678. static void byteReverse(unsigned char *buf, unsigned longs) {
  1679. uint32_t t;
  1680. do {
  1681. t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  1682. ((unsigned) buf[1] << 8 | buf[0]);
  1683. *(uint32_t *) buf = t;
  1684. buf += 4;
  1685. } while (--longs);
  1686. }
  1687. #endif
  1688. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  1689. #define F2(x, y, z) F1(z, x, y)
  1690. #define F3(x, y, z) (x ^ y ^ z)
  1691. #define F4(x, y, z) (y ^ (x | ~z))
  1692. #define MD5STEP(f, w, x, y, z, data, s) \
  1693. ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
  1694. // Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  1695. // initialization constants.
  1696. static void MD5Init(MD5_CTX *ctx) {
  1697. ctx->buf[0] = 0x67452301;
  1698. ctx->buf[1] = 0xefcdab89;
  1699. ctx->buf[2] = 0x98badcfe;
  1700. ctx->buf[3] = 0x10325476;
  1701. ctx->bits[0] = 0;
  1702. ctx->bits[1] = 0;
  1703. }
  1704. static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
  1705. register uint32_t a, b, c, d;
  1706. a = buf[0];
  1707. b = buf[1];
  1708. c = buf[2];
  1709. d = buf[3];
  1710. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  1711. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  1712. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  1713. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  1714. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  1715. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  1716. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  1717. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  1718. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  1719. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  1720. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  1721. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  1722. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  1723. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  1724. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  1725. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  1726. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  1727. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  1728. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  1729. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  1730. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  1731. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  1732. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  1733. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  1734. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  1735. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  1736. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  1737. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  1738. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  1739. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  1740. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  1741. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  1742. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  1743. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  1744. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  1745. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  1746. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  1747. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  1748. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  1749. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  1750. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  1751. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  1752. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  1753. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  1754. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  1755. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  1756. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  1757. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  1758. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  1759. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  1760. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  1761. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  1762. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  1763. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  1764. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  1765. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  1766. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  1767. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  1768. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  1769. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  1770. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  1771. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  1772. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  1773. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  1774. buf[0] += a;
  1775. buf[1] += b;
  1776. buf[2] += c;
  1777. buf[3] += d;
  1778. }
  1779. static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
  1780. uint32_t t;
  1781. t = ctx->bits[0];
  1782. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
  1783. ctx->bits[1]++;
  1784. ctx->bits[1] += len >> 29;
  1785. t = (t >> 3) & 0x3f;
  1786. if (t) {
  1787. unsigned char *p = (unsigned char *) ctx->in + t;
  1788. t = 64 - t;
  1789. if (len < t) {
  1790. memcpy(p, buf, len);
  1791. return;
  1792. }
  1793. memcpy(p, buf, t);
  1794. byteReverse(ctx->in, 16);
  1795. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1796. buf += t;
  1797. len -= t;
  1798. }
  1799. while (len >= 64) {
  1800. memcpy(ctx->in, buf, 64);
  1801. byteReverse(ctx->in, 16);
  1802. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1803. buf += 64;
  1804. len -= 64;
  1805. }
  1806. memcpy(ctx->in, buf, len);
  1807. }
  1808. static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
  1809. unsigned count;
  1810. unsigned char *p;
  1811. count = (ctx->bits[0] >> 3) & 0x3F;
  1812. p = ctx->in + count;
  1813. *p++ = 0x80;
  1814. count = 64 - 1 - count;
  1815. if (count < 8) {
  1816. memset(p, 0, count);
  1817. byteReverse(ctx->in, 16);
  1818. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1819. memset(ctx->in, 0, 56);
  1820. } else {
  1821. memset(p, 0, count - 8);
  1822. }
  1823. byteReverse(ctx->in, 14);
  1824. ((uint32_t *) ctx->in)[14] = ctx->bits[0];
  1825. ((uint32_t *) ctx->in)[15] = ctx->bits[1];
  1826. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1827. byteReverse((unsigned char *) ctx->buf, 4);
  1828. memcpy(digest, ctx->buf, 16);
  1829. memset((char *) ctx, 0, sizeof(*ctx));
  1830. }
  1831. #endif // !HAVE_MD5
  1832. // Stringify binary data. Output buffer must be twice as big as input,
  1833. // because each byte takes 2 bytes in string representation
  1834. static void bin2str(char *to, const unsigned char *p, size_t len) {
  1835. static const char *hex = "0123456789abcdef";
  1836. for (; len--; p++) {
  1837. *to++ = hex[p[0] >> 4];
  1838. *to++ = hex[p[0] & 0x0f];
  1839. }
  1840. *to = '\0';
  1841. }
  1842. // Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  1843. void mg_md5(char buf[33], ...) {
  1844. unsigned char hash[16];
  1845. const char *p;
  1846. va_list ap;
  1847. MD5_CTX ctx;
  1848. MD5Init(&ctx);
  1849. va_start(ap, buf);
  1850. while ((p = va_arg(ap, const char *)) != NULL) {
  1851. MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
  1852. }
  1853. va_end(ap);
  1854. MD5Final(hash, &ctx);
  1855. bin2str(buf, hash, sizeof(hash));
  1856. }
  1857. // Check the user's password, return 1 if OK
  1858. static int check_password(const char *method, const char *ha1, const char *uri,
  1859. const char *nonce, const char *nc, const char *cnonce,
  1860. const char *qop, const char *response) {
  1861. char ha2[32 + 1], expected_response[32 + 1];
  1862. // Some of the parameters may be NULL
  1863. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
  1864. qop == NULL || response == NULL) {
  1865. return 0;
  1866. }
  1867. // NOTE(lsm): due to a bug in MSIE, we do not compare the URI
  1868. // TODO(lsm): check for authentication timeout
  1869. if (// strcmp(dig->uri, c->ouri) != 0 ||
  1870. strlen(response) != 32
  1871. // || now - strtoul(dig->nonce, NULL, 10) > 3600
  1872. ) {
  1873. return 0;
  1874. }
  1875. mg_md5(ha2, method, ":", uri, NULL);
  1876. mg_md5(expected_response, ha1, ":", nonce, ":", nc,
  1877. ":", cnonce, ":", qop, ":", ha2, NULL);
  1878. return mg_strcasecmp(response, expected_response) == 0;
  1879. }
  1880. // Use the global passwords file, if specified by auth_gpass option,
  1881. // or search for .htpasswd in the requested directory.
  1882. static FILE *open_auth_file(struct mg_connection *conn, const char *path) {
  1883. struct mg_context *ctx = conn->ctx;
  1884. char name[PATH_MAX];
  1885. const char *p, *e;
  1886. struct mgstat st;
  1887. FILE *fp;
  1888. if (ctx->config[GLOBAL_PASSWORDS_FILE] != NULL) {
  1889. // Use global passwords file
  1890. fp = mg_fopen(ctx->config[GLOBAL_PASSWORDS_FILE], "r");
  1891. if (fp == NULL)
  1892. cry(fc(ctx), "fopen(%s): %s",
  1893. ctx->config[GLOBAL_PASSWORDS_FILE], strerror(ERRNO));
  1894. } else if (!mg_stat(path, &st) && st.is_directory) {
  1895. (void) mg_snprintf(conn, name, sizeof(name), "%s%c%s",
  1896. path, '/', PASSWORDS_FILE_NAME);
  1897. fp = mg_fopen(name, "r");
  1898. } else {
  1899. // Try to find .htpasswd in requested directory.
  1900. for (p = path, e = p + strlen(p) - 1; e > p; e--)
  1901. if (e[0] == '/')
  1902. break;
  1903. (void) mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
  1904. (int) (e - p), p, '/', PASSWORDS_FILE_NAME);
  1905. fp = mg_fopen(name, "r");
  1906. }
  1907. return fp;
  1908. }
  1909. // Parsed Authorization header
  1910. struct ah {
  1911. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  1912. };
  1913. // Return 1 on success. Always initializes the ah structure.
  1914. static int parse_auth_header(struct mg_connection *conn, char *buf,
  1915. size_t buf_size, struct ah *ah) {
  1916. char *name, *value, *s;
  1917. const char *auth_header;
  1918. (void) memset(ah, 0, sizeof(*ah));
  1919. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  1920. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  1921. return 0;
  1922. }
  1923. // Make modifiable copy of the auth header
  1924. (void) mg_strlcpy(buf, auth_header + 7, buf_size);
  1925. s = buf;
  1926. // Parse authorization header
  1927. for (;;) {
  1928. // Gobble initial spaces
  1929. while (isspace(* (unsigned char *) s)) {
  1930. s++;
  1931. }
  1932. name = skip_quoted(&s, "=", " ", 0);
  1933. // Value is either quote-delimited, or ends at first comma or space.
  1934. if (s[0] == '\"') {
  1935. s++;
  1936. value = skip_quoted(&s, "\"", " ", '\\');
  1937. if (s[0] == ',') {
  1938. s++;
  1939. }
  1940. } else {
  1941. value = skip_quoted(&s, ", ", " ", 0); // IE uses commas, FF uses spaces
  1942. }
  1943. if (*name == '\0') {
  1944. break;
  1945. }
  1946. if (!strcmp(name, "username")) {
  1947. ah->user = value;
  1948. } else if (!strcmp(name, "cnonce")) {
  1949. ah->cnonce = value;
  1950. } else if (!strcmp(name, "response")) {
  1951. ah->response = value;
  1952. } else if (!strcmp(name, "uri")) {
  1953. ah->uri = value;
  1954. } else if (!strcmp(name, "qop")) {
  1955. ah->qop = value;
  1956. } else if (!strcmp(name, "nc")) {
  1957. ah->nc = value;
  1958. } else if (!strcmp(name, "nonce")) {
  1959. ah->nonce = value;
  1960. }
  1961. }
  1962. // CGI needs it as REMOTE_USER
  1963. if (ah->user != NULL) {
  1964. conn->request_info.remote_user = mg_strdup(ah->user);
  1965. } else {
  1966. return 0;
  1967. }
  1968. return 1;
  1969. }
  1970. // Authorize against the opened passwords file. Return 1 if authorized.
  1971. static int authorize(struct mg_connection *conn, FILE *fp) {
  1972. struct ah ah;
  1973. char line[256], f_user[256], ha1[256], f_domain[256], buf[MG_BUF_LEN];
  1974. if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) {
  1975. return 0;
  1976. }
  1977. // Loop over passwords file
  1978. while (fgets(line, sizeof(line), fp) != NULL) {
  1979. if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {
  1980. continue;
  1981. }
  1982. if (!strcmp(ah.user, f_user) &&
  1983. !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))
  1984. return check_password(
  1985. conn->request_info.request_method,
  1986. ha1, ah.uri, ah.nonce, ah.nc, ah.cnonce, ah.qop,
  1987. ah.response);
  1988. }
  1989. return 0;
  1990. }
  1991. // Return 1 if request is authorised, 0 otherwise.
  1992. static int check_authorization(struct mg_connection *conn, const char *path) {
  1993. FILE *fp;
  1994. char fname[PATH_MAX];
  1995. struct vec uri_vec, filename_vec;
  1996. const char *list;
  1997. int authorized;
  1998. fp = NULL;
  1999. authorized = 1;
  2000. list = conn->ctx->config[PROTECT_URI];
  2001. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  2002. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  2003. mg_snprintf(conn, fname, sizeof(fname), "%.*s",
  2004. (int) filename_vec.len, filename_vec.ptr);
  2005. if ((fp = mg_fopen(fname, "r")) == NULL) {
  2006. cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));
  2007. }
  2008. break;
  2009. }
  2010. }
  2011. if (fp == NULL) {
  2012. fp = open_auth_file(conn, path);
  2013. }
  2014. if (fp != NULL) {
  2015. authorized = authorize(conn, fp);
  2016. (void) fclose(fp);
  2017. }
  2018. return authorized;
  2019. }
  2020. static void send_authorization_request(struct mg_connection *conn) {
  2021. conn->status_code = 401;
  2022. (void) mg_printf(conn,
  2023. "HTTP/1.1 401 Unauthorized\r\n"
  2024. "Content-Length: 0\r\n"
  2025. "WWW-Authenticate: Digest qop=\"auth\", "
  2026. "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
  2027. conn->ctx->config[AUTHENTICATION_DOMAIN],
  2028. (unsigned long) time(NULL));
  2029. }
  2030. static int is_authorized_for_put(struct mg_connection *conn) {
  2031. FILE *fp;
  2032. int ret = 0;
  2033. fp = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ? NULL :
  2034. mg_fopen(conn->ctx->config[PUT_DELETE_PASSWORDS_FILE], "r");
  2035. if (fp != NULL) {
  2036. ret = authorize(conn, fp);
  2037. (void) fclose(fp);
  2038. }
  2039. return ret;
  2040. }
  2041. int mg_modify_passwords_file(const char *fname, const char *domain,
  2042. const char *user, const char *pass) {
  2043. int found;
  2044. char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX];
  2045. FILE *fp, *fp2;
  2046. found = 0;
  2047. fp = fp2 = NULL;
  2048. // Regard empty password as no password - remove user record.
  2049. if (pass != NULL && pass[0] == '\0') {
  2050. pass = NULL;
  2051. }
  2052. (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);
  2053. // Create the file if does not exist
  2054. if ((fp = mg_fopen(fname, "a+")) != NULL) {
  2055. (void) fclose(fp);
  2056. }
  2057. // Open the given file and temporary file
  2058. if ((fp = mg_fopen(fname, "r")) == NULL) {
  2059. return 0;
  2060. } else if ((fp2 = mg_fopen(tmp, "w+")) == NULL) {
  2061. fclose(fp);
  2062. return 0;
  2063. }
  2064. // Copy the stuff to temporary file
  2065. while (fgets(line, sizeof(line), fp) != NULL) {
  2066. if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
  2067. continue;
  2068. }
  2069. if (!strcmp(u, user) && !strcmp(d, domain)) {
  2070. found++;
  2071. if (pass != NULL) {
  2072. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2073. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2074. }
  2075. } else {
  2076. (void) fprintf(fp2, "%s", line);
  2077. }
  2078. }
  2079. // If new user, just add it
  2080. if (!found && pass != NULL) {
  2081. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2082. (void) fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2083. }
  2084. // Close files
  2085. (void) fclose(fp);
  2086. (void) fclose(fp2);
  2087. // Put the temp file in place of real file
  2088. (void) mg_remove(fname);
  2089. (void) mg_rename(tmp, fname);
  2090. return 1;
  2091. }
  2092. struct de {
  2093. struct mg_connection *conn;
  2094. char *file_name;
  2095. struct mgstat st;
  2096. };
  2097. static void url_encode(const char *src, char *dst, size_t dst_len) {
  2098. static const char *dont_escape = "._-$,;~()";
  2099. static const char *hex = "0123456789abcdef";
  2100. const char *end = dst + dst_len - 1;
  2101. for (; *src != '\0' && dst < end; src++, dst++) {
  2102. if (isalnum(*(const unsigned char *) src) ||
  2103. strchr(dont_escape, * (const unsigned char *) src) != NULL) {
  2104. *dst = *src;
  2105. } else if (dst + 2 < end) {
  2106. dst[0] = '%';
  2107. dst[1] = hex[(* (const unsigned char *) src) >> 4];
  2108. dst[2] = hex[(* (const unsigned char *) src) & 0xf];
  2109. dst += 2;
  2110. }
  2111. }
  2112. *dst = '\0';
  2113. }
  2114. static void print_dir_entry(struct de *de) {
  2115. char size[64], mod[64], href[PATH_MAX];
  2116. if (de->st.is_directory) {
  2117. (void) mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
  2118. } else {
  2119. // We use (signed) cast below because MSVC 6 compiler cannot
  2120. // convert unsigned __int64 to double. Sigh.
  2121. if (de->st.size < 1024) {
  2122. (void) mg_snprintf(de->conn, size, sizeof(size),
  2123. "%lu", (unsigned long) de->st.size);
  2124. } else if (de->st.size < 0x100000) {
  2125. (void) mg_snprintf(de->conn, size, sizeof(size),
  2126. "%.1fk", (double) de->st.size / 1024.0);
  2127. } else if (de->st.size < 0x40000000) {
  2128. (void) mg_snprintf(de->conn, size, sizeof(size),
  2129. "%.1fM", (double) de->st.size / 1048576);
  2130. } else {
  2131. (void) mg_snprintf(de->conn, size, sizeof(size),
  2132. "%.1fG", (double) de->st.size / 1073741824);
  2133. }
  2134. }
  2135. (void) strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.mtime));
  2136. url_encode(de->file_name, href, sizeof(href));
  2137. de->conn->num_bytes_sent += mg_printf(de->conn,
  2138. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  2139. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2140. de->conn->request_info.uri, href, de->st.is_directory ? "/" : "",
  2141. de->file_name, de->st.is_directory ? "/" : "", mod, size);
  2142. }
  2143. // This function is called from send_directory() and used for
  2144. // sorting directory entries by size, or name, or modification time.
  2145. // On windows, __cdecl specification is needed in case if project is built
  2146. // with __stdcall convention. qsort always requires __cdels callback.
  2147. static int WINCDECL compare_dir_entries(const void *p1, const void *p2) {
  2148. const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;
  2149. const char *query_string = a->conn->request_info.query_string;
  2150. int cmp_result = 0;
  2151. if (query_string == NULL) {
  2152. query_string = "na";
  2153. }
  2154. if (a->st.is_directory && !b->st.is_directory) {
  2155. return -1; // Always put directories on top
  2156. } else if (!a->st.is_directory && b->st.is_directory) {
  2157. return 1; // Always put directories on top
  2158. } else if (*query_string == 'n') {
  2159. cmp_result = strcmp(a->file_name, b->file_name);
  2160. } else if (*query_string == 's') {
  2161. cmp_result = a->st.size == b->st.size ? 0 :
  2162. a->st.size > b->st.size ? 1 : -1;
  2163. } else if (*query_string == 'd') {
  2164. cmp_result = a->st.mtime == b->st.mtime ? 0 :
  2165. a->st.mtime > b->st.mtime ? 1 : -1;
  2166. }
  2167. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  2168. }
  2169. static int must_hide_file(struct mg_connection *conn, const char *path) {
  2170. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  2171. const char *pattern = conn->ctx->config[HIDE_FILES];
  2172. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
  2173. (pattern != NULL && match_prefix(pattern, strlen(pattern), path) > 0);
  2174. }
  2175. static int scan_directory(struct mg_connection *conn, const char *dir,
  2176. void *data, void (*cb)(struct de *, void *)) {
  2177. char path[PATH_MAX];
  2178. struct dirent *dp;
  2179. DIR *dirp;
  2180. struct de de;
  2181. if ((dirp = opendir(dir)) == NULL) {
  2182. return 0;
  2183. } else {
  2184. de.conn = conn;
  2185. while ((dp = readdir(dirp)) != NULL) {
  2186. // Do not show current dir and hidden files
  2187. if (!strcmp(dp->d_name, ".") ||
  2188. !strcmp(dp->d_name, "..") ||
  2189. must_hide_file(conn, dp->d_name)) {
  2190. continue;
  2191. }
  2192. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  2193. // If we don't memset stat structure to zero, mtime will have
  2194. // garbage and strftime() will segfault later on in
  2195. // print_dir_entry(). memset is required only if mg_stat()
  2196. // fails. For more details, see
  2197. // http://code.google.com/p/mongoose/issues/detail?id=79
  2198. if (mg_stat(path, &de.st) != 0) {
  2199. memset(&de.st, 0, sizeof(de.st));
  2200. }
  2201. de.file_name = dp->d_name;
  2202. cb(&de, data);
  2203. }
  2204. (void) closedir(dirp);
  2205. }
  2206. return 1;
  2207. }
  2208. struct dir_scan_data {
  2209. struct de *entries;
  2210. int num_entries;
  2211. int arr_size;
  2212. };
  2213. static void dir_scan_callback(struct de *de, void *data) {
  2214. struct dir_scan_data *dsd = (struct dir_scan_data *) data;
  2215. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  2216. dsd->arr_size *= 2;
  2217. dsd->entries = (struct de *) realloc(dsd->entries, dsd->arr_size *
  2218. sizeof(dsd->entries[0]));
  2219. }
  2220. if (dsd->entries == NULL) {
  2221. // TODO(lsm): propagate an error to the caller
  2222. dsd->num_entries = 0;
  2223. } else {
  2224. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  2225. dsd->entries[dsd->num_entries].st = de->st;
  2226. dsd->entries[dsd->num_entries].conn = de->conn;
  2227. dsd->num_entries++;
  2228. }
  2229. }
  2230. static void handle_directory_request(struct mg_connection *conn,
  2231. const char *dir) {
  2232. int i, sort_direction;
  2233. struct dir_scan_data data = { NULL, 0, 128 };
  2234. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  2235. send_http_error(conn, 500, "Cannot open directory",
  2236. "Error: opendir(%s): %s", dir, strerror(ERRNO));
  2237. return;
  2238. }
  2239. sort_direction = conn->request_info.query_string != NULL &&
  2240. conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
  2241. conn->must_close = 1;
  2242. mg_printf(conn, "%s",
  2243. "HTTP/1.1 200 OK\r\n"
  2244. "Connection: close\r\n"
  2245. "Content-Type: text/html; charset=utf-8\r\n\r\n");
  2246. conn->num_bytes_sent += mg_printf(conn,
  2247. "<html><head><title>Index of %s</title>"
  2248. "<style>th {text-align: left;}</style></head>"
  2249. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  2250. "<tr><th><a href=\"?n%c\">Name</a></th>"
  2251. "<th><a href=\"?d%c\">Modified</a></th>"
  2252. "<th><a href=\"?s%c\">Size</a></th></tr>"
  2253. "<tr><td colspan=\"3\"><hr></td></tr>",
  2254. conn->request_info.uri, conn->request_info.uri,
  2255. sort_direction, sort_direction, sort_direction);
  2256. // Print first entry - link to a parent directory
  2257. conn->num_bytes_sent += mg_printf(conn,
  2258. "<tr><td><a href=\"%s%s\">%s</a></td>"
  2259. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2260. conn->request_info.uri, "..", "Parent directory", "-", "-");
  2261. // Sort and print directory entries
  2262. qsort(data.entries, (size_t) data.num_entries, sizeof(data.entries[0]),
  2263. compare_dir_entries);
  2264. for (i = 0; i < data.num_entries; i++) {
  2265. print_dir_entry(&data.entries[i]);
  2266. free(data.entries[i].file_name);
  2267. }
  2268. free(data.entries);
  2269. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  2270. conn->status_code = 200;
  2271. }
  2272. // Send len bytes from the opened file to the client.
  2273. static void send_file_data(struct mg_connection *conn, FILE *fp, int64_t len) {
  2274. char buf[MG_BUF_LEN];
  2275. int to_read, num_read, num_written;
  2276. while (len > 0) {
  2277. // Calculate how much to read from the file in the buffer
  2278. to_read = sizeof(buf);
  2279. if ((int64_t) to_read > len) {
  2280. to_read = (int) len;
  2281. }
  2282. // Read from file, exit the loop on error
  2283. if ((num_read = fread(buf, 1, (size_t)to_read, fp)) <= 0) {
  2284. break;
  2285. }
  2286. // Send read bytes to the client, exit the loop on error
  2287. if ((num_written = mg_write(conn, buf, (size_t)num_read)) != num_read) {
  2288. break;
  2289. }
  2290. // Both read and were successful, adjust counters
  2291. conn->num_bytes_sent += num_written;
  2292. len -= num_written;
  2293. }
  2294. }
  2295. static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
  2296. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  2297. }
  2298. static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  2299. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
  2300. }
  2301. static void construct_etag(char *buf, size_t buf_len,
  2302. const struct mgstat *stp) {
  2303. snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
  2304. (unsigned long) stp->mtime, stp->size);
  2305. }
  2306. static void handle_file_request(struct mg_connection *conn, const char *path,
  2307. struct mgstat *stp) {
  2308. char date[64], lm[64], etag[64], range[64];
  2309. const char *msg = "OK", *hdr;
  2310. time_t curtime = time(NULL);
  2311. int64_t cl, r1, r2;
  2312. struct vec mime_vec;
  2313. FILE *fp;
  2314. int n;
  2315. get_mime_type(conn->ctx, path, &mime_vec);
  2316. cl = stp->size;
  2317. conn->status_code = 200;
  2318. range[0] = '\0';
  2319. if ((fp = mg_fopen(path, "rb")) == NULL) {
  2320. send_http_error(conn, 500, http_500_error,
  2321. "fopen(%s): %s", path, strerror(ERRNO));
  2322. return;
  2323. }
  2324. set_close_on_exec(fileno(fp));
  2325. // If Range: header specified, act accordingly
  2326. r1 = r2 = 0;
  2327. hdr = mg_get_header(conn, "Range");
  2328. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0) {
  2329. conn->status_code = 206;
  2330. (void) fseeko(fp, r1, SEEK_SET);
  2331. cl = n == 2 ? r2 - r1 + 1: cl - r1;
  2332. (void) mg_snprintf(conn, range, sizeof(range),
  2333. "Content-Range: bytes "
  2334. "%" INT64_FMT "-%"
  2335. INT64_FMT "/%" INT64_FMT "\r\n",
  2336. r1, r1 + cl - 1, stp->size);
  2337. msg = "Partial Content";
  2338. }
  2339. // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  2340. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
  2341. gmt_time_string(date, sizeof(date), &curtime);
  2342. gmt_time_string(lm, sizeof(lm), &stp->mtime);
  2343. construct_etag(etag, sizeof(etag), stp);
  2344. (void) mg_printf(conn,
  2345. "HTTP/1.1 %d %s\r\n"
  2346. "Date: %s\r\n"
  2347. "Last-Modified: %s\r\n"
  2348. "Etag: %s\r\n"
  2349. "Content-Type: %.*s\r\n"
  2350. "Content-Length: %" INT64_FMT "\r\n"
  2351. "Connection: %s\r\n"
  2352. "Accept-Ranges: bytes\r\n"
  2353. "%s\r\n",
  2354. conn->status_code, msg, date, lm, etag, (int) mime_vec.len,
  2355. mime_vec.ptr, cl, suggest_connection_header(conn), range);
  2356. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  2357. send_file_data(conn, fp, cl);
  2358. }
  2359. (void) fclose(fp);
  2360. }
  2361. void mg_send_file(struct mg_connection *conn, const char *path) {
  2362. struct mgstat st;
  2363. if (mg_stat(path, &st) == 0) {
  2364. handle_file_request(conn, path, &st);
  2365. } else {
  2366. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  2367. }
  2368. }
  2369. // Parse HTTP headers from the given buffer, advance buffer to the point
  2370. // where parsing stopped.
  2371. static void parse_http_headers(char **buf, struct mg_request_info *ri) {
  2372. int i;
  2373. for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
  2374. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  2375. ri->http_headers[i].value = skip(buf, "\r\n");
  2376. if (ri->http_headers[i].name[0] == '\0')
  2377. break;
  2378. ri->num_headers = i + 1;
  2379. }
  2380. }
  2381. static int is_valid_http_method(const char *method) {
  2382. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  2383. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  2384. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  2385. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND");
  2386. }
  2387. // Parse HTTP request, fill in mg_request_info structure.
  2388. // This function modifies the buffer by NUL-terminating
  2389. // HTTP request components, header names and header values.
  2390. static int parse_http_message(char *buf, int len, struct mg_request_info *ri) {
  2391. int request_length = get_request_len(buf, len);
  2392. if (request_length > 0) {
  2393. // Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port
  2394. ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
  2395. ri->num_headers = 0;
  2396. buf[request_length - 1] = '\0';
  2397. // RFC says that all initial whitespaces should be ingored
  2398. while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
  2399. buf++;
  2400. }
  2401. ri->request_method = skip(&buf, " ");
  2402. ri->uri = skip(&buf, " ");
  2403. ri->http_version = skip(&buf, "\r\n");
  2404. parse_http_headers(&buf, ri);
  2405. }
  2406. return request_length;
  2407. }
  2408. static int parse_http_request(char *buf, int len, struct mg_request_info *ri) {
  2409. int result = parse_http_message(buf, len, ri);
  2410. if (result > 0 &&
  2411. is_valid_http_method(ri->request_method) &&
  2412. !strncmp(ri->http_version, "HTTP/", 5)) {
  2413. ri->http_version += 5; // Skip "HTTP/"
  2414. } else {
  2415. result = -1;
  2416. }
  2417. return result;
  2418. }
  2419. static int parse_http_response(char *buf, int len, struct mg_request_info *ri) {
  2420. int result = parse_http_message(buf, len, ri);
  2421. return result > 0 && !strncmp(ri->request_method, "HTTP/", 5) ? result : -1;
  2422. }
  2423. // Keep reading the input (either opened file descriptor fd, or socket sock,
  2424. // or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  2425. // buffer (which marks the end of HTTP request). Buffer buf may already
  2426. // have some data. The length of the data is stored in nread.
  2427. // Upon every read operation, increase nread by the number of bytes read.
  2428. static int read_request(FILE *fp, struct mg_connection *conn,
  2429. char *buf, int bufsiz, int *nread) {
  2430. int request_len, n = 1;
  2431. request_len = get_request_len(buf, *nread);
  2432. while (*nread < bufsiz && request_len == 0 && n > 0) {
  2433. n = pull(fp, conn, buf + *nread, bufsiz - *nread);
  2434. if (n > 0) {
  2435. *nread += n;
  2436. request_len = get_request_len(buf, *nread);
  2437. }
  2438. }
  2439. if (n < 0) {
  2440. // recv() error -> propagate error; do not process a b0rked-with-very-high-probability request
  2441. return -1;
  2442. }
  2443. return request_len;
  2444. }
  2445. // For given directory path, substitute it to valid index file.
  2446. // Return 0 if index file has been found, -1 if not found.
  2447. // If the file is found, it's stats is returned in stp.
  2448. static int substitute_index_file(struct mg_connection *conn, char *path,
  2449. size_t path_len, struct mgstat *stp) {
  2450. const char *list = conn->ctx->config[INDEX_FILES];
  2451. struct mgstat st;
  2452. struct vec filename_vec;
  2453. size_t n = strlen(path);
  2454. int found = 0;
  2455. // The 'path' given to us points to the directory. Remove all trailing
  2456. // directory separator characters from the end of the path, and
  2457. // then append single directory separator character.
  2458. while (n > 0 && path[n - 1] == '/') {
  2459. n--;
  2460. }
  2461. path[n] = '/';
  2462. // Traverse index files list. For each entry, append it to the given
  2463. // path and see if the file exists. If it exists, break the loop
  2464. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  2465. // Ignore too long entries that may overflow path buffer
  2466. if (filename_vec.len > path_len - (n + 2))
  2467. continue;
  2468. // Prepare full path to the index file
  2469. (void) mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  2470. // Does it exist?
  2471. if (mg_stat(path, &st) == 0) {
  2472. // Yes it does, break the loop
  2473. *stp = st;
  2474. found = 1;
  2475. break;
  2476. }
  2477. }
  2478. // If no index file exists, restore directory path
  2479. if (!found) {
  2480. path[n] = '\0';
  2481. }
  2482. return found;
  2483. }
  2484. // Return True if we should reply 304 Not Modified.
  2485. static int is_not_modified(const struct mg_connection *conn,
  2486. const struct mgstat *stp) {
  2487. char etag[64];
  2488. const char *ims = mg_get_header(conn, "If-Modified-Since");
  2489. const char *inm = mg_get_header(conn, "If-None-Match");
  2490. construct_etag(etag, sizeof(etag), stp);
  2491. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  2492. (ims != NULL && stp->mtime <= parse_date_string(ims));
  2493. }
  2494. static int forward_body_data(struct mg_connection *conn, FILE *fp,
  2495. SOCKET sock, SSL *ssl) {
  2496. const char *expect, *body;
  2497. char buf[MG_BUF_LEN];
  2498. int to_read, nread, buffered_len, success = 0;
  2499. expect = mg_get_header(conn, "Expect");
  2500. assert(fp != NULL);
  2501. if (conn->content_len == -1) {
  2502. send_http_error(conn, 411, "Length Required", "%s", "");
  2503. } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
  2504. send_http_error(conn, 417, "Expectation Failed", "%s", "");
  2505. } else {
  2506. if (expect != NULL) {
  2507. (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  2508. }
  2509. body = conn->buf + conn->request_len + conn->consumed_content;
  2510. buffered_len = &conn->buf[conn->data_len] - body;
  2511. assert(buffered_len >= 0);
  2512. assert(conn->consumed_content == 0);
  2513. if (buffered_len > 0) {
  2514. if ((int64_t) buffered_len > conn->content_len) {
  2515. buffered_len = (int) conn->content_len;
  2516. }
  2517. push(fp, sock, ssl, body, (int64_t) buffered_len);
  2518. conn->consumed_content += buffered_len;
  2519. }
  2520. nread = 0;
  2521. while (conn->consumed_content < conn->content_len) {
  2522. to_read = sizeof(buf);
  2523. if ((int64_t) to_read > conn->content_len - conn->consumed_content) {
  2524. to_read = (int) (conn->content_len - conn->consumed_content);
  2525. }
  2526. nread = pull(NULL, conn, buf, to_read);
  2527. if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
  2528. break;
  2529. }
  2530. conn->consumed_content += nread;
  2531. }
  2532. if (conn->consumed_content == conn->content_len) {
  2533. success = nread >= 0;
  2534. }
  2535. // Each error code path in this function must send an error
  2536. if (!success) {
  2537. send_http_error(conn, 577, http_500_error, "%s", "");
  2538. }
  2539. }
  2540. return success;
  2541. }
  2542. #if !defined(NO_CGI)
  2543. // This structure helps to create an environment for the spawned CGI program.
  2544. // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  2545. // last element must be NULL.
  2546. // However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  2547. // strings must reside in a contiguous buffer. The end of the buffer is
  2548. // marked by two '\0' characters.
  2549. // We satisfy both worlds: we create an envp array (which is vars), all
  2550. // entries are actually pointers inside buf.
  2551. struct cgi_env_block {
  2552. struct mg_connection *conn;
  2553. char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
  2554. int len; // Space taken
  2555. char *vars[MAX_CGI_ENVIR_VARS]; // char **envp
  2556. int nvars; // Number of variables
  2557. };
  2558. static char *addenv(struct cgi_env_block *block,
  2559. PRINTF_FORMAT_STRING(const char *fmt), ...)
  2560. PRINTF_ARGS(2, 3);
  2561. // Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  2562. // pointer into the vars array.
  2563. static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
  2564. int n, space;
  2565. char *added;
  2566. va_list ap;
  2567. // Calculate how much space is left in the buffer
  2568. space = sizeof(block->buf) - block->len - 2;
  2569. assert(space >= 0);
  2570. // Make a pointer to the free space int the buffer
  2571. added = block->buf + block->len;
  2572. // Copy VARIABLE=VALUE\0 string into the free space
  2573. va_start(ap, fmt);
  2574. n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
  2575. va_end(ap);
  2576. // Make sure we do not overflow buffer and the envp array
  2577. if (n > 0 && n + 1 < space &&
  2578. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  2579. // Append a pointer to the added string into the envp array
  2580. block->vars[block->nvars++] = added;
  2581. // Bump up used length counter. Include \0 terminator
  2582. block->len += n + 1;
  2583. } else {
  2584. cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt);
  2585. }
  2586. return added;
  2587. }
  2588. static void prepare_cgi_environment(struct mg_connection *conn,
  2589. const char *prog,
  2590. struct cgi_env_block *blk) {
  2591. const char *s, *slash;
  2592. struct vec var_vec;
  2593. char *p, src_addr[20];
  2594. int i;
  2595. blk->len = blk->nvars = 0;
  2596. blk->conn = conn;
  2597. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2598. addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  2599. addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  2600. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  2601. // Prepare the environment block
  2602. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  2603. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  2604. addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
  2605. // TODO(lsm): fix this for IPv6 case
  2606. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  2607. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  2608. addenv(blk, "REMOTE_ADDR=%s", src_addr);
  2609. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  2610. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  2611. // SCRIPT_NAME
  2612. assert(conn->request_info.uri[0] == '/');
  2613. slash = strrchr(conn->request_info.uri, '/');
  2614. if ((s = strrchr(prog, '/')) == NULL)
  2615. s = prog;
  2616. addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri),
  2617. conn->request_info.uri, s);
  2618. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  2619. addenv(blk, "PATH_TRANSLATED=%s", prog);
  2620. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  2621. if ((s = mg_get_header(conn, "Content-Type")) != NULL)
  2622. addenv(blk, "CONTENT_TYPE=%s", s);
  2623. if (conn->request_info.query_string != NULL)
  2624. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  2625. if ((s = mg_get_header(conn, "Content-Length")) != NULL)
  2626. addenv(blk, "CONTENT_LENGTH=%s", s);
  2627. if ((s = getenv("PATH")) != NULL)
  2628. addenv(blk, "PATH=%s", s);
  2629. if (conn->path_info != NULL) {
  2630. addenv(blk, "PATH_INFO=%s", conn->path_info);
  2631. }
  2632. #if defined(_WIN32)
  2633. if ((s = getenv("COMSPEC")) != NULL) {
  2634. addenv(blk, "COMSPEC=%s", s);
  2635. }
  2636. if ((s = getenv("SYSTEMROOT")) != NULL) {
  2637. addenv(blk, "SYSTEMROOT=%s", s);
  2638. }
  2639. if ((s = getenv("SystemDrive")) != NULL) {
  2640. addenv(blk, "SystemDrive=%s", s);
  2641. }
  2642. #else
  2643. if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
  2644. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  2645. #endif // _WIN32
  2646. if ((s = getenv("PERLLIB")) != NULL)
  2647. addenv(blk, "PERLLIB=%s", s);
  2648. if (conn->request_info.remote_user != NULL) {
  2649. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  2650. addenv(blk, "%s", "AUTH_TYPE=Digest");
  2651. }
  2652. // Add all headers as HTTP_* variables
  2653. for (i = 0; i < conn->request_info.num_headers; i++) {
  2654. p = addenv(blk, "HTTP_%s=%s",
  2655. conn->request_info.http_headers[i].name,
  2656. conn->request_info.http_headers[i].value);
  2657. // Convert variable name into uppercase, and change - to _
  2658. for (; *p != '=' && *p != '\0'; p++) {
  2659. if (*p == '-')
  2660. *p = '_';
  2661. *p = (char) toupper(* (unsigned char *) p);
  2662. }
  2663. }
  2664. // Add user-specified variables
  2665. s = conn->ctx->config[CGI_ENVIRONMENT];
  2666. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  2667. addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr);
  2668. }
  2669. blk->vars[blk->nvars++] = NULL;
  2670. blk->buf[blk->len++] = '\0';
  2671. assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  2672. assert(blk->len > 0);
  2673. assert(blk->len < (int) sizeof(blk->buf));
  2674. }
  2675. static void handle_cgi_request(struct mg_connection *conn, const char *prog) {
  2676. int headers_len, data_len, i, fd_stdin[2], fd_stdout[2];
  2677. const char *status, *status_text;
  2678. char buf[16384], *pbuf, dir[PATH_MAX], *p;
  2679. struct mg_request_info ri;
  2680. struct cgi_env_block blk;
  2681. FILE *in, *out;
  2682. pid_t pid;
  2683. prepare_cgi_environment(conn, prog, &blk);
  2684. // CGI must be executed in its own directory. 'dir' must point to the
  2685. // directory containing executable program, 'p' must point to the
  2686. // executable program name relative to 'dir'.
  2687. (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  2688. if ((p = strrchr(dir, '/')) != NULL) {
  2689. *p++ = '\0';
  2690. } else {
  2691. dir[0] = '.', dir[1] = '\0';
  2692. p = (char *) prog;
  2693. }
  2694. pid = (pid_t) -1;
  2695. fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1;
  2696. in = out = NULL;
  2697. if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) {
  2698. send_http_error(conn, 500, http_500_error,
  2699. "Cannot create CGI pipe: %s", strerror(ERRNO));
  2700. goto done;
  2701. } else if ((pid = spawn_process(conn, p, blk.buf, blk.vars,
  2702. fd_stdin[0], fd_stdout[1], dir)) == (pid_t) -1) {
  2703. send_http_error(conn, 500, http_500_error,
  2704. "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));
  2705. goto done;
  2706. }
  2707. // spawn_process() must close those!
  2708. // If we don't mark them as closed, close() attempt before
  2709. // return from this function throws an exception on Windows.
  2710. // Windows does not like when closed descriptor is closed again.
  2711. fd_stdin[0] = fd_stdout[1] = -1;
  2712. if ((in = fdopen(fd_stdin[1], "wb")) == NULL ||
  2713. (out = fdopen(fd_stdout[0], "rb")) == NULL) {
  2714. send_http_error(conn, 500, http_500_error,
  2715. "fopen: %s", strerror(ERRNO));
  2716. goto done;
  2717. }
  2718. setbuf(in, NULL);
  2719. setbuf(out, NULL);
  2720. // Send POST data to the CGI process if needed
  2721. if (!strcmp(conn->request_info.request_method, "POST") &&
  2722. !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  2723. goto done;
  2724. }
  2725. // Close so child gets an EOF.
  2726. fclose(in);
  2727. in = NULL;
  2728. fd_stdin[1] = -1;
  2729. // Now read CGI reply into a buffer. We need to set correct
  2730. // status code, thus we need to see all HTTP headers first.
  2731. // Do not send anything back to client, until we buffer in all
  2732. // HTTP headers.
  2733. data_len = 0;
  2734. headers_len = read_request(out, conn, buf, sizeof(buf), &data_len);
  2735. if (headers_len <= 0) {
  2736. send_http_error(conn, 500, http_500_error,
  2737. "CGI program sent malformed or too big (>%u bytes) "
  2738. "HTTP headers: [%.*s]",
  2739. (unsigned) sizeof(buf), data_len, buf);
  2740. goto done;
  2741. }
  2742. pbuf = buf;
  2743. buf[headers_len - 1] = '\0';
  2744. parse_http_headers(&pbuf, &ri);
  2745. // Make up and send the status line
  2746. status_text = "OK";
  2747. if ((status = get_header(&ri, "Status")) != NULL) {
  2748. conn->status_code = atoi(status);
  2749. status_text = status;
  2750. while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {
  2751. status_text++;
  2752. }
  2753. } else if (get_header(&ri, "Location") != NULL) {
  2754. conn->status_code = 302;
  2755. } else {
  2756. conn->status_code = 200;
  2757. }
  2758. if (get_header(&ri, "Connection") != NULL &&
  2759. !mg_strcasecmp(get_header(&ri, "Connection"), "keep-alive")) {
  2760. conn->must_close = 1;
  2761. }
  2762. (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code,
  2763. status_text);
  2764. // Send headers
  2765. for (i = 0; i < ri.num_headers; i++) {
  2766. mg_printf(conn, "%s: %s\r\n",
  2767. ri.http_headers[i].name, ri.http_headers[i].value);
  2768. }
  2769. (void) mg_write(conn, "\r\n", 2);
  2770. // Send chunk of data that may have been read after the headers
  2771. conn->num_bytes_sent += mg_write(conn, buf + headers_len,
  2772. (size_t)(data_len - headers_len));
  2773. // Read the rest of CGI output and send to the client
  2774. send_file_data(conn, out, INT64_MAX);
  2775. done:
  2776. if (pid != (pid_t) -1) {
  2777. kill(pid, SIGKILL);
  2778. }
  2779. if (fd_stdin[0] != -1) {
  2780. (void) close(fd_stdin[0]);
  2781. }
  2782. if (fd_stdout[1] != -1) {
  2783. (void) close(fd_stdout[1]);
  2784. }
  2785. if (in != NULL) {
  2786. (void) fclose(in);
  2787. } else if (fd_stdin[1] != -1) {
  2788. (void) close(fd_stdin[1]);
  2789. }
  2790. if (out != NULL) {
  2791. (void) fclose(out);
  2792. } else if (fd_stdout[0] != -1) {
  2793. (void) close(fd_stdout[0]);
  2794. }
  2795. }
  2796. #endif // !NO_CGI
  2797. // For a given PUT path, create all intermediate subdirectories
  2798. // for given path. Return 0 if the path itself is a directory,
  2799. // or -1 on error, 1 if OK.
  2800. static int put_dir(const char *path) {
  2801. char buf[PATH_MAX];
  2802. const char *s, *p;
  2803. struct mgstat st;
  2804. int len, res = 1;
  2805. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  2806. len = p - path;
  2807. if (len >= (int) sizeof(buf)) {
  2808. res = -1;
  2809. break;
  2810. }
  2811. memcpy(buf, path, len);
  2812. buf[len] = '\0';
  2813. // Try to create intermediate directory
  2814. DEBUG_TRACE(("mkdir(%s)", buf));
  2815. if (mg_stat(buf, &st) == -1 && mg_mkdir(buf, 0755) != 0) {
  2816. res = -1;
  2817. break;
  2818. }
  2819. // Is path itself a directory?
  2820. if (p[1] == '\0') {
  2821. res = 0;
  2822. }
  2823. }
  2824. return res;
  2825. }
  2826. static void put_file(struct mg_connection *conn, const char *path) {
  2827. struct mgstat st;
  2828. const char *range;
  2829. int64_t r1, r2;
  2830. FILE *fp;
  2831. int rc;
  2832. conn->status_code = mg_stat(path, &st) == 0 ? 200 : 201;
  2833. if ((rc = put_dir(path)) == 0) {
  2834. mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);
  2835. } else if (rc == -1) {
  2836. send_http_error(conn, 500, http_500_error,
  2837. "put_dir(%s): %s", path, strerror(ERRNO));
  2838. } else if ((fp = mg_fopen(path, "wb+")) == NULL) {
  2839. send_http_error(conn, 500, http_500_error,
  2840. "fopen(%s): %s", path, strerror(ERRNO));
  2841. } else {
  2842. set_close_on_exec(fileno(fp));
  2843. range = mg_get_header(conn, "Content-Range");
  2844. r1 = r2 = 0;
  2845. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  2846. conn->status_code = 206;
  2847. // TODO(lsm): handle seek error
  2848. (void) fseeko(fp, r1, SEEK_SET);
  2849. }
  2850. if (forward_body_data(conn, fp, INVALID_SOCKET, NULL)) {
  2851. (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);
  2852. }
  2853. (void) fclose(fp);
  2854. }
  2855. }
  2856. static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);
  2857. static void do_ssi_include(struct mg_connection *conn, const char *ssi,
  2858. char *tag, int include_level) {
  2859. char file_name[MG_BUF_LEN], path[PATH_MAX], *p;
  2860. FILE *fp;
  2861. // sscanf() is safe here, since send_ssi_file() also uses buffer
  2862. // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
  2863. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
  2864. // File name is relative to the webserver root
  2865. (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
  2866. conn->ctx->config[DOCUMENT_ROOT], '/', file_name);
  2867. } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) {
  2868. // File name is relative to the webserver working directory
  2869. // or it is absolute system path
  2870. (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  2871. } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
  2872. // File name is relative to the currect document
  2873. (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  2874. if ((p = strrchr(path, '/')) != NULL) {
  2875. p[1] = '\0';
  2876. }
  2877. (void) mg_snprintf(conn, path + strlen(path),
  2878. sizeof(path) - strlen(path), "%s", file_name);
  2879. } else {
  2880. cry(conn, "Bad SSI #include: [%s]", tag);
  2881. return;
  2882. }
  2883. if ((fp = mg_fopen(path, "rb")) == NULL) {
  2884. cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
  2885. tag, path, strerror(ERRNO));
  2886. } else {
  2887. set_close_on_exec(fileno(fp));
  2888. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  2889. strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {
  2890. send_ssi_file(conn, path, fp, include_level + 1);
  2891. } else {
  2892. send_file_data(conn, fp, INT64_MAX);
  2893. }
  2894. (void) fclose(fp);
  2895. }
  2896. }
  2897. #if !defined(NO_POPEN)
  2898. static void do_ssi_exec(struct mg_connection *conn, char *tag) {
  2899. char cmd[MG_BUF_LEN];
  2900. FILE *fp;
  2901. if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
  2902. cry(conn, "Bad SSI #exec: [%s]", tag);
  2903. } else if ((fp = popen(cmd, "r")) == NULL) {
  2904. cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  2905. } else {
  2906. send_file_data(conn, fp, INT64_MAX);
  2907. (void) pclose(fp);
  2908. }
  2909. }
  2910. #endif // !NO_POPEN
  2911. static void send_ssi_file(struct mg_connection *conn, const char *path,
  2912. FILE *fp, int include_level) {
  2913. char buf[MG_BUF_LEN];
  2914. int ch, len, in_ssi_tag;
  2915. if (include_level > 10) {
  2916. cry(conn, "SSI #include level is too deep (%s)", path);
  2917. return;
  2918. }
  2919. in_ssi_tag = 0;
  2920. len = 0;
  2921. while ((ch = fgetc(fp)) != EOF) {
  2922. if (in_ssi_tag && ch == '>') {
  2923. in_ssi_tag = 0;
  2924. buf[len++] = (char) ch;
  2925. buf[len] = '\0';
  2926. assert(len <= (int) sizeof(buf));
  2927. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  2928. // Not an SSI tag, pass it
  2929. (void) mg_write(conn, buf, (size_t)len);
  2930. } else {
  2931. if (!memcmp(buf + 5, "include", 7)) {
  2932. do_ssi_include(conn, path, buf + 12, include_level);
  2933. #if !defined(NO_POPEN)
  2934. } else if (!memcmp(buf + 5, "exec", 4)) {
  2935. do_ssi_exec(conn, buf + 9);
  2936. #endif // !NO_POPEN
  2937. } else {
  2938. cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
  2939. }
  2940. }
  2941. len = 0;
  2942. } else if (in_ssi_tag) {
  2943. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  2944. // Not an SSI tag
  2945. in_ssi_tag = 0;
  2946. } else if (len == (int) sizeof(buf) - 2) {
  2947. cry(conn, "%s: SSI tag is too large", path);
  2948. len = 0;
  2949. }
  2950. buf[len++] = ch & 0xff;
  2951. } else if (ch == '<') {
  2952. in_ssi_tag = 1;
  2953. if (len > 0) {
  2954. (void) mg_write(conn, buf, (size_t)len);
  2955. }
  2956. len = 0;
  2957. buf[len++] = ch & 0xff;
  2958. } else {
  2959. buf[len++] = ch & 0xff;
  2960. if (len == (int) sizeof(buf)) {
  2961. (void) mg_write(conn, buf, (size_t)len);
  2962. len = 0;
  2963. }
  2964. }
  2965. }
  2966. // Send the rest of buffered data
  2967. if (len > 0) {
  2968. (void) mg_write(conn, buf, (size_t)len);
  2969. }
  2970. }
  2971. static void handle_ssi_file_request(struct mg_connection *conn,
  2972. const char *path) {
  2973. FILE *fp;
  2974. if ((fp = mg_fopen(path, "rb")) == NULL) {
  2975. send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,
  2976. strerror(ERRNO));
  2977. } else {
  2978. conn->must_close = 1;
  2979. set_close_on_exec(fileno(fp));
  2980. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  2981. "Content-Type: text/html\r\nConnection: %s\r\n\r\n",
  2982. suggest_connection_header(conn));
  2983. send_ssi_file(conn, path, fp, 0);
  2984. (void) fclose(fp);
  2985. }
  2986. }
  2987. static void send_options(struct mg_connection *conn) {
  2988. conn->status_code = 200;
  2989. (void) mg_printf(conn,
  2990. "HTTP/1.1 200 OK\r\n"
  2991. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS\r\n"
  2992. "DAV: 1\r\n\r\n");
  2993. }
  2994. // Writes PROPFIND properties for a collection element
  2995. static void print_props(struct mg_connection *conn, const char* uri,
  2996. struct mgstat* st) {
  2997. char mtime[64];
  2998. gmt_time_string(mtime, sizeof(mtime), &st->mtime);
  2999. conn->num_bytes_sent += mg_printf(conn,
  3000. "<d:response>"
  3001. "<d:href>%s</d:href>"
  3002. "<d:propstat>"
  3003. "<d:prop>"
  3004. "<d:resourcetype>%s</d:resourcetype>"
  3005. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  3006. "<d:getlastmodified>%s</d:getlastmodified>"
  3007. "</d:prop>"
  3008. "<d:status>HTTP/1.1 200 OK</d:status>"
  3009. "</d:propstat>"
  3010. "</d:response>\n",
  3011. uri,
  3012. st->is_directory ? "<d:collection/>" : "",
  3013. st->size,
  3014. mtime);
  3015. }
  3016. static void print_dav_dir_entry(struct de *de, void *data) {
  3017. char href[PATH_MAX];
  3018. struct mg_connection *conn = (struct mg_connection *) data;
  3019. mg_snprintf(conn, href, sizeof(href), "%s%s",
  3020. conn->request_info.uri, de->file_name);
  3021. print_props(conn, href, &de->st);
  3022. }
  3023. static void handle_propfind(struct mg_connection *conn, const char* path,
  3024. struct mgstat* st) {
  3025. const char *depth = mg_get_header(conn, "Depth");
  3026. conn->must_close = 1;
  3027. conn->status_code = 207;
  3028. mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
  3029. "Connection: close\r\n"
  3030. "Content-Type: text/xml; charset=utf-8\r\n\r\n");
  3031. conn->num_bytes_sent += mg_printf(conn,
  3032. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  3033. "<d:multistatus xmlns:d='DAV:'>\n");
  3034. // Print properties for the requested resource itself
  3035. print_props(conn, conn->request_info.uri, st);
  3036. // If it is a directory, print directory entries too if Depth is not 0
  3037. if (st->is_directory &&
  3038. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  3039. (depth == NULL || strcmp(depth, "0") != 0)) {
  3040. scan_directory(conn, path, conn, &print_dav_dir_entry);
  3041. }
  3042. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  3043. }
  3044. #if defined(USE_WEBSOCKET)
  3045. // START OF SHA-1 code
  3046. // Copyright(c) By Steve Reid <steve@edmweb.com>
  3047. #define SHA1HANDSOFF
  3048. #if defined(__sun)
  3049. #include "solarisfixes.h"
  3050. #endif
  3051. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  3052. #if BYTE_ORDER == LITTLE_ENDIAN
  3053. #define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
  3054. |(rol(block->l[i],8)&0x00FF00FF))
  3055. #elif BYTE_ORDER == BIG_ENDIAN
  3056. #define blk0(i) block->l[i]
  3057. #else
  3058. #error "Endianness not defined!"
  3059. #endif
  3060. #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
  3061. ^block->l[(i+2)&15]^block->l[i&15],1))
  3062. #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
  3063. #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
  3064. #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
  3065. #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
  3066. #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
  3067. typedef struct {
  3068. uint32_t state[5];
  3069. uint32_t count[2];
  3070. unsigned char buffer[64];
  3071. } SHA1_CTX;
  3072. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
  3073. uint32_t a, b, c, d, e;
  3074. typedef union { unsigned char c[64]; uint32_t l[16]; } CHAR64LONG16;
  3075. CHAR64LONG16 block[1];
  3076. memcpy(block, buffer, 64);
  3077. a = state[0];
  3078. b = state[1];
  3079. c = state[2];
  3080. d = state[3];
  3081. e = state[4];
  3082. R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
  3083. R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
  3084. R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
  3085. R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
  3086. R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
  3087. R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
  3088. R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
  3089. R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
  3090. R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
  3091. R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
  3092. R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
  3093. R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
  3094. R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
  3095. R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
  3096. R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
  3097. R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
  3098. R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
  3099. R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
  3100. R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
  3101. R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
  3102. state[0] += a;
  3103. state[1] += b;
  3104. state[2] += c;
  3105. state[3] += d;
  3106. state[4] += e;
  3107. a = b = c = d = e = 0;
  3108. memset(block, '\0', sizeof(block));
  3109. }
  3110. static void SHA1Init(SHA1_CTX* context) {
  3111. context->state[0] = 0x67452301;
  3112. context->state[1] = 0xEFCDAB89;
  3113. context->state[2] = 0x98BADCFE;
  3114. context->state[3] = 0x10325476;
  3115. context->state[4] = 0xC3D2E1F0;
  3116. context->count[0] = context->count[1] = 0;
  3117. }
  3118. static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
  3119. uint32_t len) {
  3120. uint32_t i, j;
  3121. j = context->count[0];
  3122. if ((context->count[0] += len << 3) < j)
  3123. context->count[1]++;
  3124. context->count[1] += (len>>29);
  3125. j = (j >> 3) & 63;
  3126. if ((j + len) > 63) {
  3127. memcpy(&context->buffer[j], data, (i = 64-j));
  3128. SHA1Transform(context->state, context->buffer);
  3129. for ( ; i + 63 < len; i += 64) {
  3130. SHA1Transform(context->state, &data[i]);
  3131. }
  3132. j = 0;
  3133. }
  3134. else i = 0;
  3135. memcpy(&context->buffer[j], &data[i], len - i);
  3136. }
  3137. static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) {
  3138. unsigned i;
  3139. unsigned char finalcount[8], c;
  3140. for (i = 0; i < 8; i++) {
  3141. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  3142. >> ((3-(i & 3)) * 8) ) & 255);
  3143. }
  3144. c = 0200;
  3145. SHA1Update(context, &c, 1);
  3146. while ((context->count[0] & 504) != 448) {
  3147. c = 0000;
  3148. SHA1Update(context, &c, 1);
  3149. }
  3150. SHA1Update(context, finalcount, 8);
  3151. for (i = 0; i < 20; i++) {
  3152. digest[i] = (unsigned char)
  3153. ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
  3154. }
  3155. memset(context, '\0', sizeof(*context));
  3156. memset(&finalcount, '\0', sizeof(finalcount));
  3157. }
  3158. // END OF SHA1 CODE
  3159. static void base64_encode(const unsigned char *src, int src_len, char *dst) {
  3160. static const char *b64 =
  3161. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3162. int i, j, a, b, c;
  3163. for (i = j = 0; i < src_len; i += 3) {
  3164. a = src[i];
  3165. b = i + 1 >= src_len ? 0 : src[i + 1];
  3166. c = i + 2 >= src_len ? 0 : src[i + 2];
  3167. dst[j++] = b64[a >> 2];
  3168. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3169. if (i + 1 < src_len) {
  3170. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3171. }
  3172. if (i + 2 < src_len) {
  3173. dst[j++] = b64[c & 63];
  3174. }
  3175. }
  3176. while (j % 4 != 0) {
  3177. dst[j++] = '=';
  3178. }
  3179. dst[j++] = '\0';
  3180. }
  3181. static void send_websocket_handshake(struct mg_connection *conn) {
  3182. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3183. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  3184. SHA1_CTX sha_ctx;
  3185. mg_snprintf(conn, buf, sizeof(buf), "%s%s",
  3186. mg_get_header(conn, "Sec-WebSocket-Key"), magic);
  3187. SHA1Init(&sha_ctx);
  3188. SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
  3189. SHA1Final((unsigned char *) sha, &sha_ctx);
  3190. base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
  3191. mg_printf(conn, "%s%s%s",
  3192. "HTTP/1.1 101 Switching Protocols\r\n"
  3193. "Upgrade: websocket\r\n"
  3194. "Connection: Upgrade\r\n"
  3195. "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
  3196. }
  3197. static void read_websocket(struct mg_connection *conn) {
  3198. unsigned char *mask, *buf = (unsigned char *) conn->buf + conn->request_len;
  3199. int n, len, mask_len, body_len, discard_len;
  3200. for (;;) {
  3201. if ((body_len = conn->data_len - conn->request_len) >= 2) {
  3202. len = buf[1] & 127;
  3203. mask_len = buf[1] & 128 ? 4 : 0;
  3204. if (len < 126) {
  3205. conn->content_len = 2 + mask_len + len;
  3206. mask = buf + 2;
  3207. } else if (len == 126 && body_len >= 4) {
  3208. conn->content_len = 2 + mask_len + ((((int) buf[2]) << 8) + buf[3]);
  3209. mask = buf + 4;
  3210. } else if (body_len >= 10) {
  3211. conn->content_len = 2 + mask_len +
  3212. (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) |
  3213. htonl(* (uint32_t *) &buf[6]);
  3214. mask = buf + 10;
  3215. }
  3216. }
  3217. if (conn->content_len > 0) {
  3218. if (call_user(conn, MG_WEBSOCKET_MESSAGE) != NULL) {
  3219. break; // Callback signalled to exit
  3220. }
  3221. discard_len = conn->content_len > body_len ?
  3222. body_len : (int) conn->content_len;
  3223. memmove(buf, buf + discard_len, conn->data_len - discard_len);
  3224. conn->data_len -= discard_len;
  3225. conn->content_len = conn->consumed_content = 0;
  3226. } else {
  3227. if (wait_until_socket_is_readable(conn) == 0) {
  3228. break;
  3229. }
  3230. n = pull(NULL, conn, conn->buf + conn->data_len,
  3231. conn->buf_size - conn->data_len);
  3232. if (n <= 0) {
  3233. break;
  3234. }
  3235. conn->data_len += n;
  3236. }
  3237. }
  3238. }
  3239. static void handle_websocket_request(struct mg_connection *conn) {
  3240. if (strcmp(mg_get_header(conn, "Sec-WebSocket-Version"), "13") != 0) {
  3241. send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required");
  3242. } else if (call_user(conn, MG_WEBSOCKET_CONNECT) != NULL) {
  3243. // Callback has returned non-NULL, do not proceed with handshake
  3244. } else {
  3245. send_websocket_handshake(conn);
  3246. call_user(conn, MG_WEBSOCKET_READY);
  3247. read_websocket(conn);
  3248. call_user(conn, MG_WEBSOCKET_CLOSE);
  3249. }
  3250. }
  3251. static int is_websocket_request(const struct mg_connection *conn) {
  3252. const char *host, *upgrade, *connection, *version, *key;
  3253. host = mg_get_header(conn, "Host");
  3254. upgrade = mg_get_header(conn, "Upgrade");
  3255. connection = mg_get_header(conn, "Connection");
  3256. key = mg_get_header(conn, "Sec-WebSocket-Key");
  3257. version = mg_get_header(conn, "Sec-WebSocket-Version");
  3258. return host != NULL && upgrade != NULL && connection != NULL &&
  3259. key != NULL && version != NULL &&
  3260. strstr(upgrade, "websocket") != NULL &&
  3261. strstr(connection, "Upgrade") != NULL;
  3262. }
  3263. #endif // !USE_WEBSOCKET
  3264. static int isbyte(int n) {
  3265. return n >= 0 && n <= 255;
  3266. }
  3267. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  3268. int n, a, b, c, d, slash = 32, len = 0;
  3269. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  3270. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  3271. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
  3272. slash >= 0 && slash < 33) {
  3273. len = n;
  3274. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
  3275. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  3276. }
  3277. return len;
  3278. }
  3279. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri) {
  3280. int throttle = 0;
  3281. struct vec vec, val;
  3282. uint32_t net, mask;
  3283. char mult;
  3284. double v;
  3285. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  3286. mult = ',';
  3287. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  3288. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) {
  3289. continue;
  3290. }
  3291. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1;
  3292. if (vec.len == 1 && vec.ptr[0] == '*') {
  3293. throttle = (int) v;
  3294. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  3295. if ((remote_ip & mask) == net) {
  3296. throttle = (int) v;
  3297. }
  3298. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  3299. throttle = (int) v;
  3300. }
  3301. }
  3302. return throttle;
  3303. }
  3304. static uint32_t get_remote_ip(const struct mg_connection *conn) {
  3305. return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);
  3306. }
  3307. #ifdef USE_LUA
  3308. #ifdef _WIN32
  3309. static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
  3310. int offset) {
  3311. HANDLE fh = (HANDLE) _get_osfhandle(fd);
  3312. HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
  3313. void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
  3314. CloseHandle(fh);
  3315. CloseHandle(mh);
  3316. return p;
  3317. }
  3318. #define munmap(x, y) UnmapViewOfFile(x)
  3319. #define MAP_FAILED NULL
  3320. #define PROT_READ 0
  3321. #else
  3322. #include <sys/mman.h>
  3323. #endif
  3324. static void lsp(struct mg_connection *conn, const char *p, int64_t len,
  3325. lua_State *L) {
  3326. int i, j, pos = 0;
  3327. for (i = 0; i < len; i++) {
  3328. if (p[i] == '<' && p[i + 1] == '?') {
  3329. for (j = i + 1; j < len ; j++) {
  3330. if (p[j] == '?' && p[j + 1] == '>') {
  3331. mg_write(conn, p + pos, i - pos);
  3332. if (luaL_loadbuffer(L, p + (i + 2), j - (i + 2), "") == LUA_OK) {
  3333. lua_pcall(L, 0, LUA_MULTRET, 0);
  3334. }
  3335. pos = j + 2;
  3336. i = pos - 1;
  3337. break;
  3338. }
  3339. }
  3340. }
  3341. }
  3342. if (i > pos) {
  3343. mg_write(conn, p + pos, i - pos);
  3344. }
  3345. }
  3346. static int lsp_mg_print(lua_State *L) {
  3347. int i, num_args;
  3348. const char *str;
  3349. size_t size;
  3350. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  3351. num_args = lua_gettop(L);
  3352. for (i = 1; i <= num_args; i++) {
  3353. if (lua_isstring(L, i)) {
  3354. str = lua_tolstring(L, i, &size);
  3355. mg_write(conn, str, size);
  3356. }
  3357. }
  3358. return 0;
  3359. }
  3360. static int lsp_mg_read(lua_State *L) {
  3361. struct mg_connection *conn = lua_touserdata(L, lua_upvalueindex(1));
  3362. char buf[1024];
  3363. int len = mg_read(conn, buf, sizeof(buf));
  3364. lua_settop(L, 0);
  3365. lua_pushlstring(L, buf, len);
  3366. return 1;
  3367. }
  3368. static void reg_string(struct lua_State *L, const char *name, const char *val) {
  3369. lua_pushstring(L, name);
  3370. lua_pushstring(L, val);
  3371. lua_rawset(L, -3);
  3372. }
  3373. static void reg_int(struct lua_State *L, const char *name, int val) {
  3374. lua_pushstring(L, name);
  3375. lua_pushinteger(L, val);
  3376. lua_rawset(L, -3);
  3377. }
  3378. static void prepare_lua_environment(struct mg_connection *conn, lua_State *L) {
  3379. const struct mg_request_info *ri = mg_get_request_info(conn);
  3380. extern void luaL_openlibs(lua_State *);
  3381. int i;
  3382. luaL_openlibs(L);
  3383. // Register "print" function which calls mg_write()
  3384. lua_pushlightuserdata(L, conn);
  3385. lua_pushcclosure(L, lsp_mg_print, 1);
  3386. lua_setglobal(L, "print");
  3387. // Register mg_read()
  3388. lua_pushlightuserdata(L, conn);
  3389. lua_pushcclosure(L, lsp_mg_read, 1);
  3390. lua_setglobal(L, "read");
  3391. // Export request_info
  3392. lua_newtable(L);
  3393. reg_string(L, "request_method", ri->request_method);
  3394. reg_string(L, "uri", ri->uri);
  3395. reg_string(L, "http_version", ri->http_version);
  3396. reg_string(L, "query_string", ri->query_string);
  3397. reg_int(L, "remote_ip", ri->remote_ip);
  3398. reg_int(L, "remote_port", ri->remote_port);
  3399. reg_int(L, "num_headers", ri->num_headers);
  3400. lua_pushstring(L, "http_headers");
  3401. lua_newtable(L);
  3402. for (i = 0; i < ri->num_headers; i++) {
  3403. reg_string(L, ri->http_headers[i].name, ri->http_headers[i].value);
  3404. }
  3405. lua_rawset(L, -3);
  3406. lua_setglobal(L, "request_info");
  3407. }
  3408. static void handle_lsp_request(struct mg_connection *conn, const char *path,
  3409. const struct mgstat *st) {
  3410. void *p = NULL;
  3411. FILE *fp = NULL;
  3412. lua_State *L = NULL;
  3413. if ((fp = fopen(path, "r")) == NULL) {
  3414. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  3415. } else if ((p = mmap(NULL, st->size, PROT_READ, 0,
  3416. fileno(fp), 0)) == MAP_FAILED) {
  3417. send_http_error(conn, 500, http_500_error, "%s", "x");
  3418. } else if ((L = luaL_newstate()) == NULL) {
  3419. send_http_error(conn, 500, http_500_error, "%s", "y");
  3420. } else {
  3421. mg_printf(conn, "%s", "HTTP/1.1 200 OK\r\n"
  3422. "Content-Type: text/html\r\nConnection: close\r\n\r\n");
  3423. prepare_lua_environment(conn, L);
  3424. lsp(conn, p, st->size, L);
  3425. }
  3426. if (L) lua_close(L);
  3427. if (p) munmap(p, st->size);
  3428. if (fp) fclose(fp);
  3429. }
  3430. #endif // USE_LUA
  3431. // This is the heart of the Mongoose's logic.
  3432. // This function is called when the request is read, parsed and validated,
  3433. // and Mongoose must decide what action to take: serve a file, or
  3434. // a directory, or call embedded function, etcetera.
  3435. static void handle_request(struct mg_connection *conn) {
  3436. struct mg_request_info *ri = &conn->request_info;
  3437. char path[PATH_MAX];
  3438. int stat_result, uri_len;
  3439. struct mgstat st;
  3440. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
  3441. *conn->request_info.query_string++ = '\0';
  3442. }
  3443. uri_len = (int) strlen(ri->uri);
  3444. url_decode(ri->uri, (size_t)uri_len, ri->uri, (size_t)(uri_len + 1), 0);
  3445. remove_double_dots_and_double_slashes(ri->uri);
  3446. stat_result = convert_uri_to_file_name(conn, path, sizeof(path), &st);
  3447. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  3448. get_remote_ip(conn), ri->uri);
  3449. DEBUG_TRACE(("%s", ri->uri));
  3450. if (!check_authorization(conn, path)) {
  3451. send_authorization_request(conn);
  3452. #if defined(USE_WEBSOCKET)
  3453. } else if (is_websocket_request(conn)) {
  3454. handle_websocket_request(conn);
  3455. #endif
  3456. } else if (call_user(conn, MG_NEW_REQUEST) != NULL) {
  3457. // Do nothing, callback has served the request
  3458. } else if (!strcmp(ri->request_method, "OPTIONS")) {
  3459. send_options(conn);
  3460. } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  3461. send_http_error(conn, 404, "Not Found", "Not Found");
  3462. } else if ((!strcmp(ri->request_method, "PUT") ||
  3463. !strcmp(ri->request_method, "DELETE")) &&
  3464. (conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ||
  3465. is_authorized_for_put(conn) != 1)) {
  3466. send_authorization_request(conn);
  3467. } else if (!strcmp(ri->request_method, "PUT")) {
  3468. put_file(conn, path);
  3469. } else if (!strcmp(ri->request_method, "DELETE")) {
  3470. if (mg_remove(path) == 0) {
  3471. send_http_error(conn, 200, "OK", "%s", "");
  3472. } else {
  3473. send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,
  3474. strerror(ERRNO));
  3475. }
  3476. } else if (stat_result != 0 || must_hide_file(conn, path)) {
  3477. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  3478. } else if (st.is_directory && ri->uri[uri_len - 1] != '/') {
  3479. (void) mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
  3480. "Location: %s/\r\n\r\n", ri->uri);
  3481. } else if (!strcmp(ri->request_method, "PROPFIND")) {
  3482. handle_propfind(conn, path, &st);
  3483. } else if (st.is_directory &&
  3484. !substitute_index_file(conn, path, sizeof(path), &st)) {
  3485. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {
  3486. handle_directory_request(conn, path);
  3487. } else {
  3488. send_http_error(conn, 403, "Directory Listing Denied",
  3489. "Directory listing denied");
  3490. }
  3491. #ifdef USE_LUA
  3492. } else if (match_prefix("**.lsp$", 7, path) > 0) {
  3493. handle_lsp_request(conn, path, &st);
  3494. #endif
  3495. #if !defined(NO_CGI)
  3496. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3497. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3498. path) > 0) {
  3499. if (strcmp(ri->request_method, "POST") &&
  3500. strcmp(ri->request_method, "GET")) {
  3501. send_http_error(conn, 501, "Not Implemented",
  3502. "Method %s is not implemented", ri->request_method);
  3503. } else {
  3504. handle_cgi_request(conn, path);
  3505. }
  3506. #endif // !NO_CGI
  3507. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  3508. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  3509. path) > 0) {
  3510. handle_ssi_file_request(conn, path);
  3511. } else if (is_not_modified(conn, &st)) {
  3512. send_http_error(conn, 304, "Not Modified", "%s", "");
  3513. } else {
  3514. handle_file_request(conn, path, &st);
  3515. }
  3516. }
  3517. static void close_all_listening_sockets(struct mg_context *ctx) {
  3518. struct socket *sp, *tmp;
  3519. for (sp = ctx->listening_sockets; sp != NULL; sp = tmp) {
  3520. tmp = sp->next;
  3521. (void) closesocket(sp->sock);
  3522. free(sp);
  3523. }
  3524. }
  3525. // Valid listening port specification is: [ip_address:]port[s]
  3526. // Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  3527. // TODO(lsm): add parsing of the IPv6 address
  3528. static int parse_port_string(const struct vec *vec, struct socket *so) {
  3529. int a, b, c, d, port, len;
  3530. // MacOS needs that. If we do not zero it, subsequent bind() will fail.
  3531. // Also, all-zeroes in the socket address means binding to all addresses
  3532. // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
  3533. memset(so, 0, sizeof(*so));
  3534. if (sscanf(vec->ptr, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &len) == 5) {
  3535. // Bind to a specific IPv4 address
  3536. so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
  3537. } else if (sscanf(vec->ptr, "%d%n", &port, &len) != 1 ||
  3538. len <= 0 ||
  3539. len > (int) vec->len ||
  3540. (vec->ptr[len] && vec->ptr[len] != 's' && vec->ptr[len] != ',')) {
  3541. return 0;
  3542. }
  3543. so->is_ssl = vec->ptr[len] == 's';
  3544. #if defined(USE_IPV6)
  3545. so->lsa.sin6.sin6_family = AF_INET6;
  3546. so->lsa.sin6.sin6_port = htons((uint16_t) port);
  3547. #else
  3548. so->lsa.sin.sin_family = AF_INET;
  3549. so->lsa.sin.sin_port = htons((uint16_t) port);
  3550. #endif
  3551. return 1;
  3552. }
  3553. static int set_ports_option(struct mg_context *ctx) {
  3554. const char *list = ctx->config[LISTENING_PORTS];
  3555. int on = 1, success = 1;
  3556. SOCKET sock;
  3557. struct vec vec;
  3558. struct socket so, *listener;
  3559. while (success && (list = next_option(list, &vec, NULL)) != NULL) {
  3560. if (!parse_port_string(&vec, &so)) {
  3561. cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",
  3562. __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|p]");
  3563. success = 0;
  3564. } else if (so.is_ssl &&
  3565. (ctx->ssl_ctx == NULL || ctx->config[SSL_CERTIFICATE] == NULL)) {
  3566. cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");
  3567. success = 0;
  3568. } else if ((sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
  3569. INVALID_SOCKET ||
  3570. // On Windows, SO_REUSEADDR is recommended only for
  3571. // broadcast UDP sockets
  3572. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char *) &on,
  3573. sizeof(on)) != 0 ||
  3574. // Set TCP keep-alive. This is needed because if HTTP-level
  3575. // keep-alive is enabled, and client resets the connection,
  3576. // server won't get TCP FIN or RST and will keep the connection
  3577. // open forever. With TCP keep-alive, next keep-alive
  3578. // handshake will figure out that the client is down and
  3579. // will close the server end.
  3580. // Thanks to Igor Klopov who suggested the patch.
  3581. setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *) &on,
  3582. sizeof(on)) != 0 ||
  3583. bind(sock, &so.lsa.sa, sizeof(so.lsa)) != 0 ||
  3584. listen(sock, SOMAXCONN) != 0) {
  3585. closesocket(sock);
  3586. cry(fc(ctx), "%s: cannot bind to %.*s: %s", __func__,
  3587. (int) vec.len, vec.ptr, strerror(ERRNO));
  3588. success = 0;
  3589. } else if ((listener = (struct socket *)
  3590. calloc(1, sizeof(*listener))) == NULL) {
  3591. // NOTE(lsm): order is important: call cry before closesocket(),
  3592. // cause closesocket() alters the errno.
  3593. cry(fc(ctx), "%s: %s", __func__, strerror(ERRNO));
  3594. closesocket(sock);
  3595. success = 0;
  3596. } else {
  3597. *listener = so;
  3598. listener->sock = sock;
  3599. set_close_on_exec(listener->sock);
  3600. listener->next = ctx->listening_sockets;
  3601. ctx->listening_sockets = listener;
  3602. }
  3603. }
  3604. if (!success) {
  3605. close_all_listening_sockets(ctx);
  3606. }
  3607. return success;
  3608. }
  3609. static void log_header(const struct mg_connection *conn, const char *header,
  3610. FILE *fp) {
  3611. const char *header_value;
  3612. if ((header_value = mg_get_header(conn, header)) == NULL) {
  3613. (void) fprintf(fp, "%s", " -");
  3614. } else {
  3615. (void) fprintf(fp, " \"%s\"", header_value);
  3616. }
  3617. }
  3618. static void log_access(const struct mg_connection *conn) {
  3619. const struct mg_request_info *ri;
  3620. FILE *fp;
  3621. char date[64], src_addr[20];
  3622. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ? NULL :
  3623. mg_fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  3624. if (fp == NULL)
  3625. return;
  3626. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",
  3627. localtime(&conn->birth_time));
  3628. ri = &conn->request_info;
  3629. flockfile(fp);
  3630. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3631. fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
  3632. src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,
  3633. ri->request_method ? ri->request_method : "-",
  3634. ri->uri ? ri->uri : "-", ri->http_version,
  3635. conn->status_code, conn->num_bytes_sent);
  3636. log_header(conn, "Referer", fp);
  3637. log_header(conn, "User-Agent", fp);
  3638. fputc('\n', fp);
  3639. fflush(fp);
  3640. funlockfile(fp);
  3641. fclose(fp);
  3642. }
  3643. // Verify given socket address against the ACL.
  3644. // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  3645. static int check_acl(struct mg_context *ctx, uint32_t remote_ip) {
  3646. int allowed, flag;
  3647. uint32_t net, mask;
  3648. struct vec vec;
  3649. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  3650. // If any ACL is set, deny by default
  3651. allowed = list == NULL ? '+' : '-';
  3652. while ((list = next_option(list, &vec, NULL)) != NULL) {
  3653. flag = vec.ptr[0];
  3654. if ((flag != '+' && flag != '-') ||
  3655. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  3656. cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  3657. return -1;
  3658. }
  3659. if (net == (remote_ip & mask)) {
  3660. allowed = flag;
  3661. }
  3662. }
  3663. return allowed == '+';
  3664. }
  3665. static void add_to_set(SOCKET fd, fd_set *set, int *max_fd) {
  3666. FD_SET(fd, set);
  3667. if (fd > (SOCKET) *max_fd) {
  3668. *max_fd = (int) fd;
  3669. }
  3670. }
  3671. #if !defined(_WIN32)
  3672. static int set_uid_option(struct mg_context *ctx) {
  3673. struct passwd *pw;
  3674. const char *uid = ctx->config[RUN_AS_USER];
  3675. int success = 0;
  3676. if (uid == NULL) {
  3677. success = 1;
  3678. } else {
  3679. if ((pw = getpwnam(uid)) == NULL) {
  3680. cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  3681. } else if (setgid(pw->pw_gid) == -1) {
  3682. cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));
  3683. } else if (setuid(pw->pw_uid) == -1) {
  3684. cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));
  3685. } else {
  3686. success = 1;
  3687. }
  3688. }
  3689. return success;
  3690. }
  3691. #endif // !_WIN32
  3692. #if !defined(NO_SSL)
  3693. static pthread_mutex_t *ssl_mutexes;
  3694. // Return OpenSSL error message
  3695. static const char *ssl_error(void) {
  3696. unsigned long err;
  3697. err = ERR_get_error();
  3698. return err == 0 ? "" : ERR_error_string(err, NULL);
  3699. }
  3700. static void ssl_locking_callback(int mode, int mutex_num, const char *file,
  3701. int line) {
  3702. line = 0; // Unused
  3703. file = NULL; // Unused
  3704. if (mode & CRYPTO_LOCK) {
  3705. (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  3706. } else {
  3707. (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  3708. }
  3709. }
  3710. static unsigned long ssl_id_callback(void) {
  3711. return (unsigned long) pthread_self();
  3712. }
  3713. #if !defined(NO_SSL_DL)
  3714. static int load_dll(struct mg_context *ctx, const char *dll_name,
  3715. struct ssl_func *sw) {
  3716. union {void *p; void (*fp)(void);} u;
  3717. void *dll_handle;
  3718. struct ssl_func *fp;
  3719. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  3720. cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  3721. return 0;
  3722. }
  3723. for (fp = sw; fp->name != NULL; fp++) {
  3724. #ifdef _WIN32
  3725. // GetProcAddress() returns pointer to function
  3726. u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
  3727. #else
  3728. // dlsym() on UNIX returns void *. ISO C forbids casts of data pointers to
  3729. // function pointers. We need to use a union to make a cast.
  3730. u.p = dlsym(dll_handle, fp->name);
  3731. #endif // _WIN32
  3732. if (u.fp == NULL) {
  3733. cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);
  3734. return 0;
  3735. } else {
  3736. fp->ptr = u.fp;
  3737. }
  3738. }
  3739. return 1;
  3740. }
  3741. #endif // NO_SSL_DL
  3742. // Dynamically load SSL library. Set up ctx->ssl_ctx pointer.
  3743. static int set_ssl_option(struct mg_context *ctx) {
  3744. int i, size;
  3745. const char *pem;
  3746. // If PEM file is not specified, skip SSL initialization.
  3747. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL) {
  3748. return 1;
  3749. }
  3750. #if !defined(NO_SSL_DL)
  3751. if (!load_dll(ctx, SSL_LIB, ssl_sw) ||
  3752. !load_dll(ctx, CRYPTO_LIB, crypto_sw)) {
  3753. return 0;
  3754. }
  3755. #endif // NO_SSL_DL
  3756. // Initialize SSL crap
  3757. SSL_library_init();
  3758. SSL_load_error_strings();
  3759. if ((ctx->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
  3760. cry(fc(ctx), "SSL_CTX_new (client) error: %s", ssl_error());
  3761. }
  3762. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  3763. cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  3764. return 0;
  3765. }
  3766. // If user callback returned non-NULL, that means that user callback has
  3767. // set up certificate itself. In this case, skip sertificate setting.
  3768. if (call_user(fc(ctx), MG_INIT_SSL) == NULL &&
  3769. (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, SSL_FILETYPE_PEM) == 0 ||
  3770. SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, SSL_FILETYPE_PEM) == 0)) {
  3771. cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error());
  3772. return 0;
  3773. }
  3774. if (pem != NULL) {
  3775. (void) SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  3776. }
  3777. // Initialize locking callbacks, needed for thread safety.
  3778. // http://www.openssl.org/support/faq.html#PROG1
  3779. size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
  3780. if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) {
  3781. cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
  3782. return 0;
  3783. }
  3784. for (i = 0; i < CRYPTO_num_locks(); i++) {
  3785. pthread_mutex_init(&ssl_mutexes[i], NULL);
  3786. }
  3787. CRYPTO_set_locking_callback(&ssl_locking_callback);
  3788. CRYPTO_set_id_callback(&ssl_id_callback);
  3789. return 1;
  3790. }
  3791. static void uninitialize_ssl(struct mg_context *ctx) {
  3792. int i;
  3793. if (ctx->ssl_ctx != NULL) {
  3794. CRYPTO_set_locking_callback(NULL);
  3795. for (i = 0; i < CRYPTO_num_locks(); i++) {
  3796. pthread_mutex_destroy(&ssl_mutexes[i]);
  3797. }
  3798. CRYPTO_set_locking_callback(NULL);
  3799. CRYPTO_set_id_callback(NULL);
  3800. }
  3801. }
  3802. #endif // !NO_SSL
  3803. static int set_gpass_option(struct mg_context *ctx) {
  3804. struct mgstat mgstat;
  3805. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  3806. return path == NULL || mg_stat(path, &mgstat) == 0;
  3807. }
  3808. static int set_acl_option(struct mg_context *ctx) {
  3809. return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;
  3810. }
  3811. static void reset_per_request_attributes(struct mg_connection *conn) {
  3812. conn->path_info = conn->log_message = NULL;
  3813. conn->num_bytes_sent = conn->consumed_content = 0;
  3814. conn->status_code = -1;
  3815. conn->must_close = conn->request_len = conn->throttle = 0;
  3816. }
  3817. static void close_socket_gracefully(struct mg_connection *conn) {
  3818. char buf[MG_BUF_LEN];
  3819. struct linger linger;
  3820. int n, sock = conn->client.sock;
  3821. // Set linger option to avoid socket hanging out after close. This prevent
  3822. // ephemeral port exhaust problem under high QPS.
  3823. linger.l_onoff = 1;
  3824. linger.l_linger = 1;
  3825. setsockopt(sock, SOL_SOCKET, SO_LINGER, (char *) &linger, sizeof(linger));
  3826. // Send FIN to the client
  3827. (void) shutdown(sock, SHUT_WR);
  3828. set_non_blocking_mode(sock);
  3829. // Read and discard pending incoming data. If we do not do that and close the
  3830. // socket, the data in the send buffer may be discarded. This
  3831. // behaviour is seen on Windows, when client keeps sending data
  3832. // when server decides to close the connection; then when client
  3833. // does recv() it gets no data back.
  3834. do {
  3835. n = pull(NULL, conn, buf, sizeof(buf));
  3836. } while (n > 0);
  3837. // Now we know that our FIN is ACK-ed, safe to close
  3838. (void) closesocket(sock);
  3839. }
  3840. static void close_connection(struct mg_connection *conn) {
  3841. if (conn->ssl) {
  3842. SSL_free(conn->ssl);
  3843. conn->ssl = NULL;
  3844. }
  3845. if (conn->client.sock != INVALID_SOCKET) {
  3846. close_socket_gracefully(conn);
  3847. }
  3848. }
  3849. void mg_close_connection(struct mg_connection *conn) {
  3850. close_connection(conn);
  3851. free(conn);
  3852. }
  3853. struct mg_connection *mg_connect(struct mg_context *ctx,
  3854. const char *host, int port, int use_ssl) {
  3855. struct mg_connection *newconn = NULL;
  3856. struct sockaddr_in sin;
  3857. struct hostent *he;
  3858. int sock;
  3859. if (use_ssl && (ctx == NULL || ctx->client_ssl_ctx == NULL)) {
  3860. cry(fc(ctx), "%s: SSL is not initialized", __func__);
  3861. } else if ((he = gethostbyname(host)) == NULL) {
  3862. cry(fc(ctx), "%s: gethostbyname(%s): %s", __func__, host, strerror(ERRNO));
  3863. } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
  3864. cry(fc(ctx), "%s: socket: %s", __func__, strerror(ERRNO));
  3865. } else {
  3866. sin.sin_family = AF_INET;
  3867. sin.sin_port = htons((uint16_t) port);
  3868. sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
  3869. if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
  3870. cry(fc(ctx), "%s: connect(%s:%d): %s", __func__, host, port,
  3871. strerror(ERRNO));
  3872. closesocket(sock);
  3873. } else if ((newconn = (struct mg_connection *)
  3874. calloc(1, sizeof(*newconn))) == NULL) {
  3875. cry(fc(ctx), "%s: calloc: %s", __func__, strerror(ERRNO));
  3876. closesocket(sock);
  3877. } else {
  3878. newconn->ctx = ctx;
  3879. newconn->client.sock = sock;
  3880. newconn->client.rsa.sin = sin;
  3881. newconn->client.is_ssl = use_ssl;
  3882. if (use_ssl) {
  3883. sslize(newconn, ctx->client_ssl_ctx, SSL_connect);
  3884. }
  3885. }
  3886. }
  3887. return newconn;
  3888. }
  3889. FILE *mg_fetch(struct mg_context *ctx, const char *url, const char *path,
  3890. char *buf, size_t buf_len, struct mg_request_info *ri) {
  3891. struct mg_connection *newconn;
  3892. int n, req_length, data_length, port;
  3893. char host[1025], proto[10], buf2[MG_BUF_LEN];
  3894. FILE *fp = NULL;
  3895. if (sscanf(url, "%9[htps]://%1024[^:]:%d/%n", proto, host, &port, &n) == 3) {
  3896. } else if (sscanf(url, "%9[htps]://%1024[^/]/%n", proto, host, &n) == 2) {
  3897. port = mg_strcasecmp(proto, "https") == 0 ? 443 : 80;
  3898. } else {
  3899. cry(fc(ctx), "%s: invalid URL: [%s]", __func__, url);
  3900. return NULL;
  3901. }
  3902. if ((newconn = mg_connect(ctx, host, port,
  3903. !strcmp(proto, "https"))) == NULL) {
  3904. cry(fc(ctx), "%s: mg_connect(%s): %s", __func__, url, strerror(ERRNO));
  3905. } else {
  3906. mg_printf(newconn, "GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n", url + n, host);
  3907. data_length = 0;
  3908. req_length = read_request(NULL, newconn, buf, buf_len, &data_length);
  3909. if (req_length <= 0) {
  3910. cry(fc(ctx), "%s(%s): invalid HTTP reply", __func__, url);
  3911. } else if (parse_http_response(buf, req_length, ri) <= 0) {
  3912. cry(fc(ctx), "%s(%s): cannot parse HTTP headers", __func__, url);
  3913. } else if ((fp = fopen(path, "w+b")) == NULL) {
  3914. cry(fc(ctx), "%s: fopen(%s): %s", __func__, path, strerror(ERRNO));
  3915. } else {
  3916. // Write chunk of data that may be in the user's buffer
  3917. data_length -= req_length;
  3918. if (data_length > 0 &&
  3919. fwrite(buf + req_length, 1, data_length, fp) != (size_t) data_length) {
  3920. cry(fc(ctx), "%s: fwrite(%s): %s", __func__, path, strerror(ERRNO));
  3921. fclose(fp);
  3922. fp = NULL;
  3923. }
  3924. // Read the rest of the response and write it to the file. Do not use
  3925. // mg_read() cause we didn't set newconn->content_len properly.
  3926. while (fp && (data_length = pull(0, newconn, buf2, sizeof(buf2))) > 0) {
  3927. if (fwrite(buf2, 1, data_length, fp) != (size_t) data_length) {
  3928. cry(fc(ctx), "%s: fwrite(%s): %s", __func__, path, strerror(ERRNO));
  3929. fclose(fp);
  3930. fp = NULL;
  3931. break;
  3932. }
  3933. }
  3934. }
  3935. mg_close_connection(newconn);
  3936. }
  3937. return fp;
  3938. }
  3939. static int is_valid_uri(const char *uri) {
  3940. // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  3941. // URI can be an asterisk (*) or should start with slash.
  3942. return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
  3943. }
  3944. static void process_new_connection(struct mg_connection *conn) {
  3945. struct mg_request_info *ri = &conn->request_info;
  3946. int keep_alive_enabled, discard_len;
  3947. const char *cl;
  3948. keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  3949. do {
  3950. reset_per_request_attributes(conn);
  3951. conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,
  3952. &conn->data_len);
  3953. assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  3954. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  3955. send_http_error(conn, 413, "Request Too Large", "%s", "");
  3956. return;
  3957. } if (conn->request_len <= 0) {
  3958. return; // Remote end closed the connection
  3959. }
  3960. if (parse_http_request(conn->buf, conn->buf_size, ri) <= 0 ||
  3961. !is_valid_uri(ri->uri)) {
  3962. // Do not put garbage in the access log, just send it back to the client
  3963. send_http_error(conn, 400, "Bad Request",
  3964. "Cannot parse HTTP request: [%.*s]", conn->data_len, conn->buf);
  3965. conn->must_close = 1;
  3966. } else if (strcmp(ri->http_version, "1.0") &&
  3967. strcmp(ri->http_version, "1.1")) {
  3968. // Request seems valid, but HTTP version is strange
  3969. send_http_error(conn, 505, "HTTP version not supported", "%s", "");
  3970. log_access(conn);
  3971. } else {
  3972. // Request is valid, handle it
  3973. if ((cl = get_header(ri, "Content-Length")) != NULL) {
  3974. conn->content_len = strtoll(cl, NULL, 10);
  3975. } else if (!mg_strcasecmp(ri->request_method, "POST") ||
  3976. !mg_strcasecmp(ri->request_method, "PUT")) {
  3977. conn->content_len = -1;
  3978. } else {
  3979. conn->content_len = 0;
  3980. }
  3981. conn->birth_time = time(NULL);
  3982. handle_request(conn);
  3983. call_user(conn, MG_REQUEST_COMPLETE);
  3984. log_access(conn);
  3985. }
  3986. if (ri->remote_user != NULL) {
  3987. free((void *) ri->remote_user);
  3988. }
  3989. // Discard all buffered data for this request
  3990. discard_len = conn->content_len >= 0 &&
  3991. conn->request_len + conn->content_len < (int64_t) conn->data_len ?
  3992. (int) (conn->request_len + conn->content_len) : conn->data_len;
  3993. memmove(conn->buf, conn->buf + discard_len, conn->data_len - discard_len);
  3994. conn->data_len -= discard_len;
  3995. assert(conn->data_len >= 0);
  3996. assert(conn->data_len <= conn->buf_size);
  3997. } while (conn->ctx->stop_flag == 0 &&
  3998. keep_alive_enabled &&
  3999. conn->content_len >= 0 &&
  4000. should_keep_alive(conn));
  4001. }
  4002. // Worker threads take accepted socket from the queue
  4003. static int consume_socket(struct mg_context *ctx, struct socket *sp) {
  4004. (void) pthread_mutex_lock(&ctx->mutex);
  4005. DEBUG_TRACE(("going idle"));
  4006. // If the queue is empty, wait. We're idle at this point.
  4007. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  4008. pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
  4009. }
  4010. // If we're stopping, sq_head may be equal to sq_tail.
  4011. if (ctx->sq_head > ctx->sq_tail) {
  4012. // Copy socket from the queue and increment tail
  4013. *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
  4014. ctx->sq_tail++;
  4015. DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));
  4016. // Wrap pointers if needed
  4017. while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
  4018. ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
  4019. ctx->sq_head -= ARRAY_SIZE(ctx->queue);
  4020. }
  4021. }
  4022. (void) pthread_cond_signal(&ctx->sq_empty);
  4023. (void) pthread_mutex_unlock(&ctx->mutex);
  4024. return !ctx->stop_flag;
  4025. }
  4026. static void worker_thread(struct mg_context *ctx) {
  4027. struct mg_connection *conn;
  4028. conn = (struct mg_connection *) calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  4029. if (conn == NULL) {
  4030. cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  4031. } else {
  4032. conn->buf_size = MAX_REQUEST_SIZE;
  4033. conn->buf = (char *) (conn + 1);
  4034. // Call consume_socket() even when ctx->stop_flag > 0, to let it signal
  4035. // sq_empty condvar to wake up the master waiting in produce_socket()
  4036. while (consume_socket(ctx, &conn->client)) {
  4037. conn->birth_time = time(NULL);
  4038. conn->ctx = ctx;
  4039. // Fill in IP, port info early so even if SSL setup below fails,
  4040. // error handler would have the corresponding info.
  4041. // Thanks to Johannes Winkelmann for the patch.
  4042. // TODO(lsm): Fix IPv6 case
  4043. conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);
  4044. memcpy(&conn->request_info.remote_ip,
  4045. &conn->client.rsa.sin.sin_addr.s_addr, 4);
  4046. conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
  4047. conn->request_info.is_ssl = conn->client.is_ssl;
  4048. if (!conn->client.is_ssl ||
  4049. (conn->client.is_ssl &&
  4050. sslize(conn, conn->ctx->ssl_ctx, SSL_accept))) {
  4051. process_new_connection(conn);
  4052. }
  4053. close_connection(conn);
  4054. }
  4055. free(conn);
  4056. }
  4057. // Signal master that we're done with connection and exiting
  4058. (void) pthread_mutex_lock(&ctx->mutex);
  4059. ctx->num_threads--;
  4060. (void) pthread_cond_signal(&ctx->cond);
  4061. assert(ctx->num_threads >= 0);
  4062. (void) pthread_mutex_unlock(&ctx->mutex);
  4063. DEBUG_TRACE(("exiting"));
  4064. }
  4065. // Master thread adds accepted socket to a queue
  4066. static void produce_socket(struct mg_context *ctx, const struct socket *sp) {
  4067. (void) pthread_mutex_lock(&ctx->mutex);
  4068. // If the queue is full, wait
  4069. while (ctx->stop_flag == 0 &&
  4070. ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {
  4071. (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
  4072. }
  4073. if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {
  4074. // Copy socket to the queue and increment head
  4075. ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
  4076. ctx->sq_head++;
  4077. DEBUG_TRACE(("queued socket %d", sp->sock));
  4078. }
  4079. (void) pthread_cond_signal(&ctx->sq_full);
  4080. (void) pthread_mutex_unlock(&ctx->mutex);
  4081. }
  4082. static void accept_new_connection(const struct socket *listener,
  4083. struct mg_context *ctx) {
  4084. struct socket accepted;
  4085. char src_addr[20];
  4086. socklen_t len;
  4087. int allowed;
  4088. len = sizeof(accepted.rsa);
  4089. accepted.lsa = listener->lsa;
  4090. accepted.sock = accept(listener->sock, &accepted.rsa.sa, &len);
  4091. if (accepted.sock != INVALID_SOCKET) {
  4092. allowed = check_acl(ctx, ntohl(* (uint32_t *) &accepted.rsa.sin.sin_addr));
  4093. if (allowed) {
  4094. // Put accepted socket structure into the queue
  4095. DEBUG_TRACE(("accepted socket %d", accepted.sock));
  4096. accepted.is_ssl = listener->is_ssl;
  4097. produce_socket(ctx, &accepted);
  4098. } else {
  4099. sockaddr_to_string(src_addr, sizeof(src_addr), &accepted.rsa);
  4100. cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  4101. (void) closesocket(accepted.sock);
  4102. }
  4103. }
  4104. }
  4105. static void master_thread(struct mg_context *ctx) {
  4106. fd_set read_set;
  4107. struct timeval tv;
  4108. struct socket *sp;
  4109. int max_fd;
  4110. // Increase priority of the master thread
  4111. #if defined(_WIN32)
  4112. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  4113. #endif
  4114. #if defined(ISSUE_317)
  4115. struct sched_param sched_param;
  4116. sched_param.sched_priority = sched_get_priority_max(SCHED_RR);
  4117. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  4118. #endif
  4119. while (ctx->stop_flag == 0) {
  4120. FD_ZERO(&read_set);
  4121. max_fd = -1;
  4122. // Add listening sockets to the read set
  4123. for (sp = ctx->listening_sockets; sp != NULL; sp = sp->next) {
  4124. add_to_set(sp->sock, &read_set, &max_fd);
  4125. }
  4126. tv.tv_sec = 0;
  4127. tv.tv_usec = 200 * 1000;
  4128. if (select(max_fd + 1, &read_set, NULL, NULL, &tv) < 0) {
  4129. #ifdef _WIN32
  4130. // On windows, if read_set and write_set are empty,
  4131. // select() returns "Invalid parameter" error
  4132. // (at least on my Windows XP Pro). So in this case, we sleep here.
  4133. mg_sleep(1000);
  4134. #endif // _WIN32
  4135. } else {
  4136. for (sp = ctx->listening_sockets; sp != NULL; sp = sp->next) {
  4137. if (ctx->stop_flag == 0 && FD_ISSET(sp->sock, &read_set)) {
  4138. accept_new_connection(sp, ctx);
  4139. }
  4140. }
  4141. }
  4142. }
  4143. DEBUG_TRACE(("stopping workers"));
  4144. // Stop signal received: somebody called mg_stop. Quit.
  4145. close_all_listening_sockets(ctx);
  4146. // Wakeup workers that are waiting for connections to handle.
  4147. pthread_cond_broadcast(&ctx->sq_full);
  4148. // Wait until all threads finish
  4149. (void) pthread_mutex_lock(&ctx->mutex);
  4150. while (ctx->num_threads > 0) {
  4151. (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
  4152. }
  4153. (void) pthread_mutex_unlock(&ctx->mutex);
  4154. // All threads exited, no sync is needed. Destroy mutex and condvars
  4155. (void) pthread_mutex_destroy(&ctx->mutex);
  4156. (void) pthread_cond_destroy(&ctx->cond);
  4157. (void) pthread_cond_destroy(&ctx->sq_empty);
  4158. (void) pthread_cond_destroy(&ctx->sq_full);
  4159. #if !defined(NO_SSL)
  4160. uninitialize_ssl(ctx);
  4161. #endif
  4162. DEBUG_TRACE(("exiting"));
  4163. // Signal mg_stop() that we're done.
  4164. // WARNING: This must be the very last thing this
  4165. // thread does, as ctx becomes invalid after this line.
  4166. ctx->stop_flag = 2;
  4167. }
  4168. static void free_context(struct mg_context *ctx) {
  4169. int i;
  4170. // Deallocate config parameters
  4171. for (i = 0; i < NUM_OPTIONS; i++) {
  4172. if (ctx->config[i] != NULL)
  4173. free(ctx->config[i]);
  4174. }
  4175. // Deallocate SSL context
  4176. if (ctx->ssl_ctx != NULL) {
  4177. SSL_CTX_free(ctx->ssl_ctx);
  4178. }
  4179. if (ctx->client_ssl_ctx != NULL) {
  4180. SSL_CTX_free(ctx->client_ssl_ctx);
  4181. }
  4182. #ifndef NO_SSL
  4183. if (ssl_mutexes != NULL) {
  4184. free(ssl_mutexes);
  4185. ssl_mutexes = NULL;
  4186. }
  4187. #endif // !NO_SSL
  4188. // Deallocate context itself
  4189. free(ctx);
  4190. }
  4191. void mg_stop(struct mg_context *ctx) {
  4192. ctx->stop_flag = 1;
  4193. // Wait until mg_fini() stops
  4194. while (ctx->stop_flag != 2) {
  4195. (void) mg_sleep(10);
  4196. }
  4197. free_context(ctx);
  4198. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  4199. (void) WSACleanup();
  4200. #endif // _WIN32
  4201. }
  4202. struct mg_context *mg_start(mg_callback_t user_callback, void *user_data,
  4203. const char **options) {
  4204. struct mg_context *ctx;
  4205. const char *name, *value, *default_value;
  4206. int i;
  4207. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  4208. WSADATA data;
  4209. WSAStartup(MAKEWORD(2,2), &data);
  4210. InitializeCriticalSection(&global_log_file_lock);
  4211. #endif // _WIN32
  4212. // Allocate context and initialize reasonable general case defaults.
  4213. // TODO(lsm): do proper error handling here.
  4214. if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) {
  4215. return NULL;
  4216. }
  4217. ctx->user_callback = user_callback;
  4218. ctx->user_data = user_data;
  4219. while (options && (name = *options++) != NULL) {
  4220. if ((i = get_option_index(name)) == -1) {
  4221. cry(fc(ctx), "Invalid option: %s", name);
  4222. free_context(ctx);
  4223. return NULL;
  4224. } else if ((value = *options++) == NULL) {
  4225. cry(fc(ctx), "%s: option value cannot be NULL", name);
  4226. free_context(ctx);
  4227. return NULL;
  4228. }
  4229. if (ctx->config[i] != NULL) {
  4230. cry(fc(ctx), "warning: %s: duplicate option", name);
  4231. }
  4232. ctx->config[i] = mg_strdup(value);
  4233. DEBUG_TRACE(("[%s] -> [%s]", name, value));
  4234. }
  4235. // Set default value if needed
  4236. for (i = 0; config_options[i * ENTRIES_PER_CONFIG_OPTION] != NULL; i++) {
  4237. default_value = config_options[i * ENTRIES_PER_CONFIG_OPTION + 2];
  4238. if (ctx->config[i] == NULL && default_value != NULL) {
  4239. ctx->config[i] = mg_strdup(default_value);
  4240. DEBUG_TRACE(("Setting default: [%s] -> [%s]",
  4241. config_options[i * ENTRIES_PER_CONFIG_OPTION + 1],
  4242. default_value));
  4243. }
  4244. }
  4245. // NOTE(lsm): order is important here. SSL certificates must
  4246. // be initialized before listening ports. UID must be set last.
  4247. if (!set_gpass_option(ctx) ||
  4248. #if !defined(NO_SSL)
  4249. !set_ssl_option(ctx) ||
  4250. #endif
  4251. !set_ports_option(ctx) ||
  4252. #if !defined(_WIN32)
  4253. !set_uid_option(ctx) ||
  4254. #endif
  4255. !set_acl_option(ctx)) {
  4256. free_context(ctx);
  4257. return NULL;
  4258. }
  4259. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  4260. // Ignore SIGPIPE signal, so if browser cancels the request, it
  4261. // won't kill the whole process.
  4262. (void) signal(SIGPIPE, SIG_IGN);
  4263. // Also ignoring SIGCHLD to let the OS to reap zombies properly.
  4264. (void) signal(SIGCHLD, SIG_IGN);
  4265. #endif // !_WIN32
  4266. (void) pthread_mutex_init(&ctx->mutex, NULL);
  4267. (void) pthread_cond_init(&ctx->cond, NULL);
  4268. (void) pthread_cond_init(&ctx->sq_empty, NULL);
  4269. (void) pthread_cond_init(&ctx->sq_full, NULL);
  4270. // Start master (listening) thread
  4271. mg_start_thread((mg_thread_func_t) master_thread, ctx);
  4272. // Start worker threads
  4273. for (i = 0; i < atoi(ctx->config[NUM_THREADS]); i++) {
  4274. if (mg_start_thread((mg_thread_func_t) worker_thread, ctx) != 0) {
  4275. cry(fc(ctx), "Cannot start worker thread: %d", ERRNO);
  4276. } else {
  4277. ctx->num_threads++;
  4278. }
  4279. }
  4280. return ctx;
  4281. }