mongoose.c 125 KB

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