mongoose.c 133 KB

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