mongoose.c 167 KB

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