mongoose.c 124 KB

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