mongoose.c 133 KB

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