civetweb.c 170 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313
  1. // Copyright (c) 2004-2013 Sergey Lyubka
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. #if defined(_WIN32)
  21. #if !defined(_CRT_SECURE_NO_WARNINGS)
  22. #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005
  23. #endif
  24. #else
  25. #ifdef __linux__
  26. #define _XOPEN_SOURCE 600 // For flockfile() on Linux
  27. #endif
  28. #define _LARGEFILE_SOURCE // Enable 64-bit file offsets
  29. #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++
  30. #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX
  31. #endif
  32. #if defined (_MSC_VER)
  33. // conditional expression is constant: introduced by FD_SET(..)
  34. #pragma warning (disable : 4127)
  35. // non-constant aggregate initializer: issued due to missing C99 support
  36. #pragma warning (disable : 4204)
  37. #endif
  38. // Disable WIN32_LEAN_AND_MEAN.
  39. // This makes windows.h always include winsock2.h
  40. #ifdef WIN32_LEAN_AND_MEAN
  41. #undef WIN32_LEAN_AND_MEAN
  42. #endif
  43. #if defined(__SYMBIAN32__)
  44. #define NO_SSL // SSL is not supported
  45. #define NO_CGI // CGI is not supported
  46. #define PATH_MAX FILENAME_MAX
  47. #endif // __SYMBIAN32__
  48. #ifndef IGNORE_UNUSED_RESULT
  49. #define IGNORE_UNUSED_RESULT(a) (void)((a) && 1)
  50. #endif
  51. #ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE
  52. #include <sys/types.h>
  53. #include <sys/stat.h>
  54. #include <errno.h>
  55. #include <signal.h>
  56. #include <fcntl.h>
  57. #endif // !_WIN32_WCE
  58. #include <time.h>
  59. #include <stdlib.h>
  60. #include <stdarg.h>
  61. #include <assert.h>
  62. #include <string.h>
  63. #include <ctype.h>
  64. #include <limits.h>
  65. #include <stddef.h>
  66. #include <stdio.h>
  67. #if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific
  68. #undef _WIN32_WINNT
  69. #define _WIN32_WINNT 0x0400 // To make it link in VS2005
  70. #include <windows.h>
  71. #ifndef PATH_MAX
  72. #define PATH_MAX MAX_PATH
  73. #endif
  74. #ifndef _WIN32_WCE
  75. #include <process.h>
  76. #include <direct.h>
  77. #include <io.h>
  78. #else // _WIN32_WCE
  79. #define NO_CGI // WinCE has no pipes
  80. typedef long off_t;
  81. #define errno GetLastError()
  82. #define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
  83. #endif // _WIN32_WCE
  84. #define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
  85. ((uint64_t)((uint32_t)(hi))) << 32))
  86. #define RATE_DIFF 10000000 // 100 nsecs
  87. #define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)
  88. #define SYS2UNIX_TIME(lo, hi) \
  89. (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
  90. // Visual Studio 6 does not know __func__ or __FUNCTION__
  91. // The rest of MS compilers use __FUNCTION__, not C99 __func__
  92. // Also use _strtoui64 on modern M$ compilers
  93. #if defined(_MSC_VER) && _MSC_VER < 1300
  94. #define STRX(x) #x
  95. #define STR(x) STRX(x)
  96. #define __func__ __FILE__ ":" STR(__LINE__)
  97. #define strtoull(x, y, z) (unsigned __int64) _atoi64(x)
  98. #define strtoll(x, y, z) _atoi64(x)
  99. #else
  100. #define __func__ __FUNCTION__
  101. #define strtoull(x, y, z) _strtoui64(x, y, z)
  102. #define strtoll(x, y, z) _strtoi64(x, y, z)
  103. #endif // _MSC_VER
  104. #define ERRNO GetLastError()
  105. #define NO_SOCKLEN_T
  106. #define SSL_LIB "ssleay32.dll"
  107. #define CRYPTO_LIB "libeay32.dll"
  108. #define O_NONBLOCK 0
  109. #if !defined(EWOULDBLOCK)
  110. #define EWOULDBLOCK WSAEWOULDBLOCK
  111. #endif // !EWOULDBLOCK
  112. #define _POSIX_
  113. #define INT64_FMT "I64d"
  114. #define WINCDECL __cdecl
  115. #define SHUT_WR 1
  116. #define snprintf _snprintf
  117. #define vsnprintf _vsnprintf
  118. #define mg_sleep(x) Sleep(x)
  119. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  120. #ifndef popen
  121. #define popen(x, y) _popen(x, y)
  122. #endif
  123. #ifndef pclose
  124. #define pclose(x) _pclose(x)
  125. #endif
  126. #define close(x) _close(x)
  127. #define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
  128. #define RTLD_LAZY 0
  129. #define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))
  130. #define fdopen(x, y) _fdopen((x), (y))
  131. #define write(x, y, z) _write((x), (y), (unsigned) z)
  132. #define read(x, y, z) _read((x), (y), (unsigned) z)
  133. #define flockfile(x) EnterCriticalSection(&global_log_file_lock)
  134. #define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)
  135. #define sleep(x) Sleep((x) * 1000)
  136. #define rmdir(x) _rmdir(x)
  137. #if !defined(va_copy)
  138. #define va_copy(x, y) x = y
  139. #endif // !va_copy MINGW #defines va_copy
  140. #if !defined(fileno)
  141. #define fileno(x) _fileno(x)
  142. #endif // !fileno MINGW #defines fileno
  143. typedef HANDLE pthread_mutex_t;
  144. typedef struct {HANDLE signal, broadcast;} pthread_cond_t;
  145. typedef DWORD pthread_t;
  146. #define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here.
  147. static int pthread_mutex_lock(pthread_mutex_t *);
  148. static int pthread_mutex_unlock(pthread_mutex_t *);
  149. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  150. struct file;
  151. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  152. #if defined(HAVE_STDINT)
  153. #include <stdint.h>
  154. #else
  155. typedef unsigned int uint32_t;
  156. typedef unsigned short uint16_t;
  157. typedef unsigned __int64 uint64_t;
  158. typedef __int64 int64_t;
  159. #define INT64_MAX 9223372036854775807
  160. #endif // HAVE_STDINT
  161. // POSIX dirent interface
  162. struct dirent {
  163. char d_name[PATH_MAX];
  164. };
  165. typedef struct DIR {
  166. HANDLE handle;
  167. WIN32_FIND_DATAW info;
  168. struct dirent result;
  169. } DIR;
  170. #ifndef HAVE_POLL
  171. struct pollfd {
  172. SOCKET fd;
  173. short events;
  174. short revents;
  175. };
  176. #define POLLIN 1
  177. #endif
  178. // Mark required libraries
  179. #ifdef _MSC_VER
  180. #pragma comment(lib, "Ws2_32.lib")
  181. #endif
  182. #else // UNIX specific
  183. #include <sys/wait.h>
  184. #include <sys/socket.h>
  185. #include <sys/poll.h>
  186. #include <netinet/in.h>
  187. #include <arpa/inet.h>
  188. #include <sys/time.h>
  189. #include <stdint.h>
  190. #include <inttypes.h>
  191. #include <netdb.h>
  192. #include <pwd.h>
  193. #include <unistd.h>
  194. #include <dirent.h>
  195. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  196. #include <dlfcn.h>
  197. #endif
  198. #include <pthread.h>
  199. #if defined(__MACH__)
  200. #define SSL_LIB "libssl.dylib"
  201. #define CRYPTO_LIB "libcrypto.dylib"
  202. #else
  203. #if !defined(SSL_LIB)
  204. #define SSL_LIB "libssl.so"
  205. #endif
  206. #if !defined(CRYPTO_LIB)
  207. #define CRYPTO_LIB "libcrypto.so"
  208. #endif
  209. #endif
  210. #ifndef O_BINARY
  211. #define O_BINARY 0
  212. #endif // O_BINARY
  213. #define closesocket(a) close(a)
  214. #define mg_mkdir(x, y) mkdir(x, y)
  215. #define mg_remove(x) remove(x)
  216. #define mg_sleep(x) usleep((x) * 1000)
  217. #define ERRNO errno
  218. #define INVALID_SOCKET (-1)
  219. #define INT64_FMT PRId64
  220. typedef int SOCKET;
  221. #define WINCDECL
  222. #endif // End of Windows and UNIX specific includes
  223. #include "civetweb.h"
  224. #define CIVETWEB_VERSION "1.4"
  225. #define PASSWORDS_FILE_NAME ".htpasswd"
  226. #define CGI_ENVIRONMENT_SIZE 4096
  227. #define MAX_CGI_ENVIR_VARS 64
  228. #define MG_BUF_LEN 8192
  229. #ifndef MAX_REQUEST_SIZE
  230. #define MAX_REQUEST_SIZE 16384
  231. #endif
  232. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  233. #ifdef _WIN32
  234. static CRITICAL_SECTION global_log_file_lock;
  235. static pthread_t pthread_self(void) {
  236. return GetCurrentThreadId();
  237. }
  238. #endif // _WIN32
  239. #define MD5_STATIC static
  240. #include "md5.inl"
  241. #ifdef DEBUG_TRACE
  242. #undef DEBUG_TRACE
  243. #define DEBUG_TRACE(x)
  244. #else
  245. #if defined(DEBUG)
  246. #define DEBUG_TRACE(x) do { \
  247. flockfile(stdout); \
  248. printf("*** %lu.%p.%s.%d: ", \
  249. (unsigned long) time(NULL), (void *) pthread_self(), \
  250. __func__, __LINE__); \
  251. printf x; \
  252. putchar('\n'); \
  253. fflush(stdout); \
  254. funlockfile(stdout); \
  255. } while (0)
  256. #else
  257. #define DEBUG_TRACE(x)
  258. #endif // DEBUG
  259. #endif // DEBUG_TRACE
  260. // Darwin prior to 7.0 and Win32 do not have socklen_t
  261. #ifdef NO_SOCKLEN_T
  262. typedef int socklen_t;
  263. #endif // NO_SOCKLEN_T
  264. #define _DARWIN_UNLIMITED_SELECT
  265. #define IP_ADDR_STR_LEN 50 // IPv6 hex string is 46 chars
  266. #if !defined(MSG_NOSIGNAL)
  267. #define MSG_NOSIGNAL 0
  268. #endif
  269. #if !defined(SOMAXCONN)
  270. #define SOMAXCONN 100
  271. #endif
  272. #if !defined(PATH_MAX)
  273. #define PATH_MAX 4096
  274. #endif
  275. // Size of the accepted socket queue
  276. #if !defined(MGSQLEN)
  277. #define MGSQLEN 20
  278. #endif
  279. static const char *http_500_error = "Internal Server Error";
  280. #if defined(NO_SSL_DL)
  281. #include <openssl/ssl.h>
  282. #include <openssl/err.h>
  283. #else
  284. // SSL loaded dynamically from DLL.
  285. // I put the prototypes here to be independent from OpenSSL source installation.
  286. typedef struct ssl_st SSL;
  287. typedef struct ssl_method_st SSL_METHOD;
  288. typedef struct ssl_ctx_st SSL_CTX;
  289. struct ssl_func {
  290. const char *name; // SSL function name
  291. void (*ptr)(void); // Function pointer
  292. };
  293. #define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)
  294. #define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)
  295. #define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)
  296. #define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)
  297. #define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)
  298. #define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)
  299. #define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)
  300. #define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  301. #define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  302. #define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  303. #define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)
  304. #define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \
  305. const char *, int)) ssl_sw[11].ptr)
  306. #define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \
  307. const char *, int)) ssl_sw[12].ptr)
  308. #define SSL_CTX_set_default_passwd_cb \
  309. (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)
  310. #define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)
  311. #define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)
  312. #define SSL_CTX_use_certificate_chain_file \
  313. (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)
  314. #define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  315. #define SSL_pending (* (int (*)(SSL *)) ssl_sw[18].ptr)
  316. #define SSL_CTX_set_verify (* (void (*)(SSL_CTX *, int, int)) ssl_sw[19].ptr)
  317. #define SSL_shutdown (* (int (*)(SSL *)) ssl_sw[20].ptr)
  318. #define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)
  319. #define CRYPTO_set_locking_callback \
  320. (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)
  321. #define CRYPTO_set_id_callback \
  322. (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)
  323. #define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)
  324. #define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)
  325. // set_ssl_option() function updates this array.
  326. // It loads SSL library dynamically and changes NULLs to the actual addresses
  327. // of respective functions. The macros above (like SSL_connect()) are really
  328. // just calling these functions indirectly via the pointer.
  329. static struct ssl_func ssl_sw[] = {
  330. {"SSL_free", NULL},
  331. {"SSL_accept", NULL},
  332. {"SSL_connect", NULL},
  333. {"SSL_read", NULL},
  334. {"SSL_write", NULL},
  335. {"SSL_get_error", NULL},
  336. {"SSL_set_fd", NULL},
  337. {"SSL_new", NULL},
  338. {"SSL_CTX_new", NULL},
  339. {"SSLv23_server_method", NULL},
  340. {"SSL_library_init", NULL},
  341. {"SSL_CTX_use_PrivateKey_file", NULL},
  342. {"SSL_CTX_use_certificate_file",NULL},
  343. {"SSL_CTX_set_default_passwd_cb",NULL},
  344. {"SSL_CTX_free", NULL},
  345. {"SSL_load_error_strings", NULL},
  346. {"SSL_CTX_use_certificate_chain_file", NULL},
  347. {"SSLv23_client_method", NULL},
  348. {"SSL_pending", NULL},
  349. {"SSL_CTX_set_verify", NULL},
  350. {"SSL_shutdown", NULL},
  351. {NULL, NULL}
  352. };
  353. // Similar array as ssl_sw. These functions could be located in different lib.
  354. #if !defined(NO_SSL)
  355. static struct ssl_func crypto_sw[] = {
  356. {"CRYPTO_num_locks", NULL},
  357. {"CRYPTO_set_locking_callback", NULL},
  358. {"CRYPTO_set_id_callback", NULL},
  359. {"ERR_get_error", NULL},
  360. {"ERR_error_string", NULL},
  361. {NULL, NULL}
  362. };
  363. #endif // NO_SSL
  364. #endif // NO_SSL_DL
  365. static const char *month_names[] = {
  366. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  367. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  368. };
  369. // Unified socket address. For IPv6 support, add IPv6 address structure
  370. // in the union u.
  371. union usa {
  372. struct sockaddr sa;
  373. struct sockaddr_in sin;
  374. #if defined(USE_IPV6)
  375. struct sockaddr_in6 sin6;
  376. #endif
  377. };
  378. // Describes a string (chunk of memory).
  379. struct vec {
  380. const char *ptr;
  381. size_t len;
  382. };
  383. struct file {
  384. int is_directory;
  385. time_t modification_time;
  386. int64_t size;
  387. FILE *fp;
  388. const char *membuf; // Non-NULL if file data is in memory
  389. // set to 1 if the content is gzipped
  390. // in which case we need a content-encoding: gzip header
  391. int gzipped;
  392. };
  393. #define STRUCT_FILE_INITIALIZER {0, 0, 0, NULL, NULL, 0}
  394. // Describes listening socket, or socket which was accept()-ed by the master
  395. // thread and queued for future handling by the worker thread.
  396. struct socket {
  397. SOCKET sock; // Listening socket
  398. union usa lsa; // Local socket address
  399. union usa rsa; // Remote socket address
  400. unsigned is_ssl:1; // Is port SSL-ed
  401. unsigned ssl_redir:1; // Is port supposed to redirect everything to SSL port
  402. };
  403. // NOTE(lsm): this enum shoulds be in sync with the config_options below.
  404. enum {
  405. CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,
  406. PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,
  407. ACCESS_LOG_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,
  408. GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,
  409. EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,
  410. NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES, REQUEST_TIMEOUT,
  411. NUM_OPTIONS
  412. };
  413. static const char *config_options[] = {
  414. "cgi_pattern", "**.cgi$|**.pl$|**.php$",
  415. "cgi_environment", NULL,
  416. "put_delete_auth_file", NULL,
  417. "cgi_interpreter", NULL,
  418. "protect_uri", NULL,
  419. "authentication_domain", "mydomain.com",
  420. "ssi_pattern", "**.shtml$|**.shtm$",
  421. "throttle", NULL,
  422. "access_log_file", NULL,
  423. "enable_directory_listing", "yes",
  424. "error_log_file", NULL,
  425. "global_auth_file", NULL,
  426. "index_files",
  427. "index.html,index.htm,index.cgi,index.shtml,index.php,index.lp",
  428. "enable_keep_alive", "no",
  429. "access_control_list", NULL,
  430. "extra_mime_types", NULL,
  431. "listening_ports", "8080",
  432. "document_root", NULL,
  433. "ssl_certificate", NULL,
  434. "num_threads", "50",
  435. "run_as_user", NULL,
  436. "url_rewrite_patterns", NULL,
  437. "hide_files_patterns", NULL,
  438. "request_timeout_ms", "30000",
  439. NULL
  440. };
  441. struct mg_context {
  442. volatile int stop_flag; // Should we stop event loop
  443. SSL_CTX *ssl_ctx; // SSL context
  444. char *config[NUM_OPTIONS]; // Civetweb configuration parameters
  445. struct mg_callbacks callbacks; // User-defined callback function
  446. void *user_data; // User-defined data
  447. struct socket *listening_sockets;
  448. int num_listening_sockets;
  449. volatile int num_threads; // Number of threads
  450. pthread_mutex_t mutex; // Protects (max|num)_threads
  451. pthread_cond_t cond; // Condvar for tracking workers terminations
  452. struct socket queue[MGSQLEN]; // Accepted sockets
  453. volatile int sq_head; // Head of the socket queue
  454. volatile int sq_tail; // Tail of the socket queue
  455. pthread_cond_t sq_full; // Signaled when socket is produced
  456. pthread_cond_t sq_empty; // Signaled when socket is consumed
  457. };
  458. struct mg_connection {
  459. struct mg_request_info request_info;
  460. struct mg_context *ctx;
  461. SSL *ssl; // SSL descriptor
  462. SSL_CTX *client_ssl_ctx; // SSL context for client connections
  463. struct socket client; // Connected client
  464. time_t birth_time; // Time when request was received
  465. int64_t num_bytes_sent; // Total bytes sent to client
  466. int64_t content_len; // Content-Length header value
  467. int64_t consumed_content; // How many bytes of content have been read
  468. char *buf; // Buffer for received data
  469. char *path_info; // PATH_INFO part of the URL
  470. int must_close; // 1 if connection must be closed
  471. int buf_size; // Buffer size
  472. int request_len; // Size of the request + headers in a buffer
  473. int data_len; // Total size of data in a buffer
  474. int status_code; // HTTP reply status code, e.g. 200
  475. int throttle; // Throttling, bytes/sec. <= 0 means no throttle
  476. time_t last_throttle_time; // Last time throttled data was sent
  477. int64_t last_throttle_bytes;// Bytes sent this second
  478. pthread_mutex_t mutex; // Used by mg_lock/mg_unlock to ensure atomic transmissions for websockets
  479. };
  480. // Directory entry
  481. struct de {
  482. struct mg_connection *conn;
  483. char *file_name;
  484. struct file file;
  485. };
  486. const char **mg_get_valid_option_names(void) {
  487. return config_options;
  488. }
  489. static int is_file_in_memory(struct mg_connection *conn, const char *path,
  490. struct file *filep) {
  491. size_t size = 0;
  492. if ((filep->membuf = conn->ctx->callbacks.open_file == NULL ? NULL :
  493. conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
  494. // NOTE: override filep->size only on success. Otherwise, it might break
  495. // constructs like if (!mg_stat() || !mg_fopen()) ...
  496. filep->size = size;
  497. }
  498. return filep->membuf != NULL;
  499. }
  500. static int is_file_opened(const struct file *filep) {
  501. return filep->membuf != NULL || filep->fp != NULL;
  502. }
  503. static int mg_fopen(struct mg_connection *conn, const char *path,
  504. const char *mode, struct file *filep) {
  505. if (!is_file_in_memory(conn, path, filep)) {
  506. #ifdef _WIN32
  507. wchar_t wbuf[PATH_MAX], wmode[20];
  508. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  509. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  510. filep->fp = _wfopen(wbuf, wmode);
  511. #else
  512. filep->fp = fopen(path, mode);
  513. #endif
  514. }
  515. return is_file_opened(filep);
  516. }
  517. static void mg_fclose(struct file *filep) {
  518. if (filep != NULL && filep->fp != NULL) {
  519. fclose(filep->fp);
  520. }
  521. }
  522. static int get_option_index(const char *name) {
  523. int i;
  524. for (i = 0; config_options[i * 2] != NULL; i++) {
  525. if (strcmp(config_options[i * 2], name) == 0) {
  526. return i;
  527. }
  528. }
  529. return -1;
  530. }
  531. const char *mg_get_option(const struct mg_context *ctx, const char *name) {
  532. int i;
  533. if ((i = get_option_index(name)) == -1) {
  534. return NULL;
  535. } else if (ctx->config[i] == NULL) {
  536. return "";
  537. } else {
  538. return ctx->config[i];
  539. }
  540. }
  541. static void sockaddr_to_string(char *buf, size_t len,
  542. const union usa *usa) {
  543. buf[0] = '\0';
  544. #if defined(USE_IPV6)
  545. inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
  546. (void *) &usa->sin.sin_addr :
  547. (void *) &usa->sin6.sin6_addr, buf, len);
  548. #elif defined(_WIN32)
  549. // Only Windoze Vista (and newer) have inet_ntop()
  550. strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
  551. #else
  552. inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
  553. #endif
  554. }
  555. // Print error message to the opened error log stream.
  556. void mg_cry(struct mg_connection *conn, const char *fmt, ...) {
  557. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  558. va_list ap;
  559. FILE *fp;
  560. time_t timestamp;
  561. va_start(ap, fmt);
  562. (void) vsnprintf(buf, sizeof(buf), fmt, ap);
  563. va_end(ap);
  564. // Do not lock when getting the callback value, here and below.
  565. // I suppose this is fine, since function cannot disappear in the
  566. // same way string option can.
  567. if (conn->ctx->callbacks.log_message == NULL ||
  568. conn->ctx->callbacks.log_message(conn, buf) == 0) {
  569. fp = conn->ctx == NULL || conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
  570. fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  571. if (fp != NULL) {
  572. flockfile(fp);
  573. timestamp = time(NULL);
  574. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  575. fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,
  576. src_addr);
  577. if (conn->request_info.request_method != NULL) {
  578. fprintf(fp, "%s %s: ", conn->request_info.request_method,
  579. conn->request_info.uri);
  580. }
  581. fprintf(fp, "%s", buf);
  582. fputc('\n', fp);
  583. funlockfile(fp);
  584. fclose(fp);
  585. }
  586. }
  587. }
  588. // Return fake connection structure. Used for logging, if connection
  589. // is not applicable at the moment of logging.
  590. static struct mg_connection *fc(struct mg_context *ctx) {
  591. static struct mg_connection fake_connection;
  592. fake_connection.ctx = ctx;
  593. return &fake_connection;
  594. }
  595. const char *mg_version(void) {
  596. return CIVETWEB_VERSION;
  597. }
  598. struct mg_request_info *mg_get_request_info(struct mg_connection *conn) {
  599. return &conn->request_info;
  600. }
  601. static void mg_strlcpy(register char *dst, register const char *src, size_t n) {
  602. for (; *src != '\0' && n > 1; n--) {
  603. *dst++ = *src++;
  604. }
  605. *dst = '\0';
  606. }
  607. static int lowercase(const char *s) {
  608. return tolower(* (const unsigned char *) s);
  609. }
  610. int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
  611. int diff = 0;
  612. if (len > 0)
  613. do {
  614. diff = lowercase(s1++) - lowercase(s2++);
  615. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  616. return diff;
  617. }
  618. static int mg_strcasecmp(const char *s1, const char *s2) {
  619. int diff;
  620. do {
  621. diff = lowercase(s1++) - lowercase(s2++);
  622. } while (diff == 0 && s1[-1] != '\0');
  623. return diff;
  624. }
  625. static char * mg_strndup(const char *ptr, size_t len) {
  626. char *p;
  627. if ((p = (char *) malloc(len + 1)) != NULL) {
  628. mg_strlcpy(p, ptr, len + 1);
  629. }
  630. return p;
  631. }
  632. static char * mg_strdup(const char *str) {
  633. return mg_strndup(str, strlen(str));
  634. }
  635. static const char *mg_strcasestr(const char *big_str, const char *small_str) {
  636. int i, big_len = (int)strlen(big_str), small_len = (int)strlen(small_str);
  637. for (i = 0; i <= big_len - small_len; i++) {
  638. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  639. return big_str + i;
  640. }
  641. }
  642. return NULL;
  643. }
  644. // Like snprintf(), but never returns negative value, or a value
  645. // that is larger than a supplied buffer.
  646. // Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  647. // in his audit report.
  648. static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
  649. const char *fmt, va_list ap) {
  650. int n;
  651. if (buflen == 0)
  652. return 0;
  653. n = vsnprintf(buf, buflen, fmt, ap);
  654. if (n < 0) {
  655. mg_cry(conn, "vsnprintf error");
  656. n = 0;
  657. } else if (n >= (int) buflen) {
  658. mg_cry(conn, "truncating vsnprintf buffer: [%.*s]",
  659. n > 200 ? 200 : n, buf);
  660. n = (int) buflen - 1;
  661. }
  662. buf[n] = '\0';
  663. return n;
  664. }
  665. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  666. PRINTF_FORMAT_STRING(const char *fmt), ...)
  667. PRINTF_ARGS(4, 5);
  668. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  669. const char *fmt, ...) {
  670. va_list ap;
  671. int n;
  672. va_start(ap, fmt);
  673. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  674. va_end(ap);
  675. return n;
  676. }
  677. // Skip the characters until one of the delimiters characters found.
  678. // 0-terminate resulting word. Skip the delimiter and following whitespaces.
  679. // Advance pointer to buffer to the next word. Return found 0-terminated word.
  680. // Delimiters can be quoted with quotechar.
  681. static char *skip_quoted(char **buf, const char *delimiters,
  682. const char *whitespace, char quotechar) {
  683. char *p, *begin_word, *end_word, *end_whitespace;
  684. begin_word = *buf;
  685. end_word = begin_word + strcspn(begin_word, delimiters);
  686. // Check for quotechar
  687. if (end_word > begin_word) {
  688. p = end_word - 1;
  689. while (*p == quotechar) {
  690. // If there is anything beyond end_word, copy it
  691. if (*end_word == '\0') {
  692. *p = '\0';
  693. break;
  694. } else {
  695. size_t end_off = strcspn(end_word + 1, delimiters);
  696. memmove (p, end_word, end_off + 1);
  697. p += end_off; // p must correspond to end_word - 1
  698. end_word += end_off + 1;
  699. }
  700. }
  701. for (p++; p < end_word; p++) {
  702. *p = '\0';
  703. }
  704. }
  705. if (*end_word == '\0') {
  706. *buf = end_word;
  707. } else {
  708. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  709. for (p = end_word; p < end_whitespace; p++) {
  710. *p = '\0';
  711. }
  712. *buf = end_whitespace;
  713. }
  714. return begin_word;
  715. }
  716. // Simplified version of skip_quoted without quote char
  717. // and whitespace == delimiters
  718. static char *skip(char **buf, const char *delimiters) {
  719. return skip_quoted(buf, delimiters, delimiters, 0);
  720. }
  721. // Return HTTP header value, or NULL if not found.
  722. static const char *get_header(const struct mg_request_info *ri,
  723. const char *name) {
  724. int i;
  725. for (i = 0; i < ri->num_headers; i++)
  726. if (!mg_strcasecmp(name, ri->http_headers[i].name))
  727. return ri->http_headers[i].value;
  728. return NULL;
  729. }
  730. const char *mg_get_header(const struct mg_connection *conn, const char *name) {
  731. return get_header(&conn->request_info, name);
  732. }
  733. // A helper function for traversing a comma separated list of values.
  734. // It returns a list pointer shifted to the next value, or NULL if the end
  735. // of the list found.
  736. // Value is stored in val vector. If value has form "x=y", then eq_val
  737. // vector is initialized to point to the "y" part, and val vector length
  738. // is adjusted to point only to "x".
  739. static const char *next_option(const char *list, struct vec *val,
  740. struct vec *eq_val) {
  741. if (list == NULL || *list == '\0') {
  742. // End of the list
  743. list = NULL;
  744. } else {
  745. val->ptr = list;
  746. if ((list = strchr(val->ptr, ',')) != NULL) {
  747. // Comma found. Store length and shift the list ptr
  748. val->len = list - val->ptr;
  749. list++;
  750. } else {
  751. // This value is the last one
  752. list = val->ptr + strlen(val->ptr);
  753. val->len = list - val->ptr;
  754. }
  755. if (eq_val != NULL) {
  756. // Value has form "x=y", adjust pointers and lengths
  757. // so that val points to "x", and eq_val points to "y".
  758. eq_val->len = 0;
  759. eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
  760. if (eq_val->ptr != NULL) {
  761. eq_val->ptr++; // Skip over '=' character
  762. eq_val->len = val->ptr + val->len - eq_val->ptr;
  763. val->len = (eq_val->ptr - val->ptr) - 1;
  764. }
  765. }
  766. }
  767. return list;
  768. }
  769. // Perform case-insensitive match of string against pattern
  770. static int match_prefix(const char *pattern, int pattern_len, const char *str) {
  771. const char *or_str;
  772. int i, j, len, res;
  773. if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
  774. res = match_prefix(pattern, (int)(or_str - pattern), str);
  775. return res > 0 ? res :
  776. match_prefix(or_str + 1, (int)((pattern + pattern_len) - (or_str + 1)), str);
  777. }
  778. i = j = 0;
  779. res = -1;
  780. for (; i < pattern_len; i++, j++) {
  781. if (pattern[i] == '?' && str[j] != '\0') {
  782. continue;
  783. } else if (pattern[i] == '$') {
  784. return str[j] == '\0' ? j : -1;
  785. } else if (pattern[i] == '*') {
  786. i++;
  787. if (pattern[i] == '*') {
  788. i++;
  789. len = (int) strlen(str + j);
  790. } else {
  791. len = (int) strcspn(str + j, "/");
  792. }
  793. if (i == pattern_len) {
  794. return j + len;
  795. }
  796. do {
  797. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  798. } while (res == -1 && len-- > 0);
  799. return res == -1 ? -1 : j + res + len;
  800. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  801. return -1;
  802. }
  803. }
  804. return j;
  805. }
  806. // HTTP 1.1 assumes keep alive if "Connection:" header is not set
  807. // This function must tolerate situations when connection info is not
  808. // set up, for example if request parsing failed.
  809. static int should_keep_alive(const struct mg_connection *conn) {
  810. const char *http_version = conn->request_info.http_version;
  811. const char *header = mg_get_header(conn, "Connection");
  812. if (conn->must_close ||
  813. conn->status_code == 401 ||
  814. mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
  815. (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
  816. (header == NULL && http_version && strcmp(http_version, "1.1"))) {
  817. return 0;
  818. }
  819. return 1;
  820. }
  821. static const char *suggest_connection_header(const struct mg_connection *conn) {
  822. return should_keep_alive(conn) ? "keep-alive" : "close";
  823. }
  824. static void send_http_error(struct mg_connection *, int, const char *,
  825. PRINTF_FORMAT_STRING(const char *fmt), ...)
  826. PRINTF_ARGS(4, 5);
  827. static void send_http_error(struct mg_connection *conn, int status,
  828. const char *reason, const char *fmt, ...) {
  829. char buf[MG_BUF_LEN];
  830. va_list ap;
  831. int len = 0;
  832. conn->status_code = status;
  833. if (conn->ctx->callbacks.http_error == NULL ||
  834. conn->ctx->callbacks.http_error(conn, status)) {
  835. buf[0] = '\0';
  836. // Errors 1xx, 204 and 304 MUST NOT send a body
  837. if (status > 199 && status != 204 && status != 304) {
  838. len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);
  839. buf[len++] = '\n';
  840. va_start(ap, fmt);
  841. len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
  842. va_end(ap);
  843. }
  844. DEBUG_TRACE(("[%s]", buf));
  845. mg_printf(conn, "HTTP/1.1 %d %s\r\n"
  846. "Content-Length: %d\r\n"
  847. "Connection: %s\r\n\r\n", status, reason, len,
  848. suggest_connection_header(conn));
  849. conn->num_bytes_sent += mg_printf(conn, "%s", buf);
  850. }
  851. }
  852. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  853. static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused) {
  854. (void) unused;
  855. *mutex = CreateMutex(NULL, FALSE, NULL);
  856. return *mutex == NULL ? -1 : 0;
  857. }
  858. static int pthread_mutex_destroy(pthread_mutex_t *mutex) {
  859. return CloseHandle(*mutex) == 0 ? -1 : 0;
  860. }
  861. static int pthread_mutex_lock(pthread_mutex_t *mutex) {
  862. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
  863. }
  864. static int pthread_mutex_unlock(pthread_mutex_t *mutex) {
  865. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  866. }
  867. static int pthread_cond_init(pthread_cond_t *cv, const void *unused) {
  868. (void) unused;
  869. cv->signal = CreateEvent(NULL, FALSE, FALSE, NULL);
  870. cv->broadcast = CreateEvent(NULL, TRUE, FALSE, NULL);
  871. return cv->signal != NULL && cv->broadcast != NULL ? 0 : -1;
  872. }
  873. static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) {
  874. HANDLE handles[] = {cv->signal, cv->broadcast};
  875. ReleaseMutex(*mutex);
  876. WaitForMultipleObjects(2, handles, FALSE, INFINITE);
  877. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
  878. }
  879. static int pthread_cond_signal(pthread_cond_t *cv) {
  880. return SetEvent(cv->signal) == 0 ? -1 : 0;
  881. }
  882. static int pthread_cond_broadcast(pthread_cond_t *cv) {
  883. // Implementation with PulseEvent() has race condition, see
  884. // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
  885. return PulseEvent(cv->broadcast) == 0 ? -1 : 0;
  886. }
  887. static int pthread_cond_destroy(pthread_cond_t *cv) {
  888. return CloseHandle(cv->signal) && CloseHandle(cv->broadcast) ? 0 : -1;
  889. }
  890. // For Windows, change all slashes to backslashes in path names.
  891. static void change_slashes_to_backslashes(char *path) {
  892. int i;
  893. for (i = 0; path[i] != '\0'; i++) {
  894. if (path[i] == '/')
  895. path[i] = '\\';
  896. // i > 0 check is to preserve UNC paths, like \\server\file.txt
  897. if (path[i] == '\\' && i > 0)
  898. while (path[i + 1] == '\\' || path[i + 1] == '/')
  899. (void) memmove(path + i + 1,
  900. path + i + 2, strlen(path + i + 1));
  901. }
  902. }
  903. // Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  904. // wbuf and wbuf_len is a target buffer and its length.
  905. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  906. char buf[PATH_MAX], buf2[PATH_MAX];
  907. mg_strlcpy(buf, path, sizeof(buf));
  908. change_slashes_to_backslashes(buf);
  909. // Convert to Unicode and back. If doubly-converted string does not
  910. // match the original, something is fishy, reject.
  911. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  912. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  913. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  914. NULL, NULL);
  915. if (strcmp(buf, buf2) != 0) {
  916. wbuf[0] = L'\0';
  917. }
  918. }
  919. #if defined(_WIN32_WCE)
  920. static time_t time(time_t *ptime) {
  921. time_t t;
  922. SYSTEMTIME st;
  923. FILETIME ft;
  924. GetSystemTime(&st);
  925. SystemTimeToFileTime(&st, &ft);
  926. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  927. if (ptime != NULL) {
  928. *ptime = t;
  929. }
  930. return t;
  931. }
  932. static struct tm *localtime(const time_t *ptime, struct tm *ptm) {
  933. int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;
  934. FILETIME ft, lft;
  935. SYSTEMTIME st;
  936. TIME_ZONE_INFORMATION tzinfo;
  937. if (ptm == NULL) {
  938. return NULL;
  939. }
  940. * (int64_t *) &ft = t;
  941. FileTimeToLocalFileTime(&ft, &lft);
  942. FileTimeToSystemTime(&lft, &st);
  943. ptm->tm_year = st.wYear - 1900;
  944. ptm->tm_mon = st.wMonth - 1;
  945. ptm->tm_wday = st.wDayOfWeek;
  946. ptm->tm_mday = st.wDay;
  947. ptm->tm_hour = st.wHour;
  948. ptm->tm_min = st.wMinute;
  949. ptm->tm_sec = st.wSecond;
  950. ptm->tm_yday = 0; // hope nobody uses this
  951. ptm->tm_isdst =
  952. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  953. return ptm;
  954. }
  955. static struct tm *gmtime(const time_t *ptime, struct tm *ptm) {
  956. // FIXME(lsm): fix this.
  957. return localtime(ptime, ptm);
  958. }
  959. static size_t strftime(char *dst, size_t dst_size, const char *fmt,
  960. const struct tm *tm) {
  961. (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
  962. return 0;
  963. }
  964. #endif
  965. // Windows happily opens files with some garbage at the end of file name.
  966. // For example, fopen("a.cgi ", "r") on Windows successfully opens
  967. // "a.cgi", despite one would expect an error back.
  968. // This function returns non-0 if path ends with some garbage.
  969. static int path_cannot_disclose_cgi(const char *path) {
  970. static const char *allowed_last_characters = "_-";
  971. int last = path[strlen(path) - 1];
  972. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  973. }
  974. static int mg_stat(struct mg_connection *conn, const char *path,
  975. struct file *filep) {
  976. wchar_t wbuf[PATH_MAX];
  977. WIN32_FILE_ATTRIBUTE_DATA info;
  978. if (!is_file_in_memory(conn, path, filep)) {
  979. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  980. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  981. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  982. filep->modification_time = SYS2UNIX_TIME(
  983. info.ftLastWriteTime.dwLowDateTime,
  984. info.ftLastWriteTime.dwHighDateTime);
  985. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  986. // If file name is fishy, reset the file structure and return error.
  987. // Note it is important to reset, not just return the error, cause
  988. // functions like is_file_opened() check the struct.
  989. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  990. memset(filep, 0, sizeof(*filep));
  991. }
  992. }
  993. }
  994. return filep->membuf != NULL || filep->modification_time != 0;
  995. }
  996. static int mg_remove(const char *path) {
  997. wchar_t wbuf[PATH_MAX];
  998. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  999. return DeleteFileW(wbuf) ? 0 : -1;
  1000. }
  1001. static int mg_mkdir(const char *path, int mode) {
  1002. char buf[PATH_MAX];
  1003. wchar_t wbuf[PATH_MAX];
  1004. (void) mode;
  1005. mg_strlcpy(buf, path, sizeof(buf));
  1006. change_slashes_to_backslashes(buf);
  1007. (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  1008. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  1009. }
  1010. // Implementation of POSIX opendir/closedir/readdir for Windows.
  1011. static DIR * opendir(const char *name) {
  1012. DIR *dir = NULL;
  1013. wchar_t wpath[PATH_MAX];
  1014. DWORD attrs;
  1015. if (name == NULL) {
  1016. SetLastError(ERROR_BAD_ARGUMENTS);
  1017. } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
  1018. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1019. } else {
  1020. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  1021. attrs = GetFileAttributesW(wpath);
  1022. if (attrs != 0xFFFFFFFF &&
  1023. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  1024. (void) wcscat(wpath, L"\\*");
  1025. dir->handle = FindFirstFileW(wpath, &dir->info);
  1026. dir->result.d_name[0] = '\0';
  1027. } else {
  1028. free(dir);
  1029. dir = NULL;
  1030. }
  1031. }
  1032. return dir;
  1033. }
  1034. static int closedir(DIR *dir) {
  1035. int result = 0;
  1036. if (dir != NULL) {
  1037. if (dir->handle != INVALID_HANDLE_VALUE)
  1038. result = FindClose(dir->handle) ? 0 : -1;
  1039. free(dir);
  1040. } else {
  1041. result = -1;
  1042. SetLastError(ERROR_BAD_ARGUMENTS);
  1043. }
  1044. return result;
  1045. }
  1046. static struct dirent *readdir(DIR *dir) {
  1047. struct dirent *result = 0;
  1048. if (dir) {
  1049. if (dir->handle != INVALID_HANDLE_VALUE) {
  1050. result = &dir->result;
  1051. (void) WideCharToMultiByte(CP_UTF8, 0,
  1052. dir->info.cFileName, -1, result->d_name,
  1053. sizeof(result->d_name), NULL, NULL);
  1054. if (!FindNextFileW(dir->handle, &dir->info)) {
  1055. (void) FindClose(dir->handle);
  1056. dir->handle = INVALID_HANDLE_VALUE;
  1057. }
  1058. } else {
  1059. SetLastError(ERROR_FILE_NOT_FOUND);
  1060. }
  1061. } else {
  1062. SetLastError(ERROR_BAD_ARGUMENTS);
  1063. }
  1064. return result;
  1065. }
  1066. #ifndef HAVE_POLL
  1067. static int poll(struct pollfd *pfd, int n, int milliseconds) {
  1068. struct timeval tv;
  1069. fd_set set;
  1070. int i, result;
  1071. SOCKET maxfd = 0;
  1072. tv.tv_sec = milliseconds / 1000;
  1073. tv.tv_usec = (milliseconds % 1000) * 1000;
  1074. FD_ZERO(&set);
  1075. for (i = 0; i < n; i++) {
  1076. FD_SET((SOCKET) pfd[i].fd, &set);
  1077. pfd[i].revents = 0;
  1078. if (pfd[i].fd > maxfd) {
  1079. maxfd = pfd[i].fd;
  1080. }
  1081. }
  1082. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  1083. for (i = 0; i < n; i++) {
  1084. if (FD_ISSET(pfd[i].fd, &set)) {
  1085. pfd[i].revents = POLLIN;
  1086. }
  1087. }
  1088. }
  1089. return result;
  1090. }
  1091. #endif // HAVE_POLL
  1092. static void set_close_on_exec(SOCKET sock) {
  1093. (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
  1094. }
  1095. int mg_start_thread(mg_thread_func_t f, void *p) {
  1096. return (long)_beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;
  1097. }
  1098. static HANDLE dlopen(const char *dll_name, int flags) {
  1099. wchar_t wbuf[PATH_MAX];
  1100. (void) flags;
  1101. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  1102. return LoadLibraryW(wbuf);
  1103. }
  1104. #if !defined(NO_CGI)
  1105. #define SIGKILL 0
  1106. static int kill(pid_t pid, int sig_num) {
  1107. (void) TerminateProcess(pid, sig_num);
  1108. (void) CloseHandle(pid);
  1109. return 0;
  1110. }
  1111. static void trim_trailing_whitespaces(char *s) {
  1112. char *e = s + strlen(s) - 1;
  1113. while (e > s && isspace(* (unsigned char *) e)) {
  1114. *e-- = '\0';
  1115. }
  1116. }
  1117. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1118. char *envblk, char *envp[], int fdin,
  1119. int fdout, const char *dir) {
  1120. HANDLE me;
  1121. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  1122. cmdline[PATH_MAX], buf[PATH_MAX];
  1123. struct file file = STRUCT_FILE_INITIALIZER;
  1124. STARTUPINFOA si;
  1125. PROCESS_INFORMATION pi = { 0 };
  1126. (void) envp;
  1127. memset(&si, 0, sizeof(si));
  1128. si.cb = sizeof(si);
  1129. // TODO(lsm): redirect CGI errors to the error log file
  1130. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  1131. si.wShowWindow = SW_HIDE;
  1132. me = GetCurrentProcess();
  1133. DuplicateHandle(me, (HANDLE) _get_osfhandle(fdin), me,
  1134. &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1135. DuplicateHandle(me, (HANDLE) _get_osfhandle(fdout), me,
  1136. &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1137. // If CGI file is a script, try to read the interpreter line
  1138. interp = conn->ctx->config[CGI_INTERPRETER];
  1139. if (interp == NULL) {
  1140. buf[0] = buf[1] = '\0';
  1141. // Read the first line of the script into the buffer
  1142. snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
  1143. if (mg_fopen(conn, cmdline, "r", &file)) {
  1144. p = (char *) file.membuf;
  1145. mg_fgets(buf, sizeof(buf), &file, &p);
  1146. mg_fclose(&file);
  1147. buf[sizeof(buf) - 1] = '\0';
  1148. }
  1149. if (buf[0] == '#' && buf[1] == '!') {
  1150. trim_trailing_whitespaces(buf + 2);
  1151. } else {
  1152. buf[2] = '\0';
  1153. }
  1154. interp = buf + 2;
  1155. }
  1156. if (interp[0] != '\0') {
  1157. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  1158. interp = full_interp;
  1159. }
  1160. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  1161. mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s\"%s\\%s\"",
  1162. interp, interp[0] == '\0' ? "" : " ", full_dir, prog);
  1163. DEBUG_TRACE(("Running [%s]", cmdline));
  1164. if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
  1165. CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) {
  1166. mg_cry(conn, "%s: CreateProcess(%s): %ld",
  1167. __func__, cmdline, ERRNO);
  1168. pi.hProcess = (pid_t) -1;
  1169. }
  1170. (void) CloseHandle(si.hStdOutput);
  1171. (void) CloseHandle(si.hStdInput);
  1172. if (pi.hThread != NULL)
  1173. (void) CloseHandle(pi.hThread);
  1174. return (pid_t) pi.hProcess;
  1175. }
  1176. #endif // !NO_CGI
  1177. static int set_non_blocking_mode(SOCKET sock) {
  1178. unsigned long on = 1;
  1179. return ioctlsocket(sock, FIONBIO, &on);
  1180. }
  1181. #else
  1182. static int mg_stat(struct mg_connection *conn, const char *path,
  1183. struct file *filep) {
  1184. struct stat st;
  1185. if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {
  1186. filep->size = st.st_size;
  1187. filep->modification_time = st.st_mtime;
  1188. filep->is_directory = S_ISDIR(st.st_mode);
  1189. } else {
  1190. filep->modification_time = (time_t) 0;
  1191. }
  1192. return filep->membuf != NULL || filep->modification_time != (time_t) 0;
  1193. }
  1194. static void set_close_on_exec(int fd) {
  1195. fcntl(fd, F_SETFD, FD_CLOEXEC);
  1196. }
  1197. int mg_start_thread(mg_thread_func_t func, void *param) {
  1198. pthread_t thread_id;
  1199. pthread_attr_t attr;
  1200. int result;
  1201. (void) pthread_attr_init(&attr);
  1202. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  1203. #if USE_STACK_SIZE > 1
  1204. // Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  1205. (void) pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  1206. #endif
  1207. result = pthread_create(&thread_id, &attr, func, param);
  1208. pthread_attr_destroy(&attr);
  1209. return result;
  1210. }
  1211. #ifndef NO_CGI
  1212. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1213. char *envblk, char *envp[], int fdin,
  1214. int fdout, const char *dir) {
  1215. pid_t pid;
  1216. const char *interp;
  1217. (void) envblk;
  1218. if ((pid = fork()) == -1) {
  1219. // Parent
  1220. send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));
  1221. } else if (pid == 0) {
  1222. // Child
  1223. if (chdir(dir) != 0) {
  1224. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  1225. } else if (dup2(fdin, 0) == -1) {
  1226. mg_cry(conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  1227. } else if (dup2(fdout, 1) == -1) {
  1228. mg_cry(conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  1229. } else {
  1230. // Not redirecting stderr to stdout, to avoid output being littered
  1231. // with the error messages.
  1232. (void) close(fdin);
  1233. (void) close(fdout);
  1234. // After exec, all signal handlers are restored to their default values,
  1235. // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
  1236. // implementation, SIGCHLD's handler will leave unchanged after exec
  1237. // if it was set to be ignored. Restore it to default action.
  1238. signal(SIGCHLD, SIG_DFL);
  1239. interp = conn->ctx->config[CGI_INTERPRETER];
  1240. if (interp == NULL) {
  1241. (void) execle(prog, prog, NULL, envp);
  1242. mg_cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
  1243. } else {
  1244. (void) execle(interp, interp, prog, NULL, envp);
  1245. mg_cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
  1246. strerror(ERRNO));
  1247. }
  1248. }
  1249. exit(EXIT_FAILURE);
  1250. }
  1251. return pid;
  1252. }
  1253. #endif // !NO_CGI
  1254. static int set_non_blocking_mode(SOCKET sock) {
  1255. int flags;
  1256. flags = fcntl(sock, F_GETFL, 0);
  1257. (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  1258. return 0;
  1259. }
  1260. #endif // _WIN32
  1261. // Write data to the IO channel - opened file descriptor, socket or SSL
  1262. // descriptor. Return number of bytes written.
  1263. static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
  1264. int64_t len) {
  1265. int64_t sent;
  1266. int n, k;
  1267. (void) ssl; // Get rid of warning
  1268. sent = 0;
  1269. while (sent < len) {
  1270. // How many bytes we send in this iteration
  1271. k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
  1272. #ifndef NO_SSL
  1273. if (ssl != NULL) {
  1274. n = SSL_write(ssl, buf + sent, k);
  1275. } else
  1276. #endif
  1277. if (fp != NULL) {
  1278. n = (int) fwrite(buf + sent, 1, (size_t) k, fp);
  1279. if (ferror(fp))
  1280. n = -1;
  1281. } else {
  1282. n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);
  1283. }
  1284. if (n <= 0)
  1285. break;
  1286. sent += n;
  1287. }
  1288. return sent;
  1289. }
  1290. // Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  1291. // Return negative value on error, or number of bytes read on success.
  1292. static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len) {
  1293. int nread;
  1294. if (fp != NULL) {
  1295. // Use read() instead of fread(), because if we're reading from the CGI
  1296. // pipe, fread() may block until IO buffer is filled up. We cannot afford
  1297. // to block and must pass all read bytes immediately to the client.
  1298. nread = read(fileno(fp), buf, (size_t) len);
  1299. #ifndef NO_SSL
  1300. } else if (conn->ssl != NULL) {
  1301. nread = SSL_read(conn->ssl, buf, len);
  1302. #endif
  1303. } else {
  1304. nread = recv(conn->client.sock, buf, (size_t) len, 0);
  1305. }
  1306. return conn->ctx->stop_flag ? -1 : nread;
  1307. }
  1308. static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len) {
  1309. int n, nread = 0;
  1310. while (len > 0 && conn->ctx->stop_flag == 0) {
  1311. n = pull(fp, conn, buf + nread, len);
  1312. if (n < 0) {
  1313. nread = n; // Propagate the error
  1314. break;
  1315. } else if (n == 0) {
  1316. break; // No more data to read
  1317. } else {
  1318. conn->consumed_content += n;
  1319. nread += n;
  1320. len -= n;
  1321. }
  1322. }
  1323. return nread;
  1324. }
  1325. int mg_read(struct mg_connection *conn, void *buf, size_t len) {
  1326. int n, buffered_len, nread;
  1327. const char *body;
  1328. // If Content-Length is not set, read until socket is closed
  1329. if (conn->consumed_content == 0 && conn->content_len == 0) {
  1330. conn->content_len = INT64_MAX;
  1331. conn->must_close = 1;
  1332. }
  1333. nread = 0;
  1334. if (conn->consumed_content < conn->content_len) {
  1335. // Adjust number of bytes to read.
  1336. int64_t to_read = conn->content_len - conn->consumed_content;
  1337. if (to_read < (int64_t) len) {
  1338. len = (size_t) to_read;
  1339. }
  1340. // Return buffered data
  1341. body = conn->buf + conn->request_len + conn->consumed_content;
  1342. buffered_len = (int)(&conn->buf[conn->data_len] - body);
  1343. if (buffered_len > 0) {
  1344. if (len < (size_t) buffered_len) {
  1345. buffered_len = (int) len;
  1346. }
  1347. memcpy(buf, body, (size_t) buffered_len);
  1348. len -= buffered_len;
  1349. conn->consumed_content += buffered_len;
  1350. nread += buffered_len;
  1351. buf = (char *) buf + buffered_len;
  1352. }
  1353. // We have returned all buffered data. Read new data from the remote socket.
  1354. n = pull_all(NULL, conn, (char *) buf, (int) len);
  1355. nread = n >= 0 ? nread + n : n;
  1356. }
  1357. return nread;
  1358. }
  1359. int mg_write(struct mg_connection *conn, const void *buf, size_t len) {
  1360. time_t now;
  1361. int64_t n, total, allowed;
  1362. if (conn->throttle > 0) {
  1363. if ((now = time(NULL)) != conn->last_throttle_time) {
  1364. conn->last_throttle_time = now;
  1365. conn->last_throttle_bytes = 0;
  1366. }
  1367. allowed = conn->throttle - conn->last_throttle_bytes;
  1368. if (allowed > (int64_t) len) {
  1369. allowed = len;
  1370. }
  1371. if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1372. (int64_t) allowed)) == allowed) {
  1373. buf = (char *) buf + total;
  1374. conn->last_throttle_bytes += total;
  1375. while (total < (int64_t) len && conn->ctx->stop_flag == 0) {
  1376. allowed = conn->throttle > (int64_t) len - total ?
  1377. (int64_t) len - total : conn->throttle;
  1378. if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1379. (int64_t) allowed)) != allowed) {
  1380. break;
  1381. }
  1382. sleep(1);
  1383. conn->last_throttle_bytes = allowed;
  1384. conn->last_throttle_time = time(NULL);
  1385. buf = (char *) buf + n;
  1386. total += n;
  1387. }
  1388. }
  1389. } else {
  1390. total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1391. (int64_t) len);
  1392. }
  1393. return (int) total;
  1394. }
  1395. // Alternative alloc_vprintf() for non-compliant C runtimes
  1396. static int alloc_vprintf2(char **buf, const char *fmt, va_list ap) {
  1397. va_list ap_copy;
  1398. int size = MG_BUF_LEN;
  1399. int len = -1;
  1400. *buf = NULL;
  1401. while (len == -1) {
  1402. if (*buf) free(*buf);
  1403. *buf = (char *)malloc(size *= 4);
  1404. if (!*buf) break;
  1405. va_copy(ap_copy, ap);
  1406. len = vsnprintf(*buf, size, fmt, ap_copy);
  1407. }
  1408. return len;
  1409. }
  1410. // Print message to buffer. If buffer is large enough to hold the message,
  1411. // return buffer. If buffer is to small, allocate large enough buffer on heap,
  1412. // and return allocated buffer.
  1413. static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap) {
  1414. va_list ap_copy;
  1415. int len;
  1416. // Windows is not standard-compliant, and vsnprintf() returns -1 if
  1417. // buffer is too small. Also, older versions of msvcrt.dll do not have
  1418. // _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  1419. // Therefore, we make two passes: on first pass, get required message length.
  1420. // On second pass, actually print the message.
  1421. va_copy(ap_copy, ap);
  1422. len = vsnprintf(NULL, 0, fmt, ap_copy);
  1423. if (len < 0) {
  1424. // C runtime is not standard compliant, vsnprintf() returned -1.
  1425. // Switch to alternative code path that uses incremental allocations.
  1426. va_copy(ap_copy, ap);
  1427. len = alloc_vprintf2(buf, fmt, ap);
  1428. } else if (len > (int) size &&
  1429. (size = len + 1) > 0 &&
  1430. (*buf = (char *) malloc(size)) == NULL) {
  1431. len = -1; // Allocation failed, mark failure
  1432. } else {
  1433. va_copy(ap_copy, ap);
  1434. vsnprintf(*buf, size, fmt, ap_copy);
  1435. }
  1436. return len;
  1437. }
  1438. int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap) {
  1439. char mem[MG_BUF_LEN], *buf = mem;
  1440. int len;
  1441. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  1442. len = mg_write(conn, buf, (size_t) len);
  1443. }
  1444. if (buf != mem && buf != NULL) {
  1445. free(buf);
  1446. }
  1447. return len;
  1448. }
  1449. int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
  1450. va_list ap;
  1451. va_start(ap, fmt);
  1452. return mg_vprintf(conn, fmt, ap);
  1453. }
  1454. int mg_url_decode(const char *src, int src_len, char *dst,
  1455. int dst_len, int is_form_url_encoded) {
  1456. int i, j, a, b;
  1457. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  1458. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  1459. if (src[i] == '%' && i < src_len - 2 &&
  1460. isxdigit(* (const unsigned char *) (src + i + 1)) &&
  1461. isxdigit(* (const unsigned char *) (src + i + 2))) {
  1462. a = tolower(* (const unsigned char *) (src + i + 1));
  1463. b = tolower(* (const unsigned char *) (src + i + 2));
  1464. dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
  1465. i += 2;
  1466. } else if (is_form_url_encoded && src[i] == '+') {
  1467. dst[j] = ' ';
  1468. } else {
  1469. dst[j] = src[i];
  1470. }
  1471. }
  1472. dst[j] = '\0'; // Null-terminate the destination
  1473. return i >= src_len ? j : -1;
  1474. }
  1475. int mg_get_var(const char *data, size_t data_len, const char *name,
  1476. char *dst, size_t dst_len) {
  1477. return mg_get_var2(data,data_len,name,dst,dst_len,0);
  1478. }
  1479. int mg_get_var2(const char *data, size_t data_len, const char *name,
  1480. char *dst, size_t dst_len, size_t occurrence) {
  1481. const char *p, *e, *s;
  1482. size_t name_len;
  1483. int len;
  1484. if (dst == NULL || dst_len == 0) {
  1485. len = -2;
  1486. } else if (data == NULL || name == NULL || data_len == 0) {
  1487. len = -1;
  1488. dst[0] = '\0';
  1489. } else {
  1490. name_len = strlen(name);
  1491. e = data + data_len;
  1492. len = -1;
  1493. dst[0] = '\0';
  1494. // data is "var1=val1&var2=val2...". Find variable first
  1495. for (p = data; p + name_len < e; p++) {
  1496. if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
  1497. !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  1498. // Point p to variable value
  1499. p += name_len + 1;
  1500. // Point s to the end of the value
  1501. s = (const char *) memchr(p, '&', (size_t)(e - p));
  1502. if (s == NULL) {
  1503. s = e;
  1504. }
  1505. assert(s >= p);
  1506. // Decode variable into destination buffer
  1507. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  1508. // Redirect error code from -1 to -2 (destination buffer too small).
  1509. if (len == -1) {
  1510. len = -2;
  1511. }
  1512. break;
  1513. }
  1514. }
  1515. }
  1516. return len;
  1517. }
  1518. int mg_get_cookie(const char *cookie_header, const char *var_name,
  1519. char *dst, size_t dst_size) {
  1520. const char *s, *p, *end;
  1521. int name_len, len = -1;
  1522. if (dst == NULL || dst_size == 0) {
  1523. len = -2;
  1524. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  1525. len = -1;
  1526. dst[0] = '\0';
  1527. } else {
  1528. name_len = (int) strlen(var_name);
  1529. end = s + strlen(s);
  1530. dst[0] = '\0';
  1531. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  1532. if (s[name_len] == '=') {
  1533. s += name_len + 1;
  1534. if ((p = strchr(s, ' ')) == NULL)
  1535. p = end;
  1536. if (p[-1] == ';')
  1537. p--;
  1538. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  1539. s++;
  1540. p--;
  1541. }
  1542. if ((size_t) (p - s) < dst_size) {
  1543. len = (int)(p - s);
  1544. mg_strlcpy(dst, s, (size_t) len + 1);
  1545. } else {
  1546. len = -3;
  1547. }
  1548. break;
  1549. }
  1550. }
  1551. }
  1552. return len;
  1553. }
  1554. static void convert_uri_to_file_name(struct mg_connection *conn, char *buf,
  1555. size_t buf_len, struct file *filep) {
  1556. struct vec a, b;
  1557. const char *rewrite, *uri = conn->request_info.uri,
  1558. *root = conn->ctx->config[DOCUMENT_ROOT];
  1559. char *p;
  1560. int match_len;
  1561. char gz_path[PATH_MAX];
  1562. char const* accept_encoding;
  1563. // Using buf_len - 1 because memmove() for PATH_INFO may shift part
  1564. // of the path one byte on the right.
  1565. // If document_root is NULL, leave the file empty.
  1566. mg_snprintf(conn, buf, buf_len - 1, "%s%s",
  1567. root == NULL ? "" : root,
  1568. root == NULL ? "" : uri);
  1569. rewrite = conn->ctx->config[REWRITE];
  1570. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  1571. if ((match_len = match_prefix(a.ptr, (int) a.len, uri)) > 0) {
  1572. mg_snprintf(conn, buf, buf_len - 1, "%.*s%s", (int) b.len, b.ptr,
  1573. uri + match_len);
  1574. break;
  1575. }
  1576. }
  1577. if (mg_stat(conn, buf, filep)) return;
  1578. // if we can't find the actual file, look for the file
  1579. // with the same name but a .gz extension. If we find it,
  1580. // use that and set the gzipped flag in the file struct
  1581. // to indicate that the response need to have the content-
  1582. // encoding: gzip header
  1583. // we can only do this if the browser declares support
  1584. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  1585. if (strstr(accept_encoding,"gzip") != NULL) {
  1586. snprintf(gz_path, sizeof(gz_path), "%s.gz", buf);
  1587. if (mg_stat(conn, gz_path, filep)) {
  1588. filep->gzipped = 1;
  1589. return;
  1590. }
  1591. }
  1592. }
  1593. // Support PATH_INFO for CGI scripts.
  1594. for (p = buf + strlen(buf); p > buf + 1; p--) {
  1595. if (*p == '/') {
  1596. *p = '\0';
  1597. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  1598. (int)strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 &&
  1599. mg_stat(conn, buf, filep)) {
  1600. // Shift PATH_INFO block one character right, e.g.
  1601. // "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  1602. // conn->path_info is pointing to the local variable "path" declared
  1603. // in handle_request(), so PATH_INFO is not valid after
  1604. // handle_request returns.
  1605. conn->path_info = p + 1;
  1606. memmove(p + 2, p + 1, strlen(p + 1) + 1); // +1 is for trailing \0
  1607. p[1] = '/';
  1608. break;
  1609. } else {
  1610. *p = '/';
  1611. }
  1612. }
  1613. }
  1614. }
  1615. // Check whether full request is buffered. Return:
  1616. // -1 if request is malformed
  1617. // 0 if request is not yet fully buffered
  1618. // >0 actual request length, including last \r\n\r\n
  1619. static int get_request_len(const char *buf, int buflen) {
  1620. const char *s, *e;
  1621. int len = 0;
  1622. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  1623. // Control characters are not allowed but >=128 is.
  1624. if (!isprint(* (const unsigned char *) s) && *s != '\r' &&
  1625. *s != '\n' && * (const unsigned char *) s < 128) {
  1626. len = -1;
  1627. break; // [i_a] abort scan as soon as one malformed character is found;
  1628. // don't let subsequent \r\n\r\n win us over anyhow
  1629. } else if (s[0] == '\n' && s[1] == '\n') {
  1630. len = (int) (s - buf) + 2;
  1631. } else if (s[0] == '\n' && &s[1] < e &&
  1632. s[1] == '\r' && s[2] == '\n') {
  1633. len = (int) (s - buf) + 3;
  1634. }
  1635. return len;
  1636. }
  1637. // Convert month to the month number. Return -1 on error, or month number
  1638. static int get_month_index(const char *s) {
  1639. size_t i;
  1640. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  1641. if (!strcmp(s, month_names[i]))
  1642. return (int) i;
  1643. return -1;
  1644. }
  1645. static int num_leap_years(int year) {
  1646. return year / 4 - year / 100 + year / 400;
  1647. }
  1648. // Parse UTC date-time string, and return the corresponding time_t value.
  1649. static time_t parse_date_string(const char *datetime) {
  1650. static const unsigned short days_before_month[] = {
  1651. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  1652. };
  1653. char month_str[32];
  1654. int second, minute, hour, day, month, year, leap_days, days;
  1655. time_t result = (time_t) 0;
  1656. if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
  1657. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1658. (sscanf(datetime, "%d %3s %d %d:%d:%d",
  1659. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1660. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
  1661. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1662. (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
  1663. &day, month_str, &year, &hour, &minute, &second) == 6)) &&
  1664. year > 1970 &&
  1665. (month = get_month_index(month_str)) != -1) {
  1666. leap_days = num_leap_years(year) - num_leap_years(1970);
  1667. year -= 1970;
  1668. days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
  1669. result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
  1670. }
  1671. return result;
  1672. }
  1673. // Protect against directory disclosure attack by removing '..',
  1674. // excessive '/' and '\' characters
  1675. static void remove_double_dots_and_double_slashes(char *s) {
  1676. char *p = s;
  1677. while (*s != '\0') {
  1678. *p++ = *s++;
  1679. if (s[-1] == '/' || s[-1] == '\\') {
  1680. // Skip all following slashes, backslashes and double-dots
  1681. while (s[0] != '\0') {
  1682. if (s[0] == '/' || s[0] == '\\') {
  1683. s++;
  1684. } else if (s[0] == '.' && s[1] == '.') {
  1685. s += 2;
  1686. } else {
  1687. break;
  1688. }
  1689. }
  1690. }
  1691. }
  1692. *p = '\0';
  1693. }
  1694. static const struct {
  1695. const char *extension;
  1696. size_t ext_len;
  1697. const char *mime_type;
  1698. } builtin_mime_types[] = {
  1699. {".html", 5, "text/html"},
  1700. {".htm", 4, "text/html"},
  1701. {".shtm", 5, "text/html"},
  1702. {".shtml", 6, "text/html"},
  1703. {".css", 4, "text/css"},
  1704. {".js", 3, "application/x-javascript"},
  1705. {".ico", 4, "image/x-icon"},
  1706. {".gif", 4, "image/gif"},
  1707. {".jpg", 4, "image/jpeg"},
  1708. {".jpeg", 5, "image/jpeg"},
  1709. {".png", 4, "image/png"},
  1710. {".svg", 4, "image/svg+xml"},
  1711. {".txt", 4, "text/plain"},
  1712. {".torrent", 8, "application/x-bittorrent"},
  1713. {".wav", 4, "audio/x-wav"},
  1714. {".mp3", 4, "audio/x-mp3"},
  1715. {".mid", 4, "audio/mid"},
  1716. {".m3u", 4, "audio/x-mpegurl"},
  1717. {".ogg", 4, "audio/ogg"},
  1718. {".ram", 4, "audio/x-pn-realaudio"},
  1719. {".xml", 4, "text/xml"},
  1720. {".json", 5, "text/json"},
  1721. {".xslt", 5, "application/xml"},
  1722. {".xsl", 4, "application/xml"},
  1723. {".ra", 3, "audio/x-pn-realaudio"},
  1724. {".doc", 4, "application/msword"},
  1725. {".exe", 4, "application/octet-stream"},
  1726. {".zip", 4, "application/x-zip-compressed"},
  1727. {".xls", 4, "application/excel"},
  1728. {".tgz", 4, "application/x-tar-gz"},
  1729. {".tar", 4, "application/x-tar"},
  1730. {".gz", 3, "application/x-gunzip"},
  1731. {".arj", 4, "application/x-arj-compressed"},
  1732. {".rar", 4, "application/x-arj-compressed"},
  1733. {".rtf", 4, "application/rtf"},
  1734. {".pdf", 4, "application/pdf"},
  1735. {".swf", 4, "application/x-shockwave-flash"},
  1736. {".mpg", 4, "video/mpeg"},
  1737. {".webm", 5, "video/webm"},
  1738. {".mpeg", 5, "video/mpeg"},
  1739. {".mov", 4, "video/quicktime"},
  1740. {".mp4", 4, "video/mp4"},
  1741. {".m4v", 4, "video/x-m4v"},
  1742. {".asf", 4, "video/x-ms-asf"},
  1743. {".avi", 4, "video/x-msvideo"},
  1744. {".bmp", 4, "image/bmp"},
  1745. {".ttf", 4, "application/x-font-ttf"},
  1746. {NULL, 0, NULL}
  1747. };
  1748. const char *mg_get_builtin_mime_type(const char *path) {
  1749. const char *ext;
  1750. size_t i, path_len;
  1751. path_len = strlen(path);
  1752. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  1753. ext = path + (path_len - builtin_mime_types[i].ext_len);
  1754. if (path_len > builtin_mime_types[i].ext_len &&
  1755. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  1756. return builtin_mime_types[i].mime_type;
  1757. }
  1758. }
  1759. return "text/plain";
  1760. }
  1761. // Look at the "path" extension and figure what mime type it has.
  1762. // Store mime type in the vector.
  1763. static void get_mime_type(struct mg_context *ctx, const char *path,
  1764. struct vec *vec) {
  1765. struct vec ext_vec, mime_vec;
  1766. const char *list, *ext;
  1767. size_t path_len;
  1768. path_len = strlen(path);
  1769. // Scan user-defined mime types first, in case user wants to
  1770. // override default mime types.
  1771. list = ctx->config[EXTRA_MIME_TYPES];
  1772. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  1773. // ext now points to the path suffix
  1774. ext = path + path_len - ext_vec.len;
  1775. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  1776. *vec = mime_vec;
  1777. return;
  1778. }
  1779. }
  1780. vec->ptr = mg_get_builtin_mime_type(path);
  1781. vec->len = strlen(vec->ptr);
  1782. }
  1783. // Stringify binary data. Output buffer must be twice as big as input,
  1784. // because each byte takes 2 bytes in string representation
  1785. static void bin2str(char *to, const unsigned char *p, size_t len) {
  1786. static const char *hex = "0123456789abcdef";
  1787. for (; len--; p++) {
  1788. *to++ = hex[p[0] >> 4];
  1789. *to++ = hex[p[0] & 0x0f];
  1790. }
  1791. *to = '\0';
  1792. }
  1793. // Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  1794. char *mg_md5(char buf[33], ...) {
  1795. md5_byte_t hash[16];
  1796. const char *p;
  1797. va_list ap;
  1798. md5_state_t ctx;
  1799. md5_init(&ctx);
  1800. va_start(ap, buf);
  1801. while ((p = va_arg(ap, const char *)) != NULL) {
  1802. md5_append(&ctx, (const md5_byte_t *) p, (int) strlen(p));
  1803. }
  1804. va_end(ap);
  1805. md5_finish(&ctx, hash);
  1806. bin2str(buf, hash, sizeof(hash));
  1807. return buf;
  1808. }
  1809. // Check the user's password, return 1 if OK
  1810. static int check_password(const char *method, const char *ha1, const char *uri,
  1811. const char *nonce, const char *nc, const char *cnonce,
  1812. const char *qop, const char *response) {
  1813. char ha2[32 + 1], expected_response[32 + 1];
  1814. // Some of the parameters may be NULL
  1815. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
  1816. qop == NULL || response == NULL) {
  1817. return 0;
  1818. }
  1819. // NOTE(lsm): due to a bug in MSIE, we do not compare the URI
  1820. // TODO(lsm): check for authentication timeout
  1821. if (// strcmp(dig->uri, c->ouri) != 0 ||
  1822. strlen(response) != 32
  1823. // || now - strtoul(dig->nonce, NULL, 10) > 3600
  1824. ) {
  1825. return 0;
  1826. }
  1827. mg_md5(ha2, method, ":", uri, NULL);
  1828. mg_md5(expected_response, ha1, ":", nonce, ":", nc,
  1829. ":", cnonce, ":", qop, ":", ha2, NULL);
  1830. return mg_strcasecmp(response, expected_response) == 0;
  1831. }
  1832. // Use the global passwords file, if specified by auth_gpass option,
  1833. // or search for .htpasswd in the requested directory.
  1834. static void open_auth_file(struct mg_connection *conn, const char *path,
  1835. struct file *filep) {
  1836. char name[PATH_MAX];
  1837. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  1838. struct file file = STRUCT_FILE_INITIALIZER;
  1839. if (gpass != NULL) {
  1840. // Use global passwords file
  1841. if (!mg_fopen(conn, gpass, "r", filep)) {
  1842. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  1843. }
  1844. // Important: using local struct file to test path for is_directory flag.
  1845. // If filep is used, mg_stat() makes it appear as if auth file was opened.
  1846. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  1847. mg_snprintf(conn, name, sizeof(name), "%s%c%s",
  1848. path, '/', PASSWORDS_FILE_NAME);
  1849. mg_fopen(conn, name, "r", filep);
  1850. } else {
  1851. // Try to find .htpasswd in requested directory.
  1852. for (p = path, e = p + strlen(p) - 1; e > p; e--)
  1853. if (e[0] == '/')
  1854. break;
  1855. mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
  1856. (int) (e - p), p, '/', PASSWORDS_FILE_NAME);
  1857. mg_fopen(conn, name, "r", filep);
  1858. }
  1859. }
  1860. // Parsed Authorization header
  1861. struct ah {
  1862. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  1863. };
  1864. // Return 1 on success. Always initializes the ah structure.
  1865. static int parse_auth_header(struct mg_connection *conn, char *buf,
  1866. size_t buf_size, struct ah *ah) {
  1867. char *name, *value, *s;
  1868. const char *auth_header;
  1869. (void) memset(ah, 0, sizeof(*ah));
  1870. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  1871. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  1872. return 0;
  1873. }
  1874. // Make modifiable copy of the auth header
  1875. (void) mg_strlcpy(buf, auth_header + 7, buf_size);
  1876. s = buf;
  1877. // Parse authorization header
  1878. for (;;) {
  1879. // Gobble initial spaces
  1880. while (isspace(* (unsigned char *) s)) {
  1881. s++;
  1882. }
  1883. name = skip_quoted(&s, "=", " ", 0);
  1884. // Value is either quote-delimited, or ends at first comma or space.
  1885. if (s[0] == '\"') {
  1886. s++;
  1887. value = skip_quoted(&s, "\"", " ", '\\');
  1888. if (s[0] == ',') {
  1889. s++;
  1890. }
  1891. } else {
  1892. value = skip_quoted(&s, ", ", " ", 0); // IE uses commas, FF uses spaces
  1893. }
  1894. if (*name == '\0') {
  1895. break;
  1896. }
  1897. if (!strcmp(name, "username")) {
  1898. ah->user = value;
  1899. } else if (!strcmp(name, "cnonce")) {
  1900. ah->cnonce = value;
  1901. } else if (!strcmp(name, "response")) {
  1902. ah->response = value;
  1903. } else if (!strcmp(name, "uri")) {
  1904. ah->uri = value;
  1905. } else if (!strcmp(name, "qop")) {
  1906. ah->qop = value;
  1907. } else if (!strcmp(name, "nc")) {
  1908. ah->nc = value;
  1909. } else if (!strcmp(name, "nonce")) {
  1910. ah->nonce = value;
  1911. }
  1912. }
  1913. // CGI needs it as REMOTE_USER
  1914. if (ah->user != NULL) {
  1915. conn->request_info.remote_user = mg_strdup(ah->user);
  1916. } else {
  1917. return 0;
  1918. }
  1919. return 1;
  1920. }
  1921. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p) {
  1922. char *eof;
  1923. size_t len;
  1924. char *memend;
  1925. if (filep->membuf != NULL && *p != NULL) {
  1926. memend = (char *) &filep->membuf[filep->size];
  1927. eof = (char *) memchr(*p, '\n', memend - *p); // Search for \n from p till the end of stream
  1928. if (eof != NULL) {
  1929. eof += 1; // Include \n
  1930. } else {
  1931. eof = memend; // Copy remaining data
  1932. }
  1933. len = (size_t) (eof - *p) > size - 1 ? size - 1 : (size_t) (eof - *p);
  1934. memcpy(buf, *p, len);
  1935. buf[len] = '\0';
  1936. *p += len;
  1937. return len ? eof : NULL;
  1938. } else if (filep->fp != NULL) {
  1939. return fgets(buf, (int)size, filep->fp);
  1940. } else {
  1941. return NULL;
  1942. }
  1943. }
  1944. // Authorize against the opened passwords file. Return 1 if authorized.
  1945. static int authorize(struct mg_connection *conn, struct file *filep) {
  1946. struct ah ah;
  1947. char line[256], f_user[256] = "", ha1[256] = "", f_domain[256] = "", buf[MG_BUF_LEN], *p;
  1948. if (!parse_auth_header(conn, buf, sizeof(buf), &ah)) {
  1949. return 0;
  1950. }
  1951. // Loop over passwords file
  1952. p = (char *) filep->membuf;
  1953. while (mg_fgets(line, sizeof(line), filep, &p) != NULL) {
  1954. if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {
  1955. continue;
  1956. }
  1957. if (!strcmp(ah.user, f_user) &&
  1958. !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain))
  1959. return check_password(conn->request_info.request_method, ha1, ah.uri,
  1960. ah.nonce, ah.nc, ah.cnonce, ah.qop, ah.response);
  1961. }
  1962. return 0;
  1963. }
  1964. // Return 1 if request is authorised, 0 otherwise.
  1965. static int check_authorization(struct mg_connection *conn, const char *path) {
  1966. char fname[PATH_MAX];
  1967. struct vec uri_vec, filename_vec;
  1968. const char *list;
  1969. struct file file = STRUCT_FILE_INITIALIZER;
  1970. int authorized = 1;
  1971. list = conn->ctx->config[PROTECT_URI];
  1972. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  1973. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  1974. mg_snprintf(conn, fname, sizeof(fname), "%.*s",
  1975. (int) filename_vec.len, filename_vec.ptr);
  1976. if (!mg_fopen(conn, fname, "r", &file)) {
  1977. mg_cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));
  1978. }
  1979. break;
  1980. }
  1981. }
  1982. if (!is_file_opened(&file)) {
  1983. open_auth_file(conn, path, &file);
  1984. }
  1985. if (is_file_opened(&file)) {
  1986. authorized = authorize(conn, &file);
  1987. mg_fclose(&file);
  1988. }
  1989. return authorized;
  1990. }
  1991. static void send_authorization_request(struct mg_connection *conn) {
  1992. conn->status_code = 401;
  1993. mg_printf(conn,
  1994. "HTTP/1.1 401 Unauthorized\r\n"
  1995. "Content-Length: 0\r\n"
  1996. "WWW-Authenticate: Digest qop=\"auth\", "
  1997. "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
  1998. conn->ctx->config[AUTHENTICATION_DOMAIN],
  1999. (unsigned long) time(NULL));
  2000. }
  2001. static int is_authorized_for_put(struct mg_connection *conn) {
  2002. struct file file = STRUCT_FILE_INITIALIZER;
  2003. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  2004. int ret = 0;
  2005. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  2006. ret = authorize(conn, &file);
  2007. mg_fclose(&file);
  2008. }
  2009. return ret;
  2010. }
  2011. int mg_modify_passwords_file(const char *fname, const char *domain,
  2012. const char *user, const char *pass) {
  2013. int found;
  2014. char line[512], u[512] = "", d[512] ="", ha1[33], tmp[PATH_MAX+1];
  2015. FILE *fp, *fp2;
  2016. found = 0;
  2017. fp = fp2 = NULL;
  2018. // Regard empty password as no password - remove user record.
  2019. if (pass != NULL && pass[0] == '\0') {
  2020. pass = NULL;
  2021. }
  2022. (void) snprintf(tmp, sizeof(tmp) - 1, "%s.tmp", fname);
  2023. tmp[sizeof(tmp) - 1] = 0;
  2024. // Create the file if does not exist
  2025. if ((fp = fopen(fname, "a+")) != NULL) {
  2026. (void) fclose(fp);
  2027. }
  2028. // Open the given file and temporary file
  2029. if ((fp = fopen(fname, "r")) == NULL) {
  2030. return 0;
  2031. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  2032. fclose(fp);
  2033. return 0;
  2034. }
  2035. // Copy the stuff to temporary file
  2036. while (fgets(line, sizeof(line), fp) != NULL) {
  2037. if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
  2038. continue;
  2039. }
  2040. if (!strcmp(u, user) && !strcmp(d, domain)) {
  2041. found++;
  2042. if (pass != NULL) {
  2043. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2044. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2045. }
  2046. } else {
  2047. fprintf(fp2, "%s", line);
  2048. }
  2049. }
  2050. // If new user, just add it
  2051. if (!found && pass != NULL) {
  2052. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2053. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2054. }
  2055. // Close files
  2056. fclose(fp);
  2057. fclose(fp2);
  2058. // Put the temp file in place of real file
  2059. remove(fname);
  2060. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  2061. return 1;
  2062. }
  2063. static SOCKET conn2(const char *host, int port, int use_ssl,
  2064. char *ebuf, size_t ebuf_len) {
  2065. struct sockaddr_in sin;
  2066. struct hostent *he;
  2067. SOCKET sock = INVALID_SOCKET;
  2068. if (host == NULL) {
  2069. snprintf(ebuf, ebuf_len, "%s", "NULL host");
  2070. } else if (use_ssl && SSLv23_client_method == NULL) {
  2071. snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");
  2072. // TODO(lsm): use something threadsafe instead of gethostbyname()
  2073. } else if ((he = gethostbyname(host)) == NULL) {
  2074. snprintf(ebuf, ebuf_len, "gethostbyname(%s): %s", host, strerror(ERRNO));
  2075. } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
  2076. snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));
  2077. } else {
  2078. set_close_on_exec(sock);
  2079. sin.sin_family = AF_INET;
  2080. sin.sin_port = htons((uint16_t) port);
  2081. sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
  2082. if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
  2083. snprintf(ebuf, ebuf_len, "connect(%s:%d): %s",
  2084. host, port, strerror(ERRNO));
  2085. closesocket(sock);
  2086. sock = INVALID_SOCKET;
  2087. }
  2088. }
  2089. return sock;
  2090. }
  2091. int mg_url_encode(const char *src, char *dst, size_t dst_len) {
  2092. static const char *dont_escape = "._-$,;~()";
  2093. static const char *hex = "0123456789abcdef";
  2094. char *pos = dst;
  2095. const char *end = dst + dst_len - 1;
  2096. for (; *src != '\0' && pos < end; src++, pos++) {
  2097. if (isalnum(*(const unsigned char *) src) ||
  2098. strchr(dont_escape, * (const unsigned char *) src) != NULL) {
  2099. *pos = *src;
  2100. } else if (pos + 2 < end) {
  2101. pos[0] = '%';
  2102. pos[1] = hex[(* (const unsigned char *) src) >> 4];
  2103. pos[2] = hex[(* (const unsigned char *) src) & 0xf];
  2104. pos += 2;
  2105. } else {
  2106. return -1;
  2107. }
  2108. }
  2109. *pos = '\0';
  2110. return (*src == '\0') ? (int)(pos - dst) : -1;
  2111. }
  2112. static void print_dir_entry(struct de *de) {
  2113. char size[64], mod[64], href[PATH_MAX];
  2114. if (de->file.is_directory) {
  2115. mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
  2116. } else {
  2117. // We use (signed) cast below because MSVC 6 compiler cannot
  2118. // convert unsigned __int64 to double. Sigh.
  2119. if (de->file.size < 1024) {
  2120. mg_snprintf(de->conn, size, sizeof(size), "%d", (int) de->file.size);
  2121. } else if (de->file.size < 0x100000) {
  2122. mg_snprintf(de->conn, size, sizeof(size),
  2123. "%.1fk", (double) de->file.size / 1024.0);
  2124. } else if (de->file.size < 0x40000000) {
  2125. mg_snprintf(de->conn, size, sizeof(size),
  2126. "%.1fM", (double) de->file.size / 1048576);
  2127. } else {
  2128. mg_snprintf(de->conn, size, sizeof(size),
  2129. "%.1fG", (double) de->file.size / 1073741824);
  2130. }
  2131. }
  2132. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M",
  2133. localtime(&de->file.modification_time));
  2134. mg_url_encode(de->file_name, href, sizeof(href));
  2135. de->conn->num_bytes_sent += mg_printf(de->conn,
  2136. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  2137. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2138. de->conn->request_info.uri, href, de->file.is_directory ? "/" : "",
  2139. de->file_name, de->file.is_directory ? "/" : "", mod, size);
  2140. }
  2141. // This function is called from send_directory() and used for
  2142. // sorting directory entries by size, or name, or modification time.
  2143. // On windows, __cdecl specification is needed in case if project is built
  2144. // with __stdcall convention. qsort always requires __cdels callback.
  2145. static int WINCDECL compare_dir_entries(const void *p1, const void *p2) {
  2146. const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;
  2147. const char *query_string = a->conn->request_info.query_string;
  2148. int cmp_result = 0;
  2149. if (query_string == NULL) {
  2150. query_string = "na";
  2151. }
  2152. if (a->file.is_directory && !b->file.is_directory) {
  2153. return -1; // Always put directories on top
  2154. } else if (!a->file.is_directory && b->file.is_directory) {
  2155. return 1; // Always put directories on top
  2156. } else if (*query_string == 'n') {
  2157. cmp_result = strcmp(a->file_name, b->file_name);
  2158. } else if (*query_string == 's') {
  2159. cmp_result = a->file.size == b->file.size ? 0 :
  2160. a->file.size > b->file.size ? 1 : -1;
  2161. } else if (*query_string == 'd') {
  2162. cmp_result = a->file.modification_time == b->file.modification_time ? 0 :
  2163. a->file.modification_time > b->file.modification_time ? 1 : -1;
  2164. }
  2165. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  2166. }
  2167. static int must_hide_file(struct mg_connection *conn, const char *path) {
  2168. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  2169. const char *pattern = conn->ctx->config[HIDE_FILES];
  2170. return match_prefix(pw_pattern, (int)strlen(pw_pattern), path) > 0 ||
  2171. (pattern != NULL && match_prefix(pattern, (int)strlen(pattern), path) > 0);
  2172. }
  2173. static int scan_directory(struct mg_connection *conn, const char *dir,
  2174. void *data, void (*cb)(struct de *, void *)) {
  2175. char path[PATH_MAX];
  2176. struct dirent *dp;
  2177. DIR *dirp;
  2178. struct de de;
  2179. if ((dirp = opendir(dir)) == NULL) {
  2180. return 0;
  2181. } else {
  2182. de.conn = conn;
  2183. while ((dp = readdir(dirp)) != NULL) {
  2184. // Do not show current dir and hidden files
  2185. if (!strcmp(dp->d_name, ".") ||
  2186. !strcmp(dp->d_name, "..") ||
  2187. must_hide_file(conn, dp->d_name)) {
  2188. continue;
  2189. }
  2190. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  2191. // If we don't memset stat structure to zero, mtime will have
  2192. // garbage and strftime() will segfault later on in
  2193. // print_dir_entry(). memset is required only if mg_stat()
  2194. // fails. For more details, see
  2195. // http://code.google.com/p/civetweb/issues/detail?id=79
  2196. memset(&de.file, 0, sizeof(de.file));
  2197. mg_stat(conn, path, &de.file);
  2198. de.file_name = dp->d_name;
  2199. cb(&de, data);
  2200. }
  2201. (void) closedir(dirp);
  2202. }
  2203. return 1;
  2204. }
  2205. static int remove_directory(struct mg_connection *conn, const char *dir) {
  2206. char path[PATH_MAX];
  2207. struct dirent *dp;
  2208. DIR *dirp;
  2209. struct de de;
  2210. if ((dirp = opendir(dir)) == NULL) {
  2211. return 0;
  2212. } else {
  2213. de.conn = conn;
  2214. while ((dp = readdir(dirp)) != NULL) {
  2215. // Do not show current dir (but show hidden files as they will also be removed)
  2216. if (!strcmp(dp->d_name, ".") ||
  2217. !strcmp(dp->d_name, "..")) {
  2218. continue;
  2219. }
  2220. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  2221. // If we don't memset stat structure to zero, mtime will have
  2222. // garbage and strftime() will segfault later on in
  2223. // print_dir_entry(). memset is required only if mg_stat()
  2224. // fails. For more details, see
  2225. // http://code.google.com/p/civetweb/issues/detail?id=79
  2226. memset(&de.file, 0, sizeof(de.file));
  2227. mg_stat(conn, path, &de.file);
  2228. if(de.file.modification_time) {
  2229. if(de.file.is_directory) {
  2230. remove_directory(conn, path);
  2231. } else {
  2232. mg_remove(path);
  2233. }
  2234. }
  2235. }
  2236. (void) closedir(dirp);
  2237. IGNORE_UNUSED_RESULT(rmdir(dir));
  2238. }
  2239. return 1;
  2240. }
  2241. struct dir_scan_data {
  2242. struct de *entries;
  2243. int num_entries;
  2244. int arr_size;
  2245. };
  2246. // Behaves like realloc(), but frees original pointer on failure
  2247. static void *realloc2(void *ptr, size_t size) {
  2248. void *new_ptr = realloc(ptr, size);
  2249. if (new_ptr == NULL) {
  2250. free(ptr);
  2251. }
  2252. return new_ptr;
  2253. }
  2254. static void dir_scan_callback(struct de *de, void *data) {
  2255. struct dir_scan_data *dsd = (struct dir_scan_data *) data;
  2256. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  2257. dsd->arr_size *= 2;
  2258. dsd->entries = (struct de *) realloc2(dsd->entries, dsd->arr_size *
  2259. sizeof(dsd->entries[0]));
  2260. }
  2261. if (dsd->entries == NULL) {
  2262. // TODO(lsm): propagate an error to the caller
  2263. dsd->num_entries = 0;
  2264. } else {
  2265. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  2266. dsd->entries[dsd->num_entries].file = de->file;
  2267. dsd->entries[dsd->num_entries].conn = de->conn;
  2268. dsd->num_entries++;
  2269. }
  2270. }
  2271. static void handle_directory_request(struct mg_connection *conn,
  2272. const char *dir) {
  2273. int i, sort_direction;
  2274. struct dir_scan_data data = { NULL, 0, 128 };
  2275. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  2276. send_http_error(conn, 500, "Cannot open directory",
  2277. "Error: opendir(%s): %s", dir, strerror(ERRNO));
  2278. return;
  2279. }
  2280. sort_direction = conn->request_info.query_string != NULL &&
  2281. conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
  2282. conn->must_close = 1;
  2283. mg_printf(conn, "%s",
  2284. "HTTP/1.1 200 OK\r\n"
  2285. "Connection: close\r\n"
  2286. "Content-Type: text/html; charset=utf-8\r\n\r\n");
  2287. conn->num_bytes_sent += mg_printf(conn,
  2288. "<html><head><title>Index of %s</title>"
  2289. "<style>th {text-align: left;}</style></head>"
  2290. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  2291. "<tr><th><a href=\"?n%c\">Name</a></th>"
  2292. "<th><a href=\"?d%c\">Modified</a></th>"
  2293. "<th><a href=\"?s%c\">Size</a></th></tr>"
  2294. "<tr><td colspan=\"3\"><hr></td></tr>",
  2295. conn->request_info.uri, conn->request_info.uri,
  2296. sort_direction, sort_direction, sort_direction);
  2297. // Print first entry - link to a parent directory
  2298. conn->num_bytes_sent += mg_printf(conn,
  2299. "<tr><td><a href=\"%s%s\">%s</a></td>"
  2300. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2301. conn->request_info.uri, "..", "Parent directory", "-", "-");
  2302. // Sort and print directory entries
  2303. qsort(data.entries, (size_t) data.num_entries, sizeof(data.entries[0]),
  2304. compare_dir_entries);
  2305. for (i = 0; i < data.num_entries; i++) {
  2306. print_dir_entry(&data.entries[i]);
  2307. free(data.entries[i].file_name);
  2308. }
  2309. free(data.entries);
  2310. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  2311. conn->status_code = 200;
  2312. }
  2313. // Send len bytes from the opened file to the client.
  2314. static void send_file_data(struct mg_connection *conn, struct file *filep,
  2315. int64_t offset, int64_t len) {
  2316. char buf[MG_BUF_LEN];
  2317. int to_read, num_read, num_written;
  2318. // Sanity check the offset
  2319. offset = offset < 0 ? 0 : offset > filep->size ? filep->size : offset;
  2320. if (len > 0 && filep->membuf != NULL && filep->size > 0) {
  2321. if (len > filep->size - offset) {
  2322. len = filep->size - offset;
  2323. }
  2324. mg_write(conn, filep->membuf + offset, (size_t) len);
  2325. } else if (len > 0 && filep->fp != NULL) {
  2326. fseeko(filep->fp, offset, SEEK_SET);
  2327. while (len > 0) {
  2328. // Calculate how much to read from the file in the buffer
  2329. to_read = sizeof(buf);
  2330. if ((int64_t) to_read > len) {
  2331. to_read = (int) len;
  2332. }
  2333. // Read from file, exit the loop on error
  2334. if ((num_read = (int) fread(buf, 1, (size_t) to_read, filep->fp)) <= 0) {
  2335. break;
  2336. }
  2337. // Send read bytes to the client, exit the loop on error
  2338. if ((num_written = mg_write(conn, buf, (size_t) num_read)) != num_read) {
  2339. break;
  2340. }
  2341. // Both read and were successful, adjust counters
  2342. conn->num_bytes_sent += num_written;
  2343. len -= num_written;
  2344. }
  2345. }
  2346. }
  2347. static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
  2348. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  2349. }
  2350. static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  2351. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
  2352. }
  2353. static void construct_etag(char *buf, size_t buf_len,
  2354. const struct file *filep) {
  2355. snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
  2356. (unsigned long) filep->modification_time, filep->size);
  2357. }
  2358. static void fclose_on_exec(struct file *filep) {
  2359. if (filep != NULL && filep->fp != NULL) {
  2360. #ifndef _WIN32
  2361. fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC);
  2362. #endif
  2363. }
  2364. }
  2365. static void handle_file_request(struct mg_connection *conn, const char *path,
  2366. struct file *filep) {
  2367. char date[64], lm[64], etag[64], range[64];
  2368. const char *msg = "OK", *hdr;
  2369. time_t curtime = time(NULL);
  2370. int64_t cl, r1, r2;
  2371. struct vec mime_vec;
  2372. int n;
  2373. char gz_path[PATH_MAX];
  2374. char const* encoding = "";
  2375. get_mime_type(conn->ctx, path, &mime_vec);
  2376. cl = filep->size;
  2377. conn->status_code = 200;
  2378. range[0] = '\0';
  2379. // if this file is in fact a pre-gzipped file, rewrite its filename
  2380. // it's important to rewrite the filename after resolving
  2381. // the mime type from it, to preserve the actual file's type
  2382. if (filep->gzipped) {
  2383. snprintf(gz_path, sizeof(gz_path), "%s.gz", path);
  2384. path = gz_path;
  2385. encoding = "Content-Encoding: gzip\r\n";
  2386. }
  2387. if (!mg_fopen(conn, path, "rb", filep)) {
  2388. send_http_error(conn, 500, http_500_error,
  2389. "fopen(%s): %s", path, strerror(ERRNO));
  2390. return;
  2391. }
  2392. fclose_on_exec(filep);
  2393. // If Range: header specified, act accordingly
  2394. r1 = r2 = 0;
  2395. hdr = mg_get_header(conn, "Range");
  2396. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
  2397. r1 >= 0 && r2 >= 0) {
  2398. // actually, range requests don't play well with a pre-gzipped
  2399. // file (since the range is specified in the uncmpressed space)
  2400. if (filep->gzipped) {
  2401. send_http_error(conn, 501, "Not Implemented", "range requests in gzipped files are not supported");
  2402. return;
  2403. }
  2404. conn->status_code = 206;
  2405. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1: cl - r1;
  2406. mg_snprintf(conn, range, sizeof(range),
  2407. "Content-Range: bytes "
  2408. "%" INT64_FMT "-%"
  2409. INT64_FMT "/%" INT64_FMT "\r\n",
  2410. r1, r1 + cl - 1, filep->size);
  2411. msg = "Partial Content";
  2412. }
  2413. // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  2414. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
  2415. gmt_time_string(date, sizeof(date), &curtime);
  2416. gmt_time_string(lm, sizeof(lm), &filep->modification_time);
  2417. construct_etag(etag, sizeof(etag), filep);
  2418. (void) mg_printf(conn,
  2419. "HTTP/1.1 %d %s\r\n"
  2420. "Date: %s\r\n"
  2421. "Last-Modified: %s\r\n"
  2422. "Etag: %s\r\n"
  2423. "Content-Type: %.*s\r\n"
  2424. "Content-Length: %" INT64_FMT "\r\n"
  2425. "Connection: %s\r\n"
  2426. "Accept-Ranges: bytes\r\n"
  2427. "%s%s\r\n",
  2428. conn->status_code, msg, date, lm, etag, (int) mime_vec.len,
  2429. mime_vec.ptr, cl, suggest_connection_header(conn), range, encoding);
  2430. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  2431. send_file_data(conn, filep, r1, cl);
  2432. }
  2433. mg_fclose(filep);
  2434. }
  2435. void mg_send_file(struct mg_connection *conn, const char *path) {
  2436. struct file file = STRUCT_FILE_INITIALIZER;
  2437. if (mg_stat(conn, path, &file)) {
  2438. handle_file_request(conn, path, &file);
  2439. } else {
  2440. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  2441. }
  2442. }
  2443. // Parse HTTP headers from the given buffer, advance buffer to the point
  2444. // where parsing stopped.
  2445. static void parse_http_headers(char **buf, struct mg_request_info *ri) {
  2446. int i;
  2447. for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
  2448. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  2449. ri->http_headers[i].value = skip(buf, "\r\n");
  2450. if (ri->http_headers[i].name[0] == '\0')
  2451. break;
  2452. ri->num_headers = i + 1;
  2453. }
  2454. }
  2455. static int is_valid_http_method(const char *method) {
  2456. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  2457. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  2458. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  2459. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND")
  2460. || !strcmp(method, "MKCOL")
  2461. ;
  2462. }
  2463. // Parse HTTP request, fill in mg_request_info structure.
  2464. // This function modifies the buffer by NUL-terminating
  2465. // HTTP request components, header names and header values.
  2466. static int parse_http_message(char *buf, int len, struct mg_request_info *ri) {
  2467. int is_request, request_length = get_request_len(buf, len);
  2468. if (request_length > 0) {
  2469. // Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port
  2470. ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
  2471. ri->num_headers = 0;
  2472. buf[request_length - 1] = '\0';
  2473. // RFC says that all initial whitespaces should be ingored
  2474. while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
  2475. buf++;
  2476. }
  2477. ri->request_method = skip(&buf, " ");
  2478. ri->uri = skip(&buf, " ");
  2479. ri->http_version = skip(&buf, "\r\n");
  2480. // HTTP message could be either HTTP request or HTTP response, e.g.
  2481. // "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..."
  2482. is_request = is_valid_http_method(ri->request_method);
  2483. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
  2484. (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  2485. request_length = -1;
  2486. } else {
  2487. if (is_request) {
  2488. ri->http_version += 5;
  2489. }
  2490. parse_http_headers(&buf, ri);
  2491. }
  2492. }
  2493. return request_length;
  2494. }
  2495. // Keep reading the input (either opened file descriptor fd, or socket sock,
  2496. // or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  2497. // buffer (which marks the end of HTTP request). Buffer buf may already
  2498. // have some data. The length of the data is stored in nread.
  2499. // Upon every read operation, increase nread by the number of bytes read.
  2500. static int read_request(FILE *fp, struct mg_connection *conn,
  2501. char *buf, int bufsiz, int *nread) {
  2502. int request_len, n = 0;
  2503. request_len = get_request_len(buf, *nread);
  2504. while (conn->ctx->stop_flag == 0 &&
  2505. *nread < bufsiz && request_len == 0 &&
  2506. (n = pull(fp, conn, buf + *nread, bufsiz - *nread)) > 0) {
  2507. *nread += n;
  2508. assert(*nread <= bufsiz);
  2509. request_len = get_request_len(buf, *nread);
  2510. }
  2511. return request_len <= 0 && n <= 0 ? -1 : request_len;
  2512. }
  2513. // For given directory path, substitute it to valid index file.
  2514. // Return 0 if index file has been found, -1 if not found.
  2515. // If the file is found, it's stats is returned in stp.
  2516. static int substitute_index_file(struct mg_connection *conn, char *path,
  2517. size_t path_len, struct file *filep) {
  2518. const char *list = conn->ctx->config[INDEX_FILES];
  2519. struct file file = STRUCT_FILE_INITIALIZER;
  2520. struct vec filename_vec;
  2521. size_t n = strlen(path);
  2522. int found = 0;
  2523. // The 'path' given to us points to the directory. Remove all trailing
  2524. // directory separator characters from the end of the path, and
  2525. // then append single directory separator character.
  2526. while (n > 0 && path[n - 1] == '/') {
  2527. n--;
  2528. }
  2529. path[n] = '/';
  2530. // Traverse index files list. For each entry, append it to the given
  2531. // path and see if the file exists. If it exists, break the loop
  2532. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  2533. // Ignore too long entries that may overflow path buffer
  2534. if (filename_vec.len > path_len - (n + 2))
  2535. continue;
  2536. // Prepare full path to the index file
  2537. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  2538. // Does it exist?
  2539. if (mg_stat(conn, path, &file)) {
  2540. // Yes it does, break the loop
  2541. *filep = file;
  2542. found = 1;
  2543. break;
  2544. }
  2545. }
  2546. // If no index file exists, restore directory path
  2547. if (!found) {
  2548. path[n] = '\0';
  2549. }
  2550. return found;
  2551. }
  2552. // Return True if we should reply 304 Not Modified.
  2553. static int is_not_modified(const struct mg_connection *conn,
  2554. const struct file *filep) {
  2555. char etag[64];
  2556. const char *ims = mg_get_header(conn, "If-Modified-Since");
  2557. const char *inm = mg_get_header(conn, "If-None-Match");
  2558. construct_etag(etag, sizeof(etag), filep);
  2559. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  2560. (ims != NULL && filep->modification_time <= parse_date_string(ims));
  2561. }
  2562. static int forward_body_data(struct mg_connection *conn, FILE *fp,
  2563. SOCKET sock, SSL *ssl) {
  2564. const char *expect, *body;
  2565. char buf[MG_BUF_LEN];
  2566. int to_read, nread, buffered_len, success = 0;
  2567. expect = mg_get_header(conn, "Expect");
  2568. assert(fp != NULL);
  2569. if (conn->content_len == -1) {
  2570. send_http_error(conn, 411, "Length Required", "%s", "");
  2571. } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
  2572. send_http_error(conn, 417, "Expectation Failed", "%s", "");
  2573. } else {
  2574. if (expect != NULL) {
  2575. (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  2576. }
  2577. body = conn->buf + conn->request_len + conn->consumed_content;
  2578. buffered_len = (int)(&conn->buf[conn->data_len] - body);
  2579. assert(buffered_len >= 0);
  2580. assert(conn->consumed_content == 0);
  2581. if (buffered_len > 0) {
  2582. if ((int64_t) buffered_len > conn->content_len) {
  2583. buffered_len = (int) conn->content_len;
  2584. }
  2585. push(fp, sock, ssl, body, (int64_t) buffered_len);
  2586. conn->consumed_content += buffered_len;
  2587. }
  2588. nread = 0;
  2589. while (conn->consumed_content < conn->content_len) {
  2590. to_read = sizeof(buf);
  2591. if ((int64_t) to_read > conn->content_len - conn->consumed_content) {
  2592. to_read = (int) (conn->content_len - conn->consumed_content);
  2593. }
  2594. nread = pull(NULL, conn, buf, to_read);
  2595. if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
  2596. break;
  2597. }
  2598. conn->consumed_content += nread;
  2599. }
  2600. if (conn->consumed_content == conn->content_len) {
  2601. success = nread >= 0;
  2602. }
  2603. // Each error code path in this function must send an error
  2604. if (!success) {
  2605. send_http_error(conn, 577, http_500_error, "%s", "");
  2606. }
  2607. }
  2608. return success;
  2609. }
  2610. #if !defined(NO_CGI)
  2611. // This structure helps to create an environment for the spawned CGI program.
  2612. // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  2613. // last element must be NULL.
  2614. // However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  2615. // strings must reside in a contiguous buffer. The end of the buffer is
  2616. // marked by two '\0' characters.
  2617. // We satisfy both worlds: we create an envp array (which is vars), all
  2618. // entries are actually pointers inside buf.
  2619. struct cgi_env_block {
  2620. struct mg_connection *conn;
  2621. char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
  2622. int len; // Space taken
  2623. char *vars[MAX_CGI_ENVIR_VARS]; // char **envp
  2624. int nvars; // Number of variables
  2625. };
  2626. static char *addenv(struct cgi_env_block *block,
  2627. PRINTF_FORMAT_STRING(const char *fmt), ...)
  2628. PRINTF_ARGS(2, 3);
  2629. // Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  2630. // pointer into the vars array.
  2631. static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
  2632. int n, space;
  2633. char *added;
  2634. va_list ap;
  2635. // Calculate how much space is left in the buffer
  2636. space = sizeof(block->buf) - block->len - 2;
  2637. assert(space >= 0);
  2638. // Make a pointer to the free space int the buffer
  2639. added = block->buf + block->len;
  2640. // Copy VARIABLE=VALUE\0 string into the free space
  2641. va_start(ap, fmt);
  2642. n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
  2643. va_end(ap);
  2644. // Make sure we do not overflow buffer and the envp array
  2645. if (n > 0 && n + 1 < space &&
  2646. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  2647. // Append a pointer to the added string into the envp array
  2648. block->vars[block->nvars++] = added;
  2649. // Bump up used length counter. Include \0 terminator
  2650. block->len += n + 1;
  2651. } else {
  2652. mg_cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt);
  2653. }
  2654. return added;
  2655. }
  2656. static void prepare_cgi_environment(struct mg_connection *conn,
  2657. const char *prog,
  2658. struct cgi_env_block *blk) {
  2659. const char *s, *slash;
  2660. struct vec var_vec;
  2661. char *p, src_addr[IP_ADDR_STR_LEN];
  2662. int i;
  2663. blk->len = blk->nvars = 0;
  2664. blk->conn = conn;
  2665. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2666. addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  2667. addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  2668. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  2669. addenv(blk, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  2670. // Prepare the environment block
  2671. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  2672. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  2673. addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
  2674. // TODO(lsm): fix this for IPv6 case
  2675. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  2676. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  2677. addenv(blk, "REMOTE_ADDR=%s", src_addr);
  2678. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  2679. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  2680. // SCRIPT_NAME
  2681. assert(conn->request_info.uri[0] == '/');
  2682. slash = strrchr(conn->request_info.uri, '/');
  2683. if ((s = strrchr(prog, '/')) == NULL)
  2684. s = prog;
  2685. addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri),
  2686. conn->request_info.uri, s);
  2687. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  2688. addenv(blk, "PATH_TRANSLATED=%s", prog);
  2689. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  2690. if ((s = mg_get_header(conn, "Content-Type")) != NULL)
  2691. addenv(blk, "CONTENT_TYPE=%s", s);
  2692. if (conn->request_info.query_string != NULL)
  2693. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  2694. if ((s = mg_get_header(conn, "Content-Length")) != NULL)
  2695. addenv(blk, "CONTENT_LENGTH=%s", s);
  2696. if ((s = getenv("PATH")) != NULL)
  2697. addenv(blk, "PATH=%s", s);
  2698. if (conn->path_info != NULL) {
  2699. addenv(blk, "PATH_INFO=%s", conn->path_info);
  2700. }
  2701. #if defined(_WIN32)
  2702. if ((s = getenv("COMSPEC")) != NULL) {
  2703. addenv(blk, "COMSPEC=%s", s);
  2704. }
  2705. if ((s = getenv("SYSTEMROOT")) != NULL) {
  2706. addenv(blk, "SYSTEMROOT=%s", s);
  2707. }
  2708. if ((s = getenv("SystemDrive")) != NULL) {
  2709. addenv(blk, "SystemDrive=%s", s);
  2710. }
  2711. if ((s = getenv("ProgramFiles")) != NULL) {
  2712. addenv(blk, "ProgramFiles=%s", s);
  2713. }
  2714. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  2715. addenv(blk, "ProgramFiles(x86)=%s", s);
  2716. }
  2717. #else
  2718. if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
  2719. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  2720. #endif // _WIN32
  2721. if ((s = getenv("PERLLIB")) != NULL)
  2722. addenv(blk, "PERLLIB=%s", s);
  2723. if (conn->request_info.remote_user != NULL) {
  2724. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  2725. addenv(blk, "%s", "AUTH_TYPE=Digest");
  2726. }
  2727. // Add all headers as HTTP_* variables
  2728. for (i = 0; i < conn->request_info.num_headers; i++) {
  2729. p = addenv(blk, "HTTP_%s=%s",
  2730. conn->request_info.http_headers[i].name,
  2731. conn->request_info.http_headers[i].value);
  2732. // Convert variable name into uppercase, and change - to _
  2733. for (; *p != '=' && *p != '\0'; p++) {
  2734. if (*p == '-')
  2735. *p = '_';
  2736. *p = (char) toupper(* (unsigned char *) p);
  2737. }
  2738. }
  2739. // Add user-specified variables
  2740. s = conn->ctx->config[CGI_ENVIRONMENT];
  2741. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  2742. addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr);
  2743. }
  2744. blk->vars[blk->nvars++] = NULL;
  2745. blk->buf[blk->len++] = '\0';
  2746. assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  2747. assert(blk->len > 0);
  2748. assert(blk->len < (int) sizeof(blk->buf));
  2749. }
  2750. static void handle_cgi_request(struct mg_connection *conn, const char *prog) {
  2751. int headers_len, data_len, i, fdin[2] = { 0, 0 }, fdout[2] = { 0, 0 };
  2752. const char *status, *status_text;
  2753. char buf[MAX_REQUEST_SIZE], *pbuf, dir[PATH_MAX], *p;
  2754. struct mg_request_info ri;
  2755. struct cgi_env_block blk;
  2756. FILE *in = NULL, *out = NULL;
  2757. struct file fout = STRUCT_FILE_INITIALIZER;
  2758. pid_t pid = (pid_t) -1;
  2759. prepare_cgi_environment(conn, prog, &blk);
  2760. // CGI must be executed in its own directory. 'dir' must point to the
  2761. // directory containing executable program, 'p' must point to the
  2762. // executable program name relative to 'dir'.
  2763. (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  2764. if ((p = strrchr(dir, '/')) != NULL) {
  2765. *p++ = '\0';
  2766. } else {
  2767. dir[0] = '.', dir[1] = '\0';
  2768. p = (char *) prog;
  2769. }
  2770. if (pipe(fdin) != 0 || pipe(fdout) != 0) {
  2771. send_http_error(conn, 500, http_500_error,
  2772. "Cannot create CGI pipe: %s", strerror(ERRNO));
  2773. goto done;
  2774. }
  2775. pid = spawn_process(conn, p, blk.buf, blk.vars, fdin[0], fdout[1], dir);
  2776. if (pid == (pid_t) -1) {
  2777. send_http_error(conn, 500, http_500_error,
  2778. "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));
  2779. goto done;
  2780. }
  2781. // Make sure child closes all pipe descriptors. It must dup them to 0,1
  2782. set_close_on_exec(fdin[0]);
  2783. set_close_on_exec(fdin[1]);
  2784. set_close_on_exec(fdout[0]);
  2785. set_close_on_exec(fdout[1]);
  2786. // Parent closes only one side of the pipes.
  2787. // If we don't mark them as closed, close() attempt before
  2788. // return from this function throws an exception on Windows.
  2789. // Windows does not like when closed descriptor is closed again.
  2790. (void) close(fdin[0]);
  2791. (void) close(fdout[1]);
  2792. fdin[0] = fdout[1] = -1;
  2793. if ((in = fdopen(fdin[1], "wb")) == NULL ||
  2794. (out = fdopen(fdout[0], "rb")) == NULL) {
  2795. send_http_error(conn, 500, http_500_error,
  2796. "fopen: %s", strerror(ERRNO));
  2797. goto done;
  2798. }
  2799. setbuf(in, NULL);
  2800. setbuf(out, NULL);
  2801. fout.fp = out;
  2802. // Send POST data to the CGI process if needed
  2803. if (!strcmp(conn->request_info.request_method, "POST") &&
  2804. !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  2805. goto done;
  2806. }
  2807. // Close so child gets an EOF.
  2808. fclose(in);
  2809. in = NULL;
  2810. fdin[1] = -1;
  2811. // Now read CGI reply into a buffer. We need to set correct
  2812. // status code, thus we need to see all HTTP headers first.
  2813. // Do not send anything back to client, until we buffer in all
  2814. // HTTP headers.
  2815. data_len = 0;
  2816. headers_len = read_request(out, conn, buf, sizeof(buf), &data_len);
  2817. if (headers_len <= 0) {
  2818. send_http_error(conn, 500, http_500_error,
  2819. "CGI program sent malformed or too big (>%u bytes) "
  2820. "HTTP headers: [%.*s]",
  2821. (unsigned) sizeof(buf), data_len, buf);
  2822. goto done;
  2823. }
  2824. pbuf = buf;
  2825. buf[headers_len - 1] = '\0';
  2826. parse_http_headers(&pbuf, &ri);
  2827. // Make up and send the status line
  2828. status_text = "OK";
  2829. if ((status = get_header(&ri, "Status")) != NULL) {
  2830. conn->status_code = atoi(status);
  2831. status_text = status;
  2832. while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {
  2833. status_text++;
  2834. }
  2835. } else if (get_header(&ri, "Location") != NULL) {
  2836. conn->status_code = 302;
  2837. } else {
  2838. conn->status_code = 200;
  2839. }
  2840. if (get_header(&ri, "Connection") != NULL &&
  2841. !mg_strcasecmp(get_header(&ri, "Connection"), "keep-alive")) {
  2842. conn->must_close = 1;
  2843. }
  2844. (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code,
  2845. status_text);
  2846. // Send headers
  2847. for (i = 0; i < ri.num_headers; i++) {
  2848. mg_printf(conn, "%s: %s\r\n",
  2849. ri.http_headers[i].name, ri.http_headers[i].value);
  2850. }
  2851. mg_write(conn, "\r\n", 2);
  2852. // Send chunk of data that may have been read after the headers
  2853. conn->num_bytes_sent += mg_write(conn, buf + headers_len,
  2854. (size_t)(data_len - headers_len));
  2855. // Read the rest of CGI output and send to the client
  2856. send_file_data(conn, &fout, 0, INT64_MAX);
  2857. done:
  2858. if (pid != (pid_t) -1) {
  2859. kill(pid, SIGKILL);
  2860. #if !defined(_WIN32)
  2861. {
  2862. int st;
  2863. while (waitpid(pid, &st, 0) != -1); // clean zombies
  2864. }
  2865. #endif
  2866. }
  2867. if (fdin[0] != -1) {
  2868. close(fdin[0]);
  2869. }
  2870. if (fdout[1] != -1) {
  2871. close(fdout[1]);
  2872. }
  2873. if (in != NULL) {
  2874. fclose(in);
  2875. } else if (fdin[1] != -1) {
  2876. close(fdin[1]);
  2877. }
  2878. if (out != NULL) {
  2879. fclose(out);
  2880. } else if (fdout[0] != -1) {
  2881. close(fdout[0]);
  2882. }
  2883. }
  2884. #endif // !NO_CGI
  2885. // For a given PUT path, create all intermediate subdirectories
  2886. // for given path. Return 0 if the path itself is a directory,
  2887. // or -1 on error, 1 if OK.
  2888. static int put_dir(struct mg_connection *conn, const char *path) {
  2889. char buf[PATH_MAX];
  2890. const char *s, *p;
  2891. struct file file = STRUCT_FILE_INITIALIZER;
  2892. int len, res = 1;
  2893. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  2894. len = (int)(p - path);
  2895. if (len >= (int) sizeof(buf)) {
  2896. res = -1;
  2897. break;
  2898. }
  2899. memcpy(buf, path, len);
  2900. buf[len] = '\0';
  2901. // Try to create intermediate directory
  2902. DEBUG_TRACE(("mkdir(%s)", buf));
  2903. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  2904. res = -1;
  2905. break;
  2906. }
  2907. // Is path itself a directory?
  2908. if (p[1] == '\0') {
  2909. res = 0;
  2910. }
  2911. }
  2912. return res;
  2913. }
  2914. static void mkcol(struct mg_connection *conn, const char *path) {
  2915. int rc, body_len;
  2916. struct de de;
  2917. memset(&de.file, 0, sizeof(de.file));
  2918. mg_stat(conn, path, &de.file);
  2919. if(de.file.modification_time) {
  2920. send_http_error(conn, 405, "Method Not Allowed",
  2921. "mkcol(%s): %s", path, strerror(ERRNO));
  2922. return;
  2923. }
  2924. body_len = conn->data_len - conn->request_len;
  2925. if(body_len > 0) {
  2926. send_http_error(conn, 415, "Unsupported media type",
  2927. "mkcol(%s): %s", path, strerror(ERRNO));
  2928. return;
  2929. }
  2930. rc = mg_mkdir(path, 0755);
  2931. if (rc == 0) {
  2932. conn->status_code = 201;
  2933. mg_printf(conn, "HTTP/1.1 %d Created\r\n\r\n", conn->status_code);
  2934. } else if (rc == -1) {
  2935. if(errno == EEXIST)
  2936. send_http_error(conn, 405, "Method Not Allowed",
  2937. "mkcol(%s): %s", path, strerror(ERRNO));
  2938. else if(errno == EACCES)
  2939. send_http_error(conn, 403, "Forbidden",
  2940. "mkcol(%s): %s", path, strerror(ERRNO));
  2941. else if(errno == ENOENT)
  2942. send_http_error(conn, 409, "Conflict",
  2943. "mkcol(%s): %s", path, strerror(ERRNO));
  2944. else
  2945. send_http_error(conn, 500, http_500_error,
  2946. "fopen(%s): %s", path, strerror(ERRNO));
  2947. }
  2948. }
  2949. static void put_file(struct mg_connection *conn, const char *path) {
  2950. struct file file = STRUCT_FILE_INITIALIZER;
  2951. const char *range;
  2952. int64_t r1, r2;
  2953. int rc;
  2954. conn->status_code = mg_stat(conn, path, &file) ? 200 : 201;
  2955. if ((rc = put_dir(conn, path)) == 0) {
  2956. mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->status_code);
  2957. } else if (rc == -1) {
  2958. send_http_error(conn, 500, http_500_error,
  2959. "put_dir(%s): %s", path, strerror(ERRNO));
  2960. } else if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  2961. mg_fclose(&file);
  2962. send_http_error(conn, 500, http_500_error,
  2963. "fopen(%s): %s", path, strerror(ERRNO));
  2964. } else {
  2965. fclose_on_exec(&file);
  2966. range = mg_get_header(conn, "Content-Range");
  2967. r1 = r2 = 0;
  2968. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  2969. conn->status_code = 206;
  2970. fseeko(file.fp, r1, SEEK_SET);
  2971. }
  2972. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  2973. conn->status_code = 500;
  2974. }
  2975. mg_printf(conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
  2976. conn->status_code);
  2977. mg_fclose(&file);
  2978. }
  2979. }
  2980. static void send_ssi_file(struct mg_connection *, const char *,
  2981. struct file *, int);
  2982. static void do_ssi_include(struct mg_connection *conn, const char *ssi,
  2983. char *tag, int include_level) {
  2984. char file_name[MG_BUF_LEN], path[PATH_MAX], *p;
  2985. struct file file = STRUCT_FILE_INITIALIZER;
  2986. // sscanf() is safe here, since send_ssi_file() also uses buffer
  2987. // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
  2988. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
  2989. // File name is relative to the webserver root
  2990. (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
  2991. conn->ctx->config[DOCUMENT_ROOT], '/', file_name);
  2992. } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
  2993. // File name is relative to the webserver working directory
  2994. // or it is absolute system path
  2995. (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  2996. } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
  2997. sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
  2998. // File name is relative to the currect document
  2999. (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  3000. if ((p = strrchr(path, '/')) != NULL) {
  3001. p[1] = '\0';
  3002. }
  3003. (void) mg_snprintf(conn, path + strlen(path),
  3004. sizeof(path) - strlen(path), "%s", file_name);
  3005. } else {
  3006. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  3007. return;
  3008. }
  3009. if (!mg_fopen(conn, path, "rb", &file)) {
  3010. mg_cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
  3011. tag, path, strerror(ERRNO));
  3012. } else {
  3013. fclose_on_exec(&file);
  3014. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  3015. (int)strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {
  3016. send_ssi_file(conn, path, &file, include_level + 1);
  3017. } else {
  3018. send_file_data(conn, &file, 0, INT64_MAX);
  3019. }
  3020. mg_fclose(&file);
  3021. }
  3022. }
  3023. #if !defined(NO_POPEN)
  3024. static void do_ssi_exec(struct mg_connection *conn, char *tag) {
  3025. char cmd[MG_BUF_LEN] = "";
  3026. struct file file = STRUCT_FILE_INITIALIZER;
  3027. if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
  3028. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  3029. } else if ((file.fp = popen(cmd, "r")) == NULL) {
  3030. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  3031. } else {
  3032. send_file_data(conn, &file, 0, INT64_MAX);
  3033. pclose(file.fp);
  3034. }
  3035. }
  3036. #endif // !NO_POPEN
  3037. static int mg_fgetc(struct file *filep, int offset) {
  3038. if (filep->membuf != NULL && offset >=0 && offset < filep->size) {
  3039. return ((unsigned char *) filep->membuf)[offset];
  3040. } else if (filep->fp != NULL) {
  3041. return fgetc(filep->fp);
  3042. } else {
  3043. return EOF;
  3044. }
  3045. }
  3046. static void send_ssi_file(struct mg_connection *conn, const char *path,
  3047. struct file *filep, int include_level) {
  3048. char buf[MG_BUF_LEN];
  3049. int ch, offset, len, in_ssi_tag;
  3050. if (include_level > 10) {
  3051. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  3052. return;
  3053. }
  3054. in_ssi_tag = len = offset = 0;
  3055. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  3056. if (in_ssi_tag && ch == '>') {
  3057. in_ssi_tag = 0;
  3058. buf[len++] = (char) ch;
  3059. buf[len] = '\0';
  3060. assert(len <= (int) sizeof(buf));
  3061. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  3062. // Not an SSI tag, pass it
  3063. (void) mg_write(conn, buf, (size_t) len);
  3064. } else {
  3065. if (!memcmp(buf + 5, "include", 7)) {
  3066. do_ssi_include(conn, path, buf + 12, include_level);
  3067. #if !defined(NO_POPEN)
  3068. } else if (!memcmp(buf + 5, "exec", 4)) {
  3069. do_ssi_exec(conn, buf + 9);
  3070. #endif // !NO_POPEN
  3071. } else {
  3072. mg_cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
  3073. }
  3074. }
  3075. len = 0;
  3076. } else if (in_ssi_tag) {
  3077. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  3078. // Not an SSI tag
  3079. in_ssi_tag = 0;
  3080. } else if (len == (int) sizeof(buf) - 2) {
  3081. mg_cry(conn, "%s: SSI tag is too large", path);
  3082. len = 0;
  3083. }
  3084. buf[len++] = ch & 0xff;
  3085. } else if (ch == '<') {
  3086. in_ssi_tag = 1;
  3087. if (len > 0) {
  3088. mg_write(conn, buf, (size_t) len);
  3089. }
  3090. len = 0;
  3091. buf[len++] = ch & 0xff;
  3092. } else {
  3093. buf[len++] = ch & 0xff;
  3094. if (len == (int) sizeof(buf)) {
  3095. mg_write(conn, buf, (size_t) len);
  3096. len = 0;
  3097. }
  3098. }
  3099. }
  3100. // Send the rest of buffered data
  3101. if (len > 0) {
  3102. mg_write(conn, buf, (size_t) len);
  3103. }
  3104. }
  3105. static void handle_ssi_file_request(struct mg_connection *conn,
  3106. const char *path) {
  3107. struct file file = STRUCT_FILE_INITIALIZER;
  3108. if (!mg_fopen(conn, path, "rb", &file)) {
  3109. send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,
  3110. strerror(ERRNO));
  3111. } else {
  3112. conn->must_close = 1;
  3113. fclose_on_exec(&file);
  3114. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  3115. "Content-Type: text/html\r\nConnection: %s\r\n\r\n",
  3116. suggest_connection_header(conn));
  3117. send_ssi_file(conn, path, &file, 0);
  3118. mg_fclose(&file);
  3119. }
  3120. }
  3121. static void send_options(struct mg_connection *conn) {
  3122. conn->status_code = 200;
  3123. mg_printf(conn, "%s", "HTTP/1.1 200 OK\r\n"
  3124. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, PROPFIND, MKCOL\r\n"
  3125. "DAV: 1\r\n\r\n");
  3126. }
  3127. // Writes PROPFIND properties for a collection element
  3128. static void print_props(struct mg_connection *conn, const char* uri,
  3129. struct file *filep) {
  3130. char mtime[64];
  3131. gmt_time_string(mtime, sizeof(mtime), &filep->modification_time);
  3132. conn->num_bytes_sent += mg_printf(conn,
  3133. "<d:response>"
  3134. "<d:href>%s</d:href>"
  3135. "<d:propstat>"
  3136. "<d:prop>"
  3137. "<d:resourcetype>%s</d:resourcetype>"
  3138. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  3139. "<d:getlastmodified>%s</d:getlastmodified>"
  3140. "</d:prop>"
  3141. "<d:status>HTTP/1.1 200 OK</d:status>"
  3142. "</d:propstat>"
  3143. "</d:response>\n",
  3144. uri,
  3145. filep->is_directory ? "<d:collection/>" : "",
  3146. filep->size,
  3147. mtime);
  3148. }
  3149. static void print_dav_dir_entry(struct de *de, void *data) {
  3150. char href[PATH_MAX];
  3151. char href_encoded[PATH_MAX];
  3152. struct mg_connection *conn = (struct mg_connection *) data;
  3153. mg_snprintf(conn, href, sizeof(href), "%s%s",
  3154. conn->request_info.uri, de->file_name);
  3155. mg_url_encode(href, href_encoded, PATH_MAX-1);
  3156. print_props(conn, href_encoded, &de->file);
  3157. }
  3158. static void handle_propfind(struct mg_connection *conn, const char *path,
  3159. struct file *filep) {
  3160. const char *depth = mg_get_header(conn, "Depth");
  3161. conn->must_close = 1;
  3162. conn->status_code = 207;
  3163. mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
  3164. "Connection: close\r\n"
  3165. "Content-Type: text/xml; charset=utf-8\r\n\r\n");
  3166. conn->num_bytes_sent += mg_printf(conn,
  3167. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  3168. "<d:multistatus xmlns:d='DAV:'>\n");
  3169. // Print properties for the requested resource itself
  3170. print_props(conn, conn->request_info.uri, filep);
  3171. // If it is a directory, print directory entries too if Depth is not 0
  3172. if (filep->is_directory &&
  3173. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  3174. (depth == NULL || strcmp(depth, "0") != 0)) {
  3175. scan_directory(conn, path, conn, &print_dav_dir_entry);
  3176. }
  3177. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  3178. }
  3179. void mg_lock(struct mg_connection* conn) {
  3180. (void) pthread_mutex_lock(&conn->mutex);
  3181. }
  3182. void mg_unlock(struct mg_connection* conn) {
  3183. (void) pthread_mutex_unlock(&conn->mutex);
  3184. }
  3185. #if defined(USE_WEBSOCKET)
  3186. // START OF SHA-1 code
  3187. // Copyright(c) By Steve Reid <steve@edmweb.com>
  3188. #define SHA1HANDSOFF
  3189. #if defined(__sun)
  3190. #include "solarisfixes.h"
  3191. #endif
  3192. static int is_big_endian(void) {
  3193. static const int n = 1;
  3194. return ((char *) &n)[0] == 0;
  3195. }
  3196. union char64long16 { unsigned char c[64]; uint32_t l[16]; };
  3197. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  3198. static uint32_t blk0(union char64long16 *block, int i) {
  3199. // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
  3200. if (!is_big_endian()) {
  3201. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  3202. (rol(block->l[i], 8) & 0x00FF00FF);
  3203. }
  3204. return block->l[i];
  3205. }
  3206. #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
  3207. ^block->l[(i+2)&15]^block->l[i&15],1))
  3208. #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
  3209. #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
  3210. #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
  3211. #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
  3212. #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
  3213. typedef struct {
  3214. uint32_t state[5];
  3215. uint32_t count[2];
  3216. unsigned char buffer[64];
  3217. } SHA1_CTX;
  3218. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
  3219. uint32_t a, b, c, d, e;
  3220. union char64long16 block[1];
  3221. memcpy(block, buffer, 64);
  3222. a = state[0];
  3223. b = state[1];
  3224. c = state[2];
  3225. d = state[3];
  3226. e = state[4];
  3227. 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);
  3228. 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);
  3229. 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);
  3230. 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);
  3231. 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);
  3232. 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);
  3233. 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);
  3234. 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);
  3235. 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);
  3236. 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);
  3237. 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);
  3238. 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);
  3239. 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);
  3240. 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);
  3241. 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);
  3242. 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);
  3243. 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);
  3244. 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);
  3245. 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);
  3246. 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);
  3247. state[0] += a;
  3248. state[1] += b;
  3249. state[2] += c;
  3250. state[3] += d;
  3251. state[4] += e;
  3252. a = b = c = d = e = 0;
  3253. memset(block, '\0', sizeof(block));
  3254. }
  3255. static void SHA1Init(SHA1_CTX* context) {
  3256. context->state[0] = 0x67452301;
  3257. context->state[1] = 0xEFCDAB89;
  3258. context->state[2] = 0x98BADCFE;
  3259. context->state[3] = 0x10325476;
  3260. context->state[4] = 0xC3D2E1F0;
  3261. context->count[0] = context->count[1] = 0;
  3262. }
  3263. static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
  3264. uint32_t len) {
  3265. uint32_t i, j;
  3266. j = context->count[0];
  3267. if ((context->count[0] += len << 3) < j)
  3268. context->count[1]++;
  3269. context->count[1] += (len>>29);
  3270. j = (j >> 3) & 63;
  3271. if ((j + len) > 63) {
  3272. memcpy(&context->buffer[j], data, (i = 64-j));
  3273. SHA1Transform(context->state, context->buffer);
  3274. for ( ; i + 63 < len; i += 64) {
  3275. SHA1Transform(context->state, &data[i]);
  3276. }
  3277. j = 0;
  3278. }
  3279. else i = 0;
  3280. memcpy(&context->buffer[j], &data[i], len - i);
  3281. }
  3282. static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) {
  3283. unsigned i;
  3284. unsigned char finalcount[8], c;
  3285. for (i = 0; i < 8; i++) {
  3286. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  3287. >> ((3-(i & 3)) * 8) ) & 255);
  3288. }
  3289. c = 0200;
  3290. SHA1Update(context, &c, 1);
  3291. while ((context->count[0] & 504) != 448) {
  3292. c = 0000;
  3293. SHA1Update(context, &c, 1);
  3294. }
  3295. SHA1Update(context, finalcount, 8);
  3296. for (i = 0; i < 20; i++) {
  3297. digest[i] = (unsigned char)
  3298. ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
  3299. }
  3300. memset(context, '\0', sizeof(*context));
  3301. memset(&finalcount, '\0', sizeof(finalcount));
  3302. }
  3303. // END OF SHA1 CODE
  3304. static void base64_encode(const unsigned char *src, int src_len, char *dst) {
  3305. static const char *b64 =
  3306. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3307. int i, j, a, b, c;
  3308. for (i = j = 0; i < src_len; i += 3) {
  3309. a = src[i];
  3310. b = i + 1 >= src_len ? 0 : src[i + 1];
  3311. c = i + 2 >= src_len ? 0 : src[i + 2];
  3312. dst[j++] = b64[a >> 2];
  3313. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3314. if (i + 1 < src_len) {
  3315. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3316. }
  3317. if (i + 2 < src_len) {
  3318. dst[j++] = b64[c & 63];
  3319. }
  3320. }
  3321. while (j % 4 != 0) {
  3322. dst[j++] = '=';
  3323. }
  3324. dst[j++] = '\0';
  3325. }
  3326. static void send_websocket_handshake(struct mg_connection *conn) {
  3327. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3328. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  3329. SHA1_CTX sha_ctx;
  3330. mg_snprintf(conn, buf, sizeof(buf), "%s%s",
  3331. mg_get_header(conn, "Sec-WebSocket-Key"), magic);
  3332. SHA1Init(&sha_ctx);
  3333. SHA1Update(&sha_ctx, (unsigned char *) buf, (uint32_t)strlen(buf));
  3334. SHA1Final((unsigned char *) sha, &sha_ctx);
  3335. base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
  3336. mg_printf(conn, "%s%s%s",
  3337. "HTTP/1.1 101 Switching Protocols\r\n"
  3338. "Upgrade: websocket\r\n"
  3339. "Connection: Upgrade\r\n"
  3340. "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
  3341. }
  3342. static void read_websocket(struct mg_connection *conn) {
  3343. // Pointer to the beginning of the portion of the incoming websocket message queue.
  3344. // The original websocket upgrade request is never removed, so the queue begins after it.
  3345. unsigned char *buf = (unsigned char *) conn->buf + conn->request_len;
  3346. int n;
  3347. // body_len is the length of the entire queue in bytes
  3348. // len is the length of the current message
  3349. // data_len is the length of the current message's data payload
  3350. // header_len is the length of the current message's header
  3351. size_t i, len, mask_len, data_len, header_len, body_len;
  3352. // "The masking key is a 32-bit value chosen at random by the client."
  3353. // http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  3354. unsigned char mask[4];
  3355. // data points to the place where the message is stored when passed to the websocket_data
  3356. // callback. This is either mem on the stack, or a dynamically allocated buffer if it is
  3357. // too large.
  3358. char mem[4096];
  3359. char *data = mem;
  3360. // Loop continuously, reading messages from the socket, invoking the callback,
  3361. // and waiting repeatedly until an error occurs.
  3362. assert(conn->content_len == 0);
  3363. for (;;) {
  3364. header_len = 0;
  3365. if ((body_len = conn->data_len - conn->request_len) >= 2) {
  3366. len = buf[1] & 127;
  3367. mask_len = buf[1] & 128 ? 4 : 0;
  3368. if (len < 126 && body_len >= mask_len) {
  3369. data_len = len;
  3370. header_len = 2 + mask_len;
  3371. } else if (len == 126 && body_len >= 4 + mask_len) {
  3372. header_len = 4 + mask_len;
  3373. data_len = ((((int) buf[2]) << 8) + buf[3]);
  3374. } else if (body_len >= 10 + mask_len) {
  3375. header_len = 10 + mask_len;
  3376. data_len = (((uint64_t) ntohl(* (uint32_t *) &buf[2])) << 32) +
  3377. ntohl(* (uint32_t *) &buf[6]);
  3378. }
  3379. }
  3380. if (header_len > 0) {
  3381. // Allocate space to hold websocket payload
  3382. data = mem;
  3383. if (data_len > sizeof(mem)) {
  3384. data = (char *)malloc(data_len);
  3385. if (data == NULL) {
  3386. // Allocation failed, exit the loop and then close the connection
  3387. // TODO: notify user about the failure
  3388. break;
  3389. }
  3390. }
  3391. // Copy the mask before we shift the queue and destroy it
  3392. if (mask_len > 0) {
  3393. *(uint32_t*)mask = *(uint32_t*)(buf + header_len - mask_len);
  3394. } else {
  3395. *(uint32_t*)mask = 0;
  3396. }
  3397. // Read frame payload from the first message in the queue into data and
  3398. // advance the queue by moving the memory in place.
  3399. assert(body_len >= header_len);
  3400. if (data_len + header_len > body_len) {
  3401. // Overflow case
  3402. len = body_len - header_len;
  3403. memcpy(data, buf + header_len, len);
  3404. // TODO: handle pull error
  3405. pull(NULL, conn, data + len, (int)(data_len - len));
  3406. conn->data_len = 0;
  3407. } else {
  3408. // Length of the message being read at the front of the queue
  3409. len = data_len + header_len;
  3410. // Copy the data payload into the data pointer for the callback
  3411. memcpy(data, buf + header_len, data_len);
  3412. // Move the queue forward len bytes
  3413. memmove(buf, buf + len, body_len - len);
  3414. // Mark the queue as advanced
  3415. conn->data_len -= (int)len;
  3416. }
  3417. // Apply mask if necessary
  3418. if (mask_len > 0) {
  3419. for (i = 0; i < data_len; ++i) {
  3420. data[i] ^= mask[i & 3];
  3421. }
  3422. }
  3423. // Exit the loop if callback signalled to exit,
  3424. // or "connection close" opcode received.
  3425. if ((conn->ctx->callbacks.websocket_data != NULL &&
  3426. !conn->ctx->callbacks.websocket_data(conn, buf[0], data, data_len)) ||
  3427. (buf[0] & 0xf) == 8) { // Opcode == 8, connection close
  3428. break;
  3429. }
  3430. if (data != mem) {
  3431. free(data);
  3432. }
  3433. // Not breaking the loop, process next websocket frame.
  3434. } else {
  3435. // Read from the socket into the next available location in the message queue.
  3436. if ((n = pull(NULL, conn, conn->buf + conn->data_len,
  3437. conn->buf_size - conn->data_len)) <= 0) {
  3438. // Error, no bytes read
  3439. break;
  3440. }
  3441. conn->data_len += n;
  3442. }
  3443. }
  3444. }
  3445. int mg_websocket_write(struct mg_connection* conn, int opcode, const char* data, size_t dataLen) {
  3446. unsigned char header[10];
  3447. size_t headerLen = 1;
  3448. int retval = -1;
  3449. header[0] = 0x80 + (opcode & 0xF);
  3450. // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2
  3451. if (dataLen < 126) {
  3452. // inline 7-bit length field
  3453. header[1] = (unsigned char)dataLen;
  3454. headerLen = 2;
  3455. } else if (dataLen <= 0xFFFF) {
  3456. // 16-bit length field
  3457. header[1] = 126;
  3458. *(uint16_t*)(header + 2) = htons((uint16_t)dataLen);
  3459. headerLen = 4;
  3460. } else {
  3461. // 64-bit length field
  3462. header[1] = 127;
  3463. *(uint32_t*)(header + 2) = htonl((uint64_t)dataLen >> 32);
  3464. *(uint32_t*)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  3465. headerLen = 10;
  3466. }
  3467. // Note that POSIX/Winsock's send() is threadsafe
  3468. // http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  3469. // but mongoose's mg_printf/mg_write is not (because of the loop in push(), although that is only
  3470. // a problem if the packet is large or outgoing buffer is full).
  3471. (void) mg_lock(conn);
  3472. retval = mg_write(conn, header, headerLen);
  3473. retval = mg_write(conn, data, dataLen);
  3474. mg_unlock(conn);
  3475. return retval;
  3476. }
  3477. static void handle_websocket_request(struct mg_connection *conn) {
  3478. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  3479. if (version == NULL || strcmp(version, "13") != 0) {
  3480. send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required");
  3481. } else if (conn->ctx->callbacks.websocket_connect != NULL &&
  3482. conn->ctx->callbacks.websocket_connect(conn) != 0) {
  3483. // Callback has returned non-zero, do not proceed with handshake
  3484. } else {
  3485. send_websocket_handshake(conn);
  3486. if (conn->ctx->callbacks.websocket_ready != NULL) {
  3487. conn->ctx->callbacks.websocket_ready(conn);
  3488. }
  3489. read_websocket(conn);
  3490. }
  3491. }
  3492. static int is_websocket_request(const struct mg_connection *conn) {
  3493. const char *host, *upgrade, *connection, *version, *key;
  3494. host = mg_get_header(conn, "Host");
  3495. upgrade = mg_get_header(conn, "Upgrade");
  3496. connection = mg_get_header(conn, "Connection");
  3497. key = mg_get_header(conn, "Sec-WebSocket-Key");
  3498. version = mg_get_header(conn, "Sec-WebSocket-Version");
  3499. return host != NULL && upgrade != NULL && connection != NULL &&
  3500. key != NULL && version != NULL &&
  3501. mg_strcasestr(upgrade, "websocket") != NULL &&
  3502. mg_strcasestr(connection, "Upgrade") != NULL;
  3503. }
  3504. #endif // !USE_WEBSOCKET
  3505. static int isbyte(int n) {
  3506. return n >= 0 && n <= 255;
  3507. }
  3508. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  3509. int n, a, b, c, d, slash = 32, len = 0;
  3510. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  3511. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  3512. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
  3513. slash >= 0 && slash < 33) {
  3514. len = n;
  3515. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
  3516. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  3517. }
  3518. return len;
  3519. }
  3520. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri) {
  3521. int throttle = 0;
  3522. struct vec vec, val;
  3523. uint32_t net, mask;
  3524. char mult;
  3525. double v;
  3526. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  3527. mult = ',';
  3528. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  3529. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) {
  3530. continue;
  3531. }
  3532. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1;
  3533. if (vec.len == 1 && vec.ptr[0] == '*') {
  3534. throttle = (int) v;
  3535. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  3536. if ((remote_ip & mask) == net) {
  3537. throttle = (int) v;
  3538. }
  3539. } else if (match_prefix(vec.ptr, (int)vec.len, uri) > 0) {
  3540. throttle = (int) v;
  3541. }
  3542. }
  3543. return throttle;
  3544. }
  3545. static uint32_t get_remote_ip(const struct mg_connection *conn) {
  3546. return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);
  3547. }
  3548. #ifdef USE_LUA
  3549. #include "mod_lua.inl"
  3550. #endif // USE_LUA
  3551. int mg_upload(struct mg_connection *conn, const char *destination_dir) {
  3552. const char *content_type_header, *boundary_start;
  3553. char buf[MG_BUF_LEN], path[PATH_MAX], fname[1024], boundary[100], *s;
  3554. FILE *fp;
  3555. int bl, n, i, j, headers_len, boundary_len, eof,
  3556. len = 0, num_uploaded_files = 0;
  3557. // Request looks like this:
  3558. //
  3559. // POST /upload HTTP/1.1
  3560. // Host: 127.0.0.1:8080
  3561. // Content-Length: 244894
  3562. // Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  3563. //
  3564. // ------WebKitFormBoundaryRVr
  3565. // Content-Disposition: form-data; name="file"; filename="accum.png"
  3566. // Content-Type: image/png
  3567. //
  3568. // <89>PNG
  3569. // <PNG DATA>
  3570. // ------WebKitFormBoundaryRVr
  3571. // Extract boundary string from the Content-Type header
  3572. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
  3573. (boundary_start = mg_strcasestr(content_type_header,
  3574. "boundary=")) == NULL ||
  3575. (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
  3576. sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
  3577. boundary[0] == '\0') {
  3578. return num_uploaded_files;
  3579. }
  3580. boundary_len = (int)strlen(boundary);
  3581. bl = boundary_len + 4; // \r\n--<boundary>
  3582. for (;;) {
  3583. // Pull in headers
  3584. assert(len >= 0 && len <= (int) sizeof(buf));
  3585. while ((n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0) {
  3586. len += n;
  3587. }
  3588. if ((headers_len = get_request_len(buf, len)) <= 0) {
  3589. break;
  3590. }
  3591. // Fetch file name.
  3592. fname[0] = '\0';
  3593. for (i = j = 0; i < headers_len; i++) {
  3594. if (buf[i] == '\r' && buf[i + 1] == '\n') {
  3595. buf[i] = buf[i + 1] = '\0';
  3596. // TODO(lsm): don't expect filename to be the 3rd field,
  3597. // parse the header properly instead.
  3598. IGNORE_UNUSED_RESULT(sscanf(&buf[j], "Content-Disposition: %*s %*s filename=\"%1023[^\"]",
  3599. fname));
  3600. j = i + 2;
  3601. }
  3602. }
  3603. // Give up if the headers are not what we expect
  3604. if (fname[0] == '\0') {
  3605. break;
  3606. }
  3607. // Move data to the beginning of the buffer
  3608. assert(len >= headers_len);
  3609. memmove(buf, &buf[headers_len], len - headers_len);
  3610. len -= headers_len;
  3611. // We open the file with exclusive lock held. This guarantee us
  3612. // there is no other thread can save into the same file simultaneously.
  3613. fp = NULL;
  3614. // Construct destination file name. Do not allow paths to have slashes.
  3615. if ((s = strrchr(fname, '/')) == NULL &&
  3616. (s = strrchr(fname, '\\')) == NULL) {
  3617. s = fname;
  3618. }
  3619. // Open file in binary mode. TODO: set an exclusive lock.
  3620. snprintf(path, sizeof(path), "%s/%s", destination_dir, s);
  3621. if ((fp = fopen(path, "wb")) == NULL) {
  3622. break;
  3623. }
  3624. // Read POST data, write into file until boundary is found.
  3625. eof = n = 0;
  3626. do {
  3627. len += n;
  3628. for (i = 0; i < len - bl; i++) {
  3629. if (!memcmp(&buf[i], "\r\n--", 4) &&
  3630. !memcmp(&buf[i + 4], boundary, boundary_len)) {
  3631. // Found boundary, that's the end of file data.
  3632. fwrite(buf, 1, i, fp);
  3633. eof = 1;
  3634. memmove(buf, &buf[i + bl], len - (i + bl));
  3635. len -= i + bl;
  3636. break;
  3637. }
  3638. }
  3639. if (!eof && len > bl) {
  3640. fwrite(buf, 1, len - bl, fp);
  3641. memmove(buf, &buf[len - bl], bl);
  3642. len = bl;
  3643. }
  3644. } while (!eof && (n = mg_read(conn, buf + len, sizeof(buf) - len)) > 0);
  3645. fclose(fp);
  3646. if (eof) {
  3647. num_uploaded_files++;
  3648. if (conn->ctx->callbacks.upload != NULL) {
  3649. conn->ctx->callbacks.upload(conn, path);
  3650. }
  3651. }
  3652. }
  3653. return num_uploaded_files;
  3654. }
  3655. static int is_put_or_delete_request(const struct mg_connection *conn) {
  3656. const char *s = conn->request_info.request_method;
  3657. return s != NULL && (!strcmp(s, "PUT") ||
  3658. !strcmp(s, "DELETE") ||
  3659. !strcmp(s, "MKCOL"));
  3660. }
  3661. static int get_first_ssl_listener_index(const struct mg_context *ctx) {
  3662. int i, index = -1;
  3663. for (i = 0; index == -1 && i < ctx->num_listening_sockets; i++) {
  3664. index = ctx->listening_sockets[i].is_ssl ? i : -1;
  3665. }
  3666. return index;
  3667. }
  3668. static void redirect_to_https_port(struct mg_connection *conn, int ssl_index) {
  3669. char host[1025];
  3670. const char *host_header;
  3671. if ((host_header = mg_get_header(conn, "Host")) == NULL ||
  3672. sscanf(host_header, "%1024[^:]", host) == 0) {
  3673. // Cannot get host from the Host: header. Fallback to our IP address.
  3674. sockaddr_to_string(host, sizeof(host), &conn->client.lsa);
  3675. }
  3676. mg_printf(conn, "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s\r\n\r\n",
  3677. host, (int) ntohs(conn->ctx->listening_sockets[ssl_index].
  3678. lsa.sin.sin_port), conn->request_info.uri);
  3679. }
  3680. // This is the heart of the Civetweb's logic.
  3681. // This function is called when the request is read, parsed and validated,
  3682. // and Civetweb must decide what action to take: serve a file, or
  3683. // a directory, or call embedded function, etcetera.
  3684. static void handle_request(struct mg_connection *conn) {
  3685. struct mg_request_info *ri = &conn->request_info;
  3686. char path[PATH_MAX];
  3687. int uri_len, ssl_index;
  3688. struct file file = STRUCT_FILE_INITIALIZER;
  3689. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
  3690. * ((char *) conn->request_info.query_string++) = '\0';
  3691. }
  3692. uri_len = (int) strlen(ri->uri);
  3693. mg_url_decode(ri->uri, uri_len, (char *) ri->uri, uri_len + 1, 0);
  3694. remove_double_dots_and_double_slashes((char *) ri->uri);
  3695. convert_uri_to_file_name(conn, path, sizeof(path), &file);
  3696. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  3697. get_remote_ip(conn), ri->uri);
  3698. DEBUG_TRACE(("%s", ri->uri));
  3699. // Perform redirect and auth checks before calling begin_request() handler.
  3700. // Otherwise, begin_request() would need to perform auth checks and redirects.
  3701. if (!conn->client.is_ssl && conn->client.ssl_redir &&
  3702. (ssl_index = get_first_ssl_listener_index(conn->ctx)) > -1) {
  3703. redirect_to_https_port(conn, ssl_index);
  3704. } else if (!is_put_or_delete_request(conn) &&
  3705. !check_authorization(conn, path)) {
  3706. send_authorization_request(conn);
  3707. } else if (conn->ctx->callbacks.begin_request != NULL &&
  3708. conn->ctx->callbacks.begin_request(conn)) {
  3709. // Do nothing, callback has served the request
  3710. #if defined(USE_WEBSOCKET)
  3711. } else if (is_websocket_request(conn)) {
  3712. handle_websocket_request(conn);
  3713. #endif
  3714. } else if (!strcmp(ri->request_method, "OPTIONS")) {
  3715. send_options(conn);
  3716. } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  3717. send_http_error(conn, 404, "Not Found", "Not Found");
  3718. } else if (is_put_or_delete_request(conn) &&
  3719. (is_authorized_for_put(conn) != 1)) {
  3720. send_authorization_request(conn);
  3721. } else if (!strcmp(ri->request_method, "PUT")) {
  3722. put_file(conn, path);
  3723. } else if (!strcmp(ri->request_method, "MKCOL")) {
  3724. mkcol(conn, path);
  3725. } else if (!strcmp(ri->request_method, "DELETE")) {
  3726. struct de de;
  3727. memset(&de.file, 0, sizeof(de.file));
  3728. if(!mg_stat(conn, path, &de.file)) {
  3729. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  3730. } else {
  3731. if(de.file.modification_time) {
  3732. if(de.file.is_directory) {
  3733. remove_directory(conn, path);
  3734. send_http_error(conn, 204, "No Content", "%s", "");
  3735. } else if (mg_remove(path) == 0) {
  3736. send_http_error(conn, 204, "No Content", "%s", "");
  3737. } else {
  3738. send_http_error(conn, 423, "Locked", "remove(%s): %s", path,
  3739. strerror(ERRNO));
  3740. }
  3741. }
  3742. else {
  3743. send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,
  3744. strerror(ERRNO));
  3745. }
  3746. }
  3747. } else if ((file.membuf == NULL && file.modification_time == (time_t) 0) ||
  3748. must_hide_file(conn, path)) {
  3749. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  3750. } else if (file.is_directory && ri->uri[uri_len - 1] != '/') {
  3751. mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
  3752. "Location: %s/\r\n\r\n", ri->uri);
  3753. } else if (!strcmp(ri->request_method, "PROPFIND")) {
  3754. handle_propfind(conn, path, &file);
  3755. } else if (file.is_directory &&
  3756. !substitute_index_file(conn, path, sizeof(path), &file)) {
  3757. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {
  3758. handle_directory_request(conn, path);
  3759. } else {
  3760. send_http_error(conn, 403, "Directory Listing Denied",
  3761. "Directory listing denied");
  3762. }
  3763. #ifdef USE_LUA
  3764. } else if (match_prefix("**.lp$", 6, path) > 0) {
  3765. handle_lsp_request(conn, path, &file, NULL);
  3766. #endif
  3767. #if !defined(NO_CGI)
  3768. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3769. (int)strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3770. path) > 0) {
  3771. if (strcmp(ri->request_method, "POST") &&
  3772. strcmp(ri->request_method, "HEAD") &&
  3773. strcmp(ri->request_method, "GET")) {
  3774. send_http_error(conn, 501, "Not Implemented",
  3775. "Method %s is not implemented", ri->request_method);
  3776. } else {
  3777. handle_cgi_request(conn, path);
  3778. }
  3779. #endif // !NO_CGI
  3780. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  3781. (int)strlen(conn->ctx->config[SSI_EXTENSIONS]),
  3782. path) > 0) {
  3783. handle_ssi_file_request(conn, path);
  3784. } else if (is_not_modified(conn, &file)) {
  3785. send_http_error(conn, 304, "Not Modified", "%s", "");
  3786. } else {
  3787. handle_file_request(conn, path, &file);
  3788. }
  3789. }
  3790. static void close_all_listening_sockets(struct mg_context *ctx) {
  3791. int i;
  3792. for (i = 0; i < ctx->num_listening_sockets; i++) {
  3793. closesocket(ctx->listening_sockets[i].sock);
  3794. }
  3795. free(ctx->listening_sockets);
  3796. }
  3797. static int is_valid_port(unsigned int port) {
  3798. return port > 0 && port < 0xffff;
  3799. }
  3800. // Valid listening port specification is: [ip_address:]port[s]
  3801. // Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  3802. // TODO(lsm): add parsing of the IPv6 address
  3803. static int parse_port_string(const struct vec *vec, struct socket *so) {
  3804. unsigned int a, b, c, d, ch, len, port;
  3805. #if defined(USE_IPV6)
  3806. char buf[100];
  3807. #endif
  3808. // MacOS needs that. If we do not zero it, subsequent bind() will fail.
  3809. // Also, all-zeroes in the socket address means binding to all addresses
  3810. // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
  3811. memset(so, 0, sizeof(*so));
  3812. so->lsa.sin.sin_family = AF_INET;
  3813. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
  3814. // Bind to a specific IPv4 address, e.g. 192.168.1.5:8080
  3815. so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
  3816. so->lsa.sin.sin_port = htons((uint16_t) port);
  3817. #if defined(USE_IPV6)
  3818. } else if (sscanf(vec->ptr, "[%49[^]]]:%d%n", buf, &port, &len) == 2 &&
  3819. inet_pton(AF_INET6, buf, &so->lsa.sin6.sin6_addr)) {
  3820. // IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080
  3821. so->lsa.sin6.sin6_family = AF_INET6;
  3822. so->lsa.sin6.sin6_port = htons((uint16_t) port);
  3823. #endif
  3824. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  3825. // If only port is specified, bind to IPv4, INADDR_ANY
  3826. so->lsa.sin.sin_port = htons((uint16_t) port);
  3827. } else {
  3828. port = len = 0; // Parsing failure. Make port invalid.
  3829. }
  3830. ch = vec->ptr[len]; // Next character after the port number
  3831. so->is_ssl = ch == 's';
  3832. so->ssl_redir = ch == 'r';
  3833. // Make sure the port is valid and vector ends with 's', 'r' or ','
  3834. return is_valid_port(port) &&
  3835. (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  3836. }
  3837. static int set_ports_option(struct mg_context *ctx) {
  3838. const char *list = ctx->config[LISTENING_PORTS];
  3839. int on = 1, success = 1;
  3840. #if defined(USE_IPV6)
  3841. int off = 0;
  3842. #endif
  3843. struct vec vec;
  3844. struct socket so, *ptr;
  3845. while (success && (list = next_option(list, &vec, NULL)) != NULL) {
  3846. if (!parse_port_string(&vec, &so)) {
  3847. mg_cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",
  3848. __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|r]");
  3849. success = 0;
  3850. } else if (so.is_ssl && ctx->ssl_ctx == NULL) {
  3851. mg_cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");
  3852. success = 0;
  3853. } else if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
  3854. INVALID_SOCKET ||
  3855. // On Windows, SO_REUSEADDR is recommended only for
  3856. // broadcast UDP sockets
  3857. setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR,
  3858. (void *) &on, sizeof(on)) != 0 ||
  3859. #if defined(USE_IPV6)
  3860. (so.lsa.sa.sa_family == AF_INET6 &&
  3861. setsockopt(so.sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *) &off,
  3862. sizeof(off)) != 0) ||
  3863. #endif
  3864. bind(so.sock, &so.lsa.sa, so.lsa.sa.sa_family == AF_INET ?
  3865. sizeof(so.lsa.sin) : sizeof(so.lsa)) != 0 ||
  3866. listen(so.sock, SOMAXCONN) != 0) {
  3867. mg_cry(fc(ctx), "%s: cannot bind to %.*s: %d (%s)", __func__,
  3868. (int) vec.len, vec.ptr, ERRNO, strerror(errno));
  3869. closesocket(so.sock);
  3870. success = 0;
  3871. } else if ((ptr = (struct socket *) realloc(ctx->listening_sockets,
  3872. (ctx->num_listening_sockets + 1) *
  3873. sizeof(ctx->listening_sockets[0]))) == NULL) {
  3874. closesocket(so.sock);
  3875. success = 0;
  3876. } else {
  3877. set_close_on_exec(so.sock);
  3878. ctx->listening_sockets = ptr;
  3879. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  3880. ctx->num_listening_sockets++;
  3881. }
  3882. }
  3883. if (!success) {
  3884. close_all_listening_sockets(ctx);
  3885. }
  3886. return success;
  3887. }
  3888. static void log_header(const struct mg_connection *conn, const char *header,
  3889. FILE *fp) {
  3890. const char *header_value;
  3891. if ((header_value = mg_get_header(conn, header)) == NULL) {
  3892. (void) fprintf(fp, "%s", " -");
  3893. } else {
  3894. (void) fprintf(fp, " \"%s\"", header_value);
  3895. }
  3896. }
  3897. static void log_access(const struct mg_connection *conn) {
  3898. const struct mg_request_info *ri;
  3899. FILE *fp;
  3900. char date[64], src_addr[IP_ADDR_STR_LEN];
  3901. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ? NULL :
  3902. fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  3903. if (fp == NULL)
  3904. return;
  3905. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",
  3906. localtime(&conn->birth_time));
  3907. ri = &conn->request_info;
  3908. flockfile(fp);
  3909. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3910. fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
  3911. src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,
  3912. ri->request_method ? ri->request_method : "-",
  3913. ri->uri ? ri->uri : "-", ri->http_version,
  3914. conn->status_code, conn->num_bytes_sent);
  3915. log_header(conn, "Referer", fp);
  3916. log_header(conn, "User-Agent", fp);
  3917. fputc('\n', fp);
  3918. fflush(fp);
  3919. funlockfile(fp);
  3920. fclose(fp);
  3921. }
  3922. // Verify given socket address against the ACL.
  3923. // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  3924. static int check_acl(struct mg_context *ctx, uint32_t remote_ip) {
  3925. int allowed, flag;
  3926. uint32_t net, mask;
  3927. struct vec vec;
  3928. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  3929. // If any ACL is set, deny by default
  3930. allowed = list == NULL ? '+' : '-';
  3931. while ((list = next_option(list, &vec, NULL)) != NULL) {
  3932. flag = vec.ptr[0];
  3933. if ((flag != '+' && flag != '-') ||
  3934. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  3935. mg_cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  3936. return -1;
  3937. }
  3938. if (net == (remote_ip & mask)) {
  3939. allowed = flag;
  3940. }
  3941. }
  3942. return allowed == '+';
  3943. }
  3944. #if !defined(_WIN32)
  3945. static int set_uid_option(struct mg_context *ctx) {
  3946. struct passwd *pw;
  3947. const char *uid = ctx->config[RUN_AS_USER];
  3948. int success = 0;
  3949. if (uid == NULL) {
  3950. success = 1;
  3951. } else {
  3952. if ((pw = getpwnam(uid)) == NULL) {
  3953. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  3954. } else if (setgid(pw->pw_gid) == -1) {
  3955. mg_cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));
  3956. } else if (setuid(pw->pw_uid) == -1) {
  3957. mg_cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));
  3958. } else {
  3959. success = 1;
  3960. }
  3961. }
  3962. return success;
  3963. }
  3964. #endif // !_WIN32
  3965. #if !defined(NO_SSL)
  3966. static pthread_mutex_t *ssl_mutexes;
  3967. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *)) {
  3968. return (conn->ssl = SSL_new(s)) != NULL &&
  3969. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  3970. func(conn->ssl) == 1;
  3971. }
  3972. // Return OpenSSL error message
  3973. static const char *ssl_error(void) {
  3974. unsigned long err;
  3975. err = ERR_get_error();
  3976. return err == 0 ? "" : ERR_error_string(err, NULL);
  3977. }
  3978. static void ssl_locking_callback(int mode, int mutex_num, const char *file,
  3979. int line) {
  3980. (void) line;
  3981. (void) file;
  3982. if (mode & 1) { // 1 is CRYPTO_LOCK
  3983. (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  3984. } else {
  3985. (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  3986. }
  3987. }
  3988. static unsigned long ssl_id_callback(void) {
  3989. return (unsigned long) pthread_self();
  3990. }
  3991. #if !defined(NO_SSL_DL)
  3992. static int load_dll(struct mg_context *ctx, const char *dll_name,
  3993. struct ssl_func *sw) {
  3994. union {void *p; void (*fp)(void);} u;
  3995. void *dll_handle;
  3996. struct ssl_func *fp;
  3997. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  3998. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  3999. return 0;
  4000. }
  4001. for (fp = sw; fp->name != NULL; fp++) {
  4002. #ifdef _WIN32
  4003. // GetProcAddress() returns pointer to function
  4004. u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
  4005. #else
  4006. // dlsym() on UNIX returns void *. ISO C forbids casts of data pointers to
  4007. // function pointers. We need to use a union to make a cast.
  4008. u.p = dlsym(dll_handle, fp->name);
  4009. #endif // _WIN32
  4010. if (u.fp == NULL) {
  4011. mg_cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);
  4012. return 0;
  4013. } else {
  4014. fp->ptr = u.fp;
  4015. }
  4016. }
  4017. return 1;
  4018. }
  4019. #endif // NO_SSL_DL
  4020. // Dynamically load SSL library. Set up ctx->ssl_ctx pointer.
  4021. static int set_ssl_option(struct mg_context *ctx) {
  4022. int i, size;
  4023. const char *pem;
  4024. // If PEM file is not specified and the init_ssl callback
  4025. // is not specified, skip SSL initialization.
  4026. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL &&
  4027. ctx->callbacks.init_ssl == NULL) {
  4028. return 1;
  4029. }
  4030. #if !defined(NO_SSL_DL)
  4031. if (!load_dll(ctx, SSL_LIB, ssl_sw) ||
  4032. !load_dll(ctx, CRYPTO_LIB, crypto_sw)) {
  4033. return 0;
  4034. }
  4035. #endif // NO_SSL_DL
  4036. // Initialize SSL library
  4037. SSL_library_init();
  4038. SSL_load_error_strings();
  4039. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  4040. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  4041. return 0;
  4042. }
  4043. // If user callback returned non-NULL, that means that user callback has
  4044. // set up certificate itself. In this case, skip sertificate setting.
  4045. if ((ctx->callbacks.init_ssl == NULL ||
  4046. !ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data)) &&
  4047. (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0 ||
  4048. SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
  4049. mg_cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error());
  4050. return 0;
  4051. }
  4052. if (pem != NULL) {
  4053. (void) SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  4054. }
  4055. // Initialize locking callbacks, needed for thread safety.
  4056. // http://www.openssl.org/support/faq.html#PROG1
  4057. size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
  4058. if ((ssl_mutexes = (pthread_mutex_t *) malloc((size_t)size)) == NULL) {
  4059. mg_cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
  4060. return 0;
  4061. }
  4062. for (i = 0; i < CRYPTO_num_locks(); i++) {
  4063. pthread_mutex_init(&ssl_mutexes[i], NULL);
  4064. }
  4065. CRYPTO_set_locking_callback(&ssl_locking_callback);
  4066. CRYPTO_set_id_callback(&ssl_id_callback);
  4067. return 1;
  4068. }
  4069. static void uninitialize_ssl(struct mg_context *ctx) {
  4070. int i;
  4071. if (ctx->ssl_ctx != NULL) {
  4072. CRYPTO_set_locking_callback(NULL);
  4073. for (i = 0; i < CRYPTO_num_locks(); i++) {
  4074. pthread_mutex_destroy(&ssl_mutexes[i]);
  4075. }
  4076. CRYPTO_set_locking_callback(NULL);
  4077. CRYPTO_set_id_callback(NULL);
  4078. }
  4079. }
  4080. #endif // !NO_SSL
  4081. static int set_gpass_option(struct mg_context *ctx) {
  4082. struct file file = STRUCT_FILE_INITIALIZER;
  4083. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  4084. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  4085. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  4086. return 0;
  4087. }
  4088. return 1;
  4089. }
  4090. static int set_acl_option(struct mg_context *ctx) {
  4091. return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;
  4092. }
  4093. static void reset_per_request_attributes(struct mg_connection *conn) {
  4094. conn->path_info = NULL;
  4095. conn->num_bytes_sent = conn->consumed_content = 0;
  4096. conn->status_code = -1;
  4097. conn->must_close = conn->request_len = conn->throttle = 0;
  4098. }
  4099. static void close_socket_gracefully(struct mg_connection *conn) {
  4100. #if defined(_WIN32)
  4101. char buf[MG_BUF_LEN];
  4102. int n;
  4103. #endif
  4104. struct linger linger;
  4105. // Set linger option to avoid socket hanging out after close. This prevent
  4106. // ephemeral port exhaust problem under high QPS.
  4107. linger.l_onoff = 1;
  4108. linger.l_linger = 1;
  4109. setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER,
  4110. (char *) &linger, sizeof(linger));
  4111. // Send FIN to the client
  4112. shutdown(conn->client.sock, SHUT_WR);
  4113. set_non_blocking_mode(conn->client.sock);
  4114. #if defined(_WIN32)
  4115. // Read and discard pending incoming data. If we do not do that and close the
  4116. // socket, the data in the send buffer may be discarded. This
  4117. // behaviour is seen on Windows, when client keeps sending data
  4118. // when server decides to close the connection; then when client
  4119. // does recv() it gets no data back.
  4120. do {
  4121. n = pull(NULL, conn, buf, sizeof(buf));
  4122. } while (n > 0);
  4123. #endif
  4124. // Now we know that our FIN is ACK-ed, safe to close
  4125. closesocket(conn->client.sock);
  4126. }
  4127. static void close_connection(struct mg_connection *conn) {
  4128. mg_lock(conn);
  4129. conn->must_close = 1;
  4130. #ifndef NO_SSL
  4131. if (conn->ssl != NULL) {
  4132. // Run SSL_shutdown twice to ensure completly close SSL connection
  4133. SSL_shutdown(conn->ssl);
  4134. SSL_free(conn->ssl);
  4135. conn->ssl = NULL;
  4136. }
  4137. #endif
  4138. if (conn->client.sock != INVALID_SOCKET) {
  4139. close_socket_gracefully(conn);
  4140. conn->client.sock = INVALID_SOCKET;
  4141. }
  4142. mg_unlock(conn);
  4143. }
  4144. void mg_close_connection(struct mg_connection *conn) {
  4145. #ifndef NO_SSL
  4146. if (conn->client_ssl_ctx != NULL) {
  4147. SSL_CTX_free((SSL_CTX *) conn->client_ssl_ctx);
  4148. }
  4149. #endif
  4150. close_connection(conn);
  4151. (void) pthread_mutex_destroy(&conn->mutex);
  4152. free(conn);
  4153. }
  4154. struct mg_connection *mg_connect(const char *host, int port, int use_ssl,
  4155. char *ebuf, size_t ebuf_len) {
  4156. static struct mg_context fake_ctx;
  4157. struct mg_connection *conn = NULL;
  4158. SOCKET sock;
  4159. if ((sock = conn2(host, port, use_ssl, ebuf, ebuf_len)) == INVALID_SOCKET) {
  4160. } else if ((conn = (struct mg_connection *)
  4161. calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  4162. snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
  4163. closesocket(sock);
  4164. #ifndef NO_SSL
  4165. } else if (use_ssl && (conn->client_ssl_ctx =
  4166. SSL_CTX_new(SSLv23_client_method())) == NULL) {
  4167. snprintf(ebuf, ebuf_len, "SSL_CTX_new error");
  4168. closesocket(sock);
  4169. free(conn);
  4170. conn = NULL;
  4171. #endif // NO_SSL
  4172. } else {
  4173. socklen_t len = sizeof(struct sockaddr);
  4174. conn->buf_size = MAX_REQUEST_SIZE;
  4175. conn->buf = (char *) (conn + 1);
  4176. conn->ctx = &fake_ctx;
  4177. conn->client.sock = sock;
  4178. getsockname(sock, &conn->client.rsa.sa, &len);
  4179. conn->client.is_ssl = use_ssl;
  4180. (void) pthread_mutex_init(&conn->mutex, NULL);
  4181. #ifndef NO_SSL
  4182. if (use_ssl) {
  4183. // SSL_CTX_set_verify call is needed to switch off server certificate
  4184. // checking, which is off by default in OpenSSL and on in yaSSL.
  4185. SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
  4186. sslize(conn, conn->client_ssl_ctx, SSL_connect);
  4187. }
  4188. #endif
  4189. }
  4190. return conn;
  4191. }
  4192. static int is_valid_uri(const char *uri) {
  4193. // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  4194. // URI can be an asterisk (*) or should start with slash.
  4195. return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
  4196. }
  4197. static int getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len) {
  4198. const char *cl;
  4199. ebuf[0] = '\0';
  4200. reset_per_request_attributes(conn);
  4201. conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,
  4202. &conn->data_len);
  4203. assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  4204. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  4205. snprintf(ebuf, ebuf_len, "%s", "Request Too Large");
  4206. } else if (conn->request_len <= 0) {
  4207. snprintf(ebuf, ebuf_len, "%s", "Client closed connection");
  4208. } else if (parse_http_message(conn->buf, conn->buf_size,
  4209. &conn->request_info) <= 0) {
  4210. snprintf(ebuf, ebuf_len, "Bad request: [%.*s]", conn->data_len, conn->buf);
  4211. } else {
  4212. // Request is valid
  4213. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  4214. conn->content_len = strtoll(cl, NULL, 10);
  4215. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  4216. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  4217. conn->content_len = -1;
  4218. } else {
  4219. conn->content_len = 0;
  4220. }
  4221. conn->birth_time = time(NULL);
  4222. }
  4223. return ebuf[0] == '\0';
  4224. }
  4225. struct mg_connection *mg_download(const char *host, int port, int use_ssl,
  4226. char *ebuf, size_t ebuf_len,
  4227. const char *fmt, ...) {
  4228. struct mg_connection *conn;
  4229. va_list ap;
  4230. va_start(ap, fmt);
  4231. ebuf[0] = '\0';
  4232. if ((conn = mg_connect(host, port, use_ssl, ebuf, ebuf_len)) == NULL) {
  4233. } else if (mg_vprintf(conn, fmt, ap) <= 0) {
  4234. snprintf(ebuf, ebuf_len, "%s", "Error sending request");
  4235. } else {
  4236. getreq(conn, ebuf, ebuf_len);
  4237. }
  4238. if (ebuf[0] != '\0' && conn != NULL) {
  4239. mg_close_connection(conn);
  4240. conn = NULL;
  4241. }
  4242. return conn;
  4243. }
  4244. static void process_new_connection(struct mg_connection *conn) {
  4245. struct mg_request_info *ri = &conn->request_info;
  4246. int keep_alive_enabled, keep_alive, discard_len;
  4247. char ebuf[100];
  4248. keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  4249. keep_alive = 0;
  4250. // Important: on new connection, reset the receiving buffer. Credit goes
  4251. // to crule42.
  4252. conn->data_len = 0;
  4253. do {
  4254. if (!getreq(conn, ebuf, sizeof(ebuf))) {
  4255. send_http_error(conn, 500, "Server Error", "%s", ebuf);
  4256. conn->must_close = 1;
  4257. } else if (!is_valid_uri(conn->request_info.uri)) {
  4258. snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);
  4259. send_http_error(conn, 400, "Bad Request", "%s", ebuf);
  4260. } else if (strcmp(ri->http_version, "1.0") &&
  4261. strcmp(ri->http_version, "1.1")) {
  4262. snprintf(ebuf, sizeof(ebuf), "Bad HTTP version: [%s]", ri->http_version);
  4263. send_http_error(conn, 505, "Bad HTTP version", "%s", ebuf);
  4264. }
  4265. if (ebuf[0] == '\0') {
  4266. handle_request(conn);
  4267. if (conn->ctx->callbacks.end_request != NULL) {
  4268. conn->ctx->callbacks.end_request(conn, conn->status_code);
  4269. }
  4270. log_access(conn);
  4271. }
  4272. if (ri->remote_user != NULL) {
  4273. free((void *) ri->remote_user);
  4274. // Important! When having connections with and without auth
  4275. // would cause double free and then crash
  4276. ri->remote_user = NULL;
  4277. }
  4278. // NOTE(lsm): order is important here. should_keep_alive() call
  4279. // is using parsed request, which will be invalid after memmove's below.
  4280. // Therefore, memorize should_keep_alive() result now for later use
  4281. // in loop exit condition.
  4282. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
  4283. conn->content_len >= 0 && should_keep_alive(conn);
  4284. // Discard all buffered data for this request
  4285. discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
  4286. conn->request_len + conn->content_len < (int64_t) conn->data_len ?
  4287. (int) (conn->request_len + conn->content_len) : conn->data_len;
  4288. assert(discard_len >= 0);
  4289. memmove(conn->buf, conn->buf + discard_len, conn->data_len - discard_len);
  4290. conn->data_len -= discard_len;
  4291. assert(conn->data_len >= 0);
  4292. assert(conn->data_len <= conn->buf_size);
  4293. } while (keep_alive);
  4294. }
  4295. // Worker threads take accepted socket from the queue
  4296. static int consume_socket(struct mg_context *ctx, struct socket *sp) {
  4297. (void) pthread_mutex_lock(&ctx->mutex);
  4298. DEBUG_TRACE(("going idle"));
  4299. // If the queue is empty, wait. We're idle at this point.
  4300. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  4301. pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
  4302. }
  4303. // If we're stopping, sq_head may be equal to sq_tail.
  4304. if (ctx->sq_head > ctx->sq_tail) {
  4305. // Copy socket from the queue and increment tail
  4306. *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
  4307. ctx->sq_tail++;
  4308. DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));
  4309. // Wrap pointers if needed
  4310. while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
  4311. ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
  4312. ctx->sq_head -= ARRAY_SIZE(ctx->queue);
  4313. }
  4314. }
  4315. (void) pthread_cond_signal(&ctx->sq_empty);
  4316. (void) pthread_mutex_unlock(&ctx->mutex);
  4317. return !ctx->stop_flag;
  4318. }
  4319. static void *worker_thread(void *thread_func_param) {
  4320. struct mg_context *ctx = (struct mg_context *) thread_func_param;
  4321. struct mg_connection *conn;
  4322. conn = (struct mg_connection *) calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  4323. if (conn == NULL) {
  4324. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  4325. } else {
  4326. conn->buf_size = MAX_REQUEST_SIZE;
  4327. conn->buf = (char *) (conn + 1);
  4328. conn->ctx = ctx;
  4329. conn->request_info.user_data = ctx->user_data;
  4330. // Allocate a mutex for this connection to allow communication both
  4331. // within the request handler and from elsewhere in the application
  4332. (void) pthread_mutex_init(&conn->mutex, NULL);
  4333. // Call consume_socket() even when ctx->stop_flag > 0, to let it signal
  4334. // sq_empty condvar to wake up the master waiting in produce_socket()
  4335. while (consume_socket(ctx, &conn->client)) {
  4336. conn->birth_time = time(NULL);
  4337. // Fill in IP, port info early so even if SSL setup below fails,
  4338. // error handler would have the corresponding info.
  4339. // Thanks to Johannes Winkelmann for the patch.
  4340. // TODO(lsm): Fix IPv6 case
  4341. conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);
  4342. memcpy(&conn->request_info.remote_ip,
  4343. &conn->client.rsa.sin.sin_addr.s_addr, 4);
  4344. conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
  4345. conn->request_info.is_ssl = conn->client.is_ssl;
  4346. if (!conn->client.is_ssl
  4347. #ifndef NO_SSL
  4348. || sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  4349. #endif
  4350. ) {
  4351. process_new_connection(conn);
  4352. }
  4353. close_connection(conn);
  4354. }
  4355. free(conn);
  4356. }
  4357. // Signal master that we're done with connection and exiting
  4358. (void) pthread_mutex_lock(&ctx->mutex);
  4359. ctx->num_threads--;
  4360. (void) pthread_cond_signal(&ctx->cond);
  4361. assert(ctx->num_threads >= 0);
  4362. (void) pthread_mutex_unlock(&ctx->mutex);
  4363. DEBUG_TRACE(("exiting"));
  4364. return NULL;
  4365. }
  4366. // Master thread adds accepted socket to a queue
  4367. static void produce_socket(struct mg_context *ctx, const struct socket *sp) {
  4368. (void) pthread_mutex_lock(&ctx->mutex);
  4369. // If the queue is full, wait
  4370. while (ctx->stop_flag == 0 &&
  4371. ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {
  4372. (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
  4373. }
  4374. if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {
  4375. // Copy socket to the queue and increment head
  4376. ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
  4377. ctx->sq_head++;
  4378. DEBUG_TRACE(("queued socket %d", sp->sock));
  4379. }
  4380. (void) pthread_cond_signal(&ctx->sq_full);
  4381. (void) pthread_mutex_unlock(&ctx->mutex);
  4382. }
  4383. static int set_sock_timeout(SOCKET sock, int milliseconds) {
  4384. #ifdef _WIN32
  4385. DWORD t = milliseconds;
  4386. #else
  4387. struct timeval t;
  4388. t.tv_sec = milliseconds / 1000;
  4389. t.tv_usec = (milliseconds * 1000) % 1000000;
  4390. #endif
  4391. return setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (void *) &t, sizeof(t)) ||
  4392. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (void *) &t, sizeof(t));
  4393. }
  4394. static void accept_new_connection(const struct socket *listener,
  4395. struct mg_context *ctx) {
  4396. struct socket so;
  4397. char src_addr[IP_ADDR_STR_LEN];
  4398. socklen_t len = sizeof(so.rsa);
  4399. int on = 1;
  4400. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) {
  4401. } else if (!check_acl(ctx, ntohl(* (uint32_t *) &so.rsa.sin.sin_addr))) {
  4402. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  4403. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  4404. closesocket(so.sock);
  4405. } else {
  4406. // Put so socket structure into the queue
  4407. DEBUG_TRACE(("Accepted socket %d", (int) so.sock));
  4408. set_close_on_exec(so.sock);
  4409. so.is_ssl = listener->is_ssl;
  4410. so.ssl_redir = listener->ssl_redir;
  4411. getsockname(so.sock, &so.lsa.sa, &len);
  4412. // Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  4413. // is enabled, and client resets the connection, server won't get
  4414. // TCP FIN or RST and will keep the connection open forever. With TCP
  4415. // keep-alive, next keep-alive handshake will figure out that the client
  4416. // is down and will close the server end.
  4417. // Thanks to Igor Klopov who suggested the patch.
  4418. setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &on, sizeof(on));
  4419. set_sock_timeout(so.sock, atoi(ctx->config[REQUEST_TIMEOUT]));
  4420. produce_socket(ctx, &so);
  4421. }
  4422. }
  4423. static void *master_thread(void *thread_func_param) {
  4424. struct mg_context *ctx = (struct mg_context *) thread_func_param;
  4425. struct pollfd *pfd;
  4426. int i;
  4427. // Increase priority of the master thread
  4428. #if defined(_WIN32)
  4429. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  4430. #endif
  4431. #if defined(ISSUE_317)
  4432. struct sched_param sched_param;
  4433. sched_param.sched_priority = sched_get_priority_max(SCHED_RR);
  4434. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  4435. #endif
  4436. pfd = (struct pollfd *) calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  4437. while (pfd != NULL && ctx->stop_flag == 0) {
  4438. for (i = 0; i < ctx->num_listening_sockets; i++) {
  4439. pfd[i].fd = ctx->listening_sockets[i].sock;
  4440. pfd[i].events = POLLIN;
  4441. }
  4442. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  4443. for (i = 0; i < ctx->num_listening_sockets; i++) {
  4444. // NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  4445. // successfull poll, and POLLIN is defined as (POLLRDNORM | POLLRDBAND)
  4446. // Therefore, we're checking pfd[i].revents & POLLIN, not
  4447. // pfd[i].revents == POLLIN.
  4448. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  4449. accept_new_connection(&ctx->listening_sockets[i], ctx);
  4450. }
  4451. }
  4452. }
  4453. }
  4454. free(pfd);
  4455. DEBUG_TRACE(("stopping workers"));
  4456. // Stop signal received: somebody called mg_stop. Quit.
  4457. close_all_listening_sockets(ctx);
  4458. // Wakeup workers that are waiting for connections to handle.
  4459. pthread_cond_broadcast(&ctx->sq_full);
  4460. // Wait until all threads finish
  4461. (void) pthread_mutex_lock(&ctx->mutex);
  4462. while (ctx->num_threads > 0) {
  4463. (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
  4464. }
  4465. (void) pthread_mutex_unlock(&ctx->mutex);
  4466. // All threads exited, no sync is needed. Destroy mutex and condvars
  4467. (void) pthread_mutex_destroy(&ctx->mutex);
  4468. (void) pthread_cond_destroy(&ctx->cond);
  4469. (void) pthread_cond_destroy(&ctx->sq_empty);
  4470. (void) pthread_cond_destroy(&ctx->sq_full);
  4471. #if !defined(NO_SSL)
  4472. uninitialize_ssl(ctx);
  4473. #endif
  4474. DEBUG_TRACE(("exiting"));
  4475. // Signal mg_stop() that we're done.
  4476. // WARNING: This must be the very last thing this
  4477. // thread does, as ctx becomes invalid after this line.
  4478. ctx->stop_flag = 2;
  4479. return NULL;
  4480. }
  4481. static void free_context(struct mg_context *ctx) {
  4482. int i;
  4483. if (ctx == NULL)
  4484. return;
  4485. // Deallocate config parameters
  4486. for (i = 0; i < NUM_OPTIONS; i++) {
  4487. if (ctx->config[i] != NULL)
  4488. #ifdef WIN32
  4489. #pragma warning(suppress: 6001)
  4490. #endif
  4491. free(ctx->config[i]);
  4492. }
  4493. #ifndef NO_SSL
  4494. // Deallocate SSL context
  4495. if (ctx->ssl_ctx != NULL) {
  4496. SSL_CTX_free(ctx->ssl_ctx);
  4497. }
  4498. if (ssl_mutexes != NULL) {
  4499. free(ssl_mutexes);
  4500. ssl_mutexes = NULL;
  4501. }
  4502. #endif // !NO_SSL
  4503. // Deallocate context itself
  4504. free(ctx);
  4505. }
  4506. void mg_stop(struct mg_context *ctx) {
  4507. ctx->stop_flag = 1;
  4508. // Wait until mg_fini() stops
  4509. while (ctx->stop_flag != 2) {
  4510. (void) mg_sleep(10);
  4511. }
  4512. free_context(ctx);
  4513. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  4514. (void) WSACleanup();
  4515. #endif // _WIN32
  4516. }
  4517. struct mg_context *mg_start(const struct mg_callbacks *callbacks,
  4518. void *user_data,
  4519. const char **options) {
  4520. struct mg_context *ctx;
  4521. const char *name, *value, *default_value;
  4522. int i;
  4523. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  4524. WSADATA data;
  4525. WSAStartup(MAKEWORD(2,2), &data);
  4526. #pragma warning(suppress: 28125)
  4527. InitializeCriticalSection(&global_log_file_lock);
  4528. #endif // _WIN32
  4529. // Allocate context and initialize reasonable general case defaults.
  4530. // TODO(lsm): do proper error handling here.
  4531. if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) {
  4532. return NULL;
  4533. }
  4534. ctx->callbacks = *callbacks;
  4535. ctx->user_data = user_data;
  4536. while (options && (name = *options++) != NULL) {
  4537. if ((i = get_option_index(name)) == -1) {
  4538. mg_cry(fc(ctx), "Invalid option: %s", name);
  4539. free_context(ctx);
  4540. return NULL;
  4541. } else if ((value = *options++) == NULL) {
  4542. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  4543. free_context(ctx);
  4544. return NULL;
  4545. }
  4546. if (ctx->config[i] != NULL) {
  4547. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  4548. free(ctx->config[i]);
  4549. }
  4550. ctx->config[i] = mg_strdup(value);
  4551. DEBUG_TRACE(("[%s] -> [%s]", name, value));
  4552. }
  4553. // Set default value if needed
  4554. for (i = 0; config_options[i * 2] != NULL; i++) {
  4555. default_value = config_options[i * 2 + 1];
  4556. if (ctx->config[i] == NULL && default_value != NULL) {
  4557. ctx->config[i] = mg_strdup(default_value);
  4558. }
  4559. }
  4560. // NOTE(lsm): order is important here. SSL certificates must
  4561. // be initialized before listening ports. UID must be set last.
  4562. if (!set_gpass_option(ctx) ||
  4563. #if !defined(NO_SSL)
  4564. !set_ssl_option(ctx) ||
  4565. #endif
  4566. !set_ports_option(ctx) ||
  4567. #if !defined(_WIN32)
  4568. !set_uid_option(ctx) ||
  4569. #endif
  4570. !set_acl_option(ctx)) {
  4571. free_context(ctx);
  4572. return NULL;
  4573. }
  4574. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  4575. // Ignore SIGPIPE signal, so if browser cancels the request, it
  4576. // won't kill the whole process.
  4577. (void) signal(SIGPIPE, SIG_IGN);
  4578. #endif // !_WIN32
  4579. (void) pthread_mutex_init(&ctx->mutex, NULL);
  4580. (void) pthread_cond_init(&ctx->cond, NULL);
  4581. (void) pthread_cond_init(&ctx->sq_empty, NULL);
  4582. (void) pthread_cond_init(&ctx->sq_full, NULL);
  4583. // Start master (listening) thread
  4584. mg_start_thread(master_thread, ctx);
  4585. // Start worker threads
  4586. for (i = 0; i < atoi(ctx->config[NUM_THREADS]); i++) {
  4587. if (mg_start_thread(worker_thread, ctx) != 0) {
  4588. mg_cry(fc(ctx), "Cannot start worker thread: %ld", (long) ERRNO);
  4589. } else {
  4590. ctx->num_threads++;
  4591. }
  4592. }
  4593. return ctx;
  4594. }