mongoose.c 116 KB

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