mongoose.c 127 KB

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