mongoose.c 132 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296
  1. // Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
  2. // Copyright (c) 2013-2014 Cesanta Software Limited
  3. // All rights reserved
  4. //
  5. // This library is dual-licensed: you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License version 2 as
  7. // published by the Free Software Foundation. For the terms of this
  8. // license, see <http://www.gnu.org/licenses/>.
  9. //
  10. // You are free to use this library under the terms of the GNU General
  11. // Public License, but WITHOUT ANY WARRANTY; without even the implied
  12. // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  13. // See the GNU General Public License for more details.
  14. //
  15. // Alternatively, you can license this library under a commercial
  16. // license, as set out in <http://cesanta.com/>.
  17. #undef UNICODE // Use ANSI WinAPI functions
  18. #undef _UNICODE // Use multibyte encoding on Windows
  19. #define _MBCS // Use multibyte encoding on Windows
  20. #define _INTEGRAL_MAX_BITS 64 // Enable _stati64() on Windows
  21. #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005+
  22. #undef WIN32_LEAN_AND_MEAN // Let windows.h always include winsock2.h
  23. #define _XOPEN_SOURCE 600 // For flockfile() on Linux
  24. #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++
  25. #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX
  26. #define _LARGEFILE_SOURCE // Enable fseeko() and ftello() functions
  27. #define _FILE_OFFSET_BITS 64 // Enable 64-bit file offsets
  28. #ifdef _MSC_VER
  29. #pragma warning (disable : 4127) // FD_SET() emits warning, disable it
  30. #pragma warning (disable : 4204) // missing c99 support
  31. #endif
  32. #include <sys/types.h>
  33. #include <sys/stat.h>
  34. #include <stddef.h>
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. #include <string.h>
  38. #include <fcntl.h>
  39. #include <assert.h>
  40. #include <errno.h>
  41. #include <time.h>
  42. #include <ctype.h>
  43. #include <stdarg.h>
  44. #ifdef _WIN32
  45. #include <windows.h>
  46. #include <process.h> // For _beginthread
  47. #include <io.h> // For _lseeki64
  48. #include <direct.h> // For _mkdir
  49. typedef int socklen_t;
  50. #if !defined(__MINGW32__) || !defined(_PID_T_) || defined(_NO_OLDNAMES)
  51. typedef HANDLE pid_t;
  52. #endif
  53. typedef SOCKET sock_t;
  54. typedef unsigned char uint8_t;
  55. typedef unsigned int uint32_t;
  56. typedef unsigned short uint16_t;
  57. typedef unsigned __int64 uint64_t;
  58. typedef __int64 int64_t;
  59. typedef CRITICAL_SECTION mutex_t;
  60. typedef struct _stati64 file_stat_t;
  61. #pragma comment(lib, "ws2_32.lib")
  62. #define snprintf _snprintf
  63. #define vsnprintf _vsnprintf
  64. #define INT64_FMT "I64d"
  65. #ifndef EINPROGRESS
  66. #define EINPROGRESS WSAEINPROGRESS
  67. #endif
  68. #ifndef EWOULDBLOCK
  69. #define EWOULDBLOCK WSAEWOULDBLOCK
  70. #endif
  71. #define mutex_init(x) InitializeCriticalSection(x)
  72. #define mutex_destroy(x) DeleteCriticalSection(x)
  73. #define mutex_lock(x) EnterCriticalSection(x)
  74. #define mutex_unlock(x) LeaveCriticalSection(x)
  75. #define get_thread_id() ((unsigned long) GetCurrentThreadId())
  76. #ifndef S_ISDIR
  77. #define S_ISDIR(x) ((x) & _S_IFDIR)
  78. #endif
  79. #define sleep(x) Sleep((x) * 1000)
  80. #define stat(x, y) mg_stat((x), (y))
  81. #define fopen(x, y) mg_fopen((x), (y))
  82. #define open(x, y) mg_open((x), (y))
  83. #define lseek(x, y, z) _lseeki64((x), (y), (z))
  84. #define mkdir(x, y) _mkdir(x)
  85. #define to64(x) _atoi64(x)
  86. #define flockfile(x)
  87. #define funlockfile(x)
  88. #ifndef va_copy
  89. #define va_copy(x,y) x = y
  90. #endif // MINGW #defines va_copy
  91. #ifndef __func__
  92. #define STRX(x) #x
  93. #define STR(x) STRX(x)
  94. #define __func__ __FILE__ ":" STR(__LINE__)
  95. #endif
  96. #else
  97. #include <dirent.h>
  98. #include <inttypes.h>
  99. #include <pthread.h>
  100. #include <pwd.h>
  101. #include <signal.h>
  102. #include <unistd.h>
  103. #include <netdb.h>
  104. #include <arpa/inet.h> // For inet_pton() when MONGOOSE_USE_IPV6 is defined
  105. #include <netinet/in.h>
  106. #include <sys/socket.h>
  107. #include <sys/select.h>
  108. #define closesocket(x) close(x)
  109. typedef int sock_t;
  110. typedef pthread_mutex_t mutex_t;
  111. typedef struct stat file_stat_t;
  112. #define mutex_init(x) pthread_mutex_init(x, NULL)
  113. #define mutex_destroy(x) pthread_mutex_destroy(x)
  114. #define mutex_lock(x) pthread_mutex_lock(x)
  115. #define mutex_unlock(x) pthread_mutex_unlock(x)
  116. #define get_thread_id() ((unsigned long) pthread_self())
  117. #define INVALID_SOCKET ((sock_t) -1)
  118. #define INT64_FMT PRId64
  119. #define to64(x) strtoll(x, NULL, 10)
  120. #define __cdecl
  121. #define O_BINARY 0
  122. #endif
  123. #ifdef MONGOOSE_USE_SSL
  124. #ifdef __APPLE__
  125. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  126. #endif
  127. #include <openssl/ssl.h>
  128. #endif
  129. #include "mongoose.h"
  130. struct ll { struct ll *prev, *next; };
  131. #define LINKED_LIST_INIT(N) ((N)->next = (N)->prev = (N))
  132. #define LINKED_LIST_DECLARE_AND_INIT(H) struct ll H = { &H, &H }
  133. #define LINKED_LIST_ENTRY(P,T,N) ((T *)((char *)(P) - offsetof(T, N)))
  134. #define LINKED_LIST_IS_EMPTY(N) ((N)->next == (N))
  135. #define LINKED_LIST_FOREACH(H,N,T) \
  136. for (N = (H)->next, T = (N)->next; N != (H); N = (T), T = (N)->next)
  137. #define LINKED_LIST_ADD_TO_FRONT(H,N) do { ((H)->next)->prev = (N); \
  138. (N)->next = ((H)->next); (N)->prev = (H); (H)->next = (N); } while (0)
  139. #define LINKED_LIST_ADD_TO_TAIL(H,N) do { ((H)->prev)->next = (N); \
  140. (N)->prev = ((H)->prev); (N)->next = (H); (H)->prev = (N); } while (0)
  141. #define LINKED_LIST_REMOVE(N) do { ((N)->next)->prev = ((N)->prev); \
  142. ((N)->prev)->next = ((N)->next); LINKED_LIST_INIT(N); } while (0)
  143. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  144. #define MAX_REQUEST_SIZE 16384
  145. #define IOBUF_SIZE 8192
  146. #define MAX_PATH_SIZE 8192
  147. #define LUA_SCRIPT_PATTERN "**.lp$"
  148. #define DEFAULT_CGI_PATTERN "**.cgi$|**.pl$|**.php$"
  149. #define CGI_ENVIRONMENT_SIZE 8192
  150. #define MAX_CGI_ENVIR_VARS 64
  151. #define ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
  152. #define PASSWORDS_FILE_NAME ".htpasswd"
  153. #ifndef MONGOOSE_USE_WEBSOCKET_PING_INTERVAL
  154. #define MONGOOSE_USE_WEBSOCKET_PING_INTERVAL 5
  155. #endif
  156. // Extra HTTP headers to send in every static file reply
  157. #if !defined(MONGOOSE_USE_EXTRA_HTTP_HEADERS)
  158. #define MONGOOSE_USE_EXTRA_HTTP_HEADERS ""
  159. #endif
  160. #ifndef MONGOOSE_USE_POST_SIZE_LIMIT
  161. #define MONGOOSE_USE_POST_SIZE_LIMIT 0
  162. #endif
  163. #ifndef MONGOOSE_USE_IDLE_TIMEOUT_SECONDS
  164. #define MONGOOSE_USE_IDLE_TIMEOUT_SECONDS 30
  165. #endif
  166. #ifdef MONGOOSE_NO_SOCKETPAIR
  167. #define MONGOOSE_NO_CGI
  168. #endif
  169. #ifdef MONGOOSE_ENABLE_DEBUG
  170. #define DBG(x) do { printf("%-20s ", __func__); printf x; putchar('\n'); \
  171. fflush(stdout); } while(0)
  172. #else
  173. #define DBG(x)
  174. #endif
  175. #ifdef MONGOOSE_NO_FILESYSTEM
  176. #define MONGOOSE_NO_AUTH
  177. #define MONGOOSE_NO_CGI
  178. #define MONGOOSE_NO_DAV
  179. #define MONGOOSE_NO_DIRECTORY_LISTING
  180. #define MONGOOSE_NO_LOGGING
  181. #endif
  182. union socket_address {
  183. struct sockaddr sa;
  184. struct sockaddr_in sin;
  185. #ifdef MONGOOSE_USE_IPV6
  186. struct sockaddr_in6 sin6;
  187. #endif
  188. };
  189. struct vec {
  190. const char *ptr;
  191. int len;
  192. };
  193. // For directory listing and WevDAV support
  194. struct dir_entry {
  195. struct connection *conn;
  196. char *file_name;
  197. file_stat_t st;
  198. };
  199. // NOTE(lsm): this enum shoulds be in sync with the config_options.
  200. enum {
  201. ACCESS_CONTROL_LIST,
  202. #ifndef MONGOOSE_NO_FILESYSTEM
  203. ACCESS_LOG_FILE,
  204. #ifndef MONGOOSE_NO_AUTH
  205. AUTH_DOMAIN,
  206. #endif
  207. #ifndef MONGOOSE_NO_CGI
  208. CGI_INTERPRETER,
  209. CGI_PATTERN,
  210. #endif
  211. #ifndef MONGOOSE_NO_DAV
  212. DAV_AUTH_FILE,
  213. #endif
  214. DOCUMENT_ROOT,
  215. #ifndef MONGOOSE_NO_DIRECTORY_LISTING
  216. ENABLE_DIRECTORY_LISTING,
  217. #endif
  218. #endif
  219. EXTRA_MIME_TYPES,
  220. #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
  221. GLOBAL_AUTH_FILE,
  222. #endif
  223. HIDE_FILES_PATTERN,
  224. #ifndef MONGOOSE_NO_FILESYSTEM
  225. INDEX_FILES,
  226. #endif
  227. LISTENING_PORT,
  228. #ifndef _WIN32
  229. RUN_AS_USER,
  230. #endif
  231. #ifdef MONGOOSE_USE_SSL
  232. SSL_CERTIFICATE,
  233. #endif
  234. URL_REWRITES,
  235. NUM_OPTIONS
  236. };
  237. static const char *static_config_options[] = {
  238. "access_control_list", NULL,
  239. #ifndef MONGOOSE_NO_FILESYSTEM
  240. "access_log_file", NULL,
  241. #ifndef MONGOOSE_NO_AUTH
  242. "auth_domain", "mydomain.com",
  243. #endif
  244. #ifndef MONGOOSE_NO_CGI
  245. "cgi_interpreter", NULL,
  246. "cgi_pattern", DEFAULT_CGI_PATTERN,
  247. #endif
  248. #ifndef MONGOOSE_NO_DAV
  249. "dav_auth_file", NULL,
  250. #endif
  251. "document_root", NULL,
  252. #ifndef MONGOOSE_NO_DIRECTORY_LISTING
  253. "enable_directory_listing", "yes",
  254. #endif
  255. #endif
  256. "extra_mime_types", NULL,
  257. #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
  258. "global_auth_file", NULL,
  259. #endif
  260. "hide_files_patterns", NULL,
  261. #ifndef MONGOOSE_NO_FILESYSTEM
  262. "index_files","index.html,index.htm,index.cgi,index.php,index.lp",
  263. #endif
  264. "listening_port", NULL,
  265. #ifndef _WIN32
  266. "run_as_user", NULL,
  267. #endif
  268. #ifdef MONGOOSE_USE_SSL
  269. "ssl_certificate", NULL,
  270. #endif
  271. "url_rewrites", NULL,
  272. NULL
  273. };
  274. struct mg_server {
  275. sock_t listening_sock;
  276. union socket_address lsa; // Listening socket address
  277. struct ll active_connections;
  278. mg_handler_t request_handler;
  279. mg_handler_t http_close_handler;
  280. mg_handler_t error_handler;
  281. mg_handler_t auth_handler;
  282. char *config_options[NUM_OPTIONS];
  283. char local_ip[48];
  284. void *server_data;
  285. #ifdef MONGOOSE_USE_SSL
  286. SSL_CTX *ssl_ctx; // Server SSL context
  287. SSL_CTX *client_ssl_ctx; // Client SSL context
  288. #endif
  289. #ifndef MONGOOSE_NO_SOCKETPAIR
  290. sock_t ctl[2]; // Control socketpair. Used to wake up from select() call
  291. #endif
  292. };
  293. // Expandable IO buffer
  294. struct iobuf {
  295. char *buf; // Buffer that holds the data
  296. int size; // Buffer size
  297. int len; // Number of bytes currently in a buffer
  298. };
  299. // Local endpoint representation
  300. union endpoint {
  301. int fd; // Opened regular local file
  302. sock_t cgi_sock; // CGI socket
  303. void *ssl; // SSL descriptor
  304. };
  305. enum endpoint_type { EP_NONE, EP_FILE, EP_CGI, EP_USER, EP_PUT, EP_CLIENT };
  306. enum connection_flags {
  307. CONN_CLOSE = 1, // Connection must be closed at the end of the poll
  308. CONN_SPOOL_DONE = 2, // All data has been buffered for sending
  309. CONN_SSL_HANDS_SHAKEN = 4, // SSL handshake has completed. Only for SSL
  310. CONN_HEADERS_SENT = 8, // User callback has sent HTTP headers
  311. CONN_BUFFER = 16, // CGI only. Holds data send until CGI prints
  312. // all HTTP headers
  313. CONN_CONNECTING = 32, // HTTP client is doing non-blocking connect()
  314. CONN_LONG_RUNNING = 64 // Long-running URI handlers
  315. };
  316. struct connection {
  317. struct mg_connection mg_conn; // XXX: Must be first
  318. struct ll link; // Linkage to server->active_connections
  319. struct mg_server *server;
  320. sock_t client_sock; // Connected client
  321. struct iobuf local_iobuf;
  322. struct iobuf remote_iobuf;
  323. union endpoint endpoint;
  324. enum endpoint_type endpoint_type;
  325. time_t birth_time;
  326. time_t last_activity_time;
  327. char *path_info;
  328. char *request;
  329. int64_t num_bytes_sent; // Total number of bytes sent
  330. int64_t cl; // Reply content length, for Range support
  331. int request_len; // Request length, including last \r\n after last header
  332. int flags; // CONN_* flags: CONN_CLOSE, CONN_SPOOL_DONE, etc
  333. mg_handler_t handler; // Callback for HTTP client
  334. #ifdef MONGOOSE_USE_SSL
  335. SSL *ssl; // SSL descriptor
  336. #endif
  337. };
  338. static void open_local_endpoint(struct connection *conn, int skip_user);
  339. static void close_local_endpoint(struct connection *conn);
  340. static const struct {
  341. const char *extension;
  342. size_t ext_len;
  343. const char *mime_type;
  344. } static_builtin_mime_types[] = {
  345. {".html", 5, "text/html"},
  346. {".htm", 4, "text/html"},
  347. {".shtm", 5, "text/html"},
  348. {".shtml", 6, "text/html"},
  349. {".css", 4, "text/css"},
  350. {".js", 3, "application/x-javascript"},
  351. {".ico", 4, "image/x-icon"},
  352. {".gif", 4, "image/gif"},
  353. {".jpg", 4, "image/jpeg"},
  354. {".jpeg", 5, "image/jpeg"},
  355. {".png", 4, "image/png"},
  356. {".svg", 4, "image/svg+xml"},
  357. {".txt", 4, "text/plain"},
  358. {".torrent", 8, "application/x-bittorrent"},
  359. {".wav", 4, "audio/x-wav"},
  360. {".mp3", 4, "audio/x-mp3"},
  361. {".mid", 4, "audio/mid"},
  362. {".m3u", 4, "audio/x-mpegurl"},
  363. {".ogg", 4, "application/ogg"},
  364. {".ram", 4, "audio/x-pn-realaudio"},
  365. {".xml", 4, "text/xml"},
  366. {".json", 5, "text/json"},
  367. {".xslt", 5, "application/xml"},
  368. {".xsl", 4, "application/xml"},
  369. {".ra", 3, "audio/x-pn-realaudio"},
  370. {".doc", 4, "application/msword"},
  371. {".exe", 4, "application/octet-stream"},
  372. {".zip", 4, "application/x-zip-compressed"},
  373. {".xls", 4, "application/excel"},
  374. {".tgz", 4, "application/x-tar-gz"},
  375. {".tar", 4, "application/x-tar"},
  376. {".gz", 3, "application/x-gunzip"},
  377. {".arj", 4, "application/x-arj-compressed"},
  378. {".rar", 4, "application/x-arj-compressed"},
  379. {".rtf", 4, "application/rtf"},
  380. {".pdf", 4, "application/pdf"},
  381. {".swf", 4, "application/x-shockwave-flash"},
  382. {".mpg", 4, "video/mpeg"},
  383. {".webm", 5, "video/webm"},
  384. {".mpeg", 5, "video/mpeg"},
  385. {".mov", 4, "video/quicktime"},
  386. {".mp4", 4, "video/mp4"},
  387. {".m4v", 4, "video/x-m4v"},
  388. {".asf", 4, "video/x-ms-asf"},
  389. {".avi", 4, "video/x-msvideo"},
  390. {".bmp", 4, "image/bmp"},
  391. {".ttf", 4, "application/x-font-ttf"},
  392. {NULL, 0, NULL}
  393. };
  394. #ifndef MONGOOSE_NO_THREADS
  395. void *mg_start_thread(void *(*f)(void *), void *p) {
  396. #ifdef _WIN32
  397. return (void *) _beginthread((void (__cdecl *)(void *)) f, 0, p);
  398. #else
  399. pthread_t thread_id = (pthread_t) 0;
  400. pthread_attr_t attr;
  401. (void) pthread_attr_init(&attr);
  402. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  403. #if MONGOOSE_USE_STACK_SIZE > 1
  404. (void) pthread_attr_setstacksize(&attr, MONGOOSE_USE_STACK_SIZE);
  405. #endif
  406. pthread_create(&thread_id, &attr, f, p);
  407. pthread_attr_destroy(&attr);
  408. return (void *) thread_id;
  409. #endif
  410. }
  411. #endif // MONGOOSE_NO_THREADS
  412. #ifdef _WIN32
  413. #ifndef MONGOOSE_NO_FILESYSTEM
  414. // Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  415. // wbuf and wbuf_len is a target buffer and its length.
  416. static void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  417. char buf[MAX_PATH_SIZE * 2], buf2[MAX_PATH_SIZE * 2], *p;
  418. strncpy(buf, path, sizeof(buf));
  419. buf[sizeof(buf) - 1] = '\0';
  420. // Trim trailing slashes
  421. p = buf + strlen(buf) - 1;
  422. while (p > buf && p[0] == '\\' || p[0] == '/') *p-- = '\0';
  423. //change_slashes_to_backslashes(buf);
  424. // Convert to Unicode and back. If doubly-converted string does not
  425. // match the original, something is fishy, reject.
  426. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  427. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  428. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  429. NULL, NULL);
  430. if (strcmp(buf, buf2) != 0) {
  431. wbuf[0] = L'\0';
  432. }
  433. }
  434. static int mg_stat(const char *path, file_stat_t *st) {
  435. wchar_t wpath[MAX_PATH_SIZE];
  436. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  437. DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
  438. return _wstati64(wpath, st);
  439. }
  440. static FILE *mg_fopen(const char *path, const char *mode) {
  441. wchar_t wpath[MAX_PATH_SIZE], wmode[10];
  442. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  443. to_wchar(mode, wmode, ARRAY_SIZE(wmode));
  444. return _wfopen(wpath, wmode);
  445. }
  446. static int mg_open(const char *path, int flag) {
  447. wchar_t wpath[MAX_PATH_SIZE];
  448. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  449. return _wopen(wpath, flag);
  450. }
  451. #endif
  452. #endif // MONGOOSE_NO_FILESYSTEM
  453. static void set_close_on_exec(int fd) {
  454. #ifdef _WIN32
  455. (void) SetHandleInformation((HANDLE) fd, HANDLE_FLAG_INHERIT, 0);
  456. #else
  457. fcntl(fd, F_SETFD, FD_CLOEXEC);
  458. #endif
  459. }
  460. static void set_non_blocking_mode(sock_t sock) {
  461. #ifdef _WIN32
  462. unsigned long on = 1;
  463. ioctlsocket(sock, FIONBIO, &on);
  464. #else
  465. int flags = fcntl(sock, F_GETFL, 0);
  466. fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  467. #endif
  468. }
  469. // A helper function for traversing a comma separated list of values.
  470. // It returns a list pointer shifted to the next value, or NULL if the end
  471. // of the list found.
  472. // Value is stored in val vector. If value has form "x=y", then eq_val
  473. // vector is initialized to point to the "y" part, and val vector length
  474. // is adjusted to point only to "x".
  475. static const char *next_option(const char *list, struct vec *val,
  476. struct vec *eq_val) {
  477. if (list == NULL || *list == '\0') {
  478. // End of the list
  479. list = NULL;
  480. } else {
  481. val->ptr = list;
  482. if ((list = strchr(val->ptr, ',')) != NULL) {
  483. // Comma found. Store length and shift the list ptr
  484. val->len = list - val->ptr;
  485. list++;
  486. } else {
  487. // This value is the last one
  488. list = val->ptr + strlen(val->ptr);
  489. val->len = list - val->ptr;
  490. }
  491. if (eq_val != NULL) {
  492. // Value has form "x=y", adjust pointers and lengths
  493. // so that val points to "x", and eq_val points to "y".
  494. eq_val->len = 0;
  495. eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
  496. if (eq_val->ptr != NULL) {
  497. eq_val->ptr++; // Skip over '=' character
  498. eq_val->len = val->ptr + val->len - eq_val->ptr;
  499. val->len = (eq_val->ptr - val->ptr) - 1;
  500. }
  501. }
  502. }
  503. return list;
  504. }
  505. static int spool(struct iobuf *io, const void *buf, int len) {
  506. static const double mult = 1.2;
  507. char *p = NULL;
  508. int new_len = 0;
  509. assert(io->len >= 0);
  510. assert(io->len <= io->size);
  511. //DBG(("1. %d %d %d", len, io->len, io->size));
  512. if (len <= 0) {
  513. } else if ((new_len = io->len + len) < io->size) {
  514. memcpy(io->buf + io->len, buf, len);
  515. io->len = new_len;
  516. } else if ((p = (char *) realloc(io->buf, (int) (new_len * mult))) != NULL) {
  517. io->buf = p;
  518. memcpy(io->buf + io->len, buf, len);
  519. io->len = new_len;
  520. io->size = (int) (new_len * mult);
  521. } else {
  522. len = 0;
  523. }
  524. //DBG(("%d %d %d", len, io->len, io->size));
  525. return len;
  526. }
  527. // Like snprintf(), but never returns negative value, or a value
  528. // that is larger than a supplied buffer.
  529. static int mg_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) {
  530. int n;
  531. if (buflen < 1) return 0;
  532. n = vsnprintf(buf, buflen, fmt, ap);
  533. if (n < 0) {
  534. n = 0;
  535. } else if (n >= (int) buflen) {
  536. n = (int) buflen - 1;
  537. }
  538. buf[n] = '\0';
  539. return n;
  540. }
  541. static int mg_snprintf(char *buf, size_t buflen, const char *fmt, ...) {
  542. va_list ap;
  543. int n;
  544. va_start(ap, fmt);
  545. n = mg_vsnprintf(buf, buflen, fmt, ap);
  546. va_end(ap);
  547. return n;
  548. }
  549. // Check whether full request is buffered. Return:
  550. // -1 if request is malformed
  551. // 0 if request is not yet fully buffered
  552. // >0 actual request length, including last \r\n\r\n
  553. static int get_request_len(const char *s, int buf_len) {
  554. const unsigned char *buf = (unsigned char *) s;
  555. int i;
  556. for (i = 0; i < buf_len; i++) {
  557. // Control characters are not allowed but >=128 are.
  558. // Abort scan as soon as one malformed character is found.
  559. if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
  560. return -1;
  561. } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
  562. return i + 2;
  563. } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
  564. buf[i + 2] == '\n') {
  565. return i + 3;
  566. }
  567. }
  568. return 0;
  569. }
  570. // Skip the characters until one of the delimiters characters found.
  571. // 0-terminate resulting word. Skip the rest of the delimiters if any.
  572. // Advance pointer to buffer to the next word. Return found 0-terminated word.
  573. static char *skip(char **buf, const char *delimiters) {
  574. char *p, *begin_word, *end_word, *end_delimiters;
  575. begin_word = *buf;
  576. end_word = begin_word + strcspn(begin_word, delimiters);
  577. end_delimiters = end_word + strspn(end_word, delimiters);
  578. for (p = end_word; p < end_delimiters; p++) {
  579. *p = '\0';
  580. }
  581. *buf = end_delimiters;
  582. return begin_word;
  583. }
  584. // Parse HTTP headers from the given buffer, advance buffer to the point
  585. // where parsing stopped.
  586. static void parse_http_headers(char **buf, struct mg_connection *ri) {
  587. size_t i;
  588. for (i = 0; i < ARRAY_SIZE(ri->http_headers); i++) {
  589. ri->http_headers[i].name = skip(buf, ": ");
  590. ri->http_headers[i].value = skip(buf, "\r\n");
  591. if (ri->http_headers[i].name[0] == '\0')
  592. break;
  593. ri->num_headers = i + 1;
  594. }
  595. }
  596. static const char *status_code_to_str(int status_code) {
  597. switch (status_code) {
  598. case 200: return "OK";
  599. case 201: return "Created";
  600. case 204: return "No Content";
  601. case 301: return "Moved Permanently";
  602. case 302: return "Found";
  603. case 304: return "Not Modified";
  604. case 400: return "Bad Request";
  605. case 403: return "Forbidden";
  606. case 404: return "Not Found";
  607. case 405: return "Method Not Allowed";
  608. case 409: return "Conflict";
  609. case 411: return "Length Required";
  610. case 413: return "Request Entity Too Large";
  611. case 415: return "Unsupported Media Type";
  612. case 423: return "Locked";
  613. case 500: return "Server Error";
  614. case 501: return "Not Implemented";
  615. default: return "Server Error";
  616. }
  617. }
  618. static void send_http_error(struct connection *conn, int code,
  619. const char *fmt, ...) {
  620. const char *message = status_code_to_str(code);
  621. const char *rewrites = conn->server->config_options[URL_REWRITES];
  622. char headers[200], body[200];
  623. struct vec a, b;
  624. va_list ap;
  625. int body_len, headers_len, match_code;
  626. conn->mg_conn.status_code = code;
  627. // Invoke error handler if it is set
  628. if (conn->server->error_handler != NULL &&
  629. conn->server->error_handler(&conn->mg_conn) == MG_ERROR_PROCESSED) {
  630. close_local_endpoint(conn);
  631. return;
  632. }
  633. // Handle error code rewrites
  634. while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
  635. if ((match_code = atoi(a.ptr)) > 0 && match_code == code) {
  636. conn->mg_conn.status_code = 302;
  637. mg_printf(&conn->mg_conn, "HTTP/1.1 %d Moved\r\n"
  638. "Location: %.*s?code=%d&orig_uri=%s\r\n\r\n",
  639. conn->mg_conn.status_code, b.len, b.ptr, code,
  640. conn->mg_conn.uri);
  641. close_local_endpoint(conn);
  642. return;
  643. }
  644. }
  645. body_len = mg_snprintf(body, sizeof(body), "%d %s\n", code, message);
  646. if (fmt != NULL) {
  647. va_start(ap, fmt);
  648. body_len += mg_vsnprintf(body + body_len, sizeof(body) - body_len, fmt, ap);
  649. va_end(ap);
  650. }
  651. if (code >= 300 && code <= 399) {
  652. // 3xx errors do not have body
  653. body_len = 0;
  654. }
  655. headers_len = mg_snprintf(headers, sizeof(headers),
  656. "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n"
  657. "Content-Type: text/plain\r\n\r\n",
  658. code, message, body_len);
  659. spool(&conn->remote_iobuf, headers, headers_len);
  660. spool(&conn->remote_iobuf, body, body_len);
  661. close_local_endpoint(conn); // This will write to the log file
  662. }
  663. // Print message to buffer. If buffer is large enough to hold the message,
  664. // return buffer. If buffer is to small, allocate large enough buffer on heap,
  665. // and return allocated buffer.
  666. static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap) {
  667. va_list ap_copy;
  668. int len;
  669. va_copy(ap_copy, ap);
  670. len = vsnprintf(*buf, size, fmt, ap_copy);
  671. va_end(ap_copy);
  672. if (len < 0) {
  673. // eCos and Windows are not standard-compliant and return -1 when
  674. // the buffer is too small. Keep allocating larger buffers until we
  675. // succeed or out of memory.
  676. *buf = NULL;
  677. while (len < 0) {
  678. if (*buf) free(*buf);
  679. size *= 2;
  680. if ((*buf = (char *) malloc(size)) == NULL) break;
  681. va_copy(ap_copy, ap);
  682. len = vsnprintf(*buf, size, fmt, ap_copy);
  683. va_end(ap_copy);
  684. }
  685. } else if (len > (int) size) {
  686. // Standard-compliant code path. Allocate a buffer that is large enough.
  687. if ((*buf = (char *) malloc(len + 1)) == NULL) {
  688. len = -1;
  689. } else {
  690. va_copy(ap_copy, ap);
  691. len = vsnprintf(*buf, len + 1, fmt, ap_copy);
  692. va_end(ap_copy);
  693. }
  694. }
  695. return len;
  696. }
  697. static void write_chunk(struct connection *conn, const char *buf, int len) {
  698. char chunk_size[50];
  699. int n = mg_snprintf(chunk_size, sizeof(chunk_size), "%X\r\n", len);
  700. spool(&conn->remote_iobuf, chunk_size, n);
  701. spool(&conn->remote_iobuf, buf, len);
  702. spool(&conn->remote_iobuf, "\r\n", 2);
  703. }
  704. int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap,
  705. int chunked) {
  706. char mem[IOBUF_SIZE], *buf = mem;
  707. int len;
  708. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  709. if (chunked) {
  710. write_chunk((struct connection *) conn, buf, len);
  711. } else {
  712. len = mg_write(conn, buf, (size_t) len);
  713. }
  714. }
  715. if (buf != mem && buf != NULL) {
  716. free(buf);
  717. }
  718. return len;
  719. }
  720. int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
  721. int len;
  722. va_list ap;
  723. va_start(ap, fmt);
  724. len = mg_vprintf(conn, fmt, ap, 0);
  725. va_end(ap);
  726. return len;
  727. }
  728. #ifndef MONGOOSE_NO_SOCKETPAIR
  729. static int mg_socketpair(sock_t sp[2]) {
  730. struct sockaddr_in sa;
  731. sock_t sock, ret = -1;
  732. socklen_t len = sizeof(sa);
  733. sp[0] = sp[1] = INVALID_SOCKET;
  734. (void) memset(&sa, 0, sizeof(sa));
  735. sa.sin_family = AF_INET;
  736. sa.sin_port = htons(0);
  737. sa.sin_addr.s_addr = htonl(0x7f000001);
  738. if ((sock = socket(AF_INET, SOCK_STREAM, 0)) != INVALID_SOCKET &&
  739. !bind(sock, (struct sockaddr *) &sa, len) &&
  740. !listen(sock, 1) &&
  741. !getsockname(sock, (struct sockaddr *) &sa, &len) &&
  742. (sp[0] = socket(AF_INET, SOCK_STREAM, 6)) != -1 &&
  743. !connect(sp[0], (struct sockaddr *) &sa, len) &&
  744. (sp[1] = accept(sock,(struct sockaddr *) &sa, &len)) != INVALID_SOCKET) {
  745. set_close_on_exec(sp[0]);
  746. set_close_on_exec(sp[1]);
  747. ret = 0;
  748. } else {
  749. if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
  750. if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
  751. sp[0] = sp[1] = INVALID_SOCKET;
  752. }
  753. closesocket(sock);
  754. return ret;
  755. }
  756. #endif
  757. static int is_error(int n) {
  758. return n == 0 ||
  759. (n < 0 && errno != EINTR && errno != EINPROGRESS &&
  760. errno != EAGAIN && errno != EWOULDBLOCK
  761. #ifdef _WIN32
  762. && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
  763. #endif
  764. );
  765. }
  766. static void discard_leading_iobuf_bytes(struct iobuf *io, int n) {
  767. if (n >= 0 && n <= io->len) {
  768. memmove(io->buf, io->buf + n, io->len - n);
  769. io->len -= n;
  770. }
  771. }
  772. #ifndef MONGOOSE_NO_CGI
  773. #ifdef _WIN32
  774. struct threadparam {
  775. sock_t s;
  776. HANDLE hPipe;
  777. };
  778. static int wait_until_ready(sock_t sock, int for_read) {
  779. fd_set set;
  780. FD_ZERO(&set);
  781. FD_SET(sock, &set);
  782. select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0);
  783. return 1;
  784. }
  785. static void *push_to_stdin(void *arg) {
  786. struct threadparam *tp = arg;
  787. int n, sent, stop = 0;
  788. DWORD k;
  789. char buf[IOBUF_SIZE];
  790. while (!stop && wait_until_ready(tp->s, 1) &&
  791. (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
  792. if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
  793. for (sent = 0; !stop && sent < n; sent += k) {
  794. if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
  795. }
  796. }
  797. DBG(("%s", "FORWARED EVERYTHING TO CGI"));
  798. CloseHandle(tp->hPipe);
  799. free(tp);
  800. _endthread();
  801. return NULL;
  802. }
  803. static void *pull_from_stdout(void *arg) {
  804. struct threadparam *tp = arg;
  805. int k, stop = 0;
  806. DWORD n, sent;
  807. char buf[IOBUF_SIZE];
  808. while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
  809. for (sent = 0; !stop && sent < n; sent += k) {
  810. if (wait_until_ready(tp->s, 0) &&
  811. (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1;
  812. }
  813. }
  814. DBG(("%s", "EOF FROM CGI"));
  815. CloseHandle(tp->hPipe);
  816. shutdown(tp->s, 2); // Without this, IO thread may get truncated data
  817. closesocket(tp->s);
  818. free(tp);
  819. _endthread();
  820. return NULL;
  821. }
  822. static void spawn_stdio_thread(sock_t sock, HANDLE hPipe,
  823. void *(*func)(void *)) {
  824. struct threadparam *tp = malloc(sizeof(*tp));
  825. if (tp != NULL) {
  826. tp->s = sock;
  827. tp->hPipe = hPipe;
  828. mg_start_thread(func, tp);
  829. }
  830. }
  831. static void abs_path(const char *utf8_path, char *abs_path, size_t len) {
  832. wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
  833. to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
  834. GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
  835. WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
  836. }
  837. static pid_t start_process(char *interp, const char *cmd, const char *env,
  838. const char *envp[], const char *dir, sock_t sock) {
  839. STARTUPINFOW si = {0};
  840. PROCESS_INFORMATION pi = {0};
  841. HANDLE a[2], b[2], me = GetCurrentProcess();
  842. wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
  843. char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
  844. cmdline[MAX_PATH_SIZE], *p;
  845. DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
  846. FILE *fp;
  847. si.cb = sizeof(si);
  848. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  849. si.wShowWindow = SW_HIDE;
  850. si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  851. CreatePipe(&a[0], &a[1], NULL, 0);
  852. CreatePipe(&b[0], &b[1], NULL, 0);
  853. DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
  854. DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
  855. if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
  856. buf[0] = buf[1] = '\0';
  857. fgets(buf, sizeof(buf), fp);
  858. buf[sizeof(buf) - 1] = '\0';
  859. if (buf[0] == '#' && buf[1] == '!') {
  860. interp = buf + 2;
  861. for (p = interp + strlen(interp);
  862. isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0';
  863. }
  864. fclose(fp);
  865. }
  866. if (interp != NULL) {
  867. abs_path(interp, buf4, ARRAY_SIZE(buf4));
  868. interp = buf4;
  869. }
  870. abs_path(dir, buf5, ARRAY_SIZE(buf5));
  871. to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
  872. mg_snprintf(cmdline, sizeof(cmdline), "%s%s\"%s\"",
  873. interp ? interp : "", interp ? " " : "", cmd);
  874. to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
  875. if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
  876. (void *) env, full_dir, &si, &pi) != 0) {
  877. spawn_stdio_thread(sock, a[1], push_to_stdin);
  878. spawn_stdio_thread(sock, b[0], pull_from_stdout);
  879. } else {
  880. CloseHandle(a[1]);
  881. CloseHandle(b[0]);
  882. closesocket(sock);
  883. }
  884. DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
  885. CloseHandle(si.hStdOutput);
  886. CloseHandle(si.hStdInput);
  887. CloseHandle(a[0]);
  888. CloseHandle(b[1]);
  889. CloseHandle(pi.hThread);
  890. CloseHandle(pi.hProcess);
  891. return pi.hProcess;
  892. }
  893. #else
  894. static pid_t start_process(const char *interp, const char *cmd, const char *env,
  895. const char *envp[], const char *dir, sock_t sock) {
  896. char buf[500];
  897. pid_t pid = fork();
  898. (void) env;
  899. if (pid == 0) {
  900. (void) chdir(dir);
  901. (void) dup2(sock, 0);
  902. (void) dup2(sock, 1);
  903. closesocket(sock);
  904. // After exec, all signal handlers are restored to their default values,
  905. // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
  906. // implementation, SIGCHLD's handler will leave unchanged after exec
  907. // if it was set to be ignored. Restore it to default action.
  908. signal(SIGCHLD, SIG_DFL);
  909. if (interp == NULL) {
  910. execle(cmd, cmd, NULL, envp);
  911. } else {
  912. execle(interp, interp, cmd, NULL, envp);
  913. }
  914. snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n"
  915. "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp,
  916. interp == NULL ? "" : " ", cmd, strerror(errno));
  917. send(1, buf, strlen(buf), 0);
  918. exit(EXIT_FAILURE); // exec call failed
  919. }
  920. return pid;
  921. }
  922. #endif // _WIN32
  923. // This structure helps to create an environment for the spawned CGI program.
  924. // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  925. // last element must be NULL.
  926. // However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  927. // strings must reside in a contiguous buffer. The end of the buffer is
  928. // marked by two '\0' characters.
  929. // We satisfy both worlds: we create an envp array (which is vars), all
  930. // entries are actually pointers inside buf.
  931. struct cgi_env_block {
  932. struct mg_connection *conn;
  933. char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
  934. const char *vars[MAX_CGI_ENVIR_VARS]; // char *envp[]
  935. int len; // Space taken
  936. int nvars; // Number of variables in envp[]
  937. };
  938. // Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  939. // pointer into the vars array.
  940. static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
  941. int n, space;
  942. char *added;
  943. va_list ap;
  944. // Calculate how much space is left in the buffer
  945. space = sizeof(block->buf) - block->len - 2;
  946. assert(space >= 0);
  947. // Make a pointer to the free space int the buffer
  948. added = block->buf + block->len;
  949. // Copy VARIABLE=VALUE\0 string into the free space
  950. va_start(ap, fmt);
  951. n = mg_vsnprintf(added, (size_t) space, fmt, ap);
  952. va_end(ap);
  953. // Make sure we do not overflow buffer and the envp array
  954. if (n > 0 && n + 1 < space &&
  955. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  956. // Append a pointer to the added string into the envp array
  957. block->vars[block->nvars++] = added;
  958. // Bump up used length counter. Include \0 terminator
  959. block->len += n + 1;
  960. }
  961. return added;
  962. }
  963. static void addenv2(struct cgi_env_block *blk, const char *name) {
  964. const char *s;
  965. if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s);
  966. }
  967. static void prepare_cgi_environment(struct connection *conn,
  968. const char *prog,
  969. struct cgi_env_block *blk) {
  970. struct mg_connection *ri = &conn->mg_conn;
  971. const char *s, *slash;
  972. char *p, **opts = conn->server->config_options;
  973. int i;
  974. blk->len = blk->nvars = 0;
  975. blk->conn = ri;
  976. if ((s = getenv("SERVER_NAME")) != NULL) {
  977. addenv(blk, "SERVER_NAME=%s", s);
  978. } else {
  979. addenv(blk, "SERVER_NAME=%s", conn->server->local_ip);
  980. }
  981. addenv(blk, "SERVER_ROOT=%s", opts[DOCUMENT_ROOT]);
  982. addenv(blk, "DOCUMENT_ROOT=%s", opts[DOCUMENT_ROOT]);
  983. addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MONGOOSE_VERSION);
  984. // Prepare the environment block
  985. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  986. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  987. addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
  988. // TODO(lsm): fix this for IPv6 case
  989. //addenv(blk, "SERVER_PORT=%d", ri->remote_port);
  990. addenv(blk, "REQUEST_METHOD=%s", ri->request_method);
  991. addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
  992. addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
  993. addenv(blk, "REQUEST_URI=%s%s%s", ri->uri,
  994. ri->query_string == NULL ? "" : "?",
  995. ri->query_string == NULL ? "" : ri->query_string);
  996. // SCRIPT_NAME
  997. if (conn->path_info != NULL) {
  998. addenv(blk, "SCRIPT_NAME=%.*s",
  999. (int) (strlen(ri->uri) - strlen(conn->path_info)), ri->uri);
  1000. addenv(blk, "PATH_INFO=%s", conn->path_info);
  1001. } else {
  1002. s = strrchr(prog, '/');
  1003. slash = strrchr(ri->uri, '/');
  1004. addenv(blk, "SCRIPT_NAME=%.*s%s",
  1005. slash == NULL ? 0 : (int) (slash - ri->uri), ri->uri,
  1006. s == NULL ? prog : s);
  1007. }
  1008. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  1009. addenv(blk, "PATH_TRANSLATED=%s", prog);
  1010. #ifdef MONGOOSE_USE_SSL
  1011. addenv(blk, "HTTPS=%s", conn->ssl != NULL ? "on" : "off");
  1012. #else
  1013. addenv(blk, "HTTPS=%s", "off");
  1014. #endif
  1015. if ((s = mg_get_header(ri, "Content-Type")) != NULL)
  1016. addenv(blk, "CONTENT_TYPE=%s", s);
  1017. if (ri->query_string != NULL)
  1018. addenv(blk, "QUERY_STRING=%s", ri->query_string);
  1019. if ((s = mg_get_header(ri, "Content-Length")) != NULL)
  1020. addenv(blk, "CONTENT_LENGTH=%s", s);
  1021. addenv2(blk, "PATH");
  1022. addenv2(blk, "TMP");
  1023. addenv2(blk, "TEMP");
  1024. addenv2(blk, "TMPDIR");
  1025. addenv2(blk, "PERLLIB");
  1026. addenv2(blk, ENV_EXPORT_TO_CGI);
  1027. #if defined(_WIN32)
  1028. addenv2(blk, "COMSPEC");
  1029. addenv2(blk, "SYSTEMROOT");
  1030. addenv2(blk, "SystemDrive");
  1031. addenv2(blk, "ProgramFiles");
  1032. addenv2(blk, "ProgramFiles(x86)");
  1033. addenv2(blk, "CommonProgramFiles(x86)");
  1034. #else
  1035. addenv2(blk, "LD_LIBRARY_PATH");
  1036. #endif // _WIN32
  1037. // Add all headers as HTTP_* variables
  1038. for (i = 0; i < ri->num_headers; i++) {
  1039. p = addenv(blk, "HTTP_%s=%s",
  1040. ri->http_headers[i].name, ri->http_headers[i].value);
  1041. // Convert variable name into uppercase, and change - to _
  1042. for (; *p != '=' && *p != '\0'; p++) {
  1043. if (*p == '-')
  1044. *p = '_';
  1045. *p = (char) toupper(* (unsigned char *) p);
  1046. }
  1047. }
  1048. blk->vars[blk->nvars++] = NULL;
  1049. blk->buf[blk->len++] = '\0';
  1050. assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  1051. assert(blk->len > 0);
  1052. assert(blk->len < (int) sizeof(blk->buf));
  1053. }
  1054. static const char cgi_status[] = "HTTP/1.1 200 OK\r\n";
  1055. static void open_cgi_endpoint(struct connection *conn, const char *prog) {
  1056. struct cgi_env_block blk;
  1057. char dir[MAX_PATH_SIZE], *p;
  1058. sock_t fds[2];
  1059. prepare_cgi_environment(conn, prog, &blk);
  1060. // CGI must be executed in its own directory. 'dir' must point to the
  1061. // directory containing executable program, 'p' must point to the
  1062. // executable program name relative to 'dir'.
  1063. if ((p = strrchr(prog, '/')) == NULL) {
  1064. mg_snprintf(dir, sizeof(dir), "%s", ".");
  1065. } else {
  1066. mg_snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
  1067. }
  1068. // Try to create socketpair in a loop until success. mg_socketpair()
  1069. // can be interrupted by a signal and fail.
  1070. // TODO(lsm): use sigaction to restart interrupted syscall
  1071. do {
  1072. mg_socketpair(fds);
  1073. } while (fds[0] == INVALID_SOCKET);
  1074. if (start_process(conn->server->config_options[CGI_INTERPRETER],
  1075. prog, blk.buf, blk.vars, dir, fds[1]) > 0) {
  1076. conn->endpoint_type = EP_CGI;
  1077. conn->endpoint.cgi_sock = fds[0];
  1078. spool(&conn->remote_iobuf, cgi_status, sizeof(cgi_status) - 1);
  1079. conn->mg_conn.status_code = 200;
  1080. conn->flags |= CONN_BUFFER;
  1081. } else {
  1082. closesocket(fds[0]);
  1083. send_http_error(conn, 500, "start_process(%s) failed", prog);
  1084. }
  1085. #ifndef _WIN32
  1086. closesocket(fds[1]); // On Windows, CGI stdio thread closes that socket
  1087. #endif
  1088. }
  1089. static void read_from_cgi(struct connection *conn) {
  1090. struct iobuf *io = &conn->remote_iobuf;
  1091. char buf[IOBUF_SIZE], buf2[sizeof(buf)], *s = buf2;
  1092. const char *status = "500";
  1093. struct mg_connection c;
  1094. int len, s_len = sizeof(cgi_status) - 1,
  1095. n = recv(conn->endpoint.cgi_sock, buf, sizeof(buf), 0);
  1096. DBG(("%p %d", conn, n));
  1097. if (is_error(n)) {
  1098. close_local_endpoint(conn);
  1099. } else if (n > 0) {
  1100. spool(&conn->remote_iobuf, buf, n);
  1101. if (conn->flags & CONN_BUFFER) {
  1102. len = get_request_len(io->buf + s_len, io->len - s_len);
  1103. if (len == 0) return;
  1104. if (len > 0) {
  1105. memset(&c, 0, sizeof(c));
  1106. memcpy(buf2, io->buf + s_len, len);
  1107. buf2[len - 1] = '\0';
  1108. parse_http_headers(&s, &c);
  1109. if (mg_get_header(&c, "Location") != NULL) {
  1110. status = "302";
  1111. } else if ((status = (char *) mg_get_header(&c, "Status")) == NULL) {
  1112. status = "200";
  1113. }
  1114. }
  1115. memcpy(io->buf + 9, status, 3);
  1116. conn->mg_conn.status_code = atoi(status);
  1117. conn->flags &= ~CONN_BUFFER;
  1118. }
  1119. }
  1120. }
  1121. static void forward_post_data(struct connection *conn) {
  1122. struct iobuf *io = &conn->local_iobuf;
  1123. int n = send(conn->endpoint.cgi_sock, io->buf, io->len, 0);
  1124. discard_leading_iobuf_bytes(io, n);
  1125. }
  1126. #endif // !MONGOOSE_NO_CGI
  1127. // 'sa' must be an initialized address to bind to
  1128. static sock_t open_listening_socket(union socket_address *sa) {
  1129. socklen_t len = sizeof(*sa);
  1130. sock_t on = 1, sock = INVALID_SOCKET;
  1131. if ((sock = socket(sa->sa.sa_family, SOCK_STREAM, 6)) != INVALID_SOCKET &&
  1132. !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
  1133. !bind(sock, &sa->sa, sa->sa.sa_family == AF_INET ?
  1134. sizeof(sa->sin) : sizeof(sa->sa)) &&
  1135. !listen(sock, SOMAXCONN)) {
  1136. set_non_blocking_mode(sock);
  1137. // In case port was set to 0, get the real port number
  1138. (void) getsockname(sock, &sa->sa, &len);
  1139. } else if (sock != INVALID_SOCKET) {
  1140. closesocket(sock);
  1141. sock = INVALID_SOCKET;
  1142. }
  1143. return sock;
  1144. }
  1145. static char *mg_strdup(const char *str) {
  1146. char *copy = (char *) malloc(strlen(str) + 1);
  1147. if (copy != NULL) {
  1148. strcpy(copy, str);
  1149. }
  1150. return copy;
  1151. }
  1152. static int isbyte(int n) {
  1153. return n >= 0 && n <= 255;
  1154. }
  1155. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  1156. int n, a, b, c, d, slash = 32, len = 0;
  1157. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  1158. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  1159. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
  1160. slash >= 0 && slash < 33) {
  1161. len = n;
  1162. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
  1163. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  1164. }
  1165. return len;
  1166. }
  1167. // Verify given socket address against the ACL.
  1168. // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  1169. static int check_acl(const char *acl, uint32_t remote_ip) {
  1170. int allowed, flag;
  1171. uint32_t net, mask;
  1172. struct vec vec;
  1173. // If any ACL is set, deny by default
  1174. allowed = acl == NULL ? '+' : '-';
  1175. while ((acl = next_option(acl, &vec, NULL)) != NULL) {
  1176. flag = vec.ptr[0];
  1177. if ((flag != '+' && flag != '-') ||
  1178. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  1179. return -1;
  1180. }
  1181. if (net == (remote_ip & mask)) {
  1182. allowed = flag;
  1183. }
  1184. }
  1185. return allowed == '+';
  1186. }
  1187. static void sockaddr_to_string(char *buf, size_t len,
  1188. const union socket_address *usa) {
  1189. buf[0] = '\0';
  1190. #if defined(MONGOOSE_USE_IPV6)
  1191. inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
  1192. (void *) &usa->sin.sin_addr :
  1193. (void *) &usa->sin6.sin6_addr, buf, len);
  1194. #elif defined(_WIN32)
  1195. // Only Windoze Vista (and newer) have inet_ntop()
  1196. strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
  1197. #else
  1198. inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
  1199. #endif
  1200. }
  1201. static struct connection *accept_new_connection(struct mg_server *server) {
  1202. union socket_address sa;
  1203. socklen_t len = sizeof(sa);
  1204. sock_t sock = INVALID_SOCKET;
  1205. struct connection *conn = NULL;
  1206. // NOTE(lsm): on Windows, sock is always > FD_SETSIZE
  1207. if ((sock = accept(server->listening_sock, &sa.sa, &len)) == INVALID_SOCKET) {
  1208. } else if (!check_acl(server->config_options[ACCESS_CONTROL_LIST],
  1209. ntohl(* (uint32_t *) &sa.sin.sin_addr))) {
  1210. // NOTE(lsm): check_acl doesn't work for IPv6
  1211. closesocket(sock);
  1212. } else if ((conn = (struct connection *) calloc(1, sizeof(*conn))) == NULL) {
  1213. closesocket(sock);
  1214. #ifdef MONGOOSE_USE_SSL
  1215. } else if (server->ssl_ctx != NULL &&
  1216. ((conn->ssl = SSL_new(server->ssl_ctx)) == NULL ||
  1217. SSL_set_fd(conn->ssl, sock) != 1)) {
  1218. DBG(("SSL error"));
  1219. closesocket(sock);
  1220. free(conn);
  1221. conn = NULL;
  1222. #endif
  1223. } else {
  1224. set_close_on_exec(sock);
  1225. set_non_blocking_mode(sock);
  1226. conn->server = server;
  1227. conn->client_sock = sock;
  1228. sockaddr_to_string(conn->mg_conn.remote_ip,
  1229. sizeof(conn->mg_conn.remote_ip), &sa);
  1230. conn->mg_conn.remote_port = ntohs(sa.sin.sin_port);
  1231. conn->mg_conn.server_param = server->server_data;
  1232. conn->mg_conn.local_ip = server->local_ip;
  1233. conn->mg_conn.local_port = ntohs(server->lsa.sin.sin_port);
  1234. LINKED_LIST_ADD_TO_FRONT(&server->active_connections, &conn->link);
  1235. DBG(("added conn %p", conn));
  1236. }
  1237. return conn;
  1238. }
  1239. static void close_conn(struct connection *conn) {
  1240. LINKED_LIST_REMOVE(&conn->link);
  1241. closesocket(conn->client_sock);
  1242. close_local_endpoint(conn);
  1243. if (conn->server->http_close_handler)
  1244. conn->server->http_close_handler(&conn->mg_conn);
  1245. DBG(("%p %d %d", conn, conn->flags, conn->endpoint_type));
  1246. free(conn->request); // It's OK to free(NULL), ditto below
  1247. free(conn->path_info);
  1248. free(conn->remote_iobuf.buf);
  1249. free(conn->local_iobuf.buf);
  1250. #ifdef MONGOOSE_USE_SSL
  1251. if (conn->ssl != NULL) SSL_free(conn->ssl);
  1252. #endif
  1253. free(conn);
  1254. }
  1255. // Protect against directory disclosure attack by removing '..',
  1256. // excessive '/' and '\' characters
  1257. static void remove_double_dots_and_double_slashes(char *s) {
  1258. char *p = s;
  1259. while (*s != '\0') {
  1260. *p++ = *s++;
  1261. if (s[-1] == '/' || s[-1] == '\\') {
  1262. // Skip all following slashes, backslashes and double-dots
  1263. while (s[0] != '\0') {
  1264. if (s[0] == '/' || s[0] == '\\') { s++; }
  1265. else if (s[0] == '.' && s[1] == '.') { s += 2; }
  1266. else { break; }
  1267. }
  1268. }
  1269. }
  1270. *p = '\0';
  1271. }
  1272. int mg_url_decode(const char *src, int src_len, char *dst,
  1273. int dst_len, int is_form_url_encoded) {
  1274. int i, j, a, b;
  1275. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  1276. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  1277. if (src[i] == '%' && i < src_len - 2 &&
  1278. isxdigit(* (const unsigned char *) (src + i + 1)) &&
  1279. isxdigit(* (const unsigned char *) (src + i + 2))) {
  1280. a = tolower(* (const unsigned char *) (src + i + 1));
  1281. b = tolower(* (const unsigned char *) (src + i + 2));
  1282. dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
  1283. i += 2;
  1284. } else if (is_form_url_encoded && src[i] == '+') {
  1285. dst[j] = ' ';
  1286. } else {
  1287. dst[j] = src[i];
  1288. }
  1289. }
  1290. dst[j] = '\0'; // Null-terminate the destination
  1291. return i >= src_len ? j : -1;
  1292. }
  1293. static int is_valid_http_method(const char *method) {
  1294. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  1295. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  1296. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  1297. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND")
  1298. || !strcmp(method, "MKCOL");
  1299. }
  1300. // Parse HTTP request, fill in mg_request structure.
  1301. // This function modifies the buffer by NUL-terminating
  1302. // HTTP request components, header names and header values.
  1303. // Note that len must point to the last \n of HTTP headers.
  1304. static int parse_http_message(char *buf, int len, struct mg_connection *ri) {
  1305. int is_request, n;
  1306. // Reset the connection. Make sure that we don't touch fields that are
  1307. // set elsewhere: remote_ip, remote_port, server_param
  1308. ri->request_method = ri->uri = ri->http_version = ri->query_string = NULL;
  1309. ri->num_headers = ri->status_code = ri->is_websocket = ri->content_len = 0;
  1310. buf[len - 1] = '\0';
  1311. // RFC says that all initial whitespaces should be ingored
  1312. while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
  1313. buf++;
  1314. }
  1315. ri->request_method = skip(&buf, " ");
  1316. ri->uri = skip(&buf, " ");
  1317. ri->http_version = skip(&buf, "\r\n");
  1318. // HTTP message could be either HTTP request or HTTP response, e.g.
  1319. // "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..."
  1320. is_request = is_valid_http_method(ri->request_method);
  1321. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
  1322. (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  1323. len = -1;
  1324. } else {
  1325. if (is_request) {
  1326. ri->http_version += 5;
  1327. }
  1328. parse_http_headers(&buf, ri);
  1329. if ((ri->query_string = strchr(ri->uri, '?')) != NULL) {
  1330. *(char *) ri->query_string++ = '\0';
  1331. }
  1332. n = (int) strlen(ri->uri);
  1333. mg_url_decode(ri->uri, n, (char *) ri->uri, n + 1, 0);
  1334. remove_double_dots_and_double_slashes((char *) ri->uri);
  1335. }
  1336. return len;
  1337. }
  1338. static int lowercase(const char *s) {
  1339. return tolower(* (const unsigned char *) s);
  1340. }
  1341. static int mg_strcasecmp(const char *s1, const char *s2) {
  1342. int diff;
  1343. do {
  1344. diff = lowercase(s1++) - lowercase(s2++);
  1345. } while (diff == 0 && s1[-1] != '\0');
  1346. return diff;
  1347. }
  1348. static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
  1349. int diff = 0;
  1350. if (len > 0)
  1351. do {
  1352. diff = lowercase(s1++) - lowercase(s2++);
  1353. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1354. return diff;
  1355. }
  1356. // Return HTTP header value, or NULL if not found.
  1357. const char *mg_get_header(const struct mg_connection *ri, const char *s) {
  1358. int i;
  1359. for (i = 0; i < ri->num_headers; i++)
  1360. if (!mg_strcasecmp(s, ri->http_headers[i].name))
  1361. return ri->http_headers[i].value;
  1362. return NULL;
  1363. }
  1364. #ifndef MONGOOSE_NO_FILESYSTEM
  1365. // Perform case-insensitive match of string against pattern
  1366. static int match_prefix(const char *pattern, int pattern_len, const char *str) {
  1367. const char *or_str;
  1368. int len, res, i = 0, j = 0;
  1369. if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
  1370. res = match_prefix(pattern, or_str - pattern, str);
  1371. return res > 0 ? res :
  1372. match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str);
  1373. }
  1374. for (; i < pattern_len; i++, j++) {
  1375. if (pattern[i] == '?' && str[j] != '\0') {
  1376. continue;
  1377. } else if (pattern[i] == '$') {
  1378. return str[j] == '\0' ? j : -1;
  1379. } else if (pattern[i] == '*') {
  1380. i++;
  1381. if (pattern[i] == '*') {
  1382. i++;
  1383. len = (int) strlen(str + j);
  1384. } else {
  1385. len = (int) strcspn(str + j, "/");
  1386. }
  1387. if (i == pattern_len) {
  1388. return j + len;
  1389. }
  1390. do {
  1391. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1392. } while (res == -1 && len-- > 0);
  1393. return res == -1 ? -1 : j + res + len;
  1394. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1395. return -1;
  1396. }
  1397. }
  1398. return j;
  1399. }
  1400. static int must_hide_file(struct connection *conn, const char *path) {
  1401. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  1402. const char *pattern = conn->server->config_options[HIDE_FILES_PATTERN];
  1403. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
  1404. (pattern != NULL && match_prefix(pattern, strlen(pattern), path) > 0);
  1405. }
  1406. // Return 1 if real file has been found, 0 otherwise
  1407. static int convert_uri_to_file_name(struct connection *conn, char *buf,
  1408. size_t buf_len, file_stat_t *st) {
  1409. struct vec a, b;
  1410. const char *rewrites = conn->server->config_options[URL_REWRITES];
  1411. const char *root = conn->server->config_options[DOCUMENT_ROOT];
  1412. #ifndef MONGOOSE_NO_CGI
  1413. const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
  1414. char *p;
  1415. #endif
  1416. const char *uri = conn->mg_conn.uri;
  1417. int match_len;
  1418. // No filesystem access
  1419. if (root == NULL) return 0;
  1420. // Handle URL rewrites
  1421. mg_snprintf(buf, buf_len, "%s%s", root, uri);
  1422. while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
  1423. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  1424. mg_snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.ptr, uri + match_len);
  1425. break;
  1426. }
  1427. }
  1428. if (stat(buf, st) == 0) return 1;
  1429. #ifndef MONGOOSE_NO_CGI
  1430. // Support PATH_INFO for CGI scripts.
  1431. for (p = buf + strlen(root) + 2; *p != '\0'; p++) {
  1432. if (*p == '/') {
  1433. *p = '\0';
  1434. if (match_prefix(cgi_pat, strlen(cgi_pat), buf) > 0 && !stat(buf, st)) {
  1435. DBG(("!!!! [%s]", buf));
  1436. *p = '/';
  1437. conn->path_info = mg_strdup(p);
  1438. *p = '\0';
  1439. return 1;
  1440. }
  1441. *p = '/';
  1442. }
  1443. }
  1444. #endif
  1445. return 0;
  1446. }
  1447. #endif // MONGOOSE_NO_FILESYSTEM
  1448. static int should_keep_alive(const struct mg_connection *conn) {
  1449. const char *method = conn->request_method;
  1450. const char *http_version = conn->http_version;
  1451. const char *header = mg_get_header(conn, "Connection");
  1452. return method != NULL && (!strcmp(method, "GET") ||
  1453. ((struct connection *) conn)->endpoint_type == EP_USER) &&
  1454. ((header != NULL && !mg_strcasecmp(header, "keep-alive")) ||
  1455. (header == NULL && http_version && !strcmp(http_version, "1.1")));
  1456. }
  1457. int mg_write(struct mg_connection *c, const void *buf, int len) {
  1458. return spool(&((struct connection *) c)->remote_iobuf, buf, len);
  1459. }
  1460. void mg_send_status(struct mg_connection *c, int status) {
  1461. if (c->status_code == 0) {
  1462. c->status_code = status;
  1463. mg_printf(c, "HTTP/1.1 %d %s\r\n", status, status_code_to_str(status));
  1464. }
  1465. }
  1466. void mg_send_header(struct mg_connection *c, const char *name, const char *v) {
  1467. if (c->status_code == 0) {
  1468. c->status_code = 200;
  1469. mg_printf(c, "HTTP/1.1 %d %s\r\n", 200, status_code_to_str(200));
  1470. }
  1471. mg_printf(c, "%s: %s\r\n", name, v);
  1472. }
  1473. static void terminate_headers(struct mg_connection *c) {
  1474. struct connection *conn = (struct connection *) c;
  1475. if (!(conn->flags & CONN_HEADERS_SENT)) {
  1476. mg_send_header(c, "Transfer-Encoding", "chunked");
  1477. mg_write(c, "\r\n", 2);
  1478. conn->flags |= CONN_HEADERS_SENT;
  1479. }
  1480. }
  1481. void mg_send_data(struct mg_connection *c, const void *data, int data_len) {
  1482. terminate_headers(c);
  1483. write_chunk((struct connection *) c, (const char *) data, data_len);
  1484. }
  1485. void mg_printf_data(struct mg_connection *c, const char *fmt, ...) {
  1486. va_list ap;
  1487. terminate_headers(c);
  1488. va_start(ap, fmt);
  1489. mg_vprintf(c, fmt, ap, 1);
  1490. va_end(ap);
  1491. }
  1492. #if !defined(MONGOOSE_NO_WEBSOCKET) || !defined(MONGOOSE_NO_AUTH)
  1493. static int is_big_endian(void) {
  1494. static const int n = 1;
  1495. return ((char *) &n)[0] == 0;
  1496. }
  1497. #endif
  1498. #ifndef MONGOOSE_NO_WEBSOCKET
  1499. // START OF SHA-1 code
  1500. // Copyright(c) By Steve Reid <steve@edmweb.com>
  1501. #define SHA1HANDSOFF
  1502. #if defined(__sun)
  1503. #include "solarisfixes.h"
  1504. #endif
  1505. union char64long16 { unsigned char c[64]; uint32_t l[16]; };
  1506. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  1507. static uint32_t blk0(union char64long16 *block, int i) {
  1508. // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
  1509. if (!is_big_endian()) {
  1510. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  1511. (rol(block->l[i], 8) & 0x00FF00FF);
  1512. }
  1513. return block->l[i];
  1514. }
  1515. #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
  1516. ^block->l[(i+2)&15]^block->l[i&15],1))
  1517. #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
  1518. #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
  1519. #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
  1520. #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
  1521. #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
  1522. typedef struct {
  1523. uint32_t state[5];
  1524. uint32_t count[2];
  1525. unsigned char buffer[64];
  1526. } SHA1_CTX;
  1527. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
  1528. uint32_t a, b, c, d, e;
  1529. union char64long16 block[1];
  1530. memcpy(block, buffer, 64);
  1531. a = state[0];
  1532. b = state[1];
  1533. c = state[2];
  1534. d = state[3];
  1535. e = state[4];
  1536. R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
  1537. R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
  1538. R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
  1539. R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
  1540. R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
  1541. R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
  1542. R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
  1543. R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
  1544. R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
  1545. R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
  1546. R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
  1547. R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
  1548. R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
  1549. R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
  1550. R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
  1551. R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
  1552. R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
  1553. R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
  1554. R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
  1555. R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
  1556. state[0] += a;
  1557. state[1] += b;
  1558. state[2] += c;
  1559. state[3] += d;
  1560. state[4] += e;
  1561. // Erase working structures. The order of operations is important,
  1562. // used to ensure that compiler doesn't optimize those out.
  1563. memset(block, 0, sizeof(block));
  1564. a = b = c = d = e = 0;
  1565. (void) a; (void) b; (void) c; (void) d; (void) e;
  1566. }
  1567. static void SHA1Init(SHA1_CTX* context) {
  1568. context->state[0] = 0x67452301;
  1569. context->state[1] = 0xEFCDAB89;
  1570. context->state[2] = 0x98BADCFE;
  1571. context->state[3] = 0x10325476;
  1572. context->state[4] = 0xC3D2E1F0;
  1573. context->count[0] = context->count[1] = 0;
  1574. }
  1575. static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
  1576. uint32_t len) {
  1577. uint32_t i, j;
  1578. j = context->count[0];
  1579. if ((context->count[0] += len << 3) < j)
  1580. context->count[1]++;
  1581. context->count[1] += (len>>29);
  1582. j = (j >> 3) & 63;
  1583. if ((j + len) > 63) {
  1584. memcpy(&context->buffer[j], data, (i = 64-j));
  1585. SHA1Transform(context->state, context->buffer);
  1586. for ( ; i + 63 < len; i += 64) {
  1587. SHA1Transform(context->state, &data[i]);
  1588. }
  1589. j = 0;
  1590. }
  1591. else i = 0;
  1592. memcpy(&context->buffer[j], &data[i], len - i);
  1593. }
  1594. static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) {
  1595. unsigned i;
  1596. unsigned char finalcount[8], c;
  1597. for (i = 0; i < 8; i++) {
  1598. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  1599. >> ((3-(i & 3)) * 8) ) & 255);
  1600. }
  1601. c = 0200;
  1602. SHA1Update(context, &c, 1);
  1603. while ((context->count[0] & 504) != 448) {
  1604. c = 0000;
  1605. SHA1Update(context, &c, 1);
  1606. }
  1607. SHA1Update(context, finalcount, 8);
  1608. for (i = 0; i < 20; i++) {
  1609. digest[i] = (unsigned char)
  1610. ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
  1611. }
  1612. memset(context, '\0', sizeof(*context));
  1613. memset(&finalcount, '\0', sizeof(finalcount));
  1614. }
  1615. // END OF SHA1 CODE
  1616. static void base64_encode(const unsigned char *src, int src_len, char *dst) {
  1617. static const char *b64 =
  1618. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  1619. int i, j, a, b, c;
  1620. for (i = j = 0; i < src_len; i += 3) {
  1621. a = src[i];
  1622. b = i + 1 >= src_len ? 0 : src[i + 1];
  1623. c = i + 2 >= src_len ? 0 : src[i + 2];
  1624. dst[j++] = b64[a >> 2];
  1625. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  1626. if (i + 1 < src_len) {
  1627. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  1628. }
  1629. if (i + 2 < src_len) {
  1630. dst[j++] = b64[c & 63];
  1631. }
  1632. }
  1633. while (j % 4 != 0) {
  1634. dst[j++] = '=';
  1635. }
  1636. dst[j++] = '\0';
  1637. }
  1638. static void send_websocket_handshake(struct mg_connection *conn,
  1639. const char *key) {
  1640. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  1641. char buf[500], sha[20], b64_sha[sizeof(sha) * 2];
  1642. SHA1_CTX sha_ctx;
  1643. mg_snprintf(buf, sizeof(buf), "%s%s", key, magic);
  1644. SHA1Init(&sha_ctx);
  1645. SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
  1646. SHA1Final((unsigned char *) sha, &sha_ctx);
  1647. base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
  1648. mg_snprintf(buf, sizeof(buf), "%s%s%s",
  1649. "HTTP/1.1 101 Switching Protocols\r\n"
  1650. "Upgrade: websocket\r\n"
  1651. "Connection: Upgrade\r\n"
  1652. "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
  1653. mg_write(conn, buf, strlen(buf));
  1654. }
  1655. static int deliver_websocket_frame(struct connection *conn) {
  1656. // Having buf unsigned char * is important, as it is used below in arithmetic
  1657. unsigned char *buf = (unsigned char *) conn->local_iobuf.buf;
  1658. int i, len, buf_len = conn->local_iobuf.len, frame_len = 0,
  1659. mask_len = 0, header_len = 0, data_len = 0, buffered = 0;
  1660. if (buf_len >= 2) {
  1661. len = buf[1] & 127;
  1662. mask_len = buf[1] & 128 ? 4 : 0;
  1663. if (len < 126 && buf_len >= mask_len) {
  1664. data_len = len;
  1665. header_len = 2 + mask_len;
  1666. } else if (len == 126 && buf_len >= 4 + mask_len) {
  1667. header_len = 4 + mask_len;
  1668. data_len = ((((int) buf[2]) << 8) + buf[3]);
  1669. } else if (buf_len >= 10 + mask_len) {
  1670. header_len = 10 + mask_len;
  1671. data_len = (int) (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +
  1672. htonl(* (uint32_t *) &buf[6]);
  1673. }
  1674. }
  1675. frame_len = header_len + data_len;
  1676. buffered = frame_len > 0 && frame_len <= buf_len;
  1677. if (buffered) {
  1678. conn->mg_conn.content_len = data_len;
  1679. conn->mg_conn.content = (char *) buf + header_len;
  1680. conn->mg_conn.wsbits = buf[0];
  1681. // Apply mask if necessary
  1682. if (mask_len > 0) {
  1683. for (i = 0; i < data_len; i++) {
  1684. buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
  1685. }
  1686. }
  1687. // Call the handler and remove frame from the iobuf
  1688. if (conn->server->request_handler(&conn->mg_conn) == MG_CLIENT_CLOSE) {
  1689. conn->flags |= CONN_SPOOL_DONE;
  1690. }
  1691. discard_leading_iobuf_bytes(&conn->local_iobuf, frame_len);
  1692. }
  1693. return buffered;
  1694. }
  1695. int mg_websocket_write(struct mg_connection* conn, int opcode,
  1696. const char *data, size_t data_len) {
  1697. unsigned char *copy;
  1698. size_t copy_len = 0;
  1699. int retval = -1;
  1700. if ((copy = (unsigned char *) malloc(data_len + 10)) == NULL) {
  1701. return -1;
  1702. }
  1703. copy[0] = 0x80 + (opcode & 0x0f);
  1704. // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2
  1705. if (data_len < 126) {
  1706. // Inline 7-bit length field
  1707. copy[1] = data_len;
  1708. memcpy(copy + 2, data, data_len);
  1709. copy_len = 2 + data_len;
  1710. } else if (data_len <= 0xFFFF) {
  1711. // 16-bit length field
  1712. copy[1] = 126;
  1713. * (uint16_t *) (copy + 2) = (uint16_t) htons((uint16_t) data_len);
  1714. memcpy(copy + 4, data, data_len);
  1715. copy_len = 4 + data_len;
  1716. } else {
  1717. // 64-bit length field
  1718. copy[1] = 127;
  1719. * (uint32_t *) (copy + 2) = (uint32_t)
  1720. htonl((uint32_t) ((uint64_t) data_len >> 32));
  1721. * (uint32_t *) (copy + 6) = (uint32_t) htonl(data_len & 0xffffffff);
  1722. memcpy(copy + 10, data, data_len);
  1723. copy_len = 10 + data_len;
  1724. }
  1725. if (copy_len > 0) {
  1726. retval = mg_write(conn, copy, copy_len);
  1727. }
  1728. free(copy);
  1729. return retval;
  1730. }
  1731. static void send_websocket_handshake_if_requested(struct mg_connection *conn) {
  1732. const char *ver = mg_get_header(conn, "Sec-WebSocket-Version"),
  1733. *key = mg_get_header(conn, "Sec-WebSocket-Key");
  1734. if (ver != NULL && key != NULL) {
  1735. conn->is_websocket = 1;
  1736. send_websocket_handshake(conn, key);
  1737. }
  1738. }
  1739. static void ping_idle_websocket_connection(struct connection *conn, time_t t) {
  1740. if (t - conn->last_activity_time > MONGOOSE_USE_WEBSOCKET_PING_INTERVAL) {
  1741. mg_websocket_write(&conn->mg_conn, 0x9, "", 0);
  1742. }
  1743. }
  1744. #else
  1745. #define ping_idle_websocket_connection(conn, t)
  1746. #endif // !MONGOOSE_NO_WEBSOCKET
  1747. static void write_terminating_chunk(struct connection *conn) {
  1748. mg_write(&conn->mg_conn, "0\r\n\r\n", 5);
  1749. }
  1750. static int call_request_handler(struct connection *conn) {
  1751. int result;
  1752. conn->mg_conn.content = conn->local_iobuf.buf;
  1753. switch ((result = conn->server->request_handler(&conn->mg_conn))) {
  1754. case MG_REQUEST_CALL_AGAIN: conn->flags |= CONN_LONG_RUNNING; break;
  1755. case MG_REQUEST_NOT_PROCESSED: break;
  1756. default:
  1757. if (conn->flags & CONN_HEADERS_SENT) {
  1758. write_terminating_chunk(conn);
  1759. }
  1760. close_local_endpoint(conn);
  1761. break;
  1762. }
  1763. return result;
  1764. }
  1765. static void callback_http_client_on_connect(struct connection *conn) {
  1766. int ok = 1, ret;
  1767. socklen_t len = sizeof(ok);
  1768. conn->flags &= ~CONN_CONNECTING;
  1769. ret = getsockopt(conn->client_sock, SOL_SOCKET, SO_ERROR, (char *) &ok, &len);
  1770. #ifdef MONGOOSE_USE_SSL
  1771. if (ret == 0 && ok == 0 && conn->ssl != NULL) {
  1772. int res = SSL_connect(conn->ssl), ssl_err = SSL_get_error(conn->ssl, res);
  1773. //DBG(("%p res %d %d", conn, res, ssl_err));
  1774. if (res == 1) {
  1775. conn->flags = CONN_SSL_HANDS_SHAKEN;
  1776. } else if (res == 0 || ssl_err == 2 || ssl_err == 3) {
  1777. conn->flags |= CONN_CONNECTING;
  1778. return; // Call us again
  1779. } else {
  1780. ok = 1;
  1781. }
  1782. }
  1783. #endif
  1784. conn->mg_conn.status_code =
  1785. (ret == 0 && ok == 0) ? MG_CONNECT_SUCCESS : MG_CONNECT_FAILURE;
  1786. if (conn->handler(&conn->mg_conn) || ok != 0) {
  1787. conn->flags |= CONN_CLOSE;
  1788. }
  1789. }
  1790. #ifdef MONGOOSE_HEXDUMP
  1791. static void hexdump(const struct connection *conn, const void *buf,
  1792. int len, const char *marker) {
  1793. const unsigned char *p = (const unsigned char *) buf;
  1794. char path[MAX_PATH_SIZE], date[100], ascii[17];
  1795. FILE *fp;
  1796. if (!match_prefix(MONGOOSE_HEXDUMP, strlen(MONGOOSE_HEXDUMP),
  1797. conn->mg_conn.remote_ip)) {
  1798. return;
  1799. }
  1800. snprintf(path, sizeof(path), "%s.%hu.txt",
  1801. conn->mg_conn.remote_ip, conn->mg_conn.remote_port);
  1802. if ((fp = fopen(path, "a")) != NULL) {
  1803. time_t cur_time = time(NULL);
  1804. int i, idx;
  1805. strftime(date, sizeof(date), "%d/%b/%Y %H:%M:%S", localtime(&cur_time));
  1806. fprintf(fp, "%s %s %d bytes\n", marker, date, len);
  1807. for (i = 0; i < len; i++) {
  1808. idx = i % 16;
  1809. if (idx == 0) {
  1810. if (i > 0) fprintf(fp, " %s\n", ascii);
  1811. fprintf(fp, "%04x ", i);
  1812. }
  1813. fprintf(fp, " %02x", p[i]);
  1814. ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
  1815. ascii[idx + 1] = '\0';
  1816. }
  1817. while (i++ % 16) fprintf(fp, "%s", " ");
  1818. fprintf(fp, " %s\n\n", ascii);
  1819. fclose(fp);
  1820. }
  1821. }
  1822. #endif
  1823. static void write_to_socket(struct connection *conn) {
  1824. struct iobuf *io = &conn->remote_iobuf;
  1825. int n = 0;
  1826. if (conn->endpoint_type == EP_CLIENT && conn->flags & CONN_CONNECTING) {
  1827. callback_http_client_on_connect(conn);
  1828. return;
  1829. }
  1830. #ifdef MONGOOSE_USE_SSL
  1831. if (conn->ssl != NULL) {
  1832. n = SSL_write(conn->ssl, io->buf, io->len);
  1833. } else
  1834. #endif
  1835. { n = send(conn->client_sock, io->buf, io->len, 0); }
  1836. DBG(("%p Written %d of %d(%d): [%.*s ...]",
  1837. conn, n, io->len, io->size, io->len < 40 ? io->len : 40, io->buf));
  1838. #ifdef MONGOOSE_HEXDUMP
  1839. hexdump(conn, io->buf, n, "->");
  1840. #endif
  1841. if (is_error(n)) {
  1842. conn->flags |= CONN_CLOSE;
  1843. } else if (n > 0) {
  1844. discard_leading_iobuf_bytes(io, n);
  1845. conn->num_bytes_sent += n;
  1846. }
  1847. if (io->len == 0 && conn->flags & CONN_SPOOL_DONE) {
  1848. conn->flags |= CONN_CLOSE;
  1849. }
  1850. }
  1851. const char *mg_get_mime_type(const char *path, const char *default_mime_type) {
  1852. const char *ext;
  1853. size_t i, path_len;
  1854. path_len = strlen(path);
  1855. for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) {
  1856. ext = path + (path_len - static_builtin_mime_types[i].ext_len);
  1857. if (path_len > static_builtin_mime_types[i].ext_len &&
  1858. mg_strcasecmp(ext, static_builtin_mime_types[i].extension) == 0) {
  1859. return static_builtin_mime_types[i].mime_type;
  1860. }
  1861. }
  1862. return default_mime_type;
  1863. }
  1864. #ifndef MONGOOSE_NO_FILESYSTEM
  1865. // Convert month to the month number. Return -1 on error, or month number
  1866. static int get_month_index(const char *s) {
  1867. static const char *month_names[] = {
  1868. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  1869. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  1870. };
  1871. int i;
  1872. for (i = 0; i < (int) ARRAY_SIZE(month_names); i++)
  1873. if (!strcmp(s, month_names[i]))
  1874. return i;
  1875. return -1;
  1876. }
  1877. static int num_leap_years(int year) {
  1878. return year / 4 - year / 100 + year / 400;
  1879. }
  1880. // Parse UTC date-time string, and return the corresponding time_t value.
  1881. static time_t parse_date_string(const char *datetime) {
  1882. static const unsigned short days_before_month[] = {
  1883. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  1884. };
  1885. char month_str[32];
  1886. int second, minute, hour, day, month, year, leap_days, days;
  1887. time_t result = (time_t) 0;
  1888. if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
  1889. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1890. (sscanf(datetime, "%d %3s %d %d:%d:%d",
  1891. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1892. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
  1893. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1894. (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
  1895. &day, month_str, &year, &hour, &minute, &second) == 6)) &&
  1896. year > 1970 &&
  1897. (month = get_month_index(month_str)) != -1) {
  1898. leap_days = num_leap_years(year) - num_leap_years(1970);
  1899. year -= 1970;
  1900. days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
  1901. result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
  1902. }
  1903. return result;
  1904. }
  1905. // Look at the "path" extension and figure what mime type it has.
  1906. // Store mime type in the vector.
  1907. static void get_mime_type(const struct mg_server *server, const char *path,
  1908. struct vec *vec) {
  1909. struct vec ext_vec, mime_vec;
  1910. const char *list, *ext;
  1911. size_t path_len;
  1912. path_len = strlen(path);
  1913. // Scan user-defined mime types first, in case user wants to
  1914. // override default mime types.
  1915. list = server->config_options[EXTRA_MIME_TYPES];
  1916. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  1917. // ext now points to the path suffix
  1918. ext = path + path_len - ext_vec.len;
  1919. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  1920. *vec = mime_vec;
  1921. return;
  1922. }
  1923. }
  1924. vec->ptr = mg_get_mime_type(path, "text/plain");
  1925. vec->len = strlen(vec->ptr);
  1926. }
  1927. static const char *suggest_connection_header(const struct mg_connection *conn) {
  1928. return should_keep_alive(conn) ? "keep-alive" : "close";
  1929. }
  1930. static void construct_etag(char *buf, size_t buf_len, const file_stat_t *st) {
  1931. mg_snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
  1932. (unsigned long) st->st_mtime, (int64_t) st->st_size);
  1933. }
  1934. // Return True if we should reply 304 Not Modified.
  1935. static int is_not_modified(const struct connection *conn,
  1936. const file_stat_t *stp) {
  1937. char etag[64];
  1938. const char *ims = mg_get_header(&conn->mg_conn, "If-Modified-Since");
  1939. const char *inm = mg_get_header(&conn->mg_conn, "If-None-Match");
  1940. construct_etag(etag, sizeof(etag), stp);
  1941. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  1942. (ims != NULL && stp->st_mtime <= parse_date_string(ims));
  1943. }
  1944. // For given directory path, substitute it to valid index file.
  1945. // Return 0 if index file has been found, -1 if not found.
  1946. // If the file is found, it's stats is returned in stp.
  1947. static int find_index_file(struct connection *conn, char *path,
  1948. size_t path_len, file_stat_t *stp) {
  1949. const char *list = conn->server->config_options[INDEX_FILES];
  1950. file_stat_t st;
  1951. struct vec filename_vec;
  1952. size_t n = strlen(path), found = 0;
  1953. // The 'path' given to us points to the directory. Remove all trailing
  1954. // directory separator characters from the end of the path, and
  1955. // then append single directory separator character.
  1956. while (n > 0 && path[n - 1] == '/') {
  1957. n--;
  1958. }
  1959. path[n] = '/';
  1960. // Traverse index files list. For each entry, append it to the given
  1961. // path and see if the file exists. If it exists, break the loop
  1962. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  1963. // Ignore too long entries that may overflow path buffer
  1964. if (filename_vec.len > (int) (path_len - (n + 2)))
  1965. continue;
  1966. // Prepare full path to the index file
  1967. strncpy(path + n + 1, filename_vec.ptr, filename_vec.len);
  1968. path[n + 1 + filename_vec.len] = '\0';
  1969. //DBG(("[%s]", path));
  1970. // Does it exist?
  1971. if (!stat(path, &st)) {
  1972. // Yes it does, break the loop
  1973. *stp = st;
  1974. found = 1;
  1975. break;
  1976. }
  1977. }
  1978. // If no index file exists, restore directory path
  1979. if (!found) {
  1980. path[n] = '\0';
  1981. }
  1982. return found;
  1983. }
  1984. static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
  1985. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  1986. }
  1987. static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  1988. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
  1989. }
  1990. static void open_file_endpoint(struct connection *conn, const char *path,
  1991. file_stat_t *st) {
  1992. char date[64], lm[64], etag[64], range[64], headers[500];
  1993. const char *msg = "OK", *hdr;
  1994. time_t curtime = time(NULL);
  1995. int64_t r1, r2;
  1996. struct vec mime_vec;
  1997. int n;
  1998. conn->endpoint_type = EP_FILE;
  1999. set_close_on_exec(conn->endpoint.fd);
  2000. conn->mg_conn.status_code = 200;
  2001. get_mime_type(conn->server, path, &mime_vec);
  2002. conn->cl = st->st_size;
  2003. range[0] = '\0';
  2004. // If Range: header specified, act accordingly
  2005. r1 = r2 = 0;
  2006. hdr = mg_get_header(&conn->mg_conn, "Range");
  2007. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
  2008. r1 >= 0 && r2 >= 0) {
  2009. conn->mg_conn.status_code = 206;
  2010. conn->cl = n == 2 ? (r2 > conn->cl ? conn->cl : r2) - r1 + 1: conn->cl - r1;
  2011. mg_snprintf(range, sizeof(range), "Content-Range: bytes "
  2012. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  2013. r1, r1 + conn->cl - 1, (int64_t) st->st_size);
  2014. msg = "Partial Content";
  2015. lseek(conn->endpoint.fd, r1, SEEK_SET);
  2016. }
  2017. // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  2018. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
  2019. gmt_time_string(date, sizeof(date), &curtime);
  2020. gmt_time_string(lm, sizeof(lm), &st->st_mtime);
  2021. construct_etag(etag, sizeof(etag), st);
  2022. n = mg_snprintf(headers, sizeof(headers),
  2023. "HTTP/1.1 %d %s\r\n"
  2024. "Date: %s\r\n"
  2025. "Last-Modified: %s\r\n"
  2026. "Etag: %s\r\n"
  2027. "Content-Type: %.*s\r\n"
  2028. "Content-Length: %" INT64_FMT "\r\n"
  2029. "Connection: %s\r\n"
  2030. "Accept-Ranges: bytes\r\n"
  2031. "%s%s\r\n",
  2032. conn->mg_conn.status_code, msg, date, lm, etag,
  2033. (int) mime_vec.len, mime_vec.ptr, conn->cl,
  2034. suggest_connection_header(&conn->mg_conn),
  2035. range, MONGOOSE_USE_EXTRA_HTTP_HEADERS);
  2036. spool(&conn->remote_iobuf, headers, n);
  2037. if (!strcmp(conn->mg_conn.request_method, "HEAD")) {
  2038. conn->flags |= CONN_SPOOL_DONE;
  2039. close(conn->endpoint.fd);
  2040. conn->endpoint_type = EP_NONE;
  2041. }
  2042. }
  2043. #endif // MONGOOSE_NO_FILESYSTEM
  2044. static void call_request_handler_if_data_is_buffered(struct connection *conn) {
  2045. struct iobuf *loc = &conn->local_iobuf;
  2046. struct mg_connection *c = &conn->mg_conn;
  2047. #ifndef MONGOOSE_NO_WEBSOCKET
  2048. if (conn->mg_conn.is_websocket) {
  2049. do { } while (deliver_websocket_frame(conn));
  2050. } else
  2051. #endif
  2052. if ((size_t) loc->len >= c->content_len &&
  2053. call_request_handler(conn) == MG_REQUEST_NOT_PROCESSED) {
  2054. open_local_endpoint(conn, 1);
  2055. }
  2056. }
  2057. #if !defined(MONGOOSE_NO_DIRECTORY_LISTING) || !defined(MONGOOSE_NO_DAV)
  2058. #ifdef _WIN32
  2059. struct dirent {
  2060. char d_name[MAX_PATH_SIZE];
  2061. };
  2062. typedef struct DIR {
  2063. HANDLE handle;
  2064. WIN32_FIND_DATAW info;
  2065. struct dirent result;
  2066. } DIR;
  2067. // Implementation of POSIX opendir/closedir/readdir for Windows.
  2068. static DIR *opendir(const char *name) {
  2069. DIR *dir = NULL;
  2070. wchar_t wpath[MAX_PATH_SIZE];
  2071. DWORD attrs;
  2072. if (name == NULL) {
  2073. SetLastError(ERROR_BAD_ARGUMENTS);
  2074. } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
  2075. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2076. } else {
  2077. to_wchar(name, wpath, ARRAY_SIZE(wpath));
  2078. attrs = GetFileAttributesW(wpath);
  2079. if (attrs != 0xFFFFFFFF &&
  2080. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  2081. (void) wcscat(wpath, L"\\*");
  2082. dir->handle = FindFirstFileW(wpath, &dir->info);
  2083. dir->result.d_name[0] = '\0';
  2084. } else {
  2085. free(dir);
  2086. dir = NULL;
  2087. }
  2088. }
  2089. return dir;
  2090. }
  2091. static int closedir(DIR *dir) {
  2092. int result = 0;
  2093. if (dir != NULL) {
  2094. if (dir->handle != INVALID_HANDLE_VALUE)
  2095. result = FindClose(dir->handle) ? 0 : -1;
  2096. free(dir);
  2097. } else {
  2098. result = -1;
  2099. SetLastError(ERROR_BAD_ARGUMENTS);
  2100. }
  2101. return result;
  2102. }
  2103. static struct dirent *readdir(DIR *dir) {
  2104. struct dirent *result = 0;
  2105. if (dir) {
  2106. if (dir->handle != INVALID_HANDLE_VALUE) {
  2107. result = &dir->result;
  2108. (void) WideCharToMultiByte(CP_UTF8, 0,
  2109. dir->info.cFileName, -1, result->d_name,
  2110. sizeof(result->d_name), NULL, NULL);
  2111. if (!FindNextFileW(dir->handle, &dir->info)) {
  2112. (void) FindClose(dir->handle);
  2113. dir->handle = INVALID_HANDLE_VALUE;
  2114. }
  2115. } else {
  2116. SetLastError(ERROR_FILE_NOT_FOUND);
  2117. }
  2118. } else {
  2119. SetLastError(ERROR_BAD_ARGUMENTS);
  2120. }
  2121. return result;
  2122. }
  2123. #endif // _WIN32 POSIX opendir/closedir/readdir implementation
  2124. static int scan_directory(struct connection *conn, const char *dir,
  2125. struct dir_entry **arr) {
  2126. char path[MAX_PATH_SIZE];
  2127. struct dir_entry *p;
  2128. struct dirent *dp;
  2129. int arr_size = 0, arr_ind = 0, inc = 100;
  2130. DIR *dirp;
  2131. *arr = NULL;
  2132. if ((dirp = (opendir(dir))) == NULL) return 0;
  2133. while ((dp = readdir(dirp)) != NULL) {
  2134. // Do not show current dir and hidden files
  2135. if (!strcmp(dp->d_name, ".") ||
  2136. !strcmp(dp->d_name, "..") ||
  2137. must_hide_file(conn, dp->d_name)) {
  2138. continue;
  2139. }
  2140. mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  2141. // Resize the array if nesessary
  2142. if (arr_ind >= arr_size) {
  2143. if ((p = (struct dir_entry *)
  2144. realloc(*arr, (inc + arr_size) * sizeof(**arr))) != NULL) {
  2145. // Memset new chunk to zero, otherwize st_mtime will have garbage which
  2146. // can make strftime() segfault, see
  2147. // http://code.google.com/p/mongoose/issues/detail?id=79
  2148. memset(p + arr_size, 0, sizeof(**arr) * inc);
  2149. *arr = p;
  2150. arr_size += inc;
  2151. }
  2152. }
  2153. if (arr_ind < arr_size) {
  2154. (*arr)[arr_ind].conn = conn;
  2155. (*arr)[arr_ind].file_name = strdup(dp->d_name);
  2156. stat(path, &(*arr)[arr_ind].st);
  2157. arr_ind++;
  2158. }
  2159. }
  2160. closedir(dirp);
  2161. return arr_ind;
  2162. }
  2163. static void mg_url_encode(const char *src, char *dst, size_t dst_len) {
  2164. static const char *dont_escape = "._-$,;~()";
  2165. static const char *hex = "0123456789abcdef";
  2166. const char *end = dst + dst_len - 1;
  2167. for (; *src != '\0' && dst < end; src++, dst++) {
  2168. if (isalnum(*(const unsigned char *) src) ||
  2169. strchr(dont_escape, * (const unsigned char *) src) != NULL) {
  2170. *dst = *src;
  2171. } else if (dst + 2 < end) {
  2172. dst[0] = '%';
  2173. dst[1] = hex[(* (const unsigned char *) src) >> 4];
  2174. dst[2] = hex[(* (const unsigned char *) src) & 0xf];
  2175. dst += 2;
  2176. }
  2177. }
  2178. *dst = '\0';
  2179. }
  2180. #endif // !NO_DIRECTORY_LISTING || !MONGOOSE_NO_DAV
  2181. #ifndef MONGOOSE_NO_DIRECTORY_LISTING
  2182. static void print_dir_entry(const struct dir_entry *de) {
  2183. char size[64], mod[64], href[MAX_PATH_SIZE * 3], chunk[MAX_PATH_SIZE * 4];
  2184. int64_t fsize = de->st.st_size;
  2185. int is_dir = S_ISDIR(de->st.st_mode), n;
  2186. const char *slash = is_dir ? "/" : "";
  2187. if (is_dir) {
  2188. mg_snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
  2189. } else {
  2190. // We use (signed) cast below because MSVC 6 compiler cannot
  2191. // convert unsigned __int64 to double.
  2192. if (fsize < 1024) {
  2193. mg_snprintf(size, sizeof(size), "%d", (int) fsize);
  2194. } else if (fsize < 0x100000) {
  2195. mg_snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
  2196. } else if (fsize < 0x40000000) {
  2197. mg_snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
  2198. } else {
  2199. mg_snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
  2200. }
  2201. }
  2202. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.st_mtime));
  2203. mg_url_encode(de->file_name, href, sizeof(href));
  2204. n = mg_snprintf(chunk, sizeof(chunk),
  2205. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  2206. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2207. de->conn->mg_conn.uri, href, slash, de->file_name, slash,
  2208. mod, size);
  2209. write_chunk((struct connection *) de->conn, chunk, n);
  2210. }
  2211. // Sort directory entries by size, or name, or modification time.
  2212. // On windows, __cdecl specification is needed in case if project is built
  2213. // with __stdcall convention. qsort always requires __cdels callback.
  2214. static int __cdecl compare_dir_entries(const void *p1, const void *p2) {
  2215. const struct dir_entry *a = (const struct dir_entry *) p1,
  2216. *b = (const struct dir_entry *) p2;
  2217. const char *qs = a->conn->mg_conn.query_string ?
  2218. a->conn->mg_conn.query_string : "na";
  2219. int cmp_result = 0;
  2220. if (S_ISDIR(a->st.st_mode) && !S_ISDIR(b->st.st_mode)) {
  2221. return -1; // Always put directories on top
  2222. } else if (!S_ISDIR(a->st.st_mode) && S_ISDIR(b->st.st_mode)) {
  2223. return 1; // Always put directories on top
  2224. } else if (*qs == 'n') {
  2225. cmp_result = strcmp(a->file_name, b->file_name);
  2226. } else if (*qs == 's') {
  2227. cmp_result = a->st.st_size == b->st.st_size ? 0 :
  2228. a->st.st_size > b->st.st_size ? 1 : -1;
  2229. } else if (*qs == 'd') {
  2230. cmp_result = a->st.st_mtime == b->st.st_mtime ? 0 :
  2231. a->st.st_mtime > b->st.st_mtime ? 1 : -1;
  2232. }
  2233. return qs[1] == 'd' ? -cmp_result : cmp_result;
  2234. }
  2235. static void send_directory_listing(struct connection *conn, const char *dir) {
  2236. char buf[2000];
  2237. struct dir_entry *arr = NULL;
  2238. int i, num_entries, sort_direction = conn->mg_conn.query_string != NULL &&
  2239. conn->mg_conn.query_string[1] == 'd' ? 'a' : 'd';
  2240. conn->mg_conn.status_code = 200;
  2241. mg_snprintf(buf, sizeof(buf), "%s",
  2242. "HTTP/1.1 200 OK\r\n"
  2243. "Transfer-Encoding: Chunked\r\n"
  2244. "Content-Type: text/html; charset=utf-8\r\n\r\n");
  2245. spool(&conn->remote_iobuf, buf, strlen(buf));
  2246. mg_snprintf(buf, sizeof(buf),
  2247. "<html><head><title>Index of %s</title>"
  2248. "<style>th {text-align: left;}</style></head>"
  2249. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  2250. "<tr><th><a href=\"?n%c\">Name</a></th>"
  2251. "<th><a href=\"?d%c\">Modified</a></th>"
  2252. "<th><a href=\"?s%c\">Size</a></th></tr>"
  2253. "<tr><td colspan=\"3\"><hr></td></tr>",
  2254. conn->mg_conn.uri, conn->mg_conn.uri,
  2255. sort_direction, sort_direction, sort_direction);
  2256. write_chunk(conn, buf, strlen(buf));
  2257. num_entries = scan_directory(conn, dir, &arr);
  2258. qsort(arr, num_entries, sizeof(arr[0]), compare_dir_entries);
  2259. for (i = 0; i < num_entries; i++) {
  2260. print_dir_entry(&arr[i]);
  2261. free(arr[i].file_name);
  2262. }
  2263. free(arr);
  2264. write_terminating_chunk(conn);
  2265. close_local_endpoint(conn);
  2266. }
  2267. #endif // MONGOOSE_NO_DIRECTORY_LISTING
  2268. #ifndef MONGOOSE_NO_DAV
  2269. static void print_props(struct connection *conn, const char *uri,
  2270. file_stat_t *stp) {
  2271. char mtime[64], buf[MAX_PATH_SIZE + 200];
  2272. gmt_time_string(mtime, sizeof(mtime), &stp->st_mtime);
  2273. mg_snprintf(buf, sizeof(buf),
  2274. "<d:response>"
  2275. "<d:href>%s</d:href>"
  2276. "<d:propstat>"
  2277. "<d:prop>"
  2278. "<d:resourcetype>%s</d:resourcetype>"
  2279. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  2280. "<d:getlastmodified>%s</d:getlastmodified>"
  2281. "</d:prop>"
  2282. "<d:status>HTTP/1.1 200 OK</d:status>"
  2283. "</d:propstat>"
  2284. "</d:response>\n",
  2285. uri, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
  2286. (int64_t) stp->st_size, mtime);
  2287. spool(&conn->remote_iobuf, buf, strlen(buf));
  2288. }
  2289. static void handle_propfind(struct connection *conn, const char *path,
  2290. file_stat_t *stp) {
  2291. static const char header[] = "HTTP/1.1 207 Multi-Status\r\n"
  2292. "Connection: close\r\n"
  2293. "Content-Type: text/xml; charset=utf-8\r\n\r\n"
  2294. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  2295. "<d:multistatus xmlns:d='DAV:'>\n";
  2296. static const char footer[] = "</d:multistatus>";
  2297. const char *depth = mg_get_header(&conn->mg_conn, "Depth"),
  2298. *list_dir = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
  2299. conn->mg_conn.status_code = 207;
  2300. spool(&conn->remote_iobuf, header, sizeof(header) - 1);
  2301. // Print properties for the requested resource itself
  2302. print_props(conn, conn->mg_conn.uri, stp);
  2303. // If it is a directory, print directory entries too if Depth is not 0
  2304. if (S_ISDIR(stp->st_mode) && !mg_strcasecmp(list_dir, "yes") &&
  2305. (depth == NULL || strcmp(depth, "0") != 0)) {
  2306. struct dir_entry *arr = NULL;
  2307. int i, num_entries = scan_directory(conn, path, &arr);
  2308. for (i = 0; i < num_entries; i++) {
  2309. char buf[MAX_PATH_SIZE], buf2[sizeof(buf) * 3];
  2310. struct dir_entry *de = &arr[i];
  2311. mg_snprintf(buf, sizeof(buf), "%s%s", de->conn->mg_conn.uri,
  2312. de->file_name);
  2313. mg_url_encode(buf, buf2, sizeof(buf2) - 1);
  2314. print_props(conn, buf, &de->st);
  2315. }
  2316. }
  2317. spool(&conn->remote_iobuf, footer, sizeof(footer) - 1);
  2318. close_local_endpoint(conn);
  2319. }
  2320. static void handle_mkcol(struct connection *conn, const char *path) {
  2321. int status_code = 500;
  2322. if (conn->mg_conn.content_len > 0) {
  2323. status_code = 415;
  2324. } else if (!mkdir(path, 0755)) {
  2325. status_code = 201;
  2326. } else if (errno == EEXIST) {
  2327. status_code = 405;
  2328. } else if (errno == EACCES) {
  2329. status_code = 403;
  2330. } else if (errno == ENOENT) {
  2331. status_code = 409;
  2332. }
  2333. send_http_error(conn, status_code, NULL);
  2334. }
  2335. static int remove_directory(const char *dir) {
  2336. char path[MAX_PATH_SIZE];
  2337. struct dirent *dp;
  2338. file_stat_t st;
  2339. DIR *dirp;
  2340. if ((dirp = opendir(dir)) == NULL) return 0;
  2341. while ((dp = readdir(dirp)) != NULL) {
  2342. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
  2343. mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  2344. stat(path, &st);
  2345. if (S_ISDIR(st.st_mode)) {
  2346. remove_directory(path);
  2347. } else {
  2348. remove(path);
  2349. }
  2350. }
  2351. closedir(dirp);
  2352. rmdir(dir);
  2353. return 1;
  2354. }
  2355. static void handle_delete(struct connection *conn, const char *path) {
  2356. file_stat_t st;
  2357. if (stat(path, &st) != 0) {
  2358. send_http_error(conn, 404, NULL);
  2359. } else if (S_ISDIR(st.st_mode)) {
  2360. remove_directory(path);
  2361. send_http_error(conn, 204, NULL);
  2362. } else if (!remove(path) == 0) {
  2363. send_http_error(conn, 204, NULL);
  2364. } else {
  2365. send_http_error(conn, 423, NULL);
  2366. }
  2367. }
  2368. // For a given PUT path, create all intermediate subdirectories
  2369. // for given path. Return 0 if the path itself is a directory,
  2370. // or -1 on error, 1 if OK.
  2371. static int put_dir(const char *path) {
  2372. char buf[MAX_PATH_SIZE];
  2373. const char *s, *p;
  2374. file_stat_t st;
  2375. // Create intermediate directories if they do not exist
  2376. for (s = p = path + 1; (p = strchr(s, '/')) != NULL; s = ++p) {
  2377. if (p - path >= (int) sizeof(buf)) return -1; // Buffer overflow
  2378. memcpy(buf, path, p - path);
  2379. buf[p - path] = '\0';
  2380. if (stat(buf, &st) != 0 && mkdir(buf, 0755) != 0) return -1;
  2381. if (p[1] == '\0') return 0; // Path is a directory itself
  2382. }
  2383. return 1;
  2384. }
  2385. static void handle_put(struct connection *conn, const char *path) {
  2386. file_stat_t st;
  2387. const char *range, *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
  2388. int64_t r1, r2;
  2389. int rc;
  2390. conn->mg_conn.status_code = !stat(path, &st) ? 200 : 201;
  2391. if ((rc = put_dir(path)) == 0) {
  2392. mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\n\r\n",
  2393. conn->mg_conn.status_code);
  2394. close_local_endpoint(conn);
  2395. } else if (rc == -1) {
  2396. send_http_error(conn, 500, "put_dir: %s", strerror(errno));
  2397. } else if (cl_hdr == NULL) {
  2398. send_http_error(conn, 411, NULL);
  2399. #ifdef _WIN32
  2400. //On Windows, open() is a macro with 2 params
  2401. } else if ((conn->endpoint.fd =
  2402. open(path, O_RDWR | O_CREAT | O_TRUNC)) < 0) {
  2403. #else
  2404. } else if ((conn->endpoint.fd =
  2405. open(path, O_RDWR | O_CREAT | O_TRUNC, 0644)) < 0) {
  2406. #endif
  2407. send_http_error(conn, 500, "open(%s): %s", path, strerror(errno));
  2408. } else {
  2409. DBG(("PUT [%s] %d", path, conn->local_iobuf.len));
  2410. conn->endpoint_type = EP_PUT;
  2411. set_close_on_exec(conn->endpoint.fd);
  2412. range = mg_get_header(&conn->mg_conn, "Content-Range");
  2413. conn->cl = to64(cl_hdr);
  2414. r1 = r2 = 0;
  2415. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  2416. conn->mg_conn.status_code = 206;
  2417. lseek(conn->endpoint.fd, r1, SEEK_SET);
  2418. conn->cl = r2 > r1 ? r2 - r1 + 1: conn->cl - r1;
  2419. }
  2420. mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
  2421. conn->mg_conn.status_code);
  2422. }
  2423. }
  2424. static void forward_put_data(struct connection *conn) {
  2425. struct iobuf *io = &conn->local_iobuf;
  2426. int n = write(conn->endpoint.fd, io->buf, io->len);
  2427. if (n > 0) {
  2428. discard_leading_iobuf_bytes(io, n);
  2429. conn->cl -= n;
  2430. if (conn->cl <= 0) {
  2431. close_local_endpoint(conn);
  2432. }
  2433. }
  2434. }
  2435. #endif // MONGOOSE_NO_DAV
  2436. static void send_options(struct connection *conn) {
  2437. static const char reply[] = "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, "
  2438. "CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL\r\nDAV: 1\r\n\r\n";
  2439. spool(&conn->remote_iobuf, reply, sizeof(reply) - 1);
  2440. conn->flags |= CONN_SPOOL_DONE;
  2441. }
  2442. #ifndef MONGOOSE_NO_AUTH
  2443. void mg_send_digest_auth_request(struct mg_connection *c) {
  2444. struct connection *conn = (struct connection *) c;
  2445. c->status_code = 401;
  2446. mg_printf(c,
  2447. "HTTP/1.1 401 Unauthorized\r\n"
  2448. "WWW-Authenticate: Digest qop=\"auth\", "
  2449. "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
  2450. conn->server->config_options[AUTH_DOMAIN],
  2451. (unsigned long) time(NULL));
  2452. close_local_endpoint(conn);
  2453. }
  2454. // Use the global passwords file, if specified by auth_gpass option,
  2455. // or search for .htpasswd in the requested directory.
  2456. static FILE *open_auth_file(struct connection *conn, const char *path) {
  2457. char name[MAX_PATH_SIZE];
  2458. const char *p, *gpass = conn->server->config_options[GLOBAL_AUTH_FILE];
  2459. file_stat_t st;
  2460. FILE *fp = NULL;
  2461. if (gpass != NULL) {
  2462. // Use global passwords file
  2463. fp = fopen(gpass, "r");
  2464. } else if (!stat(path, &st) && S_ISDIR(st.st_mode)) {
  2465. mg_snprintf(name, sizeof(name), "%s%c%s", path, '/', PASSWORDS_FILE_NAME);
  2466. fp = fopen(name, "r");
  2467. } else {
  2468. // Try to find .htpasswd in requested directory.
  2469. if ((p = strrchr(path, '/')) == NULL) p = path;
  2470. mg_snprintf(name, sizeof(name), "%.*s%c%s",
  2471. (int) (p - path), path, '/', PASSWORDS_FILE_NAME);
  2472. fp = fopen(name, "r");
  2473. }
  2474. return fp;
  2475. }
  2476. #if !defined(HAVE_MD5) && !defined(MONGOOSE_NO_AUTH)
  2477. typedef struct MD5Context {
  2478. uint32_t buf[4];
  2479. uint32_t bits[2];
  2480. unsigned char in[64];
  2481. } MD5_CTX;
  2482. static void byteReverse(unsigned char *buf, unsigned longs) {
  2483. uint32_t t;
  2484. // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
  2485. if (is_big_endian()) {
  2486. do {
  2487. t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  2488. ((unsigned) buf[1] << 8 | buf[0]);
  2489. * (uint32_t *) buf = t;
  2490. buf += 4;
  2491. } while (--longs);
  2492. }
  2493. }
  2494. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  2495. #define F2(x, y, z) F1(z, x, y)
  2496. #define F3(x, y, z) (x ^ y ^ z)
  2497. #define F4(x, y, z) (y ^ (x | ~z))
  2498. #define MD5STEP(f, w, x, y, z, data, s) \
  2499. ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
  2500. // Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  2501. // initialization constants.
  2502. static void MD5Init(MD5_CTX *ctx) {
  2503. ctx->buf[0] = 0x67452301;
  2504. ctx->buf[1] = 0xefcdab89;
  2505. ctx->buf[2] = 0x98badcfe;
  2506. ctx->buf[3] = 0x10325476;
  2507. ctx->bits[0] = 0;
  2508. ctx->bits[1] = 0;
  2509. }
  2510. static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
  2511. register uint32_t a, b, c, d;
  2512. a = buf[0];
  2513. b = buf[1];
  2514. c = buf[2];
  2515. d = buf[3];
  2516. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  2517. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  2518. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  2519. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  2520. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  2521. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  2522. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  2523. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  2524. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  2525. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  2526. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  2527. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  2528. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  2529. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  2530. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  2531. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  2532. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  2533. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  2534. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  2535. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  2536. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  2537. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  2538. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  2539. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  2540. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  2541. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  2542. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  2543. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  2544. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  2545. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  2546. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  2547. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  2548. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  2549. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  2550. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  2551. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  2552. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  2553. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  2554. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  2555. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  2556. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  2557. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  2558. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  2559. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  2560. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  2561. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  2562. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  2563. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  2564. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  2565. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  2566. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  2567. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  2568. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  2569. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  2570. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  2571. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  2572. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  2573. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  2574. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  2575. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  2576. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  2577. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  2578. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  2579. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  2580. buf[0] += a;
  2581. buf[1] += b;
  2582. buf[2] += c;
  2583. buf[3] += d;
  2584. }
  2585. static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
  2586. uint32_t t;
  2587. t = ctx->bits[0];
  2588. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
  2589. ctx->bits[1]++;
  2590. ctx->bits[1] += len >> 29;
  2591. t = (t >> 3) & 0x3f;
  2592. if (t) {
  2593. unsigned char *p = (unsigned char *) ctx->in + t;
  2594. t = 64 - t;
  2595. if (len < t) {
  2596. memcpy(p, buf, len);
  2597. return;
  2598. }
  2599. memcpy(p, buf, t);
  2600. byteReverse(ctx->in, 16);
  2601. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  2602. buf += t;
  2603. len -= t;
  2604. }
  2605. while (len >= 64) {
  2606. memcpy(ctx->in, buf, 64);
  2607. byteReverse(ctx->in, 16);
  2608. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  2609. buf += 64;
  2610. len -= 64;
  2611. }
  2612. memcpy(ctx->in, buf, len);
  2613. }
  2614. static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
  2615. unsigned count;
  2616. unsigned char *p;
  2617. uint32_t *a;
  2618. count = (ctx->bits[0] >> 3) & 0x3F;
  2619. p = ctx->in + count;
  2620. *p++ = 0x80;
  2621. count = 64 - 1 - count;
  2622. if (count < 8) {
  2623. memset(p, 0, count);
  2624. byteReverse(ctx->in, 16);
  2625. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  2626. memset(ctx->in, 0, 56);
  2627. } else {
  2628. memset(p, 0, count - 8);
  2629. }
  2630. byteReverse(ctx->in, 14);
  2631. a = (uint32_t *)ctx->in;
  2632. a[14] = ctx->bits[0];
  2633. a[15] = ctx->bits[1];
  2634. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  2635. byteReverse((unsigned char *) ctx->buf, 4);
  2636. memcpy(digest, ctx->buf, 16);
  2637. memset((char *) ctx, 0, sizeof(*ctx));
  2638. }
  2639. #endif // !HAVE_MD5
  2640. // Stringify binary data. Output buffer must be twice as big as input,
  2641. // because each byte takes 2 bytes in string representation
  2642. static void bin2str(char *to, const unsigned char *p, size_t len) {
  2643. static const char *hex = "0123456789abcdef";
  2644. for (; len--; p++) {
  2645. *to++ = hex[p[0] >> 4];
  2646. *to++ = hex[p[0] & 0x0f];
  2647. }
  2648. *to = '\0';
  2649. }
  2650. // Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  2651. char *mg_md5(char buf[33], ...) {
  2652. unsigned char hash[16];
  2653. const char *p;
  2654. va_list ap;
  2655. MD5_CTX ctx;
  2656. MD5Init(&ctx);
  2657. va_start(ap, buf);
  2658. while ((p = va_arg(ap, const char *)) != NULL) {
  2659. MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
  2660. }
  2661. va_end(ap);
  2662. MD5Final(hash, &ctx);
  2663. bin2str(buf, hash, sizeof(hash));
  2664. return buf;
  2665. }
  2666. // Check the user's password, return 1 if OK
  2667. static int check_password(const char *method, const char *ha1, const char *uri,
  2668. const char *nonce, const char *nc, const char *cnonce,
  2669. const char *qop, const char *response) {
  2670. char ha2[32 + 1], expected_response[32 + 1];
  2671. #if 0
  2672. // Check for authentication timeout
  2673. if ((unsigned long) time(NULL) - (unsigned long) to64(nonce) > 3600) {
  2674. return 0;
  2675. }
  2676. #endif
  2677. mg_md5(ha2, method, ":", uri, NULL);
  2678. mg_md5(expected_response, ha1, ":", nonce, ":", nc,
  2679. ":", cnonce, ":", qop, ":", ha2, NULL);
  2680. return mg_strcasecmp(response, expected_response) == 0 ?
  2681. MG_AUTH_OK : MG_AUTH_FAIL;
  2682. }
  2683. // Authorize against the opened passwords file. Return 1 if authorized.
  2684. int mg_authorize_digest(struct mg_connection *c, FILE *fp) {
  2685. struct connection *conn = (struct connection *) c;
  2686. const char *hdr;
  2687. char line[256], f_user[256], ha1[256], f_domain[256], user[100], nonce[100],
  2688. uri[MAX_REQUEST_SIZE], cnonce[100], resp[100], qop[100], nc[100];
  2689. if (c == NULL || fp == NULL) return 0;
  2690. if ((hdr = mg_get_header(c, "Authorization")) == NULL ||
  2691. mg_strncasecmp(hdr, "Digest ", 7) != 0) return 0;
  2692. if (!mg_parse_header(hdr, "username", user, sizeof(user))) return 0;
  2693. if (!mg_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce))) return 0;
  2694. if (!mg_parse_header(hdr, "response", resp, sizeof(resp))) return 0;
  2695. if (!mg_parse_header(hdr, "uri", uri, sizeof(uri))) return 0;
  2696. if (!mg_parse_header(hdr, "qop", qop, sizeof(qop))) return 0;
  2697. if (!mg_parse_header(hdr, "nc", nc, sizeof(nc))) return 0;
  2698. if (!mg_parse_header(hdr, "nonce", nonce, sizeof(nonce))) return 0;
  2699. while (fgets(line, sizeof(line), fp) != NULL) {
  2700. if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) == 3 &&
  2701. !strcmp(user, f_user) &&
  2702. // NOTE(lsm): due to a bug in MSIE, we do not compare URIs
  2703. !strcmp(conn->server->config_options[AUTH_DOMAIN], f_domain))
  2704. return check_password(c->request_method, ha1, uri,
  2705. nonce, nc, cnonce, qop, resp);
  2706. }
  2707. return MG_AUTH_FAIL;
  2708. }
  2709. // Return 1 if request is authorised, 0 otherwise.
  2710. static int is_authorized(struct connection *conn, const char *path) {
  2711. FILE *fp;
  2712. int authorized = MG_AUTH_OK;
  2713. if ((fp = open_auth_file(conn, path)) != NULL) {
  2714. authorized = mg_authorize_digest(&conn->mg_conn, fp);
  2715. fclose(fp);
  2716. }
  2717. return authorized;
  2718. }
  2719. static int is_authorized_for_dav(struct connection *conn) {
  2720. const char *auth_file = conn->server->config_options[DAV_AUTH_FILE];
  2721. FILE *fp;
  2722. int authorized = MG_AUTH_FAIL;
  2723. if (auth_file != NULL && (fp = fopen(auth_file, "r")) != NULL) {
  2724. authorized = mg_authorize_digest(&conn->mg_conn, fp);
  2725. fclose(fp);
  2726. }
  2727. return authorized;
  2728. }
  2729. static int is_dav_mutation(const struct connection *conn) {
  2730. const char *s = conn->mg_conn.request_method;
  2731. return s && (!strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
  2732. !strcmp(s, "MKCOL"));
  2733. }
  2734. #endif // MONGOOSE_NO_AUTH
  2735. int parse_header(const char *str, int str_len, const char *var_name, char *buf,
  2736. size_t buf_size) {
  2737. int ch = ' ', len = 0, n = strlen(var_name);
  2738. const char *p, *end = str + str_len, *s = NULL;
  2739. if (buf != NULL && buf_size > 0) buf[0] = '\0';
  2740. // Find where variable starts
  2741. for (s = str; s != NULL && s + n < end; s++) {
  2742. if ((s == str || s[-1] == ' ' || s[-1] == ',') && s[n] == '=' &&
  2743. !memcmp(s, var_name, n)) break;
  2744. }
  2745. if (s != NULL && &s[n + 1] < end) {
  2746. s += n + 1;
  2747. if (*s == '"' || *s == '\'') ch = *s++;
  2748. p = s;
  2749. while (p < end && p[0] != ch && p[0] != ',' && len < (int) buf_size) {
  2750. if (p[0] == '\\' && p[1] == ch) p++;
  2751. buf[len++] = *p++;
  2752. }
  2753. if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
  2754. len = 0;
  2755. } else {
  2756. if (len > 0 && s[len - 1] == ',') len--;
  2757. if (len > 0 && s[len - 1] == ';') len--;
  2758. buf[len] = '\0';
  2759. }
  2760. }
  2761. return len;
  2762. }
  2763. int mg_parse_header(const char *s, const char *var_name, char *buf,
  2764. size_t buf_size) {
  2765. return parse_header(s, s == NULL ? 0 : strlen(s), var_name, buf, buf_size);
  2766. }
  2767. #ifdef MONGOOSE_USE_LUA
  2768. #include <lua.h>
  2769. #include <lauxlib.h>
  2770. #ifdef _WIN32
  2771. static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
  2772. int offset) {
  2773. HANDLE fh = (HANDLE) _get_osfhandle(fd);
  2774. HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
  2775. void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
  2776. CloseHandle(mh);
  2777. return p;
  2778. }
  2779. #define munmap(x, y) UnmapViewOfFile(x)
  2780. #define MAP_FAILED NULL
  2781. #define MAP_PRIVATE 0
  2782. #define PROT_READ 0
  2783. #else
  2784. #include <sys/mman.h>
  2785. #endif
  2786. static void reg_string(struct lua_State *L, const char *name, const char *val) {
  2787. lua_pushstring(L, name);
  2788. lua_pushstring(L, val);
  2789. lua_rawset(L, -3);
  2790. }
  2791. static void reg_int(struct lua_State *L, const char *name, int val) {
  2792. lua_pushstring(L, name);
  2793. lua_pushinteger(L, val);
  2794. lua_rawset(L, -3);
  2795. }
  2796. static void reg_function(struct lua_State *L, const char *name,
  2797. lua_CFunction func, struct mg_connection *conn) {
  2798. lua_pushstring(L, name);
  2799. lua_pushlightuserdata(L, conn);
  2800. lua_pushcclosure(L, func, 1);
  2801. lua_rawset(L, -3);
  2802. }
  2803. static int lua_write(lua_State *L) {
  2804. int i, num_args;
  2805. const char *str;
  2806. size_t size;
  2807. struct mg_connection *conn = (struct mg_connection *)
  2808. lua_touserdata(L, lua_upvalueindex(1));
  2809. num_args = lua_gettop(L);
  2810. for (i = 1; i <= num_args; i++) {
  2811. if (lua_isstring(L, i)) {
  2812. str = lua_tolstring(L, i, &size);
  2813. mg_write(conn, str, size);
  2814. }
  2815. }
  2816. return 0;
  2817. }
  2818. static int lsp_sock_close(lua_State *L) {
  2819. if (lua_gettop(L) > 0 && lua_istable(L, -1)) {
  2820. lua_getfield(L, -1, "sock");
  2821. closesocket((sock_t) lua_tonumber(L, -1));
  2822. } else {
  2823. return luaL_error(L, "invalid :close() call");
  2824. }
  2825. return 1;
  2826. }
  2827. static int lsp_sock_recv(lua_State *L) {
  2828. char buf[2000];
  2829. int n;
  2830. if (lua_gettop(L) > 0 && lua_istable(L, -1)) {
  2831. lua_getfield(L, -1, "sock");
  2832. n = recv((sock_t) lua_tonumber(L, -1), buf, sizeof(buf), 0);
  2833. if (n <= 0) {
  2834. lua_pushnil(L);
  2835. } else {
  2836. lua_pushlstring(L, buf, n);
  2837. }
  2838. } else {
  2839. return luaL_error(L, "invalid :close() call");
  2840. }
  2841. return 1;
  2842. }
  2843. static int lsp_sock_send(lua_State *L) {
  2844. const char *buf;
  2845. size_t len, sent = 0;
  2846. int n, sock;
  2847. if (lua_gettop(L) > 1 && lua_istable(L, -2) && lua_isstring(L, -1)) {
  2848. buf = lua_tolstring(L, -1, &len);
  2849. lua_getfield(L, -2, "sock");
  2850. sock = (int) lua_tonumber(L, -1);
  2851. while (sent < len) {
  2852. if ((n = send(sock, buf + sent, len - sent, 0)) <= 0) break;
  2853. sent += n;
  2854. }
  2855. lua_pushnumber(L, sent);
  2856. } else {
  2857. return luaL_error(L, "invalid :close() call");
  2858. }
  2859. return 1;
  2860. }
  2861. static const struct luaL_Reg luasocket_methods[] = {
  2862. {"close", lsp_sock_close},
  2863. {"send", lsp_sock_send},
  2864. {"recv", lsp_sock_recv},
  2865. {NULL, NULL}
  2866. };
  2867. static sock_t conn2(const char *host, int port) {
  2868. struct sockaddr_in sin;
  2869. struct hostent *he = NULL;
  2870. sock_t sock = INVALID_SOCKET;
  2871. if (host != NULL &&
  2872. (he = gethostbyname(host)) != NULL &&
  2873. (sock = socket(PF_INET, SOCK_STREAM, 0)) != INVALID_SOCKET) {
  2874. set_close_on_exec(sock);
  2875. sin.sin_family = AF_INET;
  2876. sin.sin_port = htons((uint16_t) port);
  2877. sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
  2878. if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
  2879. closesocket(sock);
  2880. sock = INVALID_SOCKET;
  2881. }
  2882. }
  2883. return sock;
  2884. }
  2885. static int lsp_connect(lua_State *L) {
  2886. sock_t sock;
  2887. if (lua_isstring(L, -2) && lua_isnumber(L, -1)) {
  2888. sock = conn2(lua_tostring(L, -2), (int) lua_tonumber(L, -1));
  2889. if (sock == INVALID_SOCKET) {
  2890. lua_pushnil(L);
  2891. } else {
  2892. lua_newtable(L);
  2893. reg_int(L, "sock", sock);
  2894. reg_string(L, "host", lua_tostring(L, -4));
  2895. luaL_getmetatable(L, "luasocket");
  2896. lua_setmetatable(L, -2);
  2897. }
  2898. } else {
  2899. return luaL_error(L, "connect(host,port): invalid parameter given.");
  2900. }
  2901. return 1;
  2902. }
  2903. static void prepare_lua_environment(struct mg_connection *ri, lua_State *L) {
  2904. extern void luaL_openlibs(lua_State *);
  2905. int i;
  2906. luaL_openlibs(L);
  2907. #ifdef MONGOOSE_USE_LUA_SQLITE3
  2908. { extern int luaopen_lsqlite3(lua_State *); luaopen_lsqlite3(L); }
  2909. #endif
  2910. luaL_newmetatable(L, "luasocket");
  2911. lua_pushliteral(L, "__index");
  2912. lua_newtable(L);
  2913. luaL_register(L, NULL, luasocket_methods);
  2914. //luaL_newlib(L, luasocket_methods);
  2915. lua_rawset(L, -3);
  2916. lua_pop(L, 1);
  2917. lua_register(L, "connect", lsp_connect);
  2918. if (ri == NULL) return;
  2919. // Register mg module
  2920. lua_newtable(L);
  2921. reg_function(L, "write", lua_write, ri);
  2922. // Export request_info
  2923. lua_pushstring(L, "request_info");
  2924. lua_newtable(L);
  2925. reg_string(L, "request_method", ri->request_method);
  2926. reg_string(L, "uri", ri->uri);
  2927. reg_string(L, "http_version", ri->http_version);
  2928. reg_string(L, "query_string", ri->query_string);
  2929. reg_string(L, "remote_ip", ri->remote_ip);
  2930. reg_int(L, "remote_port", ri->remote_port);
  2931. lua_pushstring(L, "content");
  2932. lua_pushlstring(L, ri->content == NULL ? "" : ri->content, 0);
  2933. lua_rawset(L, -3);
  2934. reg_int(L, "content_len", ri->content_len);
  2935. reg_int(L, "num_headers", ri->num_headers);
  2936. lua_pushstring(L, "http_headers");
  2937. lua_newtable(L);
  2938. for (i = 0; i < ri->num_headers; i++) {
  2939. reg_string(L, ri->http_headers[i].name, ri->http_headers[i].value);
  2940. }
  2941. lua_rawset(L, -3);
  2942. lua_rawset(L, -3);
  2943. lua_setglobal(L, "mg");
  2944. // Register default mg.onerror function
  2945. (void) luaL_dostring(L, "mg.onerror = function(e) mg.write('\\nLua "
  2946. "error:\\n', debug.traceback(e, 1)) end");
  2947. }
  2948. static int lua_error_handler(lua_State *L) {
  2949. const char *error_msg = lua_isstring(L, -1) ? lua_tostring(L, -1) : "?\n";
  2950. lua_getglobal(L, "mg");
  2951. if (!lua_isnil(L, -1)) {
  2952. lua_getfield(L, -1, "write"); // call mg.write()
  2953. lua_pushstring(L, error_msg);
  2954. lua_pushliteral(L, "\n");
  2955. lua_call(L, 2, 0);
  2956. (void) luaL_dostring(L, "mg.write(debug.traceback(), '\\n')");
  2957. } else {
  2958. printf("Lua error: [%s]\n", error_msg);
  2959. (void) luaL_dostring(L, "print(debug.traceback(), '\\n')");
  2960. }
  2961. // TODO(lsm): leave the stack balanced
  2962. return 0;
  2963. }
  2964. static void lsp(struct connection *conn, const char *p, int len, lua_State *L) {
  2965. int i, j, pos = 0;
  2966. for (i = 0; i < len; i++) {
  2967. if (p[i] == '<' && p[i + 1] == '?') {
  2968. for (j = i + 1; j < len ; j++) {
  2969. if (p[j] == '?' && p[j + 1] == '>') {
  2970. mg_write(&conn->mg_conn, p + pos, i - pos);
  2971. if (luaL_loadbuffer(L, p + (i + 2), j - (i + 2), "") == 0) {
  2972. lua_pcall(L, 0, LUA_MULTRET, 0);
  2973. }
  2974. pos = j + 2;
  2975. i = pos - 1;
  2976. break;
  2977. }
  2978. }
  2979. }
  2980. }
  2981. if (i > pos) mg_write(&conn->mg_conn, p + pos, i - pos);
  2982. }
  2983. static void handle_lsp_request(struct connection *conn, const char *path,
  2984. file_stat_t *st) {
  2985. void *p = NULL;
  2986. lua_State *L = NULL;
  2987. FILE *fp = NULL;
  2988. if ((fp = fopen(path, "r")) == NULL ||
  2989. (p = mmap(NULL, st->st_size, PROT_READ, MAP_PRIVATE,
  2990. fileno(fp), 0)) == MAP_FAILED ||
  2991. (L = luaL_newstate()) == NULL) {
  2992. send_http_error(conn, 500, "mmap(%s): %s", path, strerror(errno));
  2993. } else {
  2994. // We're not sending HTTP headers here, Lua page must do it.
  2995. prepare_lua_environment(&conn->mg_conn, L);
  2996. lua_pushcclosure(L, &lua_error_handler, 0);
  2997. lua_pushvalue(L, LUA_GLOBALSINDEX);
  2998. lsp(conn, p, (int) st->st_size, L);
  2999. close_local_endpoint(conn);
  3000. }
  3001. if (L != NULL) lua_close(L);
  3002. if (p != NULL) munmap(p, st->st_size);
  3003. if (fp != NULL) fclose(fp);
  3004. }
  3005. #endif // MONGOOSE_USE_LUA
  3006. static void open_local_endpoint(struct connection *conn, int skip_user) {
  3007. #ifndef MONGOOSE_NO_FILESYSTEM
  3008. static const char lua_pat[] = LUA_SCRIPT_PATTERN;
  3009. file_stat_t st;
  3010. char path[MAX_PATH_SIZE];
  3011. int exists = 0, is_directory = 0;
  3012. #ifndef MONGOOSE_NO_CGI
  3013. const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
  3014. #else
  3015. const char *cgi_pat = DEFAULT_CGI_PATTERN;
  3016. #endif
  3017. #ifndef MONGOOSE_NO_DIRECTORY_LISTING
  3018. const char *dir_lst = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
  3019. #else
  3020. const char *dir_lst = "yes";
  3021. #endif
  3022. #endif
  3023. #ifndef MONGOOSE_NO_AUTH
  3024. // Call auth handler
  3025. if (conn->server->auth_handler != NULL &&
  3026. conn->server->auth_handler(&conn->mg_conn) == MG_AUTH_FAIL) {
  3027. mg_send_digest_auth_request(&conn->mg_conn);
  3028. return;
  3029. }
  3030. #endif
  3031. // Call URI handler if one is registered for this URI
  3032. if (skip_user == 0 && conn->server->request_handler != NULL) {
  3033. conn->endpoint_type = EP_USER;
  3034. #if MONGOOSE_USE_POST_SIZE_LIMIT > 1
  3035. {
  3036. const char *cl = mg_get_header(&conn->mg_conn, "Content-Length");
  3037. if (!strcmp(conn->mg_conn.request_method, "POST") &&
  3038. (cl == NULL || to64(cl) > MONGOOSE_USE_POST_SIZE_LIMIT)) {
  3039. send_http_error(conn, 500, "POST size > %zu",
  3040. (size_t) MONGOOSE_USE_POST_SIZE_LIMIT);
  3041. }
  3042. }
  3043. #endif
  3044. return;
  3045. }
  3046. #ifdef MONGOOSE_NO_FILESYSTEM
  3047. if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
  3048. send_options(conn);
  3049. } else {
  3050. send_http_error(conn, 404, NULL);
  3051. }
  3052. #else
  3053. exists = convert_uri_to_file_name(conn, path, sizeof(path), &st);
  3054. is_directory = S_ISDIR(st.st_mode);
  3055. if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
  3056. send_options(conn);
  3057. } else if (conn->server->config_options[DOCUMENT_ROOT] == NULL) {
  3058. send_http_error(conn, 404, NULL);
  3059. #ifndef MONGOOSE_NO_AUTH
  3060. } else if ((!is_dav_mutation(conn) && !is_authorized(conn, path)) ||
  3061. (is_dav_mutation(conn) && !is_authorized_for_dav(conn))) {
  3062. mg_send_digest_auth_request(&conn->mg_conn);
  3063. close_local_endpoint(conn);
  3064. #endif
  3065. #ifndef MONGOOSE_NO_DAV
  3066. } else if (!strcmp(conn->mg_conn.request_method, "PROPFIND")) {
  3067. handle_propfind(conn, path, &st);
  3068. } else if (!strcmp(conn->mg_conn.request_method, "MKCOL")) {
  3069. handle_mkcol(conn, path);
  3070. } else if (!strcmp(conn->mg_conn.request_method, "DELETE")) {
  3071. handle_delete(conn, path);
  3072. } else if (!strcmp(conn->mg_conn.request_method, "PUT")) {
  3073. handle_put(conn, path);
  3074. #endif
  3075. } else if (!exists || must_hide_file(conn, path)) {
  3076. send_http_error(conn, 404, NULL);
  3077. } else if (is_directory &&
  3078. conn->mg_conn.uri[strlen(conn->mg_conn.uri) - 1] != '/') {
  3079. conn->mg_conn.status_code = 301;
  3080. mg_printf(&conn->mg_conn, "HTTP/1.1 301 Moved Permanently\r\n"
  3081. "Location: %s/\r\n\r\n", conn->mg_conn.uri);
  3082. close_local_endpoint(conn);
  3083. } else if (is_directory && !find_index_file(conn, path, sizeof(path), &st)) {
  3084. if (!mg_strcasecmp(dir_lst, "yes")) {
  3085. #ifndef MONGOOSE_NO_DIRECTORY_LISTING
  3086. send_directory_listing(conn, path);
  3087. #else
  3088. send_http_error(conn, 501, NULL);
  3089. #endif
  3090. } else {
  3091. send_http_error(conn, 403, NULL);
  3092. }
  3093. } else if (match_prefix(lua_pat, sizeof(lua_pat) - 1, path) > 0) {
  3094. #ifdef MONGOOSE_USE_LUA
  3095. handle_lsp_request(conn, path, &st);
  3096. #else
  3097. send_http_error(conn, 501, NULL);
  3098. #endif
  3099. } else if (match_prefix(cgi_pat, strlen(cgi_pat), path) > 0) {
  3100. #if !defined(MONGOOSE_NO_CGI)
  3101. open_cgi_endpoint(conn, path);
  3102. #else
  3103. send_http_error(conn, 501, NULL);
  3104. #endif // !MONGOOSE_NO_CGI
  3105. } else if (is_not_modified(conn, &st)) {
  3106. send_http_error(conn, 304, NULL);
  3107. } else if ((conn->endpoint.fd = open(path, O_RDONLY | O_BINARY)) != -1) {
  3108. // O_BINARY is required for Windows, otherwise in default text mode
  3109. // two bytes \r\n will be read as one.
  3110. open_file_endpoint(conn, path, &st);
  3111. } else {
  3112. send_http_error(conn, 404, NULL);
  3113. }
  3114. #endif // MONGOOSE_NO_FILESYSTEM
  3115. }
  3116. static void send_continue_if_expected(struct connection *conn) {
  3117. static const char expect_response[] = "HTTP/1.1 100 Continue\r\n\r\n";
  3118. const char *expect_hdr = mg_get_header(&conn->mg_conn, "Expect");
  3119. if (expect_hdr != NULL && !mg_strcasecmp(expect_hdr, "100-continue")) {
  3120. spool(&conn->remote_iobuf, expect_response, sizeof(expect_response) - 1);
  3121. }
  3122. }
  3123. static int is_valid_uri(const char *uri) {
  3124. // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  3125. // URI can be an asterisk (*) or should start with slash.
  3126. return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
  3127. }
  3128. static void try_http_parse_and_set_content_length(struct connection *conn) {
  3129. struct iobuf *io = &conn->local_iobuf;
  3130. if (conn->request_len == 0 &&
  3131. (conn->request_len = get_request_len(io->buf, io->len)) > 0) {
  3132. // If request is buffered in, remove it from the iobuf. This is because
  3133. // iobuf could be reallocated, and pointers in parsed request could
  3134. // become invalid.
  3135. conn->request = (char *) malloc(conn->request_len);
  3136. memcpy(conn->request, io->buf, conn->request_len);
  3137. DBG(("%p [%.*s]", conn, conn->request_len, conn->request));
  3138. discard_leading_iobuf_bytes(io, conn->request_len);
  3139. conn->request_len = parse_http_message(conn->request, conn->request_len,
  3140. &conn->mg_conn);
  3141. if (conn->request_len > 0) {
  3142. const char *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
  3143. conn->cl = cl_hdr == NULL ? 0 : to64(cl_hdr);
  3144. conn->mg_conn.content_len = (long int) conn->cl;
  3145. }
  3146. }
  3147. }
  3148. static void process_request(struct connection *conn) {
  3149. struct iobuf *io = &conn->local_iobuf;
  3150. try_http_parse_and_set_content_length(conn);
  3151. DBG(("%p %d %d %d [%.*s]", conn, conn->request_len, io->len, conn->flags,
  3152. io->len, io->buf));
  3153. if (conn->request_len < 0 ||
  3154. (conn->request_len > 0 && !is_valid_uri(conn->mg_conn.uri))) {
  3155. send_http_error(conn, 400, NULL);
  3156. } else if (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE) {
  3157. send_http_error(conn, 413, NULL);
  3158. } else if (conn->request_len > 0 &&
  3159. strcmp(conn->mg_conn.http_version, "1.0") != 0 &&
  3160. strcmp(conn->mg_conn.http_version, "1.1") != 0) {
  3161. send_http_error(conn, 505, NULL);
  3162. } else if (conn->request_len > 0 && conn->endpoint_type == EP_NONE) {
  3163. #ifndef MONGOOSE_NO_WEBSOCKET
  3164. send_websocket_handshake_if_requested(&conn->mg_conn);
  3165. #endif
  3166. send_continue_if_expected(conn);
  3167. open_local_endpoint(conn, 0);
  3168. }
  3169. #ifndef MONGOOSE_NO_CGI
  3170. if (conn->endpoint_type == EP_CGI && io->len > 0) {
  3171. forward_post_data(conn);
  3172. }
  3173. #endif
  3174. if (conn->endpoint_type == EP_USER) {
  3175. call_request_handler_if_data_is_buffered(conn);
  3176. }
  3177. #ifndef MONGOOSE_NO_DAV
  3178. if (conn->endpoint_type == EP_PUT && io->len > 0) {
  3179. forward_put_data(conn);
  3180. }
  3181. #endif
  3182. }
  3183. static void call_http_client_handler(struct connection *conn, int code) {
  3184. conn->mg_conn.status_code = code;
  3185. // For responses without Content-Lengh, use the whole buffer
  3186. if (conn->cl == 0 && code == MG_DOWNLOAD_SUCCESS) {
  3187. conn->mg_conn.content_len = conn->local_iobuf.len;
  3188. }
  3189. conn->mg_conn.content = conn->local_iobuf.buf;
  3190. if (conn->handler(&conn->mg_conn) || code == MG_CONNECT_FAILURE ||
  3191. code == MG_DOWNLOAD_FAILURE) {
  3192. conn->flags |= CONN_CLOSE;
  3193. }
  3194. discard_leading_iobuf_bytes(&conn->local_iobuf, conn->mg_conn.content_len);
  3195. conn->flags = conn->mg_conn.status_code = 0;
  3196. conn->cl = conn->num_bytes_sent = conn->request_len = 0;
  3197. free(conn->request);
  3198. conn->request = NULL;
  3199. }
  3200. static void process_response(struct connection *conn) {
  3201. struct iobuf *io = &conn->local_iobuf;
  3202. try_http_parse_and_set_content_length(conn);
  3203. DBG(("%p %d %d [%.*s]", conn, conn->request_len, io->len,
  3204. io->len > 40 ? 40 : io->len, io->buf));
  3205. if (conn->request_len < 0 ||
  3206. (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE)) {
  3207. call_http_client_handler(conn, MG_DOWNLOAD_FAILURE);
  3208. }
  3209. if (io->len >= conn->cl) {
  3210. call_http_client_handler(conn, MG_DOWNLOAD_SUCCESS);
  3211. }
  3212. }
  3213. static void read_from_socket(struct connection *conn) {
  3214. char buf[IOBUF_SIZE];
  3215. int n = 0;
  3216. if (conn->endpoint_type == EP_CLIENT && conn->flags & CONN_CONNECTING) {
  3217. callback_http_client_on_connect(conn);
  3218. return;
  3219. }
  3220. #ifdef MONGOOSE_USE_SSL
  3221. if (conn->ssl != NULL) {
  3222. if (conn->flags & CONN_SSL_HANDS_SHAKEN) {
  3223. n = SSL_read(conn->ssl, buf, sizeof(buf));
  3224. } else {
  3225. if (SSL_accept(conn->ssl) == 1) {
  3226. conn->flags |= CONN_SSL_HANDS_SHAKEN;
  3227. }
  3228. return;
  3229. }
  3230. } else
  3231. #endif
  3232. {
  3233. n = recv(conn->client_sock, buf, sizeof(buf), 0);
  3234. }
  3235. DBG(("%p %d %d (1)", conn, n, conn->flags));
  3236. #ifdef MONGOOSE_HEXDUMP
  3237. hexdump(conn, buf, n, "<-");
  3238. #endif
  3239. if (is_error(n)) {
  3240. if (conn->endpoint_type == EP_CLIENT && conn->local_iobuf.len > 0) {
  3241. call_http_client_handler(conn, MG_DOWNLOAD_SUCCESS);
  3242. }
  3243. conn->flags |= CONN_CLOSE;
  3244. } else if (n > 0) {
  3245. spool(&conn->local_iobuf, buf, n);
  3246. if (conn->endpoint_type == EP_CLIENT) {
  3247. process_response(conn);
  3248. } else {
  3249. process_request(conn);
  3250. }
  3251. }
  3252. DBG(("%p %d %d (2)", conn, n, conn->flags));
  3253. }
  3254. int mg_connect(struct mg_server *server, const char *host, int port,
  3255. int use_ssl, mg_handler_t handler, void *param) {
  3256. sock_t sock = INVALID_SOCKET;
  3257. struct sockaddr_in sin;
  3258. struct hostent *he = NULL;
  3259. struct connection *conn = NULL;
  3260. int connect_ret_val;
  3261. if (host == NULL || (he = gethostbyname(host)) == NULL ||
  3262. (sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) return 0;
  3263. #ifndef MONGOOSE_USE_SSL
  3264. if (use_ssl) return 0;
  3265. #endif
  3266. sin.sin_family = AF_INET;
  3267. sin.sin_port = htons((uint16_t) port);
  3268. sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
  3269. set_non_blocking_mode(sock);
  3270. connect_ret_val = connect(sock, (struct sockaddr *) &sin, sizeof(sin));
  3271. if (is_error(connect_ret_val)) {
  3272. return 0;
  3273. } else if ((conn = (struct connection *) calloc(1, sizeof(*conn))) == NULL) {
  3274. closesocket(sock);
  3275. return 0;
  3276. }
  3277. conn->server = server;
  3278. conn->client_sock = sock;
  3279. conn->endpoint_type = EP_CLIENT;
  3280. conn->handler = handler;
  3281. conn->mg_conn.server_param = server->server_data;
  3282. conn->mg_conn.connection_param = param;
  3283. conn->birth_time = conn->last_activity_time = time(NULL);
  3284. conn->flags = CONN_CONNECTING;
  3285. conn->mg_conn.status_code = MG_CONNECT_FAILURE;
  3286. #ifdef MONGOOSE_USE_SSL
  3287. if (use_ssl && (conn->ssl = SSL_new(server->client_ssl_ctx)) != NULL) {
  3288. SSL_set_fd(conn->ssl, sock);
  3289. }
  3290. #endif
  3291. LINKED_LIST_ADD_TO_FRONT(&server->active_connections, &conn->link);
  3292. DBG(("%p %s:%d", conn, host, port));
  3293. return 1;
  3294. }
  3295. #ifndef MONGOOSE_NO_LOGGING
  3296. static void log_header(const struct mg_connection *conn, const char *header,
  3297. FILE *fp) {
  3298. const char *header_value;
  3299. if ((header_value = mg_get_header(conn, header)) == NULL) {
  3300. (void) fprintf(fp, "%s", " -");
  3301. } else {
  3302. (void) fprintf(fp, " \"%s\"", header_value);
  3303. }
  3304. }
  3305. static void log_access(const struct connection *conn, const char *path) {
  3306. const struct mg_connection *c = &conn->mg_conn;
  3307. FILE *fp = (path == NULL) ? NULL : fopen(path, "a+");
  3308. char date[64], user[100];
  3309. if (fp == NULL) return;
  3310. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",
  3311. localtime(&conn->birth_time));
  3312. flockfile(fp);
  3313. mg_parse_header(mg_get_header(&conn->mg_conn, "Authorization"), "username",
  3314. user, sizeof(user));
  3315. fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
  3316. c->remote_ip, user[0] == '\0' ? "-" : user, date,
  3317. c->request_method ? c->request_method : "-",
  3318. c->uri ? c->uri : "-", c->http_version,
  3319. c->status_code, conn->num_bytes_sent);
  3320. log_header(c, "Referer", fp);
  3321. log_header(c, "User-Agent", fp);
  3322. fputc('\n', fp);
  3323. fflush(fp);
  3324. funlockfile(fp);
  3325. fclose(fp);
  3326. }
  3327. #endif
  3328. static void close_local_endpoint(struct connection *conn) {
  3329. struct mg_connection *c = &conn->mg_conn;
  3330. // Must be done before free()
  3331. int keep_alive = should_keep_alive(&conn->mg_conn) &&
  3332. (conn->endpoint_type == EP_FILE || conn->endpoint_type == EP_USER);
  3333. DBG(("%p %d %d %d", conn, conn->endpoint_type, keep_alive, conn->flags));
  3334. switch (conn->endpoint_type) {
  3335. case EP_PUT: close(conn->endpoint.fd); break;
  3336. case EP_FILE: close(conn->endpoint.fd); break;
  3337. case EP_CGI: closesocket(conn->endpoint.cgi_sock); break;
  3338. default: break;
  3339. }
  3340. #ifndef MONGOOSE_NO_LOGGING
  3341. if (c->status_code > 0 && conn->endpoint_type != EP_CLIENT &&
  3342. c->status_code != 400) {
  3343. log_access(conn, conn->server->config_options[ACCESS_LOG_FILE]);
  3344. }
  3345. #endif
  3346. // Gobble possible POST data sent to the URI handler
  3347. discard_leading_iobuf_bytes(&conn->local_iobuf, conn->mg_conn.content_len);
  3348. conn->endpoint_type = EP_NONE;
  3349. conn->cl = conn->num_bytes_sent = conn->request_len = conn->flags = 0;
  3350. c->request_method = c->uri = c->http_version = c->query_string = NULL;
  3351. c->num_headers = c->status_code = c->is_websocket = c->content_len = 0;
  3352. free(conn->request);
  3353. conn->request = NULL;
  3354. if (keep_alive) {
  3355. process_request(conn); // Can call us recursively if pipelining is used
  3356. } else {
  3357. conn->flags |= conn->remote_iobuf.len == 0 ? CONN_CLOSE : CONN_SPOOL_DONE;
  3358. }
  3359. }
  3360. static void transfer_file_data(struct connection *conn) {
  3361. char buf[IOBUF_SIZE];
  3362. int n = read(conn->endpoint.fd, buf, conn->cl < (int64_t) sizeof(buf) ?
  3363. (int) conn->cl : (int) sizeof(buf));
  3364. if (is_error(n)) {
  3365. close_local_endpoint(conn);
  3366. } else if (n > 0) {
  3367. conn->cl -= n;
  3368. spool(&conn->remote_iobuf, buf, n);
  3369. if (conn->cl <= 0) {
  3370. close_local_endpoint(conn);
  3371. }
  3372. }
  3373. }
  3374. void add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
  3375. FD_SET(sock, set);
  3376. if (sock > *max_fd) {
  3377. *max_fd = sock;
  3378. }
  3379. }
  3380. unsigned int mg_poll_server(struct mg_server *server, int milliseconds) {
  3381. struct ll *lp, *tmp;
  3382. struct connection *conn;
  3383. struct timeval tv;
  3384. fd_set read_set, write_set;
  3385. sock_t max_fd = -1;
  3386. time_t current_time = time(NULL), expire_time = current_time -
  3387. MONGOOSE_USE_IDLE_TIMEOUT_SECONDS;
  3388. if (server->listening_sock == INVALID_SOCKET) return 0;
  3389. FD_ZERO(&read_set);
  3390. FD_ZERO(&write_set);
  3391. add_to_set(server->listening_sock, &read_set, &max_fd);
  3392. #ifndef MONGOOSE_NO_SOCKETPAIR
  3393. add_to_set(server->ctl[1], &read_set, &max_fd);
  3394. #endif
  3395. LINKED_LIST_FOREACH(&server->active_connections, lp, tmp) {
  3396. conn = LINKED_LIST_ENTRY(lp, struct connection, link);
  3397. add_to_set(conn->client_sock, &read_set, &max_fd);
  3398. if (conn->endpoint_type == EP_CLIENT && (conn->flags & CONN_CONNECTING)) {
  3399. add_to_set(conn->client_sock, &write_set, &max_fd);
  3400. }
  3401. if (conn->endpoint_type == EP_FILE) {
  3402. transfer_file_data(conn);
  3403. } else if (conn->endpoint_type == EP_CGI) {
  3404. add_to_set(conn->endpoint.cgi_sock, &read_set, &max_fd);
  3405. }
  3406. if (conn->remote_iobuf.len > 0 && !(conn->flags & CONN_BUFFER)) {
  3407. add_to_set(conn->client_sock, &write_set, &max_fd);
  3408. } else if (conn->flags & CONN_CLOSE) {
  3409. close_conn(conn);
  3410. }
  3411. }
  3412. tv.tv_sec = milliseconds / 1000;
  3413. tv.tv_usec = (milliseconds % 1000) * 1000;
  3414. if (select(max_fd + 1, &read_set, &write_set, NULL, &tv) > 0) {
  3415. // Accept new connections
  3416. if (FD_ISSET(server->listening_sock, &read_set)) {
  3417. // We're not looping here, and accepting just one connection at
  3418. // a time. The reason is that eCos does not respect non-blocking
  3419. // flag on a listening socket and hangs in a loop.
  3420. if ((conn = accept_new_connection(server)) != NULL) {
  3421. conn->birth_time = conn->last_activity_time = current_time;
  3422. }
  3423. }
  3424. // Read/write from clients
  3425. LINKED_LIST_FOREACH(&server->active_connections, lp, tmp) {
  3426. conn = LINKED_LIST_ENTRY(lp, struct connection, link);
  3427. if (FD_ISSET(conn->client_sock, &read_set)) {
  3428. conn->last_activity_time = current_time;
  3429. read_from_socket(conn);
  3430. }
  3431. #ifndef MONGOOSE_NO_CGI
  3432. if (conn->endpoint_type == EP_CGI &&
  3433. FD_ISSET(conn->endpoint.cgi_sock, &read_set)) {
  3434. read_from_cgi(conn);
  3435. }
  3436. #endif
  3437. if (FD_ISSET(conn->client_sock, &write_set)) {
  3438. if (conn->endpoint_type == EP_CLIENT &&
  3439. (conn->flags & CONN_CONNECTING)) {
  3440. read_from_socket(conn);
  3441. } else if (!(conn->flags & CONN_BUFFER)) {
  3442. conn->last_activity_time = current_time;
  3443. write_to_socket(conn);
  3444. }
  3445. }
  3446. }
  3447. }
  3448. // Close expired connections and those that need to be closed
  3449. LINKED_LIST_FOREACH(&server->active_connections, lp, tmp) {
  3450. conn = LINKED_LIST_ENTRY(lp, struct connection, link);
  3451. if (conn->mg_conn.is_websocket) {
  3452. ping_idle_websocket_connection(conn, current_time);
  3453. }
  3454. if (conn->flags & CONN_LONG_RUNNING) {
  3455. conn->mg_conn.wsbits = conn->flags & CONN_CLOSE ? 1 : 0;
  3456. if (call_request_handler(conn) == MG_REQUEST_PROCESSED) {
  3457. conn->flags |= conn->remote_iobuf.len == 0 ? CONN_CLOSE : CONN_SPOOL_DONE;
  3458. }
  3459. }
  3460. if (conn->flags & CONN_CLOSE || conn->last_activity_time < expire_time) {
  3461. close_conn(conn);
  3462. }
  3463. }
  3464. return (unsigned int) current_time;
  3465. }
  3466. void mg_destroy_server(struct mg_server **server) {
  3467. int i;
  3468. struct ll *lp, *tmp;
  3469. if (server != NULL && *server != NULL) {
  3470. struct mg_server *s = *server;
  3471. // Do one last poll, see https://github.com/cesanta/mongoose/issues/286
  3472. mg_poll_server(s, 0);
  3473. closesocket(s->listening_sock);
  3474. #ifndef MONGOOSE_NO_SOCKETPAIR
  3475. closesocket(s->ctl[0]);
  3476. closesocket(s->ctl[1]);
  3477. #endif
  3478. LINKED_LIST_FOREACH(&s->active_connections, lp, tmp) {
  3479. close_conn(LINKED_LIST_ENTRY(lp, struct connection, link));
  3480. }
  3481. for (i = 0; i < (int) ARRAY_SIZE(s->config_options); i++) {
  3482. free(s->config_options[i]); // It is OK to free(NULL)
  3483. }
  3484. #ifdef MONGOOSE_USE_SSL
  3485. if (s->ssl_ctx != NULL) SSL_CTX_free((*server)->ssl_ctx);
  3486. if (s->client_ssl_ctx != NULL) SSL_CTX_free(s->client_ssl_ctx);
  3487. #endif
  3488. free(s);
  3489. *server = NULL;
  3490. }
  3491. }
  3492. // Apply function to all active connections.
  3493. void mg_iterate_over_connections(struct mg_server *server, mg_handler_t handler,
  3494. void *param) {
  3495. struct ll *lp, *tmp;
  3496. struct connection *conn;
  3497. LINKED_LIST_FOREACH(&server->active_connections, lp, tmp) {
  3498. conn = LINKED_LIST_ENTRY(lp, struct connection, link);
  3499. conn->mg_conn.callback_param = param;
  3500. handler(&conn->mg_conn);
  3501. }
  3502. }
  3503. static int get_var(const char *data, size_t data_len, const char *name,
  3504. char *dst, size_t dst_len) {
  3505. const char *p, *e, *s;
  3506. size_t name_len;
  3507. int len;
  3508. if (dst == NULL || dst_len == 0) {
  3509. len = -2;
  3510. } else if (data == NULL || name == NULL || data_len == 0) {
  3511. len = -1;
  3512. dst[0] = '\0';
  3513. } else {
  3514. name_len = strlen(name);
  3515. e = data + data_len;
  3516. len = -1;
  3517. dst[0] = '\0';
  3518. // data is "var1=val1&var2=val2...". Find variable first
  3519. for (p = data; p + name_len < e; p++) {
  3520. if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
  3521. !mg_strncasecmp(name, p, name_len)) {
  3522. // Point p to variable value
  3523. p += name_len + 1;
  3524. // Point s to the end of the value
  3525. s = (const char *) memchr(p, '&', (size_t)(e - p));
  3526. if (s == NULL) {
  3527. s = e;
  3528. }
  3529. assert(s >= p);
  3530. // Decode variable into destination buffer
  3531. len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
  3532. // Redirect error code from -1 to -2 (destination buffer too small).
  3533. if (len == -1) {
  3534. len = -2;
  3535. }
  3536. break;
  3537. }
  3538. }
  3539. }
  3540. return len;
  3541. }
  3542. int mg_get_var(const struct mg_connection *conn, const char *name,
  3543. char *dst, size_t dst_len) {
  3544. int len = get_var(conn->query_string, conn->query_string == NULL ? 0 :
  3545. strlen(conn->query_string), name, dst, dst_len);
  3546. if (len < 0) {
  3547. len = get_var(conn->content, conn->content_len, name, dst, dst_len);
  3548. }
  3549. return len;
  3550. }
  3551. static int get_line_len(const char *buf, int buf_len) {
  3552. int len = 0;
  3553. while (len < buf_len && buf[len] != '\n') len++;
  3554. return buf[len] == '\n' ? len + 1: -1;
  3555. }
  3556. int mg_parse_multipart(const char *buf, int buf_len,
  3557. char *var_name, int var_name_len,
  3558. char *file_name, int file_name_len,
  3559. const char **data, int *data_len) {
  3560. static const char cd[] = "Content-Disposition: ";
  3561. //struct mg_connection c;
  3562. int hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
  3563. //char *p;
  3564. if (buf == NULL || buf_len <= 0) return 0;
  3565. if ((hl = get_request_len(buf, buf_len)) <= 0) return 0;
  3566. if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
  3567. // Get boundary length
  3568. bl = get_line_len(buf, buf_len);
  3569. // Loop through headers, fetch variable name and file name
  3570. var_name[0] = file_name[0] = '\0';
  3571. for (n = bl; (ll = get_line_len(buf + n, hl - n)) > 0; n += ll) {
  3572. if (mg_strncasecmp(cd, buf + n, cdl) == 0) {
  3573. parse_header(buf + n + cdl, ll - (cdl + 2), "name",
  3574. var_name, var_name_len);
  3575. parse_header(buf + n + cdl, ll - (cdl + 2), "filename",
  3576. file_name, file_name_len);
  3577. }
  3578. }
  3579. // Scan body, search for terminating boundary
  3580. for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
  3581. if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
  3582. if (data_len != NULL) *data_len = (pos - 2) - hl;
  3583. if (data != NULL) *data = buf + hl;
  3584. return pos;
  3585. }
  3586. }
  3587. return 0;
  3588. }
  3589. const char **mg_get_valid_option_names(void) {
  3590. return static_config_options;
  3591. }
  3592. static int get_option_index(const char *name) {
  3593. int i;
  3594. for (i = 0; static_config_options[i * 2] != NULL; i++) {
  3595. if (strcmp(static_config_options[i * 2], name) == 0) {
  3596. return i;
  3597. }
  3598. }
  3599. return -1;
  3600. }
  3601. static void set_default_option_values(char **opts) {
  3602. const char *value, **all_opts = mg_get_valid_option_names();
  3603. int i;
  3604. for (i = 0; all_opts[i * 2] != NULL; i++) {
  3605. value = all_opts[i * 2 + 1];
  3606. if (opts[i] == NULL && value != NULL) {
  3607. opts[i] = mg_strdup(value);
  3608. }
  3609. }
  3610. }
  3611. // Valid listening port spec is: [ip_address:]port, e.g. "80", "127.0.0.1:3128"
  3612. static int parse_port_string(const char *str, union socket_address *sa) {
  3613. unsigned int a, b, c, d, port;
  3614. int len = 0;
  3615. #ifdef MONGOOSE_USE_IPV6
  3616. char buf[100];
  3617. #endif
  3618. // MacOS needs that. If we do not zero it, subsequent bind() will fail.
  3619. // Also, all-zeroes in the socket address means binding to all addresses
  3620. // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
  3621. memset(sa, 0, sizeof(*sa));
  3622. sa->sin.sin_family = AF_INET;
  3623. if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
  3624. // Bind to a specific IPv4 address, e.g. 192.168.1.5:8080
  3625. sa->sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
  3626. sa->sin.sin_port = htons((uint16_t) port);
  3627. #if defined(MONGOOSE_USE_IPV6)
  3628. } else if (sscanf(str, "[%49[^]]]:%u%n", buf, &port, &len) == 2 &&
  3629. inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
  3630. // IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080
  3631. sa->sin6.sin6_family = AF_INET6;
  3632. sa->sin6.sin6_port = htons((uint16_t) port);
  3633. #endif
  3634. } else if (sscanf(str, "%u%n", &port, &len) == 1) {
  3635. // If only port is specified, bind to IPv4, INADDR_ANY
  3636. sa->sin.sin_port = htons((uint16_t) port);
  3637. } else {
  3638. port = 0; // Parsing failure. Make port invalid.
  3639. }
  3640. return port <= 0xffff && str[len] == '\0';
  3641. }
  3642. const char *mg_set_option(struct mg_server *server, const char *name,
  3643. const char *value) {
  3644. int ind = get_option_index(name);
  3645. const char *error_msg = NULL;
  3646. if (ind < 0) {
  3647. error_msg = "No such option";
  3648. } else {
  3649. if (server->config_options[ind] != NULL) {
  3650. free(server->config_options[ind]);
  3651. }
  3652. server->config_options[ind] = mg_strdup(value);
  3653. DBG(("%s [%s]", name, value));
  3654. if (ind == LISTENING_PORT) {
  3655. if (server->listening_sock != INVALID_SOCKET) {
  3656. closesocket(server->listening_sock);
  3657. }
  3658. parse_port_string(server->config_options[LISTENING_PORT], &server->lsa);
  3659. server->listening_sock = open_listening_socket(&server->lsa);
  3660. if (server->listening_sock == INVALID_SOCKET) {
  3661. error_msg = "Cannot bind to port";
  3662. } else {
  3663. sockaddr_to_string(server->local_ip, sizeof(server->local_ip),
  3664. &server->lsa);
  3665. if (!strcmp(value, "0")) {
  3666. char buf[10];
  3667. mg_snprintf(buf, sizeof(buf), "%d",
  3668. (int) ntohs(server->lsa.sin.sin_port));
  3669. free(server->config_options[ind]);
  3670. server->config_options[ind] = mg_strdup(buf);
  3671. }
  3672. }
  3673. #ifndef _WIN32
  3674. } else if (ind == RUN_AS_USER) {
  3675. struct passwd *pw;
  3676. if ((pw = getpwnam(value)) == NULL) {
  3677. error_msg = "Unknown user";
  3678. } else if (setgid(pw->pw_gid) != 0) {
  3679. error_msg = "setgid() failed";
  3680. } else if (setuid(pw->pw_uid) != 0) {
  3681. error_msg = "setuid() failed";
  3682. }
  3683. #endif
  3684. #ifdef MONGOOSE_USE_SSL
  3685. } else if (ind == SSL_CERTIFICATE) {
  3686. //SSL_library_init();
  3687. if ((server->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  3688. error_msg = "SSL_CTX_new() failed";
  3689. } else if (SSL_CTX_use_certificate_file(server->ssl_ctx, value, 1) == 0 ||
  3690. SSL_CTX_use_PrivateKey_file(server->ssl_ctx, value, 1) == 0) {
  3691. error_msg = "Cannot load PEM file";
  3692. } else {
  3693. SSL_CTX_use_certificate_chain_file(server->ssl_ctx, value);
  3694. }
  3695. #endif
  3696. }
  3697. }
  3698. return error_msg;
  3699. }
  3700. void mg_set_request_handler(struct mg_server *server, mg_handler_t handler) {
  3701. server->request_handler = handler;
  3702. }
  3703. void mg_set_http_close_handler(struct mg_server *server, mg_handler_t handler) {
  3704. server->http_close_handler = handler;
  3705. }
  3706. void mg_set_http_error_handler(struct mg_server *server, mg_handler_t handler) {
  3707. server->error_handler = handler;
  3708. }
  3709. void mg_set_auth_handler(struct mg_server *server, mg_handler_t handler) {
  3710. server->auth_handler = handler;
  3711. }
  3712. void mg_set_listening_socket(struct mg_server *server, int sock) {
  3713. if (server->listening_sock != INVALID_SOCKET) {
  3714. closesocket(server->listening_sock);
  3715. }
  3716. server->listening_sock = (sock_t) sock;
  3717. }
  3718. int mg_get_listening_socket(struct mg_server *server) {
  3719. return server->listening_sock;
  3720. }
  3721. const char *mg_get_option(const struct mg_server *server, const char *name) {
  3722. const char **opts = (const char **) server->config_options;
  3723. int i = get_option_index(name);
  3724. return i == -1 ? NULL : opts[i] == NULL ? "" : opts[i];
  3725. }
  3726. struct mg_server *mg_create_server(void *server_data) {
  3727. struct mg_server *server = (struct mg_server *) calloc(1, sizeof(*server));
  3728. #ifdef _WIN32
  3729. WSADATA data;
  3730. WSAStartup(MAKEWORD(2, 2), &data);
  3731. #else
  3732. // Ignore SIGPIPE signal, so if browser cancels the request, it
  3733. // won't kill the whole process.
  3734. signal(SIGPIPE, SIG_IGN);
  3735. #endif
  3736. LINKED_LIST_INIT(&server->active_connections);
  3737. #ifndef MONGOOSE_NO_SOCKETPAIR
  3738. // Create control socket pair. Do it in a loop to protect from
  3739. // interrupted syscalls in mg_socketpair().
  3740. do {
  3741. mg_socketpair(server->ctl);
  3742. } while (server->ctl[0] == INVALID_SOCKET);
  3743. #endif
  3744. #ifdef MONGOOSE_USE_SSL
  3745. SSL_library_init();
  3746. server->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method());
  3747. #endif
  3748. server->server_data = server_data;
  3749. server->listening_sock = INVALID_SOCKET;
  3750. set_default_option_values(server->config_options);
  3751. return server;
  3752. }