civetweb.c 274 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014
  1. /* Copyright (c) 2013-2015 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #ifdef __linux__
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(_MSC_VER)
  54. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  55. #pragma warning(disable : 4306)
  56. /* conditional expression is constant: introduced by FD_SET(..) */
  57. #pragma warning(disable : 4127)
  58. /* non-constant aggregate initializer: issued due to missing C99 support */
  59. #pragma warning(disable : 4204)
  60. /* padding added after data member */
  61. #pragma warning(disable : 4820)
  62. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  63. #pragma warning(disable : 4668)
  64. /* no function prototype given: converting '()' to '(void)' */
  65. #pragma warning(disable : 4255)
  66. /* function has been selected for automatic inline expansion */
  67. #pragma warning(disable : 4711)
  68. #endif
  69. /* This code uses static_assert to check some conditions.
  70. * Unfortunately some compilers still do not support it, so we have a
  71. * replacement function here. */
  72. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  73. #define mg_static_assert static_assert
  74. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  75. #define mg_static_assert static_assert
  76. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  77. #define mg_static_assert _Static_assert
  78. #else
  79. char static_assert_replacement[1];
  80. #define mg_static_assert(cond, txt) \
  81. extern char static_assert_replacement[(cond) ? 1 : -1]
  82. #endif
  83. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  84. "int data type size check");
  85. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  86. "pointer data type size check");
  87. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  88. /* mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data
  89. * type size check"); */
  90. /* DTL -- including winsock2.h works better if lean and mean */
  91. #ifndef WIN32_LEAN_AND_MEAN
  92. #define WIN32_LEAN_AND_MEAN
  93. #endif
  94. #if defined(__SYMBIAN32__)
  95. #define NO_SSL /* SSL is not supported */
  96. #define NO_CGI /* CGI is not supported */
  97. #define PATH_MAX FILENAME_MAX
  98. #endif /* __SYMBIAN32__ */
  99. #ifndef IGNORE_UNUSED_RESULT
  100. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  101. #endif
  102. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  103. #include <sys/types.h>
  104. #include <sys/stat.h>
  105. #include <errno.h>
  106. #include <signal.h>
  107. #include <fcntl.h>
  108. #endif /* !_WIN32_WCE */
  109. #ifdef __MACH__
  110. #define CLOCK_MONOTONIC (1)
  111. #define CLOCK_REALTIME (2)
  112. #include <sys/time.h>
  113. #include <mach/clock.h>
  114. #include <mach/mach.h>
  115. #include <mach/mach_time.h>
  116. #include <assert.h>
  117. /* clock_gettime is not implemented on OSX */
  118. int clock_gettime(int clk_id, struct timespec *t)
  119. {
  120. if (clk_id == CLOCK_REALTIME) {
  121. struct timeval now;
  122. int rv = gettimeofday(&now, NULL);
  123. if (rv)
  124. return rv;
  125. t->tv_sec = now.tv_sec;
  126. t->tv_nsec = now.tv_usec * 1000;
  127. return 0;
  128. } else if (clk_id == CLOCK_MONOTONIC) {
  129. static uint64_t start_time = 0;
  130. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  131. uint64_t now = mach_absolute_time();
  132. if (start_time == 0) {
  133. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  134. #if defined(DEBUG)
  135. assert(mach_status == KERN_SUCCESS);
  136. #else
  137. /* appease "unused variable" warning for release builds */
  138. (void)mach_status;
  139. #endif
  140. start_time = now;
  141. }
  142. now =
  143. (uint64_t)((double)(now - start_time) * (double)timebase_ifo.numer /
  144. (double)timebase_ifo.denom);
  145. t->tv_sec = now / 1000000000;
  146. t->tv_nsec = now % 1000000000;
  147. return 0;
  148. }
  149. return -1; /* EINVAL - Clock ID is unknown */
  150. }
  151. #endif
  152. #include <time.h>
  153. #include <stdlib.h>
  154. #include <stdarg.h>
  155. #include <assert.h>
  156. #include <string.h>
  157. #include <ctype.h>
  158. #include <limits.h>
  159. #include <stddef.h>
  160. #include <stdio.h>
  161. #ifndef MAX_WORKER_THREADS
  162. #define MAX_WORKER_THREADS (1024 * 64)
  163. #endif
  164. #ifndef SOCKET_TIMEOUT_QUANTUM
  165. #define SOCKET_TIMEOUT_QUANTUM (10000)
  166. #endif
  167. mg_static_assert(MAX_WORKER_THREADS >= 1,
  168. "worker threads must be a positive number");
  169. #if defined(_WIN32) && !defined(__SYMBIAN32__) /* Windows specific */
  170. #include <windows.h>
  171. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  172. #include <ws2tcpip.h>
  173. typedef const char *SOCK_OPT_TYPE;
  174. #if !defined(PATH_MAX)
  175. #define PATH_MAX (MAX_PATH)
  176. #endif
  177. #if !defined(PATH_MAX)
  178. #define PATH_MAX (4096)
  179. #endif
  180. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  181. #ifndef _IN_PORT_T
  182. #ifndef in_port_t
  183. #define in_port_t u_short
  184. #endif
  185. #endif
  186. #ifndef _WIN32_WCE
  187. #include <process.h>
  188. #include <direct.h>
  189. #include <io.h>
  190. #else /* _WIN32_WCE */
  191. #define NO_CGI /* WinCE has no pipes */
  192. typedef long off_t;
  193. #define errno ((int)(GetLastError()))
  194. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  195. #endif /* _WIN32_WCE */
  196. #define MAKEUQUAD(lo, hi) \
  197. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  198. #define RATE_DIFF (10000000) /* 100 nsecs */
  199. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  200. #define SYS2UNIX_TIME(lo, hi) \
  201. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  202. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  203. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  204. * Also use _strtoui64 on modern M$ compilers */
  205. #if defined(_MSC_VER)
  206. #if (_MSC_VER < 1300)
  207. #define STRX(x) #x
  208. #define STR(x) STRX(x)
  209. #define __func__ __FILE__ ":" STR(__LINE__)
  210. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  211. #define strtoll(x, y, z) (_atoi64(x))
  212. #else
  213. #define __func__ __FUNCTION__
  214. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  215. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  216. #endif
  217. #endif /* _MSC_VER */
  218. #define ERRNO ((int)(GetLastError()))
  219. #define NO_SOCKLEN_T
  220. #define SSL_LIB "ssleay32.dll"
  221. #define CRYPTO_LIB "libeay32.dll"
  222. #define O_NONBLOCK (0)
  223. #ifndef W_OK
  224. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  225. #endif
  226. #if !defined(EWOULDBLOCK)
  227. #define EWOULDBLOCK WSAEWOULDBLOCK
  228. #endif /* !EWOULDBLOCK */
  229. #define _POSIX_
  230. #define INT64_FMT "I64d"
  231. #define WINCDECL __cdecl
  232. #define SHUT_RD (0)
  233. #define SHUT_WR (1)
  234. #define SHUT_BOTH (2)
  235. #define snprintf _snprintf
  236. #define vsnprintf _vsnprintf
  237. #define access _access
  238. #define mg_sleep(x) (Sleep(x))
  239. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  240. #ifndef popen
  241. #define popen(x, y) (_popen(x, y))
  242. #endif
  243. #ifndef pclose
  244. #define pclose(x) (_pclose(x))
  245. #endif
  246. #define close(x) (_close(x))
  247. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  248. #define RTLD_LAZY (0)
  249. #define fseeko(x, y, z) (_lseeki64(_fileno(x), (y), (z)))
  250. #define fdopen(x, y) (_fdopen((x), (y)))
  251. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  252. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  253. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  254. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  255. #define sleep(x) (Sleep((x)*1000))
  256. #define rmdir(x) (_rmdir(x))
  257. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  258. #define USE_TIMERS
  259. #endif
  260. #if !defined(fileno)
  261. #define fileno(x) (_fileno(x))
  262. #endif /* !fileno MINGW #defines fileno */
  263. typedef HANDLE pthread_mutex_t;
  264. typedef DWORD pthread_key_t;
  265. typedef HANDLE pthread_t;
  266. typedef struct {
  267. CRITICAL_SECTION threadIdSec;
  268. int waitingthreadcount; /* The number of threads queued. */
  269. pthread_t *waitingthreadhdls; /* The thread handles. */
  270. } pthread_cond_t;
  271. #ifndef __clockid_t_defined
  272. typedef DWORD clockid_t;
  273. #endif
  274. #ifndef CLOCK_MONOTONIC
  275. #define CLOCK_MONOTONIC (1)
  276. #endif
  277. #ifndef CLOCK_REALTIME
  278. #define CLOCK_REALTIME (2)
  279. #endif
  280. #ifndef _TIMESPEC_DEFINED
  281. struct timespec {
  282. time_t tv_sec; /* seconds */
  283. long tv_nsec; /* nanoseconds */
  284. };
  285. #endif
  286. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  287. static int pthread_mutex_lock(pthread_mutex_t *);
  288. static int pthread_mutex_unlock(pthread_mutex_t *);
  289. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len);
  290. struct file;
  291. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p);
  292. #if defined(HAVE_STDINT)
  293. #include <stdint.h>
  294. #else
  295. typedef unsigned int uint32_t;
  296. typedef unsigned short uint16_t;
  297. typedef unsigned __int64 uint64_t;
  298. typedef __int64 int64_t;
  299. #define INT64_MAX (9223372036854775807)
  300. #endif /* HAVE_STDINT */
  301. /* POSIX dirent interface */
  302. struct dirent {
  303. char d_name[PATH_MAX];
  304. };
  305. typedef struct DIR {
  306. HANDLE handle;
  307. WIN32_FIND_DATAW info;
  308. struct dirent result;
  309. } DIR;
  310. #if defined(_WIN32) && !defined(POLLIN)
  311. #ifndef HAVE_POLL
  312. struct pollfd {
  313. SOCKET fd;
  314. short events;
  315. short revents;
  316. };
  317. #define POLLIN (0x0300)
  318. #endif
  319. #endif
  320. /* Mark required libraries */
  321. #if defined(_MSC_VER)
  322. #pragma comment(lib, "Ws2_32.lib")
  323. #endif
  324. #else /* UNIX specific */
  325. #include <sys/wait.h>
  326. #include <sys/socket.h>
  327. #include <sys/poll.h>
  328. #include <netinet/in.h>
  329. #include <arpa/inet.h>
  330. #include <sys/time.h>
  331. #include <sys/utsname.h>
  332. #include <stdint.h>
  333. #include <inttypes.h>
  334. #include <netdb.h>
  335. typedef const void *SOCK_OPT_TYPE;
  336. #if defined(ANDROID)
  337. typedef unsigned short int in_port_t;
  338. #endif
  339. #include <pwd.h>
  340. #include <unistd.h>
  341. #include <grp.h>
  342. #include <dirent.h>
  343. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  344. #include <dlfcn.h>
  345. #endif
  346. #include <pthread.h>
  347. #if defined(__MACH__)
  348. #define SSL_LIB "libssl.dylib"
  349. #define CRYPTO_LIB "libcrypto.dylib"
  350. #else
  351. #if !defined(SSL_LIB)
  352. #define SSL_LIB "libssl.so"
  353. #endif
  354. #if !defined(CRYPTO_LIB)
  355. #define CRYPTO_LIB "libcrypto.so"
  356. #endif
  357. #endif
  358. #ifndef O_BINARY
  359. #define O_BINARY (0)
  360. #endif /* O_BINARY */
  361. #define closesocket(a) (close(a))
  362. #define mg_mkdir(x, y) (mkdir(x, y))
  363. #define mg_remove(x) (remove(x))
  364. #define mg_sleep(x) (usleep((x)*1000))
  365. #define ERRNO (errno)
  366. #define INVALID_SOCKET (-1)
  367. #define INT64_FMT PRId64
  368. typedef int SOCKET;
  369. #define WINCDECL
  370. #if defined(__hpux)
  371. /* HPUX 11 does not have monotonic, fall back to realtime */
  372. #ifndef CLOCK_MONOTONIC
  373. #define CLOCK_MONOTONIC CLOCK_REALTIME
  374. #endif
  375. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  376. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  377. * the prototypes use int* rather than socklen_t* which matches the
  378. * actual library expectation. When called with the wrong size arg
  379. * accept() returns a zero client inet addr and check_acl() always
  380. * fails. Since socklen_t is widely used below, just force replace
  381. * their typedef with int. - DTL
  382. */
  383. #define socklen_t int
  384. #endif /* hpux */
  385. #endif /* End of Windows and UNIX specific includes */
  386. /* va_copy should always be a macro, C99 and C++11 - DTL */
  387. #ifndef va_copy
  388. #define va_copy(x, y) ((x) = (y))
  389. #endif
  390. #ifdef _WIN32
  391. static CRITICAL_SECTION global_log_file_lock;
  392. static DWORD pthread_self(void) { return GetCurrentThreadId(); }
  393. static int pthread_key_create(
  394. pthread_key_t *key,
  395. void (*_must_be_zero)(
  396. void *) /* destructor function not supported for windows */)
  397. {
  398. assert(_must_be_zero == NULL);
  399. if ((key != 0) && (_must_be_zero == NULL)) {
  400. *key = TlsAlloc();
  401. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  402. }
  403. return -2;
  404. }
  405. static int pthread_key_delete(pthread_key_t key)
  406. {
  407. return TlsFree(key) ? 0 : 1;
  408. }
  409. static int pthread_setspecific(pthread_key_t key, void *value)
  410. {
  411. return TlsSetValue(key, value) ? 0 : 1;
  412. }
  413. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  414. static void *pthread_getspecific(pthread_key_t key) { return TlsGetValue(key); }
  415. #endif
  416. #endif /* _WIN32 */
  417. #include "civetweb.h"
  418. #define PASSWORDS_FILE_NAME ".htpasswd"
  419. #define CGI_ENVIRONMENT_SIZE (4096)
  420. #define MAX_CGI_ENVIR_VARS (64)
  421. #define MG_BUF_LEN (8192)
  422. #ifndef MAX_REQUEST_SIZE
  423. #define MAX_REQUEST_SIZE (16384)
  424. #endif
  425. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  426. "request size length must be a positive number");
  427. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  428. #if !defined(DEBUG_TRACE)
  429. #if defined(DEBUG)
  430. static void DEBUG_TRACE_FUNC(const char *func,
  431. unsigned line,
  432. PRINTF_FORMAT_STRING(const char *fmt),
  433. ...) PRINTF_ARGS(3, 4);
  434. static void
  435. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  436. {
  437. va_list args;
  438. flockfile(stdout);
  439. printf("*** %lu.%p.%s.%u: ",
  440. (unsigned long)time(NULL),
  441. (void *)pthread_self(),
  442. func,
  443. line);
  444. va_start(args, fmt);
  445. vprintf(fmt, args);
  446. va_end(args);
  447. putchar('\n');
  448. fflush(stdout);
  449. funlockfile(stdout);
  450. }
  451. #define DEBUG_TRACE(fmt, ...) \
  452. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  453. #else
  454. #define DEBUG_TRACE(fmt, ...) \
  455. do { \
  456. } while (0)
  457. #endif /* DEBUG */
  458. #endif /* DEBUG_TRACE */
  459. #if defined(MEMORY_DEBUGGING)
  460. unsigned long mg_memory_debug_blockCount = 0;
  461. unsigned long mg_memory_debug_totalMemUsed = 0;
  462. static void *mg_malloc_ex(size_t size, const char *file, unsigned line)
  463. {
  464. void *data = malloc(size + sizeof(size_t));
  465. void *memory = 0;
  466. char mallocStr[256];
  467. if (data) {
  468. *(size_t *)data = size;
  469. mg_memory_debug_totalMemUsed += size;
  470. mg_memory_debug_blockCount++;
  471. memory = (void *)(((char *)data) + sizeof(size_t));
  472. }
  473. sprintf(mallocStr,
  474. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  475. memory,
  476. (unsigned long)size,
  477. mg_memory_debug_totalMemUsed,
  478. mg_memory_debug_blockCount,
  479. file,
  480. line);
  481. #if defined(_WIN32)
  482. OutputDebugStringA(mallocStr);
  483. #else
  484. DEBUG_TRACE("%s", mallocStr);
  485. #endif
  486. return memory;
  487. }
  488. static void *
  489. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  490. {
  491. void *data = mg_malloc_ex(size * count, file, line);
  492. if (data)
  493. memset(data, 0, size);
  494. return data;
  495. }
  496. static void mg_free_ex(void *memory, const char *file, unsigned line)
  497. {
  498. char mallocStr[256];
  499. void *data = (void *)(((char *)memory) - sizeof(size_t));
  500. size_t size;
  501. if (memory) {
  502. size = *(size_t *)data;
  503. mg_memory_debug_totalMemUsed -= size;
  504. mg_memory_debug_blockCount--;
  505. sprintf(mallocStr,
  506. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  507. memory,
  508. (unsigned long)size,
  509. mg_memory_debug_totalMemUsed,
  510. mg_memory_debug_blockCount,
  511. file,
  512. line);
  513. #if defined(_WIN32)
  514. OutputDebugStringA(mallocStr);
  515. #else
  516. DEBUG_TRACE("%s", mallocStr);
  517. #endif
  518. free(data);
  519. }
  520. }
  521. static void *
  522. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  523. {
  524. char mallocStr[256];
  525. void *data;
  526. void *_realloc;
  527. size_t oldsize;
  528. if (newsize) {
  529. if (memory) {
  530. data = (void *)(((char *)memory) - sizeof(size_t));
  531. oldsize = *(size_t *)data;
  532. _realloc = realloc(data, newsize + sizeof(size_t));
  533. if (_realloc) {
  534. data = _realloc;
  535. mg_memory_debug_totalMemUsed -= oldsize;
  536. sprintf(mallocStr,
  537. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  538. memory,
  539. (unsigned long)oldsize,
  540. mg_memory_debug_totalMemUsed,
  541. mg_memory_debug_blockCount,
  542. file,
  543. line);
  544. #if defined(_WIN32)
  545. OutputDebugStringA(mallocStr);
  546. #else
  547. DEBUG_TRACE("%s", mallocStr);
  548. #endif
  549. mg_memory_debug_totalMemUsed += newsize;
  550. sprintf(mallocStr,
  551. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  552. memory,
  553. (unsigned long)newsize,
  554. mg_memory_debug_totalMemUsed,
  555. mg_memory_debug_blockCount,
  556. file,
  557. line);
  558. #if defined(_WIN32)
  559. OutputDebugStringA(mallocStr);
  560. #else
  561. DEBUG_TRACE("%s", mallocStr);
  562. #endif
  563. *(size_t *)data = newsize;
  564. data = (void *)(((char *)data) + sizeof(size_t));
  565. } else {
  566. #if defined(_WIN32)
  567. OutputDebugStringA("MEM: realloc failed\n");
  568. #else
  569. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  570. #endif
  571. return _realloc;
  572. }
  573. } else {
  574. data = mg_malloc_ex(newsize, file, line);
  575. }
  576. } else {
  577. data = 0;
  578. mg_free_ex(memory, file, line);
  579. }
  580. return data;
  581. }
  582. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  583. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  584. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  585. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  586. #else
  587. static __inline void *mg_malloc(size_t a) { return malloc(a); }
  588. static __inline void *mg_calloc(size_t a, size_t b) { return calloc(a, b); }
  589. static __inline void *mg_realloc(void *a, size_t b) { return realloc(a, b); }
  590. static __inline void mg_free(void *a) { free(a); }
  591. #endif
  592. /* This following lines are just meant as a reminder to use the mg-functions
  593. * for memory management */
  594. #ifdef malloc
  595. #undef malloc
  596. #endif
  597. #ifdef calloc
  598. #undef calloc
  599. #endif
  600. #ifdef realloc
  601. #undef realloc
  602. #endif
  603. #ifdef free
  604. #undef free
  605. #endif
  606. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  607. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  608. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  609. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  610. #define MD5_STATIC static
  611. #include "md5.inl"
  612. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  613. #ifdef NO_SOCKLEN_T
  614. typedef int socklen_t;
  615. #endif /* NO_SOCKLEN_T */
  616. #define _DARWIN_UNLIMITED_SELECT
  617. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  618. #if !defined(MSG_NOSIGNAL)
  619. #define MSG_NOSIGNAL (0)
  620. #endif
  621. #if !defined(SOMAXCONN)
  622. #define SOMAXCONN (100)
  623. #endif
  624. /* Size of the accepted socket queue */
  625. #if !defined(MGSQLEN)
  626. #define MGSQLEN (20)
  627. #endif
  628. #if defined(NO_SSL_DL)
  629. #include <openssl/ssl.h>
  630. #include <openssl/err.h>
  631. #else
  632. /* SSL loaded dynamically from DLL.
  633. * I put the prototypes here to be independent from OpenSSL source
  634. * installation. */
  635. typedef struct ssl_st SSL;
  636. typedef struct ssl_method_st SSL_METHOD;
  637. typedef struct ssl_ctx_st SSL_CTX;
  638. struct ssl_func {
  639. const char *name; /* SSL function name */
  640. void (*ptr)(void); /* Function pointer */
  641. };
  642. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  643. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  644. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  645. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  646. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  647. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  648. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  649. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  650. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  651. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  652. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  653. #define SSL_CTX_use_PrivateKey_file \
  654. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  655. #define SSL_CTX_use_certificate_file \
  656. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  657. #define SSL_CTX_set_default_passwd_cb \
  658. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  659. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  660. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  661. #define SSL_CTX_use_certificate_chain_file \
  662. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  663. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  664. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  665. #define SSL_CTX_set_verify (*(void (*)(SSL_CTX *, int, int))ssl_sw[19].ptr)
  666. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  667. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  668. #define CRYPTO_set_locking_callback \
  669. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  670. #define CRYPTO_set_id_callback \
  671. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  672. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  673. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  674. /* set_ssl_option() function updates this array.
  675. * It loads SSL library dynamically and changes NULLs to the actual addresses
  676. * of respective functions. The macros above (like SSL_connect()) are really
  677. * just calling these functions indirectly via the pointer. */
  678. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  679. {"SSL_accept", NULL},
  680. {"SSL_connect", NULL},
  681. {"SSL_read", NULL},
  682. {"SSL_write", NULL},
  683. {"SSL_get_error", NULL},
  684. {"SSL_set_fd", NULL},
  685. {"SSL_new", NULL},
  686. {"SSL_CTX_new", NULL},
  687. {"SSLv23_server_method", NULL},
  688. {"SSL_library_init", NULL},
  689. {"SSL_CTX_use_PrivateKey_file", NULL},
  690. {"SSL_CTX_use_certificate_file", NULL},
  691. {"SSL_CTX_set_default_passwd_cb", NULL},
  692. {"SSL_CTX_free", NULL},
  693. {"SSL_load_error_strings", NULL},
  694. {"SSL_CTX_use_certificate_chain_file", NULL},
  695. {"SSLv23_client_method", NULL},
  696. {"SSL_pending", NULL},
  697. {"SSL_CTX_set_verify", NULL},
  698. {"SSL_shutdown", NULL},
  699. {NULL, NULL}};
  700. /* Similar array as ssl_sw. These functions could be located in different
  701. * lib. */
  702. #if !defined(NO_SSL)
  703. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  704. {"CRYPTO_set_locking_callback", NULL},
  705. {"CRYPTO_set_id_callback", NULL},
  706. {"ERR_get_error", NULL},
  707. {"ERR_error_string", NULL},
  708. {NULL, NULL}};
  709. #endif /* NO_SSL */
  710. #endif /* NO_SSL_DL */
  711. static const char *month_names[] = {"Jan",
  712. "Feb",
  713. "Mar",
  714. "Apr",
  715. "May",
  716. "Jun",
  717. "Jul",
  718. "Aug",
  719. "Sep",
  720. "Oct",
  721. "Nov",
  722. "Dec"};
  723. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  724. * union u. */
  725. union usa {
  726. struct sockaddr sa;
  727. struct sockaddr_in sin;
  728. #if defined(USE_IPV6)
  729. struct sockaddr_in6 sin6;
  730. #endif
  731. };
  732. /* Describes a string (chunk of memory). */
  733. struct vec {
  734. const char *ptr;
  735. size_t len;
  736. };
  737. struct file {
  738. int is_directory;
  739. time_t modification_time;
  740. uint64_t size;
  741. FILE *fp;
  742. const char *membuf; /* Non-NULL if file data is in memory */
  743. /* set to 1 if the content is gzipped
  744. * in which case we need a content-encoding: gzip header */
  745. int gzipped;
  746. };
  747. #define STRUCT_FILE_INITIALIZER \
  748. { \
  749. 0, 0, 0, NULL, NULL, 0 \
  750. }
  751. /* Describes listening socket, or socket which was accept()-ed by the master
  752. * thread and queued for future handling by the worker thread. */
  753. struct socket {
  754. SOCKET sock; /* Listening socket */
  755. union usa lsa; /* Local socket address */
  756. union usa rsa; /* Remote socket address */
  757. unsigned char is_ssl; /* Is port SSL-ed */
  758. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  759. * port */
  760. };
  761. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  762. enum {
  763. CGI_EXTENSIONS,
  764. CGI_ENVIRONMENT,
  765. PUT_DELETE_PASSWORDS_FILE,
  766. CGI_INTERPRETER,
  767. PROTECT_URI,
  768. AUTHENTICATION_DOMAIN,
  769. SSI_EXTENSIONS,
  770. THROTTLE,
  771. ACCESS_LOG_FILE,
  772. ENABLE_DIRECTORY_LISTING,
  773. ERROR_LOG_FILE,
  774. GLOBAL_PASSWORDS_FILE,
  775. INDEX_FILES,
  776. ENABLE_KEEP_ALIVE,
  777. ACCESS_CONTROL_LIST,
  778. EXTRA_MIME_TYPES,
  779. LISTENING_PORTS,
  780. DOCUMENT_ROOT,
  781. SSL_CERTIFICATE,
  782. NUM_THREADS,
  783. RUN_AS_USER,
  784. REWRITE,
  785. HIDE_FILES,
  786. REQUEST_TIMEOUT,
  787. #if defined(USE_WEBSOCKET)
  788. WEBSOCKET_TIMEOUT,
  789. #endif
  790. DECODE_URL,
  791. #if defined(USE_LUA)
  792. LUA_PRELOAD_FILE,
  793. LUA_SCRIPT_EXTENSIONS,
  794. LUA_SERVER_PAGE_EXTENSIONS,
  795. #endif
  796. #if defined(USE_WEBSOCKET)
  797. WEBSOCKET_ROOT,
  798. #endif
  799. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  800. LUA_WEBSOCKET_EXTENSIONS,
  801. #endif
  802. ACCESS_CONTROL_ALLOW_ORIGIN,
  803. ERROR_PAGES,
  804. NUM_OPTIONS
  805. };
  806. /* Config option name, config types, default value */
  807. static struct mg_option config_options[] = {
  808. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  809. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  810. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  811. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  812. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  813. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  814. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  815. {"throttle", CONFIG_TYPE_STRING, NULL},
  816. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  817. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  818. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  819. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  820. {"index_files",
  821. CONFIG_TYPE_STRING,
  822. #ifdef USE_LUA
  823. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  824. "index.shtml,index.php"},
  825. #else
  826. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  827. #endif
  828. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  829. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  830. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  831. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  832. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  833. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  834. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  835. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  836. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  837. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  838. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  839. #if defined(USE_WEBSOCKET)
  840. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  841. #endif
  842. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  843. #if defined(USE_LUA)
  844. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  845. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  846. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  847. #endif
  848. #if defined(USE_WEBSOCKET)
  849. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  850. #endif
  851. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  852. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  853. #endif
  854. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  855. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  856. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  857. /* Check if the config_options and the corresponding enum have compatible
  858. * sizes. */
  859. mg_static_assert((sizeof(config_options) / sizeof(config_options[0])) ==
  860. (NUM_OPTIONS + 1),
  861. "config_options and enum not sync");
  862. struct mg_request_handler_info {
  863. /* Name/Pattern of the URI. */
  864. char *uri;
  865. size_t uri_len;
  866. /* URI type: ws/wss (websocket) or http/https (web page). */
  867. int is_websocket_handler;
  868. /* Handler for http/https requests. */
  869. mg_request_handler handler;
  870. /* Handler for ws/wss (websocket) requests. */
  871. mg_websocket_connect_handler connect_handler;
  872. mg_websocket_ready_handler ready_handler;
  873. mg_websocket_data_handler data_handler;
  874. mg_websocket_close_handler close_handler;
  875. /* User supplied argument for the handler function. */
  876. void *cbdata;
  877. /* next request handler in a linked list */
  878. struct mg_request_handler_info *next;
  879. };
  880. struct mg_context {
  881. volatile int stop_flag; /* Should we stop event loop */
  882. SSL_CTX *ssl_ctx; /* SSL context */
  883. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  884. struct mg_callbacks callbacks; /* User-defined callback function */
  885. void *user_data; /* User-defined data */
  886. int context_type; /* 1 = server context, 2 = client context */
  887. struct socket *listening_sockets;
  888. in_port_t *listening_ports;
  889. unsigned int num_listening_sockets;
  890. volatile int num_threads; /* Number of threads */
  891. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  892. pthread_cond_t thread_cond; /* Condvar for tracking workers terminations */
  893. struct socket queue[MGSQLEN]; /* Accepted sockets */
  894. volatile int sq_head; /* Head of the socket queue */
  895. volatile int sq_tail; /* Tail of the socket queue */
  896. pthread_cond_t sq_full; /* Signaled when socket is produced */
  897. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  898. pthread_t masterthreadid; /* The master thread ID */
  899. unsigned int workerthreadcount; /* The amount of worker threads. */
  900. pthread_t *workerthreadids; /* The worker thread IDs */
  901. unsigned long start_time; /* Server start time, used for authentication */
  902. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  903. unsigned long nonce_count; /* Used nonces, used for authentication */
  904. char *systemName; /* What operating system is running */
  905. /* linked list of uri handlers */
  906. struct mg_request_handler_info *request_handlers;
  907. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  908. /* linked list of shared lua websockets */
  909. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  910. #endif
  911. #ifdef USE_TIMERS
  912. struct ttimers *timers;
  913. #endif
  914. };
  915. struct mg_connection {
  916. struct mg_request_info request_info;
  917. struct mg_context *ctx;
  918. SSL *ssl; /* SSL descriptor */
  919. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  920. struct socket client; /* Connected client */
  921. time_t conn_birth_time; /* Time (wall clock) when connection was
  922. * established */
  923. struct timespec req_time; /* Time (since system start) when the request
  924. * was received */
  925. int64_t num_bytes_sent; /* Total bytes sent to client */
  926. int64_t content_len; /* Content-Length header value */
  927. int64_t consumed_content; /* How many bytes of content have been read */
  928. int is_chunked; /* Transfer-encoding is chunked: 0=no, 1=yes:
  929. * data available, 2: all data read */
  930. size_t chunk_remainder; /* Unread data from the last chunk */
  931. char *buf; /* Buffer for received data */
  932. char *path_info; /* PATH_INFO part of the URL */
  933. int must_close; /* 1 if connection must be closed */
  934. int in_error_handler; /* 1 if in handler for user defined error
  935. * pages */
  936. int buf_size; /* Buffer size */
  937. int request_len; /* Size of the request + headers in a buffer */
  938. int data_len; /* Total size of data in a buffer */
  939. int status_code; /* HTTP reply status code, e.g. 200 */
  940. int throttle; /* Throttling, bytes/sec. <= 0 means no
  941. * throttle */
  942. time_t last_throttle_time; /* Last time throttled data was sent */
  943. int64_t last_throttle_bytes; /* Bytes sent this second */
  944. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  945. * atomic transmissions for websockets */
  946. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  947. void *lua_websocket_state; /* Lua_State for a websocket connection */
  948. #endif
  949. };
  950. static pthread_key_t sTlsKey; /* Thread local storage index */
  951. static int sTlsInit = 0;
  952. struct mg_workerTLS {
  953. int is_master;
  954. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  955. HANDLE pthread_cond_helper_mutex;
  956. #endif
  957. };
  958. /* Directory entry */
  959. struct de {
  960. struct mg_connection *conn;
  961. char *file_name;
  962. struct file file;
  963. };
  964. #if defined(USE_WEBSOCKET)
  965. static int is_websocket_protocol(const struct mg_connection *conn);
  966. #else
  967. #define is_websocket_protocol(conn) (0)
  968. #endif
  969. static int mg_atomic_inc(volatile int *addr)
  970. {
  971. int ret;
  972. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  973. /* Depending on the SDK, this function uses either
  974. * (volatile unsigned int *) or (volatile LONG *),
  975. * so whatever you use, the other SDK is likely to raise a warning. */
  976. ret = InterlockedIncrement((volatile long *)addr);
  977. #elif defined(__GNUC__)
  978. ret = __sync_add_and_fetch(addr, 1);
  979. #else
  980. ret = (++(*addr));
  981. #endif
  982. return ret;
  983. }
  984. static int mg_atomic_dec(volatile int *addr)
  985. {
  986. int ret;
  987. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  988. /* Depending on the SDK, this function uses either
  989. * (volatile unsigned int *) or (volatile LONG *),
  990. * so whatever you use, the other SDK is likely to raise a warning. */
  991. ret = InterlockedDecrement((volatile long *)addr);
  992. #elif defined(__GNUC__)
  993. ret = __sync_sub_and_fetch(addr, 1);
  994. #else
  995. ret = (--(*addr));
  996. #endif
  997. return ret;
  998. }
  999. #if !defined(NO_THREAD_NAME)
  1000. #if defined(_WIN32) && defined(_MSC_VER)
  1001. /* Set the thread name for debugging purposes in Visual Studio
  1002. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1003. */
  1004. #pragma pack(push, 8)
  1005. typedef struct tagTHREADNAME_INFO {
  1006. DWORD dwType; /* Must be 0x1000. */
  1007. LPCSTR szName; /* Pointer to name (in user addr space). */
  1008. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1009. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1010. } THREADNAME_INFO;
  1011. #pragma pack(pop)
  1012. #elif defined(__linux__)
  1013. #include <sys/prctl.h>
  1014. #endif
  1015. static void mg_set_thread_name(const char *name)
  1016. {
  1017. char threadName[16]; /* Max. thread length in Linux/OSX/.. */
  1018. /* TODO (low): use strcpy and strcat instad of snprintf, use server name,
  1019. * don't
  1020. * return */
  1021. if (snprintf(threadName, sizeof(threadName), "civetweb-%s", name) < 0)
  1022. return;
  1023. threadName[sizeof(threadName) - 1] = 0;
  1024. #if defined(_WIN32)
  1025. #if defined(_MSC_VER)
  1026. /* Windows and Visual Studio Compiler */
  1027. __try
  1028. {
  1029. THREADNAME_INFO info;
  1030. info.dwType = 0x1000;
  1031. info.szName = threadName;
  1032. info.dwThreadID = ~0U;
  1033. info.dwFlags = 0;
  1034. RaiseException(0x406D1388,
  1035. 0,
  1036. sizeof(info) / sizeof(ULONG_PTR),
  1037. (ULONG_PTR *)&info);
  1038. }
  1039. __except(EXCEPTION_EXECUTE_HANDLER) {}
  1040. #elif defined(__MINGW32__)
  1041. /* No option known to set thread name for MinGW */
  1042. ;
  1043. #endif
  1044. #elif defined(__linux__)
  1045. /* Linux */
  1046. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1047. #elif defined(__APPLE__) || defined(__MACH__)
  1048. /* OS X (TODO: test) */
  1049. (void)pthread_setname_np(threadName);
  1050. #elif defined(BSD) || defined(__FreeBSD__) || defined(__OpenBSD__)
  1051. /* BSD (TODO: test) */
  1052. pthread_set_name_np(pthread_self(), threadName);
  1053. #elif defined(__AIX__) || defined(_AIX) || defined(__hpux) || defined(__sun)
  1054. /* pthread_set_name_np seems to be missing on AIX, hpux, sun, ... */
  1055. #else
  1056. /* POSIX */
  1057. (void)pthread_setname_np(pthread_self(), threadName);
  1058. #endif
  1059. }
  1060. #else /* !defined(NO_THREAD_NAME) */
  1061. void mg_set_thread_name(const char *threadName) {}
  1062. #endif
  1063. #if defined(MG_LEGACY_INTERFACE)
  1064. const char **mg_get_valid_option_names(void)
  1065. {
  1066. static const char *
  1067. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1068. int i;
  1069. for (i = 0; config_options[i].name != NULL; i++) {
  1070. data[i * 2] = config_options[i].name;
  1071. data[i * 2 + 1] = config_options[i].default_value;
  1072. }
  1073. return data;
  1074. }
  1075. #endif
  1076. const struct mg_option *mg_get_valid_options(void) { return config_options; }
  1077. static int is_file_in_memory(struct mg_connection *conn,
  1078. const char *path,
  1079. struct file *filep)
  1080. {
  1081. size_t size = 0;
  1082. if (!conn || !filep)
  1083. return 0;
  1084. if ((filep->membuf =
  1085. conn->ctx->callbacks.open_file == NULL
  1086. ? NULL
  1087. : conn->ctx->callbacks.open_file(conn, path, &size)) != NULL) {
  1088. /* NOTE: override filep->size only on success. Otherwise, it might
  1089. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1090. filep->size = size;
  1091. }
  1092. return filep->membuf != NULL;
  1093. }
  1094. static int is_file_opened(const struct file *filep)
  1095. {
  1096. if (!filep) {
  1097. return 0;
  1098. }
  1099. return filep->membuf != NULL || filep->fp != NULL;
  1100. }
  1101. static int mg_fopen(struct mg_connection *conn,
  1102. const char *path,
  1103. const char *mode,
  1104. struct file *filep)
  1105. {
  1106. if (!filep) {
  1107. return 0;
  1108. }
  1109. if (!is_file_in_memory(conn, path, filep)) {
  1110. #ifdef _WIN32
  1111. wchar_t wbuf[PATH_MAX], wmode[20];
  1112. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1113. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1114. filep->fp = _wfopen(wbuf, wmode);
  1115. #else
  1116. filep->fp = fopen(path, mode);
  1117. #endif
  1118. }
  1119. return is_file_opened(filep);
  1120. }
  1121. static void mg_fclose(struct file *filep)
  1122. {
  1123. if (filep != NULL && filep->fp != NULL) {
  1124. fclose(filep->fp);
  1125. }
  1126. }
  1127. static void mg_strlcpy(register char *dst, register const char *src, size_t n)
  1128. {
  1129. for (; *src != '\0' && n > 1; n--) {
  1130. *dst++ = *src++;
  1131. }
  1132. *dst = '\0';
  1133. }
  1134. static int lowercase(const char *s)
  1135. {
  1136. return tolower(*(const unsigned char *)s);
  1137. }
  1138. int mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1139. {
  1140. int diff = 0;
  1141. if (len > 0)
  1142. do {
  1143. diff = lowercase(s1++) - lowercase(s2++);
  1144. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1145. return diff;
  1146. }
  1147. static int mg_strcasecmp(const char *s1, const char *s2)
  1148. {
  1149. int diff;
  1150. do {
  1151. diff = lowercase(s1++) - lowercase(s2++);
  1152. } while (diff == 0 && s1[-1] != '\0');
  1153. return diff;
  1154. }
  1155. static char *mg_strndup(const char *ptr, size_t len)
  1156. {
  1157. char *p;
  1158. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1159. mg_strlcpy(p, ptr, len + 1);
  1160. }
  1161. return p;
  1162. }
  1163. static char *mg_strdup(const char *str) { return mg_strndup(str, strlen(str)); }
  1164. static const char *mg_strcasestr(const char *big_str, const char *small_str)
  1165. {
  1166. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1167. if (big_len >= small_len) {
  1168. for (i = 0; i <= (big_len - small_len); i++) {
  1169. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1170. return big_str + i;
  1171. }
  1172. }
  1173. }
  1174. return NULL;
  1175. }
  1176. /* Like snprintf(), but never returns negative value, or a value
  1177. * that is larger than a supplied buffer.
  1178. * Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  1179. * in his audit report. */
  1180. static int mg_vsnprintf(struct mg_connection *conn,
  1181. char *buf,
  1182. size_t buflen,
  1183. const char *fmt,
  1184. va_list ap)
  1185. {
  1186. int n;
  1187. if (buflen == 0)
  1188. return 0;
  1189. #ifdef __clang__
  1190. #pragma clang diagnostic push
  1191. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1192. /* Using fmt as a non-literal is intended here, since it is mostly called
  1193. * indirectly by mg_snprintf */
  1194. #endif
  1195. n = vsnprintf(buf, buflen, fmt, ap);
  1196. #ifdef __clang__
  1197. #pragma clang diagnostic pop
  1198. #endif
  1199. if (n < 0) {
  1200. mg_cry(conn, "vsnprintf error");
  1201. n = 0;
  1202. } else if (n >= (int)buflen) {
  1203. mg_cry(conn,
  1204. "truncating vsnprintf buffer: [%.*s]",
  1205. n > 200 ? 200 : n,
  1206. buf);
  1207. n = (int)buflen - 1;
  1208. }
  1209. buf[n] = '\0';
  1210. return n;
  1211. }
  1212. static int mg_snprintf(struct mg_connection *conn,
  1213. char *buf,
  1214. size_t buflen,
  1215. PRINTF_FORMAT_STRING(const char *fmt),
  1216. ...) PRINTF_ARGS(4, 5);
  1217. static int mg_snprintf(
  1218. struct mg_connection *conn, char *buf, size_t buflen, const char *fmt, ...)
  1219. {
  1220. va_list ap;
  1221. int n;
  1222. va_start(ap, fmt);
  1223. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  1224. va_end(ap);
  1225. return n;
  1226. }
  1227. static int get_option_index(const char *name)
  1228. {
  1229. int i;
  1230. for (i = 0; config_options[i].name != NULL; i++) {
  1231. if (strcmp(config_options[i].name, name) == 0) {
  1232. return i;
  1233. }
  1234. }
  1235. return -1;
  1236. }
  1237. const char *mg_get_option(const struct mg_context *ctx, const char *name)
  1238. {
  1239. int i;
  1240. if ((i = get_option_index(name)) == -1) {
  1241. return NULL;
  1242. } else if (!ctx || ctx->config[i] == NULL) {
  1243. return "";
  1244. } else {
  1245. return ctx->config[i];
  1246. }
  1247. }
  1248. struct mg_context *mg_get_context(const struct mg_connection *conn)
  1249. {
  1250. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  1251. }
  1252. void *mg_get_user_data(const struct mg_context *ctx)
  1253. {
  1254. return (ctx == NULL) ? NULL : ctx->user_data;
  1255. }
  1256. void mg_set_user_connection_data(const struct mg_connection *conn, void *data)
  1257. {
  1258. if (conn != NULL) {
  1259. ((struct mg_connection *)conn)->request_info.conn_data = data;
  1260. }
  1261. }
  1262. void *mg_get_user_connection_data(const struct mg_connection *conn)
  1263. {
  1264. if (conn != NULL) {
  1265. return conn->request_info.conn_data;
  1266. }
  1267. return NULL;
  1268. }
  1269. size_t
  1270. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  1271. {
  1272. size_t i;
  1273. if (!ctx) {
  1274. return 0;
  1275. }
  1276. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  1277. ssl[i] = ctx->listening_sockets[i].is_ssl;
  1278. ports[i] = ctx->listening_ports[i];
  1279. }
  1280. return i;
  1281. }
  1282. static void sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  1283. {
  1284. buf[0] = '\0';
  1285. if (!usa) {
  1286. return;
  1287. }
  1288. if (usa->sa.sa_family == AF_INET) {
  1289. getnameinfo(&usa->sa,
  1290. sizeof(usa->sin),
  1291. buf,
  1292. (unsigned)len,
  1293. NULL,
  1294. 0,
  1295. NI_NUMERICHOST);
  1296. }
  1297. #if defined(USE_IPV6)
  1298. else if (usa->sa.sa_family == AF_INET6) {
  1299. getnameinfo(&usa->sa,
  1300. sizeof(usa->sin6),
  1301. buf,
  1302. (unsigned)len,
  1303. NULL,
  1304. 0,
  1305. NI_NUMERICHOST);
  1306. }
  1307. #endif
  1308. }
  1309. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  1310. * included in all responses other than 100, 101, 5xx. */
  1311. static void gmt_time_string(char *buf, size_t buf_len, time_t *t)
  1312. {
  1313. struct tm *tm;
  1314. tm = gmtime(t);
  1315. if (tm != NULL) {
  1316. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  1317. } else {
  1318. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  1319. buf[buf_len - 1] = '\0';
  1320. }
  1321. }
  1322. /* difftime for struct timespec. Return value is in seconds. */
  1323. static double mg_difftimespec(const struct timespec *ts_now,
  1324. const struct timespec *ts_before)
  1325. {
  1326. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9 +
  1327. (double)(ts_now->tv_sec - ts_before->tv_sec);
  1328. }
  1329. /* Print error message to the opened error log stream. */
  1330. void mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  1331. {
  1332. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  1333. va_list ap;
  1334. FILE *fp;
  1335. time_t timestamp;
  1336. va_start(ap, fmt);
  1337. IGNORE_UNUSED_RESULT(vsnprintf(buf, sizeof(buf), fmt, ap));
  1338. va_end(ap);
  1339. /* Do not lock when getting the callback value, here and below.
  1340. * I suppose this is fine, since function cannot disappear in the
  1341. * same way string option can. */
  1342. if (conn && (conn->ctx->callbacks.log_message == NULL ||
  1343. conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  1344. fp = conn->ctx->config[ERROR_LOG_FILE] == NULL
  1345. ? NULL
  1346. : fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  1347. if (fp != NULL) {
  1348. flockfile(fp);
  1349. timestamp = time(NULL);
  1350. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  1351. fprintf(fp,
  1352. "[%010lu] [error] [client %s] ",
  1353. (unsigned long)timestamp,
  1354. src_addr);
  1355. if (conn->request_info.request_method != NULL) {
  1356. fprintf(fp,
  1357. "%s %s: ",
  1358. conn->request_info.request_method,
  1359. conn->request_info.uri);
  1360. }
  1361. fprintf(fp, "%s", buf);
  1362. fputc('\n', fp);
  1363. funlockfile(fp);
  1364. fclose(fp);
  1365. }
  1366. }
  1367. }
  1368. /* Return fake connection structure. Used for logging, if connection
  1369. * is not applicable at the moment of logging. */
  1370. static struct mg_connection *fc(struct mg_context *ctx)
  1371. {
  1372. static struct mg_connection fake_connection;
  1373. fake_connection.ctx = ctx;
  1374. return &fake_connection;
  1375. }
  1376. const char *mg_version(void) { return CIVETWEB_VERSION; }
  1377. const struct mg_request_info *
  1378. mg_get_request_info(const struct mg_connection *conn)
  1379. {
  1380. if (!conn) {
  1381. return NULL;
  1382. }
  1383. return &conn->request_info;
  1384. }
  1385. /* Skip the characters until one of the delimiters characters found.
  1386. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  1387. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  1388. * Delimiters can be quoted with quotechar. */
  1389. static char *skip_quoted(char **buf,
  1390. const char *delimiters,
  1391. const char *whitespace,
  1392. char quotechar)
  1393. {
  1394. char *p, *begin_word, *end_word, *end_whitespace;
  1395. begin_word = *buf;
  1396. end_word = begin_word + strcspn(begin_word, delimiters);
  1397. /* Check for quotechar */
  1398. if (end_word > begin_word) {
  1399. p = end_word - 1;
  1400. while (*p == quotechar) {
  1401. /* TODO (bel, low): it seems this code is never reached, so
  1402. * quotechar is actually not needed - check if this code may be
  1403. * droped */
  1404. /* If there is anything beyond end_word, copy it */
  1405. if (*end_word == '\0') {
  1406. *p = '\0';
  1407. break;
  1408. } else {
  1409. size_t end_off = strcspn(end_word + 1, delimiters);
  1410. memmove(p, end_word, end_off + 1);
  1411. p += end_off; /* p must correspond to end_word - 1 */
  1412. end_word += end_off + 1;
  1413. }
  1414. }
  1415. for (p++; p < end_word; p++) {
  1416. *p = '\0';
  1417. }
  1418. }
  1419. if (*end_word == '\0') {
  1420. *buf = end_word;
  1421. } else {
  1422. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  1423. for (p = end_word; p < end_whitespace; p++) {
  1424. *p = '\0';
  1425. }
  1426. *buf = end_whitespace;
  1427. }
  1428. return begin_word;
  1429. }
  1430. /* Simplified version of skip_quoted without quote char
  1431. * and whitespace == delimiters */
  1432. static char *skip(char **buf, const char *delimiters)
  1433. {
  1434. return skip_quoted(buf, delimiters, delimiters, 0);
  1435. }
  1436. /* Return HTTP header value, or NULL if not found. */
  1437. static const char *get_header(const struct mg_request_info *ri,
  1438. const char *name)
  1439. {
  1440. int i;
  1441. if (ri) {
  1442. for (i = 0; i < ri->num_headers; i++) {
  1443. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  1444. return ri->http_headers[i].value;
  1445. }
  1446. }
  1447. }
  1448. return NULL;
  1449. }
  1450. const char *mg_get_header(const struct mg_connection *conn, const char *name)
  1451. {
  1452. if (!conn) {
  1453. return NULL;
  1454. }
  1455. return get_header(&conn->request_info, name);
  1456. }
  1457. /* A helper function for traversing a comma separated list of values.
  1458. * It returns a list pointer shifted to the next value, or NULL if the end
  1459. * of the list found.
  1460. * Value is stored in val vector. If value has form "x=y", then eq_val
  1461. * vector is initialized to point to the "y" part, and val vector length
  1462. * is adjusted to point only to "x". */
  1463. static const char *
  1464. next_option(const char *list, struct vec *val, struct vec *eq_val)
  1465. {
  1466. if (val == NULL || list == NULL || *list == '\0') {
  1467. /* End of the list */
  1468. list = NULL;
  1469. } else {
  1470. val->ptr = list;
  1471. if ((list = strchr(val->ptr, ',')) != NULL) {
  1472. /* Comma found. Store length and shift the list ptr */
  1473. val->len = ((size_t)(list - val->ptr));
  1474. list++;
  1475. } else {
  1476. /* This value is the last one */
  1477. list = val->ptr + strlen(val->ptr);
  1478. val->len = ((size_t)(list - val->ptr));
  1479. }
  1480. if (eq_val != NULL) {
  1481. /* Value has form "x=y", adjust pointers and lengths
  1482. * so that val points to "x", and eq_val points to "y". */
  1483. eq_val->len = 0;
  1484. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  1485. if (eq_val->ptr != NULL) {
  1486. eq_val->ptr++; /* Skip over '=' character */
  1487. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  1488. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  1489. }
  1490. }
  1491. }
  1492. return list;
  1493. }
  1494. /* Perform case-insensitive match of string against pattern */
  1495. static int
  1496. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  1497. {
  1498. const char *or_str;
  1499. size_t i;
  1500. int j, len, res;
  1501. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  1502. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  1503. return res > 0 ? res : match_prefix(or_str + 1,
  1504. (size_t)((pattern + pattern_len) -
  1505. (or_str + 1)),
  1506. str);
  1507. }
  1508. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  1509. if (pattern[i] == '?' && str[j] != '\0') {
  1510. continue;
  1511. } else if (pattern[i] == '$') {
  1512. return str[j] == '\0' ? j : -1;
  1513. } else if (pattern[i] == '*') {
  1514. i++;
  1515. if (pattern[i] == '*') {
  1516. i++;
  1517. len = (int)strlen(str + j);
  1518. } else {
  1519. len = (int)strcspn(str + j, "/");
  1520. }
  1521. if (i == pattern_len) {
  1522. return j + len;
  1523. }
  1524. do {
  1525. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  1526. } while (res == -1 && len-- > 0);
  1527. return res == -1 ? -1 : j + res + len;
  1528. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  1529. return -1;
  1530. }
  1531. }
  1532. return j;
  1533. }
  1534. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  1535. * This function must tolerate situations when connection info is not
  1536. * set up, for example if request parsing failed. */
  1537. static int should_keep_alive(const struct mg_connection *conn)
  1538. {
  1539. if (conn != NULL) {
  1540. const char *http_version = conn->request_info.http_version;
  1541. const char *header = mg_get_header(conn, "Connection");
  1542. if (conn->must_close || conn->status_code == 401 ||
  1543. mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
  1544. (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
  1545. (header == NULL && http_version &&
  1546. 0 != strcmp(http_version, "1.1"))) {
  1547. return 0;
  1548. }
  1549. return 1;
  1550. }
  1551. return 0;
  1552. }
  1553. static int should_decode_url(const struct mg_connection *conn)
  1554. {
  1555. if (!conn || !conn->ctx) {
  1556. return 0;
  1557. }
  1558. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  1559. }
  1560. static const char *suggest_connection_header(const struct mg_connection *conn)
  1561. {
  1562. return should_keep_alive(conn) ? "keep-alive" : "close";
  1563. }
  1564. static void handle_file_based_request(struct mg_connection *conn,
  1565. const char *path,
  1566. struct file *filep);
  1567. static int
  1568. mg_stat(struct mg_connection *conn, const char *path, struct file *filep);
  1569. static const char *mg_get_response_code_text(int response_code,
  1570. struct mg_connection *conn)
  1571. {
  1572. switch (response_code) {
  1573. /* RFC2616 Section 10.1 - Informational 1xx */
  1574. case 100:
  1575. return "Continue"; /* RFC2616 Section 10.1.1 */
  1576. case 101:
  1577. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  1578. case 102:
  1579. return "Processing"; /* RFC2518 Section 10.1 */
  1580. /* RFC2616 Section 10.2 - Successful 2xx */
  1581. case 200:
  1582. return "OK"; /* RFC2616 Section 10.2.1 */
  1583. case 201:
  1584. return "Created"; /* RFC2616 Section 10.2.2 */
  1585. case 202:
  1586. return "Accepted"; /* RFC2616 Section 10.2.3 */
  1587. case 203:
  1588. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  1589. case 204:
  1590. return "No Content"; /* RFC2616 Section 10.2.5 */
  1591. case 205:
  1592. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  1593. case 206:
  1594. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  1595. case 207:
  1596. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  1597. /* RFC2616 Section 10.3 - Redirection 3xx */
  1598. case 300:
  1599. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  1600. case 301:
  1601. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  1602. case 302:
  1603. return "Found"; /* RFC2616 Section 10.3.3 */
  1604. case 303:
  1605. return "See Other"; /* RFC2616 Section 10.3.4 */
  1606. case 304:
  1607. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  1608. case 305:
  1609. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  1610. case 307:
  1611. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  1612. /* RFC2616 Section 10.4 - Client Error 4xx */
  1613. case 400:
  1614. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  1615. case 401:
  1616. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  1617. case 402:
  1618. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  1619. case 403:
  1620. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  1621. case 404:
  1622. return "Not Found"; /* RFC2616 Section 10.4.5 */
  1623. case 405:
  1624. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  1625. case 406:
  1626. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  1627. case 407:
  1628. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  1629. case 408:
  1630. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  1631. case 409:
  1632. return "Conflict"; /* RFC2616 Section 10.4.10 */
  1633. case 410:
  1634. return "Gone"; /* RFC2616 Section 10.4.11 */
  1635. case 411:
  1636. return "Length Required"; /* RFC2616 Section 10.4.12 */
  1637. case 412:
  1638. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  1639. case 413:
  1640. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  1641. case 414:
  1642. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  1643. case 415:
  1644. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  1645. case 416:
  1646. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  1647. case 417:
  1648. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  1649. case 422:
  1650. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  1651. * Section 11.2 */
  1652. case 423:
  1653. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  1654. case 424:
  1655. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  1656. * Section 11.4 */
  1657. case 428:
  1658. return "Precondition Required"; /* RFC 6585, Section 3 */
  1659. case 429:
  1660. return "Too Many Requests"; /* RFC 6585, Section 4 */
  1661. case 431:
  1662. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  1663. /* RFC2616 Section 10.5 - Server Error 5xx */
  1664. case 500:
  1665. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  1666. case 501:
  1667. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  1668. case 502:
  1669. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  1670. case 503:
  1671. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  1672. case 504:
  1673. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  1674. case 505:
  1675. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  1676. case 507:
  1677. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  1678. * Section 11.5 */
  1679. case 511:
  1680. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  1681. /* Other RFCs */
  1682. case 426:
  1683. return "Upgrade Required"; /* RFC 2817 */
  1684. /* Return codes from non normative RFCs: */
  1685. /* Informative and experimental RFCs, "de facto" standards due to common
  1686. * use, ... */
  1687. case 208:
  1688. return "Already Reported"; /* RFC5842 Section 7.1 */
  1689. case 226:
  1690. return "IM used"; /* RFC3229 Section 10.4.1 */
  1691. case 308:
  1692. return "Permanent Redirect"; /* RFC7238 Section 3 */
  1693. case 418:
  1694. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  1695. case 419:
  1696. return "Authentication Timeout"; /* common use */
  1697. case 451:
  1698. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  1699. * Section 3 */
  1700. case 506:
  1701. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  1702. case 508:
  1703. return "Loop Detected"; /* RFC5842 Section 7.1 */
  1704. case 510:
  1705. return "Not Extended"; /* RFC 2774, Section 7 */
  1706. default:
  1707. /* This error code is unknown. This should not happen. */
  1708. if (conn) {
  1709. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  1710. }
  1711. /* Return at least a category according to RFC 2616 Section 10. */
  1712. if (response_code >= 100 && response_code < 200) {
  1713. /* Unknown informational status code */
  1714. return "Information";
  1715. }
  1716. if (response_code >= 200 && response_code < 300) {
  1717. /* Unknown success code */
  1718. return "Success";
  1719. }
  1720. if (response_code >= 300 && response_code < 400) {
  1721. /* Unknown redirection code */
  1722. return "Redirection";
  1723. }
  1724. if (response_code >= 400 && response_code < 500) {
  1725. /* Unknown request error code */
  1726. return "Client Error";
  1727. }
  1728. if (response_code >= 500 && response_code < 600) {
  1729. /* Unknown server error code */
  1730. return "Server Error";
  1731. }
  1732. /* Response code not even within reasonable range */
  1733. return "";
  1734. }
  1735. }
  1736. static void send_http_error(struct mg_connection *,
  1737. int,
  1738. PRINTF_FORMAT_STRING(const char *fmt),
  1739. ...) PRINTF_ARGS(3, 4);
  1740. static void
  1741. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  1742. {
  1743. char buf[MG_BUF_LEN];
  1744. va_list ap;
  1745. int len = 0, i, page_handler_found, scope;
  1746. char date[64];
  1747. time_t curtime = time(NULL);
  1748. const char *error_handler = NULL;
  1749. struct file error_page_file = STRUCT_FILE_INITIALIZER;
  1750. const char *error_page_file_ext, *tstr;
  1751. const char *status_text = mg_get_response_code_text(status, conn);
  1752. if (conn == NULL) {
  1753. return;
  1754. }
  1755. conn->status_code = status;
  1756. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL ||
  1757. conn->ctx->callbacks.http_error(conn, status)) {
  1758. if (!conn->in_error_handler) {
  1759. /* Send user defined error pages, if defined */
  1760. error_handler = conn->ctx->config[ERROR_PAGES];
  1761. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  1762. page_handler_found = 0;
  1763. if (error_handler != NULL) {
  1764. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  1765. switch (scope) {
  1766. case 1:
  1767. len = mg_snprintf(conn,
  1768. buf,
  1769. sizeof(buf) - 32,
  1770. "%serror%03u.",
  1771. error_handler,
  1772. status);
  1773. break;
  1774. case 2:
  1775. len = mg_snprintf(conn,
  1776. buf,
  1777. sizeof(buf) - 32,
  1778. "%serror%01uxx.",
  1779. error_handler,
  1780. status / 100);
  1781. break;
  1782. default:
  1783. len = mg_snprintf(conn,
  1784. buf,
  1785. sizeof(buf) - 32,
  1786. "%serror.",
  1787. error_handler);
  1788. break;
  1789. }
  1790. tstr = strchr(error_page_file_ext, '.');
  1791. while (tstr) {
  1792. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  1793. i++)
  1794. buf[len + i - 1] = tstr[i];
  1795. buf[len + i - 1] = 0;
  1796. if (mg_stat(conn, buf, &error_page_file)) {
  1797. page_handler_found = 1;
  1798. break;
  1799. }
  1800. tstr = strchr(tstr + i, '.');
  1801. }
  1802. }
  1803. }
  1804. if (page_handler_found) {
  1805. conn->in_error_handler = 1;
  1806. handle_file_based_request(conn, buf, &error_page_file);
  1807. conn->in_error_handler = 0;
  1808. return;
  1809. }
  1810. }
  1811. buf[0] = '\0';
  1812. gmt_time_string(date, sizeof(date), &curtime);
  1813. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  1814. if (status > 199 && status != 204 && status != 304) {
  1815. len = mg_snprintf(conn,
  1816. buf,
  1817. sizeof(buf) - 1,
  1818. "Error %d: %s",
  1819. status,
  1820. status_text);
  1821. buf[len] = '\n';
  1822. len++;
  1823. buf[len] = 0;
  1824. va_start(ap, fmt);
  1825. len += mg_vsnprintf(
  1826. conn, buf + len, sizeof(buf) - (size_t)len, fmt, ap);
  1827. va_end(ap);
  1828. }
  1829. DEBUG_TRACE("[%s]", buf);
  1830. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  1831. if (len > 0) {
  1832. mg_printf(conn, "Content-Type: text/plain\r\n");
  1833. }
  1834. mg_printf(conn,
  1835. "Content-Length: %d\r\n"
  1836. "Date: %s\r\n"
  1837. "Connection: %s\r\n\r\n",
  1838. len,
  1839. date,
  1840. suggest_connection_header(conn));
  1841. conn->num_bytes_sent += mg_printf(conn, "%s", buf);
  1842. }
  1843. }
  1844. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1845. static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  1846. {
  1847. (void)unused;
  1848. *mutex = CreateMutex(NULL, FALSE, NULL);
  1849. return *mutex == NULL ? -1 : 0;
  1850. }
  1851. static int pthread_mutex_destroy(pthread_mutex_t *mutex)
  1852. {
  1853. return CloseHandle(*mutex) == 0 ? -1 : 0;
  1854. }
  1855. static int pthread_mutex_lock(pthread_mutex_t *mutex)
  1856. {
  1857. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0 ? 0 : -1;
  1858. }
  1859. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  1860. static int pthread_mutex_trylock(pthread_mutex_t *mutex)
  1861. {
  1862. switch (WaitForSingleObject(*mutex, 0)) {
  1863. case WAIT_OBJECT_0:
  1864. return 0;
  1865. case WAIT_TIMEOUT:
  1866. return -2; /* EBUSY */
  1867. }
  1868. return -1;
  1869. }
  1870. #endif
  1871. static int pthread_mutex_unlock(pthread_mutex_t *mutex)
  1872. {
  1873. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  1874. }
  1875. #ifndef WIN_PTHREADS_TIME_H
  1876. static int clock_gettime(clockid_t clk_id, struct timespec *tp)
  1877. {
  1878. FILETIME ft;
  1879. ULARGE_INTEGER li;
  1880. BOOL ok = FALSE;
  1881. double d;
  1882. static double perfcnt_per_sec = 0.0;
  1883. if (tp) {
  1884. if (clk_id == CLOCK_REALTIME) {
  1885. GetSystemTimeAsFileTime(&ft);
  1886. li.LowPart = ft.dwLowDateTime;
  1887. li.HighPart = ft.dwHighDateTime;
  1888. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  1889. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  1890. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  1891. ok = TRUE;
  1892. } else if (clk_id == CLOCK_MONOTONIC) {
  1893. if (perfcnt_per_sec == 0.0) {
  1894. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  1895. perfcnt_per_sec = 1.0 / li.QuadPart;
  1896. }
  1897. if (perfcnt_per_sec != 0.0) {
  1898. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  1899. d = li.QuadPart * perfcnt_per_sec;
  1900. tp->tv_sec = (time_t)d;
  1901. d -= tp->tv_sec;
  1902. tp->tv_nsec = (long)(d * 1.0E9);
  1903. ok = TRUE;
  1904. }
  1905. }
  1906. }
  1907. return ok ? 0 : -1;
  1908. }
  1909. #endif
  1910. static int pthread_cond_init(pthread_cond_t *cv, const void *unused)
  1911. {
  1912. (void)unused;
  1913. InitializeCriticalSection(&cv->threadIdSec);
  1914. cv->waitingthreadcount = 0;
  1915. cv->waitingthreadhdls =
  1916. (pthread_t *)mg_calloc(MAX_WORKER_THREADS, sizeof(pthread_t));
  1917. return (cv->waitingthreadhdls != NULL) ? 0 : -1;
  1918. }
  1919. static int pthread_cond_timedwait(pthread_cond_t *cv,
  1920. pthread_mutex_t *mutex,
  1921. const struct timespec *abstime)
  1922. {
  1923. struct mg_workerTLS *tls = (struct mg_workerTLS *)TlsGetValue(sTlsKey);
  1924. int ok;
  1925. struct timespec tsnow;
  1926. int64_t nsnow, nswaitabs, nswaitrel;
  1927. DWORD mswaitrel;
  1928. EnterCriticalSection(&cv->threadIdSec);
  1929. assert(cv->waitingthreadcount < MAX_WORKER_THREADS);
  1930. cv->waitingthreadhdls[cv->waitingthreadcount] =
  1931. tls->pthread_cond_helper_mutex;
  1932. cv->waitingthreadcount++;
  1933. LeaveCriticalSection(&cv->threadIdSec);
  1934. if (abstime) {
  1935. clock_gettime(CLOCK_REALTIME, &tsnow);
  1936. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  1937. nswaitabs =
  1938. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  1939. nswaitrel = nswaitabs - nsnow;
  1940. if (nswaitrel < 0)
  1941. nswaitrel = 0;
  1942. mswaitrel = (DWORD)(nswaitrel / 1000000);
  1943. } else {
  1944. mswaitrel = INFINITE;
  1945. }
  1946. pthread_mutex_unlock(mutex);
  1947. ok = (WAIT_OBJECT_0 ==
  1948. WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  1949. pthread_mutex_lock(mutex);
  1950. return ok ? 0 : -1;
  1951. }
  1952. static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  1953. {
  1954. return pthread_cond_timedwait(cv, mutex, NULL);
  1955. }
  1956. static int pthread_cond_signal(pthread_cond_t *cv)
  1957. {
  1958. int i;
  1959. HANDLE wkup = NULL;
  1960. BOOL ok = FALSE;
  1961. EnterCriticalSection(&cv->threadIdSec);
  1962. if (cv->waitingthreadcount) {
  1963. wkup = cv->waitingthreadhdls[0];
  1964. ok = SetEvent(wkup);
  1965. for (i = 1; i < cv->waitingthreadcount; i++) {
  1966. cv->waitingthreadhdls[i - 1] = cv->waitingthreadhdls[i];
  1967. }
  1968. cv->waitingthreadcount--;
  1969. assert(ok);
  1970. }
  1971. LeaveCriticalSection(&cv->threadIdSec);
  1972. return ok ? 0 : 1;
  1973. }
  1974. static int pthread_cond_broadcast(pthread_cond_t *cv)
  1975. {
  1976. EnterCriticalSection(&cv->threadIdSec);
  1977. while (cv->waitingthreadcount) {
  1978. pthread_cond_signal(cv);
  1979. }
  1980. LeaveCriticalSection(&cv->threadIdSec);
  1981. return 0;
  1982. }
  1983. static int pthread_cond_destroy(pthread_cond_t *cv)
  1984. {
  1985. EnterCriticalSection(&cv->threadIdSec);
  1986. assert(cv->waitingthreadcount == 0);
  1987. mg_free(cv->waitingthreadhdls);
  1988. cv->waitingthreadhdls = 0;
  1989. LeaveCriticalSection(&cv->threadIdSec);
  1990. DeleteCriticalSection(&cv->threadIdSec);
  1991. return 0;
  1992. }
  1993. /* For Windows, change all slashes to backslashes in path names. */
  1994. static void change_slashes_to_backslashes(char *path)
  1995. {
  1996. int i;
  1997. for (i = 0; path[i] != '\0'; i++) {
  1998. if (path[i] == '/') {
  1999. path[i] = '\\';
  2000. }
  2001. /* remove double backslash (check i > 0 to preserve UNC paths,
  2002. * like \\server\file.txt) */
  2003. if ((path[i] == '\\') && (i > 0)) {
  2004. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2005. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2006. }
  2007. }
  2008. }
  2009. }
  2010. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  2011. * wbuf and wbuf_len is a target buffer and its length. */
  2012. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  2013. {
  2014. char buf[PATH_MAX], buf2[PATH_MAX];
  2015. mg_strlcpy(buf, path, sizeof(buf));
  2016. change_slashes_to_backslashes(buf);
  2017. /* Convert to Unicode and back. If doubly-converted string does not
  2018. * match the original, something is fishy, reject. */
  2019. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  2020. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  2021. WideCharToMultiByte(
  2022. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  2023. if (strcmp(buf, buf2) != 0) {
  2024. wbuf[0] = L'\0';
  2025. }
  2026. }
  2027. #if defined(_WIN32_WCE)
  2028. static time_t time(time_t *ptime)
  2029. {
  2030. time_t t;
  2031. SYSTEMTIME st;
  2032. FILETIME ft;
  2033. GetSystemTime(&st);
  2034. SystemTimeToFileTime(&st, &ft);
  2035. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  2036. if (ptime != NULL) {
  2037. *ptime = t;
  2038. }
  2039. return t;
  2040. }
  2041. static struct tm *localtime(const time_t *ptime, struct tm *ptm)
  2042. {
  2043. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  2044. FILETIME ft, lft;
  2045. SYSTEMTIME st;
  2046. TIME_ZONE_INFORMATION tzinfo;
  2047. if (ptm == NULL) {
  2048. return NULL;
  2049. }
  2050. *(int64_t *)&ft = t;
  2051. FileTimeToLocalFileTime(&ft, &lft);
  2052. FileTimeToSystemTime(&lft, &st);
  2053. ptm->tm_year = st.wYear - 1900;
  2054. ptm->tm_mon = st.wMonth - 1;
  2055. ptm->tm_wday = st.wDayOfWeek;
  2056. ptm->tm_mday = st.wDay;
  2057. ptm->tm_hour = st.wHour;
  2058. ptm->tm_min = st.wMinute;
  2059. ptm->tm_sec = st.wSecond;
  2060. ptm->tm_yday = 0; /* hope nobody uses this */
  2061. ptm->tm_isdst =
  2062. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  2063. return ptm;
  2064. }
  2065. static struct tm *gmtime(const time_t *ptime, struct tm *ptm)
  2066. {
  2067. /* FIXME(lsm): fix this. */
  2068. return localtime(ptime, ptm);
  2069. }
  2070. static size_t
  2071. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  2072. {
  2073. (void)snprintf(dst, dst_size, "implement strftime() for WinCE");
  2074. return 0;
  2075. }
  2076. #endif
  2077. /* Windows happily opens files with some garbage at the end of file name.
  2078. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  2079. * "a.cgi", despite one would expect an error back.
  2080. * This function returns non-0 if path ends with some garbage. */
  2081. static int path_cannot_disclose_cgi(const char *path)
  2082. {
  2083. static const char *allowed_last_characters = "_-";
  2084. int last = path[strlen(path) - 1];
  2085. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  2086. }
  2087. static int
  2088. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2089. {
  2090. wchar_t wbuf[PATH_MAX];
  2091. WIN32_FILE_ATTRIBUTE_DATA info;
  2092. if (!is_file_in_memory(conn, path, filep)) {
  2093. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2094. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  2095. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  2096. filep->modification_time =
  2097. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  2098. info.ftLastWriteTime.dwHighDateTime);
  2099. filep->is_directory =
  2100. info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  2101. /* If file name is fishy, reset the file structure and return
  2102. * error.
  2103. * Note it is important to reset, not just return the error, cause
  2104. * functions like is_file_opened() check the struct. */
  2105. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  2106. memset(filep, 0, sizeof(*filep));
  2107. }
  2108. }
  2109. }
  2110. return filep->membuf != NULL || filep->modification_time != 0;
  2111. }
  2112. static int mg_remove(const char *path)
  2113. {
  2114. wchar_t wbuf[PATH_MAX];
  2115. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  2116. return DeleteFileW(wbuf) ? 0 : -1;
  2117. }
  2118. static int mg_mkdir(const char *path, int mode)
  2119. {
  2120. char buf[PATH_MAX];
  2121. wchar_t wbuf[PATH_MAX];
  2122. (void)mode;
  2123. mg_strlcpy(buf, path, sizeof(buf));
  2124. change_slashes_to_backslashes(buf);
  2125. (void)MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, ARRAY_SIZE(wbuf));
  2126. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  2127. }
  2128. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  2129. static DIR *opendir(const char *name)
  2130. {
  2131. DIR *dir = NULL;
  2132. wchar_t wpath[PATH_MAX];
  2133. DWORD attrs;
  2134. if (name == NULL) {
  2135. SetLastError(ERROR_BAD_ARGUMENTS);
  2136. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  2137. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2138. } else {
  2139. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  2140. attrs = GetFileAttributesW(wpath);
  2141. if (attrs != 0xFFFFFFFF &&
  2142. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  2143. (void)wcscat(wpath, L"\\*");
  2144. dir->handle = FindFirstFileW(wpath, &dir->info);
  2145. dir->result.d_name[0] = '\0';
  2146. } else {
  2147. mg_free(dir);
  2148. dir = NULL;
  2149. }
  2150. }
  2151. return dir;
  2152. }
  2153. static int closedir(DIR *dir)
  2154. {
  2155. int result = 0;
  2156. if (dir != NULL) {
  2157. if (dir->handle != INVALID_HANDLE_VALUE)
  2158. result = FindClose(dir->handle) ? 0 : -1;
  2159. mg_free(dir);
  2160. } else {
  2161. result = -1;
  2162. SetLastError(ERROR_BAD_ARGUMENTS);
  2163. }
  2164. return result;
  2165. }
  2166. static struct dirent *readdir(DIR *dir)
  2167. {
  2168. struct dirent *result = 0;
  2169. if (dir) {
  2170. if (dir->handle != INVALID_HANDLE_VALUE) {
  2171. result = &dir->result;
  2172. (void)WideCharToMultiByte(CP_UTF8,
  2173. 0,
  2174. dir->info.cFileName,
  2175. -1,
  2176. result->d_name,
  2177. sizeof(result->d_name),
  2178. NULL,
  2179. NULL);
  2180. if (!FindNextFileW(dir->handle, &dir->info)) {
  2181. (void)FindClose(dir->handle);
  2182. dir->handle = INVALID_HANDLE_VALUE;
  2183. }
  2184. } else {
  2185. SetLastError(ERROR_FILE_NOT_FOUND);
  2186. }
  2187. } else {
  2188. SetLastError(ERROR_BAD_ARGUMENTS);
  2189. }
  2190. return result;
  2191. }
  2192. #ifndef HAVE_POLL
  2193. static int poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  2194. {
  2195. struct timeval tv;
  2196. fd_set set;
  2197. unsigned int i;
  2198. int result;
  2199. SOCKET maxfd = 0;
  2200. tv.tv_sec = milliseconds / 1000;
  2201. tv.tv_usec = (milliseconds % 1000) * 1000;
  2202. FD_ZERO(&set);
  2203. for (i = 0; i < n; i++) {
  2204. FD_SET((SOCKET)pfd[i].fd, &set);
  2205. pfd[i].revents = 0;
  2206. if (pfd[i].fd > maxfd) {
  2207. maxfd = pfd[i].fd;
  2208. }
  2209. }
  2210. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  2211. for (i = 0; i < n; i++) {
  2212. if (FD_ISSET(pfd[i].fd, &set)) {
  2213. pfd[i].revents = POLLIN;
  2214. }
  2215. }
  2216. }
  2217. return result;
  2218. }
  2219. #endif /* HAVE_POLL */
  2220. static void set_close_on_exec(SOCKET sock,
  2221. struct mg_connection *conn /* may be null */)
  2222. {
  2223. (void)conn; /* Unused. */
  2224. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  2225. }
  2226. int mg_start_thread(mg_thread_func_t f, void *p)
  2227. {
  2228. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2229. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  2230. */
  2231. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p) ==
  2232. ((uintptr_t)(-1L)))
  2233. ? -1
  2234. : 0);
  2235. #else
  2236. return (
  2237. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  2238. ? -1
  2239. : 0);
  2240. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2241. }
  2242. /* Start a thread storing the thread context. */
  2243. static int mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  2244. void *p,
  2245. pthread_t *threadidptr)
  2246. {
  2247. uintptr_t uip;
  2248. HANDLE threadhandle;
  2249. int result = -1;
  2250. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  2251. threadhandle = (HANDLE)uip;
  2252. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  2253. *threadidptr = threadhandle;
  2254. result = 0;
  2255. }
  2256. return result;
  2257. }
  2258. /* Wait for a thread to finish. */
  2259. static int mg_join_thread(pthread_t threadid)
  2260. {
  2261. int result;
  2262. DWORD dwevent;
  2263. result = -1;
  2264. dwevent = WaitForSingleObject(threadid, INFINITE);
  2265. if (dwevent == WAIT_FAILED) {
  2266. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  2267. } else {
  2268. if (dwevent == WAIT_OBJECT_0) {
  2269. CloseHandle(threadid);
  2270. result = 0;
  2271. }
  2272. }
  2273. return result;
  2274. }
  2275. static HANDLE dlopen(const char *dll_name, int flags)
  2276. {
  2277. wchar_t wbuf[PATH_MAX];
  2278. (void)flags;
  2279. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  2280. return LoadLibraryW(wbuf);
  2281. }
  2282. static int dlclose(void *handle)
  2283. {
  2284. int result;
  2285. if (FreeLibrary((HMODULE)handle) != 0) {
  2286. result = 0;
  2287. } else {
  2288. result = -1;
  2289. }
  2290. return result;
  2291. }
  2292. #if !defined(NO_CGI)
  2293. #define SIGKILL (0)
  2294. static int kill(pid_t pid, int sig_num)
  2295. {
  2296. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  2297. (void)CloseHandle((HANDLE)pid);
  2298. return 0;
  2299. }
  2300. static void trim_trailing_whitespaces(char *s)
  2301. {
  2302. char *e = s + strlen(s) - 1;
  2303. while (e > s && isspace(*(unsigned char *)e)) {
  2304. *e-- = '\0';
  2305. }
  2306. }
  2307. static pid_t spawn_process(struct mg_connection *conn,
  2308. const char *prog,
  2309. char *envblk,
  2310. char *envp[],
  2311. int fdin,
  2312. int fdout,
  2313. const char *dir)
  2314. {
  2315. HANDLE me;
  2316. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  2317. cmdline[PATH_MAX], buf[PATH_MAX];
  2318. struct file file = STRUCT_FILE_INITIALIZER;
  2319. STARTUPINFOA si;
  2320. PROCESS_INFORMATION pi = {0};
  2321. (void)envp;
  2322. memset(&si, 0, sizeof(si));
  2323. si.cb = sizeof(si);
  2324. /* TODO(lsm, mid): redirect CGI errors to the error log file */
  2325. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  2326. si.wShowWindow = SW_HIDE;
  2327. me = GetCurrentProcess();
  2328. DuplicateHandle(me,
  2329. (HANDLE)_get_osfhandle(fdin),
  2330. me,
  2331. &si.hStdInput,
  2332. 0,
  2333. TRUE,
  2334. DUPLICATE_SAME_ACCESS);
  2335. DuplicateHandle(me,
  2336. (HANDLE)_get_osfhandle(fdout),
  2337. me,
  2338. &si.hStdOutput,
  2339. 0,
  2340. TRUE,
  2341. DUPLICATE_SAME_ACCESS);
  2342. /* If CGI file is a script, try to read the interpreter line */
  2343. interp = conn->ctx->config[CGI_INTERPRETER];
  2344. if (interp == NULL) {
  2345. buf[0] = buf[1] = '\0';
  2346. /* Read the first line of the script into the buffer */
  2347. snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
  2348. if (mg_fopen(conn, cmdline, "r", &file)) {
  2349. p = (char *)file.membuf;
  2350. mg_fgets(buf, sizeof(buf), &file, &p);
  2351. mg_fclose(&file);
  2352. buf[sizeof(buf) - 1] = '\0';
  2353. }
  2354. if (buf[0] == '#' && buf[1] == '!') {
  2355. trim_trailing_whitespaces(buf + 2);
  2356. } else {
  2357. buf[2] = '\0';
  2358. }
  2359. interp = buf + 2;
  2360. }
  2361. if (interp[0] != '\0') {
  2362. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  2363. interp = full_interp;
  2364. }
  2365. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  2366. if (interp[0] != '\0')
  2367. mg_snprintf(conn,
  2368. cmdline,
  2369. sizeof(cmdline),
  2370. "\"%s\" \"%s\\%s\"",
  2371. interp,
  2372. full_dir,
  2373. prog);
  2374. else
  2375. mg_snprintf(
  2376. conn, cmdline, sizeof(cmdline), "\"%s\\%s\"", full_dir, prog);
  2377. DEBUG_TRACE("Running [%s]", cmdline);
  2378. if (CreateProcessA(NULL,
  2379. cmdline,
  2380. NULL,
  2381. NULL,
  2382. TRUE,
  2383. CREATE_NEW_PROCESS_GROUP,
  2384. envblk,
  2385. NULL,
  2386. &si,
  2387. &pi) == 0) {
  2388. mg_cry(conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, ERRNO);
  2389. pi.hProcess = (pid_t)-1;
  2390. }
  2391. (void)CloseHandle(si.hStdOutput);
  2392. (void)CloseHandle(si.hStdInput);
  2393. if (pi.hThread != NULL)
  2394. (void)CloseHandle(pi.hThread);
  2395. return (pid_t)pi.hProcess;
  2396. }
  2397. #endif /* !NO_CGI */
  2398. static int set_non_blocking_mode(SOCKET sock)
  2399. {
  2400. unsigned long on = 1;
  2401. return ioctlsocket(sock, (long)FIONBIO, &on);
  2402. }
  2403. #else
  2404. static int
  2405. mg_stat(struct mg_connection *conn, const char *path, struct file *filep)
  2406. {
  2407. struct stat st;
  2408. if (!filep) {
  2409. return 0;
  2410. }
  2411. if (!is_file_in_memory(conn, path, filep) && !stat(path, &st)) {
  2412. filep->size = (uint64_t)(st.st_size);
  2413. filep->modification_time = st.st_mtime;
  2414. filep->is_directory = S_ISDIR(st.st_mode);
  2415. } else {
  2416. filep->modification_time = (time_t)0;
  2417. }
  2418. return filep->membuf != NULL || filep->modification_time != (time_t)0;
  2419. }
  2420. static void set_close_on_exec(SOCKET fd,
  2421. struct mg_connection *conn /* may be null */)
  2422. {
  2423. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  2424. if (conn) {
  2425. mg_cry(conn,
  2426. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  2427. __func__,
  2428. strerror(ERRNO));
  2429. }
  2430. }
  2431. }
  2432. int mg_start_thread(mg_thread_func_t func, void *param)
  2433. {
  2434. pthread_t thread_id;
  2435. pthread_attr_t attr;
  2436. int result;
  2437. (void)pthread_attr_init(&attr);
  2438. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  2439. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2440. /* Compile-time option to control stack size,
  2441. * e.g. -DUSE_STACK_SIZE=16384 */
  2442. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2443. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  2444. result = pthread_create(&thread_id, &attr, func, param);
  2445. pthread_attr_destroy(&attr);
  2446. return result;
  2447. }
  2448. /* Start a thread storing the thread context. */
  2449. static int mg_start_thread_with_id(mg_thread_func_t func,
  2450. void *param,
  2451. pthread_t *threadidptr)
  2452. {
  2453. pthread_t thread_id;
  2454. pthread_attr_t attr;
  2455. int result;
  2456. (void)pthread_attr_init(&attr);
  2457. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  2458. /* Compile-time option to control stack size,
  2459. * e.g. -DUSE_STACK_SIZE=16384 */
  2460. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  2461. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  2462. result = pthread_create(&thread_id, &attr, func, param);
  2463. pthread_attr_destroy(&attr);
  2464. if ((result == 0) && (threadidptr != NULL)) {
  2465. *threadidptr = thread_id;
  2466. }
  2467. return result;
  2468. }
  2469. /* Wait for a thread to finish. */
  2470. static int mg_join_thread(pthread_t threadid)
  2471. {
  2472. int result;
  2473. result = pthread_join(threadid, NULL);
  2474. return result;
  2475. }
  2476. #ifndef NO_CGI
  2477. static pid_t spawn_process(struct mg_connection *conn,
  2478. const char *prog,
  2479. char *envblk,
  2480. char *envp[],
  2481. int fdin,
  2482. int fdout,
  2483. const char *dir)
  2484. {
  2485. pid_t pid;
  2486. const char *interp;
  2487. (void)envblk;
  2488. if (conn == NULL) {
  2489. return 0;
  2490. }
  2491. if ((pid = fork()) == -1) {
  2492. /* Parent */
  2493. send_http_error(conn,
  2494. 500,
  2495. "Error: Creating CGI process\nfork(): %s",
  2496. strerror(ERRNO));
  2497. } else if (pid == 0) {
  2498. /* Child */
  2499. if (chdir(dir) != 0) {
  2500. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  2501. } else if (dup2(fdin, 0) == -1) {
  2502. mg_cry(
  2503. conn, "%s: dup2(%d, 0): %s", __func__, fdin, strerror(ERRNO));
  2504. } else if (dup2(fdout, 1) == -1) {
  2505. mg_cry(
  2506. conn, "%s: dup2(%d, 1): %s", __func__, fdout, strerror(ERRNO));
  2507. } else {
  2508. /* Not redirecting stderr to stdout, to avoid output being littered
  2509. * with the error messages. */
  2510. (void)close(fdin);
  2511. (void)close(fdout);
  2512. /* After exec, all signal handlers are restored to their default
  2513. * values, with one exception of SIGCHLD. According to
  2514. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  2515. * leave unchanged after exec if it was set to be ignored. Restore
  2516. * it to default action. */
  2517. signal(SIGCHLD, SIG_DFL);
  2518. interp = conn->ctx->config[CGI_INTERPRETER];
  2519. if (interp == NULL) {
  2520. (void)execle(prog, prog, NULL, envp);
  2521. mg_cry(conn,
  2522. "%s: execle(%s): %s",
  2523. __func__,
  2524. prog,
  2525. strerror(ERRNO));
  2526. } else {
  2527. (void)execle(interp, interp, prog, NULL, envp);
  2528. mg_cry(conn,
  2529. "%s: execle(%s %s): %s",
  2530. __func__,
  2531. interp,
  2532. prog,
  2533. strerror(ERRNO));
  2534. }
  2535. }
  2536. exit(EXIT_FAILURE);
  2537. }
  2538. return pid;
  2539. }
  2540. #endif /* !NO_CGI */
  2541. static int set_non_blocking_mode(SOCKET sock)
  2542. {
  2543. int flags;
  2544. flags = fcntl(sock, F_GETFL, 0);
  2545. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  2546. return 0;
  2547. }
  2548. #endif /* _WIN32 */
  2549. /* Write data to the IO channel - opened file descriptor, socket or SSL
  2550. * descriptor. Return number of bytes written. */
  2551. static int push(struct mg_context *ctx,
  2552. FILE *fp,
  2553. SOCKET sock,
  2554. SSL *ssl,
  2555. const char *buf,
  2556. int len,
  2557. double timeout)
  2558. {
  2559. struct timespec start, now;
  2560. int n;
  2561. #ifdef _WIN32
  2562. typedef int len_t;
  2563. #else
  2564. typedef size_t len_t;
  2565. #endif
  2566. if (timeout > 0) {
  2567. memset(&start, 0, sizeof(start));
  2568. memset(&now, 0, sizeof(now));
  2569. clock_gettime(CLOCK_MONOTONIC, &start);
  2570. }
  2571. if (ctx == NULL) {
  2572. return -1;
  2573. }
  2574. do {
  2575. #ifndef NO_SSL
  2576. if (ssl != NULL) {
  2577. n = SSL_write(ssl, buf, len);
  2578. } else
  2579. #endif
  2580. if (fp != NULL) {
  2581. n = (int)fwrite(buf, 1, (size_t)len, fp);
  2582. if (ferror(fp))
  2583. n = -1;
  2584. } else {
  2585. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  2586. }
  2587. if (ctx->stop_flag) {
  2588. return -1;
  2589. }
  2590. if ((n > 0) || (n == 0 && len == 0)) {
  2591. /* some data has been read, or no data was requested */
  2592. return n;
  2593. }
  2594. if (n == 0) {
  2595. /* shutdown of the socket at client side */
  2596. return -1;
  2597. }
  2598. if (n < 0) {
  2599. /* socket error - check errno */
  2600. DEBUG_TRACE("send() failed, error %d", ERRNO);
  2601. return -1;
  2602. }
  2603. if (timeout > 0) {
  2604. clock_gettime(CLOCK_MONOTONIC, &now);
  2605. }
  2606. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  2607. return -1;
  2608. }
  2609. static int64_t push_all(struct mg_context *ctx,
  2610. FILE *fp,
  2611. SOCKET sock,
  2612. SSL *ssl,
  2613. const char *buf,
  2614. int64_t len)
  2615. {
  2616. double timeout = -1.0;
  2617. int64_t n, nwritten = 0;
  2618. if (ctx == NULL) {
  2619. return -1;
  2620. }
  2621. if (ctx->config[REQUEST_TIMEOUT]) {
  2622. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  2623. }
  2624. while (len > 0 && ctx->stop_flag == 0) {
  2625. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  2626. if (n < 0) {
  2627. nwritten = n; /* Propagate the error */
  2628. break;
  2629. } else if (n == 0) {
  2630. break; /* No more data to write */
  2631. } else {
  2632. nwritten += n;
  2633. len -= n;
  2634. }
  2635. }
  2636. return nwritten;
  2637. }
  2638. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  2639. * Return negative value on error, or number of bytes read on success. */
  2640. static int
  2641. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  2642. {
  2643. int nread;
  2644. struct timespec start, now;
  2645. #ifdef _WIN32
  2646. typedef int len_t;
  2647. #else
  2648. typedef size_t len_t;
  2649. #endif
  2650. if (timeout > 0) {
  2651. memset(&start, 0, sizeof(start));
  2652. memset(&now, 0, sizeof(now));
  2653. clock_gettime(CLOCK_MONOTONIC, &start);
  2654. }
  2655. do {
  2656. if (fp != NULL) {
  2657. /* Use read() instead of fread(), because if we're reading from the
  2658. * CGI pipe, fread() may block until IO buffer is filled up. We
  2659. * cannot afford to block and must pass all read bytes immediately
  2660. * to the client. */
  2661. nread = (int)read(fileno(fp), buf, (size_t)len);
  2662. #ifndef NO_SSL
  2663. } else if (conn->ssl != NULL) {
  2664. nread = SSL_read(conn->ssl, buf, len);
  2665. #endif
  2666. } else {
  2667. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  2668. }
  2669. if (conn->ctx->stop_flag) {
  2670. return -1;
  2671. }
  2672. if ((nread > 0) || (nread == 0 && len == 0)) {
  2673. /* some data has been read, or no data was requested */
  2674. return nread;
  2675. }
  2676. if (nread == 0) {
  2677. /* shutdown of the socket at client side */
  2678. return -1;
  2679. }
  2680. if (nread < 0) {
  2681. /* socket error - check errno */
  2682. DEBUG_TRACE("recv() failed, error %d", ERRNO);
  2683. return -1;
  2684. }
  2685. if (timeout > 0) {
  2686. clock_gettime(CLOCK_MONOTONIC, &now);
  2687. }
  2688. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  2689. /* Timeout occured, but no data available. */
  2690. return -1;
  2691. }
  2692. static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  2693. {
  2694. int n, nread = 0;
  2695. double timeout = -1.0;
  2696. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  2697. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  2698. }
  2699. while (len > 0 && conn->ctx->stop_flag == 0) {
  2700. n = pull(fp, conn, buf + nread, len, timeout);
  2701. if (n < 0) {
  2702. nread = n; /* Propagate the error */
  2703. break;
  2704. } else if (n == 0) {
  2705. break; /* No more data to read */
  2706. } else {
  2707. conn->consumed_content += n;
  2708. nread += n;
  2709. len -= n;
  2710. }
  2711. }
  2712. return nread;
  2713. }
  2714. static void discard_unread_request_data(struct mg_connection *conn)
  2715. {
  2716. char buf[MG_BUF_LEN];
  2717. size_t to_read;
  2718. int nread;
  2719. if (conn == NULL) {
  2720. return;
  2721. }
  2722. to_read = sizeof(buf);
  2723. if (conn->is_chunked) {
  2724. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  2725. * completely */
  2726. while (conn->is_chunked == 1) {
  2727. nread = mg_read(conn, buf, to_read);
  2728. if (nread <= 0) {
  2729. break;
  2730. }
  2731. }
  2732. } else {
  2733. /* Not chunked: content length is known */
  2734. while (conn->consumed_content < conn->content_len) {
  2735. if (to_read >
  2736. (size_t)(conn->content_len - conn->consumed_content)) {
  2737. to_read = (size_t)(conn->content_len - conn->consumed_content);
  2738. }
  2739. nread = mg_read(conn, buf, to_read);
  2740. if (nread <= 0) {
  2741. break;
  2742. }
  2743. }
  2744. }
  2745. }
  2746. static int mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  2747. {
  2748. int64_t n, buffered_len, nread;
  2749. int64_t len64 =
  2750. (int64_t)(len > INT_MAX ? INT_MAX : len); /* since the return value is
  2751. * int, we may not read more
  2752. * bytes */
  2753. const char *body;
  2754. if (conn == NULL)
  2755. return 0;
  2756. /* If Content-Length is not set for a PUT or POST request, read until
  2757. * socket is closed */
  2758. if (conn->consumed_content == 0 && conn->content_len == -1) {
  2759. conn->content_len = INT64_MAX;
  2760. conn->must_close = 1;
  2761. }
  2762. nread = 0;
  2763. if (conn->consumed_content < conn->content_len) {
  2764. /* Adjust number of bytes to read. */
  2765. int64_t left_to_read = conn->content_len - conn->consumed_content;
  2766. if (left_to_read < len64) {
  2767. /* Do not reade more than the total content length of the request.
  2768. */
  2769. len64 = left_to_read;
  2770. }
  2771. /* Return buffered data */
  2772. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len -
  2773. conn->consumed_content;
  2774. if (buffered_len > 0) {
  2775. if (len64 < buffered_len) {
  2776. buffered_len = len64;
  2777. }
  2778. body = conn->buf + conn->request_len + conn->consumed_content;
  2779. memcpy(buf, body, (size_t)buffered_len);
  2780. len64 -= buffered_len;
  2781. conn->consumed_content += buffered_len;
  2782. nread += buffered_len;
  2783. buf = (char *)buf + buffered_len;
  2784. }
  2785. /* We have returned all buffered data. Read new data from the remote
  2786. * socket.
  2787. */
  2788. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  2789. nread += n;
  2790. } else {
  2791. nread = (nread > 0 ? nread : n);
  2792. }
  2793. }
  2794. return (int)nread;
  2795. }
  2796. static char mg_getc(struct mg_connection *conn)
  2797. {
  2798. char c;
  2799. if (conn == NULL) {
  2800. return 0;
  2801. }
  2802. conn->content_len++;
  2803. if (mg_read_inner(conn, &c, 1) <= 0) {
  2804. return (char)0;
  2805. }
  2806. return c;
  2807. }
  2808. int mg_read(struct mg_connection *conn, void *buf, size_t len)
  2809. {
  2810. if (len > INT_MAX)
  2811. len = INT_MAX;
  2812. if (conn == NULL)
  2813. return 0;
  2814. if (conn->is_chunked) {
  2815. size_t all_read = 0;
  2816. while (len > 0) {
  2817. if (conn->chunk_remainder) {
  2818. /* copy from the remainder of the last received chunk */
  2819. long read_ret;
  2820. size_t read_now =
  2821. ((conn->chunk_remainder > len) ? (len)
  2822. : (conn->chunk_remainder));
  2823. conn->content_len += (int)read_now;
  2824. read_ret =
  2825. mg_read_inner(conn, (char *)buf + all_read, read_now);
  2826. all_read += (size_t)read_ret;
  2827. conn->chunk_remainder -= read_now;
  2828. len -= read_now;
  2829. if (conn->chunk_remainder == 0) {
  2830. /* the rest of the data in the current chunk has been read
  2831. */
  2832. if ((mg_getc(conn) != '\r') || (mg_getc(conn) != '\n')) {
  2833. /* Protocol violation */
  2834. return -1;
  2835. }
  2836. }
  2837. } else {
  2838. /* fetch a new chunk */
  2839. int i = 0;
  2840. char lenbuf[64];
  2841. char *end = 0;
  2842. unsigned long chunkSize = 0;
  2843. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  2844. lenbuf[i] = mg_getc(conn);
  2845. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r')
  2846. continue;
  2847. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  2848. lenbuf[i + 1] = 0;
  2849. chunkSize = strtoul(lenbuf, &end, 16);
  2850. break;
  2851. }
  2852. if (!isalnum(lenbuf[i])) {
  2853. /* illegal character for chunk length */
  2854. return -1;
  2855. }
  2856. }
  2857. if ((end == NULL) || (*end != '\r')) {
  2858. /* chunksize not set correctly */
  2859. return -1;
  2860. }
  2861. conn->chunk_remainder = chunkSize;
  2862. if (chunkSize == 0) {
  2863. /* regular end of content */
  2864. conn->is_chunked = 2;
  2865. break;
  2866. }
  2867. }
  2868. }
  2869. return (int)all_read;
  2870. }
  2871. return mg_read_inner(conn, buf, len);
  2872. }
  2873. int mg_write(struct mg_connection *conn, const void *buf, size_t len)
  2874. {
  2875. time_t now;
  2876. int64_t n, total, allowed;
  2877. if (conn == NULL) {
  2878. return 0;
  2879. }
  2880. if (conn->throttle > 0) {
  2881. if ((now = time(NULL)) != conn->last_throttle_time) {
  2882. conn->last_throttle_time = now;
  2883. conn->last_throttle_bytes = 0;
  2884. }
  2885. allowed = conn->throttle - conn->last_throttle_bytes;
  2886. if (allowed > (int64_t)len) {
  2887. allowed = (int64_t)len;
  2888. }
  2889. if ((total = push_all(conn->ctx,
  2890. NULL,
  2891. conn->client.sock,
  2892. conn->ssl,
  2893. (const char *)buf,
  2894. (int64_t)allowed)) == allowed) {
  2895. buf = (char *)buf + total;
  2896. conn->last_throttle_bytes += total;
  2897. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  2898. allowed = conn->throttle > (int64_t)len - total
  2899. ? (int64_t)len - total
  2900. : conn->throttle;
  2901. if ((n = push_all(conn->ctx,
  2902. NULL,
  2903. conn->client.sock,
  2904. conn->ssl,
  2905. (const char *)buf,
  2906. (int64_t)allowed)) != allowed) {
  2907. break;
  2908. }
  2909. sleep(1);
  2910. conn->last_throttle_bytes = allowed;
  2911. conn->last_throttle_time = time(NULL);
  2912. buf = (char *)buf + n;
  2913. total += n;
  2914. }
  2915. }
  2916. } else {
  2917. total = push_all(conn->ctx,
  2918. NULL,
  2919. conn->client.sock,
  2920. conn->ssl,
  2921. (const char *)buf,
  2922. (int64_t)len);
  2923. }
  2924. return (int)total;
  2925. }
  2926. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  2927. static int alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  2928. {
  2929. va_list ap_copy;
  2930. size_t size = MG_BUF_LEN;
  2931. int len = -1;
  2932. *buf = NULL;
  2933. while (len == -1) {
  2934. if (*buf)
  2935. mg_free(*buf);
  2936. *buf = (char *)mg_malloc(size *= 4);
  2937. if (!*buf)
  2938. break;
  2939. va_copy(ap_copy, ap);
  2940. len = vsnprintf(*buf, size, fmt, ap_copy);
  2941. va_end(ap_copy);
  2942. }
  2943. return len;
  2944. }
  2945. /* Print message to buffer. If buffer is large enough to hold the message,
  2946. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  2947. * and return allocated buffer. */
  2948. static int alloc_vprintf(char **buf, size_t size, const char *fmt, va_list ap)
  2949. {
  2950. va_list ap_copy;
  2951. int len;
  2952. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  2953. * buffer is too small. Also, older versions of msvcrt.dll do not have
  2954. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  2955. * Therefore, we make two passes: on first pass, get required message
  2956. * length.
  2957. * On second pass, actually print the message. */
  2958. va_copy(ap_copy, ap);
  2959. len = vsnprintf(NULL, 0, fmt, ap_copy);
  2960. va_end(ap_copy);
  2961. if (len < 0) {
  2962. /* C runtime is not standard compliant, vsnprintf() returned -1.
  2963. * Switch to alternative code path that uses incremental allocations.
  2964. */
  2965. va_copy(ap_copy, ap);
  2966. len = alloc_vprintf2(buf, fmt, ap);
  2967. va_end(ap_copy);
  2968. } else if ((size_t)(len) > size && (size = (size_t)(len) + 1) > 0 &&
  2969. (*buf = (char *)mg_malloc(size)) == NULL) {
  2970. len = -1; /* Allocation failed, mark failure */
  2971. } else {
  2972. va_copy(ap_copy, ap);
  2973. IGNORE_UNUSED_RESULT(vsnprintf(*buf, size, fmt, ap_copy));
  2974. va_end(ap_copy);
  2975. }
  2976. return len;
  2977. }
  2978. static int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  2979. {
  2980. char mem[MG_BUF_LEN], *buf = mem;
  2981. int len;
  2982. if ((len = alloc_vprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  2983. len = mg_write(conn, buf, (size_t)len);
  2984. }
  2985. if (buf != mem && buf != NULL) {
  2986. mg_free(buf);
  2987. }
  2988. return len;
  2989. }
  2990. int mg_printf(struct mg_connection *conn, const char *fmt, ...)
  2991. {
  2992. va_list ap;
  2993. int result;
  2994. va_start(ap, fmt);
  2995. result = mg_vprintf(conn, fmt, ap);
  2996. va_end(ap);
  2997. return result;
  2998. }
  2999. int mg_url_decode(const char *src,
  3000. int src_len,
  3001. char *dst,
  3002. int dst_len,
  3003. int is_form_url_encoded)
  3004. {
  3005. int i, j, a, b;
  3006. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  3007. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  3008. if (i < src_len - 2 && src[i] == '%' &&
  3009. isxdigit(*(const unsigned char *)(src + i + 1)) &&
  3010. isxdigit(*(const unsigned char *)(src + i + 2))) {
  3011. a = tolower(*(const unsigned char *)(src + i + 1));
  3012. b = tolower(*(const unsigned char *)(src + i + 2));
  3013. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  3014. i += 2;
  3015. } else if (is_form_url_encoded && src[i] == '+') {
  3016. dst[j] = ' ';
  3017. } else {
  3018. dst[j] = src[i];
  3019. }
  3020. }
  3021. dst[j] = '\0'; /* Null-terminate the destination */
  3022. return i >= src_len ? j : -1;
  3023. }
  3024. int mg_get_var(const char *data,
  3025. size_t data_len,
  3026. const char *name,
  3027. char *dst,
  3028. size_t dst_len)
  3029. {
  3030. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  3031. }
  3032. int mg_get_var2(const char *data,
  3033. size_t data_len,
  3034. const char *name,
  3035. char *dst,
  3036. size_t dst_len,
  3037. size_t occurrence)
  3038. {
  3039. const char *p, *e, *s;
  3040. size_t name_len;
  3041. int len;
  3042. if (dst == NULL || dst_len == 0) {
  3043. len = -2;
  3044. } else if (data == NULL || name == NULL || data_len == 0) {
  3045. len = -1;
  3046. dst[0] = '\0';
  3047. } else {
  3048. name_len = strlen(name);
  3049. e = data + data_len;
  3050. len = -1;
  3051. dst[0] = '\0';
  3052. /* data is "var1=val1&var2=val2...". Find variable first */
  3053. for (p = data; p + name_len < e; p++) {
  3054. if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
  3055. !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  3056. /* Point p to variable value */
  3057. p += name_len + 1;
  3058. /* Point s to the end of the value */
  3059. s = (const char *)memchr(p, '&', (size_t)(e - p));
  3060. if (s == NULL) {
  3061. s = e;
  3062. }
  3063. /* assert(s >= p); */
  3064. if (s < p) {
  3065. return -3;
  3066. }
  3067. /* Decode variable into destination buffer */
  3068. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  3069. /* Redirect error code from -1 to -2 (destination buffer too
  3070. * small). */
  3071. if (len == -1) {
  3072. len = -2;
  3073. }
  3074. break;
  3075. }
  3076. }
  3077. }
  3078. return len;
  3079. }
  3080. int mg_get_cookie(const char *cookie_header,
  3081. const char *var_name,
  3082. char *dst,
  3083. size_t dst_size)
  3084. {
  3085. const char *s, *p, *end;
  3086. int name_len, len = -1;
  3087. if (dst == NULL || dst_size == 0) {
  3088. len = -2;
  3089. } else if (var_name == NULL || (s = cookie_header) == NULL) {
  3090. len = -1;
  3091. dst[0] = '\0';
  3092. } else {
  3093. name_len = (int)strlen(var_name);
  3094. end = s + strlen(s);
  3095. dst[0] = '\0';
  3096. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  3097. if (s[name_len] == '=') {
  3098. s += name_len + 1;
  3099. if ((p = strchr(s, ' ')) == NULL)
  3100. p = end;
  3101. if (p[-1] == ';')
  3102. p--;
  3103. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  3104. s++;
  3105. p--;
  3106. }
  3107. if ((size_t)(p - s) < dst_size) {
  3108. len = (int)(p - s);
  3109. mg_strlcpy(dst, s, (size_t)len + 1);
  3110. } else {
  3111. len = -3;
  3112. }
  3113. break;
  3114. }
  3115. }
  3116. }
  3117. return len;
  3118. }
  3119. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  3120. static void base64_encode(const unsigned char *src, int src_len, char *dst)
  3121. {
  3122. static const char *b64 =
  3123. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3124. int i, j, a, b, c;
  3125. for (i = j = 0; i < src_len; i += 3) {
  3126. a = src[i];
  3127. b = i + 1 >= src_len ? 0 : src[i + 1];
  3128. c = i + 2 >= src_len ? 0 : src[i + 2];
  3129. dst[j++] = b64[a >> 2];
  3130. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3131. if (i + 1 < src_len) {
  3132. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3133. }
  3134. if (i + 2 < src_len) {
  3135. dst[j++] = b64[c & 63];
  3136. }
  3137. }
  3138. while (j % 4 != 0) {
  3139. dst[j++] = '=';
  3140. }
  3141. dst[j++] = '\0';
  3142. }
  3143. #endif
  3144. #if defined(USE_LUA)
  3145. static unsigned char b64reverse(char letter)
  3146. {
  3147. if (letter >= 'A' && letter <= 'Z')
  3148. return letter - 'A';
  3149. if (letter >= 'a' && letter <= 'z')
  3150. return letter - 'a' + 26;
  3151. if (letter >= '0' && letter <= '9')
  3152. return letter - '0' + 52;
  3153. if (letter == '+')
  3154. return 62;
  3155. if (letter == '/')
  3156. return 63;
  3157. if (letter == '=')
  3158. return 255; /* normal end */
  3159. return 254; /* error */
  3160. }
  3161. static int
  3162. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  3163. {
  3164. int i;
  3165. unsigned char a, b, c, d;
  3166. *dst_len = 0;
  3167. for (i = 0; i < src_len; i += 4) {
  3168. a = b64reverse(src[i]);
  3169. if (a >= 254)
  3170. return i;
  3171. b = b64reverse(i + 1 >= src_len ? 0 : src[i + 1]);
  3172. if (b >= 254)
  3173. return i + 1;
  3174. c = b64reverse(i + 2 >= src_len ? 0 : src[i + 2]);
  3175. if (c == 254)
  3176. return i + 2;
  3177. d = b64reverse(i + 3 >= src_len ? 0 : src[i + 3]);
  3178. if (c == 254)
  3179. return i + 3;
  3180. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  3181. if (c != 255) {
  3182. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  3183. if (d != 255) {
  3184. dst[(*dst_len)++] = (c << 6) + d;
  3185. }
  3186. }
  3187. }
  3188. return -1;
  3189. }
  3190. #endif
  3191. static int is_put_or_delete_method(const struct mg_connection *conn)
  3192. {
  3193. if (conn) {
  3194. const char *s = conn->request_info.request_method;
  3195. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
  3196. !strcmp(s, "MKCOL"));
  3197. }
  3198. return 0;
  3199. }
  3200. static void
  3201. interpret_uri(struct mg_connection *conn, /* in: request */
  3202. char *filename, /* out: filename */
  3203. size_t filename_buf_len, /* in: size of filename buffer */
  3204. struct file *filep, /* out: file structure */
  3205. int *is_script_ressource, /* out: handled by a script? */
  3206. int *is_websocket_request, /* out: websocket connetion? */
  3207. int *is_put_or_delete_request /* out: put/delete a file? */
  3208. )
  3209. {
  3210. if (conn && conn->ctx) {
  3211. const char *uri = conn->request_info.uri;
  3212. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  3213. #if !defined(NO_FILES)
  3214. const char *rewrite;
  3215. struct vec a, b;
  3216. char *p;
  3217. int match_len;
  3218. char gz_path[PATH_MAX];
  3219. char const *accept_encoding;
  3220. #endif
  3221. memset(filep, 0, sizeof(*filep));
  3222. *filename = 0;
  3223. *is_script_ressource = 0;
  3224. *is_put_or_delete_request = is_put_or_delete_method(conn);
  3225. #if defined(USE_WEBSOCKET)
  3226. *is_websocket_request = is_websocket_protocol(conn);
  3227. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  3228. root = conn->ctx->config[WEBSOCKET_ROOT];
  3229. }
  3230. #else
  3231. *is_websocket_request = 0;
  3232. #endif
  3233. #if !defined(NO_FILES)
  3234. /* Note that root == NULL is a regular use case here. This occurs,
  3235. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  3236. * config is not required. */
  3237. if (root == NULL) {
  3238. /* all file related outputs have already been set to 0, just return
  3239. */
  3240. return;
  3241. }
  3242. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  3243. * of the path one byte on the right.
  3244. * If document_root is NULL, leave the file empty. */
  3245. mg_snprintf(conn, filename, filename_buf_len - 1, "%s%s", root, uri);
  3246. rewrite = conn->ctx->config[REWRITE];
  3247. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  3248. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  3249. mg_snprintf(conn,
  3250. filename,
  3251. filename_buf_len - 1,
  3252. "%.*s%s",
  3253. (int)b.len,
  3254. b.ptr,
  3255. uri + match_len);
  3256. break;
  3257. }
  3258. }
  3259. /* Local file path and name, corresponding to requested URI
  3260. * is now stored in "filename" variable. */
  3261. if (mg_stat(conn, filename, filep)) {
  3262. /* File exists. Check if it is a script type. */
  3263. if (0
  3264. #if !defined(NO_CGI)
  3265. ||
  3266. match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3267. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3268. filename) > 0
  3269. #endif
  3270. #if defined(USE_LUA)
  3271. ||
  3272. match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3273. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3274. filename) > 0
  3275. #endif
  3276. ) {
  3277. /* The request addresses a CGI script or a Lua script. The URI
  3278. * corresponds to the script itself (like /path/script.cgi),
  3279. * and there is no additional resource path
  3280. * (like /path/script.cgi/something).
  3281. * Requests that modify (replace or delete) a resource, like
  3282. * PUT and DELETE requests, should replace/delete the script
  3283. * file.
  3284. * Requests that read or write from/to a resource, like GET and
  3285. * POST requests, should call the script and return the
  3286. * generated response. */
  3287. *is_script_ressource = !*is_put_or_delete_request;
  3288. }
  3289. return;
  3290. }
  3291. /* If we can't find the actual file, look for the file
  3292. * with the same name but a .gz extension. If we find it,
  3293. * use that and set the gzipped flag in the file struct
  3294. * to indicate that the response need to have the content-
  3295. * encoding: gzip header.
  3296. * We can only do this if the browser declares support. */
  3297. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) !=
  3298. NULL) {
  3299. if (strstr(accept_encoding, "gzip") != NULL) {
  3300. snprintf(gz_path, sizeof(gz_path), "%s.gz", filename);
  3301. if (mg_stat(conn, gz_path, filep)) {
  3302. if (filep)
  3303. filep->gzipped = 1;
  3304. /* Currently gz files can not be scripts. */
  3305. return;
  3306. }
  3307. }
  3308. }
  3309. /* Support PATH_INFO for CGI scripts. */
  3310. for (p = filename + strlen(filename); p > filename + 1; p--) {
  3311. if (*p == '/') {
  3312. *p = '\0';
  3313. if ((0
  3314. #if !defined(NO_CGI)
  3315. ||
  3316. match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3317. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3318. filename) > 0
  3319. #endif
  3320. #if defined(USE_LUA)
  3321. ||
  3322. match_prefix(
  3323. conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  3324. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  3325. filename) > 0
  3326. #endif
  3327. ) &&
  3328. mg_stat(conn, filename, filep)) {
  3329. /* Shift PATH_INFO block one character right, e.g.
  3330. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  3331. * conn->path_info is pointing to the local variable "path"
  3332. * declared in handle_request(), so PATH_INFO is not valid
  3333. * after handle_request returns. */
  3334. conn->path_info = p + 1;
  3335. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  3336. * trailing \0 */
  3337. p[1] = '/';
  3338. *is_script_ressource = 1;
  3339. break;
  3340. } else {
  3341. *p = '/';
  3342. }
  3343. }
  3344. }
  3345. #endif
  3346. }
  3347. }
  3348. /* Check whether full request is buffered. Return:
  3349. * -1 if request is malformed
  3350. * 0 if request is not yet fully buffered
  3351. * >0 actual request length, including last \r\n\r\n */
  3352. static int get_request_len(const char *buf, int buflen)
  3353. {
  3354. const char *s, *e;
  3355. int len = 0;
  3356. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  3357. /* Control characters are not allowed but >=128 is. */
  3358. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n' &&
  3359. *(const unsigned char *)s < 128) {
  3360. len = -1;
  3361. break; /* [i_a] abort scan as soon as one malformed character is
  3362. * found; */
  3363. /* don't let subsequent \r\n\r\n win us over anyhow */
  3364. } else if (s[0] == '\n' && s[1] == '\n') {
  3365. len = (int)(s - buf) + 2;
  3366. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  3367. len = (int)(s - buf) + 3;
  3368. }
  3369. return len;
  3370. }
  3371. /* Convert month to the month number. Return -1 on error, or month number */
  3372. static int get_month_index(const char *s)
  3373. {
  3374. size_t i;
  3375. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  3376. if (!strcmp(s, month_names[i]))
  3377. return (int)i;
  3378. return -1;
  3379. }
  3380. static int num_leap_years(int year)
  3381. {
  3382. return year / 4 - year / 100 + year / 400;
  3383. }
  3384. /* Parse UTC date-time string, and return the corresponding time_t value. */
  3385. static time_t parse_date_string(const char *datetime)
  3386. {
  3387. static const unsigned short days_before_month[] = {
  3388. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
  3389. char month_str[32] = {0};
  3390. int second, minute, hour, day, month, year, leap_days, days;
  3391. time_t result = (time_t)0;
  3392. if ((sscanf(datetime,
  3393. "%d/%3s/%d %d:%d:%d",
  3394. &day,
  3395. month_str,
  3396. &year,
  3397. &hour,
  3398. &minute,
  3399. &second) == 6) ||
  3400. (sscanf(datetime,
  3401. "%d %3s %d %d:%d:%d",
  3402. &day,
  3403. month_str,
  3404. &year,
  3405. &hour,
  3406. &minute,
  3407. &second) == 6) ||
  3408. (sscanf(datetime,
  3409. "%*3s, %d %3s %d %d:%d:%d",
  3410. &day,
  3411. month_str,
  3412. &year,
  3413. &hour,
  3414. &minute,
  3415. &second) == 6) ||
  3416. (sscanf(datetime,
  3417. "%d-%3s-%d %d:%d:%d",
  3418. &day,
  3419. month_str,
  3420. &year,
  3421. &hour,
  3422. &minute,
  3423. &second) == 6)) {
  3424. month = get_month_index(month_str);
  3425. if ((month >= 0) && (year > 1970)) {
  3426. leap_days = num_leap_years(year) - num_leap_years(1970);
  3427. year -= 1970;
  3428. days =
  3429. year * 365 + days_before_month[month] + (day - 1) + leap_days;
  3430. result = (time_t)days * 24 * 3600 + (time_t)hour * 3600 +
  3431. minute * 60 + second;
  3432. }
  3433. }
  3434. return result;
  3435. }
  3436. /* Protect against directory disclosure attack by removing '..',
  3437. * excessive '/' and '\' characters */
  3438. static void remove_double_dots_and_double_slashes(char *s)
  3439. {
  3440. char *p = s;
  3441. while (*s != '\0') {
  3442. *p++ = *s++;
  3443. if (s[-1] == '/' || s[-1] == '\\') {
  3444. /* Skip all following slashes, backslashes and double-dots */
  3445. while (s[0] != '\0') {
  3446. if (s[0] == '/' || s[0] == '\\') {
  3447. s++;
  3448. } else if (s[0] == '.' && s[1] == '.') {
  3449. s += 2;
  3450. } else {
  3451. break;
  3452. }
  3453. }
  3454. }
  3455. }
  3456. *p = '\0';
  3457. }
  3458. static const struct {
  3459. const char *extension;
  3460. size_t ext_len;
  3461. const char *mime_type;
  3462. } builtin_mime_types[] = {
  3463. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  3464. * application types */
  3465. {".doc", 4, "application/msword"},
  3466. {".eps", 4, "application/postscript"},
  3467. {".exe", 4, "application/octet-stream"},
  3468. {".js", 3, "application/javascript"},
  3469. {".json", 5, "application/json"},
  3470. {".pdf", 4, "application/pdf"},
  3471. {".ps", 3, "application/postscript"},
  3472. {".rtf", 4, "application/rtf"},
  3473. {".xhtml", 6, "application/xhtml+xml"},
  3474. {".xsl", 4, "application/xml"},
  3475. {".xslt", 5, "application/xml"},
  3476. /* audio */
  3477. {".mp3", 4, "audio/mpeg"},
  3478. {".oga", 4, "audio/ogg"},
  3479. {".ogg", 4, "audio/ogg"},
  3480. /* image */
  3481. {".gif", 4, "image/gif"},
  3482. {".ief", 4, "image/ief"},
  3483. {".jpeg", 5, "image/jpeg"},
  3484. {".jpg", 4, "image/jpeg"},
  3485. {".jpm", 4, "image/jpm"},
  3486. {".jpx", 4, "image/jpx"},
  3487. {".png", 4, "image/png"},
  3488. {".svg", 4, "image/svg+xml"},
  3489. {".tif", 4, "image/tiff"},
  3490. {".tiff", 5, "image/tiff"},
  3491. /* model */
  3492. {".wrl", 4, "model/vrml"},
  3493. /* text */
  3494. {".css", 4, "text/css"},
  3495. {".csv", 4, "text/csv"},
  3496. {".htm", 4, "text/html"},
  3497. {".html", 5, "text/html"},
  3498. {".sgm", 4, "text/sgml"},
  3499. {".shtm", 5, "text/html"},
  3500. {".shtml", 6, "text/html"},
  3501. {".txt", 4, "text/plain"},
  3502. {".xml", 4, "text/xml"},
  3503. /* video */
  3504. {".mov", 4, "video/quicktime"},
  3505. {".mp4", 4, "video/mp4"},
  3506. {".mpeg", 5, "video/mpeg"},
  3507. {".mpg", 4, "video/mpeg"},
  3508. {".ogv", 4, "video/ogg"},
  3509. {".qt", 3, "video/quicktime"},
  3510. /* not registered types
  3511. * (http://reference.sitepoint.com/html/mime-types-full,
  3512. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  3513. {".arj", 4, "application/x-arj-compressed"},
  3514. {".gz", 3, "application/x-gunzip"},
  3515. {".rar", 4, "application/x-arj-compressed"},
  3516. {".swf", 4, "application/x-shockwave-flash"},
  3517. {".tar", 4, "application/x-tar"},
  3518. {".tgz", 4, "application/x-tar-gz"},
  3519. {".torrent", 8, "application/x-bittorrent"},
  3520. {".ppt", 4, "application/x-mspowerpoint"},
  3521. {".xls", 4, "application/x-msexcel"},
  3522. {".zip", 4, "application/x-zip-compressed"},
  3523. {".aac",
  3524. 4,
  3525. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  3526. {".aif", 4, "audio/x-aif"},
  3527. {".m3u", 4, "audio/x-mpegurl"},
  3528. {".mid", 4, "audio/x-midi"},
  3529. {".ra", 3, "audio/x-pn-realaudio"},
  3530. {".ram", 4, "audio/x-pn-realaudio"},
  3531. {".wav", 4, "audio/x-wav"},
  3532. {".bmp", 4, "image/bmp"},
  3533. {".ico", 4, "image/x-icon"},
  3534. {".pct", 4, "image/x-pct"},
  3535. {".pict", 5, "image/pict"},
  3536. {".rgb", 4, "image/x-rgb"},
  3537. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  3538. {".asf", 4, "video/x-ms-asf"},
  3539. {".avi", 4, "video/x-msvideo"},
  3540. {".m4v", 4, "video/x-m4v"},
  3541. {NULL, 0, NULL}};
  3542. const char *mg_get_builtin_mime_type(const char *path)
  3543. {
  3544. const char *ext;
  3545. size_t i, path_len;
  3546. path_len = strlen(path);
  3547. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  3548. ext = path + (path_len - builtin_mime_types[i].ext_len);
  3549. if (path_len > builtin_mime_types[i].ext_len &&
  3550. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  3551. return builtin_mime_types[i].mime_type;
  3552. }
  3553. }
  3554. return "text/plain";
  3555. }
  3556. /* Look at the "path" extension and figure what mime type it has.
  3557. * Store mime type in the vector. */
  3558. static void
  3559. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  3560. {
  3561. struct vec ext_vec, mime_vec;
  3562. const char *list, *ext;
  3563. size_t path_len;
  3564. path_len = strlen(path);
  3565. if (ctx == NULL || vec == NULL) {
  3566. return;
  3567. }
  3568. /* Scan user-defined mime types first, in case user wants to
  3569. * override default mime types. */
  3570. list = ctx->config[EXTRA_MIME_TYPES];
  3571. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  3572. /* ext now points to the path suffix */
  3573. ext = path + path_len - ext_vec.len;
  3574. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  3575. *vec = mime_vec;
  3576. return;
  3577. }
  3578. }
  3579. vec->ptr = mg_get_builtin_mime_type(path);
  3580. vec->len = strlen(vec->ptr);
  3581. }
  3582. /* Stringify binary data. Output buffer must be twice as big as input,
  3583. * because each byte takes 2 bytes in string representation */
  3584. static void bin2str(char *to, const unsigned char *p, size_t len)
  3585. {
  3586. static const char *hex = "0123456789abcdef";
  3587. for (; len--; p++) {
  3588. *to++ = hex[p[0] >> 4];
  3589. *to++ = hex[p[0] & 0x0f];
  3590. }
  3591. *to = '\0';
  3592. }
  3593. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  3594. char *mg_md5(char buf[33], ...)
  3595. {
  3596. md5_byte_t hash[16];
  3597. const char *p;
  3598. va_list ap;
  3599. md5_state_t ctx;
  3600. md5_init(&ctx);
  3601. va_start(ap, buf);
  3602. while ((p = va_arg(ap, const char *)) != NULL) {
  3603. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  3604. }
  3605. va_end(ap);
  3606. md5_finish(&ctx, hash);
  3607. bin2str(buf, hash, sizeof(hash));
  3608. return buf;
  3609. }
  3610. /* Check the user's password, return 1 if OK */
  3611. static int check_password(const char *method,
  3612. const char *ha1,
  3613. const char *uri,
  3614. const char *nonce,
  3615. const char *nc,
  3616. const char *cnonce,
  3617. const char *qop,
  3618. const char *response)
  3619. {
  3620. char ha2[32 + 1], expected_response[32 + 1];
  3621. /* Some of the parameters may be NULL */
  3622. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL ||
  3623. qop == NULL || response == NULL) {
  3624. return 0;
  3625. }
  3626. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  3627. /* TODO(lsm): check for authentication timeout */
  3628. if (/* strcmp(dig->uri, c->ouri) != 0 || */
  3629. strlen(response) != 32
  3630. /* || now - strtoul(dig->nonce, NULL, 10) > 3600 */
  3631. ) {
  3632. return 0;
  3633. }
  3634. mg_md5(ha2, method, ":", uri, NULL);
  3635. mg_md5(expected_response,
  3636. ha1,
  3637. ":",
  3638. nonce,
  3639. ":",
  3640. nc,
  3641. ":",
  3642. cnonce,
  3643. ":",
  3644. qop,
  3645. ":",
  3646. ha2,
  3647. NULL);
  3648. return mg_strcasecmp(response, expected_response) == 0;
  3649. }
  3650. /* Use the global passwords file, if specified by auth_gpass option,
  3651. * or search for .htpasswd in the requested directory. */
  3652. static void
  3653. open_auth_file(struct mg_connection *conn, const char *path, struct file *filep)
  3654. {
  3655. if (conn != NULL && conn->ctx != NULL) {
  3656. char name[PATH_MAX];
  3657. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  3658. struct file file = STRUCT_FILE_INITIALIZER;
  3659. if (gpass != NULL) {
  3660. /* Use global passwords file */
  3661. if (!mg_fopen(conn, gpass, "r", filep)) {
  3662. #ifdef DEBUG
  3663. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  3664. #endif
  3665. }
  3666. /* Important: using local struct file to test path for is_directory
  3667. * flag.
  3668. * If filep is used, mg_stat() makes it appear as if auth file was
  3669. * opened. */
  3670. } else if (mg_stat(conn, path, &file) && file.is_directory) {
  3671. mg_snprintf(conn,
  3672. name,
  3673. sizeof(name),
  3674. "%s%c%s",
  3675. path,
  3676. '/',
  3677. PASSWORDS_FILE_NAME);
  3678. if (!mg_fopen(conn, name, "r", filep)) {
  3679. #ifdef DEBUG
  3680. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  3681. #endif
  3682. }
  3683. } else {
  3684. /* Try to find .htpasswd in requested directory. */
  3685. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  3686. if (e[0] == '/') {
  3687. break;
  3688. }
  3689. }
  3690. mg_snprintf(conn,
  3691. name,
  3692. sizeof(name),
  3693. "%.*s%c%s",
  3694. (int)(e - p),
  3695. p,
  3696. '/',
  3697. PASSWORDS_FILE_NAME);
  3698. if (!mg_fopen(conn, name, "r", filep)) {
  3699. #ifdef DEBUG
  3700. mg_cry(conn, "fopen(%s): %s", name, strerror(ERRNO));
  3701. #endif
  3702. }
  3703. }
  3704. }
  3705. }
  3706. /* Parsed Authorization header */
  3707. struct ah {
  3708. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  3709. };
  3710. /* Return 1 on success. Always initializes the ah structure. */
  3711. static int parse_auth_header(struct mg_connection *conn,
  3712. char *buf,
  3713. size_t buf_size,
  3714. struct ah *ah)
  3715. {
  3716. char *name, *value, *s;
  3717. const char *auth_header;
  3718. unsigned long nonce;
  3719. if (!ah || !conn)
  3720. return 0;
  3721. (void)memset(ah, 0, sizeof(*ah));
  3722. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  3723. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  3724. return 0;
  3725. }
  3726. /* Make modifiable copy of the auth header */
  3727. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  3728. s = buf;
  3729. /* Parse authorization header */
  3730. for (;;) {
  3731. /* Gobble initial spaces */
  3732. while (isspace(*(unsigned char *)s)) {
  3733. s++;
  3734. }
  3735. name = skip_quoted(&s, "=", " ", 0);
  3736. /* Value is either quote-delimited, or ends at first comma or space. */
  3737. if (s[0] == '\"') {
  3738. s++;
  3739. value = skip_quoted(&s, "\"", " ", '\\');
  3740. if (s[0] == ',') {
  3741. s++;
  3742. }
  3743. } else {
  3744. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  3745. * spaces */
  3746. }
  3747. if (*name == '\0') {
  3748. break;
  3749. }
  3750. if (!strcmp(name, "username")) {
  3751. ah->user = value;
  3752. } else if (!strcmp(name, "cnonce")) {
  3753. ah->cnonce = value;
  3754. } else if (!strcmp(name, "response")) {
  3755. ah->response = value;
  3756. } else if (!strcmp(name, "uri")) {
  3757. ah->uri = value;
  3758. } else if (!strcmp(name, "qop")) {
  3759. ah->qop = value;
  3760. } else if (!strcmp(name, "nc")) {
  3761. ah->nc = value;
  3762. } else if (!strcmp(name, "nonce")) {
  3763. ah->nonce = value;
  3764. }
  3765. }
  3766. #ifndef NO_NONCE_CHECK
  3767. /* Convert the nonce from the client to a number and check it. */
  3768. /* Server side nonce check is valuable in all situations but one: if the
  3769. * server restarts frequently,
  3770. * but the client should not see that, so the server should accept nonces
  3771. * from
  3772. * previous starts. */
  3773. if (ah->nonce == NULL) {
  3774. return 0;
  3775. }
  3776. s = NULL;
  3777. nonce = strtoul(ah->nonce, &s, 10);
  3778. if ((s == NULL) || (*s != 0)) {
  3779. return 0;
  3780. }
  3781. nonce ^= (uintptr_t)(conn->ctx);
  3782. if (nonce < conn->ctx->start_time) {
  3783. /* nonce is from a previous start of the server and no longer valid
  3784. * (replay attack?) */
  3785. return 0;
  3786. }
  3787. if (nonce >= conn->ctx->start_time + conn->ctx->nonce_count) {
  3788. return 0;
  3789. }
  3790. #endif
  3791. /* CGI needs it as REMOTE_USER */
  3792. if (ah->user != NULL) {
  3793. conn->request_info.remote_user = mg_strdup(ah->user);
  3794. } else {
  3795. return 0;
  3796. }
  3797. return 1;
  3798. }
  3799. static char *mg_fgets(char *buf, size_t size, struct file *filep, char **p)
  3800. {
  3801. char *eof;
  3802. size_t len;
  3803. char *memend;
  3804. if (!filep)
  3805. return NULL;
  3806. if (filep->membuf != NULL && *p != NULL) {
  3807. memend = (char *)&filep->membuf[filep->size];
  3808. /* Search for \n from p till the end of stream */
  3809. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  3810. if (eof != NULL) {
  3811. eof += 1; /* Include \n */
  3812. } else {
  3813. eof = memend; /* Copy remaining data */
  3814. }
  3815. len = (size_t)(eof - *p) > size - 1 ? size - 1 : (size_t)(eof - *p);
  3816. memcpy(buf, *p, len);
  3817. buf[len] = '\0';
  3818. *p += len;
  3819. return len ? eof : NULL;
  3820. } else if (filep->fp != NULL) {
  3821. return fgets(buf, (int)size, filep->fp);
  3822. } else {
  3823. return NULL;
  3824. }
  3825. }
  3826. struct read_auth_file_struct {
  3827. struct mg_connection *conn;
  3828. struct ah ah;
  3829. char *domain;
  3830. char buf[256 + 256 + 40];
  3831. char *f_user;
  3832. char *f_domain;
  3833. char *f_ha1;
  3834. };
  3835. static int read_auth_file(struct file *filep,
  3836. struct read_auth_file_struct *workdata)
  3837. {
  3838. char *p;
  3839. int is_authorized = 0;
  3840. struct file fp;
  3841. size_t l;
  3842. if (!filep || !workdata)
  3843. return 0;
  3844. /* Loop over passwords file */
  3845. p = (char *)filep->membuf;
  3846. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  3847. l = strlen(workdata->buf);
  3848. while (l > 0) {
  3849. if (isspace(workdata->buf[l - 1]) ||
  3850. iscntrl(workdata->buf[l - 1])) {
  3851. l--;
  3852. workdata->buf[l] = 0;
  3853. } else
  3854. break;
  3855. }
  3856. if (l < 1)
  3857. continue;
  3858. workdata->f_user = workdata->buf;
  3859. if (workdata->f_user[0] == ':') {
  3860. /* user names may not contain a ':' and may not be empty,
  3861. * so lines starting with ':' may be used for a special purpose */
  3862. if (workdata->f_user[1] == '#') {
  3863. /* :# is a comment */
  3864. continue;
  3865. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  3866. if (mg_fopen(workdata->conn, workdata->f_user + 9, "r", &fp)) {
  3867. is_authorized = read_auth_file(&fp, workdata);
  3868. mg_fclose(&fp);
  3869. } else {
  3870. mg_cry(workdata->conn,
  3871. "%s: cannot open authorization file: %s",
  3872. __func__,
  3873. workdata->buf);
  3874. }
  3875. continue;
  3876. }
  3877. /* everything is invalid for the moment (might change in the
  3878. * future) */
  3879. mg_cry(workdata->conn,
  3880. "%s: syntax error in authorization file: %s",
  3881. __func__,
  3882. workdata->buf);
  3883. continue;
  3884. }
  3885. workdata->f_domain = strchr(workdata->f_user, ':');
  3886. if (workdata->f_domain == NULL) {
  3887. mg_cry(workdata->conn,
  3888. "%s: syntax error in authorization file: %s",
  3889. __func__,
  3890. workdata->buf);
  3891. continue;
  3892. }
  3893. *(workdata->f_domain) = 0;
  3894. (workdata->f_domain)++;
  3895. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  3896. if (workdata->f_ha1 == NULL) {
  3897. mg_cry(workdata->conn,
  3898. "%s: syntax error in authorization file: %s",
  3899. __func__,
  3900. workdata->buf);
  3901. continue;
  3902. }
  3903. *(workdata->f_ha1) = 0;
  3904. (workdata->f_ha1)++;
  3905. if (!strcmp(workdata->ah.user, workdata->f_user) &&
  3906. !strcmp(workdata->domain, workdata->f_domain)) {
  3907. return check_password(workdata->conn->request_info.request_method,
  3908. workdata->f_ha1,
  3909. workdata->ah.uri,
  3910. workdata->ah.nonce,
  3911. workdata->ah.nc,
  3912. workdata->ah.cnonce,
  3913. workdata->ah.qop,
  3914. workdata->ah.response);
  3915. }
  3916. }
  3917. return is_authorized;
  3918. }
  3919. /* Authorize against the opened passwords file. Return 1 if authorized. */
  3920. static int authorize(struct mg_connection *conn, struct file *filep)
  3921. {
  3922. struct read_auth_file_struct workdata;
  3923. char buf[MG_BUF_LEN];
  3924. if (!conn || !conn->ctx)
  3925. return 0;
  3926. memset(&workdata, 0, sizeof(workdata));
  3927. workdata.conn = conn;
  3928. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  3929. return 0;
  3930. }
  3931. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  3932. return read_auth_file(filep, &workdata);
  3933. }
  3934. /* Return 1 if request is authorised, 0 otherwise. */
  3935. static int check_authorization(struct mg_connection *conn, const char *path)
  3936. {
  3937. char fname[PATH_MAX];
  3938. struct vec uri_vec, filename_vec;
  3939. const char *list;
  3940. struct file file = STRUCT_FILE_INITIALIZER;
  3941. int authorized = 1;
  3942. if (!conn || !conn->ctx)
  3943. return 0;
  3944. list = conn->ctx->config[PROTECT_URI];
  3945. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  3946. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  3947. mg_snprintf(conn,
  3948. fname,
  3949. sizeof(fname),
  3950. "%.*s",
  3951. (int)filename_vec.len,
  3952. filename_vec.ptr);
  3953. if (!mg_fopen(conn, fname, "r", &file)) {
  3954. mg_cry(conn,
  3955. "%s: cannot open %s: %s",
  3956. __func__,
  3957. fname,
  3958. strerror(errno));
  3959. }
  3960. break;
  3961. }
  3962. }
  3963. if (!is_file_opened(&file)) {
  3964. open_auth_file(conn, path, &file);
  3965. }
  3966. if (is_file_opened(&file)) {
  3967. authorized = authorize(conn, &file);
  3968. mg_fclose(&file);
  3969. }
  3970. return authorized;
  3971. }
  3972. static void send_authorization_request(struct mg_connection *conn)
  3973. {
  3974. char date[64];
  3975. time_t curtime = time(NULL);
  3976. if (conn && conn->ctx) {
  3977. unsigned long nonce = (unsigned long)(conn->ctx->start_time);
  3978. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  3979. nonce += conn->ctx->nonce_count;
  3980. ++conn->ctx->nonce_count;
  3981. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  3982. nonce ^= (uintptr_t)(conn->ctx);
  3983. conn->status_code = 401;
  3984. conn->must_close = 1;
  3985. gmt_time_string(date, sizeof(date), &curtime);
  3986. mg_printf(conn,
  3987. "HTTP/1.1 401 Unauthorized\r\n"
  3988. "Date: %s\r\n"
  3989. "Connection: %s\r\n"
  3990. "Content-Length: 0\r\n"
  3991. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  3992. "nonce=\"%lu\"\r\n\r\n",
  3993. date,
  3994. suggest_connection_header(conn),
  3995. conn->ctx->config[AUTHENTICATION_DOMAIN],
  3996. nonce);
  3997. }
  3998. }
  3999. static int is_authorized_for_put(struct mg_connection *conn)
  4000. {
  4001. if (conn) {
  4002. struct file file = STRUCT_FILE_INITIALIZER;
  4003. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  4004. int ret = 0;
  4005. if (passfile != NULL && mg_fopen(conn, passfile, "r", &file)) {
  4006. ret = authorize(conn, &file);
  4007. mg_fclose(&file);
  4008. }
  4009. return ret;
  4010. }
  4011. return 0;
  4012. }
  4013. int mg_modify_passwords_file(const char *fname,
  4014. const char *domain,
  4015. const char *user,
  4016. const char *pass)
  4017. {
  4018. int found, i;
  4019. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  4020. FILE *fp, *fp2;
  4021. found = 0;
  4022. fp = fp2 = NULL;
  4023. /* Regard empty password as no password - remove user record. */
  4024. if (pass != NULL && pass[0] == '\0') {
  4025. pass = NULL;
  4026. }
  4027. /* Other arguments must not be empty */
  4028. if (fname == NULL || domain == NULL || user == NULL)
  4029. return 0;
  4030. /* Using the given file format, user name and domain must not contain ':'
  4031. */
  4032. if (strchr(user, ':') != NULL)
  4033. return 0;
  4034. if (strchr(domain, ':') != NULL)
  4035. return 0;
  4036. /* Do not allow control characters like newline in user name and domain.
  4037. * Do not allow excessively long names either. */
  4038. for (i = 0; i < 255 && user[i] != 0; i++) {
  4039. if (iscntrl(user[i]))
  4040. return 0;
  4041. }
  4042. if (user[i])
  4043. return 0;
  4044. for (i = 0; i < 255 && domain[i] != 0; i++) {
  4045. if (iscntrl(domain[i]))
  4046. return 0;
  4047. }
  4048. if (domain[i])
  4049. return 0;
  4050. /* Create a temporary file name */
  4051. (void)snprintf(tmp, sizeof(tmp) - 1, "%s.tmp", fname);
  4052. tmp[sizeof(tmp) - 1] = 0;
  4053. /* Create the file if does not exist */
  4054. if ((fp = fopen(fname, "a+")) != NULL) {
  4055. (void)fclose(fp);
  4056. }
  4057. /* Open the given file and temporary file */
  4058. if ((fp = fopen(fname, "r")) == NULL) {
  4059. return 0;
  4060. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  4061. fclose(fp);
  4062. return 0;
  4063. }
  4064. /* Copy the stuff to temporary file */
  4065. while (fgets(line, sizeof(line), fp) != NULL) {
  4066. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  4067. continue;
  4068. }
  4069. u[255] = 0;
  4070. d[255] = 0;
  4071. if (!strcmp(u, user) && !strcmp(d, domain)) {
  4072. found++;
  4073. if (pass != NULL) {
  4074. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4075. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4076. }
  4077. } else {
  4078. fprintf(fp2, "%s", line);
  4079. }
  4080. }
  4081. /* If new user, just add it */
  4082. if (!found && pass != NULL) {
  4083. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  4084. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  4085. }
  4086. /* Close files */
  4087. fclose(fp);
  4088. fclose(fp2);
  4089. /* Put the temp file in place of real file */
  4090. IGNORE_UNUSED_RESULT(remove(fname));
  4091. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  4092. return 1;
  4093. }
  4094. static int is_valid_port(unsigned int port) { return port < 0xffff; }
  4095. static int mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  4096. {
  4097. struct addrinfo hints, *res, *ressave;
  4098. int ret = 0;
  4099. memset(&hints, 0, sizeof(struct addrinfo));
  4100. hints.ai_family = af;
  4101. if (getaddrinfo(src, NULL, &hints, &res) != 0) {
  4102. /* bad src string or bad address family */
  4103. return 0;
  4104. }
  4105. ressave = res;
  4106. while (res) {
  4107. if (dstlen >= res->ai_addrlen) {
  4108. memcpy(dst, res->ai_addr, res->ai_addrlen);
  4109. ret = 1;
  4110. }
  4111. res = res->ai_next;
  4112. }
  4113. freeaddrinfo(ressave);
  4114. return ret;
  4115. }
  4116. static SOCKET conn2(struct mg_context *ctx /* may be null */,
  4117. const char *host,
  4118. int port,
  4119. int use_ssl,
  4120. char *ebuf,
  4121. size_t ebuf_len)
  4122. {
  4123. union usa sa;
  4124. SOCKET sock = INVALID_SOCKET;
  4125. memset(&sa, 0, sizeof(sa));
  4126. if (ebuf_len > 0) {
  4127. *ebuf = 0;
  4128. }
  4129. if (host == NULL) {
  4130. snprintf(ebuf, ebuf_len, "%s", "NULL host");
  4131. return INVALID_SOCKET;
  4132. }
  4133. if (port < 0 || !is_valid_port((unsigned)port)) {
  4134. snprintf(ebuf, ebuf_len, "%s", "invalid port");
  4135. return INVALID_SOCKET;
  4136. }
  4137. if (use_ssl && (SSLv23_client_method == NULL)) {
  4138. snprintf(ebuf, ebuf_len, "%s", "SSL is not initialized");
  4139. return INVALID_SOCKET;
  4140. }
  4141. if (mg_inet_pton(AF_INET, host, &sa.sin, sizeof(sa.sin))) {
  4142. sa.sin.sin_port = htons((uint16_t)port);
  4143. #ifdef USE_IPV6
  4144. } else if (mg_inet_pton(AF_INET6, host, &sa.sin6, sizeof(sa.sin6))) {
  4145. sa.sin6.sin6_port = htons((uint16_t)port);
  4146. #endif
  4147. } else {
  4148. snprintf(ebuf, ebuf_len, "%s", "host not found");
  4149. return INVALID_SOCKET;
  4150. }
  4151. sock = socket(PF_INET, SOCK_STREAM, 0);
  4152. if (sock == INVALID_SOCKET) {
  4153. snprintf(ebuf, ebuf_len, "socket(): %s", strerror(ERRNO));
  4154. return INVALID_SOCKET;
  4155. }
  4156. set_close_on_exec(sock, fc(ctx));
  4157. /* TODO(mid): IPV6 */
  4158. if (connect(sock, (struct sockaddr *)&sa.sin, sizeof(sa.sin)) != 0) {
  4159. snprintf(
  4160. ebuf, ebuf_len, "connect(%s:%d): %s", host, port, strerror(ERRNO));
  4161. closesocket(sock);
  4162. sock = INVALID_SOCKET;
  4163. }
  4164. return sock;
  4165. }
  4166. int mg_url_encode(const char *src, char *dst, size_t dst_len)
  4167. {
  4168. static const char *dont_escape = "._-$,;~()";
  4169. static const char *hex = "0123456789abcdef";
  4170. char *pos = dst;
  4171. const char *end = dst + dst_len - 1;
  4172. for (; *src != '\0' && pos < end; src++, pos++) {
  4173. if (isalnum(*(const unsigned char *)src) ||
  4174. strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  4175. *pos = *src;
  4176. } else if (pos + 2 < end) {
  4177. pos[0] = '%';
  4178. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  4179. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  4180. pos += 2;
  4181. } else {
  4182. break;
  4183. }
  4184. }
  4185. *pos = '\0';
  4186. return (*src == '\0') ? (int)(pos - dst) : -1;
  4187. }
  4188. static void print_dir_entry(struct de *de)
  4189. {
  4190. char size[64], mod[64], href[PATH_MAX];
  4191. struct tm *tm;
  4192. if (de->file.is_directory) {
  4193. mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
  4194. } else {
  4195. /* We use (signed) cast below because MSVC 6 compiler cannot
  4196. * convert unsigned __int64 to double. Sigh. */
  4197. if (de->file.size < 1024) {
  4198. mg_snprintf(de->conn, size, sizeof(size), "%d", (int)de->file.size);
  4199. } else if (de->file.size < 0x100000) {
  4200. mg_snprintf(de->conn,
  4201. size,
  4202. sizeof(size),
  4203. "%.1fk",
  4204. (double)de->file.size / 1024.0);
  4205. } else if (de->file.size < 0x40000000) {
  4206. mg_snprintf(de->conn,
  4207. size,
  4208. sizeof(size),
  4209. "%.1fM",
  4210. (double)de->file.size / 1048576);
  4211. } else {
  4212. mg_snprintf(de->conn,
  4213. size,
  4214. sizeof(size),
  4215. "%.1fG",
  4216. (double)de->file.size / 1073741824);
  4217. }
  4218. }
  4219. tm = localtime(&de->file.modification_time);
  4220. if (tm != NULL) {
  4221. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  4222. } else {
  4223. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  4224. mod[sizeof(mod) - 1] = '\0';
  4225. }
  4226. mg_url_encode(de->file_name, href, sizeof(href));
  4227. de->conn->num_bytes_sent +=
  4228. mg_printf(de->conn,
  4229. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  4230. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4231. de->conn->request_info.uri,
  4232. href,
  4233. de->file.is_directory ? "/" : "",
  4234. de->file_name,
  4235. de->file.is_directory ? "/" : "",
  4236. mod,
  4237. size);
  4238. }
  4239. /* This function is called from send_directory() and used for
  4240. * sorting directory entries by size, or name, or modification time.
  4241. * On windows, __cdecl specification is needed in case if project is built
  4242. * with __stdcall convention. qsort always requires __cdels callback. */
  4243. static int WINCDECL compare_dir_entries(const void *p1, const void *p2)
  4244. {
  4245. if (p1 && p2) {
  4246. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  4247. const char *query_string = a->conn->request_info.query_string;
  4248. int cmp_result = 0;
  4249. if (query_string == NULL) {
  4250. query_string = "na";
  4251. }
  4252. if (a->file.is_directory && !b->file.is_directory) {
  4253. return -1; /* Always put directories on top */
  4254. } else if (!a->file.is_directory && b->file.is_directory) {
  4255. return 1; /* Always put directories on top */
  4256. } else if (*query_string == 'n') {
  4257. cmp_result = strcmp(a->file_name, b->file_name);
  4258. } else if (*query_string == 's') {
  4259. cmp_result = a->file.size == b->file.size
  4260. ? 0
  4261. : a->file.size > b->file.size ? 1 : -1;
  4262. } else if (*query_string == 'd') {
  4263. cmp_result =
  4264. a->file.modification_time == b->file.modification_time
  4265. ? 0
  4266. : a->file.modification_time > b->file.modification_time
  4267. ? 1
  4268. : -1;
  4269. }
  4270. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  4271. }
  4272. return 0;
  4273. }
  4274. static int must_hide_file(struct mg_connection *conn, const char *path)
  4275. {
  4276. if (conn && conn->ctx) {
  4277. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  4278. const char *pattern = conn->ctx->config[HIDE_FILES];
  4279. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
  4280. (pattern != NULL &&
  4281. match_prefix(pattern, strlen(pattern), path) > 0);
  4282. }
  4283. return 0;
  4284. }
  4285. static int scan_directory(struct mg_connection *conn,
  4286. const char *dir,
  4287. void *data,
  4288. void (*cb)(struct de *, void *))
  4289. {
  4290. char path[PATH_MAX];
  4291. struct dirent *dp;
  4292. DIR *dirp;
  4293. struct de de;
  4294. if ((dirp = opendir(dir)) == NULL) {
  4295. return 0;
  4296. } else {
  4297. de.conn = conn;
  4298. while ((dp = readdir(dirp)) != NULL) {
  4299. /* Do not show current dir and hidden files */
  4300. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") ||
  4301. must_hide_file(conn, dp->d_name)) {
  4302. continue;
  4303. }
  4304. mg_snprintf(
  4305. conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  4306. /* If we don't memset stat structure to zero, mtime will have
  4307. * garbage and strftime() will segfault later on in
  4308. * print_dir_entry(). memset is required only if mg_stat()
  4309. * fails. For more details, see
  4310. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4311. memset(&de.file, 0, sizeof(de.file));
  4312. if (!mg_stat(conn, path, &de.file)) {
  4313. mg_cry(conn,
  4314. "%s: mg_stat(%s) failed: %s",
  4315. __func__,
  4316. path,
  4317. strerror(ERRNO));
  4318. }
  4319. de.file_name = dp->d_name;
  4320. cb(&de, data);
  4321. }
  4322. (void)closedir(dirp);
  4323. }
  4324. return 1;
  4325. }
  4326. static int remove_directory(struct mg_connection *conn, const char *dir)
  4327. {
  4328. char path[PATH_MAX];
  4329. struct dirent *dp;
  4330. DIR *dirp;
  4331. struct de de;
  4332. if ((dirp = opendir(dir)) == NULL) {
  4333. return 0;
  4334. } else {
  4335. de.conn = conn;
  4336. while ((dp = readdir(dirp)) != NULL) {
  4337. /* Do not show current dir (but show hidden files as they will
  4338. * also be removed) */
  4339. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  4340. continue;
  4341. }
  4342. mg_snprintf(
  4343. conn, path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  4344. /* If we don't memset stat structure to zero, mtime will have
  4345. * garbage and strftime() will segfault later on in
  4346. * print_dir_entry(). memset is required only if mg_stat()
  4347. * fails. For more details, see
  4348. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  4349. memset(&de.file, 0, sizeof(de.file));
  4350. if (!mg_stat(conn, path, &de.file)) {
  4351. mg_cry(conn,
  4352. "%s: mg_stat(%s) failed: %s",
  4353. __func__,
  4354. path,
  4355. strerror(ERRNO));
  4356. }
  4357. if (de.file.modification_time) {
  4358. if (de.file.is_directory) {
  4359. remove_directory(conn, path);
  4360. } else {
  4361. mg_remove(path);
  4362. }
  4363. }
  4364. }
  4365. (void)closedir(dirp);
  4366. IGNORE_UNUSED_RESULT(rmdir(dir));
  4367. }
  4368. return 1;
  4369. }
  4370. struct dir_scan_data {
  4371. struct de *entries;
  4372. unsigned int num_entries;
  4373. unsigned int arr_size;
  4374. };
  4375. /* Behaves like realloc(), but frees original pointer on failure */
  4376. static void *realloc2(void *ptr, size_t size)
  4377. {
  4378. void *new_ptr = mg_realloc(ptr, size);
  4379. if (new_ptr == NULL) {
  4380. mg_free(ptr);
  4381. }
  4382. return new_ptr;
  4383. }
  4384. static void dir_scan_callback(struct de *de, void *data)
  4385. {
  4386. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  4387. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  4388. dsd->arr_size *= 2;
  4389. dsd->entries = (struct de *)realloc2(
  4390. dsd->entries, dsd->arr_size * sizeof(dsd->entries[0]));
  4391. }
  4392. if (dsd->entries == NULL) {
  4393. /* TODO(lsm, low): propagate an error to the caller */
  4394. dsd->num_entries = 0;
  4395. } else {
  4396. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  4397. dsd->entries[dsd->num_entries].file = de->file;
  4398. dsd->entries[dsd->num_entries].conn = de->conn;
  4399. dsd->num_entries++;
  4400. }
  4401. }
  4402. static void handle_directory_request(struct mg_connection *conn,
  4403. const char *dir)
  4404. {
  4405. unsigned int i;
  4406. int sort_direction;
  4407. struct dir_scan_data data = {NULL, 0, 128};
  4408. char date[64];
  4409. time_t curtime = time(NULL);
  4410. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  4411. send_http_error(conn,
  4412. 500,
  4413. "Error: Cannot open directory\nopendir(%s): %s",
  4414. dir,
  4415. strerror(ERRNO));
  4416. return;
  4417. }
  4418. gmt_time_string(date, sizeof(date), &curtime);
  4419. if (!conn)
  4420. return;
  4421. sort_direction = conn->request_info.query_string != NULL &&
  4422. conn->request_info.query_string[1] == 'd'
  4423. ? 'a'
  4424. : 'd';
  4425. conn->must_close = 1;
  4426. mg_printf(conn,
  4427. "HTTP/1.1 200 OK\r\n"
  4428. "Date: %s\r\n"
  4429. "Connection: close\r\n"
  4430. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  4431. date);
  4432. conn->num_bytes_sent +=
  4433. mg_printf(conn,
  4434. "<html><head><title>Index of %s</title>"
  4435. "<style>th {text-align: left;}</style></head>"
  4436. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  4437. "<tr><th><a href=\"?n%c\">Name</a></th>"
  4438. "<th><a href=\"?d%c\">Modified</a></th>"
  4439. "<th><a href=\"?s%c\">Size</a></th></tr>"
  4440. "<tr><td colspan=\"3\"><hr></td></tr>",
  4441. conn->request_info.uri,
  4442. conn->request_info.uri,
  4443. sort_direction,
  4444. sort_direction,
  4445. sort_direction);
  4446. /* Print first entry - link to a parent directory */
  4447. conn->num_bytes_sent +=
  4448. mg_printf(conn,
  4449. "<tr><td><a href=\"%s%s\">%s</a></td>"
  4450. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  4451. conn->request_info.uri,
  4452. "..",
  4453. "Parent directory",
  4454. "-",
  4455. "-");
  4456. /* Sort and print directory entries */
  4457. if (data.entries != NULL) {
  4458. qsort(data.entries,
  4459. (size_t)data.num_entries,
  4460. sizeof(data.entries[0]),
  4461. compare_dir_entries);
  4462. for (i = 0; i < data.num_entries; i++) {
  4463. print_dir_entry(&data.entries[i]);
  4464. mg_free(data.entries[i].file_name);
  4465. }
  4466. mg_free(data.entries);
  4467. }
  4468. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  4469. conn->status_code = 200;
  4470. }
  4471. /* Send len bytes from the opened file to the client. */
  4472. static void send_file_data(struct mg_connection *conn,
  4473. struct file *filep,
  4474. int64_t offset,
  4475. int64_t len)
  4476. {
  4477. char buf[MG_BUF_LEN];
  4478. int to_read, num_read, num_written;
  4479. int64_t size;
  4480. /* Sanity check the offset */
  4481. if (!filep)
  4482. return;
  4483. size = filep->size > INT64_MAX ? INT64_MAX : (int64_t)(filep->size);
  4484. offset = offset < 0 ? 0 : offset > size ? size : offset;
  4485. if (len > 0 && filep->membuf != NULL && size > 0) {
  4486. if (len > size - offset) {
  4487. len = size - offset;
  4488. }
  4489. mg_write(conn, filep->membuf + offset, (size_t)len);
  4490. } else if (len > 0 && filep->fp != NULL) {
  4491. if (offset > 0 && fseeko(filep->fp, offset, SEEK_SET) != 0) {
  4492. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  4493. }
  4494. while (len > 0) {
  4495. /* Calculate how much to read from the file in the buffer */
  4496. to_read = sizeof(buf);
  4497. if ((int64_t)to_read > len) {
  4498. to_read = (int)len;
  4499. }
  4500. /* Read from file, exit the loop on error */
  4501. if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->fp)) <=
  4502. 0) {
  4503. break;
  4504. }
  4505. /* Send read bytes to the client, exit the loop on error */
  4506. if ((num_written = mg_write(conn, buf, (size_t)num_read)) !=
  4507. num_read) {
  4508. break;
  4509. }
  4510. /* Both read and were successful, adjust counters */
  4511. if (!conn)
  4512. break;
  4513. conn->num_bytes_sent += num_written;
  4514. len -= num_written;
  4515. }
  4516. }
  4517. }
  4518. static int parse_range_header(const char *header, int64_t *a, int64_t *b)
  4519. {
  4520. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  4521. }
  4522. static void construct_etag(char *buf, size_t buf_len, const struct file *filep)
  4523. {
  4524. if (filep)
  4525. snprintf(buf,
  4526. buf_len,
  4527. "\"%lx.%" INT64_FMT "\"",
  4528. (unsigned long)filep->modification_time,
  4529. filep->size);
  4530. }
  4531. static void fclose_on_exec(struct file *filep, struct mg_connection *conn)
  4532. {
  4533. if (filep != NULL && filep->fp != NULL) {
  4534. #ifdef _WIN32
  4535. (void)conn; /* Unused. */
  4536. #else
  4537. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  4538. mg_cry(conn,
  4539. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4540. __func__,
  4541. strerror(ERRNO));
  4542. }
  4543. #endif
  4544. }
  4545. }
  4546. static void handle_static_file_request(struct mg_connection *conn,
  4547. const char *path,
  4548. struct file *filep)
  4549. {
  4550. char date[64], lm[64], etag[64], range[64];
  4551. const char *msg = "OK", *hdr;
  4552. time_t curtime = time(NULL);
  4553. int64_t cl, r1, r2;
  4554. struct vec mime_vec;
  4555. int n;
  4556. char gz_path[PATH_MAX];
  4557. const char *encoding = "";
  4558. const char *cors1, *cors2, *cors3;
  4559. if (!conn || !conn->ctx || !filep)
  4560. return;
  4561. get_mime_type(conn->ctx, path, &mime_vec);
  4562. if (filep->size > INT64_MAX) {
  4563. send_http_error(conn,
  4564. 500,
  4565. "Error: File size is too large to send\n%" INT64_FMT,
  4566. filep->size);
  4567. }
  4568. cl = (int64_t)filep->size;
  4569. conn->status_code = 200;
  4570. range[0] = '\0';
  4571. /* if this file is in fact a pre-gzipped file, rewrite its filename
  4572. * it's important to rewrite the filename after resolving
  4573. * the mime type from it, to preserve the actual file's type */
  4574. if (filep->gzipped) {
  4575. snprintf(gz_path, sizeof(gz_path), "%s.gz", path);
  4576. path = gz_path;
  4577. encoding = "Content-Encoding: gzip\r\n";
  4578. }
  4579. if (!mg_fopen(conn, path, "rb", filep)) {
  4580. send_http_error(conn,
  4581. 500,
  4582. "Error: Cannot open file\nfopen(%s): %s",
  4583. path,
  4584. strerror(ERRNO));
  4585. return;
  4586. }
  4587. fclose_on_exec(filep, conn);
  4588. /* If Range: header specified, act accordingly */
  4589. r1 = r2 = 0;
  4590. hdr = mg_get_header(conn, "Range");
  4591. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0 &&
  4592. r2 >= 0) {
  4593. /* actually, range requests don't play well with a pre-gzipped
  4594. * file (since the range is specified in the uncompressed space) */
  4595. if (filep->gzipped) {
  4596. send_http_error(
  4597. conn,
  4598. 501,
  4599. "%s",
  4600. "Error: Range requests in gzipped files are not supported");
  4601. mg_fclose(filep);
  4602. return;
  4603. }
  4604. conn->status_code = 206;
  4605. cl = n == 2 ? (r2 > cl ? cl : r2) - r1 + 1 : cl - r1;
  4606. mg_snprintf(conn,
  4607. range,
  4608. sizeof(range),
  4609. "Content-Range: bytes "
  4610. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  4611. r1,
  4612. r1 + cl - 1,
  4613. filep->size);
  4614. msg = "Partial Content";
  4615. }
  4616. hdr = mg_get_header(conn, "Origin");
  4617. if (hdr) {
  4618. /* Cross-origin resource sharing (CORS), see
  4619. * http://www.html5rocks.com/en/tutorials/cors/,
  4620. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  4621. * preflight is not supported for files. */
  4622. cors1 = "Access-Control-Allow-Origin: ";
  4623. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  4624. cors3 = "\r\n";
  4625. } else {
  4626. cors1 = cors2 = cors3 = "";
  4627. }
  4628. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  4629. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  4630. gmt_time_string(date, sizeof(date), &curtime);
  4631. gmt_time_string(lm, sizeof(lm), &filep->modification_time);
  4632. construct_etag(etag, sizeof(etag), filep);
  4633. (void)mg_printf(conn,
  4634. "HTTP/1.1 %d %s\r\n"
  4635. "%s%s%s"
  4636. "Date: %s\r\n"
  4637. "Last-Modified: %s\r\n"
  4638. "Etag: %s\r\n"
  4639. "Content-Type: %.*s\r\n"
  4640. "Content-Length: %" INT64_FMT "\r\n"
  4641. "Connection: %s\r\n"
  4642. "Accept-Ranges: bytes\r\n"
  4643. "%s%s\r\n",
  4644. conn->status_code,
  4645. msg,
  4646. cors1,
  4647. cors2,
  4648. cors3,
  4649. date,
  4650. lm,
  4651. etag,
  4652. (int)mime_vec.len,
  4653. mime_vec.ptr,
  4654. cl,
  4655. suggest_connection_header(conn),
  4656. range,
  4657. encoding);
  4658. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  4659. send_file_data(conn, filep, r1, cl);
  4660. }
  4661. mg_fclose(filep);
  4662. }
  4663. void mg_send_file(struct mg_connection *conn, const char *path)
  4664. {
  4665. struct file file = STRUCT_FILE_INITIALIZER;
  4666. if (mg_stat(conn, path, &file)) {
  4667. if (file.is_directory) {
  4668. if (!conn)
  4669. return;
  4670. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  4671. "yes")) {
  4672. handle_directory_request(conn, path);
  4673. } else {
  4674. send_http_error(
  4675. conn, 403, "%s", "Error: Directory listing denied");
  4676. }
  4677. } else {
  4678. handle_static_file_request(conn, path, &file);
  4679. }
  4680. } else {
  4681. send_http_error(conn, 404, "%s", "Error: File not found");
  4682. }
  4683. }
  4684. /* Parse HTTP headers from the given buffer, advance buffer to the point
  4685. * where parsing stopped. */
  4686. static void parse_http_headers(char **buf, struct mg_request_info *ri)
  4687. {
  4688. int i;
  4689. if (!ri)
  4690. return;
  4691. ri->num_headers = 0;
  4692. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  4693. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  4694. ri->http_headers[i].value = skip(buf, "\r\n");
  4695. if (ri->http_headers[i].name[0] == '\0') {
  4696. break;
  4697. }
  4698. ri->num_headers = i + 1;
  4699. }
  4700. }
  4701. static int is_valid_http_method(const char *method)
  4702. {
  4703. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  4704. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  4705. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  4706. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND") ||
  4707. !strcmp(method, "MKCOL");
  4708. /* TRACE method is not supported for security reasons */
  4709. }
  4710. /* Parse HTTP request, fill in mg_request_info structure.
  4711. * This function modifies the buffer by NUL-terminating
  4712. * HTTP request components, header names and header values. */
  4713. static int parse_http_message(char *buf, int len, struct mg_request_info *ri)
  4714. {
  4715. int is_request, request_length = get_request_len(buf, len);
  4716. if (request_length > 0) {
  4717. if (!ri)
  4718. return 0;
  4719. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  4720. * remote_port */
  4721. ri->remote_user = ri->request_method = ri->uri = ri->http_version =
  4722. NULL;
  4723. ri->num_headers = 0;
  4724. buf[request_length - 1] = '\0';
  4725. /* RFC says that all initial whitespaces should be ingored */
  4726. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  4727. buf++;
  4728. }
  4729. ri->request_method = skip(&buf, " ");
  4730. ri->uri = skip(&buf, " ");
  4731. ri->http_version = skip(&buf, "\r\n");
  4732. /* HTTP message could be either HTTP request or HTTP response, e.g.
  4733. * "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..." */
  4734. is_request = is_valid_http_method(ri->request_method);
  4735. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
  4736. (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  4737. request_length = -1;
  4738. } else {
  4739. if (is_request) {
  4740. ri->http_version += 5;
  4741. }
  4742. parse_http_headers(&buf, ri);
  4743. }
  4744. }
  4745. return request_length;
  4746. }
  4747. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  4748. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  4749. * buffer (which marks the end of HTTP request). Buffer buf may already
  4750. * have some data. The length of the data is stored in nread.
  4751. * Upon every read operation, increase nread by the number of bytes read. */
  4752. static int read_request(
  4753. FILE *fp, struct mg_connection *conn, char *buf, int bufsiz, int *nread)
  4754. {
  4755. int request_len, n = 0;
  4756. struct timespec last_action_time = {0, 0};
  4757. double request_timeout;
  4758. if (!conn)
  4759. return 0;
  4760. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4761. /* value of request_timeout is in seconds, config in milliseconds */
  4762. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4763. } else {
  4764. request_timeout = -1.0;
  4765. }
  4766. request_len = get_request_len(buf, *nread);
  4767. while (
  4768. (conn->ctx->stop_flag == 0) && (*nread < bufsiz) &&
  4769. (request_len == 0) &&
  4770. ((mg_difftimespec(&last_action_time, &(conn->req_time)) <=
  4771. request_timeout) ||
  4772. (request_timeout < 0)) &&
  4773. ((n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout)) >
  4774. 0)) {
  4775. *nread += n;
  4776. /* assert(*nread <= bufsiz); */
  4777. if (*nread > bufsiz)
  4778. return -2;
  4779. request_len = get_request_len(buf, *nread);
  4780. if (request_timeout > 0.0) {
  4781. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  4782. }
  4783. }
  4784. return (request_len <= 0 && n <= 0) ? -1 : request_len;
  4785. }
  4786. /* For given directory path, substitute it to valid index file.
  4787. * Return 1 if index file has been found, 0 if not found.
  4788. * If the file is found, it's stats is returned in stp. */
  4789. static int substitute_index_file(struct mg_connection *conn,
  4790. char *path,
  4791. size_t path_len,
  4792. struct file *filep)
  4793. {
  4794. if (conn && conn->ctx) {
  4795. const char *list = conn->ctx->config[INDEX_FILES];
  4796. struct file file = STRUCT_FILE_INITIALIZER;
  4797. struct vec filename_vec;
  4798. size_t n = strlen(path);
  4799. int found = 0;
  4800. /* The 'path' given to us points to the directory. Remove all trailing
  4801. * directory separator characters from the end of the path, and
  4802. * then append single directory separator character. */
  4803. while (n > 0 && path[n - 1] == '/') {
  4804. n--;
  4805. }
  4806. path[n] = '/';
  4807. /* Traverse index files list. For each entry, append it to the given
  4808. * path and see if the file exists. If it exists, break the loop */
  4809. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  4810. /* Ignore too long entries that may overflow path buffer */
  4811. if (filename_vec.len > path_len - (n + 2))
  4812. continue;
  4813. /* Prepare full path to the index file */
  4814. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  4815. /* Does it exist? */
  4816. if (mg_stat(conn, path, &file)) {
  4817. /* Yes it does, break the loop */
  4818. *filep = file;
  4819. found = 1;
  4820. break;
  4821. }
  4822. }
  4823. /* If no index file exists, restore directory path */
  4824. if (!found) {
  4825. path[n] = '\0';
  4826. }
  4827. return found;
  4828. }
  4829. return 0;
  4830. }
  4831. /* Return True if we should reply 304 Not Modified. */
  4832. static int is_not_modified(const struct mg_connection *conn,
  4833. const struct file *filep)
  4834. {
  4835. char etag[64];
  4836. const char *ims = mg_get_header(conn, "If-Modified-Since");
  4837. const char *inm = mg_get_header(conn, "If-None-Match");
  4838. construct_etag(etag, sizeof(etag), filep);
  4839. if (!filep)
  4840. return 0;
  4841. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  4842. (ims != NULL && filep->modification_time <= parse_date_string(ims));
  4843. }
  4844. static int
  4845. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  4846. {
  4847. const char *expect, *body;
  4848. char buf[MG_BUF_LEN];
  4849. int to_read, nread, success = 0;
  4850. int64_t buffered_len;
  4851. double timeout = -1.0;
  4852. if (!conn) {
  4853. return 0;
  4854. }
  4855. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4856. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4857. }
  4858. expect = mg_get_header(conn, "Expect");
  4859. /* assert(fp != NULL); */
  4860. if (!fp) {
  4861. send_http_error(conn, 500, "%s", "Error: NULL File");
  4862. return 0;
  4863. }
  4864. if (conn->content_len == -1 && !conn->is_chunked) {
  4865. /* Content length is not specified by the client. */
  4866. send_http_error(
  4867. conn, 411, "%s", "Error: Client did not specify content length");
  4868. } else if ((expect != NULL) &&
  4869. (mg_strcasecmp(expect, "100-continue") != 0)) {
  4870. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  4871. send_http_error(
  4872. conn, 417, "Error: Can not fulfill expectation %s", expect);
  4873. } else {
  4874. if (expect != NULL) {
  4875. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  4876. conn->status_code = 100;
  4877. } else {
  4878. conn->status_code = 200;
  4879. }
  4880. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len -
  4881. conn->consumed_content;
  4882. /* assert(buffered_len >= 0); */
  4883. /* assert(conn->consumed_content == 0); */
  4884. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  4885. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  4886. return 0;
  4887. }
  4888. if (buffered_len > 0) {
  4889. if ((int64_t)buffered_len > conn->content_len) {
  4890. buffered_len = (int)conn->content_len;
  4891. }
  4892. body = conn->buf + conn->request_len + conn->consumed_content;
  4893. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  4894. conn->consumed_content += buffered_len;
  4895. }
  4896. nread = 0;
  4897. while (conn->consumed_content < conn->content_len) {
  4898. to_read = sizeof(buf);
  4899. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  4900. to_read = (int)(conn->content_len - conn->consumed_content);
  4901. }
  4902. nread = pull(NULL, conn, buf, to_read, timeout);
  4903. if (nread <= 0 ||
  4904. push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  4905. break;
  4906. }
  4907. conn->consumed_content += nread;
  4908. }
  4909. if (conn->consumed_content == conn->content_len) {
  4910. success = nread >= 0;
  4911. }
  4912. /* Each error code path in this function must send an error */
  4913. if (!success) {
  4914. /* NOTE: Maybe some data has already been sent. */
  4915. /* TODO (low): If some data has been sent, a correct error
  4916. * reply can no longer be sent, so just close the connection */
  4917. send_http_error(conn, 500, "%s", "");
  4918. }
  4919. }
  4920. return success;
  4921. }
  4922. #if !defined(NO_CGI)
  4923. /* This structure helps to create an environment for the spawned CGI program.
  4924. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  4925. * last element must be NULL.
  4926. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  4927. * strings must reside in a contiguous buffer. The end of the buffer is
  4928. * marked by two '\0' characters.
  4929. * We satisfy both worlds: we create an envp array (which is vars), all
  4930. * entries are actually pointers inside buf. */
  4931. struct cgi_env_block {
  4932. struct mg_connection *conn;
  4933. char buf[CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
  4934. unsigned int len; /* Space taken */
  4935. char *vars[MAX_CGI_ENVIR_VARS]; /* char **envp */
  4936. unsigned int nvars; /* Number of variables */
  4937. };
  4938. static char *addenv(struct cgi_env_block *block,
  4939. PRINTF_FORMAT_STRING(const char *fmt),
  4940. ...) PRINTF_ARGS(2, 3);
  4941. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  4942. * pointer into the vars array. */
  4943. static char *addenv(struct cgi_env_block *block, const char *fmt, ...)
  4944. {
  4945. int n, space;
  4946. char *added;
  4947. va_list ap;
  4948. if (!block)
  4949. return NULL;
  4950. /* Calculate how much space is left in the buffer */
  4951. space = (int)(sizeof(block->buf) - block->len) - 2;
  4952. /* assert(space >= 0); */
  4953. if (space < 0)
  4954. return NULL;
  4955. /* Make a pointer to the free space int the buffer */
  4956. added = block->buf + block->len;
  4957. /* Copy VARIABLE=VALUE\0 string into the free space */
  4958. va_start(ap, fmt);
  4959. n = mg_vsnprintf(block->conn, added, (size_t)space, fmt, ap);
  4960. va_end(ap);
  4961. /* Make sure we do not overflow buffer and the envp array */
  4962. if (n > 0 && n + 1 < space && block->nvars + 2 < ARRAY_SIZE(block->vars)) {
  4963. /* Append a pointer to the added string into the envp array */
  4964. block->vars[block->nvars++] = added;
  4965. /* Bump up used length counter. Include \0 terminator */
  4966. block->len += (unsigned int)(n) + 1;
  4967. } else {
  4968. mg_cry(block->conn,
  4969. "%s: CGI env buffer truncated for [%s]",
  4970. __func__,
  4971. fmt);
  4972. }
  4973. return added;
  4974. }
  4975. static void prepare_cgi_environment(struct mg_connection *conn,
  4976. const char *prog,
  4977. struct cgi_env_block *blk)
  4978. {
  4979. const char *s;
  4980. struct vec var_vec;
  4981. char *p, src_addr[IP_ADDR_STR_LEN];
  4982. int i;
  4983. if (conn == NULL || blk == NULL)
  4984. return;
  4985. blk->len = blk->nvars = 0;
  4986. blk->conn = conn;
  4987. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  4988. addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  4989. addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  4990. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  4991. addenv(blk, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  4992. /* Prepare the environment block */
  4993. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  4994. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  4995. addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  4996. /* TODO(lsm, high): fix this for IPv6 case */
  4997. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  4998. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  4999. addenv(blk, "REMOTE_ADDR=%s", src_addr);
  5000. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  5001. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  5002. /* SCRIPT_NAME */
  5003. addenv(blk,
  5004. "SCRIPT_NAME=%.*s",
  5005. (int)strlen(conn->request_info.uri) -
  5006. ((conn->path_info == NULL) ? 0 : (int)strlen(conn->path_info)),
  5007. conn->request_info.uri);
  5008. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  5009. if (conn->path_info == NULL) {
  5010. addenv(blk, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  5011. } else {
  5012. addenv(blk,
  5013. "PATH_TRANSLATED=%s%s",
  5014. conn->ctx->config[DOCUMENT_ROOT],
  5015. conn->path_info);
  5016. }
  5017. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  5018. if ((s = mg_get_header(conn, "Content-Type")) != NULL)
  5019. addenv(blk, "CONTENT_TYPE=%s", s);
  5020. if (conn->request_info.query_string != NULL)
  5021. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  5022. if ((s = mg_get_header(conn, "Content-Length")) != NULL)
  5023. addenv(blk, "CONTENT_LENGTH=%s", s);
  5024. if ((s = getenv("PATH")) != NULL)
  5025. addenv(blk, "PATH=%s", s);
  5026. if (conn->path_info != NULL) {
  5027. addenv(blk, "PATH_INFO=%s", conn->path_info);
  5028. }
  5029. if (conn->status_code > 0) {
  5030. /* CGI error handler should show the status code */
  5031. addenv(blk, "STATUS=%d", conn->status_code);
  5032. }
  5033. #if defined(_WIN32)
  5034. if ((s = getenv("COMSPEC")) != NULL) {
  5035. addenv(blk, "COMSPEC=%s", s);
  5036. }
  5037. if ((s = getenv("SYSTEMROOT")) != NULL) {
  5038. addenv(blk, "SYSTEMROOT=%s", s);
  5039. }
  5040. if ((s = getenv("SystemDrive")) != NULL) {
  5041. addenv(blk, "SystemDrive=%s", s);
  5042. }
  5043. if ((s = getenv("ProgramFiles")) != NULL) {
  5044. addenv(blk, "ProgramFiles=%s", s);
  5045. }
  5046. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  5047. addenv(blk, "ProgramFiles(x86)=%s", s);
  5048. }
  5049. #else
  5050. if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
  5051. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  5052. #endif /* _WIN32 */
  5053. if ((s = getenv("PERLLIB")) != NULL)
  5054. addenv(blk, "PERLLIB=%s", s);
  5055. if (conn->request_info.remote_user != NULL) {
  5056. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  5057. addenv(blk, "%s", "AUTH_TYPE=Digest");
  5058. }
  5059. /* Add all headers as HTTP_* variables */
  5060. for (i = 0; i < conn->request_info.num_headers; i++) {
  5061. p = addenv(blk,
  5062. "HTTP_%s=%s",
  5063. conn->request_info.http_headers[i].name,
  5064. conn->request_info.http_headers[i].value);
  5065. /* Convert variable name into uppercase, and change - to _ */
  5066. for (; *p != '=' && *p != '\0'; p++) {
  5067. if (*p == '-')
  5068. *p = '_';
  5069. *p = (char)toupper(*(unsigned char *)p);
  5070. }
  5071. }
  5072. /* Add user-specified variables */
  5073. s = conn->ctx->config[CGI_ENVIRONMENT];
  5074. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  5075. addenv(blk, "%.*s", (int)var_vec.len, var_vec.ptr);
  5076. }
  5077. blk->vars[blk->nvars++] = NULL;
  5078. blk->buf[blk->len++] = '\0';
  5079. /* assert(blk->nvars < (int) ARRAY_SIZE(blk->vars)); */
  5080. /* assert(blk->len > 0); */
  5081. /* assert(blk->len < (int) sizeof(blk->buf)); */
  5082. if ((blk->nvars >= (int)ARRAY_SIZE(blk->vars)) || (blk->len <= 0) ||
  5083. (blk->len >= (int)sizeof(blk->buf)))
  5084. return;
  5085. }
  5086. static void handle_cgi_request(struct mg_connection *conn, const char *prog)
  5087. {
  5088. char *buf;
  5089. size_t buflen;
  5090. int headers_len, data_len, i, fdin[2] = {0, 0}, fdout[2] = {0, 0};
  5091. const char *status, *status_text, *connection_state;
  5092. char *pbuf, dir[PATH_MAX], *p;
  5093. struct mg_request_info ri;
  5094. struct cgi_env_block blk;
  5095. FILE *in = NULL, *out = NULL;
  5096. struct file fout = STRUCT_FILE_INITIALIZER;
  5097. pid_t pid = (pid_t)-1;
  5098. if (conn == NULL)
  5099. return;
  5100. buf = NULL;
  5101. buflen = 16384;
  5102. prepare_cgi_environment(conn, prog, &blk);
  5103. /* CGI must be executed in its own directory. 'dir' must point to the
  5104. * directory containing executable program, 'p' must point to the
  5105. * executable program name relative to 'dir'. */
  5106. (void)mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  5107. if ((p = strrchr(dir, '/')) != NULL) {
  5108. *p++ = '\0';
  5109. } else {
  5110. dir[0] = '.', dir[1] = '\0';
  5111. p = (char *)prog;
  5112. }
  5113. if (pipe(fdin) != 0 || pipe(fdout) != 0) {
  5114. send_http_error(
  5115. conn, 500, "Error: Cannot create CGI pipe: %s", strerror(ERRNO));
  5116. goto done;
  5117. }
  5118. pid = spawn_process(conn, p, blk.buf, blk.vars, fdin[0], fdout[1], dir);
  5119. if (pid == (pid_t)-1) {
  5120. send_http_error(conn,
  5121. 500,
  5122. "Error: Cannot spawn CGI process [%s]: %s",
  5123. prog,
  5124. strerror(ERRNO));
  5125. goto done;
  5126. }
  5127. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  5128. set_close_on_exec((SOCKET)fdin[0], conn);
  5129. set_close_on_exec((SOCKET)fdin[1], conn);
  5130. set_close_on_exec((SOCKET)fdout[0], conn);
  5131. set_close_on_exec((SOCKET)fdout[1], conn);
  5132. /* Parent closes only one side of the pipes.
  5133. * If we don't mark them as closed, close() attempt before
  5134. * return from this function throws an exception on Windows.
  5135. * Windows does not like when closed descriptor is closed again. */
  5136. (void)close(fdin[0]);
  5137. (void)close(fdout[1]);
  5138. fdin[0] = fdout[1] = -1;
  5139. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  5140. send_http_error(conn,
  5141. 500,
  5142. "Error: CGI can not open fdin\nfopen: %s",
  5143. strerror(ERRNO));
  5144. goto done;
  5145. }
  5146. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  5147. send_http_error(conn,
  5148. 500,
  5149. "Error: CGI can not open fdout\nfopen: %s",
  5150. strerror(ERRNO));
  5151. goto done;
  5152. }
  5153. setbuf(in, NULL);
  5154. setbuf(out, NULL);
  5155. fout.fp = out;
  5156. /* Send POST or PUT data to the CGI process if needed */
  5157. if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  5158. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  5159. /* This is a POST/PUT request */
  5160. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  5161. /* Error sending the body data */
  5162. goto done;
  5163. }
  5164. }
  5165. /* Close so child gets an EOF. */
  5166. fclose(in);
  5167. in = NULL;
  5168. fdin[1] = -1;
  5169. /* Now read CGI reply into a buffer. We need to set correct
  5170. * status code, thus we need to see all HTTP headers first.
  5171. * Do not send anything back to client, until we buffer in all
  5172. * HTTP headers. */
  5173. data_len = 0;
  5174. buf = (char *)mg_malloc(buflen);
  5175. if (buf == NULL) {
  5176. send_http_error(conn,
  5177. 500,
  5178. "Error: Not enough memory for CGI buffer (%u bytes)",
  5179. (unsigned int)buflen);
  5180. goto done;
  5181. }
  5182. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  5183. if (headers_len <= 0) {
  5184. send_http_error(conn,
  5185. 500,
  5186. "Error: CGI program sent malformed or too big "
  5187. "(>%u bytes) HTTP headers: [%.*s]",
  5188. (unsigned)buflen,
  5189. data_len,
  5190. buf);
  5191. goto done;
  5192. }
  5193. pbuf = buf;
  5194. buf[headers_len - 1] = '\0';
  5195. parse_http_headers(&pbuf, &ri);
  5196. /* Make up and send the status line */
  5197. status_text = "OK";
  5198. if ((status = get_header(&ri, "Status")) != NULL) {
  5199. conn->status_code = atoi(status);
  5200. status_text = status;
  5201. while (isdigit(*(unsigned char *)status_text) || *status_text == ' ') {
  5202. status_text++;
  5203. }
  5204. } else if (get_header(&ri, "Location") != NULL) {
  5205. conn->status_code = 302;
  5206. } else {
  5207. conn->status_code = 200;
  5208. }
  5209. connection_state = get_header(&ri, "Connection");
  5210. if (connection_state == NULL ||
  5211. mg_strcasecmp(connection_state, "keep-alive")) {
  5212. conn->must_close = 1;
  5213. }
  5214. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  5215. /* Send headers */
  5216. for (i = 0; i < ri.num_headers; i++) {
  5217. mg_printf(conn,
  5218. "%s: %s\r\n",
  5219. ri.http_headers[i].name,
  5220. ri.http_headers[i].value);
  5221. }
  5222. mg_write(conn, "\r\n", 2);
  5223. /* Send chunk of data that may have been read after the headers */
  5224. conn->num_bytes_sent +=
  5225. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  5226. /* Read the rest of CGI output and send to the client */
  5227. send_file_data(conn, &fout, 0, INT64_MAX);
  5228. done:
  5229. if (pid != (pid_t)-1) {
  5230. kill(pid, SIGKILL);
  5231. #if !defined(_WIN32)
  5232. {
  5233. int st;
  5234. while (waitpid(pid, &st, 0) != -1)
  5235. ; /* clean zombies */
  5236. }
  5237. #endif
  5238. }
  5239. if (fdin[0] != -1) {
  5240. close(fdin[0]);
  5241. }
  5242. if (fdout[1] != -1) {
  5243. close(fdout[1]);
  5244. }
  5245. if (in != NULL) {
  5246. fclose(in);
  5247. } else if (fdin[1] != -1) {
  5248. close(fdin[1]);
  5249. }
  5250. if (out != NULL) {
  5251. fclose(out);
  5252. } else if (fdout[0] != -1) {
  5253. close(fdout[0]);
  5254. }
  5255. if (buf != NULL) {
  5256. mg_free(buf);
  5257. }
  5258. }
  5259. #endif /* !NO_CGI */
  5260. /* For a given PUT path, create all intermediate subdirectories.
  5261. * Return 0 if the path itself is a directory.
  5262. * Return 1 if the path leads to a file.
  5263. * Return -1 for if the path is too long.
  5264. * Return -2 if path can not be created.
  5265. */
  5266. static int put_dir(struct mg_connection *conn, const char *path)
  5267. {
  5268. char buf[PATH_MAX];
  5269. const char *s, *p;
  5270. struct file file = STRUCT_FILE_INITIALIZER;
  5271. size_t len;
  5272. int res = 1;
  5273. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  5274. len = (size_t)(p - path);
  5275. if (len >= sizeof(buf)) {
  5276. /* path too long */
  5277. res = -1;
  5278. break;
  5279. }
  5280. memcpy(buf, path, len);
  5281. buf[len] = '\0';
  5282. /* Try to create intermediate directory */
  5283. DEBUG_TRACE("mkdir(%s)", buf);
  5284. if (!mg_stat(conn, buf, &file) && mg_mkdir(buf, 0755) != 0) {
  5285. /* path does not exixt and can not be created */
  5286. res = -2;
  5287. break;
  5288. }
  5289. /* Is path itself a directory? */
  5290. if (p[1] == '\0') {
  5291. res = 0;
  5292. }
  5293. }
  5294. return res;
  5295. }
  5296. static void mkcol(struct mg_connection *conn, const char *path)
  5297. {
  5298. int rc, body_len;
  5299. struct de de;
  5300. char date[64];
  5301. time_t curtime = time(NULL);
  5302. if (conn == NULL)
  5303. return;
  5304. /* TODO (mid): Check the send_http_error situations in this function */
  5305. memset(&de.file, 0, sizeof(de.file));
  5306. if (!mg_stat(conn, path, &de.file)) {
  5307. mg_cry(conn,
  5308. "%s: mg_stat(%s) failed: %s",
  5309. __func__,
  5310. path,
  5311. strerror(ERRNO));
  5312. }
  5313. if (de.file.modification_time) {
  5314. send_http_error(
  5315. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5316. return;
  5317. }
  5318. body_len = conn->data_len - conn->request_len;
  5319. if (body_len > 0) {
  5320. send_http_error(
  5321. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5322. return;
  5323. }
  5324. rc = mg_mkdir(path, 0755);
  5325. if (rc == 0) {
  5326. conn->status_code = 201;
  5327. gmt_time_string(date, sizeof(date), &curtime);
  5328. mg_printf(conn,
  5329. "HTTP/1.1 %d Created\r\nDate: %s\r\nContent-Length: "
  5330. "0\r\nConnection: %s\r\n\r\n",
  5331. conn->status_code,
  5332. date,
  5333. suggest_connection_header(conn));
  5334. } else if (rc == -1) {
  5335. if (errno == EEXIST)
  5336. send_http_error(
  5337. conn, 405, "Error:mkcol(%s): %s", path, strerror(ERRNO));
  5338. else if (errno == EACCES)
  5339. send_http_error(
  5340. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5341. else if (errno == ENOENT)
  5342. send_http_error(
  5343. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  5344. else
  5345. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  5346. }
  5347. }
  5348. static void put_file(struct mg_connection *conn, const char *path)
  5349. {
  5350. struct file file = STRUCT_FILE_INITIALIZER;
  5351. const char *range;
  5352. int64_t r1, r2;
  5353. int rc;
  5354. char date[64];
  5355. time_t curtime = time(NULL);
  5356. if (conn == NULL)
  5357. return;
  5358. if (mg_stat(conn, path, &file)) {
  5359. /* File already exists */
  5360. conn->status_code = 200;
  5361. if (file.is_directory) {
  5362. /* This is an already existing directory,
  5363. * so there is nothing to do for the server. */
  5364. rc = 0;
  5365. } else {
  5366. /* File exists and is not a directory. */
  5367. /* Can it be replaced? */
  5368. if (file.modification_time == 0) {
  5369. /* This is an "in-memory" file, that can not be replaced */
  5370. send_http_error(
  5371. conn,
  5372. 405,
  5373. "Error: Put not possible\nReplacing %s is not supported",
  5374. path);
  5375. return;
  5376. }
  5377. /* Check if the server may write this file */
  5378. if (access(path, W_OK) == 0) {
  5379. /* Access granted */
  5380. conn->status_code = 200;
  5381. rc = 1;
  5382. } else {
  5383. send_http_error(
  5384. conn,
  5385. 403,
  5386. "Error: Put not possible\nReplacing %s is not allowed",
  5387. path);
  5388. return;
  5389. }
  5390. }
  5391. } else {
  5392. /* File should be created */
  5393. conn->status_code = 201;
  5394. rc = put_dir(conn, path);
  5395. }
  5396. if (rc == 0) {
  5397. /* put_dir returns 0 if path is a directory */
  5398. gmt_time_string(date, sizeof(date), &curtime);
  5399. mg_printf(conn,
  5400. "HTTP/1.1 %d %s\r\n"
  5401. "Date: %s\r\n"
  5402. "Content-Length: 0\r\n"
  5403. "Connection: %s\r\n\r\n",
  5404. conn->status_code,
  5405. mg_get_response_code_text(conn->status_code, NULL),
  5406. date,
  5407. suggest_connection_header(conn));
  5408. /* Request to create a directory has been fulfilled successfully.
  5409. * No need to put a file. */
  5410. return;
  5411. }
  5412. if (rc == -1) {
  5413. /* put_dir returns -1 if the path is too long */
  5414. send_http_error(conn,
  5415. 414,
  5416. "Error: Path too long\nput_dir(%s): %s",
  5417. path,
  5418. strerror(ERRNO));
  5419. return;
  5420. }
  5421. if (rc == -2) {
  5422. /* put_dir returns -2 if the directory can not be created */
  5423. send_http_error(conn,
  5424. 500,
  5425. "Error: Can not create directory\nput_dir(%s): %s",
  5426. path,
  5427. strerror(ERRNO));
  5428. return;
  5429. }
  5430. /* A file should be created or overwritten. */
  5431. if (!mg_fopen(conn, path, "wb+", &file) || file.fp == NULL) {
  5432. mg_fclose(&file);
  5433. send_http_error(conn,
  5434. 500,
  5435. "Error: Can not create file\nfopen(%s): %s",
  5436. path,
  5437. strerror(ERRNO));
  5438. return;
  5439. }
  5440. fclose_on_exec(&file, conn);
  5441. range = mg_get_header(conn, "Content-Range");
  5442. r1 = r2 = 0;
  5443. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  5444. conn->status_code = 206; /* Partial content */
  5445. fseeko(file.fp, r1, SEEK_SET);
  5446. }
  5447. if (!forward_body_data(conn, file.fp, INVALID_SOCKET, NULL)) {
  5448. /* forward_body_data failed.
  5449. * The error code has already been sent to the client,
  5450. * and conn->status_code is already set. */
  5451. return;
  5452. }
  5453. gmt_time_string(date, sizeof(date), &curtime);
  5454. mg_printf(conn,
  5455. "HTTP/1.1 %d %s\r\n"
  5456. "Date: %s\r\n"
  5457. "Content-Length: 0\r\n"
  5458. "Connection: %s\r\n\r\n",
  5459. conn->status_code,
  5460. mg_get_response_code_text(conn->status_code, NULL),
  5461. date,
  5462. suggest_connection_header(conn));
  5463. mg_fclose(&file);
  5464. }
  5465. static void delete_file(struct mg_connection *conn, const char *path)
  5466. {
  5467. struct de de;
  5468. memset(&de.file, 0, sizeof(de.file));
  5469. if (!mg_stat(conn, path, &de.file)) {
  5470. /* mg_stat returns 0 if the file does not exist */
  5471. send_http_error(
  5472. conn, 404, "Error: Cannot delete file\nFile %s not found", path);
  5473. return;
  5474. }
  5475. if (de.file.modification_time == 0) {
  5476. /* mg_stat returns != 0 and modification_time == 0
  5477. * if the file is cached in memory */
  5478. send_http_error(
  5479. conn,
  5480. 405,
  5481. "Error: Delete not possible\nDeleting %s is not supported",
  5482. path);
  5483. return;
  5484. }
  5485. if (de.file.is_directory) {
  5486. remove_directory(conn, path);
  5487. /* TODO (mid): remove_dir does not return success of the operation */
  5488. /* Assume delete is successful: Return 204 without content. */
  5489. send_http_error(conn, 204, "%s", "");
  5490. return;
  5491. }
  5492. /* This is an existing file (not a directory).
  5493. * Check if write permission is granted. */
  5494. if (access(path, W_OK) != 0) {
  5495. /* File is read only */
  5496. send_http_error(
  5497. conn,
  5498. 403,
  5499. "Error: Delete not possible\nDeleting %s is not allowed",
  5500. path);
  5501. return;
  5502. }
  5503. /* Try to delete it. */
  5504. if (mg_remove(path) == 0) {
  5505. /* Delete was successful: Return 204 without content. */
  5506. send_http_error(conn, 204, "%s", "");
  5507. } else {
  5508. /* Delete not successful (file locked). */
  5509. send_http_error(conn,
  5510. 423,
  5511. "Error: Cannot delete file\nremove(%s): %s",
  5512. path,
  5513. strerror(ERRNO));
  5514. }
  5515. }
  5516. static void
  5517. send_ssi_file(struct mg_connection *, const char *, struct file *, int);
  5518. static void do_ssi_include(struct mg_connection *conn,
  5519. const char *ssi,
  5520. char *tag,
  5521. int include_level)
  5522. {
  5523. char file_name[MG_BUF_LEN], path[512], *p;
  5524. struct file file = STRUCT_FILE_INITIALIZER;
  5525. size_t len;
  5526. if (conn == NULL)
  5527. return;
  5528. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  5529. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  5530. * always < MG_BUF_LEN. */
  5531. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  5532. /* File name is relative to the webserver root */
  5533. file_name[511] = 0;
  5534. (void)mg_snprintf(conn,
  5535. path,
  5536. sizeof(path),
  5537. "%s%c%s",
  5538. conn->ctx->config[DOCUMENT_ROOT],
  5539. '/',
  5540. file_name);
  5541. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  5542. /* File name is relative to the webserver working directory
  5543. * or it is absolute system path */
  5544. file_name[511] = 0;
  5545. (void)mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  5546. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1 ||
  5547. sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  5548. /* File name is relative to the currect document */
  5549. file_name[511] = 0;
  5550. (void)mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  5551. if ((p = strrchr(path, '/')) != NULL) {
  5552. p[1] = '\0';
  5553. }
  5554. len = strlen(path);
  5555. (void)mg_snprintf(
  5556. conn, path + len, sizeof(path) - len, "%s", file_name);
  5557. } else {
  5558. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  5559. return;
  5560. }
  5561. if (!mg_fopen(conn, path, "rb", &file)) {
  5562. mg_cry(conn,
  5563. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  5564. tag,
  5565. path,
  5566. strerror(ERRNO));
  5567. } else {
  5568. fclose_on_exec(&file, conn);
  5569. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  5570. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  5571. path) > 0) {
  5572. send_ssi_file(conn, path, &file, include_level + 1);
  5573. } else {
  5574. send_file_data(conn, &file, 0, INT64_MAX);
  5575. }
  5576. mg_fclose(&file);
  5577. }
  5578. }
  5579. #if !defined(NO_POPEN)
  5580. static void do_ssi_exec(struct mg_connection *conn, char *tag)
  5581. {
  5582. char cmd[1024] = "";
  5583. struct file file = STRUCT_FILE_INITIALIZER;
  5584. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  5585. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  5586. } else {
  5587. cmd[1023] = 0;
  5588. if ((file.fp = popen(cmd, "r")) == NULL) {
  5589. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  5590. } else {
  5591. send_file_data(conn, &file, 0, INT64_MAX);
  5592. pclose(file.fp);
  5593. }
  5594. }
  5595. }
  5596. #endif /* !NO_POPEN */
  5597. static int mg_fgetc(struct file *filep, int offset)
  5598. {
  5599. if (filep == NULL)
  5600. return EOF;
  5601. if (filep->membuf != NULL && offset >= 0 &&
  5602. ((unsigned int)(offset)) < filep->size) {
  5603. return ((unsigned char *)filep->membuf)[offset];
  5604. } else if (filep->fp != NULL) {
  5605. return fgetc(filep->fp);
  5606. } else {
  5607. return EOF;
  5608. }
  5609. }
  5610. static void send_ssi_file(struct mg_connection *conn,
  5611. const char *path,
  5612. struct file *filep,
  5613. int include_level)
  5614. {
  5615. char buf[MG_BUF_LEN];
  5616. int ch, offset, len, in_ssi_tag;
  5617. if (include_level > 10) {
  5618. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  5619. return;
  5620. }
  5621. in_ssi_tag = len = offset = 0;
  5622. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  5623. if (in_ssi_tag && ch == '>') {
  5624. in_ssi_tag = 0;
  5625. buf[len++] = (char)ch;
  5626. buf[len] = '\0';
  5627. /* assert(len <= (int) sizeof(buf)); */
  5628. if (len > (int)sizeof(buf))
  5629. break;
  5630. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  5631. /* Not an SSI tag, pass it */
  5632. (void)mg_write(conn, buf, (size_t)len);
  5633. } else {
  5634. if (!memcmp(buf + 5, "include", 7)) {
  5635. do_ssi_include(conn, path, buf + 12, include_level);
  5636. #if !defined(NO_POPEN)
  5637. } else if (!memcmp(buf + 5, "exec", 4)) {
  5638. do_ssi_exec(conn, buf + 9);
  5639. #endif /* !NO_POPEN */
  5640. } else {
  5641. mg_cry(conn,
  5642. "%s: unknown SSI "
  5643. "command: \"%s\"",
  5644. path,
  5645. buf);
  5646. }
  5647. }
  5648. len = 0;
  5649. } else if (in_ssi_tag) {
  5650. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  5651. /* Not an SSI tag */
  5652. in_ssi_tag = 0;
  5653. } else if (len == (int)sizeof(buf) - 2) {
  5654. mg_cry(conn, "%s: SSI tag is too large", path);
  5655. len = 0;
  5656. }
  5657. buf[len++] = (char)(ch & 0xff);
  5658. } else if (ch == '<') {
  5659. in_ssi_tag = 1;
  5660. if (len > 0) {
  5661. mg_write(conn, buf, (size_t)len);
  5662. }
  5663. len = 0;
  5664. buf[len++] = (char)(ch & 0xff);
  5665. } else {
  5666. buf[len++] = (char)(ch & 0xff);
  5667. if (len == (int)sizeof(buf)) {
  5668. mg_write(conn, buf, (size_t)len);
  5669. len = 0;
  5670. }
  5671. }
  5672. }
  5673. /* Send the rest of buffered data */
  5674. if (len > 0) {
  5675. mg_write(conn, buf, (size_t)len);
  5676. }
  5677. }
  5678. static void handle_ssi_file_request(struct mg_connection *conn,
  5679. const char *path,
  5680. struct file *filep)
  5681. {
  5682. char date[64];
  5683. time_t curtime = time(NULL);
  5684. const char *cors1, *cors2, *cors3;
  5685. if (!conn)
  5686. return;
  5687. if (mg_get_header(conn, "Origin")) {
  5688. /* Cross-origin resource sharing (CORS). */
  5689. cors1 = "Access-Control-Allow-Origin: ";
  5690. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  5691. cors3 = "\r\n";
  5692. } else {
  5693. cors1 = cors2 = cors3 = "";
  5694. }
  5695. if (!mg_fopen(conn, path, "rb", filep)) {
  5696. /* File exists (precondition for calling this function),
  5697. * but can not be opened by the server. */
  5698. send_http_error(conn,
  5699. 500,
  5700. "Error: Cannot read file\nfopen(%s): %s",
  5701. path,
  5702. strerror(ERRNO));
  5703. } else {
  5704. conn->must_close = 1;
  5705. gmt_time_string(date, sizeof(date), &curtime);
  5706. fclose_on_exec(filep, conn);
  5707. mg_printf(conn,
  5708. "HTTP/1.1 200 OK\r\n"
  5709. "%s%s%s"
  5710. "Date: %s\r\n"
  5711. "Content-Type: text/html\r\n"
  5712. "Connection: %s\r\n\r\n",
  5713. cors1,
  5714. cors2,
  5715. cors3,
  5716. date,
  5717. suggest_connection_header(conn));
  5718. send_ssi_file(conn, path, filep, 0);
  5719. mg_fclose(filep);
  5720. }
  5721. }
  5722. static void send_options(struct mg_connection *conn)
  5723. {
  5724. char date[64];
  5725. time_t curtime = time(NULL);
  5726. if (!conn)
  5727. return;
  5728. conn->status_code = 200;
  5729. conn->must_close = 1;
  5730. gmt_time_string(date, sizeof(date), &curtime);
  5731. mg_printf(conn,
  5732. "HTTP/1.1 200 OK\r\n"
  5733. "Date: %s\r\n"
  5734. "Connection: %s\r\n"
  5735. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  5736. "PROPFIND, MKCOL\r\n"
  5737. "DAV: 1\r\n\r\n",
  5738. date,
  5739. suggest_connection_header(conn));
  5740. }
  5741. /* Writes PROPFIND properties for a collection element */
  5742. static void
  5743. print_props(struct mg_connection *conn, const char *uri, struct file *filep)
  5744. {
  5745. char mtime[64];
  5746. if (!filep || !conn)
  5747. return;
  5748. gmt_time_string(mtime, sizeof(mtime), &filep->modification_time);
  5749. conn->num_bytes_sent +=
  5750. mg_printf(conn,
  5751. "<d:response>"
  5752. "<d:href>%s</d:href>"
  5753. "<d:propstat>"
  5754. "<d:prop>"
  5755. "<d:resourcetype>%s</d:resourcetype>"
  5756. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  5757. "<d:getlastmodified>%s</d:getlastmodified>"
  5758. "</d:prop>"
  5759. "<d:status>HTTP/1.1 200 OK</d:status>"
  5760. "</d:propstat>"
  5761. "</d:response>\n",
  5762. uri,
  5763. filep->is_directory ? "<d:collection/>" : "",
  5764. filep->size,
  5765. mtime);
  5766. }
  5767. static void print_dav_dir_entry(struct de *de, void *data)
  5768. {
  5769. char href[PATH_MAX];
  5770. char href_encoded[PATH_MAX];
  5771. struct mg_connection *conn = (struct mg_connection *)data;
  5772. if (!de || !conn)
  5773. return;
  5774. mg_snprintf(conn,
  5775. href,
  5776. sizeof(href),
  5777. "%s%s",
  5778. conn->request_info.uri,
  5779. de->file_name);
  5780. mg_url_encode(href, href_encoded, PATH_MAX - 1);
  5781. print_props(conn, href_encoded, &de->file);
  5782. }
  5783. static void handle_propfind(struct mg_connection *conn,
  5784. const char *path,
  5785. struct file *filep)
  5786. {
  5787. const char *depth = mg_get_header(conn, "Depth");
  5788. char date[64];
  5789. time_t curtime = time(NULL);
  5790. gmt_time_string(date, sizeof(date), &curtime);
  5791. if (!conn)
  5792. return;
  5793. conn->must_close = 1;
  5794. conn->status_code = 207;
  5795. mg_printf(conn,
  5796. "HTTP/1.1 207 Multi-Status\r\n"
  5797. "Date: %s\r\n"
  5798. "Connection: %s\r\n"
  5799. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  5800. date,
  5801. suggest_connection_header(conn));
  5802. conn->num_bytes_sent +=
  5803. mg_printf(conn,
  5804. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  5805. "<d:multistatus xmlns:d='DAV:'>\n");
  5806. /* Print properties for the requested resource itself */
  5807. print_props(conn, conn->request_info.uri, filep);
  5808. /* If it is a directory, print directory entries too if Depth is not 0 */
  5809. if (filep && conn->ctx && filep->is_directory &&
  5810. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  5811. (depth == NULL || strcmp(depth, "0") != 0)) {
  5812. scan_directory(conn, path, conn, &print_dav_dir_entry);
  5813. }
  5814. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  5815. }
  5816. void mg_lock_connection(struct mg_connection *conn)
  5817. {
  5818. if (conn)
  5819. (void)pthread_mutex_lock(&conn->mutex);
  5820. }
  5821. void mg_unlock_connection(struct mg_connection *conn)
  5822. {
  5823. if (conn)
  5824. (void)pthread_mutex_unlock(&conn->mutex);
  5825. }
  5826. void mg_lock_context(struct mg_context *ctx)
  5827. {
  5828. if (ctx)
  5829. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  5830. }
  5831. void mg_unlock_context(struct mg_context *ctx)
  5832. {
  5833. if (ctx)
  5834. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  5835. }
  5836. #if defined(USE_TIMERS)
  5837. #include "timer.inl"
  5838. #endif /* USE_TIMERS */
  5839. #ifdef USE_LUA
  5840. #include "mod_lua.inl"
  5841. #endif /* USE_LUA */
  5842. #if defined(USE_WEBSOCKET)
  5843. /* START OF SHA-1 code
  5844. * Copyright(c) By Steve Reid <steve@edmweb.com> */
  5845. #define SHA1HANDSOFF
  5846. /* According to current tests (May 2015), the <solarisfixes.h> is not required.
  5847. *
  5848. * #if defined(__sun)
  5849. * #include "solarisfixes.h"
  5850. * #endif
  5851. */
  5852. static int is_big_endian(void)
  5853. {
  5854. static const int n = 1;
  5855. return ((char *)&n)[0] == 0;
  5856. }
  5857. union char64long16 {
  5858. unsigned char c[64];
  5859. uint32_t l[16];
  5860. };
  5861. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  5862. static uint32_t blk0(union char64long16 *block, int i)
  5863. {
  5864. /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
  5865. if (!is_big_endian()) {
  5866. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  5867. (rol(block->l[i], 8) & 0x00FF00FF);
  5868. }
  5869. return block->l[i];
  5870. }
  5871. #define blk(i) \
  5872. (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
  5873. block->l[(i + 2) & 15] ^ block->l[i & 15], \
  5874. 1))
  5875. #define R0(v, w, x, y, z, i) \
  5876. z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
  5877. w = rol(w, 30);
  5878. #define R1(v, w, x, y, z, i) \
  5879. z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
  5880. w = rol(w, 30);
  5881. #define R2(v, w, x, y, z, i) \
  5882. z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
  5883. w = rol(w, 30);
  5884. #define R3(v, w, x, y, z, i) \
  5885. z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
  5886. w = rol(w, 30);
  5887. #define R4(v, w, x, y, z, i) \
  5888. z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
  5889. w = rol(w, 30);
  5890. typedef struct {
  5891. uint32_t state[5];
  5892. uint32_t count[2];
  5893. unsigned char buffer[64];
  5894. } SHA1_CTX;
  5895. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64])
  5896. {
  5897. uint32_t a, b, c, d, e;
  5898. union char64long16 block[1];
  5899. memcpy(block, buffer, 64);
  5900. a = state[0];
  5901. b = state[1];
  5902. c = state[2];
  5903. d = state[3];
  5904. e = state[4];
  5905. R0(a, b, c, d, e, 0);
  5906. R0(e, a, b, c, d, 1);
  5907. R0(d, e, a, b, c, 2);
  5908. R0(c, d, e, a, b, 3);
  5909. R0(b, c, d, e, a, 4);
  5910. R0(a, b, c, d, e, 5);
  5911. R0(e, a, b, c, d, 6);
  5912. R0(d, e, a, b, c, 7);
  5913. R0(c, d, e, a, b, 8);
  5914. R0(b, c, d, e, a, 9);
  5915. R0(a, b, c, d, e, 10);
  5916. R0(e, a, b, c, d, 11);
  5917. R0(d, e, a, b, c, 12);
  5918. R0(c, d, e, a, b, 13);
  5919. R0(b, c, d, e, a, 14);
  5920. R0(a, b, c, d, e, 15);
  5921. R1(e, a, b, c, d, 16);
  5922. R1(d, e, a, b, c, 17);
  5923. R1(c, d, e, a, b, 18);
  5924. R1(b, c, d, e, a, 19);
  5925. R2(a, b, c, d, e, 20);
  5926. R2(e, a, b, c, d, 21);
  5927. R2(d, e, a, b, c, 22);
  5928. R2(c, d, e, a, b, 23);
  5929. R2(b, c, d, e, a, 24);
  5930. R2(a, b, c, d, e, 25);
  5931. R2(e, a, b, c, d, 26);
  5932. R2(d, e, a, b, c, 27);
  5933. R2(c, d, e, a, b, 28);
  5934. R2(b, c, d, e, a, 29);
  5935. R2(a, b, c, d, e, 30);
  5936. R2(e, a, b, c, d, 31);
  5937. R2(d, e, a, b, c, 32);
  5938. R2(c, d, e, a, b, 33);
  5939. R2(b, c, d, e, a, 34);
  5940. R2(a, b, c, d, e, 35);
  5941. R2(e, a, b, c, d, 36);
  5942. R2(d, e, a, b, c, 37);
  5943. R2(c, d, e, a, b, 38);
  5944. R2(b, c, d, e, a, 39);
  5945. R3(a, b, c, d, e, 40);
  5946. R3(e, a, b, c, d, 41);
  5947. R3(d, e, a, b, c, 42);
  5948. R3(c, d, e, a, b, 43);
  5949. R3(b, c, d, e, a, 44);
  5950. R3(a, b, c, d, e, 45);
  5951. R3(e, a, b, c, d, 46);
  5952. R3(d, e, a, b, c, 47);
  5953. R3(c, d, e, a, b, 48);
  5954. R3(b, c, d, e, a, 49);
  5955. R3(a, b, c, d, e, 50);
  5956. R3(e, a, b, c, d, 51);
  5957. R3(d, e, a, b, c, 52);
  5958. R3(c, d, e, a, b, 53);
  5959. R3(b, c, d, e, a, 54);
  5960. R3(a, b, c, d, e, 55);
  5961. R3(e, a, b, c, d, 56);
  5962. R3(d, e, a, b, c, 57);
  5963. R3(c, d, e, a, b, 58);
  5964. R3(b, c, d, e, a, 59);
  5965. R4(a, b, c, d, e, 60);
  5966. R4(e, a, b, c, d, 61);
  5967. R4(d, e, a, b, c, 62);
  5968. R4(c, d, e, a, b, 63);
  5969. R4(b, c, d, e, a, 64);
  5970. R4(a, b, c, d, e, 65);
  5971. R4(e, a, b, c, d, 66);
  5972. R4(d, e, a, b, c, 67);
  5973. R4(c, d, e, a, b, 68);
  5974. R4(b, c, d, e, a, 69);
  5975. R4(a, b, c, d, e, 70);
  5976. R4(e, a, b, c, d, 71);
  5977. R4(d, e, a, b, c, 72);
  5978. R4(c, d, e, a, b, 73);
  5979. R4(b, c, d, e, a, 74);
  5980. R4(a, b, c, d, e, 75);
  5981. R4(e, a, b, c, d, 76);
  5982. R4(d, e, a, b, c, 77);
  5983. R4(c, d, e, a, b, 78);
  5984. R4(b, c, d, e, a, 79);
  5985. state[0] += a;
  5986. state[1] += b;
  5987. state[2] += c;
  5988. state[3] += d;
  5989. state[4] += e;
  5990. a = b = c = d = e = 0;
  5991. memset(block, '\0', sizeof(block));
  5992. }
  5993. static void SHA1Init(SHA1_CTX *context)
  5994. {
  5995. context->state[0] = 0x67452301;
  5996. context->state[1] = 0xEFCDAB89;
  5997. context->state[2] = 0x98BADCFE;
  5998. context->state[3] = 0x10325476;
  5999. context->state[4] = 0xC3D2E1F0;
  6000. context->count[0] = context->count[1] = 0;
  6001. }
  6002. static void
  6003. SHA1Update(SHA1_CTX *context, const unsigned char *data, uint32_t len)
  6004. {
  6005. uint32_t i, j;
  6006. j = context->count[0];
  6007. if ((context->count[0] += len << 3) < j)
  6008. context->count[1]++;
  6009. context->count[1] += (len >> 29);
  6010. j = (j >> 3) & 63;
  6011. if ((j + len) > 63) {
  6012. memcpy(&context->buffer[j], data, (i = 64 - j));
  6013. SHA1Transform(context->state, context->buffer);
  6014. for (; i + 63 < len; i += 64) {
  6015. SHA1Transform(context->state, &data[i]);
  6016. }
  6017. j = 0;
  6018. } else
  6019. i = 0;
  6020. memcpy(&context->buffer[j], &data[i], len - i);
  6021. }
  6022. static void SHA1Final(unsigned char digest[20], SHA1_CTX *context)
  6023. {
  6024. unsigned i;
  6025. unsigned char finalcount[8], c;
  6026. for (i = 0; i < 8; i++) {
  6027. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >>
  6028. ((3 - (i & 3)) * 8)) &
  6029. 255);
  6030. }
  6031. c = 0200;
  6032. SHA1Update(context, &c, 1);
  6033. while ((context->count[0] & 504) != 448) {
  6034. c = 0000;
  6035. SHA1Update(context, &c, 1);
  6036. }
  6037. SHA1Update(context, finalcount, 8);
  6038. for (i = 0; i < 20; i++) {
  6039. digest[i] =
  6040. (unsigned char)((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) &
  6041. 255);
  6042. }
  6043. memset(context, '\0', sizeof(*context));
  6044. memset(&finalcount, '\0', sizeof(finalcount));
  6045. }
  6046. /* END OF SHA1 CODE */
  6047. static void send_websocket_handshake(struct mg_connection *conn)
  6048. {
  6049. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  6050. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  6051. SHA1_CTX sha_ctx;
  6052. mg_snprintf(conn,
  6053. buf,
  6054. sizeof(buf),
  6055. "%s%s",
  6056. mg_get_header(conn, "Sec-WebSocket-Key"),
  6057. magic);
  6058. SHA1Init(&sha_ctx);
  6059. SHA1Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  6060. SHA1Final((unsigned char *)sha, &sha_ctx);
  6061. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  6062. mg_printf(conn,
  6063. "%s%s%s",
  6064. "HTTP/1.1 101 Switching Protocols\r\n"
  6065. "Upgrade: websocket\r\n"
  6066. "Connection: Upgrade\r\n"
  6067. "Sec-WebSocket-Accept: ",
  6068. b64_sha,
  6069. "\r\n\r\n");
  6070. }
  6071. static void read_websocket(struct mg_connection *conn,
  6072. mg_websocket_data_handler ws_data_handler,
  6073. void *callback_data)
  6074. {
  6075. /* Pointer to the beginning of the portion of the incoming websocket
  6076. * message queue.
  6077. * The original websocket upgrade request is never removed, so the queue
  6078. * begins after it. */
  6079. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  6080. int n, error, exit_by_callback;
  6081. /* body_len is the length of the entire queue in bytes
  6082. * len is the length of the current message
  6083. * data_len is the length of the current message's data payload
  6084. * header_len is the length of the current message's header */
  6085. size_t i, len, mask_len, data_len, header_len, body_len;
  6086. /* "The masking key is a 32-bit value chosen at random by the client."
  6087. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  6088. */
  6089. unsigned char mask[4];
  6090. /* data points to the place where the message is stored when passed to the
  6091. * websocket_data callback. This is either mem on the stack, or a
  6092. * dynamically allocated buffer if it is too large. */
  6093. char mem[4096];
  6094. char *data = mem;
  6095. unsigned char mop; /* mask flag and opcode */
  6096. double timeout = -1.0;
  6097. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  6098. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  6099. }
  6100. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  6101. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6102. }
  6103. mg_set_thread_name("wsock");
  6104. /* Loop continuously, reading messages from the socket, invoking the
  6105. * callback, and waiting repeatedly until an error occurs. */
  6106. while (!conn->ctx->stop_flag) {
  6107. header_len = 0;
  6108. assert(conn->data_len >= conn->request_len);
  6109. if ((body_len = conn->data_len - conn->request_len) >= 2) {
  6110. len = buf[1] & 127;
  6111. mask_len = buf[1] & 128 ? 4 : 0;
  6112. if (len < 126 && body_len >= mask_len) {
  6113. data_len = len;
  6114. header_len = 2 + mask_len;
  6115. } else if (len == 126 && body_len >= 4 + mask_len) {
  6116. header_len = 4 + mask_len;
  6117. data_len = ((((int)buf[2]) << 8) + buf[3]);
  6118. } else if (body_len >= 10 + mask_len) {
  6119. header_len = 10 + mask_len;
  6120. data_len = (((uint64_t)ntohl(*(uint32_t *)&buf[2])) << 32) +
  6121. ntohl(*(uint32_t *)&buf[6]);
  6122. }
  6123. }
  6124. if (header_len > 0 && body_len >= header_len) {
  6125. /* Allocate space to hold websocket payload */
  6126. data = mem;
  6127. if (data_len > sizeof(mem)) {
  6128. data = (char *)mg_malloc(data_len);
  6129. if (data == NULL) {
  6130. /* Allocation failed, exit the loop and then close the
  6131. * connection */
  6132. mg_cry(conn, "websocket out of memory; closing connection");
  6133. break;
  6134. }
  6135. }
  6136. /* Copy the mask before we shift the queue and destroy it */
  6137. if (mask_len > 0) {
  6138. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  6139. } else {
  6140. memset(mask, 0, sizeof(mask));
  6141. }
  6142. /* Read frame payload from the first message in the queue into
  6143. * data and advance the queue by moving the memory in place. */
  6144. assert(body_len >= header_len);
  6145. if (data_len + header_len > body_len) {
  6146. mop = buf[0]; /* current mask and opcode */
  6147. /* Overflow case */
  6148. len = body_len - header_len;
  6149. memcpy(data, buf + header_len, len);
  6150. error = 0;
  6151. while (len < data_len) {
  6152. n = pull(
  6153. NULL, conn, data + len, (int)(data_len - len), timeout);
  6154. if (n <= 0) {
  6155. error = 1;
  6156. break;
  6157. }
  6158. len += n;
  6159. }
  6160. if (error) {
  6161. mg_cry(conn, "Websocket pull failed; closing connection");
  6162. break;
  6163. }
  6164. conn->data_len = conn->request_len;
  6165. } else {
  6166. mop = buf[0]; /* current mask and opcode, overwritten by
  6167. * memmove() */
  6168. /* Length of the message being read at the front of the
  6169. * queue */
  6170. len = data_len + header_len;
  6171. /* Copy the data payload into the data pointer for the
  6172. * callback */
  6173. memcpy(data, buf + header_len, data_len);
  6174. /* Move the queue forward len bytes */
  6175. memmove(buf, buf + len, body_len - len);
  6176. /* Mark the queue as advanced */
  6177. conn->data_len -= (int)len;
  6178. }
  6179. /* Apply mask if necessary */
  6180. if (mask_len > 0) {
  6181. for (i = 0; i < data_len; ++i) {
  6182. data[i] ^= mask[i & 3];
  6183. }
  6184. }
  6185. /* Exit the loop if callback signals to exit (server side),
  6186. * or "connection close" opcode received (client side). */
  6187. exit_by_callback = 0;
  6188. if ((ws_data_handler != NULL) &&
  6189. !ws_data_handler(conn, mop, data, data_len, callback_data)) {
  6190. exit_by_callback = 1;
  6191. }
  6192. if (data != mem) {
  6193. mg_free(data);
  6194. }
  6195. if (exit_by_callback ||
  6196. ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  6197. /* Opcode == 8, connection close */
  6198. break;
  6199. }
  6200. /* Not breaking the loop, process next websocket frame. */
  6201. } else {
  6202. /* Read from the socket into the next available location in the
  6203. * message queue. */
  6204. if ((n = pull(NULL,
  6205. conn,
  6206. conn->buf + conn->data_len,
  6207. conn->buf_size - conn->data_len,
  6208. timeout)) <= 0) {
  6209. /* Error, no bytes read */
  6210. break;
  6211. }
  6212. conn->data_len += n;
  6213. }
  6214. }
  6215. mg_set_thread_name("worker");
  6216. }
  6217. int mg_websocket_write(struct mg_connection *conn,
  6218. int opcode,
  6219. const char *data,
  6220. size_t dataLen)
  6221. {
  6222. unsigned char header[10];
  6223. size_t headerLen = 1;
  6224. int retval = -1;
  6225. header[0] = 0x80 + (opcode & 0xF);
  6226. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  6227. if (dataLen < 126) {
  6228. /* inline 7-bit length field */
  6229. header[1] = (unsigned char)dataLen;
  6230. headerLen = 2;
  6231. } else if (dataLen <= 0xFFFF) {
  6232. /* 16-bit length field */
  6233. header[1] = 126;
  6234. *(uint16_t *)(header + 2) = htons((uint16_t)dataLen);
  6235. headerLen = 4;
  6236. } else {
  6237. /* 64-bit length field */
  6238. header[1] = 127;
  6239. *(uint32_t *)(header + 2) = htonl((uint64_t)dataLen >> 32);
  6240. *(uint32_t *)(header + 6) = htonl(dataLen & 0xFFFFFFFF);
  6241. headerLen = 10;
  6242. }
  6243. /* Note that POSIX/Winsock's send() is threadsafe
  6244. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  6245. * but mongoose's mg_printf/mg_write is not (because of the loop in
  6246. * push(), although that is only a problem if the packet is large or
  6247. * outgoing buffer is full). */
  6248. (void)mg_lock_connection(conn);
  6249. retval = mg_write(conn, header, headerLen);
  6250. retval = mg_write(conn, data, dataLen);
  6251. mg_unlock_connection(conn);
  6252. return retval;
  6253. }
  6254. static void
  6255. handle_websocket_request(struct mg_connection *conn,
  6256. const char *path,
  6257. int is_callback_resource,
  6258. mg_websocket_connect_handler ws_connect_handler,
  6259. mg_websocket_ready_handler ws_ready_handler,
  6260. mg_websocket_data_handler ws_data_handler,
  6261. mg_websocket_close_handler ws_close_handler,
  6262. void *cbData)
  6263. {
  6264. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  6265. int lua_websock = 0;
  6266. #if !defined(USE_LUA)
  6267. (void)path;
  6268. #endif
  6269. /* Step 1: Check websocket protocol version. */
  6270. if (version == NULL || strcmp(version, "13") != 0) {
  6271. /* Reject wrong versions */
  6272. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  6273. return;
  6274. }
  6275. /* Step 2: If a callback is responsible, call it. */
  6276. if (is_callback_resource) {
  6277. if (ws_connect_handler != NULL &&
  6278. ws_connect_handler(conn, cbData) != 0) {
  6279. /* C callback has returned non-zero, do not proceed with handshake.
  6280. */
  6281. /* Note that C callbacks are no longer called when Lua is
  6282. * responsible, so C can no longer filter callbacks for Lua. */
  6283. return;
  6284. }
  6285. }
  6286. #if defined(USE_LUA)
  6287. /* Step 3: No callback. Check if Lua is responsible. */
  6288. else {
  6289. /* Step 3.1: Check if Lua is responsible. */
  6290. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  6291. lua_websock = match_prefix(
  6292. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  6293. strlen(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  6294. path);
  6295. }
  6296. if (lua_websock) {
  6297. /* Step 3.2: Lua is responsible: call it. */
  6298. conn->lua_websocket_state = lua_websocket_new(path, conn);
  6299. if (!conn->lua_websocket_state) {
  6300. /* Lua rejected the new client */
  6301. return;
  6302. }
  6303. }
  6304. }
  6305. #endif
  6306. /* Step 4: Check if there is a responsible websocket handler. */
  6307. if (!is_callback_resource && !lua_websock) {
  6308. /* There is no callback, an Lua is not responsible either. */
  6309. /* Reply with a 404 Not Found or with nothing at all?
  6310. * TODO (mid): check the websocket standards, how to reply to
  6311. * requests to invalid websocket addresses. */
  6312. send_http_error(conn, 404, "%s", "Not found");
  6313. return;
  6314. }
  6315. /* Step 5: The websocket connection has been accepted */
  6316. send_websocket_handshake(conn);
  6317. /* Step 6: Call the ready handler */
  6318. if (is_callback_resource) {
  6319. if (ws_ready_handler != NULL) {
  6320. ws_ready_handler(conn, cbData);
  6321. }
  6322. #if defined(USE_LUA)
  6323. } else if (lua_websock) {
  6324. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  6325. /* the ready handler returned false */
  6326. return;
  6327. }
  6328. #endif
  6329. }
  6330. /* Step 7: Enter the read loop */
  6331. if (is_callback_resource) {
  6332. read_websocket(conn, ws_data_handler, cbData);
  6333. #if defined(USE_LUA)
  6334. } else if (lua_websock) {
  6335. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  6336. #endif
  6337. }
  6338. /* Step 8: Call the close handler */
  6339. if (ws_close_handler) {
  6340. ws_close_handler(conn, cbData);
  6341. }
  6342. }
  6343. static int is_websocket_protocol(const struct mg_connection *conn)
  6344. {
  6345. const char *host, *upgrade, *connection, *version, *key;
  6346. upgrade = mg_get_header(conn, "Upgrade");
  6347. if (upgrade == NULL)
  6348. return 0; /* fail early, don't waste time checking other header fields
  6349. */
  6350. if (!mg_strcasestr(upgrade, "websocket"))
  6351. return 0;
  6352. connection = mg_get_header(conn, "Connection");
  6353. if (connection == NULL)
  6354. return 0;
  6355. if (!mg_strcasestr(connection, "upgrade"))
  6356. return 0;
  6357. host = mg_get_header(conn, "Host");
  6358. key = mg_get_header(conn, "Sec-WebSocket-Key");
  6359. version = mg_get_header(conn, "Sec-WebSocket-Version");
  6360. return host != NULL && key != NULL && version != NULL;
  6361. }
  6362. #endif /* !USE_WEBSOCKET */
  6363. static int isbyte(int n) { return n >= 0 && n <= 255; }
  6364. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  6365. {
  6366. int n, a, b, c, d, slash = 32, len = 0;
  6367. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  6368. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  6369. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
  6370. slash < 33) {
  6371. len = n;
  6372. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) |
  6373. (uint32_t)d;
  6374. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  6375. }
  6376. return len;
  6377. }
  6378. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  6379. {
  6380. int throttle = 0;
  6381. struct vec vec, val;
  6382. uint32_t net, mask;
  6383. char mult;
  6384. double v;
  6385. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  6386. mult = ',';
  6387. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  6388. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' &&
  6389. mult != ',')) {
  6390. continue;
  6391. }
  6392. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576
  6393. : 1;
  6394. if (vec.len == 1 && vec.ptr[0] == '*') {
  6395. throttle = (int)v;
  6396. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  6397. if ((remote_ip & mask) == net) {
  6398. throttle = (int)v;
  6399. }
  6400. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  6401. throttle = (int)v;
  6402. }
  6403. }
  6404. return throttle;
  6405. }
  6406. static uint32_t get_remote_ip(const struct mg_connection *conn)
  6407. {
  6408. if (!conn)
  6409. return 0;
  6410. return ntohl(*(uint32_t *)&conn->client.rsa.sin.sin_addr);
  6411. }
  6412. int mg_upload(struct mg_connection *conn, const char *destination_dir)
  6413. {
  6414. /* TODO (mid): set a timeout */
  6415. const char *content_type_header, *boundary_start, *sc;
  6416. char *s;
  6417. char buf[MG_BUF_LEN], path[PATH_MAX], tmp_path[PATH_MAX], fname[1024],
  6418. boundary[100];
  6419. FILE *fp;
  6420. int bl, n, i, headers_len, boundary_len, eof, len = 0,
  6421. num_uploaded_files = 0;
  6422. struct mg_request_info part_request_info;
  6423. /* Request looks like this:
  6424. *
  6425. * POST /upload HTTP/1.1
  6426. * Host: 127.0.0.1:8080
  6427. * Content-Length: 244894
  6428. * Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryRVr
  6429. *
  6430. * ------WebKitFormBoundaryRVr
  6431. * Content-Disposition: form-data; name="file"; filename="accum.png"
  6432. * Content-Type: image/png
  6433. *
  6434. * <89>PNG
  6435. * <PNG DATA>
  6436. * ------WebKitFormBoundaryRVr */
  6437. /* Extract boundary string from the Content-Type header */
  6438. if ((content_type_header = mg_get_header(conn, "Content-Type")) == NULL ||
  6439. (boundary_start = mg_strcasestr(content_type_header, "boundary=")) ==
  6440. NULL ||
  6441. (sscanf(boundary_start, "boundary=\"%99[^\"]\"", boundary) == 0 &&
  6442. sscanf(boundary_start, "boundary=%99s", boundary) == 0) ||
  6443. boundary[0] == '\0') {
  6444. return num_uploaded_files;
  6445. }
  6446. boundary[99] = 0;
  6447. boundary_len = (int)strlen(boundary);
  6448. bl = boundary_len + 4; /* \r\n--<boundary> */
  6449. for (;;) {
  6450. /* Pull in headers */
  6451. /* assert(len >= 0 && len <= (int) sizeof(buf)); */
  6452. if (len < 0 || len > (int)sizeof(buf))
  6453. break;
  6454. while ((n = mg_read(conn, buf + len, sizeof(buf) - (size_t)len)) > 0) {
  6455. len += n;
  6456. /* assert(len <= (int) sizeof(buf)); */
  6457. if (len > (int)sizeof(buf))
  6458. break;
  6459. }
  6460. if ((headers_len = get_request_len(buf, len)) <= 0) {
  6461. break;
  6462. }
  6463. /* terminate header */
  6464. buf[headers_len - 1] = 0;
  6465. /* Scan for the boundary string and skip it */
  6466. if (buf[0] == '-' && buf[1] == '-' &&
  6467. !memcmp(buf + 2, boundary, (size_t)boundary_len)) {
  6468. s = &buf[bl];
  6469. } else {
  6470. s = &buf[2];
  6471. }
  6472. /* Get headers for this part of the multipart message */
  6473. memset(&part_request_info, 0, sizeof(part_request_info));
  6474. parse_http_headers(&s, &part_request_info);
  6475. /* assert(&buf[headers_len-1] == s); */
  6476. if (&buf[headers_len - 1] != s)
  6477. break;
  6478. /* Fetch file name. */
  6479. sc = get_header(&part_request_info, "Content-Disposition");
  6480. if (!sc) {
  6481. /* invalid part of a multipart message */
  6482. break;
  6483. }
  6484. sc = strstr(sc, "filename");
  6485. if (!sc) {
  6486. /* no filename set */
  6487. break;
  6488. }
  6489. sc += 8; /* skip "filename" */
  6490. fname[0] = '\0';
  6491. IGNORE_UNUSED_RESULT(sscanf(sc, " = \"%1023[^\"]", fname));
  6492. fname[1023] = 0;
  6493. /* Give up if the headers are not what we expect */
  6494. if (fname[0] == '\0') {
  6495. break;
  6496. }
  6497. /* Construct destination file name. Do not allow paths to have
  6498. * slashes. */
  6499. if ((s = strrchr(fname, '/')) == NULL &&
  6500. (s = strrchr(fname, '\\')) == NULL) {
  6501. s = fname;
  6502. } else {
  6503. s++;
  6504. }
  6505. /* There data is written to a temporary file first. */
  6506. /* Different users should use a different destination_dir. */
  6507. snprintf(path, sizeof(path) - 1, "%s/%s", destination_dir, s);
  6508. strcpy(tmp_path, path);
  6509. strcat(tmp_path, "~");
  6510. /* We open the file with exclusive lock held. This guarantee us
  6511. * there is no other thread can save into the same file
  6512. * simultaneously. */
  6513. fp = NULL;
  6514. /* Open file in binary mode. */
  6515. if ((fp = fopen(tmp_path, "wb")) == NULL) {
  6516. break;
  6517. }
  6518. /* Move data to the beginning of the buffer */
  6519. /* part_request_info is no longer valid after this operation */
  6520. /* assert(len >= headers_len); */
  6521. if (len < headers_len)
  6522. break;
  6523. memmove(buf, &buf[headers_len], (size_t)(len - headers_len));
  6524. len -= headers_len;
  6525. /* Read POST data, write into file until boundary is found. */
  6526. eof = n = 0;
  6527. do {
  6528. len += n;
  6529. for (i = 0; i < len - bl; i++) {
  6530. if (!memcmp(&buf[i], "\r\n--", 4) &&
  6531. !memcmp(&buf[i + 4], boundary, (size_t)boundary_len)) {
  6532. /* Found boundary, that's the end of file data. */
  6533. fwrite(buf, 1, (size_t)i, fp);
  6534. eof = 1;
  6535. memmove(buf, &buf[i + bl], (size_t)(len - (i + bl)));
  6536. len -= i + bl;
  6537. break;
  6538. }
  6539. }
  6540. if (!eof && len > bl) {
  6541. fwrite(buf, 1, (size_t)(len - bl), fp);
  6542. memmove(buf, &buf[len - bl], (size_t)bl);
  6543. len = bl;
  6544. }
  6545. n = mg_read(conn, buf + len, sizeof(buf) - ((size_t)(len)));
  6546. } while (!eof && (n > 0));
  6547. fclose(fp);
  6548. if (eof) {
  6549. remove(path);
  6550. rename(tmp_path, path);
  6551. num_uploaded_files++;
  6552. if (conn && conn->ctx && conn->ctx->callbacks.upload != NULL) {
  6553. conn->ctx->callbacks.upload(conn, path);
  6554. }
  6555. } else {
  6556. remove(tmp_path);
  6557. }
  6558. }
  6559. return num_uploaded_files;
  6560. }
  6561. static int get_first_ssl_listener_index(const struct mg_context *ctx)
  6562. {
  6563. unsigned int i;
  6564. int idx = -1;
  6565. if (ctx)
  6566. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  6567. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  6568. }
  6569. return idx;
  6570. }
  6571. static void redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  6572. {
  6573. char host[1025];
  6574. const char *host_header;
  6575. size_t hostlen;
  6576. host_header = mg_get_header(conn, "Host");
  6577. hostlen = sizeof(host);
  6578. if (host_header != NULL) {
  6579. char *pos;
  6580. mg_strlcpy(host, host_header, hostlen);
  6581. host[hostlen - 1] = '\0';
  6582. pos = strchr(host, ':');
  6583. if (pos != NULL) {
  6584. *pos = '\0';
  6585. }
  6586. } else {
  6587. /* Cannot get host from the Host: header.
  6588. * Fallback to our IP address. */
  6589. if (conn)
  6590. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  6591. }
  6592. /* Send host, port, uri and (if it exists) ?query_string */
  6593. if (conn)
  6594. mg_printf(conn,
  6595. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  6596. host,
  6597. (int)ntohs(
  6598. conn->ctx->listening_sockets[ssl_index].lsa.sin.sin_port),
  6599. conn->request_info.uri,
  6600. (conn->request_info.query_string == NULL) ? "" : "?",
  6601. (conn->request_info.query_string == NULL)
  6602. ? ""
  6603. : conn->request_info.query_string);
  6604. }
  6605. static void
  6606. mg_set_request_handler_type(struct mg_context *ctx,
  6607. const char *uri,
  6608. int is_websocket_handler,
  6609. int is_delete_request,
  6610. mg_request_handler handler,
  6611. mg_websocket_connect_handler connect_handler,
  6612. mg_websocket_ready_handler ready_handler,
  6613. mg_websocket_data_handler data_handler,
  6614. mg_websocket_close_handler close_handler,
  6615. void *cbdata)
  6616. {
  6617. struct mg_request_handler_info *tmp_rh, **lastref;
  6618. size_t urilen = strlen(uri);
  6619. if (is_websocket_handler) {
  6620. /* assert(handler == NULL); */
  6621. /* assert(is_delete_request || connect_handler!=NULL ||
  6622. * ready_handler!=NULL || data_handler!=NULL ||
  6623. * close_handler!=NULL);
  6624. */
  6625. if (handler != NULL)
  6626. return;
  6627. if (!is_delete_request && connect_handler == NULL &&
  6628. ready_handler == NULL && data_handler == NULL &&
  6629. close_handler == NULL)
  6630. return;
  6631. } else {
  6632. /* assert(connect_handler==NULL && ready_handler==NULL &&
  6633. * data_handler==NULL && close_handler==NULL); */
  6634. /* assert(is_delete_request || (handler!=NULL));
  6635. */
  6636. if (connect_handler != NULL || ready_handler != NULL ||
  6637. data_handler != NULL || close_handler != NULL)
  6638. return;
  6639. if (!is_delete_request && (handler == NULL))
  6640. return;
  6641. }
  6642. if (!ctx)
  6643. return;
  6644. mg_lock_context(ctx);
  6645. /* first try to find an existing handler */
  6646. lastref = &(ctx->request_handlers);
  6647. for (tmp_rh = ctx->request_handlers; tmp_rh != NULL;
  6648. tmp_rh = tmp_rh->next) {
  6649. if (tmp_rh->is_websocket_handler == is_websocket_handler) {
  6650. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  6651. if (!is_delete_request) {
  6652. /* update existing handler */
  6653. if (!is_websocket_handler) {
  6654. tmp_rh->handler = handler;
  6655. } else {
  6656. tmp_rh->connect_handler = connect_handler;
  6657. tmp_rh->ready_handler = ready_handler;
  6658. tmp_rh->data_handler = data_handler;
  6659. tmp_rh->close_handler = close_handler;
  6660. }
  6661. tmp_rh->cbdata = cbdata;
  6662. } else {
  6663. /* remove existing handler */
  6664. *lastref = tmp_rh->next;
  6665. mg_free(tmp_rh->uri);
  6666. mg_free(tmp_rh);
  6667. }
  6668. mg_unlock_context(ctx);
  6669. return;
  6670. }
  6671. }
  6672. lastref = &(tmp_rh->next);
  6673. }
  6674. if (is_delete_request) {
  6675. /* no handler to set, this was a remove request to a non-existing
  6676. * handler */
  6677. mg_unlock_context(ctx);
  6678. return;
  6679. }
  6680. tmp_rh = (struct mg_request_handler_info *)mg_calloc(
  6681. sizeof(struct mg_request_handler_info), 1);
  6682. if (tmp_rh == NULL) {
  6683. mg_unlock_context(ctx);
  6684. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  6685. return;
  6686. }
  6687. tmp_rh->uri = mg_strdup(uri);
  6688. if (!tmp_rh->uri) {
  6689. mg_unlock_context(ctx);
  6690. mg_free(tmp_rh);
  6691. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  6692. return;
  6693. }
  6694. tmp_rh->uri_len = urilen;
  6695. if (!is_websocket_handler) {
  6696. tmp_rh->handler = handler;
  6697. } else {
  6698. tmp_rh->connect_handler = connect_handler;
  6699. tmp_rh->ready_handler = ready_handler;
  6700. tmp_rh->data_handler = data_handler;
  6701. tmp_rh->close_handler = close_handler;
  6702. }
  6703. tmp_rh->cbdata = cbdata;
  6704. tmp_rh->is_websocket_handler = is_websocket_handler;
  6705. tmp_rh->next = NULL;
  6706. *lastref = tmp_rh;
  6707. mg_unlock_context(ctx);
  6708. }
  6709. void mg_set_request_handler(struct mg_context *ctx,
  6710. const char *uri,
  6711. mg_request_handler handler,
  6712. void *cbdata)
  6713. {
  6714. mg_set_request_handler_type(
  6715. ctx, uri, 0, handler == NULL, handler, NULL, NULL, NULL, NULL, cbdata);
  6716. }
  6717. void mg_set_websocket_handler(struct mg_context *ctx,
  6718. const char *uri,
  6719. mg_websocket_connect_handler connect_handler,
  6720. mg_websocket_ready_handler ready_handler,
  6721. mg_websocket_data_handler data_handler,
  6722. mg_websocket_close_handler close_handler,
  6723. void *cbdata)
  6724. {
  6725. int is_delete_request = (connect_handler == NULL) &&
  6726. (ready_handler == NULL) && (data_handler == NULL) &&
  6727. (close_handler == NULL);
  6728. mg_set_request_handler_type(ctx,
  6729. uri,
  6730. 1,
  6731. is_delete_request,
  6732. NULL,
  6733. connect_handler,
  6734. ready_handler,
  6735. data_handler,
  6736. close_handler,
  6737. cbdata);
  6738. }
  6739. static int get_request_handler(struct mg_connection *conn,
  6740. int is_websocket_request,
  6741. mg_request_handler *handler,
  6742. mg_websocket_connect_handler *connect_handler,
  6743. mg_websocket_ready_handler *ready_handler,
  6744. mg_websocket_data_handler *data_handler,
  6745. mg_websocket_close_handler *close_handler,
  6746. void **cbdata)
  6747. {
  6748. const struct mg_request_info *request_info = mg_get_request_info(conn);
  6749. if (request_info) {
  6750. const char *uri = request_info->uri;
  6751. size_t urilen = strlen(uri);
  6752. struct mg_request_handler_info *tmp_rh;
  6753. if (!conn || !conn->ctx)
  6754. return 0;
  6755. mg_lock_context(conn->ctx);
  6756. /* first try for an exact match */
  6757. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  6758. tmp_rh = tmp_rh->next) {
  6759. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  6760. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  6761. if (is_websocket_request) {
  6762. *connect_handler = tmp_rh->connect_handler;
  6763. *ready_handler = tmp_rh->ready_handler;
  6764. *data_handler = tmp_rh->data_handler;
  6765. *close_handler = tmp_rh->close_handler;
  6766. } else {
  6767. *handler = tmp_rh->handler;
  6768. }
  6769. *cbdata = tmp_rh->cbdata;
  6770. mg_unlock_context(conn->ctx);
  6771. return 1;
  6772. }
  6773. }
  6774. }
  6775. /* next try for a partial match, we will accept uri/something */
  6776. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  6777. tmp_rh = tmp_rh->next) {
  6778. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  6779. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/' &&
  6780. memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  6781. if (is_websocket_request) {
  6782. *connect_handler = tmp_rh->connect_handler;
  6783. *ready_handler = tmp_rh->ready_handler;
  6784. *data_handler = tmp_rh->data_handler;
  6785. *close_handler = tmp_rh->close_handler;
  6786. } else {
  6787. *handler = tmp_rh->handler;
  6788. }
  6789. *cbdata = tmp_rh->cbdata;
  6790. mg_unlock_context(conn->ctx);
  6791. return 1;
  6792. }
  6793. }
  6794. }
  6795. /* finally try for pattern match */
  6796. for (tmp_rh = conn->ctx->request_handlers; tmp_rh != NULL;
  6797. tmp_rh = tmp_rh->next) {
  6798. if (tmp_rh->is_websocket_handler == is_websocket_request) {
  6799. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  6800. if (is_websocket_request) {
  6801. *connect_handler = tmp_rh->connect_handler;
  6802. *ready_handler = tmp_rh->ready_handler;
  6803. *data_handler = tmp_rh->data_handler;
  6804. *close_handler = tmp_rh->close_handler;
  6805. } else {
  6806. *handler = tmp_rh->handler;
  6807. }
  6808. *cbdata = tmp_rh->cbdata;
  6809. mg_unlock_context(conn->ctx);
  6810. return 1;
  6811. }
  6812. }
  6813. }
  6814. mg_unlock_context(conn->ctx);
  6815. }
  6816. return 0; /* none found */
  6817. }
  6818. #if defined(USE_WEBSOCKET)
  6819. static int
  6820. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  6821. void *cbdata)
  6822. {
  6823. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  6824. if (pcallbacks->websocket_connect) {
  6825. return pcallbacks->websocket_connect(conn);
  6826. }
  6827. /* No handler set - assume "OK" */
  6828. return 0;
  6829. }
  6830. static void deprecated_websocket_ready_wrapper(struct mg_connection *conn,
  6831. void *cbdata)
  6832. {
  6833. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  6834. if (pcallbacks->websocket_ready) {
  6835. pcallbacks->websocket_ready(conn);
  6836. }
  6837. }
  6838. static int deprecated_websocket_data_wrapper(
  6839. struct mg_connection *conn, int bits, char *data, size_t len, void *cbdata)
  6840. {
  6841. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  6842. if (pcallbacks->websocket_data) {
  6843. return pcallbacks->websocket_data(conn, bits, data, len);
  6844. }
  6845. /* No handler set - assume "OK" */
  6846. return 1;
  6847. }
  6848. #endif
  6849. /* This is the heart of the Civetweb's logic.
  6850. * This function is called when the request is read, parsed and validated,
  6851. * and Civetweb must decide what action to take: serve a file, or
  6852. * a directory, or call embedded function, etcetera. */
  6853. static void handle_request(struct mg_connection *conn)
  6854. {
  6855. if (conn) {
  6856. struct mg_request_info *ri = &conn->request_info;
  6857. char path[PATH_MAX];
  6858. int uri_len, ssl_index, is_script_resource, is_websocket_request,
  6859. is_put_or_delete_request, is_callback_resource;
  6860. int i;
  6861. struct file file = STRUCT_FILE_INITIALIZER;
  6862. time_t curtime = time(NULL);
  6863. mg_request_handler callback_handler = NULL;
  6864. mg_websocket_connect_handler ws_connect_handler = NULL;
  6865. mg_websocket_ready_handler ws_ready_handler = NULL;
  6866. mg_websocket_data_handler ws_data_handler = NULL;
  6867. mg_websocket_close_handler ws_close_handler = NULL;
  6868. void *callback_data = NULL;
  6869. #if !defined(NO_FILES)
  6870. char date[64];
  6871. #endif
  6872. path[0] = 0;
  6873. if (!ri)
  6874. return;
  6875. /* 1. get the request url */
  6876. /* 1.1. split into url and query string */
  6877. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
  6878. *((char *)conn->request_info.query_string++) = '\0';
  6879. }
  6880. uri_len = (int)strlen(ri->uri);
  6881. /* 1.2. decode url (if config says so) */
  6882. if (should_decode_url(conn)) {
  6883. mg_url_decode(ri->uri, uri_len, (char *)ri->uri, uri_len + 1, 0);
  6884. }
  6885. /* 1.3. clean URIs, so a path like allowed_dir/../forbidden_file is not
  6886. * possible */
  6887. remove_double_dots_and_double_slashes((char *)ri->uri);
  6888. /* step 1. completed, the url is known now */
  6889. DEBUG_TRACE("URL: %s", ri->uri);
  6890. /* 2. do a https redirect, if required */
  6891. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  6892. ssl_index = get_first_ssl_listener_index(conn->ctx);
  6893. if (ssl_index >= 0) {
  6894. redirect_to_https_port(conn, ssl_index);
  6895. } else {
  6896. /* A http to https forward port has been specified,
  6897. * but no https port to forward to. */
  6898. send_http_error(conn,
  6899. 503,
  6900. "%s",
  6901. "Error: SSL forward not configured properly");
  6902. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  6903. }
  6904. return;
  6905. }
  6906. /* 3. if this ip has limited speed, set it for this connection */
  6907. conn->throttle = set_throttle(
  6908. conn->ctx->config[THROTTLE], get_remote_ip(conn), ri->uri);
  6909. /* 4. call a "handle everything" callback, if registered */
  6910. if (conn->ctx->callbacks.begin_request != NULL) {
  6911. /* Note that since V1.7 the "begin_request" function is called
  6912. * before an authorization check. If an authorization check is
  6913. * required, use a request_handler instead. */
  6914. i = conn->ctx->callbacks.begin_request(conn);
  6915. switch (i) {
  6916. case 1:
  6917. /* callback already processed the request */
  6918. return;
  6919. case 0:
  6920. /* civetweb should process the request */
  6921. break;
  6922. default:
  6923. /* unspecified - may change with the next version */
  6924. return;
  6925. }
  6926. }
  6927. /* request not yet handled by a handler or redirect, so the request
  6928. * is processed here */
  6929. /* 5. interpret the url to find out how the request must be handled */
  6930. /* 5.1. first test, if the request targets the regular http(s)://
  6931. * protocol namespace or the websocket ws(s):// protocol namespace. */
  6932. is_websocket_request = is_websocket_protocol(conn);
  6933. /* 5.2. check if the request will be handled by a callback */
  6934. if (get_request_handler(conn,
  6935. is_websocket_request,
  6936. &callback_handler,
  6937. &ws_connect_handler,
  6938. &ws_ready_handler,
  6939. &ws_data_handler,
  6940. &ws_close_handler,
  6941. &callback_data)) {
  6942. /* 5.2.1. A callback will handle this request. All requests handled
  6943. * by a callback have to be considered as requests to a script
  6944. * resource. */
  6945. is_callback_resource = 1;
  6946. is_script_resource = 1;
  6947. is_put_or_delete_request = is_put_or_delete_method(conn);
  6948. } else {
  6949. no_callback_resource:
  6950. /* 5.2.2. No callback is responsible for this request. The URI
  6951. * addresses a file based resource (static content or Lua/cgi
  6952. * scripts in the file system). */
  6953. is_callback_resource = 0;
  6954. interpret_uri(conn,
  6955. path,
  6956. sizeof(path),
  6957. &file,
  6958. &is_script_resource,
  6959. &is_websocket_request,
  6960. &is_put_or_delete_request);
  6961. }
  6962. /* 6. authorization check */
  6963. if (is_put_or_delete_request && !is_script_resource &&
  6964. !is_callback_resource) {
  6965. /* 6.1. this request is a PUT/DELETE to a real file */
  6966. /* 6.1.1. thus, the server must have real files */
  6967. #if defined(NO_FILES)
  6968. if (1) {
  6969. #else
  6970. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  6971. #endif
  6972. /* This server does not have any real files, thus the
  6973. * PUT/DELETE methods are not valid. */
  6974. send_http_error(conn,
  6975. 405,
  6976. "%s method not allowed",
  6977. conn->request_info.request_method);
  6978. return;
  6979. }
  6980. /* 6.1.2. Check if put authorization for static files is available.
  6981. */
  6982. if (!is_authorized_for_put(conn)) {
  6983. send_authorization_request(conn);
  6984. return;
  6985. }
  6986. } else {
  6987. /* 6.2. This is either a OPTIONS, GET, HEAD or POST request,
  6988. * or it is a PUT or DELETE request to a resource that does not
  6989. * correspond to a file. Check authorization. */
  6990. if (!check_authorization(conn, path)) {
  6991. send_authorization_request(conn);
  6992. return;
  6993. }
  6994. }
  6995. /* request is authorized or does not need authorization */
  6996. /* 7. check if there are request handlers for this uri */
  6997. if (is_callback_resource) {
  6998. if (!is_websocket_request) {
  6999. if (callback_handler(conn, callback_data)) {
  7000. /* Do nothing, callback has served the request */
  7001. discard_unread_request_data(conn);
  7002. } else {
  7003. /* TODO (high): what if the handler did NOT handle the
  7004. * request */
  7005. /* The last version did handle this as a file request, but
  7006. * since a file request is not always a script resource,
  7007. * the authorization check might be different */
  7008. interpret_uri(conn,
  7009. path,
  7010. sizeof(path),
  7011. &file,
  7012. &is_script_resource,
  7013. &is_websocket_request,
  7014. &is_put_or_delete_request);
  7015. callback_handler = NULL;
  7016. /* TODO (very low): goto is deprecatedm but for the moment,
  7017. * a goto is
  7018. * simpler than some curious loop. */
  7019. /* The situation "callback does not handle the request"
  7020. * needs to be reconsidered anyway. */
  7021. goto no_callback_resource;
  7022. }
  7023. } else {
  7024. #if defined(USE_WEBSOCKET)
  7025. handle_websocket_request(conn,
  7026. path,
  7027. is_callback_resource,
  7028. ws_connect_handler,
  7029. ws_ready_handler,
  7030. ws_data_handler,
  7031. ws_close_handler,
  7032. callback_data);
  7033. #endif
  7034. }
  7035. return;
  7036. }
  7037. /* 8. handle websocket requests */
  7038. #if defined(USE_WEBSOCKET)
  7039. if (is_websocket_request) {
  7040. handle_websocket_request(
  7041. conn,
  7042. path,
  7043. !is_script_resource /* could be deprecated global callback */,
  7044. deprecated_websocket_connect_wrapper,
  7045. deprecated_websocket_ready_wrapper,
  7046. deprecated_websocket_data_wrapper,
  7047. NULL,
  7048. &conn->ctx->callbacks);
  7049. return;
  7050. } else
  7051. #endif
  7052. #if defined(NO_FILES)
  7053. /* 9a. In case the server uses only callbacks, this uri is unknown.
  7054. * Then, all request handling ends here. */
  7055. send_http_error(conn, 404, "%s", "Not Found");
  7056. #else
  7057. /* 9b. This request is either for a static file or resource handled
  7058. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  7059. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  7060. send_http_error(conn, 404, "%s", "Not Found");
  7061. return;
  7062. }
  7063. /* 10. File is handled by a script. */
  7064. if (is_script_resource) {
  7065. handle_file_based_request(conn, path, &file);
  7066. return;
  7067. }
  7068. /* 11. Handle put/delete/mkcol requests */
  7069. if (is_put_or_delete_request) {
  7070. /* 11.1. PUT method */
  7071. if (!strcmp(ri->request_method, "PUT")) {
  7072. put_file(conn, path);
  7073. return;
  7074. }
  7075. /* 11.2. DELETE method */
  7076. if (!strcmp(ri->request_method, "DELETE")) {
  7077. delete_file(conn, path);
  7078. return;
  7079. }
  7080. /* 11.3. MKCOL method */
  7081. if (!strcmp(ri->request_method, "MKCOL")) {
  7082. mkcol(conn, path);
  7083. return;
  7084. }
  7085. /* 11.4. should never reach this point */
  7086. send_http_error(conn,
  7087. 405,
  7088. "%s method not allowed",
  7089. conn->request_info.request_method);
  7090. return;
  7091. }
  7092. /* 11. File does not exist, or it was configured that it should be
  7093. * hidden */
  7094. if (((file.membuf == NULL) && (file.modification_time == (time_t)0)) ||
  7095. (must_hide_file(conn, path))) {
  7096. send_http_error(conn, 404, "%s", "Not found");
  7097. return;
  7098. }
  7099. /* 12. Directories uris should end with a slash */
  7100. if (file.is_directory && ri->uri[uri_len - 1] != '/') {
  7101. gmt_time_string(date, sizeof(date), &curtime);
  7102. mg_printf(conn,
  7103. "HTTP/1.1 301 Moved Permanently\r\n"
  7104. "Location: %s/\r\n"
  7105. "Date: %s\r\n"
  7106. "Content-Length: 0\r\n"
  7107. "Connection: %s\r\n\r\n",
  7108. ri->uri,
  7109. date,
  7110. suggest_connection_header(conn));
  7111. return;
  7112. }
  7113. /* 13. Handle other methods than GET/HEAD */
  7114. /* 13.1. Handle PROPFIND */
  7115. if (!strcmp(ri->request_method, "PROPFIND")) {
  7116. handle_propfind(conn, path, &file);
  7117. return;
  7118. }
  7119. /* 13.2. Handle OPTIONS for files */
  7120. if (!strcmp(ri->request_method, "OPTIONS")) {
  7121. /* This standard handler is only used for real files.
  7122. * Scripts should support the OPTIONS method themselves, to allow a
  7123. * maximum flexibility.
  7124. * Lua and CGI scripts may fully support CORS this way (including
  7125. * preflights). */
  7126. send_options(conn);
  7127. return;
  7128. }
  7129. /* 13.3. everything but GET and HEAD (e.g. POST) */
  7130. if (0 != strcmp(ri->request_method, "GET") &&
  7131. 0 != strcmp(ri->request_method, "HEAD")) {
  7132. send_http_error(conn,
  7133. 405,
  7134. "%s method not allowed",
  7135. conn->request_info.request_method);
  7136. return;
  7137. }
  7138. /* 14. directories */
  7139. if (file.is_directory) {
  7140. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  7141. /* 14.1. use a substitute file */
  7142. /* TODO (high): substitute index may be a script resource.
  7143. * define what should be possible in this case. */
  7144. } else {
  7145. /* 14.2. no substitute file */
  7146. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  7147. "yes")) {
  7148. handle_directory_request(conn, path);
  7149. } else {
  7150. send_http_error(
  7151. conn, 403, "%s", "Error: Directory listing denied");
  7152. }
  7153. return;
  7154. }
  7155. }
  7156. handle_file_based_request(conn, path, &file);
  7157. #endif /* !defined(NO_FILES) */
  7158. #if 0
  7159. /* Perform redirect and auth checks before calling begin_request()
  7160. * handler.
  7161. * Otherwise, begin_request() would need to perform auth checks and
  7162. * redirects. */
  7163. #endif
  7164. }
  7165. return;
  7166. }
  7167. static void handle_file_based_request(struct mg_connection *conn,
  7168. const char *path,
  7169. struct file *file)
  7170. {
  7171. if (!conn || !conn->ctx)
  7172. return;
  7173. if (0) {
  7174. #ifdef USE_LUA
  7175. } else if (match_prefix(
  7176. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  7177. strlen(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  7178. path) > 0) {
  7179. /* Lua server page: an SSI like page containing mostly plain html code
  7180. * plus some tags with server generated contents. */
  7181. handle_lsp_request(conn, path, file, NULL);
  7182. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  7183. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  7184. path) > 0) {
  7185. /* Lua in-server module script: a CGI like script used to generate the
  7186. * entire reply. */
  7187. mg_exec_lua_script(conn, path, NULL);
  7188. #endif
  7189. #if !defined(NO_CGI)
  7190. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  7191. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  7192. path) > 0) {
  7193. /* CGI scripts may support all HTTP methods */
  7194. handle_cgi_request(conn, path);
  7195. #endif /* !NO_CGI */
  7196. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7197. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7198. path) > 0) {
  7199. handle_ssi_file_request(conn, path, file);
  7200. } else if ((!conn->in_error_handler) && is_not_modified(conn, file)) {
  7201. /* Send 304 "Not Modified" - this must not send any body data */
  7202. send_http_error(conn, 304, "%s", "");
  7203. } else {
  7204. handle_static_file_request(conn, path, file);
  7205. }
  7206. }
  7207. static void close_all_listening_sockets(struct mg_context *ctx)
  7208. {
  7209. unsigned int i;
  7210. if (!ctx)
  7211. return;
  7212. for (i = 0; i < ctx->num_listening_sockets; i++) {
  7213. closesocket(ctx->listening_sockets[i].sock);
  7214. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  7215. }
  7216. mg_free(ctx->listening_sockets);
  7217. ctx->listening_sockets = NULL;
  7218. mg_free(ctx->listening_ports);
  7219. ctx->listening_ports = NULL;
  7220. }
  7221. /* Valid listening port specification is: [ip_address:]port[s]
  7222. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  7223. * Examples for IPv6: [::]:80, [::1]:80,
  7224. * [FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:443s
  7225. * see https://tools.ietf.org/html/rfc3513#section-2.2 */
  7226. static int parse_port_string(const struct vec *vec, struct socket *so)
  7227. {
  7228. unsigned int a, b, c, d, port;
  7229. int ch, len;
  7230. #if defined(USE_IPV6)
  7231. char buf[100] = {0};
  7232. #endif
  7233. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  7234. * Also, all-zeroes in the socket address means binding to all addresses
  7235. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  7236. memset(so, 0, sizeof(*so));
  7237. so->lsa.sin.sin_family = AF_INET;
  7238. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) ==
  7239. 5) {
  7240. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  7241. so->lsa.sin.sin_addr.s_addr =
  7242. htonl((a << 24) | (b << 16) | (c << 8) | d);
  7243. so->lsa.sin.sin_port = htons((uint16_t)port);
  7244. #if defined(USE_IPV6)
  7245. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2 &&
  7246. mg_inet_pton(
  7247. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  7248. /* IPv6 address, examples: see above */
  7249. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton */
  7250. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  7251. #endif
  7252. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  7253. /* If only port is specified, bind to IPv4, INADDR_ANY */
  7254. so->lsa.sin.sin_port = htons((uint16_t)port);
  7255. } else {
  7256. /* Parsing failure. Make port invalid. */
  7257. port = 0;
  7258. len = 0;
  7259. }
  7260. /* sscanf and the option splitting code ensure the following condition */
  7261. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  7262. return 0;
  7263. }
  7264. ch = vec->ptr[len]; /* Next character after the port number */
  7265. so->is_ssl = (ch == 's');
  7266. so->ssl_redir = (ch == 'r');
  7267. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  7268. return is_valid_port(port) &&
  7269. (ch == '\0' || ch == 's' || ch == 'r' || ch == ',');
  7270. }
  7271. static int set_ports_option(struct mg_context *ctx)
  7272. {
  7273. if (ctx) {
  7274. const char *list = ctx->config[LISTENING_PORTS];
  7275. int on = 1, success = 1;
  7276. #if defined(USE_IPV6)
  7277. int off = 0;
  7278. #endif
  7279. struct vec vec;
  7280. struct socket so, *ptr;
  7281. in_port_t *portPtr;
  7282. union usa usa;
  7283. socklen_t len;
  7284. memset(&so, 0, sizeof(so));
  7285. memset(&usa, 0, sizeof(usa));
  7286. len = sizeof(usa);
  7287. while (success && (list = next_option(list, &vec, NULL)) != NULL) {
  7288. if (!parse_port_string(&vec, &so)) {
  7289. mg_cry(fc(ctx),
  7290. "%s: %.*s: invalid port spec. Expecting list of: %s",
  7291. __func__,
  7292. (int)vec.len,
  7293. vec.ptr,
  7294. "[IP_ADDRESS:]PORT[s|r]");
  7295. success = 0;
  7296. } else if (so.is_ssl && ctx->ssl_ctx == NULL) {
  7297. mg_cry(
  7298. fc(ctx),
  7299. "Cannot add SSL socket, is -ssl_certificate option set?");
  7300. success = 0;
  7301. } else if ((so.sock =
  7302. socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
  7303. INVALID_SOCKET ||
  7304. #ifdef _WIN32
  7305. /* Windows SO_REUSEADDR lets many procs binds to a
  7306. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  7307. * if someone already has the socket -- DTL */
  7308. setsockopt(so.sock,
  7309. SOL_SOCKET,
  7310. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  7311. * Windows might need a few seconds before
  7312. * the same port can be used again in the
  7313. * same process, so a short Sleep may be
  7314. * required between mg_stop and mg_start.
  7315. */
  7316. SO_EXCLUSIVEADDRUSE,
  7317. (SOCK_OPT_TYPE)&on,
  7318. sizeof(on)) != 0 ||
  7319. #else
  7320. setsockopt(so.sock,
  7321. SOL_SOCKET,
  7322. SO_REUSEADDR,
  7323. (SOCK_OPT_TYPE)&on,
  7324. sizeof(on)) != 0 ||
  7325. #endif
  7326. #if defined(USE_IPV6)
  7327. (so.lsa.sa.sa_family == AF_INET6 &&
  7328. setsockopt(so.sock,
  7329. IPPROTO_IPV6,
  7330. IPV6_V6ONLY,
  7331. (void *)&off,
  7332. sizeof(off)) != 0) ||
  7333. #endif
  7334. bind(so.sock,
  7335. &so.lsa.sa,
  7336. so.lsa.sa.sa_family == AF_INET
  7337. ? sizeof(so.lsa.sin)
  7338. : sizeof(so.lsa.sa)) != 0 ||
  7339. listen(so.sock, SOMAXCONN) != 0 ||
  7340. getsockname(so.sock, &(usa.sa), &len) != 0) {
  7341. /* TODO(mid): rewrite this IF above */
  7342. mg_cry(fc(ctx),
  7343. "%s: cannot bind to %.*s: %d (%s)",
  7344. __func__,
  7345. (int)vec.len,
  7346. vec.ptr,
  7347. (int)ERRNO,
  7348. strerror(errno));
  7349. if (so.sock != INVALID_SOCKET) {
  7350. closesocket(so.sock);
  7351. so.sock = INVALID_SOCKET;
  7352. }
  7353. success = 0;
  7354. } else if ((ptr = (struct socket *)mg_realloc(
  7355. ctx->listening_sockets,
  7356. (ctx->num_listening_sockets + 1) *
  7357. sizeof(ctx->listening_sockets[0]))) == NULL) {
  7358. closesocket(so.sock);
  7359. so.sock = INVALID_SOCKET;
  7360. success = 0;
  7361. } else if ((portPtr = (in_port_t *)mg_realloc(
  7362. ctx->listening_ports,
  7363. (ctx->num_listening_sockets + 1) *
  7364. sizeof(ctx->listening_ports[0]))) == NULL) {
  7365. closesocket(so.sock);
  7366. so.sock = INVALID_SOCKET;
  7367. mg_free(ptr);
  7368. success = 0;
  7369. } else {
  7370. set_close_on_exec(so.sock, fc(ctx));
  7371. ctx->listening_sockets = ptr;
  7372. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  7373. ctx->listening_ports = portPtr;
  7374. ctx->listening_ports[ctx->num_listening_sockets] =
  7375. ntohs(usa.sin.sin_port);
  7376. ctx->num_listening_sockets++;
  7377. }
  7378. }
  7379. if (!success) {
  7380. close_all_listening_sockets(ctx);
  7381. }
  7382. return success;
  7383. }
  7384. return 0;
  7385. }
  7386. static const char *header_val(const struct mg_connection *conn,
  7387. const char *header)
  7388. {
  7389. const char *header_value;
  7390. if ((header_value = mg_get_header(conn, header)) == NULL) {
  7391. return "-";
  7392. } else {
  7393. return header_value;
  7394. }
  7395. }
  7396. static void log_access(const struct mg_connection *conn)
  7397. {
  7398. const struct mg_request_info *ri;
  7399. FILE *fp;
  7400. char date[64], src_addr[IP_ADDR_STR_LEN];
  7401. struct tm *tm;
  7402. const char *referer;
  7403. const char *user_agent;
  7404. char buf[4096];
  7405. if (!conn || !conn->ctx)
  7406. return;
  7407. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL
  7408. ? NULL
  7409. : fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  7410. if (fp == NULL && conn->ctx->callbacks.log_message == NULL)
  7411. return;
  7412. tm = localtime(&conn->conn_birth_time);
  7413. if (tm != NULL) {
  7414. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  7415. } else {
  7416. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  7417. date[sizeof(date) - 1] = '\0';
  7418. }
  7419. ri = &conn->request_info;
  7420. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7421. referer = header_val(conn, "Referer");
  7422. user_agent = header_val(conn, "User-Agent");
  7423. snprintf(buf,
  7424. sizeof(buf),
  7425. "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT " %s %s",
  7426. src_addr,
  7427. ri->remote_user == NULL ? "-" : ri->remote_user,
  7428. date,
  7429. ri->request_method ? ri->request_method : "-",
  7430. ri->uri ? ri->uri : "-",
  7431. ri->http_version,
  7432. conn->status_code,
  7433. conn->num_bytes_sent,
  7434. referer,
  7435. user_agent);
  7436. if (conn->ctx->callbacks.log_access) {
  7437. conn->ctx->callbacks.log_access(conn, buf);
  7438. }
  7439. if (fp) {
  7440. flockfile(fp);
  7441. fprintf(fp, "%s", buf);
  7442. fputc('\n', fp);
  7443. fflush(fp);
  7444. funlockfile(fp);
  7445. fclose(fp);
  7446. }
  7447. }
  7448. /* Verify given socket address against the ACL.
  7449. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */
  7450. static int check_acl(struct mg_context *ctx, uint32_t remote_ip)
  7451. {
  7452. int allowed, flag;
  7453. uint32_t net, mask;
  7454. struct vec vec;
  7455. if (ctx) {
  7456. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  7457. /* If any ACL is set, deny by default */
  7458. allowed = list == NULL ? '+' : '-';
  7459. while ((list = next_option(list, &vec, NULL)) != NULL) {
  7460. flag = vec.ptr[0];
  7461. if ((flag != '+' && flag != '-') ||
  7462. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  7463. mg_cry(
  7464. fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  7465. return -1;
  7466. }
  7467. if (net == (remote_ip & mask)) {
  7468. allowed = flag;
  7469. }
  7470. }
  7471. return allowed == '+';
  7472. }
  7473. return -1;
  7474. }
  7475. #if !defined(_WIN32)
  7476. static int set_uid_option(struct mg_context *ctx)
  7477. {
  7478. struct passwd *pw;
  7479. if (ctx) {
  7480. const char *uid = ctx->config[RUN_AS_USER];
  7481. int success = 0;
  7482. if (uid == NULL) {
  7483. success = 1;
  7484. } else {
  7485. if ((pw = getpwnam(uid)) == NULL) {
  7486. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  7487. } else if (setgid(pw->pw_gid) == -1) {
  7488. mg_cry(fc(ctx),
  7489. "%s: setgid(%s): %s",
  7490. __func__,
  7491. uid,
  7492. strerror(errno));
  7493. } else if (setgroups(0, NULL)) {
  7494. mg_cry(
  7495. fc(ctx), "%s: setgroups(): %s", __func__, strerror(errno));
  7496. } else if (setuid(pw->pw_uid) == -1) {
  7497. mg_cry(fc(ctx),
  7498. "%s: setuid(%s): %s",
  7499. __func__,
  7500. uid,
  7501. strerror(errno));
  7502. } else {
  7503. success = 1;
  7504. }
  7505. }
  7506. return success;
  7507. }
  7508. return 0;
  7509. }
  7510. #endif /* !_WIN32 */
  7511. #if !defined(NO_SSL)
  7512. static pthread_mutex_t *ssl_mutexes;
  7513. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *))
  7514. {
  7515. if (!conn)
  7516. return 0;
  7517. return (conn->ssl = SSL_new(s)) != NULL &&
  7518. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  7519. func(conn->ssl) == 1;
  7520. }
  7521. /* Return OpenSSL error message (from CRYPTO lib) */
  7522. static const char *ssl_error(void)
  7523. {
  7524. unsigned long err;
  7525. err = ERR_get_error();
  7526. return err == 0 ? "" : ERR_error_string(err, NULL);
  7527. }
  7528. static void
  7529. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  7530. {
  7531. (void)line;
  7532. (void)file;
  7533. if (mode & 1) {
  7534. /* 1 is CRYPTO_LOCK */
  7535. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  7536. } else {
  7537. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  7538. }
  7539. }
  7540. static unsigned long ssl_id_callback(void)
  7541. {
  7542. return (unsigned long)pthread_self();
  7543. }
  7544. #if !defined(NO_SSL_DL)
  7545. static void *
  7546. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  7547. {
  7548. union {
  7549. void *p;
  7550. void (*fp)(void);
  7551. } u;
  7552. void *dll_handle;
  7553. struct ssl_func *fp;
  7554. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  7555. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  7556. return NULL;
  7557. }
  7558. for (fp = sw; fp->name != NULL; fp++) {
  7559. #ifdef _WIN32
  7560. /* GetProcAddress() returns pointer to function */
  7561. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  7562. #else
  7563. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  7564. * pointers to function pointers. We need to use a union to make a
  7565. * cast. */
  7566. u.p = dlsym(dll_handle, fp->name);
  7567. #endif /* _WIN32 */
  7568. if (u.fp == NULL) {
  7569. mg_cry(fc(ctx),
  7570. "%s: %s: cannot find %s",
  7571. __func__,
  7572. dll_name,
  7573. fp->name);
  7574. dlclose(dll_handle);
  7575. return NULL;
  7576. } else {
  7577. fp->ptr = u.fp;
  7578. }
  7579. }
  7580. return dll_handle;
  7581. }
  7582. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  7583. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  7584. #endif /* NO_SSL_DL */
  7585. #if defined(SSL_ALREADY_INITIALIZED)
  7586. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  7587. #else
  7588. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  7589. #endif
  7590. static int initialize_ssl(struct mg_context *ctx)
  7591. {
  7592. int i;
  7593. size_t size;
  7594. #if !defined(NO_SSL_DL)
  7595. if (!cryptolib_dll_handle) {
  7596. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  7597. if (!cryptolib_dll_handle) {
  7598. return 0;
  7599. }
  7600. }
  7601. #endif /* NO_SSL_DL */
  7602. if (mg_atomic_inc(&cryptolib_users) > 1)
  7603. return 1;
  7604. /* Initialize locking callbacks, needed for thread safety.
  7605. * http://www.openssl.org/support/faq.html#PROG1
  7606. */
  7607. i = CRYPTO_num_locks();
  7608. if (i < 0)
  7609. i = 0;
  7610. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  7611. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  7612. mg_cry(
  7613. fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error());
  7614. return 0;
  7615. }
  7616. for (i = 0; i < CRYPTO_num_locks(); i++) {
  7617. pthread_mutex_init(&ssl_mutexes[i], NULL);
  7618. }
  7619. CRYPTO_set_locking_callback(&ssl_locking_callback);
  7620. CRYPTO_set_id_callback(&ssl_id_callback);
  7621. return 1;
  7622. }
  7623. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  7624. static int set_ssl_option(struct mg_context *ctx)
  7625. {
  7626. const char *pem;
  7627. int callback_ret;
  7628. /* If PEM file is not specified and the init_ssl callback
  7629. * is not specified, skip SSL initialization. */
  7630. if (!ctx)
  7631. return 0;
  7632. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL &&
  7633. ctx->callbacks.init_ssl == NULL) {
  7634. return 1;
  7635. }
  7636. if (!initialize_ssl(ctx)) {
  7637. return 0;
  7638. }
  7639. #if !defined(NO_SSL_DL)
  7640. if (!ssllib_dll_handle) {
  7641. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  7642. if (!ssllib_dll_handle) {
  7643. return 0;
  7644. }
  7645. }
  7646. #endif /* NO_SSL_DL */
  7647. /* Initialize SSL library */
  7648. SSL_library_init();
  7649. SSL_load_error_strings();
  7650. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  7651. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  7652. return 0;
  7653. }
  7654. /* If a callback has been specified, call it. */
  7655. callback_ret =
  7656. (ctx->callbacks.init_ssl == NULL)
  7657. ? 0
  7658. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  7659. /* If callback returns 0, civetweb sets up the SSL certificate.
  7660. * If it returns 1, civetweb assumes the calback already did this.
  7661. * If it returns -1, initializing ssl fails. */
  7662. if (callback_ret < 0) {
  7663. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  7664. return 0;
  7665. }
  7666. if (callback_ret == 0) {
  7667. if (pem != NULL) {
  7668. if ((SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) ||
  7669. (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0)) {
  7670. mg_cry(fc(ctx),
  7671. "%s: cannot open %s: %s",
  7672. __func__,
  7673. pem,
  7674. ssl_error());
  7675. return 0;
  7676. }
  7677. }
  7678. }
  7679. if (pem != NULL) {
  7680. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  7681. }
  7682. return 1;
  7683. }
  7684. static void uninitialize_ssl(struct mg_context *ctx)
  7685. {
  7686. int i;
  7687. (void)ctx;
  7688. if (mg_atomic_dec(&cryptolib_users) == 0) {
  7689. CRYPTO_set_locking_callback(NULL);
  7690. for (i = 0; i < CRYPTO_num_locks(); i++) {
  7691. pthread_mutex_destroy(&ssl_mutexes[i]);
  7692. }
  7693. CRYPTO_set_locking_callback(NULL);
  7694. CRYPTO_set_id_callback(NULL);
  7695. }
  7696. }
  7697. #endif /* !NO_SSL */
  7698. static int set_gpass_option(struct mg_context *ctx)
  7699. {
  7700. if (ctx) {
  7701. struct file file = STRUCT_FILE_INITIALIZER;
  7702. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  7703. if (path != NULL && !mg_stat(fc(ctx), path, &file)) {
  7704. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  7705. return 0;
  7706. }
  7707. return 1;
  7708. }
  7709. return 0;
  7710. }
  7711. static int set_acl_option(struct mg_context *ctx)
  7712. {
  7713. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  7714. }
  7715. static void reset_per_request_attributes(struct mg_connection *conn)
  7716. {
  7717. if (!conn)
  7718. return;
  7719. conn->path_info = NULL;
  7720. conn->num_bytes_sent = conn->consumed_content = 0;
  7721. conn->status_code = -1;
  7722. conn->is_chunked = 0;
  7723. conn->must_close = conn->request_len = conn->throttle = 0;
  7724. conn->request_info.content_length = -1;
  7725. conn->request_info.remote_user = NULL;
  7726. conn->request_info.request_method = NULL;
  7727. conn->request_info.uri = NULL;
  7728. conn->request_info.http_version = NULL;
  7729. conn->request_info.num_headers = 0;
  7730. conn->data_len = 0;
  7731. conn->chunk_remainder = 0;
  7732. }
  7733. static int set_sock_timeout(SOCKET sock, int milliseconds)
  7734. {
  7735. int r1, r2;
  7736. #ifdef _WIN32
  7737. DWORD t = (DWORD)milliseconds;
  7738. #else
  7739. #if defined(TCP_USER_TIMEOUT)
  7740. unsigned int uto = (unsigned int)milliseconds;
  7741. #endif
  7742. struct timeval t;
  7743. t.tv_sec = milliseconds / 1000;
  7744. t.tv_usec = (milliseconds * 1000) % 1000000;
  7745. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  7746. * max. time waiting for the acknowledged of TCP data before the connection
  7747. * will be forcefully closed and ETIMEDOUT is returned to the application.
  7748. * If this option is not set, the default timeout of 20-30 minutes is used.
  7749. */
  7750. /* #define TCP_USER_TIMEOUT (18) */
  7751. #if defined(TCP_USER_TIMEOUT)
  7752. setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  7753. #endif
  7754. #endif
  7755. r1 =
  7756. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&t, sizeof(t));
  7757. r2 =
  7758. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&t, sizeof(t));
  7759. return r1 || r2;
  7760. }
  7761. static void close_socket_gracefully(struct mg_connection *conn)
  7762. {
  7763. #if defined(_WIN32)
  7764. char buf[MG_BUF_LEN];
  7765. int n;
  7766. #endif
  7767. struct linger linger;
  7768. double timeout = -1.0;
  7769. if (!conn) {
  7770. return;
  7771. }
  7772. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  7773. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  7774. }
  7775. /* Set linger option to avoid socket hanging out after close. This prevent
  7776. * ephemeral port exhaust problem under high QPS. */
  7777. linger.l_onoff = 1;
  7778. linger.l_linger = 1;
  7779. if (setsockopt(conn->client.sock,
  7780. SOL_SOCKET,
  7781. SO_LINGER,
  7782. (char *)&linger,
  7783. sizeof(linger)) != 0) {
  7784. mg_cry(conn,
  7785. "%s: setsockopt(SOL_SOCKET SO_LINGER) failed: %s",
  7786. __func__,
  7787. strerror(ERRNO));
  7788. }
  7789. /* Send FIN to the client */
  7790. shutdown(conn->client.sock, SHUT_WR);
  7791. set_non_blocking_mode(conn->client.sock);
  7792. #if defined(_WIN32)
  7793. /* Read and discard pending incoming data. If we do not do that and close
  7794. * the socket, the data in the send buffer may be discarded. This
  7795. * behaviour is seen on Windows, when client keeps sending data
  7796. * when server decides to close the connection; then when client
  7797. * does recv() it gets no data back. */
  7798. do {
  7799. n = pull(NULL, conn, buf, sizeof(buf), timeout);
  7800. } while (n > 0);
  7801. #endif
  7802. /* Now we know that our FIN is ACK-ed, safe to close */
  7803. closesocket(conn->client.sock);
  7804. conn->client.sock = INVALID_SOCKET;
  7805. }
  7806. static void close_connection(struct mg_connection *conn)
  7807. {
  7808. if (!conn || !conn->ctx)
  7809. return;
  7810. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  7811. if (conn->lua_websocket_state) {
  7812. lua_websocket_close(conn, conn->lua_websocket_state);
  7813. conn->lua_websocket_state = NULL;
  7814. }
  7815. #endif
  7816. /* call the connection_close callback if assigned */
  7817. if ((conn->ctx->callbacks.connection_close != NULL) &&
  7818. (conn->ctx->context_type == 1)) {
  7819. conn->ctx->callbacks.connection_close(conn);
  7820. }
  7821. mg_lock_connection(conn);
  7822. conn->must_close = 1;
  7823. #ifndef NO_SSL
  7824. if (conn->ssl != NULL) {
  7825. /* Run SSL_shutdown twice to ensure completly close SSL connection */
  7826. SSL_shutdown(conn->ssl);
  7827. SSL_free(conn->ssl);
  7828. conn->ssl = NULL;
  7829. }
  7830. #endif
  7831. if (conn->client.sock != INVALID_SOCKET) {
  7832. close_socket_gracefully(conn);
  7833. conn->client.sock = INVALID_SOCKET;
  7834. }
  7835. mg_unlock_connection(conn);
  7836. }
  7837. void mg_close_connection(struct mg_connection *conn)
  7838. {
  7839. struct mg_context *client_ctx = NULL;
  7840. unsigned int i;
  7841. if (conn == NULL)
  7842. return;
  7843. if (conn->ctx->context_type == 2) {
  7844. client_ctx = conn->ctx;
  7845. /* client context: loops must end */
  7846. conn->ctx->stop_flag = 1;
  7847. }
  7848. #ifndef NO_SSL
  7849. if (conn->client_ssl_ctx != NULL) {
  7850. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  7851. }
  7852. #endif
  7853. close_connection(conn);
  7854. if (client_ctx != NULL) {
  7855. /* join worker thread and free context */
  7856. for (i = 0; i < client_ctx->workerthreadcount; i++) {
  7857. mg_join_thread(client_ctx->workerthreadids[i]);
  7858. }
  7859. mg_free(client_ctx->workerthreadids);
  7860. mg_free(client_ctx);
  7861. }
  7862. (void)pthread_mutex_destroy(&conn->mutex);
  7863. mg_free(conn);
  7864. }
  7865. struct mg_connection *mg_connect_client(
  7866. const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len)
  7867. {
  7868. static struct mg_context fake_ctx;
  7869. struct mg_connection *conn = NULL;
  7870. SOCKET sock;
  7871. if ((sock = conn2(&fake_ctx, host, port, use_ssl, ebuf, ebuf_len)) ==
  7872. INVALID_SOCKET) {
  7873. } else if ((conn = (struct mg_connection *)mg_calloc(
  7874. 1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  7875. snprintf(ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO));
  7876. closesocket(sock);
  7877. #ifndef NO_SSL
  7878. } else if (use_ssl &&
  7879. (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method())) ==
  7880. NULL) {
  7881. snprintf(ebuf, ebuf_len, "SSL_CTX_new error");
  7882. closesocket(sock);
  7883. mg_free(conn);
  7884. conn = NULL;
  7885. #endif /* NO_SSL */
  7886. } else {
  7887. socklen_t len = sizeof(struct sockaddr);
  7888. conn->buf_size = MAX_REQUEST_SIZE;
  7889. conn->buf = (char *)(conn + 1);
  7890. conn->ctx = &fake_ctx;
  7891. conn->client.sock = sock;
  7892. if (getsockname(sock, &conn->client.rsa.sa, &len) != 0) {
  7893. mg_cry(conn,
  7894. "%s: getsockname() failed: %s",
  7895. __func__,
  7896. strerror(ERRNO));
  7897. }
  7898. conn->client.is_ssl = use_ssl ? 1 : 0;
  7899. (void)pthread_mutex_init(&conn->mutex, NULL);
  7900. #ifndef NO_SSL
  7901. if (use_ssl) {
  7902. /* SSL_CTX_set_verify call is needed to switch off server
  7903. * certificate checking, which is off by default in OpenSSL and on
  7904. * in yaSSL. */
  7905. SSL_CTX_set_verify(conn->client_ssl_ctx, 0, 0);
  7906. sslize(conn, conn->client_ssl_ctx, SSL_connect);
  7907. }
  7908. #endif
  7909. }
  7910. return conn;
  7911. }
  7912. static int is_valid_uri(const char *uri)
  7913. {
  7914. /* Conform to
  7915. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  7916. * URI can be an asterisk (*) or should start with slash. */
  7917. return uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0');
  7918. }
  7919. static int
  7920. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  7921. {
  7922. const char *cl;
  7923. if (ebuf_len > 0) {
  7924. ebuf[0] = '\0';
  7925. }
  7926. *err = 0;
  7927. reset_per_request_attributes(conn);
  7928. if (!conn) {
  7929. snprintf(ebuf, ebuf_len, "%s", "Internal error");
  7930. *err = 500;
  7931. return 0;
  7932. }
  7933. /* Set the time the request was received. This value should be used for
  7934. * timeouts. */
  7935. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  7936. conn->request_len =
  7937. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  7938. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len); */
  7939. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  7940. snprintf(ebuf, ebuf_len, "%s", "Invalid request size");
  7941. *err = 500;
  7942. return 0;
  7943. }
  7944. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  7945. snprintf(ebuf, ebuf_len, "%s", "Request Too Large");
  7946. *err = 413;
  7947. return 0;
  7948. } else if (conn->request_len <= 0) {
  7949. if (conn->data_len > 0) {
  7950. snprintf(ebuf, ebuf_len, "%s", "Client sent malformed request");
  7951. *err = 400;
  7952. } else {
  7953. /* Server did not send anything -> just close the connection */
  7954. conn->must_close = 1;
  7955. snprintf(ebuf, ebuf_len, "%s", "Client did not send a request");
  7956. *err = 0;
  7957. }
  7958. return 0;
  7959. } else if (parse_http_message(
  7960. conn->buf, conn->buf_size, &conn->request_info) <= 0) {
  7961. snprintf(ebuf, ebuf_len, "%s", "Bad Request");
  7962. *err = 400;
  7963. return 0;
  7964. } else {
  7965. /* Message is a valid request or response */
  7966. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  7967. /* Request/response has content length set */
  7968. char *endptr = NULL;
  7969. conn->content_len = strtoll(cl, &endptr, 10);
  7970. if (endptr == cl) {
  7971. snprintf(ebuf, ebuf_len, "%s", "Bad Request");
  7972. *err = 411;
  7973. return 0;
  7974. }
  7975. /* Publish the content length back to the request info. */
  7976. conn->request_info.content_length = conn->content_len;
  7977. } else if ((cl = get_header(&conn->request_info,
  7978. "Transfer-encoding")) != NULL &&
  7979. strcmp(cl, "chunked") == 0) {
  7980. conn->is_chunked = 1;
  7981. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST") ||
  7982. !mg_strcasecmp(conn->request_info.request_method, "PUT")) {
  7983. /* POST or PUT request without content length set */
  7984. conn->content_len = -1;
  7985. } else if (!mg_strncasecmp(
  7986. conn->request_info.request_method, "HTTP/", 5)) {
  7987. /* Response without content length set */
  7988. conn->content_len = -1;
  7989. } else {
  7990. /* Other request */
  7991. conn->content_len = 0;
  7992. }
  7993. }
  7994. return 1;
  7995. }
  7996. int mg_get_response(struct mg_connection *conn,
  7997. char *ebuf,
  7998. size_t ebuf_len,
  7999. int timeout)
  8000. {
  8001. if (conn) {
  8002. /* Implementation of API function for HTTP clients */
  8003. int err, ret;
  8004. struct mg_context *octx = conn->ctx;
  8005. struct mg_context rctx = *(conn->ctx);
  8006. char txt[32];
  8007. if (timeout >= 0) {
  8008. snprintf(txt, sizeof(txt), "%i", timeout);
  8009. rctx.config[REQUEST_TIMEOUT] = txt;
  8010. set_sock_timeout(conn->client.sock, timeout);
  8011. } else {
  8012. rctx.config[REQUEST_TIMEOUT] = NULL;
  8013. }
  8014. conn->ctx = &rctx;
  8015. ret = getreq(conn, ebuf, ebuf_len, &err);
  8016. conn->ctx = octx;
  8017. /* TODO (mid): Define proper return values - maybe return length?
  8018. * For the first test use <0 for error and >0 for OK */
  8019. return (ret == 0) ? -1 : +1;
  8020. }
  8021. return -1;
  8022. }
  8023. struct mg_connection *mg_download(const char *host,
  8024. int port,
  8025. int use_ssl,
  8026. char *ebuf,
  8027. size_t ebuf_len,
  8028. const char *fmt,
  8029. ...)
  8030. {
  8031. struct mg_connection *conn;
  8032. va_list ap;
  8033. int i;
  8034. int reqerr;
  8035. va_start(ap, fmt);
  8036. ebuf[0] = '\0';
  8037. /* open a connection */
  8038. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  8039. if (conn != NULL) {
  8040. i = mg_vprintf(conn, fmt, ap);
  8041. if (i <= 0) {
  8042. snprintf(ebuf, ebuf_len, "%s", "Error sending request");
  8043. } else {
  8044. getreq(conn, ebuf, ebuf_len, &reqerr);
  8045. }
  8046. }
  8047. /* if an error occured, close the connection */
  8048. if (ebuf[0] != '\0' && conn != NULL) {
  8049. mg_close_connection(conn);
  8050. conn = NULL;
  8051. }
  8052. va_end(ap);
  8053. return conn;
  8054. }
  8055. struct websocket_client_thread_data {
  8056. struct mg_connection *conn;
  8057. mg_websocket_data_handler data_handler;
  8058. mg_websocket_close_handler close_handler;
  8059. void *callback_data;
  8060. };
  8061. #if defined(USE_WEBSOCKET)
  8062. #ifdef _WIN32
  8063. static unsigned __stdcall websocket_client_thread(void *data)
  8064. #else
  8065. static void *websocket_client_thread(void *data)
  8066. #endif
  8067. {
  8068. struct websocket_client_thread_data *cdata =
  8069. (struct websocket_client_thread_data *)data;
  8070. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  8071. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  8072. if (cdata->close_handler != NULL) {
  8073. cdata->close_handler(cdata->conn, cdata->callback_data);
  8074. }
  8075. mg_free((void *)cdata);
  8076. #ifdef _WIN32
  8077. return 0;
  8078. #else
  8079. return NULL;
  8080. #endif
  8081. }
  8082. #endif
  8083. struct mg_connection *
  8084. mg_connect_websocket_client(const char *host,
  8085. int port,
  8086. int use_ssl,
  8087. char *error_buffer,
  8088. size_t error_buffer_size,
  8089. const char *path,
  8090. const char *origin,
  8091. mg_websocket_data_handler data_func,
  8092. mg_websocket_close_handler close_func,
  8093. void *user_data)
  8094. {
  8095. struct mg_connection *conn = NULL;
  8096. #if defined(USE_WEBSOCKET)
  8097. struct mg_context *newctx = NULL;
  8098. struct websocket_client_thread_data *thread_data;
  8099. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  8100. static const char *handshake_req;
  8101. if (origin != NULL) {
  8102. handshake_req = "GET %s HTTP/1.1\r\n"
  8103. "Host: %s\r\n"
  8104. "Upgrade: websocket\r\n"
  8105. "Connection: Upgrade\r\n"
  8106. "Sec-WebSocket-Key: %s\r\n"
  8107. "Sec-WebSocket-Version: 13\r\n"
  8108. "Origin: %s\r\n"
  8109. "\r\n";
  8110. } else {
  8111. handshake_req = "GET %s HTTP/1.1\r\n"
  8112. "Host: %s\r\n"
  8113. "Upgrade: websocket\r\n"
  8114. "Connection: Upgrade\r\n"
  8115. "Sec-WebSocket-Key: %s\r\n"
  8116. "Sec-WebSocket-Version: 13\r\n"
  8117. "\r\n";
  8118. }
  8119. /* Establish the client connection and request upgrade */
  8120. conn = mg_download(host,
  8121. port,
  8122. use_ssl,
  8123. error_buffer,
  8124. error_buffer_size,
  8125. handshake_req,
  8126. path,
  8127. host,
  8128. magic,
  8129. origin);
  8130. /* Connection object will be null if something goes wrong */
  8131. if (conn == NULL || (strcmp(conn->request_info.uri, "101") != 0)) {
  8132. if (!*error_buffer) {
  8133. /* if there is a connection, but it did not return 101,
  8134. * error_buffer is not yet set */
  8135. mg_snprintf(conn,
  8136. error_buffer,
  8137. error_buffer_size,
  8138. "Unexpected server reply");
  8139. }
  8140. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  8141. if (conn != NULL) {
  8142. mg_free(conn);
  8143. conn = NULL;
  8144. }
  8145. return conn;
  8146. }
  8147. /* For client connections, mg_context is fake. Since we need to set a
  8148. * callback function, we need to create a copy and modify it. */
  8149. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  8150. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  8151. newctx->user_data = user_data;
  8152. newctx->context_type = 2; /* client context type */
  8153. newctx->workerthreadcount = 1; /* one worker thread will be created */
  8154. newctx->workerthreadids =
  8155. (pthread_t *)mg_calloc(newctx->workerthreadcount, sizeof(pthread_t));
  8156. conn->ctx = newctx;
  8157. thread_data = (struct websocket_client_thread_data *)mg_calloc(
  8158. sizeof(struct websocket_client_thread_data), 1);
  8159. thread_data->conn = conn;
  8160. thread_data->data_handler = data_func;
  8161. thread_data->close_handler = close_func;
  8162. thread_data->callback_data = NULL;
  8163. /* Start a thread to read the websocket client connection
  8164. * This thread will automatically stop when mg_disconnect is
  8165. * called on the client connection */
  8166. if (mg_start_thread_with_id(websocket_client_thread,
  8167. (void *)thread_data,
  8168. newctx->workerthreadids) != 0) {
  8169. mg_free((void *)thread_data);
  8170. mg_free((void *)newctx->workerthreadids);
  8171. mg_free((void *)newctx);
  8172. mg_free((void *)conn);
  8173. conn = NULL;
  8174. DEBUG_TRACE("%s",
  8175. "Websocket client connect thread could not be started\r\n");
  8176. }
  8177. #else
  8178. /* Appease "unused parameter" warnings */
  8179. (void)host;
  8180. (void)port;
  8181. (void)use_ssl;
  8182. (void)error_buffer;
  8183. (void)error_buffer_size;
  8184. (void)path;
  8185. (void)origin;
  8186. (void)user_data;
  8187. (void)data_func;
  8188. (void)close_func;
  8189. #endif
  8190. return conn;
  8191. }
  8192. static void process_new_connection(struct mg_connection *conn)
  8193. {
  8194. if (conn && conn->ctx) {
  8195. struct mg_request_info *ri = &conn->request_info;
  8196. int keep_alive_enabled, keep_alive, discard_len;
  8197. char ebuf[100];
  8198. int reqerr;
  8199. keep_alive_enabled =
  8200. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  8201. /* Important: on new connection, reset the receiving buffer. Credit
  8202. * goes to crule42. */
  8203. conn->data_len = 0;
  8204. do {
  8205. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  8206. /* The request sent by the client could not be understood by
  8207. * the server, or it was incomplete or a timeout. Send an
  8208. * error message and close the connection. */
  8209. if (reqerr > 0) {
  8210. /*assert(ebuf[0] != '\0');*/
  8211. send_http_error(conn, reqerr, "%s", ebuf);
  8212. }
  8213. } else if (!is_valid_uri(conn->request_info.uri)) {
  8214. snprintf(ebuf, sizeof(ebuf), "Invalid URI: [%s]", ri->uri);
  8215. send_http_error(conn, 400, "%s", ebuf);
  8216. } else if (strcmp(ri->http_version, "1.0") &&
  8217. strcmp(ri->http_version, "1.1")) {
  8218. snprintf(ebuf,
  8219. sizeof(ebuf),
  8220. "Bad HTTP version: [%s]",
  8221. ri->http_version);
  8222. send_http_error(conn, 505, "%s", ebuf);
  8223. }
  8224. if (ebuf[0] == '\0') {
  8225. handle_request(conn);
  8226. if (conn->ctx->callbacks.end_request != NULL) {
  8227. conn->ctx->callbacks.end_request(conn, conn->status_code);
  8228. }
  8229. log_access(conn);
  8230. } else {
  8231. conn->must_close = 1;
  8232. }
  8233. if (ri->remote_user != NULL) {
  8234. mg_free((void *)ri->remote_user);
  8235. /* Important! When having connections with and without auth
  8236. * would cause double free and then crash */
  8237. ri->remote_user = NULL;
  8238. }
  8239. /* NOTE(lsm): order is important here. should_keep_alive() call is
  8240. * using parsed request, which will be invalid after memmove's
  8241. * below.
  8242. * Therefore, memorize should_keep_alive() result now for later use
  8243. * in loop exit condition. */
  8244. keep_alive = conn->ctx->stop_flag == 0 && keep_alive_enabled &&
  8245. conn->content_len >= 0 && should_keep_alive(conn);
  8246. /* Discard all buffered data for this request */
  8247. discard_len = conn->content_len >= 0 && conn->request_len > 0 &&
  8248. conn->request_len + conn->content_len <
  8249. (int64_t)conn->data_len
  8250. ? (int)(conn->request_len + conn->content_len)
  8251. : conn->data_len;
  8252. /*assert(discard_len >= 0);*/
  8253. if (discard_len < 0)
  8254. break;
  8255. conn->data_len -= discard_len;
  8256. if (conn->data_len > 0)
  8257. memmove(
  8258. conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  8259. /* assert(conn->data_len >= 0); */
  8260. /* assert(conn->data_len <= conn->buf_size); */
  8261. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size))
  8262. break;
  8263. } while (keep_alive);
  8264. }
  8265. }
  8266. /* Worker threads take accepted socket from the queue */
  8267. static int consume_socket(struct mg_context *ctx, struct socket *sp)
  8268. {
  8269. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  8270. if (!ctx)
  8271. return 0;
  8272. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8273. DEBUG_TRACE("%s", "going idle");
  8274. /* If the queue is empty, wait. We're idle at this point. */
  8275. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  8276. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  8277. }
  8278. /* If we're stopping, sq_head may be equal to sq_tail. */
  8279. if (ctx->sq_head > ctx->sq_tail) {
  8280. /* Copy socket from the queue and increment tail */
  8281. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  8282. ctx->sq_tail++;
  8283. if (sp)
  8284. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  8285. /* Wrap pointers if needed */
  8286. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  8287. ctx->sq_tail -= QUEUE_SIZE(ctx);
  8288. ctx->sq_head -= QUEUE_SIZE(ctx);
  8289. }
  8290. }
  8291. (void)pthread_cond_signal(&ctx->sq_empty);
  8292. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8293. return !ctx->stop_flag;
  8294. #undef QUEUE_SIZE
  8295. }
  8296. static void *worker_thread_run(void *thread_func_param)
  8297. {
  8298. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  8299. struct mg_connection *conn;
  8300. struct mg_workerTLS tls;
  8301. uint32_t addr;
  8302. mg_set_thread_name("worker");
  8303. tls.is_master = 0;
  8304. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8305. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  8306. #endif
  8307. conn =
  8308. (struct mg_connection *)mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE);
  8309. if (conn == NULL) {
  8310. mg_cry(fc(ctx), "%s", "Cannot create new connection struct, OOM");
  8311. } else {
  8312. pthread_setspecific(sTlsKey, &tls);
  8313. conn->buf_size = MAX_REQUEST_SIZE;
  8314. conn->buf = (char *)(conn + 1);
  8315. conn->ctx = ctx;
  8316. conn->request_info.user_data = ctx->user_data;
  8317. /* Allocate a mutex for this connection to allow communication both
  8318. * within the request handler and from elsewhere in the application */
  8319. (void)pthread_mutex_init(&conn->mutex, NULL);
  8320. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  8321. * signal sq_empty condvar to wake up the master waiting in
  8322. * produce_socket() */
  8323. while (consume_socket(ctx, &conn->client)) {
  8324. conn->conn_birth_time = time(NULL);
  8325. /* Fill in IP, port info early so even if SSL setup below fails,
  8326. * error handler would have the corresponding info.
  8327. * Thanks to Johannes Winkelmann for the patch.
  8328. * TODO(lsm, high): Fix IPv6 case */
  8329. conn->request_info.remote_port =
  8330. ntohs(conn->client.rsa.sin.sin_port);
  8331. sockaddr_to_string(conn->request_info.remote_addr,
  8332. sizeof(conn->request_info.remote_addr),
  8333. &conn->client.rsa);
  8334. /* TODO: #if defined(MG_LEGACY_INTERFACE) */
  8335. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  8336. memcpy(&conn->request_info.remote_ip, &addr, 4);
  8337. /* #endif */
  8338. conn->request_info.is_ssl = conn->client.is_ssl;
  8339. if (!conn->client.is_ssl
  8340. #ifndef NO_SSL
  8341. ||
  8342. sslize(conn, conn->ctx->ssl_ctx, SSL_accept)
  8343. #endif
  8344. ) {
  8345. process_new_connection(conn);
  8346. }
  8347. close_connection(conn);
  8348. }
  8349. }
  8350. /* Signal master that we're done with connection and exiting */
  8351. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8352. ctx->num_threads--;
  8353. (void)pthread_cond_signal(&ctx->thread_cond);
  8354. /* assert(ctx->num_threads >= 0); */
  8355. if (ctx->num_threads < 0)
  8356. return NULL;
  8357. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8358. pthread_setspecific(sTlsKey, NULL);
  8359. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8360. CloseHandle(tls.pthread_cond_helper_mutex);
  8361. #endif
  8362. mg_free(conn);
  8363. DEBUG_TRACE("%s", "exiting");
  8364. return NULL;
  8365. }
  8366. /* Threads have different return types on Windows and Unix. */
  8367. #ifdef _WIN32
  8368. static unsigned __stdcall worker_thread(void *thread_func_param)
  8369. {
  8370. worker_thread_run(thread_func_param);
  8371. return 0;
  8372. }
  8373. #else
  8374. static void *worker_thread(void *thread_func_param)
  8375. {
  8376. worker_thread_run(thread_func_param);
  8377. return NULL;
  8378. }
  8379. #endif /* _WIN32 */
  8380. /* Master thread adds accepted socket to a queue */
  8381. static void produce_socket(struct mg_context *ctx, const struct socket *sp)
  8382. {
  8383. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  8384. if (!ctx)
  8385. return;
  8386. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8387. /* If the queue is full, wait */
  8388. while (ctx->stop_flag == 0 &&
  8389. ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  8390. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  8391. }
  8392. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  8393. /* Copy socket to the queue and increment head */
  8394. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  8395. ctx->sq_head++;
  8396. if (sp)
  8397. DEBUG_TRACE("queued socket %d", sp->sock);
  8398. }
  8399. (void)pthread_cond_signal(&ctx->sq_full);
  8400. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8401. #undef QUEUE_SIZE
  8402. }
  8403. static void accept_new_connection(const struct socket *listener,
  8404. struct mg_context *ctx)
  8405. {
  8406. struct socket so;
  8407. char src_addr[IP_ADDR_STR_LEN];
  8408. socklen_t len = sizeof(so.rsa);
  8409. int on = 1;
  8410. int timeout;
  8411. if (!listener)
  8412. return;
  8413. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) ==
  8414. INVALID_SOCKET) {
  8415. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  8416. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  8417. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  8418. closesocket(so.sock);
  8419. so.sock = INVALID_SOCKET;
  8420. } else {
  8421. /* Put so socket structure into the queue */
  8422. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  8423. set_close_on_exec(so.sock, fc(ctx));
  8424. so.is_ssl = listener->is_ssl;
  8425. so.ssl_redir = listener->ssl_redir;
  8426. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  8427. mg_cry(fc(ctx),
  8428. "%s: getsockname() failed: %s",
  8429. __func__,
  8430. strerror(ERRNO));
  8431. }
  8432. /* Set TCP keep-alive. This is needed because if HTTP-level keep-alive
  8433. * is enabled, and client resets the connection, server won't get
  8434. * TCP FIN or RST and will keep the connection open forever. With TCP
  8435. * keep-alive, next keep-alive handshake will figure out that the
  8436. * client is down and will close the server end.
  8437. * Thanks to Igor Klopov who suggested the patch. */
  8438. if (setsockopt(so.sock,
  8439. SOL_SOCKET,
  8440. SO_KEEPALIVE,
  8441. (SOCK_OPT_TYPE)&on,
  8442. sizeof(on)) != 0) {
  8443. mg_cry(fc(ctx),
  8444. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  8445. __func__,
  8446. strerror(ERRNO));
  8447. }
  8448. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  8449. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  8450. } else {
  8451. timeout = -1;
  8452. }
  8453. /* Set socket timeout to the given value, but not more than a
  8454. * a certain limit (SOCKET_TIMEOUT_QUANTUM, default 10 seconds),
  8455. * so the server can exit after that time if requested. */
  8456. if ((timeout > 0) && (timeout < SOCKET_TIMEOUT_QUANTUM)) {
  8457. set_sock_timeout(so.sock, timeout);
  8458. } else {
  8459. set_sock_timeout(so.sock, SOCKET_TIMEOUT_QUANTUM);
  8460. }
  8461. produce_socket(ctx, &so);
  8462. }
  8463. }
  8464. static void master_thread_run(void *thread_func_param)
  8465. {
  8466. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  8467. struct mg_workerTLS tls;
  8468. struct pollfd *pfd;
  8469. unsigned int i;
  8470. unsigned int workerthreadcount;
  8471. if (!ctx)
  8472. return;
  8473. mg_set_thread_name("master");
  8474. /* Increase priority of the master thread */
  8475. #if defined(_WIN32)
  8476. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  8477. #elif defined(USE_MASTER_THREAD_PRIORITY)
  8478. int min_prio = sched_get_priority_min(SCHED_RR);
  8479. int max_prio = sched_get_priority_max(SCHED_RR);
  8480. if ((min_prio >= 0) && (max_prio >= 0) &&
  8481. ((USE_MASTER_THREAD_PRIORITY) <= max_prio) &&
  8482. ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  8483. struct sched_param sched_param = {0};
  8484. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  8485. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  8486. }
  8487. #endif
  8488. /* Initialize thread local storage */
  8489. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8490. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  8491. #endif
  8492. tls.is_master = 1;
  8493. pthread_setspecific(sTlsKey, &tls);
  8494. /* Server starts *now* */
  8495. ctx->start_time = (unsigned long)time(NULL);
  8496. /* Allocate memory for the listening sockets, and start the server */
  8497. pfd =
  8498. (struct pollfd *)mg_calloc(ctx->num_listening_sockets, sizeof(pfd[0]));
  8499. while (pfd != NULL && ctx->stop_flag == 0) {
  8500. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8501. pfd[i].fd = ctx->listening_sockets[i].sock;
  8502. pfd[i].events = POLLIN;
  8503. }
  8504. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  8505. for (i = 0; i < ctx->num_listening_sockets; i++) {
  8506. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  8507. * successful poll, and POLLIN is defined as
  8508. * (POLLRDNORM | POLLRDBAND)
  8509. * Therefore, we're checking pfd[i].revents & POLLIN, not
  8510. * pfd[i].revents == POLLIN. */
  8511. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  8512. accept_new_connection(&ctx->listening_sockets[i], ctx);
  8513. }
  8514. }
  8515. }
  8516. }
  8517. mg_free(pfd);
  8518. DEBUG_TRACE("%s", "stopping workers");
  8519. /* Stop signal received: somebody called mg_stop. Quit. */
  8520. close_all_listening_sockets(ctx);
  8521. /* Wakeup workers that are waiting for connections to handle. */
  8522. pthread_cond_broadcast(&ctx->sq_full);
  8523. /* Wait until all threads finish */
  8524. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8525. while (ctx->num_threads > 0) {
  8526. (void)pthread_cond_wait(&ctx->thread_cond, &ctx->thread_mutex);
  8527. }
  8528. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8529. /* Join all worker threads to avoid leaking threads. */
  8530. workerthreadcount = ctx->workerthreadcount;
  8531. for (i = 0; i < workerthreadcount; i++) {
  8532. mg_join_thread(ctx->workerthreadids[i]);
  8533. }
  8534. #if !defined(NO_SSL)
  8535. if (ctx->ssl_ctx != NULL) {
  8536. uninitialize_ssl(ctx);
  8537. }
  8538. #endif
  8539. DEBUG_TRACE("%s", "exiting");
  8540. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8541. CloseHandle(tls.pthread_cond_helper_mutex);
  8542. #endif
  8543. pthread_setspecific(sTlsKey, NULL);
  8544. /* Signal mg_stop() that we're done.
  8545. * WARNING: This must be the very last thing this
  8546. * thread does, as ctx becomes invalid after this line. */
  8547. ctx->stop_flag = 2;
  8548. }
  8549. /* Threads have different return types on Windows and Unix. */
  8550. #ifdef _WIN32
  8551. static unsigned __stdcall master_thread(void *thread_func_param)
  8552. {
  8553. master_thread_run(thread_func_param);
  8554. return 0;
  8555. }
  8556. #else
  8557. static void *master_thread(void *thread_func_param)
  8558. {
  8559. master_thread_run(thread_func_param);
  8560. return NULL;
  8561. }
  8562. #endif /* _WIN32 */
  8563. static void free_context(struct mg_context *ctx)
  8564. {
  8565. int i;
  8566. struct mg_request_handler_info *tmp_rh;
  8567. if (ctx == NULL)
  8568. return;
  8569. if (ctx->callbacks.exit_context) {
  8570. ctx->callbacks.exit_context(ctx);
  8571. }
  8572. /* All threads exited, no sync is needed. Destroy thread mutex and condvars
  8573. */
  8574. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  8575. (void)pthread_cond_destroy(&ctx->thread_cond);
  8576. (void)pthread_cond_destroy(&ctx->sq_empty);
  8577. (void)pthread_cond_destroy(&ctx->sq_full);
  8578. /* Destroy other context global data structures mutex */
  8579. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  8580. #if defined(USE_TIMERS)
  8581. timers_exit(ctx);
  8582. #endif
  8583. /* Deallocate config parameters */
  8584. for (i = 0; i < NUM_OPTIONS; i++) {
  8585. if (ctx->config[i] != NULL)
  8586. #if defined(_MSC_VER)
  8587. #pragma warning(suppress : 6001)
  8588. #endif
  8589. mg_free(ctx->config[i]);
  8590. }
  8591. /* Deallocate request handlers */
  8592. while (ctx->request_handlers) {
  8593. tmp_rh = ctx->request_handlers;
  8594. ctx->request_handlers = tmp_rh->next;
  8595. mg_free(tmp_rh->uri);
  8596. mg_free(tmp_rh);
  8597. }
  8598. #ifndef NO_SSL
  8599. /* Deallocate SSL context */
  8600. if (ctx->ssl_ctx != NULL) {
  8601. SSL_CTX_free(ctx->ssl_ctx);
  8602. }
  8603. if (ssl_mutexes != NULL) {
  8604. mg_free(ssl_mutexes);
  8605. ssl_mutexes = NULL;
  8606. }
  8607. #endif /* !NO_SSL */
  8608. /* Deallocate worker thread ID array */
  8609. if (ctx->workerthreadids != NULL) {
  8610. mg_free(ctx->workerthreadids);
  8611. }
  8612. /* Deallocate the tls variable */
  8613. if (mg_atomic_dec(&sTlsInit) == 0) {
  8614. pthread_key_delete(sTlsKey);
  8615. }
  8616. /* deallocate system name string */
  8617. mg_free(ctx->systemName);
  8618. /* Deallocate context itself */
  8619. mg_free(ctx);
  8620. }
  8621. void mg_stop(struct mg_context *ctx)
  8622. {
  8623. if (!ctx)
  8624. return;
  8625. ctx->stop_flag = 1;
  8626. /* Wait until mg_fini() stops */
  8627. while (ctx->stop_flag != 2) {
  8628. (void)mg_sleep(10);
  8629. }
  8630. mg_join_thread(ctx->masterthreadid);
  8631. free_context(ctx);
  8632. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8633. (void)WSACleanup();
  8634. #endif /* _WIN32 && !__SYMBIAN32__ */
  8635. }
  8636. static void get_system_name(char **sysName)
  8637. {
  8638. #if defined(_WIN32)
  8639. #if !defined(__SYMBIAN32__)
  8640. char name[128];
  8641. DWORD dwVersion = 0;
  8642. DWORD dwMajorVersion = 0;
  8643. DWORD dwMinorVersion = 0;
  8644. DWORD dwBuild = 0;
  8645. #ifdef _MSC_VER
  8646. #pragma warning(push)
  8647. // GetVersion was declared deprecated
  8648. #pragma warning(disable : 4996)
  8649. #endif
  8650. dwVersion = GetVersion();
  8651. #ifdef _MSC_VER
  8652. #pragma warning(pop)
  8653. #endif
  8654. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  8655. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  8656. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  8657. (void)dwBuild;
  8658. sprintf(name,
  8659. "Windows %u.%u",
  8660. (unsigned)dwMajorVersion,
  8661. (unsigned)dwMinorVersion);
  8662. *sysName = mg_strdup(name);
  8663. #else
  8664. *sysName = mg_strdup("Symbian");
  8665. #endif
  8666. #else
  8667. struct utsname name;
  8668. memset(&name, 0, sizeof(name));
  8669. uname(&name);
  8670. *sysName = mg_strdup(name.sysname);
  8671. #endif
  8672. }
  8673. struct mg_context *mg_start(const struct mg_callbacks *callbacks,
  8674. void *user_data,
  8675. const char **options)
  8676. {
  8677. struct mg_context *ctx;
  8678. const char *name, *value, *default_value;
  8679. int idx, ok, workerthreadcount;
  8680. unsigned int i;
  8681. void (*exit_callback)(const struct mg_context *ctx) = 0;
  8682. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  8683. WSADATA data;
  8684. WSAStartup(MAKEWORD(2, 2), &data);
  8685. #if defined(_MSC_VER)
  8686. #pragma warning(suppress : 28125)
  8687. #endif
  8688. if (!sTlsInit)
  8689. InitializeCriticalSection(&global_log_file_lock);
  8690. #endif /* _WIN32 && !__SYMBIAN32__ */
  8691. /* Allocate context and initialize reasonable general case defaults. */
  8692. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  8693. return NULL;
  8694. }
  8695. if (mg_atomic_inc(&sTlsInit) == 1) {
  8696. if (0 != pthread_key_create(&sTlsKey, NULL)) {
  8697. /* Fatal error - abort start. However, this situation should never
  8698. * occur in practice. */
  8699. mg_atomic_dec(&sTlsInit);
  8700. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  8701. mg_free(ctx);
  8702. return NULL;
  8703. }
  8704. } else {
  8705. /* TODO (low): istead of sleeping, check if sTlsKey is already
  8706. * initialized. */
  8707. mg_sleep(1);
  8708. }
  8709. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, NULL);
  8710. ok &= 0 == pthread_cond_init(&ctx->thread_cond, NULL);
  8711. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  8712. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  8713. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, NULL);
  8714. if (!ok) {
  8715. /* Fatal error - abort start. However, this situation should never
  8716. * occur in practice. */
  8717. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  8718. mg_free(ctx);
  8719. return NULL;
  8720. }
  8721. if (callbacks) {
  8722. ctx->callbacks = *callbacks;
  8723. exit_callback = callbacks->exit_context;
  8724. ctx->callbacks.exit_context = 0;
  8725. }
  8726. ctx->user_data = user_data;
  8727. ctx->request_handlers = NULL;
  8728. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  8729. ctx->shared_lua_websockets = 0;
  8730. #endif
  8731. while (options && (name = *options++) != NULL) {
  8732. if ((idx = get_option_index(name)) == -1) {
  8733. mg_cry(fc(ctx), "Invalid option: %s", name);
  8734. free_context(ctx);
  8735. return NULL;
  8736. } else if ((value = *options++) == NULL) {
  8737. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  8738. free_context(ctx);
  8739. return NULL;
  8740. }
  8741. if (ctx->config[idx] != NULL) {
  8742. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  8743. mg_free(ctx->config[idx]);
  8744. }
  8745. ctx->config[idx] = mg_strdup(value);
  8746. DEBUG_TRACE("[%s] -> [%s]", name, value);
  8747. }
  8748. /* Set default value if needed */
  8749. for (i = 0; config_options[i].name != NULL; i++) {
  8750. default_value = config_options[i].default_value;
  8751. if (ctx->config[i] == NULL && default_value != NULL) {
  8752. ctx->config[i] = mg_strdup(default_value);
  8753. }
  8754. }
  8755. #if defined(NO_FILES)
  8756. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  8757. mg_cry(fc(ctx), "%s", "Document root must not be set");
  8758. free_context(ctx);
  8759. return NULL;
  8760. }
  8761. #endif
  8762. get_system_name(&ctx->systemName);
  8763. /* NOTE(lsm): order is important here. SSL certificates must
  8764. * be initialized before listening ports. UID must be set last. */
  8765. if (!set_gpass_option(ctx) ||
  8766. #if !defined(NO_SSL)
  8767. !set_ssl_option(ctx) ||
  8768. #endif
  8769. !set_ports_option(ctx) ||
  8770. #if !defined(_WIN32)
  8771. !set_uid_option(ctx) ||
  8772. #endif
  8773. !set_acl_option(ctx)) {
  8774. free_context(ctx);
  8775. return NULL;
  8776. }
  8777. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  8778. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  8779. * won't kill the whole process. */
  8780. (void)signal(SIGPIPE, SIG_IGN);
  8781. #endif /* !_WIN32 && !__SYMBIAN32__ */
  8782. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  8783. if (workerthreadcount > MAX_WORKER_THREADS) {
  8784. mg_cry(fc(ctx), "Too many worker threads");
  8785. free_context(ctx);
  8786. return NULL;
  8787. }
  8788. if (workerthreadcount > 0) {
  8789. ctx->workerthreadcount = ((unsigned int)(workerthreadcount));
  8790. ctx->workerthreadids =
  8791. (pthread_t *)mg_calloc(ctx->workerthreadcount, sizeof(pthread_t));
  8792. if (ctx->workerthreadids == NULL) {
  8793. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  8794. free_context(ctx);
  8795. return NULL;
  8796. }
  8797. }
  8798. #if defined(USE_TIMERS)
  8799. if (timers_init(ctx) != 0) {
  8800. mg_cry(fc(ctx), "Error creating timers");
  8801. free_context(ctx);
  8802. return NULL;
  8803. }
  8804. #endif
  8805. /* Context has been created - init user libraries */
  8806. if (ctx->callbacks.init_context) {
  8807. ctx->callbacks.init_context(ctx);
  8808. }
  8809. ctx->callbacks.exit_context = exit_callback;
  8810. ctx->context_type = 1; /* server context */
  8811. /* Start master (listening) thread */
  8812. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  8813. /* Start worker threads */
  8814. for (i = 0; i < ctx->workerthreadcount; i++) {
  8815. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8816. ctx->num_threads++;
  8817. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8818. if (mg_start_thread_with_id(
  8819. worker_thread, ctx, &ctx->workerthreadids[i]) != 0) {
  8820. (void)pthread_mutex_lock(&ctx->thread_mutex);
  8821. ctx->num_threads--;
  8822. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  8823. if (i > 0) {
  8824. mg_cry(fc(ctx),
  8825. "Cannot start worker thread %i: error %ld",
  8826. i + 1,
  8827. (long)ERRNO);
  8828. } else {
  8829. mg_cry(
  8830. fc(ctx), "Cannot create threads: error %ld", (long)ERRNO);
  8831. free_context(ctx);
  8832. return NULL;
  8833. }
  8834. break;
  8835. }
  8836. }
  8837. return ctx;
  8838. }