mongoose.c 117 KB

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