mongoose.c 137 KB

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