mongoose.c 133 KB

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