mongoose.c 142 KB

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