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 MAX_LISTENING_SOCKETS 10
  180. #define MAX_CALLBACKS 20
  181. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  182. #define DEBUG_MGS_PREFIX "*** Mongoose debug *** "
  183. #if defined(DEBUG)
  184. #define DEBUG_TRACE(x) do {printf x; putchar('\n'); fflush(stdout);} while (0)
  185. #else
  186. #define DEBUG_TRACE(x)
  187. #endif /* DEBUG */
  188. /*
  189. * Darwin prior to 7.0 and Win32 do not have socklen_t
  190. */
  191. #ifdef NO_SOCKLEN_T
  192. typedef int socklen_t;
  193. #endif /* NO_SOCKLEN_T */
  194. #if !defined(FALSE)
  195. enum {FALSE, TRUE};
  196. #endif /* !FALSE */
  197. typedef int bool_t;
  198. typedef void * (*mg_thread_func_t)(void *);
  199. static const char *http_500_error = "Internal Server Error";
  200. /*
  201. * Snatched from OpenSSL includes. I put the prototypes here to be independent
  202. * from the OpenSSL source installation. Having this, mongoose + SSL can be
  203. * built on any system with binary SSL libraries installed.
  204. */
  205. typedef struct ssl_st SSL;
  206. typedef struct ssl_method_st SSL_METHOD;
  207. typedef struct ssl_ctx_st SSL_CTX;
  208. #define SSL_ERROR_WANT_READ 2
  209. #define SSL_ERROR_WANT_WRITE 3
  210. #define SSL_FILETYPE_PEM 1
  211. #define CRYPTO_LOCK 1
  212. /*
  213. * Dynamically loaded SSL functionality
  214. */
  215. struct ssl_func {
  216. const char *name; /* SSL function name */
  217. void (*ptr)(void); /* Function pointer */
  218. };
  219. #define SSL_free(x) (* (void (*)(SSL *)) ssl_sw[0].ptr)(x)
  220. #define SSL_accept(x) (* (int (*)(SSL *)) ssl_sw[1].ptr)(x)
  221. #define SSL_connect(x) (* (int (*)(SSL *)) ssl_sw[2].ptr)(x)
  222. #define SSL_read(x,y,z) (* (int (*)(SSL *, void *, int)) \
  223. ssl_sw[3].ptr)((x),(y),(z))
  224. #define SSL_write(x,y,z) (* (int (*)(SSL *, const void *,int)) \
  225. ssl_sw[4].ptr)((x), (y), (z))
  226. #define SSL_get_error(x,y)(* (int (*)(SSL *, int)) ssl_sw[5])((x), (y))
  227. #define SSL_set_fd(x,y) (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)((x), (y))
  228. #define SSL_new(x) (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)(x)
  229. #define SSL_CTX_new(x) (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)(x)
  230. #define SSLv23_server_method() (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)()
  231. #define SSL_library_init() (* (int (*)(void)) ssl_sw[10].ptr)()
  232. #define SSL_CTX_use_PrivateKey_file(x,y,z) (* (int (*)(SSL_CTX *, \
  233. const char *, int)) ssl_sw[11].ptr)((x), (y), (z))
  234. #define SSL_CTX_use_certificate_file(x,y,z) (* (int (*)(SSL_CTX *, \
  235. const char *, int)) ssl_sw[12].ptr)((x), (y), (z))
  236. #define SSL_CTX_set_default_passwd_cb(x,y) \
  237. (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)((x),(y))
  238. #define SSL_CTX_free(x) (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)(x)
  239. #define ERR_get_error() (* (unsigned long (*)(void)) ssl_sw[15].ptr)()
  240. #define ERR_error_string(x, y) (* (char * (*)(unsigned long, char *)) ssl_sw[16].ptr)((x), (y))
  241. #define SSL_load_error_strings() (* (void (*)(void)) ssl_sw[17].ptr)()
  242. #define CRYPTO_num_locks() (* (int (*)(void)) crypto_sw[0].ptr)()
  243. #define CRYPTO_set_locking_callback(x) \
  244. (* (void (*)(void (*)(int, int, const char *, int))) \
  245. crypto_sw[1].ptr)(x)
  246. #define CRYPTO_set_id_callback(x) \
  247. (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)(x)
  248. /*
  249. * set_ssl_option() function updates this array.
  250. * It loads SSL library dynamically and changes NULLs to the actual addresses
  251. * of respective functions. The macros above (like SSL_connect()) are really
  252. * just calling these functions indirectly via the pointer.
  253. */
  254. static struct ssl_func ssl_sw[] = {
  255. {"SSL_free", NULL},
  256. {"SSL_accept", NULL},
  257. {"SSL_connect", NULL},
  258. {"SSL_read", NULL},
  259. {"SSL_write", NULL},
  260. {"SSL_get_error", NULL},
  261. {"SSL_set_fd", NULL},
  262. {"SSL_new", NULL},
  263. {"SSL_CTX_new", NULL},
  264. {"SSLv23_server_method", NULL},
  265. {"SSL_library_init", NULL},
  266. {"SSL_CTX_use_PrivateKey_file", NULL},
  267. {"SSL_CTX_use_certificate_file",NULL},
  268. {"SSL_CTX_set_default_passwd_cb",NULL},
  269. {"SSL_CTX_free", NULL},
  270. {"ERR_get_error", NULL},
  271. {"ERR_error_string", NULL},
  272. {"SSL_load_error_strings", NULL},
  273. {NULL, NULL}
  274. };
  275. /*
  276. * Similar array as ssl_sw. These functions could be located in different lib.
  277. */
  278. static struct ssl_func crypto_sw[] = {
  279. {"CRYPTO_num_locks", NULL},
  280. {"CRYPTO_set_locking_callback", NULL},
  281. {"CRYPTO_set_id_callback", NULL},
  282. {NULL, NULL}
  283. };
  284. /*
  285. * Month names
  286. */
  287. static const char *month_names[] = {
  288. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  289. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  290. };
  291. /*
  292. * Unified socket address. For IPv6 support, add IPv6 address structure
  293. * in the union u.
  294. */
  295. struct usa {
  296. socklen_t len;
  297. union {
  298. struct sockaddr sa;
  299. struct sockaddr_in sin;
  300. } u;
  301. };
  302. /*
  303. * Specifies a string (chunk of memory).
  304. * Used to traverse comma separated lists of options.
  305. */
  306. struct vec {
  307. const char *ptr;
  308. size_t len;
  309. };
  310. /*
  311. * Structure used by mg_stat() function. Uses 64 bit file length.
  312. */
  313. struct mgstat {
  314. bool_t is_directory; /* Directory marker */
  315. int64_t size; /* File size */
  316. time_t mtime; /* Modification time */
  317. };
  318. struct mg_option {
  319. const char *name;
  320. const char *description;
  321. const char *default_value;
  322. int index;
  323. enum mg_error_t (*setter)(struct mg_context *, const char *);
  324. };
  325. /*
  326. * Numeric indexes for the option values in context, ctx->options
  327. */
  328. enum mg_option_index {
  329. OPT_ROOT, OPT_INDEX_FILES, OPT_PORTS, OPT_DIR_LIST, OPT_CGI_EXTENSIONS,
  330. OPT_CGI_INTERPRETER, OPT_CGI_ENV, OPT_SSI_EXTENSIONS, OPT_AUTH_DOMAIN,
  331. OPT_AUTH_GPASSWD, OPT_AUTH_PUT, OPT_ACCESS_LOG, OPT_ERROR_LOG,
  332. OPT_SSL_CERTIFICATE, OPT_ALIASES, OPT_ACL, OPT_UID, OPT_PROTECT,
  333. OPT_SERVICE, OPT_HIDE, OPT_ADMIN_URI, OPT_MAX_THREADS, OPT_IDLE_TIME,
  334. OPT_MIME_TYPES,
  335. NUM_OPTIONS
  336. };
  337. /*
  338. * Structure used to describe listening socket, or socket which was
  339. * accept()-ed by the master thread and queued for future handling
  340. * by the worker thread.
  341. */
  342. struct socket {
  343. SOCKET sock; /* Listening socket */
  344. struct usa lsa; /* Local socket address */
  345. struct usa rsa; /* Remote socket address */
  346. bool_t is_ssl; /* Is socket SSL-ed */
  347. };
  348. /*
  349. * Mongoose context
  350. */
  351. struct mg_context {
  352. int stop_flag; /* Should we stop event loop */
  353. SSL_CTX *ssl_ctx; /* SSL context */
  354. struct socket listeners[MAX_LISTENING_SOCKETS];
  355. int num_listeners;
  356. char *options[NUM_OPTIONS];
  357. mg_callback_t callbacks[NUM_EVENTS];
  358. int num_threads; /* Number of threads */
  359. int num_idle; /* Number of idle threads */
  360. pthread_mutex_t mutex; /* Protects (max|num)_threads */
  361. pthread_rwlock_t rwlock; /* Protects options, callbacks */
  362. pthread_cond_t thr_cond; /* Condvar for thread sync */
  363. struct socket queue[20]; /* Accepted sockets */
  364. int sq_head; /* Head of the socket queue */
  365. int sq_tail; /* Tail of the socket queue */
  366. pthread_cond_t empty_cond; /* Socket queue empty condvar */
  367. pthread_cond_t full_cond; /* Socket queue full condvar */
  368. };
  369. /*
  370. * Client connection.
  371. */
  372. struct mg_connection {
  373. struct mg_request_info request_info;
  374. struct mg_context *ctx; /* Mongoose context we belong to*/
  375. SSL *ssl; /* SSL descriptor */
  376. struct socket client; /* Connected client */
  377. time_t birth_time; /* Time connection was accepted */
  378. bool_t free_post_data; /* post_data was malloc-ed */
  379. int64_t num_bytes_sent; /* Total bytes sent to client */
  380. };
  381. /*
  382. * Print error message to the opened error log stream.
  383. */
  384. static void
  385. cry(struct mg_connection *conn, const char *fmt, ...)
  386. {
  387. char buf[BUFSIZ];
  388. mg_callback_t log_callback;
  389. enum mg_error_t processed = MG_ERROR;
  390. va_list ap;
  391. FILE *fp;
  392. time_t timestamp;
  393. va_start(ap, fmt);
  394. (void) vsnprintf(buf, sizeof(buf), fmt, ap);
  395. va_end(ap);
  396. /*
  397. * Do not lock when getting the callback value, here and below.
  398. * I suppose this is fine, since function cannot disappear in the
  399. * same way string option can.
  400. */
  401. log_callback = conn->ctx->callbacks[MG_EVENT_LOG];
  402. conn->request_info.log_message = buf;
  403. if (log_callback != NULL)
  404. processed = log_callback(conn, &conn->request_info);
  405. if (processed == MG_ERROR) {
  406. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  407. fp = conn->ctx->options[OPT_ERROR_LOG] == NULL ? stderr :
  408. mg_fopen(conn->ctx->options[OPT_ERROR_LOG], "a+");
  409. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  410. if (fp != NULL) {
  411. flockfile(fp);
  412. timestamp = time(NULL);
  413. (void) fprintf(fp,
  414. "[%010lu] [error] [client %s] ",
  415. (unsigned long) timestamp,
  416. inet_ntoa(conn->client.rsa.u.sin.sin_addr));
  417. if (conn->request_info.request_method != NULL)
  418. (void) fprintf(fp, "%s %s: ",
  419. conn->request_info.request_method,
  420. conn->request_info.uri);
  421. (void) fprintf(fp, "%s", buf);
  422. fputc('\n', fp);
  423. funlockfile(fp);
  424. // (void) fclose(fp);
  425. }
  426. }
  427. conn->request_info.log_message = NULL;
  428. }
  429. /*
  430. * Print OpenSSL error messages, if any, to the error log.
  431. */
  432. static void ssl_cry(struct mg_connection *conn, const char *fmt, ...) {
  433. char buf[BUFSIZ];
  434. va_list ap;
  435. /* first just log the mongoose-level error message passed in via fmt, etc. */
  436. va_start(ap, fmt);
  437. (void) vsnprintf(buf, sizeof(buf), fmt, ap);
  438. va_end(ap);
  439. cry(conn, buf);
  440. /* then loop through any unlogged OpenSSL errors */
  441. unsigned long err;
  442. while ((err = ERR_get_error()) != 0) {
  443. cry(conn, " OpenSSL: %s", ERR_error_string(err, NULL));
  444. }
  445. }
  446. /*
  447. * Return fake connection structure. Used for logging, if connection
  448. * is not applicable at the moment of logging.
  449. */
  450. static struct mg_connection *
  451. fc(struct mg_context *ctx)
  452. {
  453. static struct mg_connection fake_connection;
  454. fake_connection.ctx = ctx;
  455. return (&fake_connection);
  456. }
  457. const char *
  458. mg_version(void)
  459. {
  460. return ("\"" MONGOOSE_VERSION ", $Rev: 517 $\"");
  461. }
  462. static void
  463. mg_strlcpy(register char *dst, register const char *src, size_t n)
  464. {
  465. for (; *src != '\0' && n > 1; n--)
  466. *dst++ = *src++;
  467. *dst = '\0';
  468. }
  469. static int
  470. lowercase(const char *s)
  471. {
  472. return (tolower(* (unsigned char *) s));
  473. }
  474. static int
  475. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  476. {
  477. int diff = 0;
  478. if (len > 0)
  479. do {
  480. diff = lowercase(s1++) - lowercase(s2++);
  481. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  482. return (diff);
  483. }
  484. static int
  485. mg_strcasecmp(const char *s1, const char *s2)
  486. {
  487. int diff;
  488. do {
  489. diff = lowercase(s1++) - lowercase(s2++);
  490. } while (diff == 0 && s1[-1] != '\0');
  491. return (diff);
  492. }
  493. static char *
  494. mg_strndup(const char *ptr, size_t len)
  495. {
  496. char *p;
  497. if ((p = (char *) malloc(len + 1)) != NULL)
  498. mg_strlcpy(p, ptr, len + 1);
  499. return (p);
  500. }
  501. static char *
  502. mg_strdup(const char *str)
  503. {
  504. return (mg_strndup(str, strlen(str)));
  505. }
  506. /*
  507. * Like snprintf(), but never returns negative value, or the value
  508. * that is larger than a supplied buffer.
  509. * Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  510. * in his audit report.
  511. */
  512. static int
  513. mg_vsnprintf(struct mg_connection *conn,
  514. char *buf, size_t buflen, const char *fmt, va_list ap)
  515. {
  516. int n;
  517. if (buflen == 0)
  518. return (0);
  519. n = vsnprintf(buf, buflen, fmt, ap);
  520. if (n < 0) {
  521. cry(conn, "vsnprintf error");
  522. n = 0;
  523. } else if (n >= (int) buflen) {
  524. cry(conn, "truncating vsnprintf buffer: [%.*s]",
  525. n > 200 ? 200 : n, buf);
  526. n = (int) buflen - 1;
  527. }
  528. buf[n] = '\0';
  529. return (n);
  530. }
  531. static int
  532. mg_snprintf(struct mg_connection *conn,
  533. char *buf, size_t buflen, const char *fmt, ...)
  534. {
  535. va_list ap;
  536. int n;
  537. va_start(ap, fmt);
  538. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  539. va_end(ap);
  540. return (n);
  541. }
  542. /*
  543. * Convert string representing a boolean value to a boolean value
  544. */
  545. static bool_t
  546. is_true(const char *str)
  547. {
  548. static const char *trues[] = {"1", "yes", "true", "ja", NULL};
  549. int i;
  550. for (i = 0; trues[i] != NULL; i++)
  551. if (str != NULL && mg_strcasecmp(str, trues[i]) == 0)
  552. return (TRUE);
  553. return (FALSE);
  554. }
  555. /*
  556. * Skip the characters until one of the delimiters characters found.
  557. * 0-terminate resulting word. Skip the rest of the delimiters if any.
  558. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  559. */
  560. static char *
  561. skip(char **buf, const char *delimiters)
  562. {
  563. char *p, *begin_word, *end_word, *end_delimiters;
  564. begin_word = *buf;
  565. end_word = begin_word + strcspn(begin_word, delimiters);
  566. end_delimiters = end_word + strspn(end_word, delimiters);
  567. for (p = end_word; p < end_delimiters; p++)
  568. *p = '\0';
  569. *buf = end_delimiters;
  570. return (begin_word);
  571. }
  572. /*
  573. * Return HTTP header value, or NULL if not found.
  574. */
  575. static const char *
  576. get_header(const struct mg_request_info *ri, const char *name)
  577. {
  578. int i;
  579. for (i = 0; i < ri->num_headers; i++)
  580. if (!mg_strcasecmp(name, ri->http_headers[i].name))
  581. return (ri->http_headers[i].value);
  582. return (NULL);
  583. }
  584. const char *
  585. mg_get_header(const struct mg_connection *conn, const char *name)
  586. {
  587. return (get_header(&conn->request_info, name));
  588. }
  589. /*
  590. * A helper function for traversing comma separated list of values.
  591. * It returns a list pointer shifted to the next value, of NULL if the end
  592. * of the list found.
  593. * Value is stored in val vector. If value has form "x=y", then eq_val
  594. * vector is initialized to point to the "y" part, and val vector length
  595. * is adjusted to point only to "x".
  596. */
  597. static const char *
  598. next_option(const char *list, struct vec *val, struct vec *eq_val)
  599. {
  600. if (list == NULL || *list == '\0') {
  601. /* End of the list */
  602. list = NULL;
  603. } else {
  604. val->ptr = list;
  605. if ((list = strchr(val->ptr, ',')) != NULL) {
  606. /* Comma found. Store length and shift the list ptr */
  607. val->len = list - val->ptr;
  608. list++;
  609. } else {
  610. /* This value is the last one */
  611. list = val->ptr + strlen(val->ptr);
  612. val->len = list - val->ptr;
  613. }
  614. if (eq_val != NULL) {
  615. /*
  616. * Value has form "x=y", adjust pointers and lengths
  617. * so that val points to "x", and eq_val points to "y".
  618. */
  619. eq_val->len = 0;
  620. eq_val->ptr = memchr(val->ptr, '=', val->len);
  621. if (eq_val->ptr != NULL) {
  622. eq_val->ptr++; /* Skip over '=' character */
  623. eq_val->len = val->ptr + val->len - eq_val->ptr;
  624. val->len = (eq_val->ptr - val->ptr) - 1;
  625. }
  626. }
  627. }
  628. return (list);
  629. }
  630. #if !(defined(NO_CGI) && defined(NO_SSI))
  631. /*
  632. * Verify that given file has certain extension
  633. */
  634. static bool_t
  635. match_extension(const char *path, const char *ext_list)
  636. {
  637. struct vec ext_vec;
  638. size_t path_len;
  639. path_len = strlen(path);
  640. while ((ext_list = next_option(ext_list, &ext_vec, NULL)) != NULL)
  641. if (ext_vec.len < path_len &&
  642. mg_strncasecmp(path + path_len - ext_vec.len,
  643. ext_vec.ptr, ext_vec.len) == 0)
  644. return (TRUE);
  645. return (FALSE);
  646. }
  647. #endif /* !(NO_CGI && NO_SSI) */
  648. /*
  649. * Send error message back to the client.
  650. */
  651. static void
  652. send_error(struct mg_connection *conn, int status, const char *reason,
  653. const char *fmt, ...)
  654. {
  655. char buf[BUFSIZ];
  656. va_list ap;
  657. int len;
  658. mg_callback_t error_handler;
  659. bool_t handled;
  660. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: %d %s", __func__, status, reason));
  661. conn->request_info.status_code = status;
  662. error_handler = conn->ctx->callbacks[MG_EVENT_HTTP_ERROR];
  663. handled = error_handler ?
  664. error_handler(conn, &conn->request_info) : FALSE;
  665. if (handled == FALSE) {
  666. buf[0] = '\0';
  667. len = 0;
  668. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  669. if (status > 199 && status != 204 && status != 304) {
  670. len = mg_snprintf(conn, buf, sizeof(buf),
  671. "Error %d: %s\n", status, reason);
  672. cry(conn, "%s", buf);
  673. va_start(ap, fmt);
  674. len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len,
  675. fmt, ap);
  676. va_end(ap);
  677. conn->num_bytes_sent = len;
  678. }
  679. (void) mg_printf(conn,
  680. "HTTP/1.1 %d %s\r\n"
  681. "Content-Type: text/plain\r\n"
  682. "Content-Length: %d\r\n"
  683. "Connection: close\r\n"
  684. "\r\n%s", status, reason, len, buf);
  685. }
  686. }
  687. #ifdef _WIN32
  688. static int
  689. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  690. {
  691. unused = NULL;
  692. *mutex = CreateMutex(NULL, FALSE, NULL);
  693. return (*mutex == NULL ? -1 : 0);
  694. }
  695. static int
  696. pthread_mutex_destroy(pthread_mutex_t *mutex)
  697. {
  698. return (CloseHandle(*mutex) == 0 ? -1 : 0);
  699. }
  700. static int
  701. pthread_mutex_lock(pthread_mutex_t *mutex)
  702. {
  703. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1);
  704. }
  705. static int
  706. pthread_mutex_unlock(pthread_mutex_t *mutex)
  707. {
  708. return (ReleaseMutex(*mutex) == 0 ? -1 : 0);
  709. }
  710. static int
  711. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  712. {
  713. unused = NULL;
  714. *cv = CreateEvent(NULL, FALSE, FALSE, NULL);
  715. return (*cv == NULL ? -1 : 0);
  716. }
  717. static int
  718. pthread_cond_timedwait(pthread_cond_t *cv, pthread_mutex_t *mutex,
  719. const struct timespec *ts)
  720. {
  721. DWORD status;
  722. DWORD msec = INFINITE;
  723. time_t now;
  724. if (ts != NULL) {
  725. now = time(NULL);
  726. msec = 1000 * (now > ts->tv_sec ? 0 : ts->tv_sec - now);
  727. }
  728. (void) ReleaseMutex(*mutex);
  729. status = WaitForSingleObject(*cv, msec);
  730. (void) WaitForSingleObject(*mutex, INFINITE);
  731. return (status == WAIT_OBJECT_0 ? 0 : -1);
  732. }
  733. static int
  734. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  735. {
  736. return (pthread_cond_timedwait(cv, mutex, NULL));
  737. }
  738. static int
  739. pthread_cond_signal(pthread_cond_t *cv)
  740. {
  741. return (SetEvent(*cv) == 0 ? -1 : 0);
  742. }
  743. static int
  744. pthread_cond_destroy(pthread_cond_t *cv)
  745. {
  746. return (CloseHandle(*cv) == 0 ? -1 : 0);
  747. }
  748. static pthread_t
  749. pthread_self(void)
  750. {
  751. return (GetCurrentThreadId());
  752. }
  753. /*
  754. * Change all slashes to backslashes. It is Windows.
  755. */
  756. static void
  757. fix_directory_separators(char *path)
  758. {
  759. int i;
  760. for (i = 0; path[i] != '\0'; i++) {
  761. if (path[i] == '/')
  762. path[i] = '\\';
  763. /* i > 0 check is to preserve UNC paths, \\server\file.txt */
  764. if (path[i] == '\\' && i > 0)
  765. while (path[i + 1] == '\\' || path[i + 1] == '/')
  766. (void) memmove(path + i + 1,
  767. path + i + 2, strlen(path + i + 1));
  768. }
  769. }
  770. /*
  771. * Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  772. * wbuf and wbuf_len is a target buffer and its length.
  773. */
  774. static void
  775. to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  776. {
  777. char buf[FILENAME_MAX], *p;
  778. mg_strlcpy(buf, path, sizeof(buf));
  779. fix_directory_separators(buf);
  780. /* Point p to the end of the file name */
  781. p = buf + strlen(buf) - 1;
  782. /* Trim trailing backslash character */
  783. while (p > buf && *p == '\\' && p[-1] != ':')
  784. *p-- = '\0';
  785. /*
  786. * Protect from CGI code disclosure.
  787. * This is very nasty hole. Windows happily opens files with
  788. * some garbage in the end of file name. So fopen("a.cgi ", "r")
  789. * actually opens "a.cgi", and does not return an error!
  790. */
  791. if (*p == 0x20 || /* No space at the end */
  792. (*p == 0x2e && p > buf) || /* No '.' but allow '.' as full path */
  793. *p == 0x2b || /* No '+' */
  794. (*p & ~0x7f)) { /* And generally no non-ascii chars */
  795. (void) fprintf(stderr, "Rejecting suspicious path: [%s]", buf);
  796. buf[0] = '\0';
  797. }
  798. (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  799. }
  800. #if defined(_WIN32_WCE)
  801. static time_t
  802. time(time_t *ptime)
  803. {
  804. time_t t;
  805. SYSTEMTIME st;
  806. FILETIME ft;
  807. GetSystemTime(&st);
  808. SystemTimeToFileTime(&st, &ft);
  809. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  810. if (ptime != NULL)
  811. *ptime = t;
  812. return (t);
  813. }
  814. static time_t
  815. mktime(struct tm *ptm)
  816. {
  817. SYSTEMTIME st;
  818. FILETIME ft, lft;
  819. st.wYear = ptm->tm_year + 1900;
  820. st.wMonth = ptm->tm_mon + 1;
  821. st.wDay = ptm->tm_mday;
  822. st.wHour = ptm->tm_hour;
  823. st.wMinute = ptm->tm_min;
  824. st.wSecond = ptm->tm_sec;
  825. st.wMilliseconds = 0;
  826. SystemTimeToFileTime(&st, &ft);
  827. LocalFileTimeToFileTime(&ft, &lft);
  828. return (time_t)((MAKEUQUAD(lft.dwLowDateTime, lft.dwHighDateTime) -
  829. EPOCH_DIFF) / RATE_DIFF);
  830. }
  831. static struct tm *
  832. localtime(const time_t *ptime, struct tm *ptm)
  833. {
  834. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  835. FILETIME ft, lft;
  836. SYSTEMTIME st;
  837. TIME_ZONE_INFORMATION tzinfo;
  838. if (ptm == NULL)
  839. return NULL;
  840. * (int64_t *) &ft = t;
  841. FileTimeToLocalFileTime(&ft, &lft);
  842. FileTimeToSystemTime(&lft, &st);
  843. ptm->tm_year = st.wYear - 1900;
  844. ptm->tm_mon = st.wMonth - 1;
  845. ptm->tm_wday = st.wDayOfWeek;
  846. ptm->tm_mday = st.wDay;
  847. ptm->tm_hour = st.wHour;
  848. ptm->tm_min = st.wMinute;
  849. ptm->tm_sec = st.wSecond;
  850. ptm->tm_yday = 0; // hope nobody uses this
  851. ptm->tm_isdst = ((GetTimeZoneInformation(&tzinfo) ==
  852. TIME_ZONE_ID_DAYLIGHT) ? 1 : 0);
  853. return ptm;
  854. }
  855. static size_t
  856. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  857. {
  858. (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
  859. return (0);
  860. }
  861. #endif
  862. static int
  863. mg_rename(const char* oldname, const char* newname)
  864. {
  865. wchar_t woldbuf[FILENAME_MAX];
  866. wchar_t wnewbuf[FILENAME_MAX];
  867. to_unicode(oldname, woldbuf, ARRAY_SIZE(woldbuf));
  868. to_unicode(newname, wnewbuf, ARRAY_SIZE(wnewbuf));
  869. return (MoveFileW(woldbuf, wnewbuf) ? 0 : -1);
  870. }
  871. static FILE *
  872. mg_fopen(const char *path, const char *mode)
  873. {
  874. wchar_t wbuf[FILENAME_MAX], wmode[20];
  875. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  876. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  877. return (_wfopen(wbuf, wmode));
  878. }
  879. static int
  880. mg_stat(const char *path, struct mgstat *stp)
  881. {
  882. int ok = -1; /* Error */
  883. wchar_t wbuf[FILENAME_MAX];
  884. WIN32_FILE_ATTRIBUTE_DATA info;
  885. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  886. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  887. stp->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  888. stp->mtime = SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  889. info.ftLastWriteTime.dwHighDateTime);
  890. stp->is_directory =
  891. info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  892. ok = 0; /* Success */
  893. }
  894. return (ok);
  895. }
  896. static int
  897. mg_remove(const char *path)
  898. {
  899. wchar_t wbuf[FILENAME_MAX];
  900. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  901. return (DeleteFileW(wbuf) ? 0 : -1);
  902. }
  903. static int
  904. mg_mkdir(const char *path, int mode)
  905. {
  906. char buf[FILENAME_MAX];
  907. wchar_t wbuf[FILENAME_MAX];
  908. mode = 0; /* Unused */
  909. mg_strlcpy(buf, path, sizeof(buf));
  910. fix_directory_separators(buf);
  911. (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, sizeof(wbuf));
  912. return (CreateDirectoryW(wbuf, NULL) ? 0 : -1);
  913. }
  914. /*
  915. * Implementation of POSIX opendir/closedir/readdir for Windows.
  916. */
  917. static DIR *
  918. opendir(const char *name)
  919. {
  920. DIR *dir = NULL;
  921. wchar_t wpath[FILENAME_MAX];
  922. DWORD attrs;
  923. if (name == NULL) {
  924. SetLastError(ERROR_BAD_ARGUMENTS);
  925. } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
  926. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  927. } else {
  928. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  929. attrs = GetFileAttributesW(wpath);
  930. if (attrs != 0xFFFFFFFF &&
  931. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  932. (void) wcscat(wpath, L"\\*");
  933. dir->handle = FindFirstFileW(wpath, &dir->info);
  934. dir->result.d_name[0] = '\0';
  935. } else {
  936. free(dir);
  937. dir = NULL;
  938. }
  939. }
  940. return (dir);
  941. }
  942. static int
  943. closedir(DIR *dir)
  944. {
  945. int result = 0;
  946. if (dir != NULL) {
  947. if (dir->handle != INVALID_HANDLE_VALUE)
  948. result = FindClose(dir->handle) ? 0 : -1;
  949. free(dir);
  950. } else {
  951. result = -1;
  952. SetLastError(ERROR_BAD_ARGUMENTS);
  953. }
  954. return (result);
  955. }
  956. struct dirent *
  957. readdir(DIR *dir)
  958. {
  959. struct dirent *result = 0;
  960. if (dir) {
  961. if (dir->handle != INVALID_HANDLE_VALUE) {
  962. result = &dir->result;
  963. (void) WideCharToMultiByte(CP_UTF8, 0,
  964. dir->info.cFileName, -1, result->d_name,
  965. sizeof(result->d_name), NULL, NULL);
  966. if (!FindNextFileW(dir->handle, &dir->info)) {
  967. (void) FindClose(dir->handle);
  968. dir->handle = INVALID_HANDLE_VALUE;
  969. }
  970. } else {
  971. SetLastError(ERROR_FILE_NOT_FOUND);
  972. }
  973. } else {
  974. SetLastError(ERROR_BAD_ARGUMENTS);
  975. }
  976. return (result);
  977. }
  978. #define set_close_on_exec(fd) /* No FD_CLOEXEC on Windows */
  979. static int
  980. start_thread(struct mg_context *ctx, mg_thread_func_t func, void *param)
  981. {
  982. HANDLE hThread;
  983. ctx = NULL; /* Unused */
  984. hThread = CreateThread(NULL, 0,
  985. (LPTHREAD_START_ROUTINE) func, param, 0, NULL);
  986. if (hThread != NULL)
  987. (void) CloseHandle(hThread);
  988. return (hThread == NULL ? -1 : 0);
  989. }
  990. static HANDLE
  991. dlopen(const char *dll_name, int flags)
  992. {
  993. wchar_t wbuf[FILENAME_MAX];
  994. flags = 0; /* Unused */
  995. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  996. return (LoadLibraryW(wbuf));
  997. }
  998. #if !defined(NO_CGI)
  999. static int
  1000. kill(pid_t pid, int sig_num)
  1001. {
  1002. (void) TerminateProcess(pid, sig_num);
  1003. (void) CloseHandle(pid);
  1004. return (0);
  1005. }
  1006. static pid_t
  1007. spawn_process(struct mg_connection *conn, const char *prog, char *envblk,
  1008. char *envp[], int fd_stdin, int fd_stdout, const char *dir)
  1009. {
  1010. HANDLE me;
  1011. char *p, *interp, cmdline[FILENAME_MAX], line[FILENAME_MAX];
  1012. FILE *fp;
  1013. STARTUPINFOA si;
  1014. PROCESS_INFORMATION pi;
  1015. envp = NULL; /* Unused */
  1016. (void) memset(&si, 0, sizeof(si));
  1017. (void) memset(&pi, 0, sizeof(pi));
  1018. /* XXX redirect CGI errors to the error log file */
  1019. si.cb = sizeof(si);
  1020. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  1021. si.wShowWindow = SW_HIDE;
  1022. me = GetCurrentProcess();
  1023. (void) DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me,
  1024. &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1025. (void) DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me,
  1026. &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1027. /* If CGI file is a script, try to read the interpreter line */
  1028. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  1029. interp = conn->ctx->options[OPT_CGI_INTERPRETER];
  1030. if (interp == NULL) {
  1031. line[2] = '\0';
  1032. (void) mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%c%s",
  1033. dir, DIRSEP, prog);
  1034. if ((fp = fopen(cmdline, "r")) != NULL) {
  1035. (void) fgets(line, sizeof(line), fp);
  1036. if (memcmp(line, "#!", 2) != 0)
  1037. line[2] = '\0';
  1038. /* Trim whitespaces from interpreter name */
  1039. for (p = &line[strlen(line) - 1]; p > line &&
  1040. isspace(*p); p--)
  1041. *p = '\0';
  1042. (void) fclose(fp);
  1043. }
  1044. interp = line + 2;
  1045. }
  1046. if ((p = (char *) strrchr(prog, '/')) != NULL)
  1047. prog = p + 1;
  1048. (void) mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s",
  1049. interp, interp[0] == '\0' ? "" : " ", prog);
  1050. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  1051. (void) mg_snprintf(conn, line, sizeof(line), "%s", dir);
  1052. fix_directory_separators(line);
  1053. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: Running [%s]", __func__, cmdline));
  1054. if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
  1055. CREATE_NEW_PROCESS_GROUP, envblk, line, &si, &pi) == 0) {
  1056. cry(conn, "%s: CreateProcess(%s): %d",
  1057. __func__, cmdline, ERRNO);
  1058. pi.hProcess = (pid_t) -1;
  1059. } else {
  1060. (void) close(fd_stdin);
  1061. (void) close(fd_stdout);
  1062. }
  1063. (void) CloseHandle(si.hStdOutput);
  1064. (void) CloseHandle(si.hStdInput);
  1065. (void) CloseHandle(pi.hThread);
  1066. return ((pid_t) pi.hProcess);
  1067. }
  1068. static int
  1069. pipe(int *fds)
  1070. {
  1071. return (_pipe(fds, BUFSIZ, _O_BINARY));
  1072. }
  1073. #endif /* !NO_CGI */
  1074. static int
  1075. set_non_blocking_mode(struct mg_connection *conn, SOCKET sock)
  1076. {
  1077. unsigned long on = 1;
  1078. conn = NULL; /* unused */
  1079. return (ioctlsocket(sock, FIONBIO, &on));
  1080. }
  1081. #else
  1082. static int
  1083. mg_stat(const char *path, struct mgstat *stp)
  1084. {
  1085. struct stat st;
  1086. int ok;
  1087. if (stat(path, &st) == 0) {
  1088. ok = 0;
  1089. stp->size = st.st_size;
  1090. stp->mtime = st.st_mtime;
  1091. stp->is_directory = S_ISDIR(st.st_mode);
  1092. } else {
  1093. ok = -1;
  1094. }
  1095. return (ok);
  1096. }
  1097. static void
  1098. set_close_on_exec(int fd)
  1099. {
  1100. (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
  1101. }
  1102. static int
  1103. start_thread(struct mg_context *ctx, mg_thread_func_t func, void *param)
  1104. {
  1105. pthread_t thread_id;
  1106. pthread_attr_t attr;
  1107. int retval;
  1108. (void) pthread_attr_init(&attr);
  1109. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  1110. (void) pthread_attr_setstacksize(&attr,
  1111. sizeof(struct mg_connection) * 2);
  1112. if ((retval = pthread_create(&thread_id, &attr, func, param)) != 0)
  1113. cry(fc(ctx), "%s: %s", __func__, strerror(retval));
  1114. return (retval);
  1115. }
  1116. #ifndef NO_CGI
  1117. static pid_t
  1118. spawn_process(struct mg_connection *conn, const char *prog, char *envblk,
  1119. char *envp[], int fd_stdin, int fd_stdout, const char *dir)
  1120. {
  1121. pid_t pid;
  1122. const char *interp;
  1123. envblk = NULL; /* unused */
  1124. if ((pid = fork()) == -1) {
  1125. /* Parent */
  1126. send_error(conn, 500, http_500_error,
  1127. "fork(): %s", strerror(ERRNO));
  1128. } else if (pid == 0) {
  1129. /* Child */
  1130. if (chdir(dir) != 0) {
  1131. cry(conn, "%s: chdir(%s): %s",
  1132. __func__, dir, strerror(ERRNO));
  1133. } else if (dup2(fd_stdin, 0) == -1) {
  1134. cry(conn, "%s: dup2(stdin, %d): %s",
  1135. __func__, fd_stdin, strerror(ERRNO));
  1136. } else if (dup2(fd_stdout, 1) == -1) {
  1137. cry(conn, "%s: dup2(stdout, %d): %s",
  1138. __func__, fd_stdout, strerror(ERRNO));
  1139. } else {
  1140. (void) dup2(fd_stdout, 2);
  1141. (void) close(fd_stdin);
  1142. (void) close(fd_stdout);
  1143. /* Execute CGI program. No need to lock: new process */
  1144. interp = conn->ctx->options[OPT_CGI_INTERPRETER];
  1145. if (interp == NULL) {
  1146. (void) execle(prog, prog, NULL, envp);
  1147. cry(conn, "%s: execle(%s): %s",
  1148. __func__, prog, strerror(ERRNO));
  1149. } else {
  1150. (void) execle(interp, interp, prog, NULL, envp);
  1151. cry(conn, "%s: execle(%s %s): %s",
  1152. __func__, interp, prog, strerror(ERRNO));
  1153. }
  1154. }
  1155. exit(EXIT_FAILURE);
  1156. } else {
  1157. /* Parent. Close stdio descriptors */
  1158. (void) close(fd_stdin);
  1159. (void) close(fd_stdout);
  1160. }
  1161. return (pid);
  1162. }
  1163. #endif /* !NO_CGI */
  1164. static int
  1165. set_non_blocking_mode(struct mg_connection *conn, SOCKET sock)
  1166. {
  1167. int flags, ok = -1;
  1168. if ((flags = fcntl(sock, F_GETFL, 0)) == -1) {
  1169. cry(conn, "%s: fcntl(F_GETFL): %d", __func__, ERRNO);
  1170. } else if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) != 0) {
  1171. cry(conn, "%s: fcntl(F_SETFL): %d", __func__, ERRNO);
  1172. } else {
  1173. ok = 0; /* Success */
  1174. }
  1175. return (ok);
  1176. }
  1177. #endif /* _WIN32 */
  1178. /*
  1179. * Write data to the IO channel - opened file descriptor, socket or SSL
  1180. * descriptor. Return number of bytes written.
  1181. */
  1182. static int64_t
  1183. push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int64_t len)
  1184. {
  1185. int64_t sent;
  1186. int n, k;
  1187. sent = 0;
  1188. while (sent < len) {
  1189. /* How many bytes we send in this iteration */
  1190. k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
  1191. if (ssl != NULL) {
  1192. n = SSL_write(ssl, buf + sent, k);
  1193. } else if (fp != NULL) {
  1194. n = fwrite(buf + sent, 1, k, fp);
  1195. if (ferror(fp))
  1196. n = -1;
  1197. } else {
  1198. n = send(sock, buf + sent, k, 0);
  1199. }
  1200. if (n < 0)
  1201. break;
  1202. sent += n;
  1203. }
  1204. return (sent);
  1205. }
  1206. /*
  1207. * Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  1208. * Return number of bytes read.
  1209. */
  1210. static int
  1211. pull(FILE *fp, SOCKET sock, SSL *ssl, char *buf, int len)
  1212. {
  1213. int nread;
  1214. if (ssl != NULL) {
  1215. nread = SSL_read(ssl, buf, len);
  1216. } else if (fp != NULL) {
  1217. nread = fread(buf, 1, (size_t) len, fp);
  1218. if (ferror(fp))
  1219. nread = -1;
  1220. } else {
  1221. nread = recv(sock, buf, (size_t) len, 0);
  1222. }
  1223. return (nread);
  1224. }
  1225. int
  1226. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  1227. {
  1228. return ((int) push(NULL, conn->client.sock, conn->ssl,
  1229. (const char *) buf, (int64_t) len));
  1230. }
  1231. int
  1232. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  1233. {
  1234. char buf[MAX_REQUEST_SIZE];
  1235. int len;
  1236. va_list ap;
  1237. va_start(ap, fmt);
  1238. len = mg_vsnprintf(conn, buf, sizeof(buf), fmt, ap);
  1239. va_end(ap);
  1240. return (mg_write(conn, buf, len));
  1241. }
  1242. /*
  1243. * Return content length of the request, or -1 constant if
  1244. * Content-Length header is not set.
  1245. */
  1246. static int64_t
  1247. get_content_length(const struct mg_connection *conn)
  1248. {
  1249. const char *cl = mg_get_header(conn, "Content-Length");
  1250. return (cl == NULL ? -1 : strtoll(cl, NULL, 10));
  1251. }
  1252. /*
  1253. * URL-decode input buffer into destination buffer.
  1254. * 0-terminate the destination buffer. Return the length of decoded data.
  1255. * form-url-encoded data differs from URI encoding in a way that it
  1256. * uses '+' as character for space, see RFC 1866 section 8.2.1
  1257. * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  1258. */
  1259. static size_t
  1260. url_decode(const char *src, size_t src_len, char *dst, size_t dst_len,
  1261. bool_t is_form_url_encoded)
  1262. {
  1263. size_t i, j;
  1264. int a, b;
  1265. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  1266. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  1267. if (src[i] == '%' &&
  1268. isxdigit(* (unsigned char *) (src + i + 1)) &&
  1269. isxdigit(* (unsigned char *) (src + i + 2))) {
  1270. a = tolower(* (unsigned char *) (src + i + 1));
  1271. b = tolower(* (unsigned char *) (src + i + 2));
  1272. dst[j] = ((HEXTOI(a) << 4) | HEXTOI(b)) & 0xff;
  1273. i += 2;
  1274. } else if (is_form_url_encoded && src[i] == '+') {
  1275. dst[j] = ' ';
  1276. } else {
  1277. dst[j] = src[i];
  1278. }
  1279. }
  1280. dst[j] = '\0'; /* Null-terminate the destination */
  1281. return (j);
  1282. }
  1283. /*
  1284. * Scan given buffer and fetch the value of the given variable.
  1285. * It can be specified in query string, or in the POST data.
  1286. * Return NULL if the variable not found, or allocated 0-terminated value.
  1287. * It is caller's responsibility to free the returned value.
  1288. */
  1289. enum mg_error_t
  1290. mg_get_var(const char *buf, size_t buf_len, const char *var_name,
  1291. char *var_value, size_t var_value_len)
  1292. {
  1293. const char *p, *e, *s;
  1294. char *val;
  1295. size_t var_len, len;
  1296. enum mg_error_t ret_val;
  1297. var_len = strlen(var_name);
  1298. e = buf + buf_len;
  1299. val = NULL;
  1300. ret_val = MG_NOT_FOUND;
  1301. var_value[0] = '\0';
  1302. /* buf is "var1=val1&var2=val2...". Find variable first */
  1303. for (p = buf; p + var_len < e; p++)
  1304. if ((p == buf || p[-1] == '&') && p[var_len] == '=' &&
  1305. !mg_strncasecmp(var_name, p, var_len)) {
  1306. /* Point p to variable value */
  1307. p += var_len + 1;
  1308. /* Point s to the end of the value */
  1309. s = (const char *) memchr(p, '&', e - p);
  1310. if (s == NULL)
  1311. s = e;
  1312. /* Try to allocate the buffer */
  1313. len = s - p;
  1314. if (len >= var_value_len) {
  1315. ret_val = MG_BUFFER_TOO_SMALL;
  1316. } else {
  1317. url_decode(p, len, var_value, len + 1, TRUE);
  1318. ret_val = MG_SUCCESS;
  1319. }
  1320. break;
  1321. }
  1322. return (ret_val);
  1323. }
  1324. enum mg_error_t
  1325. mg_get_qsvar(const struct mg_request_info *ri, const char *var_name,
  1326. char *var_value, size_t var_value_len) {
  1327. return (ri->query_string == NULL ? MG_NOT_FOUND : mg_get_var(ri->query_string,
  1328. strlen(ri->query_string), var_name, var_value, var_value_len));
  1329. }
  1330. enum mg_error_t
  1331. mg_get_cookie(const struct mg_connection *conn,
  1332. const char *cookie_name, char *dst, size_t dst_size)
  1333. {
  1334. const char *s, *p, *end;
  1335. int len;
  1336. dst[0] = '\0';
  1337. if ((s = mg_get_header(conn, "Cookie")) == NULL)
  1338. return (MG_NOT_FOUND);
  1339. len = strlen(cookie_name);
  1340. end = s + strlen(s);
  1341. for (; (s = strstr(s, cookie_name)) != NULL; s += len)
  1342. if (s[len] == '=') {
  1343. s += len + 1;
  1344. if ((p = strchr(s, ' ')) == NULL)
  1345. p = end;
  1346. if (p[-1] == ';')
  1347. p--;
  1348. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  1349. s++;
  1350. p--;
  1351. }
  1352. if ((size_t) (p - s) >= dst_size) {
  1353. return (MG_BUFFER_TOO_SMALL);
  1354. } else {
  1355. mg_strlcpy(dst, s, (p - s) + 1);
  1356. return (MG_SUCCESS);
  1357. }
  1358. }
  1359. return (MG_NOT_FOUND);
  1360. }
  1361. /*
  1362. * Transform URI to the file name.
  1363. */
  1364. static void
  1365. convert_uri_to_file_name(struct mg_connection *conn, const char *uri,
  1366. char *buf, size_t buf_len)
  1367. {
  1368. struct mg_context *ctx = conn->ctx;
  1369. struct vec uri_vec, path_vec;
  1370. const char *list;
  1371. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  1372. mg_snprintf(conn, buf, buf_len, "%s%s", ctx->options[OPT_ROOT], uri);
  1373. /* If requested URI has aliased prefix, use alternate root */
  1374. list = ctx->options[OPT_ALIASES];
  1375. while ((list = next_option(list, &uri_vec, &path_vec)) != NULL) {
  1376. if (memcmp(uri, uri_vec.ptr, uri_vec.len) == 0) {
  1377. (void) mg_snprintf(conn, buf, buf_len, "%.*s%s",
  1378. path_vec.len, path_vec.ptr, uri + uri_vec.len);
  1379. break;
  1380. }
  1381. }
  1382. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  1383. #ifdef _WIN32
  1384. fix_directory_separators(buf);
  1385. #endif /* _WIN32 */
  1386. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: [%s] -> [%s]", __func__, uri, buf));
  1387. }
  1388. /*
  1389. * Setup listening socket on given address, return socket.
  1390. * Address format: [local_ip_address:]port_number
  1391. */
  1392. static SOCKET
  1393. mg_open_listening_port(struct mg_context *ctx, const char *str, struct usa *usa)
  1394. {
  1395. SOCKET sock;
  1396. int on = 1, a, b, c, d, port;
  1397. /* MacOS needs that. If we do not zero it, bind() will fail. */
  1398. (void) memset(usa, 0, sizeof(*usa));
  1399. if (sscanf(str, "%d.%d.%d.%d:%d", &a, &b, &c, &d, &port) == 5) {
  1400. /* IP address to bind to is specified */
  1401. usa->u.sin.sin_addr.s_addr =
  1402. htonl((a << 24) | (b << 16) | (c << 8) | d);
  1403. } else if (sscanf(str, "%d", &port) == 1) {
  1404. /* Only port number is specified. Bind to all addresses */
  1405. usa->u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
  1406. } else {
  1407. return (INVALID_SOCKET);
  1408. }
  1409. usa->len = sizeof(usa->u.sin);
  1410. usa->u.sin.sin_family = AF_INET;
  1411. usa->u.sin.sin_port = htons((uint16_t) port);
  1412. if ((sock = socket(PF_INET, SOCK_STREAM, 6)) != INVALID_SOCKET &&
  1413. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  1414. (char *) &on, sizeof(on)) == 0 &&
  1415. bind(sock, &usa->u.sa, usa->len) == 0 &&
  1416. listen(sock, 20) == 0) {
  1417. /* Success */
  1418. set_close_on_exec(sock);
  1419. } else {
  1420. /* Error */
  1421. cry(fc(ctx), "%s(%d): %s", __func__, port, strerror(ERRNO));
  1422. if (sock != INVALID_SOCKET)
  1423. (void) closesocket(sock);
  1424. sock = INVALID_SOCKET;
  1425. }
  1426. return (sock);
  1427. }
  1428. /*
  1429. * Check whether full request is buffered. Return:
  1430. * -1 if request is malformed
  1431. * 0 if request is not yet fully buffered
  1432. * >0 actual request length, including last \r\n\r\n
  1433. */
  1434. static int
  1435. get_request_len(const char *buf, size_t buflen)
  1436. {
  1437. const char *s, *e;
  1438. int len = 0;
  1439. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  1440. /* Control characters are not allowed but >=128 is. */
  1441. if (!isprint(* (unsigned char *) s) && *s != '\r' &&
  1442. *s != '\n' && * (unsigned char *) s < 128)
  1443. len = -1;
  1444. else if (s[0] == '\n' && s[1] == '\n')
  1445. len = (int) (s - buf) + 2;
  1446. else if (s[0] == '\n' && &s[1] < e &&
  1447. s[1] == '\r' && s[2] == '\n')
  1448. len = (int) (s - buf) + 3;
  1449. return (len);
  1450. }
  1451. /*
  1452. * Convert month to the month number. Return -1 on error, or month number
  1453. */
  1454. static int
  1455. montoi(const char *s)
  1456. {
  1457. size_t i;
  1458. for (i = 0; i < sizeof(month_names) / sizeof(month_names[0]); i++)
  1459. if (!strcmp(s, month_names[i]))
  1460. return ((int) i);
  1461. return (-1);
  1462. }
  1463. /*
  1464. * Parse date-time string, and return the corresponding time_t value
  1465. */
  1466. static time_t
  1467. date_to_epoch(const char *s)
  1468. {
  1469. time_t current_time;
  1470. struct tm tm, *tmp;
  1471. char mon[32];
  1472. int sec, min, hour, mday, month, year;
  1473. (void) memset(&tm, 0, sizeof(tm));
  1474. sec = min = hour = mday = month = year = 0;
  1475. if (((sscanf(s, "%d/%3s/%d %d:%d:%d",
  1476. &mday, mon, &year, &hour, &min, &sec) == 6) ||
  1477. (sscanf(s, "%d %3s %d %d:%d:%d",
  1478. &mday, mon, &year, &hour, &min, &sec) == 6) ||
  1479. (sscanf(s, "%*3s, %d %3s %d %d:%d:%d",
  1480. &mday, mon, &year, &hour, &min, &sec) == 6) ||
  1481. (sscanf(s, "%d-%3s-%d %d:%d:%d",
  1482. &mday, mon, &year, &hour, &min, &sec) == 6)) &&
  1483. (month = montoi(mon)) != -1) {
  1484. tm.tm_mday = mday;
  1485. tm.tm_mon = month;
  1486. tm.tm_year = year;
  1487. tm.tm_hour = hour;
  1488. tm.tm_min = min;
  1489. tm.tm_sec = sec;
  1490. }
  1491. if (tm.tm_year > 1900)
  1492. tm.tm_year -= 1900;
  1493. else if (tm.tm_year < 70)
  1494. tm.tm_year += 100;
  1495. /* Set Daylight Saving Time field */
  1496. current_time = time(NULL);
  1497. tmp = localtime(&current_time);
  1498. tm.tm_isdst = tmp->tm_isdst;
  1499. return (mktime(&tm));
  1500. }
  1501. /*
  1502. * Protect against directory disclosure attack by removing '..',
  1503. * excessive '/' and '\' characters
  1504. */
  1505. static void
  1506. remove_double_dots_and_double_slashes(char *s)
  1507. {
  1508. char *p = s;
  1509. while (*s != '\0') {
  1510. *p++ = *s++;
  1511. if (s[-1] == '/' || s[-1] == '\\') {
  1512. /* Skip all following slashes and backslashes */
  1513. while (*s == '/' || *s == '\\')
  1514. s++;
  1515. /* Skip all double-dots */
  1516. while (*s == '.' && s[1] == '.')
  1517. s += 2;
  1518. }
  1519. }
  1520. *p = '\0';
  1521. }
  1522. /*
  1523. * Built-in mime types
  1524. */
  1525. static const struct {
  1526. const char *extension;
  1527. size_t ext_len;
  1528. const char *mime_type;
  1529. size_t mime_type_len;
  1530. } mime_types[] = {
  1531. {".html", 5, "text/html", 9},
  1532. {".htm", 4, "text/html", 9},
  1533. {".shtm", 5, "text/html", 9},
  1534. {".shtml", 6, "text/html", 9},
  1535. {".css", 4, "text/css", 8},
  1536. {".js", 3, "application/x-javascript", 24},
  1537. {".ico", 4, "image/x-icon", 12},
  1538. {".gif", 4, "image/gif", 9},
  1539. {".jpg", 4, "image/jpeg", 10},
  1540. {".jpeg", 5, "image/jpeg", 10},
  1541. {".png", 4, "image/png", 9},
  1542. {".svg", 4, "image/svg+xml", 13},
  1543. {".torrent", 8, "application/x-bittorrent", 24},
  1544. {".wav", 4, "audio/x-wav", 11},
  1545. {".mp3", 4, "audio/x-mp3", 11},
  1546. {".mid", 4, "audio/mid", 9},
  1547. {".m3u", 4, "audio/x-mpegurl", 15},
  1548. {".ram", 4, "audio/x-pn-realaudio", 20},
  1549. {".xml", 4, "text/xml", 8},
  1550. {".xslt", 5, "application/xml", 15},
  1551. {".ra", 3, "audio/x-pn-realaudio", 20},
  1552. {".doc", 4, "application/msword", 19},
  1553. {".exe", 4, "application/octet-stream", 24},
  1554. {".zip", 4, "application/x-zip-compressed", 28},
  1555. {".xls", 4, "application/excel", 17},
  1556. {".tgz", 4, "application/x-tar-gz", 20},
  1557. {".tar", 4, "application/x-tar", 17},
  1558. {".gz", 3, "application/x-gunzip", 20},
  1559. {".arj", 4, "application/x-arj-compressed", 28},
  1560. {".rar", 4, "application/x-arj-compressed", 28},
  1561. {".rtf", 4, "application/rtf", 15},
  1562. {".pdf", 4, "application/pdf", 15},
  1563. {".swf", 4, "application/x-shockwave-flash",29},
  1564. {".mpg", 4, "video/mpeg", 10},
  1565. {".mpeg", 5, "video/mpeg", 10},
  1566. {".asf", 4, "video/x-ms-asf", 14},
  1567. {".avi", 4, "video/x-msvideo", 15},
  1568. {".bmp", 4, "image/bmp", 9},
  1569. {NULL, 0, NULL, 0}
  1570. };
  1571. /*
  1572. * Look at the "path" extension and figure what mime type it has.
  1573. * Store mime type in the vector.
  1574. */
  1575. static void
  1576. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  1577. {
  1578. struct vec ext_vec, mime_vec;
  1579. const char *list, *ext;
  1580. size_t i, path_len;
  1581. path_len = strlen(path);
  1582. /*
  1583. * Scan user-defined mime types first, in case user wants to
  1584. * override default mime types.
  1585. */
  1586. (void) pthread_rwlock_rdlock(&ctx->rwlock);
  1587. list = ctx->options[OPT_MIME_TYPES];
  1588. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  1589. /* ext now points to the path suffix */
  1590. ext = path + path_len - ext_vec.len;
  1591. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  1592. *vec = mime_vec;
  1593. (void) pthread_rwlock_unlock(&ctx->rwlock);
  1594. return;
  1595. }
  1596. }
  1597. (void) pthread_rwlock_unlock(&ctx->rwlock);
  1598. /* Now scan built-in mime types */
  1599. for (i = 0; mime_types[i].extension != NULL; i++) {
  1600. ext = path + (path_len - mime_types[i].ext_len);
  1601. if (path_len > mime_types[i].ext_len &&
  1602. mg_strcasecmp(ext, mime_types[i].extension) == 0) {
  1603. vec->ptr = mime_types[i].mime_type;
  1604. vec->len = mime_types[i].mime_type_len;
  1605. return;
  1606. }
  1607. }
  1608. /* Nothing found. Fall back to text/plain */
  1609. vec->ptr = "text/plain";
  1610. vec->len = 10;
  1611. }
  1612. #ifndef HAVE_MD5
  1613. typedef struct MD5Context {
  1614. uint32_t buf[4];
  1615. uint32_t bits[2];
  1616. unsigned char in[64];
  1617. } MD5_CTX;
  1618. #if __BYTE_ORDER == 1234
  1619. #define byteReverse(buf, len) /* Nothing */
  1620. #else
  1621. /*
  1622. * Note: this code is harmless on little-endian machines.
  1623. */
  1624. static void
  1625. byteReverse(unsigned char *buf, unsigned longs)
  1626. {
  1627. uint32_t t;
  1628. do {
  1629. t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  1630. ((unsigned) buf[1] << 8 | buf[0]);
  1631. *(uint32_t *) buf = t;
  1632. buf += 4;
  1633. } while (--longs);
  1634. }
  1635. #endif /* __BYTE_ORDER */
  1636. /* The four core functions - F1 is optimized somewhat */
  1637. /* #define F1(x, y, z) (x & y | ~x & z) */
  1638. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  1639. #define F2(x, y, z) F1(z, x, y)
  1640. #define F3(x, y, z) (x ^ y ^ z)
  1641. #define F4(x, y, z) (y ^ (x | ~z))
  1642. /* This is the central step in the MD5 algorithm. */
  1643. #define MD5STEP(f, w, x, y, z, data, s) \
  1644. ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
  1645. /*
  1646. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  1647. * initialization constants.
  1648. */
  1649. static void
  1650. MD5Init(MD5_CTX *ctx)
  1651. {
  1652. ctx->buf[0] = 0x67452301;
  1653. ctx->buf[1] = 0xefcdab89;
  1654. ctx->buf[2] = 0x98badcfe;
  1655. ctx->buf[3] = 0x10325476;
  1656. ctx->bits[0] = 0;
  1657. ctx->bits[1] = 0;
  1658. }
  1659. /*
  1660. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  1661. * reflect the addition of 16 longwords of new data. MD5Update blocks
  1662. * the data and converts bytes into longwords for this routine.
  1663. */
  1664. static void
  1665. MD5Transform(uint32_t buf[4], uint32_t const in[16])
  1666. {
  1667. register uint32_t a, b, c, d;
  1668. a = buf[0];
  1669. b = buf[1];
  1670. c = buf[2];
  1671. d = buf[3];
  1672. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  1673. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  1674. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  1675. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  1676. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  1677. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  1678. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  1679. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  1680. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  1681. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  1682. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  1683. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  1684. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  1685. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  1686. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  1687. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  1688. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  1689. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  1690. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  1691. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  1692. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  1693. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  1694. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  1695. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  1696. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  1697. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  1698. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  1699. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  1700. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  1701. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  1702. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  1703. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  1704. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  1705. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  1706. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  1707. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  1708. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  1709. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  1710. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  1711. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  1712. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  1713. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  1714. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  1715. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  1716. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  1717. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  1718. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  1719. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  1720. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  1721. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  1722. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  1723. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  1724. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  1725. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  1726. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  1727. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  1728. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  1729. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  1730. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  1731. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  1732. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  1733. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  1734. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  1735. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  1736. buf[0] += a;
  1737. buf[1] += b;
  1738. buf[2] += c;
  1739. buf[3] += d;
  1740. }
  1741. /*
  1742. * Update context to reflect the concatenation of another buffer full
  1743. * of bytes.
  1744. */
  1745. static void
  1746. MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len)
  1747. {
  1748. uint32_t t;
  1749. /* Update bitcount */
  1750. t = ctx->bits[0];
  1751. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
  1752. ctx->bits[1]++; /* Carry from low to high */
  1753. ctx->bits[1] += len >> 29;
  1754. t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
  1755. /* Handle any leading odd-sized chunks */
  1756. if (t) {
  1757. unsigned char *p = (unsigned char *) ctx->in + t;
  1758. t = 64 - t;
  1759. if (len < t) {
  1760. memcpy(p, buf, len);
  1761. return;
  1762. }
  1763. memcpy(p, buf, t);
  1764. byteReverse(ctx->in, 16);
  1765. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1766. buf += t;
  1767. len -= t;
  1768. }
  1769. /* Process data in 64-byte chunks */
  1770. while (len >= 64) {
  1771. memcpy(ctx->in, buf, 64);
  1772. byteReverse(ctx->in, 16);
  1773. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1774. buf += 64;
  1775. len -= 64;
  1776. }
  1777. /* Handle any remaining bytes of data. */
  1778. memcpy(ctx->in, buf, len);
  1779. }
  1780. /*
  1781. * Final wrapup - pad to 64-byte boundary with the bit pattern
  1782. * 1 0* (64-bit count of bits processed, MSB-first)
  1783. */
  1784. static void
  1785. MD5Final(unsigned char digest[16], MD5_CTX *ctx)
  1786. {
  1787. unsigned count;
  1788. unsigned char *p;
  1789. /* Compute number of bytes mod 64 */
  1790. count = (ctx->bits[0] >> 3) & 0x3F;
  1791. /* Set the first char of padding to 0x80. This is safe since there is
  1792. always at least one byte free */
  1793. p = ctx->in + count;
  1794. *p++ = 0x80;
  1795. /* Bytes of padding needed to make 64 bytes */
  1796. count = 64 - 1 - count;
  1797. /* Pad out to 56 mod 64 */
  1798. if (count < 8) {
  1799. /* Two lots of padding: Pad the first block to 64 bytes */
  1800. memset(p, 0, count);
  1801. byteReverse(ctx->in, 16);
  1802. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1803. /* Now fill the next block with 56 bytes */
  1804. memset(ctx->in, 0, 56);
  1805. } else {
  1806. /* Pad block to 56 bytes */
  1807. memset(p, 0, count - 8);
  1808. }
  1809. byteReverse(ctx->in, 14);
  1810. /* Append length in bits and transform */
  1811. ((uint32_t *) ctx->in)[14] = ctx->bits[0];
  1812. ((uint32_t *) ctx->in)[15] = ctx->bits[1];
  1813. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1814. byteReverse((unsigned char *) ctx->buf, 4);
  1815. memcpy(digest, ctx->buf, 16);
  1816. memset((char *) ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  1817. }
  1818. #endif /* !HAVE_MD5 */
  1819. /*
  1820. * Stringify binary data. Output buffer must be twice as big as input,
  1821. * because each byte takes 2 bytes in string representation
  1822. */
  1823. static void
  1824. bin2str(char *to, const unsigned char *p, size_t len)
  1825. {
  1826. static const char *hex = "0123456789abcdef";
  1827. for (; len--; p++) {
  1828. *to++ = hex[p[0] >> 4];
  1829. *to++ = hex[p[0] & 0x0f];
  1830. }
  1831. *to = '\0';
  1832. }
  1833. /*
  1834. * Return stringified MD5 hash for list of vectors.
  1835. * buf must point to 33-bytes long buffer
  1836. */
  1837. void
  1838. mg_md5(char *buf, ...)
  1839. {
  1840. unsigned char hash[16];
  1841. const char *p;
  1842. va_list ap;
  1843. MD5_CTX ctx;
  1844. MD5Init(&ctx);
  1845. va_start(ap, buf);
  1846. while ((p = va_arg(ap, const char *)) != NULL)
  1847. MD5Update(&ctx, (unsigned char *) p, (int) strlen(p));
  1848. va_end(ap);
  1849. MD5Final(hash, &ctx);
  1850. bin2str(buf, hash, sizeof(hash));
  1851. }
  1852. /*
  1853. * Check the user's password, return 1 if OK
  1854. */
  1855. static bool_t
  1856. check_password(const char *method, const char *ha1, const char *uri,
  1857. const char *nonce, const char *nc, const char *cnonce,
  1858. const char *qop, const char *response)
  1859. {
  1860. char ha2[32 + 1], expected_response[32 + 1];
  1861. /* XXX Due to a bug in MSIE, we do not compare the URI */
  1862. /* Also, we do not check for authentication timeout */
  1863. if (/*strcmp(dig->uri, c->ouri) != 0 || */
  1864. strlen(response) != 32 /*||
  1865. now - strtoul(dig->nonce, NULL, 10) > 3600 */)
  1866. return (FALSE);
  1867. mg_md5(ha2, method, ":", uri, NULL);
  1868. mg_md5(expected_response, ha1, ":", nonce, ":", nc,
  1869. ":", cnonce, ":", qop, ":", ha2, NULL);
  1870. return (mg_strcasecmp(response, expected_response) == 0);
  1871. }
  1872. /*
  1873. * Use the global passwords file, if specified by auth_gpass option,
  1874. * or search for .htpasswd in the requested directory.
  1875. */
  1876. static FILE *
  1877. open_auth_file(struct mg_connection *conn, const char *path)
  1878. {
  1879. struct mg_context *ctx = conn->ctx;
  1880. char name[FILENAME_MAX];
  1881. const char *p, *e;
  1882. struct mgstat st;
  1883. FILE *fp;
  1884. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  1885. if (ctx->options[OPT_AUTH_GPASSWD] != NULL) {
  1886. /* Use global passwords file */
  1887. fp = mg_fopen(ctx->options[OPT_AUTH_GPASSWD], "r");
  1888. if (fp == NULL)
  1889. cry(fc(ctx), "fopen(%s): %s",
  1890. ctx->options[OPT_AUTH_GPASSWD], strerror(ERRNO));
  1891. } else if (!mg_stat(path, &st) && st.is_directory) {
  1892. (void) mg_snprintf(conn, name, sizeof(name), "%s%c%s",
  1893. path, DIRSEP, PASSWORDS_FILE_NAME);
  1894. fp = mg_fopen(name, "r");
  1895. } else {
  1896. /*
  1897. * Try to find .htpasswd in requested directory.
  1898. * Given the path, create the path to .htpasswd file
  1899. * in the same directory. Find the right-most
  1900. * directory separator character first. That would be the
  1901. * directory name. If directory separator character is not
  1902. * found, 'e' will point to 'p'.
  1903. */
  1904. for (p = path, e = p + strlen(p) - 1; e > p; e--)
  1905. if (IS_DIRSEP_CHAR(*e))
  1906. break;
  1907. /*
  1908. * Make up the path by concatenating directory name and
  1909. * .htpasswd file name.
  1910. */
  1911. (void) mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
  1912. (int) (e - p), p, DIRSEP, PASSWORDS_FILE_NAME);
  1913. fp = mg_fopen(name, "r");
  1914. }
  1915. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  1916. return (fp);
  1917. }
  1918. /*
  1919. * Parsed Authorization: header
  1920. */
  1921. struct ah {
  1922. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  1923. };
  1924. static bool_t
  1925. parse_auth_header(struct mg_connection *conn, char *buf, size_t buf_size,
  1926. struct ah *ah)
  1927. {
  1928. char *name, *value, *s;
  1929. const char *auth_header;
  1930. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  1931. mg_strncasecmp(auth_header, "Digest ", 7) != 0)
  1932. return (FALSE);
  1933. /* Make modifiable copy of the auth header */
  1934. (void) mg_strlcpy(buf, auth_header + 7, buf_size);
  1935. s = buf;
  1936. (void) memset(ah, 0, sizeof(*ah));
  1937. /* Gobble initial spaces */
  1938. while (isspace(* (unsigned char *) s))
  1939. s++;
  1940. /* Parse authorization header */
  1941. for (;;) {
  1942. name = skip(&s, "=");
  1943. value = skip(&s, " ");
  1944. /* Handle commas: Digest username="a", realm="b", ...*/
  1945. if (value[strlen(value) - 1] == ',')
  1946. value[strlen(value) - 1] = '\0';
  1947. /* Trim double quotes around values */
  1948. if (*value == '"') {
  1949. value++;
  1950. value[strlen(value) - 1] = '\0';
  1951. } else if (*value == '\0') {
  1952. break;
  1953. }
  1954. if (!strcmp(name, "username")) {
  1955. ah->user = value;
  1956. } else if (!strcmp(name, "cnonce")) {
  1957. ah->cnonce = value;
  1958. } else if (!strcmp(name, "response")) {
  1959. ah->response = value;
  1960. } else if (!strcmp(name, "uri")) {
  1961. ah->uri = value;
  1962. } else if (!strcmp(name, "qop")) {
  1963. ah->qop = value;
  1964. } else if (!strcmp(name, "nc")) {
  1965. ah->nc = value;
  1966. } else if (!strcmp(name, "nonce")) {
  1967. ah->nonce = value;
  1968. }
  1969. }
  1970. /* CGI needs it as REMOTE_USER */
  1971. if (ah->user != NULL)
  1972. conn->request_info.remote_user = mg_strdup(ah->user);
  1973. return (TRUE);
  1974. }
  1975. /*
  1976. * Authorize against the opened passwords file. Return 1 if authorized.
  1977. */
  1978. static bool_t
  1979. authorize(struct mg_connection *conn, FILE *fp)
  1980. {
  1981. struct ah ah;
  1982. char line[256], f_user[256], domain[256], ha1[256],
  1983. f_domain[256], buf[MAX_REQUEST_SIZE];
  1984. if (!parse_auth_header(conn, buf, sizeof(buf), &ah))
  1985. return (FALSE);
  1986. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  1987. mg_strlcpy(domain, conn->ctx->options[OPT_AUTH_DOMAIN], sizeof(domain));
  1988. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  1989. /* Loop over passwords file */
  1990. while (fgets(line, sizeof(line), fp) != NULL) {
  1991. if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3)
  1992. continue;
  1993. if (!strcmp(ah.user, f_user) && !strcmp(domain, f_domain))
  1994. return (check_password(
  1995. conn->request_info.request_method,
  1996. ha1, ah.uri, ah.nonce, ah.nc, ah.cnonce, ah.qop,
  1997. ah.response));
  1998. }
  1999. return (FALSE);
  2000. }
  2001. /*
  2002. * Return TRUE if request is authorised, FALSE otherwise.
  2003. */
  2004. static bool_t
  2005. check_authorization(struct mg_connection *conn, const char *path)
  2006. {
  2007. FILE *fp;
  2008. char fname[FILENAME_MAX];
  2009. struct vec uri_vec, filename_vec;
  2010. const char *list;
  2011. bool_t authorized;
  2012. fp = NULL;
  2013. authorized = TRUE;
  2014. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2015. list = conn->ctx->options[OPT_PROTECT];
  2016. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  2017. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  2018. (void) mg_snprintf(conn, fname, sizeof(fname), "%.*s",
  2019. filename_vec.len, filename_vec.ptr);
  2020. if ((fp = mg_fopen(fname, "r")) == NULL)
  2021. cry(conn, "%s: cannot open %s: %s",
  2022. __func__, fname, strerror(errno));
  2023. break;
  2024. }
  2025. }
  2026. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2027. if (fp == NULL)
  2028. fp = open_auth_file(conn, path);
  2029. if (fp != NULL) {
  2030. authorized = authorize(conn, fp);
  2031. (void) fclose(fp);
  2032. }
  2033. return (authorized);
  2034. }
  2035. static void
  2036. send_authorization_request(struct mg_connection *conn)
  2037. {
  2038. char domain[128];
  2039. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2040. mg_strlcpy(domain, conn->ctx->options[OPT_AUTH_DOMAIN], sizeof(domain));
  2041. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2042. conn->request_info.status_code = 401;
  2043. (void) mg_printf(conn,
  2044. "HTTP/1.1 401 Unauthorized\r\n"
  2045. "WWW-Authenticate: Digest qop=\"auth\", "
  2046. "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
  2047. domain, (unsigned long) time(NULL));
  2048. }
  2049. static bool_t
  2050. is_authorized_for_put(struct mg_connection *conn)
  2051. {
  2052. FILE *fp;
  2053. int ret = FALSE;
  2054. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2055. fp = conn->ctx->options[OPT_AUTH_PUT] == NULL ? NULL :
  2056. mg_fopen(conn->ctx->options[OPT_AUTH_PUT], "r");
  2057. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2058. if (fp != NULL) {
  2059. ret = authorize(conn, fp);
  2060. (void) fclose(fp);
  2061. }
  2062. return (ret);
  2063. }
  2064. enum mg_error_t
  2065. mg_modify_passwords_file(struct mg_context *ctx, const char *fname,
  2066. const char *user, const char *pass)
  2067. {
  2068. int found;
  2069. char line[512], u[512], d[512], domain[512],
  2070. ha1[33], tmp[FILENAME_MAX];
  2071. FILE *fp, *fp2;
  2072. found = 0;
  2073. fp = fp2 = NULL;
  2074. (void) pthread_rwlock_rdlock(&ctx->rwlock);
  2075. mg_strlcpy(domain, ctx->options[OPT_AUTH_DOMAIN], sizeof(domain));
  2076. (void) pthread_rwlock_unlock(&ctx->rwlock);
  2077. /* Regard empty password as no password - remove user record. */
  2078. if (pass[0] == '\0')
  2079. pass = NULL;
  2080. (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);
  2081. /* Create the file if does not exist */
  2082. if ((fp = mg_fopen(fname, "a+")) != NULL)
  2083. (void) fclose(fp);
  2084. /* Open the given file and temporary file */
  2085. if ((fp = mg_fopen(fname, "r")) == NULL) {
  2086. cry(fc(ctx), "Cannot open %s: %s", fname, strerror(errno));
  2087. return (MG_ERROR);
  2088. } else if ((fp2 = mg_fopen(tmp, "w+")) == NULL) {
  2089. cry(fc(ctx), "Cannot open %s: %s", tmp, strerror(errno));
  2090. return (MG_ERROR);
  2091. }
  2092. /* Copy the stuff to temporary file */
  2093. while (fgets(line, sizeof(line), fp) != NULL) {
  2094. if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2)
  2095. continue;
  2096. if (!strcmp(u, user) && !strcmp(d, domain)) {
  2097. found++;
  2098. if (pass != NULL) {
  2099. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2100. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2101. }
  2102. } else {
  2103. (void) fprintf(fp2, "%s", line);
  2104. }
  2105. }
  2106. /* If new user, just add it */
  2107. if (!found && pass != NULL) {
  2108. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2109. (void) fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2110. }
  2111. /* Close files */
  2112. (void) fclose(fp);
  2113. (void) fclose(fp2);
  2114. /* Put the temp file in place of real file */
  2115. (void) mg_remove(fname);
  2116. (void) mg_rename(tmp, fname);
  2117. return (MG_SUCCESS);
  2118. }
  2119. struct de {
  2120. struct mg_connection *conn;
  2121. char *file_name;
  2122. struct mgstat st;
  2123. };
  2124. static void
  2125. url_encode(const char *src, char *dst, size_t dst_len)
  2126. {
  2127. const char *dont_escape = "._-$,;~()";
  2128. const char *hex = "0123456789abcdef";
  2129. const char *end = dst + dst_len - 1;
  2130. for (; *src != '\0' && dst < end; src++, dst++) {
  2131. if (isalnum(*(unsigned char *) src) ||
  2132. strchr(dont_escape, * (unsigned char *) src) != NULL) {
  2133. *dst = *src;
  2134. } else if (dst + 2 < end) {
  2135. dst[0] = '%';
  2136. dst[1] = hex[(* (unsigned char *) src) >> 4];
  2137. dst[2] = hex[(* (unsigned char *) src) & 0xf];
  2138. dst += 2;
  2139. }
  2140. }
  2141. *dst = '\0';
  2142. }
  2143. /*
  2144. * This function is called from send_directory() and prints out
  2145. * single directory entry.
  2146. */
  2147. static void
  2148. print_dir_entry(struct de *de)
  2149. {
  2150. char size[64], mod[64], href[FILENAME_MAX];
  2151. if (de->st.is_directory) {
  2152. (void) mg_snprintf(de->conn,
  2153. size, sizeof(size), "%s", "[DIRECTORY]");
  2154. } else {
  2155. /*
  2156. * We use (signed) cast below because MSVC 6 compiler cannot
  2157. * convert unsigned __int64 to double. Sigh.
  2158. */
  2159. if (de->st.size < 1024)
  2160. (void) mg_snprintf(de->conn, size, sizeof(size),
  2161. "%lu", (unsigned long) de->st.size);
  2162. else if (de->st.size < 1024 * 1024)
  2163. (void) mg_snprintf(de->conn, size, sizeof(size),
  2164. "%.1fk", (double) de->st.size / 1024.0);
  2165. else if (de->st.size < 1024 * 1024 * 1024)
  2166. (void) mg_snprintf(de->conn, size, sizeof(size),
  2167. "%.1fM", (double) de->st.size / 1048576);
  2168. else
  2169. (void) mg_snprintf(de->conn, size, sizeof(size),
  2170. "%.1fG", (double) de->st.size / 1073741824);
  2171. }
  2172. (void) strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M",
  2173. localtime(&de->st.mtime));
  2174. url_encode(de->file_name, href, sizeof(href));
  2175. de->conn->num_bytes_sent += mg_printf(de->conn,
  2176. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  2177. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2178. de->conn->request_info.uri, href, de->st.is_directory ? "/" : "",
  2179. de->file_name, de->st.is_directory ? "/" : "", mod, size);
  2180. }
  2181. /*
  2182. * This function is called from send_directory() and used for
  2183. * sorting direcotory entries by size, or name, or modification time.
  2184. */
  2185. static int
  2186. compare_dir_entries(const void *p1, const void *p2)
  2187. {
  2188. const struct de *a = (struct de *) p1, *b = (struct de *) p2;
  2189. const char *query_string = a->conn->request_info.query_string;
  2190. int cmp_result = 0;
  2191. if (query_string == NULL)
  2192. query_string = "na";
  2193. if (a->st.is_directory && !b->st.is_directory) {
  2194. return (-1); /* Always put directories on top */
  2195. } else if (!a->st.is_directory && b->st.is_directory) {
  2196. return (1); /* Always put directories on top */
  2197. } else if (*query_string == 'n') {
  2198. cmp_result = strcmp(a->file_name, b->file_name);
  2199. } else if (*query_string == 's') {
  2200. cmp_result = a->st.size == b->st.size ? 0 :
  2201. a->st.size > b->st.size ? 1 : -1;
  2202. } else if (*query_string == 'd') {
  2203. cmp_result = a->st.mtime == b->st.mtime ? 0 :
  2204. a->st.mtime > b->st.mtime ? 1 : -1;
  2205. }
  2206. return (query_string[1] == 'd' ? -cmp_result : cmp_result);
  2207. }
  2208. /*
  2209. * Send directory contents.
  2210. */
  2211. static void
  2212. send_directory(struct mg_connection *conn, const char *dir)
  2213. {
  2214. struct dirent *dp;
  2215. DIR *dirp;
  2216. struct de *entries = NULL;
  2217. char path[FILENAME_MAX];
  2218. int i, sort_direction, num_entries = 0, arr_size = 128;
  2219. if ((dirp = opendir(dir)) == NULL) {
  2220. send_error(conn, 500, "Cannot open directory",
  2221. "Error: opendir(%s): %s", path, strerror(ERRNO));
  2222. return;
  2223. }
  2224. (void) mg_printf(conn, "%s",
  2225. "HTTP/1.1 200 OK\r\n"
  2226. "Connection: close\r\n"
  2227. "Content-Type: text/html; charset=utf-8\r\n\r\n");
  2228. sort_direction = conn->request_info.query_string != NULL &&
  2229. conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
  2230. while ((dp = readdir(dirp)) != NULL) {
  2231. /* Do not show current dir and passwords file */
  2232. if (!strcmp(dp->d_name, ".") ||
  2233. !strcmp(dp->d_name, "..") ||
  2234. !strcmp(dp->d_name, PASSWORDS_FILE_NAME))
  2235. continue;
  2236. if (entries == NULL || num_entries >= arr_size) {
  2237. arr_size *= 2;
  2238. entries = (struct de *) realloc(entries,
  2239. arr_size * sizeof(entries[0]));
  2240. }
  2241. if (entries == NULL) {
  2242. send_error(conn, 500, "Cannot open directory",
  2243. "%s", "Error: cannot allocate memory");
  2244. return;
  2245. }
  2246. (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
  2247. dir, DIRSEP, dp->d_name);
  2248. /*
  2249. * If we don't memset stat structure to zero, mtime will have
  2250. * garbage and strftime() will segfault later on in
  2251. * print_dir_entry(). memset is required only if mg_stat()
  2252. * fails. For more details, see
  2253. * http://code.google.com/p/mongoose/issues/detail?id=79
  2254. */
  2255. if (mg_stat(path, &entries[num_entries].st) != 0)
  2256. (void) memset(&entries[num_entries].st, 0,
  2257. sizeof(entries[num_entries].st));
  2258. entries[num_entries].conn = conn;
  2259. entries[num_entries].file_name = mg_strdup(dp->d_name);
  2260. num_entries++;
  2261. }
  2262. (void) closedir(dirp);
  2263. conn->num_bytes_sent += mg_printf(conn,
  2264. "<html><head><title>Index of %s</title>"
  2265. "<style>th {text-align: left;}</style></head>"
  2266. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  2267. "<tr><th><a href=\"?n%c\">Name</a></th>"
  2268. "<th><a href=\"?d%c\">Modified</a></th>"
  2269. "<th><a href=\"?s%c\">Size</a></th></tr>"
  2270. "<tr><td colspan=\"3\"><hr></td></tr>",
  2271. conn->request_info.uri, conn->request_info.uri,
  2272. sort_direction, sort_direction, sort_direction);
  2273. /* Print first entry - link to a parent directory */
  2274. conn->num_bytes_sent += mg_printf(conn,
  2275. "<tr><td><a href=\"%s%s\">%s</a></td>"
  2276. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2277. conn->request_info.uri, "..", "Parent directory", "-", "-");
  2278. /* Sort and print directory entries */
  2279. qsort(entries, num_entries, sizeof(entries[0]), compare_dir_entries);
  2280. for (i = 0; i < num_entries; i++) {
  2281. print_dir_entry(&entries[i]);
  2282. free(entries[i].file_name);
  2283. }
  2284. free(entries);
  2285. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  2286. conn->request_info.status_code = 200;
  2287. }
  2288. /*
  2289. * Send len bytes from the opened file to the client.
  2290. */
  2291. static void
  2292. send_opened_file_stream(struct mg_connection *conn, FILE *fp, int64_t len)
  2293. {
  2294. char buf[BUFSIZ];
  2295. int to_read, num_read, num_written;
  2296. while (len > 0) {
  2297. /* Calculate how much to read from the file in the buffer */
  2298. to_read = sizeof(buf);
  2299. if ((int64_t) to_read > len)
  2300. to_read = (int) len;
  2301. /* Read from file, exit the loop on error */
  2302. if ((num_read = fread(buf, 1, to_read, fp)) == 0)
  2303. break;
  2304. /* Send read bytes to the client, exit the loop on error */
  2305. if ((num_written = mg_write(conn, buf, num_read)) != num_read)
  2306. break;
  2307. /* Both read and were successful, adjust counters */
  2308. conn->num_bytes_sent += num_written;
  2309. len -= num_written;
  2310. }
  2311. }
  2312. static int
  2313. parse_range_header(const char *header, int64_t *a, int64_t *b)
  2314. {
  2315. return sscanf(header, "bytes=%" INT64_FMT "u-%" INT64_FMT "u", a, b);
  2316. }
  2317. /*
  2318. * Send regular file contents.
  2319. */
  2320. static void
  2321. send_file(struct mg_connection *conn, const char *path, struct mgstat *stp)
  2322. {
  2323. char date[64], lm[64], etag[64], range[64];
  2324. const char *fmt = "%a, %d %b %Y %H:%M:%S %Z", *msg = "OK", *hdr;
  2325. time_t curtime = time(NULL);
  2326. int64_t cl, r1, r2;
  2327. struct vec mime_vec;
  2328. FILE *fp;
  2329. int n;
  2330. get_mime_type(conn->ctx, path, &mime_vec);
  2331. cl = stp->size;
  2332. conn->request_info.status_code = 200;
  2333. range[0] = '\0';
  2334. if ((fp = mg_fopen(path, "rb")) == NULL) {
  2335. send_error(conn, 500, http_500_error,
  2336. "fopen(%s): %s", path, strerror(ERRNO));
  2337. return;
  2338. }
  2339. set_close_on_exec(fileno(fp));
  2340. /* If Range: header specified, act accordingly */
  2341. r1 = r2 = 0;
  2342. hdr = mg_get_header(conn, "Range");
  2343. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0) {
  2344. conn->request_info.status_code = 206;
  2345. (void) fseeko(fp, (off_t) r1, SEEK_SET);
  2346. cl = n == 2 ? r2 - r1 + 1: cl - r1;
  2347. (void) mg_snprintf(conn, range, sizeof(range),
  2348. "Content-Range: bytes "
  2349. "%" INT64_FMT "-%"
  2350. INT64_FMT "/%" INT64_FMT "\r\n",
  2351. r1, r1 + cl - 1, stp->size);
  2352. msg = "Partial Content";
  2353. }
  2354. /* Prepare Etag, Date, Last-Modified headers */
  2355. (void) strftime(date, sizeof(date), fmt, localtime(&curtime));
  2356. (void) strftime(lm, sizeof(lm), fmt, localtime(&stp->mtime));
  2357. (void) mg_snprintf(conn, etag, sizeof(etag), "%lx.%lx",
  2358. (unsigned long) stp->mtime, (unsigned long) stp->size);
  2359. (void) mg_printf(conn,
  2360. "HTTP/1.1 %d %s\r\n"
  2361. "Date: %s\r\n"
  2362. "Last-Modified: %s\r\n"
  2363. "Etag: \"%s\"\r\n"
  2364. "Content-Type: %.*s\r\n"
  2365. "Content-Length: %" INT64_FMT "\r\n"
  2366. "Connection: close\r\n"
  2367. "Accept-Ranges: bytes\r\n"
  2368. "%s\r\n",
  2369. conn->request_info.status_code, msg, date, lm, etag,
  2370. mime_vec.len, mime_vec.ptr, cl, range);
  2371. if (strcmp(conn->request_info.request_method, "HEAD") != 0)
  2372. send_opened_file_stream(conn, fp, cl);
  2373. (void) fclose(fp);
  2374. }
  2375. /*
  2376. * Parse HTTP headers from the given buffer, advance buffer to the point
  2377. * where parsing stopped.
  2378. */
  2379. static void
  2380. parse_http_headers(char **buf, struct mg_request_info *ri)
  2381. {
  2382. int i;
  2383. for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
  2384. ri->http_headers[i].name = skip(buf, ": ");
  2385. ri->http_headers[i].value = skip(buf, "\r\n");
  2386. if (ri->http_headers[i].name[0] == '\0')
  2387. break;
  2388. ri->num_headers = i + 1;
  2389. }
  2390. }
  2391. static bool_t
  2392. is_valid_http_method(const char *method)
  2393. {
  2394. return (!strcmp(method, "GET") ||
  2395. !strcmp(method, "POST") ||
  2396. !strcmp(method, "HEAD") ||
  2397. !strcmp(method, "PUT") ||
  2398. !strcmp(method, "DELETE"));
  2399. }
  2400. /*
  2401. * Parse HTTP request, fill in mg_request_info structure.
  2402. */
  2403. static bool_t
  2404. parse_http_request(char *buf, struct mg_request_info *ri)
  2405. {
  2406. int success_code = FALSE;
  2407. ri->request_method = skip(&buf, " ");
  2408. ri->uri = skip(&buf, " ");
  2409. ri->http_version = skip(&buf, "\r\n");
  2410. if (is_valid_http_method(ri->request_method) &&
  2411. ri->uri[0] == '/' &&
  2412. strncmp(ri->http_version, "HTTP/", 5) == 0) {
  2413. ri->http_version += 5; /* Skip "HTTP/" */
  2414. parse_http_headers(&buf, ri);
  2415. success_code = TRUE;
  2416. }
  2417. return (success_code);
  2418. }
  2419. /*
  2420. * Keep reading the input (either opened file descriptor fd, or socket sock,
  2421. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  2422. * buffer (which marks the end of HTTP request). Buffer buf may already
  2423. * have some data. The length of the data is stored in nread.
  2424. * Upon every read operation, increase nread by the number of bytes read.
  2425. */
  2426. static int
  2427. read_request(FILE *fp, SOCKET sock, SSL *ssl, char *buf, int bufsiz, int *nread)
  2428. {
  2429. int n, request_len;
  2430. request_len = 0;
  2431. while (*nread < bufsiz && request_len == 0) {
  2432. n = pull(fp, sock, ssl, buf + *nread, bufsiz - *nread);
  2433. if (n <= 0) {
  2434. break;
  2435. } else {
  2436. *nread += n;
  2437. request_len = get_request_len(buf, (size_t) *nread);
  2438. }
  2439. }
  2440. return (request_len);
  2441. }
  2442. /*
  2443. * For given directory path, substitute it to valid index file.
  2444. * Return 0 if index file has been found, -1 if not found.
  2445. * If the file is found, it's stats is returned in stp.
  2446. */
  2447. static bool_t
  2448. substitute_index_file(struct mg_connection *conn,
  2449. char *path, size_t path_len, struct mgstat *stp)
  2450. {
  2451. const char *list;
  2452. struct mgstat st;
  2453. struct vec filename_vec;
  2454. size_t n;
  2455. bool_t found;
  2456. n = strlen(path);
  2457. /*
  2458. * The 'path' given to us points to the directory. Remove all trailing
  2459. * directory separator characters from the end of the path, and
  2460. * then append single directory separator character.
  2461. */
  2462. while (n > 0 && IS_DIRSEP_CHAR(path[n - 1]))
  2463. n--;
  2464. path[n] = DIRSEP;
  2465. /*
  2466. * Traverse index files list. For each entry, append it to the given
  2467. * path and see if the file exists. If it exists, break the loop
  2468. */
  2469. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2470. list = conn->ctx->options[OPT_INDEX_FILES];
  2471. found = FALSE;
  2472. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  2473. /* Ignore too long entries that may overflow path buffer */
  2474. if (filename_vec.len > path_len - n)
  2475. continue;
  2476. /* Prepare full path to the index file */
  2477. (void) mg_strlcpy(path + n + 1,
  2478. filename_vec.ptr, filename_vec.len + 1);
  2479. /* Does it exist ? */
  2480. if (mg_stat(path, &st) == 0) {
  2481. /* Yes it does, break the loop */
  2482. *stp = st;
  2483. found = TRUE;
  2484. break;
  2485. }
  2486. }
  2487. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2488. /* If no index file exists, restore directory path */
  2489. if (found == FALSE)
  2490. path[n] = '\0';
  2491. return (found);
  2492. }
  2493. /*
  2494. * Return True if we should reply 304 Not Modified.
  2495. */
  2496. static bool_t
  2497. is_not_modified(const struct mg_connection *conn, const struct mgstat *stp)
  2498. {
  2499. const char *ims = mg_get_header(conn, "If-Modified-Since");
  2500. return FALSE;
  2501. return (ims != NULL && stp->mtime <= date_to_epoch(ims));
  2502. }
  2503. static bool_t
  2504. append_chunk(struct mg_request_info *ri, FILE *fp, const char *buf, int len)
  2505. {
  2506. bool_t ret_code = TRUE;
  2507. if (fp == NULL) {
  2508. /* TODO: check for NULL here */
  2509. ri->post_data = (char *) realloc(ri->post_data,
  2510. ri->post_data_len + len);
  2511. (void) memcpy(ri->post_data + ri->post_data_len, buf, len);
  2512. ri->post_data_len += len;
  2513. } else if (push(fp, INVALID_SOCKET,
  2514. NULL, buf, (int64_t) len) != (int64_t) len) {
  2515. ret_code = FALSE;
  2516. }
  2517. return (ret_code);
  2518. }
  2519. static bool_t
  2520. handle_request_body(struct mg_connection *conn, FILE *fp)
  2521. {
  2522. struct mg_request_info *ri = &conn->request_info;
  2523. const char *expect, *tmp;
  2524. int64_t content_len;
  2525. char buf[BUFSIZ];
  2526. int to_read, nread, already_read;
  2527. bool_t success_code = FALSE;
  2528. content_len = get_content_length(conn);
  2529. expect = mg_get_header(conn, "Expect");
  2530. if (content_len == -1) {
  2531. send_error(conn, 411, "Length Required", "");
  2532. } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
  2533. send_error(conn, 417, "Expectation Failed", "");
  2534. } else {
  2535. if (expect != NULL)
  2536. (void) mg_printf(conn, "HTTP/1.1 100 Continue\r\n\r\n");
  2537. already_read = ri->post_data_len;
  2538. assert(already_read >= 0);
  2539. if (content_len <= (int64_t) already_read) {
  2540. ri->post_data_len = (int) content_len;
  2541. /*
  2542. * If fp is NULL, this is embedded mode, and we do not
  2543. * have to do anything: POST data is already there,
  2544. * no need to allocate a buffer and copy it in.
  2545. * If fp != NULL, we need to write the data.
  2546. */
  2547. success_code = fp == NULL || (push(fp, INVALID_SOCKET,
  2548. NULL, ri->post_data, content_len) == content_len) ?
  2549. TRUE : FALSE;
  2550. } else {
  2551. if (fp == NULL) {
  2552. conn->free_post_data = TRUE;
  2553. tmp = ri->post_data;
  2554. /* +1 in case if already_read == 0 */
  2555. ri->post_data = (char*)malloc(already_read + 1);
  2556. (void) memcpy(ri->post_data, tmp, already_read);
  2557. } else {
  2558. (void) push(fp, INVALID_SOCKET, NULL,
  2559. ri->post_data, (int64_t) already_read);
  2560. }
  2561. content_len -= already_read;
  2562. while (content_len > 0) {
  2563. to_read = sizeof(buf);
  2564. if ((int64_t) to_read > content_len)
  2565. to_read = (int) content_len;
  2566. nread = pull(NULL, conn->client.sock,
  2567. conn->ssl, buf, to_read);
  2568. if (nread <= 0)
  2569. break;
  2570. if (!append_chunk(ri, fp, buf, nread))
  2571. break;
  2572. content_len -= nread;
  2573. }
  2574. success_code = content_len == 0 ? TRUE : FALSE;
  2575. }
  2576. /* Each error code path in this function must send an error */
  2577. if (success_code != TRUE)
  2578. send_error(conn, 577, http_500_error,
  2579. "%s", "Error handling body data");
  2580. }
  2581. return (success_code);
  2582. }
  2583. #if !defined(NO_CGI)
  2584. /*
  2585. * This structure helps to create an environment for the spawned CGI program.
  2586. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  2587. * last element must be NULL.
  2588. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  2589. * strings must reside in a contiguous buffer. The end of the buffer is
  2590. * marked by two '\0' characters.
  2591. * We satisfy both worlds: we create an envp array (which is vars), all
  2592. * entries are actually pointers inside buf.
  2593. */
  2594. struct cgi_env_block {
  2595. struct mg_connection *conn;
  2596. char buf[CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
  2597. int len; /* Space taken */
  2598. char *vars[MAX_CGI_ENVIR_VARS]; /* char **envp */
  2599. int nvars; /* Number of variables */
  2600. };
  2601. /*
  2602. * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  2603. * pointer into the vars array.
  2604. */
  2605. static char *
  2606. addenv(struct cgi_env_block *block, const char *fmt, ...)
  2607. {
  2608. int n, space;
  2609. char *added;
  2610. va_list ap;
  2611. /* Calculate how much space is left in the buffer */
  2612. space = sizeof(block->buf) - block->len - 2;
  2613. assert(space >= 0);
  2614. /* Make a pointer to the free space int the buffer */
  2615. added = block->buf + block->len;
  2616. /* Copy VARIABLE=VALUE\0 string into the free space */
  2617. va_start(ap, fmt);
  2618. n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
  2619. va_end(ap);
  2620. /* Make sure we do not overflow buffer and the envp array */
  2621. if (n > 0 && n < space &&
  2622. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  2623. /* Append a pointer to the added string into the envp array */
  2624. block->vars[block->nvars++] = block->buf + block->len;
  2625. /* Bump up used length counter. Include \0 terminator */
  2626. block->len += n + 1;
  2627. }
  2628. return (added);
  2629. }
  2630. static void
  2631. prepare_cgi_environment(struct mg_connection *conn, const char *prog,
  2632. struct cgi_env_block *blk)
  2633. {
  2634. const char *s, *script_filename, *slash;
  2635. struct vec var_vec;
  2636. char *p;
  2637. int i;
  2638. blk->len = blk->nvars = 0;
  2639. blk->conn = conn;
  2640. /* SCRIPT_FILENAME */
  2641. script_filename = prog;
  2642. if ((s = strrchr(prog, '/')) != NULL)
  2643. script_filename = s + 1;
  2644. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2645. addenv(blk, "SERVER_NAME=%s", conn->ctx->options[OPT_AUTH_DOMAIN]);
  2646. addenv(blk, "SERVER_ROOT=%s", conn->ctx->options[OPT_ROOT]);
  2647. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->options[OPT_ROOT]);
  2648. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2649. /* Prepare the environment block */
  2650. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  2651. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  2652. addenv(blk, "%s", "REDIRECT_STATUS=200"); /* PHP */
  2653. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.u.sin.sin_port));
  2654. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  2655. addenv(blk, "REMOTE_ADDR=%s",
  2656. inet_ntoa(conn->client.rsa.u.sin.sin_addr));
  2657. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  2658. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  2659. slash = strrchr(conn->request_info.uri, '/');
  2660. addenv(blk, "SCRIPT_NAME=%.*s%s",
  2661. (slash - conn->request_info.uri) + 1, conn->request_info.uri,
  2662. script_filename);
  2663. addenv(blk, "SCRIPT_FILENAME=%s", script_filename); /* PHP */
  2664. addenv(blk, "PATH_TRANSLATED=%s", prog);
  2665. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  2666. if ((s = mg_get_header(conn, "Content-Type")) != NULL)
  2667. addenv(blk, "CONTENT_TYPE=%s", s);
  2668. if (conn->request_info.query_string != NULL)
  2669. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  2670. if ((s = mg_get_header(conn, "Content-Length")) != NULL)
  2671. addenv(blk, "CONTENT_LENGTH=%s", s);
  2672. if ((s = getenv("PATH")) != NULL)
  2673. addenv(blk, "PATH=%s", s);
  2674. #if defined(_WIN32)
  2675. if ((s = getenv("COMSPEC")) != NULL)
  2676. addenv(blk, "COMSPEC=%s", s);
  2677. if ((s = getenv("SYSTEMROOT")) != NULL)
  2678. addenv(blk, "SYSTEMROOT=%s", s);
  2679. #else
  2680. if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
  2681. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  2682. #endif /* _WIN32 */
  2683. if ((s = getenv("PERLLIB")) != NULL)
  2684. addenv(blk, "PERLLIB=%s", s);
  2685. if (conn->request_info.remote_user != NULL) {
  2686. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  2687. addenv(blk, "%s", "AUTH_TYPE=Digest");
  2688. }
  2689. /* Add all headers as HTTP_* variables */
  2690. for (i = 0; i < conn->request_info.num_headers; i++) {
  2691. p = addenv(blk, "HTTP_%s=%s",
  2692. conn->request_info.http_headers[i].name,
  2693. conn->request_info.http_headers[i].value);
  2694. /* Convert variable name into uppercase, and change - to _ */
  2695. for (; *p != '=' && *p != '\0'; p++) {
  2696. if (*p == '-')
  2697. *p = '_';
  2698. *p = (char) toupper(* (unsigned char *) p);
  2699. }
  2700. }
  2701. /* Add user-specified variables */
  2702. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2703. s = conn->ctx->options[OPT_CGI_ENV];
  2704. while ((s = next_option(s, &var_vec, NULL)) != NULL)
  2705. addenv(blk, "%.*s", var_vec.len, var_vec.ptr);
  2706. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2707. blk->vars[blk->nvars++] = NULL;
  2708. blk->buf[blk->len++] = '\0';
  2709. assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  2710. assert(blk->len > 0);
  2711. assert(blk->len < (int) sizeof(blk->buf));
  2712. }
  2713. static void
  2714. send_cgi(struct mg_connection *conn, const char *prog)
  2715. {
  2716. int headers_len, data_len, i;
  2717. const char *status;
  2718. char buf[MAX_REQUEST_SIZE], *pbuf;
  2719. struct mg_request_info ri;
  2720. struct cgi_env_block blk;
  2721. char dir[FILENAME_MAX], *p;
  2722. int fd_stdin[2], fd_stdout[2];
  2723. FILE *in, *out;
  2724. pid_t pid;
  2725. prepare_cgi_environment(conn, prog, &blk);
  2726. /* CGI must be executed in its own directory */
  2727. (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  2728. if ((p = strrchr(dir, DIRSEP)) != NULL)
  2729. *p++ = '\0';
  2730. pid = (pid_t) -1;
  2731. fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1;
  2732. in = out = NULL;
  2733. if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) {
  2734. send_error(conn, 500, http_500_error,
  2735. "Cannot create CGI pipe: %s", strerror(ERRNO));
  2736. goto done;
  2737. } else if ((pid = spawn_process(conn, p, blk.buf, blk.vars,
  2738. fd_stdin[0], fd_stdout[1], dir)) == (pid_t) -1) {
  2739. goto done;
  2740. } else if ((in = fdopen(fd_stdin[1], "wb")) == NULL ||
  2741. (out = fdopen(fd_stdout[0], "rb")) == NULL) {
  2742. send_error(conn, 500, http_500_error,
  2743. "fopen: %s", strerror(ERRNO));
  2744. goto done;
  2745. }
  2746. setbuf(in, NULL);
  2747. setbuf(out, NULL);
  2748. /*
  2749. * spawn_process() must close those!
  2750. * If we don't mark them as closed, close() attempt before
  2751. * return from this function throws an exception on Windows.
  2752. * Windows does not like when closed descriptor is closed again.
  2753. */
  2754. fd_stdin[0] = fd_stdout[1] = -1;
  2755. /* Send POST data to the CGI process if needed */
  2756. if (!strcmp(conn->request_info.request_method, "POST") &&
  2757. !handle_request_body(conn, in)) {
  2758. goto done;
  2759. }
  2760. /*
  2761. * Now read CGI reply into a buffer. We need to set correct
  2762. * status code, thus we need to see all HTTP headers first.
  2763. * Do not send anything back to client, until we buffer in all
  2764. * HTTP headers.
  2765. */
  2766. data_len = 0;
  2767. headers_len = read_request(out, INVALID_SOCKET, NULL,
  2768. buf, sizeof(buf), &data_len);
  2769. if (headers_len <= 0) {
  2770. send_error(conn, 500, http_500_error,
  2771. "CGI program sent malformed HTTP headers: [%.*s]",
  2772. data_len, buf);
  2773. goto done;
  2774. }
  2775. pbuf = buf;
  2776. buf[headers_len - 1] = '\0';
  2777. parse_http_headers(&pbuf, &ri);
  2778. /* Make up and send the status line */
  2779. status = get_header(&ri, "Status");
  2780. conn->request_info.status_code = status == NULL ? 200 : atoi(status);
  2781. (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n",
  2782. conn->request_info.status_code);
  2783. /* Send headers */
  2784. for (i = 0; i < ri.num_headers; i++)
  2785. (void) mg_printf(conn, "%s: %s\r\n",
  2786. ri.http_headers[i].name,
  2787. ri.http_headers[i].value);
  2788. (void) mg_write(conn, "\r\n", 2);
  2789. /* Send chunk of data that may be read after the headers */
  2790. conn->num_bytes_sent += mg_write(conn,
  2791. buf + headers_len, data_len - headers_len);
  2792. /* Read the rest of CGI output and send to the client */
  2793. send_opened_file_stream(conn, out, INT64_MAX);
  2794. done:
  2795. if (pid != (pid_t) -1)
  2796. kill(pid, SIGTERM);
  2797. if (fd_stdin[0] != -1)
  2798. (void) close(fd_stdin[0]);
  2799. if (fd_stdout[1] != -1)
  2800. (void) close(fd_stdout[1]);
  2801. if (in != NULL)
  2802. (void) fclose(in);
  2803. else if (fd_stdin[1] != -1)
  2804. (void) close(fd_stdin[1]);
  2805. if (out != NULL)
  2806. (void) fclose(out);
  2807. else if (fd_stdout[0] != -1)
  2808. (void) close(fd_stdout[0]);
  2809. }
  2810. #endif /* !NO_CGI */
  2811. /*
  2812. * For a given PUT path, create all intermediate subdirectories
  2813. * for given path. Return 0 if the path itself is a directory,
  2814. * or -1 on error, 1 if OK.
  2815. */
  2816. static int
  2817. put_dir(const char *path)
  2818. {
  2819. char buf[FILENAME_MAX];
  2820. const char *s, *p;
  2821. struct mgstat st;
  2822. size_t len;
  2823. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  2824. len = p - path;
  2825. assert(len < sizeof(buf));
  2826. (void) memcpy(buf, path, len);
  2827. buf[len] = '\0';
  2828. /* Try to create intermediate directory */
  2829. if (mg_stat(buf, &st) == -1 && mg_mkdir(buf, 0755) != 0)
  2830. return (-1);
  2831. /* Is path itself a directory ? */
  2832. if (p[1] == '\0')
  2833. return (0);
  2834. }
  2835. return (1);
  2836. }
  2837. static void
  2838. put_file(struct mg_connection *conn, const char *path)
  2839. {
  2840. struct mgstat st;
  2841. const char *range;
  2842. int64_t r1, r2;
  2843. FILE *fp;
  2844. int rc;
  2845. conn->request_info.status_code = mg_stat(path, &st) == 0 ? 200 : 201;
  2846. if ((rc = put_dir(path)) == 0) {
  2847. (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n",
  2848. conn->request_info.status_code);
  2849. } else if (rc == -1) {
  2850. send_error(conn, 500, http_500_error,
  2851. "put_dir(%s): %s", path, strerror(ERRNO));
  2852. } else if ((fp = mg_fopen(path, "wb+")) == NULL) {
  2853. send_error(conn, 500, http_500_error,
  2854. "fopen(%s): %s", path, strerror(ERRNO));
  2855. } else {
  2856. set_close_on_exec(fileno(fp));
  2857. range = mg_get_header(conn, "Content-Range");
  2858. r1 = r2 = 0;
  2859. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  2860. conn->request_info.status_code = 206;
  2861. /* TODO(lsm): handle seek error */
  2862. (void) fseeko(fp, (off_t) r1, SEEK_SET);
  2863. }
  2864. if (handle_request_body(conn, fp))
  2865. (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n",
  2866. conn->request_info.status_code);
  2867. (void) fclose(fp);
  2868. }
  2869. }
  2870. #if !defined(NO_SSI)
  2871. static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);
  2872. static void
  2873. do_ssi_include(struct mg_connection *conn, const char *ssi, char *tag,
  2874. int include_level)
  2875. {
  2876. char file_name[BUFSIZ], path[FILENAME_MAX], *p;
  2877. bool_t is_ssi;
  2878. FILE *fp;
  2879. /*
  2880. * sscanf() is safe here, since send_ssi_file() also uses buffer
  2881. * of size BUFSIZ to get the tag. So strlen(tag) is always < BUFSIZ.
  2882. */
  2883. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
  2884. /* File name is relative to the webserver root */
  2885. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2886. (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
  2887. conn->ctx->options[OPT_ROOT], DIRSEP, file_name);
  2888. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2889. } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) {
  2890. /*
  2891. * File name is relative to the webserver working directory
  2892. * or it is absolute system path
  2893. */
  2894. (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  2895. } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
  2896. /* File name is relative to the currect document */
  2897. (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  2898. if ((p = strrchr(path, DIRSEP)) != NULL)
  2899. p[1] = '\0';
  2900. (void) mg_snprintf(conn, path + strlen(path),
  2901. sizeof(path) - strlen(path), "%s", file_name);
  2902. } else {
  2903. cry(conn, "Bad SSI #include: [%s]", tag);
  2904. return;
  2905. }
  2906. if ((fp = mg_fopen(path, "rb")) == NULL) {
  2907. cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
  2908. tag, path, strerror(ERRNO));
  2909. } else {
  2910. set_close_on_exec(fileno(fp));
  2911. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2912. is_ssi = match_extension(path,
  2913. conn->ctx->options[OPT_SSI_EXTENSIONS]);
  2914. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2915. if (is_ssi) {
  2916. send_ssi_file(conn, path, fp, include_level + 1);
  2917. } else {
  2918. send_opened_file_stream(conn, fp, INT64_MAX);
  2919. }
  2920. (void) fclose(fp);
  2921. }
  2922. }
  2923. static void
  2924. do_ssi_exec(struct mg_connection *conn, char *tag)
  2925. {
  2926. char cmd[BUFSIZ];
  2927. FILE *fp;
  2928. if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
  2929. cry(conn, "Bad SSI #exec: [%s]", tag);
  2930. } else if ((fp = popen(cmd, "r")) == NULL) {
  2931. cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  2932. } else {
  2933. send_opened_file_stream(conn, fp, INT64_MAX);
  2934. (void) pclose(fp);
  2935. }
  2936. }
  2937. static void
  2938. send_ssi_file(struct mg_connection *conn, const char *path, FILE *fp,
  2939. int include_level)
  2940. {
  2941. char buf[BUFSIZ];
  2942. int ch, len, in_ssi_tag;
  2943. if (include_level > 10) {
  2944. cry(conn, "SSI #include level is too deep (%s)", path);
  2945. return;
  2946. }
  2947. in_ssi_tag = FALSE;
  2948. len = 0;
  2949. while ((ch = fgetc(fp)) != EOF) {
  2950. if (in_ssi_tag && ch == '>') {
  2951. in_ssi_tag = FALSE;
  2952. buf[len++] = ch & 0xff;
  2953. buf[len] = '\0';
  2954. assert(len <= (int) sizeof(buf));
  2955. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  2956. /* Not an SSI tag, pass it */
  2957. (void) mg_write(conn, buf, len);
  2958. } else {
  2959. if (!memcmp(buf + 5, "include", 7)) {
  2960. do_ssi_include(conn, path, buf + 12,
  2961. include_level);
  2962. } else if (!memcmp(buf + 5, "exec", 4)) {
  2963. do_ssi_exec(conn, buf + 9);
  2964. } else {
  2965. cry(conn, "%s: unknown SSI "
  2966. "command: \"%s\"", path, buf);
  2967. }
  2968. }
  2969. len = 0;
  2970. } else if (in_ssi_tag) {
  2971. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  2972. /* Not an SSI tag */
  2973. in_ssi_tag = FALSE;
  2974. } else if (len == (int) sizeof(buf) - 2) {
  2975. cry(conn, "%s: SSI tag is too large", path);
  2976. len = 0;
  2977. }
  2978. buf[len++] = ch & 0xff;
  2979. } else if (ch == '<') {
  2980. in_ssi_tag = TRUE;
  2981. if (len > 0)
  2982. (void) mg_write(conn, buf, len);
  2983. len = 0;
  2984. buf[len++] = ch & 0xff;
  2985. } else {
  2986. buf[len++] = ch & 0xff;
  2987. if (len == (int) sizeof(buf)) {
  2988. (void) mg_write(conn, buf, len);
  2989. len = 0;
  2990. }
  2991. }
  2992. }
  2993. /* Send the rest of buffered data */
  2994. if (len > 0)
  2995. (void) mg_write(conn, buf, len);
  2996. }
  2997. static void
  2998. send_ssi(struct mg_connection *conn, const char *path)
  2999. {
  3000. FILE *fp;
  3001. if ((fp = mg_fopen(path, "rb")) == NULL) {
  3002. send_error(conn, 500, http_500_error,
  3003. "fopen(%s): %s", path, strerror(ERRNO));
  3004. } else {
  3005. set_close_on_exec(fileno(fp));
  3006. (void) mg_printf(conn, "%s", "HTTP/1.1 200 OK\r\n"
  3007. "Content-Type: text/html\r\nConnection: close\r\n\r\n");
  3008. send_ssi_file(conn, path, fp, 0);
  3009. (void) fclose(fp);
  3010. }
  3011. }
  3012. #endif /* !NO_SSI */
  3013. /*
  3014. * This is the heart of the Mongoose's logic.
  3015. * This function is called when the request is read, parsed and validated,
  3016. * and Mongoose must decide what action to take: serve a file, or
  3017. * a directory, or call embedded function, etcetera.
  3018. */
  3019. static void
  3020. analyze_request(struct mg_connection *conn)
  3021. {
  3022. struct mg_request_info *ri;
  3023. char path[FILENAME_MAX];
  3024. int uri_len;
  3025. struct mgstat st;
  3026. mg_callback_t new_request_callback;
  3027. ri = &conn->request_info;
  3028. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL)
  3029. * conn->request_info.query_string++ = '\0';
  3030. uri_len = strlen(ri->uri);
  3031. new_request_callback = conn->ctx->callbacks[MG_EVENT_NEW_REQUEST];
  3032. (void) url_decode(ri->uri, uri_len, ri->uri, uri_len + 1, FALSE);
  3033. remove_double_dots_and_double_slashes(ri->uri);
  3034. convert_uri_to_file_name(conn, ri->uri, path, sizeof(path));
  3035. if (new_request_callback && new_request_callback(conn, ri) == TRUE) {
  3036. /* Do nothing, callback has served the request */
  3037. } else if (!check_authorization(conn, path)) {
  3038. send_authorization_request(conn);
  3039. } else if (strstr(path, PASSWORDS_FILE_NAME)) {
  3040. /* Do not allow to view passwords files */
  3041. send_error(conn, 403, "Forbidden", "Access Forbidden");
  3042. } else if ((!strcmp(ri->request_method, "PUT") ||
  3043. !strcmp(ri->request_method, "DELETE")) &&
  3044. (conn->ctx->options[OPT_AUTH_PUT] == NULL ||
  3045. !is_authorized_for_put(conn))) {
  3046. send_authorization_request(conn);
  3047. } else if (!strcmp(ri->request_method, "PUT")) {
  3048. put_file(conn, path);
  3049. } else if (!strcmp(ri->request_method, "DELETE")) {
  3050. if (mg_remove(path) == 0)
  3051. send_error(conn, 200, "OK", "");
  3052. else
  3053. send_error(conn, 500, http_500_error,
  3054. "remove(%s): %s", path, strerror(ERRNO));
  3055. } else if (mg_stat(path, &st) != 0) {
  3056. send_error(conn, 404, "Not Found", "%s", "File not found");
  3057. } else if (st.is_directory && ri->uri[uri_len - 1] != '/') {
  3058. (void) mg_printf(conn,
  3059. "HTTP/1.1 301 Moved Permanently\r\n"
  3060. "Location: %s/\r\n\r\n", ri->uri);
  3061. } else if (st.is_directory &&
  3062. substitute_index_file(conn, path, sizeof(path), &st) == FALSE) {
  3063. if (is_true(conn->ctx->options[OPT_DIR_LIST])) {
  3064. send_directory(conn, path);
  3065. } else {
  3066. send_error(conn, 403, "Directory Listing Denied",
  3067. "Directory listing denied");
  3068. }
  3069. #if !defined(NO_CGI)
  3070. } else if (match_extension(path,
  3071. conn->ctx->options[OPT_CGI_EXTENSIONS])) {
  3072. if (strcmp(ri->request_method, "POST") &&
  3073. strcmp(ri->request_method, "GET")) {
  3074. send_error(conn, 501, "Not Implemented",
  3075. "Method %s is not implemented", ri->request_method);
  3076. } else {
  3077. send_cgi(conn, path);
  3078. }
  3079. #endif /* NO_CGI */
  3080. #if !defined(NO_SSI)
  3081. } else if (match_extension(path,
  3082. conn->ctx->options[OPT_SSI_EXTENSIONS])) {
  3083. send_ssi(conn, path);
  3084. #endif /* NO_SSI */
  3085. } else if (is_not_modified(conn, &st)) {
  3086. send_error(conn, 304, "Not Modified", "");
  3087. } else {
  3088. send_file(conn, path, &st);
  3089. }
  3090. }
  3091. static void
  3092. close_all_listening_sockets(struct mg_context *ctx)
  3093. {
  3094. int i;
  3095. for (i = 0; i < ctx->num_listeners; i++)
  3096. (void) closesocket(ctx->listeners[i].sock);
  3097. ctx->num_listeners = 0;
  3098. }
  3099. static enum mg_error_t
  3100. set_ports_option(struct mg_context *ctx, const char *list)
  3101. {
  3102. SOCKET sock;
  3103. int is_ssl;
  3104. struct vec vec;
  3105. struct socket *listener;
  3106. close_all_listening_sockets(ctx);
  3107. assert(ctx->num_listeners == 0);
  3108. while ((list = next_option(list, &vec, NULL)) != NULL) {
  3109. is_ssl = vec.ptr[vec.len - 1] == 's' ? TRUE : FALSE;
  3110. listener = ctx->listeners + ctx->num_listeners;
  3111. if (ctx->num_listeners >=
  3112. (int) (ARRAY_SIZE(ctx->listeners) - 1)) {
  3113. cry(fc(ctx), "%s", "Too many listeninig sockets");
  3114. return (MG_ERROR);
  3115. } else if ((sock = mg_open_listening_port(ctx,
  3116. vec.ptr, &listener->lsa)) == INVALID_SOCKET) {
  3117. cry(fc(ctx), "cannot bind to %.*s", vec.len, vec.ptr);
  3118. return (MG_ERROR);
  3119. } else if (is_ssl == TRUE && ctx->ssl_ctx == NULL) {
  3120. (void) closesocket(sock);
  3121. cry(fc(ctx), "cannot add SSL socket, please specify "
  3122. "-ssl_cert option BEFORE -ports option");
  3123. return (MG_ERROR);
  3124. } else {
  3125. listener->sock = sock;
  3126. listener->is_ssl = is_ssl;
  3127. ctx->num_listeners++;
  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. int i, max_fd;
  3835. while (ctx->stop_flag == 0) {
  3836. FD_ZERO(&read_set);
  3837. max_fd = -1;
  3838. /* Add listening sockets to the read set */
  3839. (void) pthread_rwlock_rdlock(&ctx->rwlock);
  3840. for (i = 0; i < ctx->num_listeners; i++)
  3841. add_to_set(ctx->listeners[i].sock, &read_set, &max_fd);
  3842. (void) pthread_rwlock_unlock(&ctx->rwlock);
  3843. tv.tv_sec = 1;
  3844. tv.tv_usec = 0;
  3845. if (select(max_fd + 1, &read_set, NULL, NULL, &tv) < 0) {
  3846. #ifdef _WIN32
  3847. /*
  3848. * On windows, if read_set and write_set are empty,
  3849. * select() returns "Invalid parameter" error
  3850. * (at least on my Windows XP Pro). So in this case,
  3851. * we sleep here.
  3852. */
  3853. sleep(1);
  3854. #endif /* _WIN32 */
  3855. } else {
  3856. (void) pthread_rwlock_rdlock(&ctx->rwlock);
  3857. for (i = 0; i < ctx->num_listeners; i++)
  3858. if (FD_ISSET(ctx->listeners[i].sock, &read_set))
  3859. accept_new_connection(
  3860. ctx->listeners + i, ctx);
  3861. (void) pthread_rwlock_unlock(&ctx->rwlock);
  3862. }
  3863. }
  3864. /* Stop signal received: somebody called mg_stop. Quit. */
  3865. mg_fini(ctx);
  3866. }
  3867. void
  3868. mg_stop(struct mg_context *ctx)
  3869. {
  3870. ctx->stop_flag = 1;
  3871. /* Wait until mg_fini() stops */
  3872. while (ctx->stop_flag != 2)
  3873. (void) sleep(1);
  3874. assert(ctx->num_threads == 0);
  3875. free(ctx);
  3876. #if defined(_WIN32)
  3877. (void) WSACleanup();
  3878. #endif /* _WIN32 */
  3879. }
  3880. struct mg_context *
  3881. mg_start(void)
  3882. {
  3883. struct mg_context *ctx;
  3884. const struct mg_option *option;
  3885. #if defined(_WIN32)
  3886. WSADATA data;
  3887. WSAStartup(MAKEWORD(2,2), &data);
  3888. #endif /* _WIN32 */
  3889. if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) {
  3890. cry(fc(ctx), "cannot allocate mongoose context");
  3891. return (NULL);
  3892. }
  3893. /* Initialize options. First pass: set default option values */
  3894. for (option = known_options; option->name != NULL; option++)
  3895. ctx->options[option->index] = option->default_value == NULL ?
  3896. NULL : mg_strdup(option->default_value);
  3897. /* Call setter functions */
  3898. for (option = known_options; option->name != NULL; option++)
  3899. if (option->setter != NULL &&
  3900. ctx->options[option->index] != NULL)
  3901. if (option->setter(ctx,
  3902. ctx->options[option->index]) == FALSE) {
  3903. mg_fini(ctx);
  3904. return (NULL);
  3905. }
  3906. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: root [%s]",
  3907. __func__, ctx->options[OPT_ROOT]));
  3908. #if !defined(_WIN32)
  3909. /*
  3910. * Ignore SIGPIPE signal, so if browser cancels the request, it
  3911. * won't kill the whole process.
  3912. */
  3913. (void) signal(SIGPIPE, SIG_IGN);
  3914. #endif /* _WIN32 */
  3915. (void) pthread_rwlock_init(&ctx->rwlock, NULL);
  3916. (void) pthread_mutex_init(&ctx->mutex, NULL);
  3917. (void) pthread_cond_init(&ctx->thr_cond, NULL);
  3918. (void) pthread_cond_init(&ctx->empty_cond, NULL);
  3919. (void) pthread_cond_init(&ctx->full_cond, NULL);
  3920. /* Start master (listening) thread */
  3921. start_thread(ctx, (mg_thread_func_t) master_thread, ctx);
  3922. return (ctx);
  3923. }