mongoose.c 134 KB

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