mongoose.c 124 KB

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