mongoose.c 124 KB

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