civetweb.c 385 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754
  1. /* Copyright (c) 2013-2016 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. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  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(USE_LUA)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* DTL -- including winsock2.h works better if lean and mean */
  92. #ifndef WIN32_LEAN_AND_MEAN
  93. #define WIN32_LEAN_AND_MEAN
  94. #endif
  95. #if defined(__SYMBIAN32__)
  96. #define NO_SSL /* SSL is not supported */
  97. #define NO_CGI /* CGI is not supported */
  98. #define PATH_MAX FILENAME_MAX
  99. #endif /* __SYMBIAN32__ */
  100. /* Include the header file here, so the CivetWeb interface is defined for the
  101. * entire implementation, including the following forward definitions. */
  102. #include "civetweb.h"
  103. #ifndef IGNORE_UNUSED_RESULT
  104. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  105. #endif
  106. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  107. #include <sys/types.h>
  108. #include <sys/stat.h>
  109. #include <errno.h>
  110. #include <signal.h>
  111. #include <fcntl.h>
  112. #endif /* !_WIN32_WCE */
  113. #ifdef __clang__
  114. /* When using -Weverything, clang does not accept it's own headers
  115. * in a release build configuration. Disable what is too much in
  116. * -Weverything. */
  117. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  118. #endif
  119. #ifdef __MACH__ /* Apple OSX section */
  120. #ifdef __clang__
  121. /* Avoid warnings for Xopen 7.00 and higher */
  122. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  123. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  124. #endif
  125. #define CLOCK_MONOTONIC (1)
  126. #define CLOCK_REALTIME (2)
  127. #include <sys/errno.h>
  128. #include <sys/time.h>
  129. #include <mach/clock.h>
  130. #include <mach/mach.h>
  131. #include <mach/mach_time.h>
  132. #include <assert.h>
  133. /* clock_gettime is not implemented on OSX prior to 10.12 */
  134. static int
  135. _civet_clock_gettime(int clk_id, struct timespec *t)
  136. {
  137. memset(t, 0, sizeof(*t));
  138. if (clk_id == CLOCK_REALTIME) {
  139. struct timeval now;
  140. int rv = gettimeofday(&now, NULL);
  141. if (rv) {
  142. return rv;
  143. }
  144. t->tv_sec = now.tv_sec;
  145. t->tv_nsec = now.tv_usec * 1000;
  146. return 0;
  147. } else if (clk_id == CLOCK_MONOTONIC) {
  148. static uint64_t clock_start_time = 0;
  149. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  150. uint64_t now = mach_absolute_time();
  151. if (clock_start_time == 0) {
  152. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  153. #if defined(DEBUG)
  154. assert(mach_status == KERN_SUCCESS);
  155. #else
  156. /* appease "unused variable" warning for release builds */
  157. (void)mach_status;
  158. #endif
  159. clock_start_time = now;
  160. }
  161. now = (uint64_t)((double)(now - clock_start_time)
  162. * (double)timebase_ifo.numer
  163. / (double)timebase_ifo.denom);
  164. t->tv_sec = now / 1000000000;
  165. t->tv_nsec = now % 1000000000;
  166. return 0;
  167. }
  168. return -1; /* EINVAL - Clock ID is unknown */
  169. }
  170. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  171. #ifdef __CLOCK_AVAILABILITY
  172. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  173. * declared but it may be NULL at runtime. So we need to check before using
  174. * it. */
  175. static int
  176. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  177. {
  178. if (clock_gettime) {
  179. return clock_gettime(clk_id, t);
  180. }
  181. return _civet_clock_gettime(clk_id, t);
  182. }
  183. #define clock_gettime _civet_safe_clock_gettime
  184. #else
  185. #define clock_gettime _civet_clock_gettime
  186. #endif
  187. #endif
  188. #include <time.h>
  189. #include <stdlib.h>
  190. #include <stdarg.h>
  191. #include <assert.h>
  192. #include <string.h>
  193. #include <ctype.h>
  194. #include <limits.h>
  195. #include <stddef.h>
  196. #include <stdio.h>
  197. #include <stdint.h>
  198. #ifndef INT64_MAX
  199. #define INT64_MAX (9223372036854775807)
  200. #endif
  201. #ifndef MAX_WORKER_THREADS
  202. #define MAX_WORKER_THREADS (1024 * 64)
  203. #endif
  204. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  205. #define SOCKET_TIMEOUT_QUANTUM (2000)
  206. #endif
  207. #define SHUTDOWN_RD (0)
  208. #define SHUTDOWN_WR (1)
  209. #define SHUTDOWN_BOTH (2)
  210. mg_static_assert(MAX_WORKER_THREADS >= 1,
  211. "worker threads must be a positive number");
  212. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  213. "size_t data type size check");
  214. #if defined(_WIN32) \
  215. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  216. #include <windows.h>
  217. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  218. #include <ws2tcpip.h>
  219. typedef const char *SOCK_OPT_TYPE;
  220. #if !defined(PATH_MAX)
  221. #define PATH_MAX (MAX_PATH)
  222. #endif
  223. #if !defined(PATH_MAX)
  224. #define PATH_MAX (4096)
  225. #endif
  226. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  227. #ifndef _IN_PORT_T
  228. #ifndef in_port_t
  229. #define in_port_t u_short
  230. #endif
  231. #endif
  232. #ifndef _WIN32_WCE
  233. #include <process.h>
  234. #include <direct.h>
  235. #include <io.h>
  236. #else /* _WIN32_WCE */
  237. #define NO_CGI /* WinCE has no pipes */
  238. #define NO_POPEN /* WinCE has no popen */
  239. typedef long off_t;
  240. #define errno ((int)(GetLastError()))
  241. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  242. #endif /* _WIN32_WCE */
  243. #define MAKEUQUAD(lo, hi) \
  244. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  245. #define RATE_DIFF (10000000) /* 100 nsecs */
  246. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  247. #define SYS2UNIX_TIME(lo, hi) \
  248. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  249. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  250. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  251. * Also use _strtoui64 on modern M$ compilers */
  252. #if defined(_MSC_VER)
  253. #if (_MSC_VER < 1300)
  254. #define STRX(x) #x
  255. #define STR(x) STRX(x)
  256. #define __func__ __FILE__ ":" STR(__LINE__)
  257. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  258. #define strtoll(x, y, z) (_atoi64(x))
  259. #else
  260. #define __func__ __FUNCTION__
  261. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  262. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  263. #endif
  264. #endif /* _MSC_VER */
  265. #define ERRNO ((int)(GetLastError()))
  266. #define NO_SOCKLEN_T
  267. #if defined(_WIN64) || defined(__MINGW64__)
  268. #define SSL_LIB "ssleay64.dll"
  269. #define CRYPTO_LIB "libeay64.dll"
  270. #else
  271. #define SSL_LIB "ssleay32.dll"
  272. #define CRYPTO_LIB "libeay32.dll"
  273. #endif
  274. #define O_NONBLOCK (0)
  275. #ifndef W_OK
  276. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  277. #endif
  278. #if !defined(EWOULDBLOCK)
  279. #define EWOULDBLOCK WSAEWOULDBLOCK
  280. #endif /* !EWOULDBLOCK */
  281. #define _POSIX_
  282. #define INT64_FMT "I64d"
  283. #define UINT64_FMT "I64u"
  284. #define WINCDECL __cdecl
  285. #define vsnprintf_impl _vsnprintf
  286. #define access _access
  287. #define mg_sleep(x) (Sleep(x))
  288. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  289. #ifndef popen
  290. #define popen(x, y) (_popen(x, y))
  291. #endif
  292. #ifndef pclose
  293. #define pclose(x) (_pclose(x))
  294. #endif
  295. #define close(x) (_close(x))
  296. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  297. #define RTLD_LAZY (0)
  298. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  299. #define fdopen(x, y) (_fdopen((x), (y)))
  300. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  301. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  302. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  303. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  304. #define sleep(x) (Sleep((x)*1000))
  305. #define rmdir(x) (_rmdir(x))
  306. #define timegm(x) (_mkgmtime(x))
  307. #if !defined(fileno)
  308. #define fileno(x) (_fileno(x))
  309. #endif /* !fileno MINGW #defines fileno */
  310. typedef HANDLE pthread_mutex_t;
  311. typedef DWORD pthread_key_t;
  312. typedef HANDLE pthread_t;
  313. typedef struct {
  314. CRITICAL_SECTION threadIdSec;
  315. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  316. } pthread_cond_t;
  317. #ifndef __clockid_t_defined
  318. typedef DWORD clockid_t;
  319. #endif
  320. #ifndef CLOCK_MONOTONIC
  321. #define CLOCK_MONOTONIC (1)
  322. #endif
  323. #ifndef CLOCK_REALTIME
  324. #define CLOCK_REALTIME (2)
  325. #endif
  326. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  327. #define _TIMESPEC_DEFINED
  328. #endif
  329. #ifndef _TIMESPEC_DEFINED
  330. struct timespec {
  331. time_t tv_sec; /* seconds */
  332. long tv_nsec; /* nanoseconds */
  333. };
  334. #endif
  335. #if !defined(WIN_PTHREADS_TIME_H)
  336. #define MUST_IMPLEMENT_CLOCK_GETTIME
  337. #endif
  338. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  339. #define clock_gettime mg_clock_gettime
  340. static int
  341. clock_gettime(clockid_t clk_id, struct timespec *tp)
  342. {
  343. FILETIME ft;
  344. ULARGE_INTEGER li;
  345. BOOL ok = FALSE;
  346. double d;
  347. static double perfcnt_per_sec = 0.0;
  348. if (tp) {
  349. memset(tp, 0, sizeof(*tp));
  350. if (clk_id == CLOCK_REALTIME) {
  351. GetSystemTimeAsFileTime(&ft);
  352. li.LowPart = ft.dwLowDateTime;
  353. li.HighPart = ft.dwHighDateTime;
  354. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  355. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  356. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  357. ok = TRUE;
  358. } else if (clk_id == CLOCK_MONOTONIC) {
  359. if (perfcnt_per_sec == 0.0) {
  360. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  361. perfcnt_per_sec = 1.0 / li.QuadPart;
  362. }
  363. if (perfcnt_per_sec != 0.0) {
  364. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  365. d = li.QuadPart * perfcnt_per_sec;
  366. tp->tv_sec = (time_t)d;
  367. d -= tp->tv_sec;
  368. tp->tv_nsec = (long)(d * 1.0E9);
  369. ok = TRUE;
  370. }
  371. }
  372. }
  373. return ok ? 0 : -1;
  374. }
  375. #endif
  376. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  377. static int pthread_mutex_lock(pthread_mutex_t *);
  378. static int pthread_mutex_unlock(pthread_mutex_t *);
  379. static void path_to_unicode(const struct mg_connection *conn,
  380. const char *path,
  381. wchar_t *wbuf,
  382. size_t wbuf_len);
  383. /* All file operations need to be rewritten to solve #246. */
  384. #include "file_ops.inl"
  385. struct mg_file;
  386. static const char *
  387. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  388. /* POSIX dirent interface */
  389. struct dirent {
  390. char d_name[PATH_MAX];
  391. };
  392. typedef struct DIR {
  393. HANDLE handle;
  394. WIN32_FIND_DATAW info;
  395. struct dirent result;
  396. } DIR;
  397. #if defined(_WIN32) && !defined(POLLIN)
  398. #ifndef HAVE_POLL
  399. struct pollfd {
  400. SOCKET fd;
  401. short events;
  402. short revents;
  403. };
  404. #define POLLIN (0x0300)
  405. #endif
  406. #endif
  407. /* Mark required libraries */
  408. #if defined(_MSC_VER)
  409. #pragma comment(lib, "Ws2_32.lib")
  410. #endif
  411. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  412. WINDOWS / UNIX include block */
  413. #include <sys/wait.h>
  414. #include <sys/socket.h>
  415. #include <sys/poll.h>
  416. #include <netinet/in.h>
  417. #include <arpa/inet.h>
  418. #include <sys/time.h>
  419. #include <sys/utsname.h>
  420. #include <stdint.h>
  421. #include <inttypes.h>
  422. #include <netdb.h>
  423. #include <netinet/tcp.h>
  424. typedef const void *SOCK_OPT_TYPE;
  425. #if defined(ANDROID)
  426. typedef unsigned short int in_port_t;
  427. #endif
  428. #include <pwd.h>
  429. #include <unistd.h>
  430. #include <grp.h>
  431. #include <dirent.h>
  432. #define vsnprintf_impl vsnprintf
  433. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  434. #include <dlfcn.h>
  435. #endif
  436. #include <pthread.h>
  437. #if defined(__MACH__)
  438. #define SSL_LIB "libssl.dylib"
  439. #define CRYPTO_LIB "libcrypto.dylib"
  440. #else
  441. #if !defined(SSL_LIB)
  442. #define SSL_LIB "libssl.so"
  443. #endif
  444. #if !defined(CRYPTO_LIB)
  445. #define CRYPTO_LIB "libcrypto.so"
  446. #endif
  447. #endif
  448. #ifndef O_BINARY
  449. #define O_BINARY (0)
  450. #endif /* O_BINARY */
  451. #define closesocket(a) (close(a))
  452. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  453. #define mg_remove(conn, x) (remove(x))
  454. #define mg_sleep(x) (usleep((x)*1000))
  455. #define mg_opendir(conn, x) (opendir(x))
  456. #define mg_closedir(x) (closedir(x))
  457. #define mg_readdir(x) (readdir(x))
  458. #define ERRNO (errno)
  459. #define INVALID_SOCKET (-1)
  460. #define INT64_FMT PRId64
  461. #define UINT64_FMT PRIu64
  462. typedef int SOCKET;
  463. #define WINCDECL
  464. #if defined(__hpux)
  465. /* HPUX 11 does not have monotonic, fall back to realtime */
  466. #ifndef CLOCK_MONOTONIC
  467. #define CLOCK_MONOTONIC CLOCK_REALTIME
  468. #endif
  469. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  470. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  471. * the prototypes use int* rather than socklen_t* which matches the
  472. * actual library expectation. When called with the wrong size arg
  473. * accept() returns a zero client inet addr and check_acl() always
  474. * fails. Since socklen_t is widely used below, just force replace
  475. * their typedef with int. - DTL
  476. */
  477. #define socklen_t int
  478. #endif /* hpux */
  479. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  480. WINDOWS / UNIX include block */
  481. /* va_copy should always be a macro, C99 and C++11 - DTL */
  482. #ifndef va_copy
  483. #define va_copy(x, y) ((x) = (y))
  484. #endif
  485. #ifdef _WIN32
  486. /* Create substitutes for POSIX functions in Win32. */
  487. #if defined(__MINGW32__)
  488. /* Show no warning in case system functions are not used. */
  489. #pragma GCC diagnostic push
  490. #pragma GCC diagnostic ignored "-Wunused-function"
  491. #endif
  492. static CRITICAL_SECTION global_log_file_lock;
  493. static DWORD
  494. pthread_self(void)
  495. {
  496. return GetCurrentThreadId();
  497. }
  498. static int
  499. pthread_key_create(
  500. pthread_key_t *key,
  501. void (*_ignored)(void *) /* destructor not supported for Windows */
  502. )
  503. {
  504. (void)_ignored;
  505. if ((key != 0)) {
  506. *key = TlsAlloc();
  507. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  508. }
  509. return -2;
  510. }
  511. static int
  512. pthread_key_delete(pthread_key_t key)
  513. {
  514. return TlsFree(key) ? 0 : 1;
  515. }
  516. static int
  517. pthread_setspecific(pthread_key_t key, void *value)
  518. {
  519. return TlsSetValue(key, value) ? 0 : 1;
  520. }
  521. static void *
  522. pthread_getspecific(pthread_key_t key)
  523. {
  524. return TlsGetValue(key);
  525. }
  526. #if defined(__MINGW32__)
  527. /* Enable unused function warning again */
  528. #pragma GCC diagnostic pop
  529. #endif
  530. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  531. #else
  532. static pthread_mutexattr_t pthread_mutex_attr;
  533. #endif /* _WIN32 */
  534. #define PASSWORDS_FILE_NAME ".htpasswd"
  535. #define CGI_ENVIRONMENT_SIZE (4096)
  536. #define MAX_CGI_ENVIR_VARS (256)
  537. #define MG_BUF_LEN (8192)
  538. #ifndef MAX_REQUEST_SIZE
  539. #define MAX_REQUEST_SIZE (16384)
  540. #endif
  541. mg_static_assert(MAX_REQUEST_SIZE >= 256,
  542. "request size length must be a positive number");
  543. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  544. #if defined(_WIN32_WCE)
  545. /* Create substitutes for POSIX functions in Win32. */
  546. #if defined(__MINGW32__)
  547. /* Show no warning in case system functions are not used. */
  548. #pragma GCC diagnostic push
  549. #pragma GCC diagnostic ignored "-Wunused-function"
  550. #endif
  551. static time_t
  552. time(time_t *ptime)
  553. {
  554. time_t t;
  555. SYSTEMTIME st;
  556. FILETIME ft;
  557. GetSystemTime(&st);
  558. SystemTimeToFileTime(&st, &ft);
  559. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  560. if (ptime != NULL) {
  561. *ptime = t;
  562. }
  563. return t;
  564. }
  565. static struct tm *
  566. localtime_s(const time_t *ptime, struct tm *ptm)
  567. {
  568. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  569. FILETIME ft, lft;
  570. SYSTEMTIME st;
  571. TIME_ZONE_INFORMATION tzinfo;
  572. if (ptm == NULL) {
  573. return NULL;
  574. }
  575. *(int64_t *)&ft = t;
  576. FileTimeToLocalFileTime(&ft, &lft);
  577. FileTimeToSystemTime(&lft, &st);
  578. ptm->tm_year = st.wYear - 1900;
  579. ptm->tm_mon = st.wMonth - 1;
  580. ptm->tm_wday = st.wDayOfWeek;
  581. ptm->tm_mday = st.wDay;
  582. ptm->tm_hour = st.wHour;
  583. ptm->tm_min = st.wMinute;
  584. ptm->tm_sec = st.wSecond;
  585. ptm->tm_yday = 0; /* hope nobody uses this */
  586. ptm->tm_isdst =
  587. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  588. return ptm;
  589. }
  590. static struct tm *
  591. gmtime_s(const time_t *ptime, struct tm *ptm)
  592. {
  593. /* FIXME(lsm): fix this. */
  594. return localtime_s(ptime, ptm);
  595. }
  596. static int mg_atomic_inc(volatile int *addr);
  597. static struct tm tm_array[MAX_WORKER_THREADS];
  598. static int tm_index = 0;
  599. static struct tm *
  600. localtime(const time_t *ptime)
  601. {
  602. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  603. return localtime_s(ptime, tm_array + i);
  604. }
  605. static struct tm *
  606. gmtime(const time_t *ptime)
  607. {
  608. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  609. return gmtime_s(ptime, tm_array + i);
  610. }
  611. static size_t
  612. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  613. {
  614. /* TODO */ //(void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  615. // for WinCE");
  616. return 0;
  617. }
  618. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  619. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  620. #define remove(f) mg_remove(NULL, f)
  621. static int
  622. rename(const char *a, const char *b)
  623. {
  624. wchar_t wa[PATH_MAX];
  625. wchar_t wb[PATH_MAX];
  626. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  627. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  628. return MoveFileW(wa, wb) ? 0 : -1;
  629. }
  630. struct stat {
  631. int64_t st_size;
  632. time_t st_mtime;
  633. };
  634. static int
  635. stat(const char *name, struct stat *st)
  636. {
  637. wchar_t wbuf[PATH_MAX];
  638. WIN32_FILE_ATTRIBUTE_DATA attr;
  639. time_t creation_time, write_time;
  640. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  641. memset(&attr, 0, sizeof(attr));
  642. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  643. st->st_size =
  644. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  645. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  646. attr.ftLastWriteTime.dwHighDateTime);
  647. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  648. attr.ftCreationTime.dwHighDateTime);
  649. if (creation_time > write_time) {
  650. st->st_mtime = creation_time;
  651. } else {
  652. st->st_mtime = write_time;
  653. }
  654. return 0;
  655. }
  656. #define access(x, a) 1 /* not required anyway */
  657. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  658. #define EEXIST 1 /* TODO: See Windows error codes */
  659. #define EACCES 2 /* TODO: See Windows error codes */
  660. #define ENOENT 3 /* TODO: See Windows Error codes */
  661. #if defined(__MINGW32__)
  662. /* Enable unused function warning again */
  663. #pragma GCC diagnostic pop
  664. #endif
  665. #endif /* defined(_WIN32_WCE) */
  666. static int
  667. mg_atomic_inc(volatile int *addr)
  668. {
  669. int ret;
  670. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  671. /* Depending on the SDK, this function uses either
  672. * (volatile unsigned int *) or (volatile LONG *),
  673. * so whatever you use, the other SDK is likely to raise a warning. */
  674. ret = InterlockedIncrement((volatile long *)addr);
  675. #elif defined(__GNUC__) \
  676. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  677. ret = __sync_add_and_fetch(addr, 1);
  678. #else
  679. ret = (++(*addr));
  680. #endif
  681. return ret;
  682. }
  683. static int
  684. mg_atomic_dec(volatile int *addr)
  685. {
  686. int ret;
  687. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  688. /* Depending on the SDK, this function uses either
  689. * (volatile unsigned int *) or (volatile LONG *),
  690. * so whatever you use, the other SDK is likely to raise a warning. */
  691. ret = InterlockedDecrement((volatile long *)addr);
  692. #elif defined(__GNUC__) \
  693. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0)))
  694. ret = __sync_sub_and_fetch(addr, 1);
  695. #else
  696. ret = (--(*addr));
  697. #endif
  698. return ret;
  699. }
  700. #if defined(MEMORY_DEBUGGING)
  701. static unsigned long mg_memory_debug_blockCount = 0;
  702. static unsigned long mg_memory_debug_totalMemUsed = 0;
  703. static void *
  704. mg_malloc_ex(size_t size, const char *file, unsigned line)
  705. {
  706. void *data = malloc(size + sizeof(size_t));
  707. void *memory = 0;
  708. char mallocStr[256];
  709. if (data) {
  710. *(size_t *)data = size;
  711. mg_memory_debug_totalMemUsed += size;
  712. mg_memory_debug_blockCount++;
  713. memory = (void *)(((char *)data) + sizeof(size_t));
  714. }
  715. sprintf(mallocStr,
  716. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  717. memory,
  718. (unsigned long)size,
  719. mg_memory_debug_totalMemUsed,
  720. mg_memory_debug_blockCount,
  721. file,
  722. line);
  723. #if defined(_WIN32)
  724. OutputDebugStringA(mallocStr);
  725. #else
  726. DEBUG_TRACE("%s", mallocStr);
  727. #endif
  728. return memory;
  729. }
  730. static void *
  731. mg_calloc_ex(size_t count, size_t size, const char *file, unsigned line)
  732. {
  733. void *data = mg_malloc_ex(size * count, file, line);
  734. if (data) {
  735. memset(data, 0, size * count);
  736. }
  737. return data;
  738. }
  739. static void
  740. mg_free_ex(void *memory, const char *file, unsigned line)
  741. {
  742. char mallocStr[256];
  743. void *data = (void *)(((char *)memory) - sizeof(size_t));
  744. size_t size;
  745. if (memory) {
  746. size = *(size_t *)data;
  747. mg_memory_debug_totalMemUsed -= size;
  748. mg_memory_debug_blockCount--;
  749. sprintf(mallocStr,
  750. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  751. memory,
  752. (unsigned long)size,
  753. mg_memory_debug_totalMemUsed,
  754. mg_memory_debug_blockCount,
  755. file,
  756. line);
  757. #if defined(_WIN32)
  758. OutputDebugStringA(mallocStr);
  759. #else
  760. DEBUG_TRACE("%s", mallocStr);
  761. #endif
  762. free(data);
  763. }
  764. }
  765. static void *
  766. mg_realloc_ex(void *memory, size_t newsize, const char *file, unsigned line)
  767. {
  768. char mallocStr[256];
  769. void *data;
  770. void *_realloc;
  771. size_t oldsize;
  772. if (newsize) {
  773. if (memory) {
  774. data = (void *)(((char *)memory) - sizeof(size_t));
  775. oldsize = *(size_t *)data;
  776. _realloc = realloc(data, newsize + sizeof(size_t));
  777. if (_realloc) {
  778. data = _realloc;
  779. mg_memory_debug_totalMemUsed -= oldsize;
  780. sprintf(mallocStr,
  781. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  782. memory,
  783. (unsigned long)oldsize,
  784. mg_memory_debug_totalMemUsed,
  785. mg_memory_debug_blockCount,
  786. file,
  787. line);
  788. #if defined(_WIN32)
  789. OutputDebugStringA(mallocStr);
  790. #else
  791. DEBUG_TRACE("%s", mallocStr);
  792. #endif
  793. mg_memory_debug_totalMemUsed += newsize;
  794. sprintf(mallocStr,
  795. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  796. memory,
  797. (unsigned long)newsize,
  798. mg_memory_debug_totalMemUsed,
  799. mg_memory_debug_blockCount,
  800. file,
  801. line);
  802. #if defined(_WIN32)
  803. OutputDebugStringA(mallocStr);
  804. #else
  805. DEBUG_TRACE("%s", mallocStr);
  806. #endif
  807. *(size_t *)data = newsize;
  808. data = (void *)(((char *)data) + sizeof(size_t));
  809. } else {
  810. #if defined(_WIN32)
  811. OutputDebugStringA("MEM: realloc failed\n");
  812. #else
  813. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  814. #endif
  815. return _realloc;
  816. }
  817. } else {
  818. data = mg_malloc_ex(newsize, file, line);
  819. }
  820. } else {
  821. data = 0;
  822. mg_free_ex(memory, file, line);
  823. }
  824. return data;
  825. }
  826. #define mg_malloc(a) mg_malloc_ex(a, __FILE__, __LINE__)
  827. #define mg_calloc(a, b) mg_calloc_ex(a, b, __FILE__, __LINE__)
  828. #define mg_realloc(a, b) mg_realloc_ex(a, b, __FILE__, __LINE__)
  829. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  830. #else
  831. static __inline void *
  832. mg_malloc(size_t a)
  833. {
  834. return malloc(a);
  835. }
  836. static __inline void *
  837. mg_calloc(size_t a, size_t b)
  838. {
  839. return calloc(a, b);
  840. }
  841. static __inline void *
  842. mg_realloc(void *a, size_t b)
  843. {
  844. return realloc(a, b);
  845. }
  846. static __inline void
  847. mg_free(void *a)
  848. {
  849. free(a);
  850. }
  851. #endif
  852. static void mg_vsnprintf(const struct mg_connection *conn,
  853. int *truncated,
  854. char *buf,
  855. size_t buflen,
  856. const char *fmt,
  857. va_list ap);
  858. static void mg_snprintf(const struct mg_connection *conn,
  859. int *truncated,
  860. char *buf,
  861. size_t buflen,
  862. PRINTF_FORMAT_STRING(const char *fmt),
  863. ...) PRINTF_ARGS(5, 6);
  864. /* This following lines are just meant as a reminder to use the mg-functions
  865. * for memory management */
  866. #ifdef malloc
  867. #undef malloc
  868. #endif
  869. #ifdef calloc
  870. #undef calloc
  871. #endif
  872. #ifdef realloc
  873. #undef realloc
  874. #endif
  875. #ifdef free
  876. #undef free
  877. #endif
  878. #ifdef snprintf
  879. #undef snprintf
  880. #endif
  881. #ifdef vsnprintf
  882. #undef vsnprintf
  883. #endif
  884. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  885. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  886. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  887. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  888. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  889. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  890. * but this define only works well for Windows. */
  891. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  892. #endif
  893. static pthread_key_t sTlsKey; /* Thread local storage index */
  894. static int sTlsInit = 0;
  895. static int thread_idx_max = 0;
  896. struct mg_workerTLS {
  897. int is_master;
  898. unsigned long thread_idx;
  899. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  900. HANDLE pthread_cond_helper_mutex;
  901. struct mg_workerTLS *next_waiting_thread;
  902. #endif
  903. };
  904. #if defined(__GNUC__) || defined(__MINGW32__)
  905. /* Show no warning in case system functions are not used. */
  906. #pragma GCC diagnostic push
  907. #pragma GCC diagnostic ignored "-Wunused-function"
  908. #endif
  909. #if defined(__clang__)
  910. /* Show no warning in case system functions are not used. */
  911. #pragma clang diagnostic push
  912. #pragma clang diagnostic ignored "-Wunused-function"
  913. #endif
  914. /* Get a unique thread ID as unsigned long, independent from the data type
  915. * of thread IDs defined by the operating system API.
  916. * If two calls to mg_current_thread_id return the same value, they calls
  917. * are done from the same thread. If they return different values, they are
  918. * done from different threads. (Provided this function is used in the same
  919. * process context and threads are not repeatedly created and deleted, but
  920. * CivetWeb does not do that).
  921. * This function must match the signature required for SSL id callbacks:
  922. * CRYPTO_set_id_callback
  923. */
  924. static unsigned long
  925. mg_current_thread_id(void)
  926. {
  927. #ifdef _WIN32
  928. return GetCurrentThreadId();
  929. #else
  930. #ifdef __clang__
  931. #pragma clang diagnostic push
  932. #pragma clang diagnostic ignored "-Wunreachable-code"
  933. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  934. * or not, so one of the two conditions will be unreachable by construction.
  935. * Unfortunately the C standard does not define a way to check this at
  936. * compile time, since the #if preprocessor conditions can not use the sizeof
  937. * operator as an argument. */
  938. #endif
  939. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  940. /* This is the problematic case for CRYPTO_set_id_callback:
  941. * The OS pthread_t can not be cast to unsigned long. */
  942. struct mg_workerTLS *tls =
  943. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  944. if (tls == NULL) {
  945. /* SSL called from an unknown thread: Create some thread index.
  946. */
  947. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  948. tls->is_master = -2; /* -2 means "3rd party thread" */
  949. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  950. pthread_setspecific(sTlsKey, tls);
  951. }
  952. return tls->thread_idx;
  953. } else {
  954. /* pthread_t may be any data type, so a simple cast to unsigned long
  955. * can rise a warning/error, depending on the platform.
  956. * Here memcpy is used as an anything-to-anything cast. */
  957. unsigned long ret = 0;
  958. pthread_t t = pthread_self();
  959. memcpy(&ret, &t, sizeof(pthread_t));
  960. return ret;
  961. }
  962. #ifdef __clang__
  963. #pragma clang diagnostic pop
  964. #endif
  965. #endif
  966. }
  967. #if defined(__GNUC__)
  968. /* Show no warning in case system functions are not used. */
  969. #pragma GCC diagnostic pop
  970. #endif
  971. #if defined(__clang__)
  972. /* Show no warning in case system functions are not used. */
  973. #pragma clang diagnostic pop
  974. #endif
  975. #if !defined(DEBUG_TRACE)
  976. #if defined(DEBUG)
  977. static void DEBUG_TRACE_FUNC(const char *func,
  978. unsigned line,
  979. PRINTF_FORMAT_STRING(const char *fmt),
  980. ...) PRINTF_ARGS(3, 4);
  981. static void
  982. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  983. {
  984. va_list args;
  985. struct timespec tsnow;
  986. uint64_t nsnow;
  987. static uint64_t nslast;
  988. /* Get some operating system independent thread id */
  989. unsigned long thread_id = mg_current_thread_id();
  990. clock_gettime(CLOCK_REALTIME, &tsnow);
  991. nsnow = (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  992. flockfile(stdout);
  993. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  994. (unsigned long)tsnow.tv_sec,
  995. (unsigned long)tsnow.tv_nsec,
  996. nsnow - nslast,
  997. thread_id,
  998. func,
  999. line);
  1000. va_start(args, fmt);
  1001. vprintf(fmt, args);
  1002. va_end(args);
  1003. putchar('\n');
  1004. fflush(stdout);
  1005. funlockfile(stdout);
  1006. nslast = nsnow;
  1007. }
  1008. #define DEBUG_TRACE(fmt, ...) \
  1009. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  1010. #else
  1011. #define DEBUG_TRACE(fmt, ...) \
  1012. do { \
  1013. } while (0)
  1014. #endif /* DEBUG */
  1015. #endif /* DEBUG_TRACE */
  1016. #define MD5_STATIC static
  1017. #include "md5.inl"
  1018. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1019. #ifdef NO_SOCKLEN_T
  1020. typedef int socklen_t;
  1021. #endif /* NO_SOCKLEN_T */
  1022. #define _DARWIN_UNLIMITED_SELECT
  1023. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1024. #if !defined(MSG_NOSIGNAL)
  1025. #define MSG_NOSIGNAL (0)
  1026. #endif
  1027. #if !defined(SOMAXCONN)
  1028. #define SOMAXCONN (100)
  1029. #endif
  1030. /* Size of the accepted socket queue */
  1031. #if !defined(MGSQLEN)
  1032. #define MGSQLEN (20)
  1033. #endif
  1034. #if defined(NO_SSL)
  1035. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1036. typedef struct SSL_CTX SSL_CTX;
  1037. #else
  1038. #if defined(NO_SSL_DL)
  1039. #include <openssl/ssl.h>
  1040. #include <openssl/err.h>
  1041. #include <openssl/crypto.h>
  1042. #include <openssl/x509.h>
  1043. #include <openssl/pem.h>
  1044. #include <openssl/engine.h>
  1045. #include <openssl/conf.h>
  1046. #include <openssl/dh.h>
  1047. #else
  1048. /* SSL loaded dynamically from DLL.
  1049. * I put the prototypes here to be independent from OpenSSL source
  1050. * installation. */
  1051. typedef struct ssl_st SSL;
  1052. typedef struct ssl_method_st SSL_METHOD;
  1053. typedef struct ssl_ctx_st SSL_CTX;
  1054. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1055. typedef struct x509_name X509_NAME;
  1056. typedef struct asn1_integer ASN1_INTEGER;
  1057. typedef struct evp_md EVP_MD;
  1058. typedef struct x509 X509;
  1059. #define SSL_CTRL_OPTIONS (32)
  1060. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1061. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1062. #define SSL_VERIFY_NONE (0)
  1063. #define SSL_VERIFY_PEER (1)
  1064. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1065. #define SSL_VERIFY_CLIENT_ONCE (4)
  1066. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1067. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1068. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1069. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1070. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1071. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1072. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1073. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1074. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1075. #define SSL_ERROR_NONE (0)
  1076. #define SSL_ERROR_SSL (1)
  1077. #define SSL_ERROR_WANT_READ (2)
  1078. #define SSL_ERROR_WANT_WRITE (3)
  1079. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1080. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1081. #define SSL_ERROR_ZERO_RETURN (6)
  1082. #define SSL_ERROR_WANT_CONNECT (7)
  1083. #define SSL_ERROR_WANT_ACCEPT (8)
  1084. struct ssl_func {
  1085. const char *name; /* SSL function name */
  1086. void (*ptr)(void); /* Function pointer */
  1087. };
  1088. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1089. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1090. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1091. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1092. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1093. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1094. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1095. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1096. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1097. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1098. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1099. #define SSL_CTX_use_PrivateKey_file \
  1100. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1101. #define SSL_CTX_use_certificate_file \
  1102. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1103. #define SSL_CTX_set_default_passwd_cb \
  1104. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1105. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1106. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1107. #define SSL_CTX_use_certificate_chain_file \
  1108. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1109. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1110. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1111. #define SSL_CTX_set_verify \
  1112. (*(void (*)(SSL_CTX *, \
  1113. int, \
  1114. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1115. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1116. #define SSL_CTX_load_verify_locations \
  1117. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1118. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1119. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1120. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1121. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1122. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1123. #define SSL_CIPHER_get_name \
  1124. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1125. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1126. #define SSL_CTX_set_session_id_context \
  1127. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1128. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1129. #define SSL_CTX_set_cipher_list \
  1130. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1131. #define SSL_CTX_set_options(ctx, op) \
  1132. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1133. #define SSL_CTX_clear_options(ctx, op) \
  1134. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1135. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1136. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1137. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1138. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1139. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1140. #define CRYPTO_set_locking_callback \
  1141. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1142. #define CRYPTO_set_id_callback \
  1143. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1144. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1145. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1146. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1147. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1148. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1149. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1150. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1151. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1152. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1153. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1154. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1155. #define X509_NAME_oneline \
  1156. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1157. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1158. #define i2c_ASN1_INTEGER \
  1159. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1160. #define EVP_get_digestbyname \
  1161. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1162. #define ASN1_digest \
  1163. (*(int (*)(int (*)(), \
  1164. const EVP_MD *, \
  1165. char *, \
  1166. unsigned char *, \
  1167. unsigned int *))crypto_sw[18].ptr)
  1168. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1169. /* set_ssl_option() function updates this array.
  1170. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1171. * of respective functions. The macros above (like SSL_connect()) are really
  1172. * just calling these functions indirectly via the pointer. */
  1173. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1174. {"SSL_accept", NULL},
  1175. {"SSL_connect", NULL},
  1176. {"SSL_read", NULL},
  1177. {"SSL_write", NULL},
  1178. {"SSL_get_error", NULL},
  1179. {"SSL_set_fd", NULL},
  1180. {"SSL_new", NULL},
  1181. {"SSL_CTX_new", NULL},
  1182. {"SSLv23_server_method", NULL},
  1183. {"SSL_library_init", NULL},
  1184. {"SSL_CTX_use_PrivateKey_file", NULL},
  1185. {"SSL_CTX_use_certificate_file", NULL},
  1186. {"SSL_CTX_set_default_passwd_cb", NULL},
  1187. {"SSL_CTX_free", NULL},
  1188. {"SSL_load_error_strings", NULL},
  1189. {"SSL_CTX_use_certificate_chain_file", NULL},
  1190. {"SSLv23_client_method", NULL},
  1191. {"SSL_pending", NULL},
  1192. {"SSL_CTX_set_verify", NULL},
  1193. {"SSL_shutdown", NULL},
  1194. {"SSL_CTX_load_verify_locations", NULL},
  1195. {"SSL_CTX_set_default_verify_paths", NULL},
  1196. {"SSL_CTX_set_verify_depth", NULL},
  1197. {"SSL_get_peer_certificate", NULL},
  1198. {"SSL_get_version", NULL},
  1199. {"SSL_get_current_cipher", NULL},
  1200. {"SSL_CIPHER_get_name", NULL},
  1201. {"SSL_CTX_check_private_key", NULL},
  1202. {"SSL_CTX_set_session_id_context", NULL},
  1203. {"SSL_CTX_ctrl", NULL},
  1204. {"SSL_CTX_set_cipher_list", NULL},
  1205. {NULL, NULL}};
  1206. /* Similar array as ssl_sw. These functions could be located in different
  1207. * lib. */
  1208. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1209. {"CRYPTO_set_locking_callback", NULL},
  1210. {"CRYPTO_set_id_callback", NULL},
  1211. {"ERR_get_error", NULL},
  1212. {"ERR_error_string", NULL},
  1213. {"ERR_remove_state", NULL},
  1214. {"ERR_free_strings", NULL},
  1215. {"ENGINE_cleanup", NULL},
  1216. {"CONF_modules_unload", NULL},
  1217. {"CRYPTO_cleanup_all_ex_data", NULL},
  1218. {"EVP_cleanup", NULL},
  1219. {"X509_free", NULL},
  1220. {"X509_get_subject_name", NULL},
  1221. {"X509_get_issuer_name", NULL},
  1222. {"X509_NAME_oneline", NULL},
  1223. {"X509_get_serialNumber", NULL},
  1224. {"i2c_ASN1_INTEGER", NULL},
  1225. {"EVP_get_digestbyname", NULL},
  1226. {"ASN1_digest", NULL},
  1227. {"i2d_X509", NULL},
  1228. {NULL, NULL}};
  1229. #endif /* NO_SSL_DL */
  1230. #endif /* NO_SSL */
  1231. #if !defined(NO_CACHING)
  1232. static const char *month_names[] = {"Jan",
  1233. "Feb",
  1234. "Mar",
  1235. "Apr",
  1236. "May",
  1237. "Jun",
  1238. "Jul",
  1239. "Aug",
  1240. "Sep",
  1241. "Oct",
  1242. "Nov",
  1243. "Dec"};
  1244. #endif /* !NO_CACHING */
  1245. /* Unified socket address. For IPv6 support, add IPv6 address structure in the
  1246. * union u. */
  1247. union usa {
  1248. struct sockaddr sa;
  1249. struct sockaddr_in sin;
  1250. #if defined(USE_IPV6)
  1251. struct sockaddr_in6 sin6;
  1252. #endif
  1253. };
  1254. /* Describes a string (chunk of memory). */
  1255. struct vec {
  1256. const char *ptr;
  1257. size_t len;
  1258. };
  1259. struct mg_file_stat {
  1260. /* File properties filled by mg_stat: */
  1261. uint64_t size;
  1262. time_t last_modified;
  1263. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1264. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1265. * case we need a "Content-Eencoding: gzip" header */
  1266. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1267. };
  1268. struct mg_file_in_memory {
  1269. char *p;
  1270. uint32_t pos;
  1271. char mode;
  1272. };
  1273. struct mg_file_access {
  1274. /* File properties filled by mg_fopen: */
  1275. FILE *fp;
  1276. /* TODO: struct mg_file_in_memory *mf; */
  1277. const char *membuf; /* TODO: remove */
  1278. };
  1279. struct mg_file {
  1280. struct mg_file_stat stat;
  1281. struct mg_file_access access;
  1282. };
  1283. #define STRUCT_FILE_INITIALIZER \
  1284. { \
  1285. { \
  1286. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1287. } \
  1288. , \
  1289. { \
  1290. (FILE *) NULL, (const char *)NULL \
  1291. } \
  1292. }
  1293. /* Describes listening socket, or socket which was accept()-ed by the master
  1294. * thread and queued for future handling by the worker thread. */
  1295. struct socket {
  1296. SOCKET sock; /* Listening socket */
  1297. union usa lsa; /* Local socket address */
  1298. union usa rsa; /* Remote socket address */
  1299. unsigned char is_ssl; /* Is port SSL-ed */
  1300. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1301. * port */
  1302. unsigned char in_use; /* Is valid */
  1303. };
  1304. /* NOTE(lsm): this enum shoulds be in sync with the config_options below. */
  1305. enum {
  1306. CGI_EXTENSIONS,
  1307. CGI_ENVIRONMENT,
  1308. PUT_DELETE_PASSWORDS_FILE,
  1309. CGI_INTERPRETER,
  1310. PROTECT_URI,
  1311. AUTHENTICATION_DOMAIN,
  1312. SSI_EXTENSIONS,
  1313. THROTTLE,
  1314. ACCESS_LOG_FILE,
  1315. ENABLE_DIRECTORY_LISTING,
  1316. ERROR_LOG_FILE,
  1317. GLOBAL_PASSWORDS_FILE,
  1318. INDEX_FILES,
  1319. ENABLE_KEEP_ALIVE,
  1320. ACCESS_CONTROL_LIST,
  1321. EXTRA_MIME_TYPES,
  1322. LISTENING_PORTS,
  1323. DOCUMENT_ROOT,
  1324. SSL_CERTIFICATE,
  1325. NUM_THREADS,
  1326. RUN_AS_USER,
  1327. REWRITE,
  1328. HIDE_FILES,
  1329. REQUEST_TIMEOUT,
  1330. KEEP_ALIVE_TIMEOUT,
  1331. LINGER_TIMEOUT,
  1332. SSL_DO_VERIFY_PEER,
  1333. SSL_CA_PATH,
  1334. SSL_CA_FILE,
  1335. SSL_VERIFY_DEPTH,
  1336. SSL_DEFAULT_VERIFY_PATHS,
  1337. SSL_CIPHER_LIST,
  1338. SSL_PROTOCOL_VERSION,
  1339. SSL_SHORT_TRUST,
  1340. #if defined(USE_WEBSOCKET)
  1341. WEBSOCKET_TIMEOUT,
  1342. #endif
  1343. DECODE_URL,
  1344. #if defined(USE_LUA)
  1345. LUA_PRELOAD_FILE,
  1346. LUA_SCRIPT_EXTENSIONS,
  1347. LUA_SERVER_PAGE_EXTENSIONS,
  1348. #endif
  1349. #if defined(USE_DUKTAPE)
  1350. DUKTAPE_SCRIPT_EXTENSIONS,
  1351. #endif
  1352. #if defined(USE_WEBSOCKET)
  1353. WEBSOCKET_ROOT,
  1354. #endif
  1355. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1356. LUA_WEBSOCKET_EXTENSIONS,
  1357. #endif
  1358. ACCESS_CONTROL_ALLOW_ORIGIN,
  1359. ERROR_PAGES,
  1360. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1361. * socket option typedef TCP_NODELAY. */
  1362. #if !defined(NO_CACHING)
  1363. STATIC_FILE_MAX_AGE,
  1364. #endif
  1365. #if defined(__linux__)
  1366. ALLOW_SENDFILE_CALL,
  1367. #endif
  1368. #if defined(_WIN32)
  1369. CASE_SENSITIVE_FILES,
  1370. #endif
  1371. #if defined(USE_LUA)
  1372. LUA_BACKGROUND_SCRIPT,
  1373. #endif
  1374. NUM_OPTIONS
  1375. };
  1376. /* Config option name, config types, default value */
  1377. static struct mg_option config_options[] = {
  1378. {"cgi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1379. {"cgi_environment", CONFIG_TYPE_STRING, NULL},
  1380. {"put_delete_auth_file", CONFIG_TYPE_FILE, NULL},
  1381. {"cgi_interpreter", CONFIG_TYPE_FILE, NULL},
  1382. {"protect_uri", CONFIG_TYPE_STRING, NULL},
  1383. {"authentication_domain", CONFIG_TYPE_STRING, "mydomain.com"},
  1384. {"ssi_pattern", CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1385. {"throttle", CONFIG_TYPE_STRING, NULL},
  1386. {"access_log_file", CONFIG_TYPE_FILE, NULL},
  1387. {"enable_directory_listing", CONFIG_TYPE_BOOLEAN, "yes"},
  1388. {"error_log_file", CONFIG_TYPE_FILE, NULL},
  1389. {"global_auth_file", CONFIG_TYPE_FILE, NULL},
  1390. {"index_files",
  1391. CONFIG_TYPE_STRING,
  1392. #ifdef USE_LUA
  1393. "index.xhtml,index.html,index.htm,index.lp,index.lsp,index.lua,index.cgi,"
  1394. "index.shtml,index.php"},
  1395. #else
  1396. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1397. #endif
  1398. {"enable_keep_alive", CONFIG_TYPE_BOOLEAN, "no"},
  1399. {"access_control_list", CONFIG_TYPE_STRING, NULL},
  1400. {"extra_mime_types", CONFIG_TYPE_STRING, NULL},
  1401. {"listening_ports", CONFIG_TYPE_STRING, "8080"},
  1402. {"document_root", CONFIG_TYPE_DIRECTORY, NULL},
  1403. {"ssl_certificate", CONFIG_TYPE_FILE, NULL},
  1404. {"num_threads", CONFIG_TYPE_NUMBER, "50"},
  1405. {"run_as_user", CONFIG_TYPE_STRING, NULL},
  1406. {"url_rewrite_patterns", CONFIG_TYPE_STRING, NULL},
  1407. {"hide_files_patterns", CONFIG_TYPE_EXT_PATTERN, NULL},
  1408. {"request_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1409. {"keep_alive_timeout_ms", CONFIG_TYPE_NUMBER, "500"},
  1410. {"linger_timeout_ms", CONFIG_TYPE_NUMBER, NULL},
  1411. {"ssl_verify_peer", CONFIG_TYPE_BOOLEAN, "no"},
  1412. {"ssl_ca_path", CONFIG_TYPE_DIRECTORY, NULL},
  1413. {"ssl_ca_file", CONFIG_TYPE_FILE, NULL},
  1414. {"ssl_verify_depth", CONFIG_TYPE_NUMBER, "9"},
  1415. {"ssl_default_verify_paths", CONFIG_TYPE_BOOLEAN, "yes"},
  1416. {"ssl_cipher_list", CONFIG_TYPE_STRING, NULL},
  1417. {"ssl_protocol_version", CONFIG_TYPE_NUMBER, "0"},
  1418. {"ssl_short_trust", CONFIG_TYPE_BOOLEAN, "no"},
  1419. #if defined(USE_WEBSOCKET)
  1420. {"websocket_timeout_ms", CONFIG_TYPE_NUMBER, "30000"},
  1421. #endif
  1422. {"decode_url", CONFIG_TYPE_BOOLEAN, "yes"},
  1423. #if defined(USE_LUA)
  1424. {"lua_preload_file", CONFIG_TYPE_FILE, NULL},
  1425. {"lua_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1426. {"lua_server_page_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1427. #endif
  1428. #if defined(USE_DUKTAPE)
  1429. /* The support for duktape is still in alpha version state.
  1430. * The name of this config option might change. */
  1431. {"duktape_script_pattern", CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1432. #endif
  1433. #if defined(USE_WEBSOCKET)
  1434. {"websocket_root", CONFIG_TYPE_DIRECTORY, NULL},
  1435. #endif
  1436. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1437. {"lua_websocket_pattern", CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1438. #endif
  1439. {"access_control_allow_origin", CONFIG_TYPE_STRING, "*"},
  1440. {"error_pages", CONFIG_TYPE_DIRECTORY, NULL},
  1441. {"tcp_nodelay", CONFIG_TYPE_NUMBER, "0"},
  1442. #if !defined(NO_CACHING)
  1443. {"static_file_max_age", CONFIG_TYPE_NUMBER, "3600"},
  1444. #endif
  1445. #if defined(__linux__)
  1446. {"allow_sendfile_call", CONFIG_TYPE_BOOLEAN, "yes"},
  1447. #endif
  1448. #if defined(_WIN32)
  1449. {"case_sensitive", CONFIG_TYPE_BOOLEAN, "no"},
  1450. #endif
  1451. #if defined(USE_LUA)
  1452. {"lua_background_script", CONFIG_TYPE_FILE, NULL},
  1453. #endif
  1454. {NULL, CONFIG_TYPE_UNKNOWN, NULL}};
  1455. /* Check if the config_options and the corresponding enum have compatible
  1456. * sizes. */
  1457. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1458. == (NUM_OPTIONS + 1),
  1459. "config_options and enum not sync");
  1460. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1461. struct mg_handler_info {
  1462. /* Name/Pattern of the URI. */
  1463. char *uri;
  1464. size_t uri_len;
  1465. /* handler type */
  1466. int handler_type;
  1467. /* Handler for http/https or authorization requests. */
  1468. mg_request_handler handler;
  1469. /* Handler for ws/wss (websocket) requests. */
  1470. mg_websocket_connect_handler connect_handler;
  1471. mg_websocket_ready_handler ready_handler;
  1472. mg_websocket_data_handler data_handler;
  1473. mg_websocket_close_handler close_handler;
  1474. /* accepted subprotocols for ws/wss requests. */
  1475. struct mg_websocket_subprotocols *subprotocols;
  1476. /* Handler for authorization requests */
  1477. mg_authorization_handler auth_handler;
  1478. /* User supplied argument for the handler function. */
  1479. void *cbdata;
  1480. /* next handler in a linked list */
  1481. struct mg_handler_info *next;
  1482. };
  1483. struct mg_context {
  1484. volatile int stop_flag; /* Should we stop event loop */
  1485. SSL_CTX *ssl_ctx; /* SSL context */
  1486. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  1487. struct mg_callbacks callbacks; /* User-defined callback function */
  1488. void *user_data; /* User-defined data */
  1489. int context_type; /* 1 = server context,
  1490. * 2 = ws/wss client context,
  1491. */
  1492. struct socket *listening_sockets;
  1493. struct pollfd *listening_socket_fds;
  1494. unsigned int num_listening_sockets;
  1495. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  1496. #ifdef ALTERNATIVE_QUEUE
  1497. struct socket *client_socks;
  1498. void **client_wait_events;
  1499. #else
  1500. struct socket queue[MGSQLEN]; /* Accepted sockets */
  1501. volatile int sq_head; /* Head of the socket queue */
  1502. volatile int sq_tail; /* Tail of the socket queue */
  1503. pthread_cond_t sq_full; /* Signaled when socket is produced */
  1504. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  1505. #endif
  1506. pthread_t masterthreadid; /* The master thread ID */
  1507. unsigned int
  1508. cfg_worker_threads; /* The number of configured worker threads. */
  1509. pthread_t *worker_threadids; /* The worker thread IDs */
  1510. struct mg_connection *worker_connections; /* The connection struct, pre-
  1511. * allocated for each worker */
  1512. time_t start_time; /* Server start time, used for authentication */
  1513. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  1514. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  1515. unsigned long nonce_count; /* Used nonces, used for authentication */
  1516. char *systemName; /* What operating system is running */
  1517. /* linked list of uri handlers */
  1518. struct mg_handler_info *handlers;
  1519. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1520. /* linked list of shared lua websockets */
  1521. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  1522. #endif
  1523. #if defined(USE_TIMERS)
  1524. struct ttimers *timers;
  1525. #endif
  1526. #if defined(USE_LUA)
  1527. void *lua_background_state;
  1528. #endif
  1529. };
  1530. struct mg_connection {
  1531. struct mg_request_info request_info;
  1532. struct mg_context *ctx;
  1533. SSL *ssl; /* SSL descriptor */
  1534. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  1535. struct socket client; /* Connected client */
  1536. time_t conn_birth_time; /* Time (wall clock) when connection was
  1537. * established */
  1538. struct timespec req_time; /* Time (since system start) when the request
  1539. * was received */
  1540. int64_t num_bytes_sent; /* Total bytes sent to client */
  1541. int64_t content_len; /* Content-Length header value */
  1542. int64_t consumed_content; /* How many bytes of content have been read */
  1543. int is_chunked; /* Transfer-Encoding is chunked: 0=no, 1=yes:
  1544. * data available, 2: all data read */
  1545. size_t chunk_remainder; /* Unread data from the last chunk */
  1546. char *buf; /* Buffer for received data */
  1547. char *path_info; /* PATH_INFO part of the URL */
  1548. int must_close; /* 1 if connection must be closed */
  1549. int in_error_handler; /* 1 if in handler for user defined error
  1550. * pages */
  1551. int handled_requests; /* Number of requests handled by this connection */
  1552. int buf_size; /* Buffer size */
  1553. int request_len; /* Size of the request + headers in a buffer */
  1554. int data_len; /* Total size of data in a buffer */
  1555. int status_code; /* HTTP reply status code, e.g. 200 */
  1556. int throttle; /* Throttling, bytes/sec. <= 0 means no
  1557. * throttle */
  1558. time_t last_throttle_time; /* Last time throttled data was sent */
  1559. int64_t last_throttle_bytes; /* Bytes sent this second */
  1560. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  1561. * atomic transmissions for websockets */
  1562. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1563. void *lua_websocket_state; /* Lua_State for a websocket connection */
  1564. #endif
  1565. int thread_index; /* Thread index within ctx */
  1566. };
  1567. /* Directory entry */
  1568. struct de {
  1569. struct mg_connection *conn;
  1570. char *file_name;
  1571. struct mg_file_stat file;
  1572. };
  1573. #if defined(USE_WEBSOCKET)
  1574. static int is_websocket_protocol(const struct mg_connection *conn);
  1575. #else
  1576. #define is_websocket_protocol(conn) (0)
  1577. #endif
  1578. #if !defined(NO_THREAD_NAME)
  1579. #if defined(_WIN32) && defined(_MSC_VER)
  1580. /* Set the thread name for debugging purposes in Visual Studio
  1581. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  1582. */
  1583. #pragma pack(push, 8)
  1584. typedef struct tagTHREADNAME_INFO {
  1585. DWORD dwType; /* Must be 0x1000. */
  1586. LPCSTR szName; /* Pointer to name (in user addr space). */
  1587. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  1588. DWORD dwFlags; /* Reserved for future use, must be zero. */
  1589. } THREADNAME_INFO;
  1590. #pragma pack(pop)
  1591. #elif defined(__linux__)
  1592. #include <sys/prctl.h>
  1593. #include <sys/sendfile.h>
  1594. #include <sys/eventfd.h>
  1595. #if defined(ALTERNATIVE_QUEUE)
  1596. static void *
  1597. event_create(void)
  1598. {
  1599. int ret = eventfd(0, EFD_CLOEXEC);
  1600. if (ret == -1) {
  1601. /* Linux uses -1 on error, Windows NULL. */
  1602. /* However, Linux does not return 0 on success either. */
  1603. return 0;
  1604. }
  1605. return (void *)ret;
  1606. }
  1607. static int
  1608. event_wait(void *eventhdl)
  1609. {
  1610. uint64_t u;
  1611. int s = (int)read((int)eventhdl, &u, sizeof(u));
  1612. if (s != sizeof(uint64_t)) {
  1613. /* error */
  1614. return 0;
  1615. }
  1616. (void)u; /* the value is not required */
  1617. return 1;
  1618. }
  1619. static int
  1620. event_signal(void *eventhdl)
  1621. {
  1622. uint64_t u = 1;
  1623. int s = (int)write((int)eventhdl, &u, sizeof(u));
  1624. if (s != sizeof(uint64_t)) {
  1625. /* error */
  1626. return 0;
  1627. }
  1628. return 1;
  1629. }
  1630. static void
  1631. event_destroy(void *eventhdl)
  1632. {
  1633. close((int)eventhdl);
  1634. }
  1635. #endif
  1636. #endif
  1637. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  1638. struct posix_event {
  1639. pthread_mutex_t mutex;
  1640. pthread_cond_t cond;
  1641. };
  1642. static void *
  1643. event_create(void)
  1644. {
  1645. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  1646. if (ret == 0) {
  1647. /* out of memory */
  1648. return 0;
  1649. }
  1650. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  1651. /* pthread mutex not available */
  1652. mg_free(ret);
  1653. return 0;
  1654. }
  1655. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  1656. /* pthread cond not available */
  1657. pthread_mutex_destroy(&(ret->mutex));
  1658. mg_free(ret);
  1659. return 0;
  1660. }
  1661. return (void *)ret;
  1662. }
  1663. static int
  1664. event_wait(void *eventhdl)
  1665. {
  1666. struct posix_event *ev = (struct posix_event *)eventhdl;
  1667. pthread_mutex_lock(&(ev->mutex));
  1668. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  1669. pthread_mutex_unlock(&(ev->mutex));
  1670. return 1;
  1671. }
  1672. static int
  1673. event_signal(void *eventhdl)
  1674. {
  1675. struct posix_event *ev = (struct posix_event *)eventhdl;
  1676. pthread_mutex_lock(&(ev->mutex));
  1677. pthread_cond_signal(&(ev->cond));
  1678. pthread_mutex_unlock(&(ev->mutex));
  1679. return 1;
  1680. }
  1681. static void
  1682. event_destroy(void *eventhdl)
  1683. {
  1684. struct posix_event *ev = (struct posix_event *)eventhdl;
  1685. pthread_cond_destroy(&(ev->cond));
  1686. pthread_mutex_destroy(&(ev->mutex));
  1687. mg_free(ev);
  1688. }
  1689. #endif
  1690. static void
  1691. mg_set_thread_name(const char *name)
  1692. {
  1693. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  1694. mg_snprintf(
  1695. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  1696. #if defined(_WIN32)
  1697. #if defined(_MSC_VER)
  1698. /* Windows and Visual Studio Compiler */
  1699. __try
  1700. {
  1701. THREADNAME_INFO info;
  1702. info.dwType = 0x1000;
  1703. info.szName = threadName;
  1704. info.dwThreadID = ~0U;
  1705. info.dwFlags = 0;
  1706. RaiseException(0x406D1388,
  1707. 0,
  1708. sizeof(info) / sizeof(ULONG_PTR),
  1709. (ULONG_PTR *)&info);
  1710. }
  1711. __except(EXCEPTION_EXECUTE_HANDLER)
  1712. {
  1713. }
  1714. #elif defined(__MINGW32__)
  1715. /* No option known to set thread name for MinGW */
  1716. #endif
  1717. #elif defined(__GLIBC__) \
  1718. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  1719. /* pthread_setname_np first appeared in glibc in version 2.12*/
  1720. (void)pthread_setname_np(pthread_self(), threadName);
  1721. #elif defined(__linux__)
  1722. /* on linux we can use the old prctl function */
  1723. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  1724. #endif
  1725. }
  1726. #else /* !defined(NO_THREAD_NAME) */
  1727. void
  1728. mg_set_thread_name(const char *threadName)
  1729. {
  1730. }
  1731. #endif
  1732. #if defined(MG_LEGACY_INTERFACE)
  1733. const char **
  1734. mg_get_valid_option_names(void)
  1735. {
  1736. /* This function is deprecated. Use mg_get_valid_options instead. */
  1737. static const char *
  1738. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  1739. int i;
  1740. for (i = 0; config_options[i].name != NULL; i++) {
  1741. data[i * 2] = config_options[i].name;
  1742. data[i * 2 + 1] = config_options[i].default_value;
  1743. }
  1744. return data;
  1745. }
  1746. #endif
  1747. const struct mg_option *
  1748. mg_get_valid_options(void)
  1749. {
  1750. return config_options;
  1751. }
  1752. /* Do not open file (used in is_file_in_memory) */
  1753. #define MG_FOPEN_MODE_NONE (0)
  1754. /* Open file for read only access */
  1755. #define MG_FOPEN_MODE_READ (1)
  1756. /* Open file for writing, create and overwrite */
  1757. #define MG_FOPEN_MODE_WRITE (2)
  1758. /* Open file for writing, create and append */
  1759. #define MG_FOPEN_MODE_APPEND (4)
  1760. /* If a file is in memory, set all "stat" members and the membuf pointer of
  1761. * output filep and return 1, otherwise return 0 and don't modify anything. */
  1762. static int
  1763. open_file_in_memory(const struct mg_connection *conn,
  1764. const char *path,
  1765. struct mg_file *filep,
  1766. int mode)
  1767. {
  1768. size_t size = 0;
  1769. const char *buf = NULL;
  1770. if (!conn) {
  1771. return 0;
  1772. }
  1773. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  1774. return 0;
  1775. }
  1776. if (conn->ctx->callbacks.open_file) {
  1777. buf = conn->ctx->callbacks.open_file(conn, path, &size);
  1778. if (buf != NULL) {
  1779. if (filep == NULL) {
  1780. /* This is a file in memory, but we cannot store the properties
  1781. * now.
  1782. * Called from "is_file_in_memory" function. */
  1783. return 1;
  1784. }
  1785. /* NOTE: override filep->size only on success. Otherwise, it might
  1786. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  1787. filep->access.membuf = buf;
  1788. filep->access.fp = NULL;
  1789. /* Size was set by the callback */
  1790. filep->stat.size = size;
  1791. /* Assume the data may change during runtime by setting
  1792. * last_modified = now */
  1793. filep->stat.last_modified = time(NULL);
  1794. filep->stat.is_directory = 0;
  1795. filep->stat.is_gzipped = 0;
  1796. }
  1797. }
  1798. return (buf != NULL);
  1799. }
  1800. static int
  1801. is_file_in_memory(const struct mg_connection *conn, const char *path)
  1802. {
  1803. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  1804. }
  1805. static int
  1806. is_file_opened(const struct mg_file_access *fileacc)
  1807. {
  1808. if (!fileacc) {
  1809. return 0;
  1810. }
  1811. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  1812. }
  1813. static int mg_stat(const struct mg_connection *conn,
  1814. const char *path,
  1815. struct mg_file_stat *filep);
  1816. /* mg_fopen will open a file either in memory or on the disk.
  1817. * The input parameter path is a string in UTF-8 encoding.
  1818. * The input parameter mode is MG_FOPEN_MODE_*
  1819. * On success, either fp or membuf will be set in the output
  1820. * struct file. All status members will also be set.
  1821. * The function returns 1 on success, 0 on error. */
  1822. static int
  1823. mg_fopen(const struct mg_connection *conn,
  1824. const char *path,
  1825. int mode,
  1826. struct mg_file *filep)
  1827. {
  1828. int found;
  1829. if (!filep) {
  1830. return 0;
  1831. }
  1832. filep->access.fp = NULL;
  1833. filep->access.membuf = NULL;
  1834. if (!is_file_in_memory(conn, path)) {
  1835. /* filep is initialized in mg_stat: all fields with memset to,
  1836. * some fields like size and modification date with values */
  1837. found = mg_stat(conn, path, &(filep->stat));
  1838. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  1839. /* file does not exist and will not be created */
  1840. return 0;
  1841. }
  1842. #ifdef _WIN32
  1843. {
  1844. wchar_t wbuf[PATH_MAX];
  1845. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  1846. switch (mode) {
  1847. case MG_FOPEN_MODE_READ:
  1848. filep->access.fp = _wfopen(wbuf, L"rb");
  1849. break;
  1850. case MG_FOPEN_MODE_WRITE:
  1851. filep->access.fp = _wfopen(wbuf, L"wb");
  1852. break;
  1853. case MG_FOPEN_MODE_APPEND:
  1854. filep->access.fp = _wfopen(wbuf, L"ab");
  1855. break;
  1856. }
  1857. }
  1858. #else
  1859. /* Linux et al already use unicode. No need to convert. */
  1860. switch (mode) {
  1861. case MG_FOPEN_MODE_READ:
  1862. filep->access.fp = fopen(path, "r");
  1863. break;
  1864. case MG_FOPEN_MODE_WRITE:
  1865. filep->access.fp = fopen(path, "w");
  1866. break;
  1867. case MG_FOPEN_MODE_APPEND:
  1868. filep->access.fp = fopen(path, "a");
  1869. break;
  1870. }
  1871. #endif
  1872. if (!found) {
  1873. /* File did not exist before fopen was called.
  1874. * Maybe it has been created now. Get stat info
  1875. * like creation time now. */
  1876. found = mg_stat(conn, path, &(filep->stat));
  1877. (void)found;
  1878. }
  1879. /* file is on disk */
  1880. return (filep->access.fp != NULL);
  1881. } else {
  1882. /* is_file_in_memory returned true */
  1883. if (open_file_in_memory(conn, path, filep, mode)) {
  1884. /* file is in memory */
  1885. return (filep->access.membuf != NULL);
  1886. }
  1887. }
  1888. /* Open failed */
  1889. return 0;
  1890. }
  1891. /* return 0 on success, just like fclose */
  1892. static int
  1893. mg_fclose(struct mg_file_access *fileacc)
  1894. {
  1895. int ret = -1;
  1896. if (fileacc != NULL) {
  1897. if (fileacc->fp != NULL) {
  1898. ret = fclose(fileacc->fp);
  1899. } else if (fileacc->membuf != NULL) {
  1900. ret = 0;
  1901. }
  1902. /* reset all members of fileacc */
  1903. memset(fileacc, 0, sizeof(*fileacc));
  1904. }
  1905. return ret;
  1906. }
  1907. static void
  1908. mg_strlcpy(register char *dst, register const char *src, size_t n)
  1909. {
  1910. for (; *src != '\0' && n > 1; n--) {
  1911. *dst++ = *src++;
  1912. }
  1913. *dst = '\0';
  1914. }
  1915. static int
  1916. lowercase(const char *s)
  1917. {
  1918. return tolower(*(const unsigned char *)s);
  1919. }
  1920. int
  1921. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  1922. {
  1923. int diff = 0;
  1924. if (len > 0) {
  1925. do {
  1926. diff = lowercase(s1++) - lowercase(s2++);
  1927. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  1928. }
  1929. return diff;
  1930. }
  1931. int
  1932. mg_strcasecmp(const char *s1, const char *s2)
  1933. {
  1934. int diff;
  1935. do {
  1936. diff = lowercase(s1++) - lowercase(s2++);
  1937. } while (diff == 0 && s1[-1] != '\0');
  1938. return diff;
  1939. }
  1940. static char *
  1941. mg_strndup(const char *ptr, size_t len)
  1942. {
  1943. char *p;
  1944. if ((p = (char *)mg_malloc(len + 1)) != NULL) {
  1945. mg_strlcpy(p, ptr, len + 1);
  1946. }
  1947. return p;
  1948. }
  1949. static char *
  1950. mg_strdup(const char *str)
  1951. {
  1952. return mg_strndup(str, strlen(str));
  1953. }
  1954. static const char *
  1955. mg_strcasestr(const char *big_str, const char *small_str)
  1956. {
  1957. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  1958. if (big_len >= small_len) {
  1959. for (i = 0; i <= (big_len - small_len); i++) {
  1960. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  1961. return big_str + i;
  1962. }
  1963. }
  1964. }
  1965. return NULL;
  1966. }
  1967. /* Return null terminated string of given maximum length.
  1968. * Report errors if length is exceeded. */
  1969. static void
  1970. mg_vsnprintf(const struct mg_connection *conn,
  1971. int *truncated,
  1972. char *buf,
  1973. size_t buflen,
  1974. const char *fmt,
  1975. va_list ap)
  1976. {
  1977. int n, ok;
  1978. if (buflen == 0) {
  1979. return;
  1980. }
  1981. #ifdef __clang__
  1982. #pragma clang diagnostic push
  1983. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  1984. /* Using fmt as a non-literal is intended here, since it is mostly called
  1985. * indirectly by mg_snprintf */
  1986. #endif
  1987. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  1988. ok = (n >= 0) && ((size_t)n < buflen);
  1989. #ifdef __clang__
  1990. #pragma clang diagnostic pop
  1991. #endif
  1992. if (ok) {
  1993. if (truncated) {
  1994. *truncated = 0;
  1995. }
  1996. } else {
  1997. if (truncated) {
  1998. *truncated = 1;
  1999. }
  2000. mg_cry(conn,
  2001. "truncating vsnprintf buffer: [%.*s]",
  2002. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2003. buf);
  2004. n = (int)buflen - 1;
  2005. }
  2006. buf[n] = '\0';
  2007. }
  2008. static void
  2009. mg_snprintf(const struct mg_connection *conn,
  2010. int *truncated,
  2011. char *buf,
  2012. size_t buflen,
  2013. const char *fmt,
  2014. ...)
  2015. {
  2016. va_list ap;
  2017. va_start(ap, fmt);
  2018. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2019. va_end(ap);
  2020. }
  2021. static int
  2022. get_option_index(const char *name)
  2023. {
  2024. int i;
  2025. for (i = 0; config_options[i].name != NULL; i++) {
  2026. if (strcmp(config_options[i].name, name) == 0) {
  2027. return i;
  2028. }
  2029. }
  2030. return -1;
  2031. }
  2032. const char *
  2033. mg_get_option(const struct mg_context *ctx, const char *name)
  2034. {
  2035. int i;
  2036. if ((i = get_option_index(name)) == -1) {
  2037. return NULL;
  2038. } else if (!ctx || ctx->config[i] == NULL) {
  2039. return "";
  2040. } else {
  2041. return ctx->config[i];
  2042. }
  2043. }
  2044. struct mg_context *
  2045. mg_get_context(const struct mg_connection *conn)
  2046. {
  2047. return (conn == NULL) ? (struct mg_context *)NULL : (conn->ctx);
  2048. }
  2049. void *
  2050. mg_get_user_data(const struct mg_context *ctx)
  2051. {
  2052. return (ctx == NULL) ? NULL : ctx->user_data;
  2053. }
  2054. void
  2055. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2056. {
  2057. if (conn != NULL) {
  2058. conn->request_info.conn_data = data;
  2059. }
  2060. }
  2061. void *
  2062. mg_get_user_connection_data(const struct mg_connection *conn)
  2063. {
  2064. if (conn != NULL) {
  2065. return conn->request_info.conn_data;
  2066. }
  2067. return NULL;
  2068. }
  2069. size_t
  2070. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2071. {
  2072. size_t i;
  2073. if (!ctx) {
  2074. return 0;
  2075. }
  2076. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2077. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2078. ports[i] =
  2079. #if defined(USE_IPV6)
  2080. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2081. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2082. :
  2083. #endif
  2084. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2085. }
  2086. return i;
  2087. }
  2088. int
  2089. mg_get_server_ports(const struct mg_context *ctx,
  2090. int size,
  2091. struct mg_server_ports *ports)
  2092. {
  2093. int i, cnt = 0;
  2094. if (size <= 0) {
  2095. return -1;
  2096. }
  2097. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2098. if (!ctx) {
  2099. return -1;
  2100. }
  2101. if (!ctx->listening_sockets) {
  2102. return -1;
  2103. }
  2104. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2105. ports[cnt].port =
  2106. #if defined(USE_IPV6)
  2107. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2108. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2109. :
  2110. #endif
  2111. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2112. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2113. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2114. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2115. /* IPv4 */
  2116. ports[cnt].protocol = 1;
  2117. cnt++;
  2118. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2119. /* IPv6 */
  2120. ports[cnt].protocol = 3;
  2121. cnt++;
  2122. }
  2123. }
  2124. return cnt;
  2125. }
  2126. static void
  2127. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2128. {
  2129. buf[0] = '\0';
  2130. if (!usa) {
  2131. return;
  2132. }
  2133. if (usa->sa.sa_family == AF_INET) {
  2134. getnameinfo(&usa->sa,
  2135. sizeof(usa->sin),
  2136. buf,
  2137. (unsigned)len,
  2138. NULL,
  2139. 0,
  2140. NI_NUMERICHOST);
  2141. }
  2142. #if defined(USE_IPV6)
  2143. else if (usa->sa.sa_family == AF_INET6) {
  2144. getnameinfo(&usa->sa,
  2145. sizeof(usa->sin6),
  2146. buf,
  2147. (unsigned)len,
  2148. NULL,
  2149. 0,
  2150. NI_NUMERICHOST);
  2151. }
  2152. #endif
  2153. }
  2154. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2155. * included in all responses other than 100, 101, 5xx. */
  2156. static void
  2157. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2158. {
  2159. struct tm *tm;
  2160. tm = ((t != NULL) ? gmtime(t) : NULL);
  2161. if (tm != NULL) {
  2162. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2163. } else {
  2164. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2165. buf[buf_len - 1] = '\0';
  2166. }
  2167. }
  2168. /* difftime for struct timespec. Return value is in seconds. */
  2169. static double
  2170. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2171. {
  2172. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2173. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2174. }
  2175. /* Print error message to the opened error log stream. */
  2176. void
  2177. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2178. {
  2179. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2180. va_list ap;
  2181. struct mg_file fi;
  2182. time_t timestamp;
  2183. va_start(ap, fmt);
  2184. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2185. va_end(ap);
  2186. buf[sizeof(buf) - 1] = 0;
  2187. if (!conn) {
  2188. puts(buf);
  2189. return;
  2190. }
  2191. /* Do not lock when getting the callback value, here and below.
  2192. * I suppose this is fine, since function cannot disappear in the
  2193. * same way string option can. */
  2194. if ((conn->ctx->callbacks.log_message == NULL)
  2195. || (conn->ctx->callbacks.log_message(conn, buf) == 0)) {
  2196. if (conn->ctx->config[ERROR_LOG_FILE] != NULL) {
  2197. if (mg_fopen(conn,
  2198. conn->ctx->config[ERROR_LOG_FILE],
  2199. MG_FOPEN_MODE_APPEND,
  2200. &fi) == 0) {
  2201. fi.access.fp = NULL;
  2202. }
  2203. } else {
  2204. fi.access.fp = NULL;
  2205. }
  2206. if (fi.access.fp != NULL) {
  2207. flockfile(fi.access.fp);
  2208. timestamp = time(NULL);
  2209. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2210. fprintf(fi.access.fp,
  2211. "[%010lu] [error] [client %s] ",
  2212. (unsigned long)timestamp,
  2213. src_addr);
  2214. if (conn->request_info.request_method != NULL) {
  2215. fprintf(fi.access.fp,
  2216. "%s %s: ",
  2217. conn->request_info.request_method,
  2218. conn->request_info.request_uri);
  2219. }
  2220. fprintf(fi.access.fp, "%s", buf);
  2221. fputc('\n', fi.access.fp);
  2222. fflush(fi.access.fp);
  2223. funlockfile(fi.access.fp);
  2224. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2225. * mg_cry here anyway ;-) */
  2226. }
  2227. }
  2228. }
  2229. /* Return fake connection structure. Used for logging, if connection
  2230. * is not applicable at the moment of logging. */
  2231. static struct mg_connection *
  2232. fc(struct mg_context *ctx)
  2233. {
  2234. static struct mg_connection fake_connection;
  2235. fake_connection.ctx = ctx;
  2236. return &fake_connection;
  2237. }
  2238. const char *
  2239. mg_version(void)
  2240. {
  2241. return CIVETWEB_VERSION;
  2242. }
  2243. const struct mg_request_info *
  2244. mg_get_request_info(const struct mg_connection *conn)
  2245. {
  2246. if (!conn) {
  2247. return NULL;
  2248. }
  2249. return &conn->request_info;
  2250. }
  2251. /* Skip the characters until one of the delimiters characters found.
  2252. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  2253. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  2254. * Delimiters can be quoted with quotechar. */
  2255. static char *
  2256. skip_quoted(char **buf,
  2257. const char *delimiters,
  2258. const char *whitespace,
  2259. char quotechar)
  2260. {
  2261. char *p, *begin_word, *end_word, *end_whitespace;
  2262. begin_word = *buf;
  2263. end_word = begin_word + strcspn(begin_word, delimiters);
  2264. /* Check for quotechar */
  2265. if (end_word > begin_word) {
  2266. p = end_word - 1;
  2267. while (*p == quotechar) {
  2268. /* While the delimiter is quoted, look for the next delimiter. */
  2269. /* This happens, e.g., in calls from parse_auth_header,
  2270. * if the user name contains a " character. */
  2271. /* If there is anything beyond end_word, copy it. */
  2272. if (*end_word != '\0') {
  2273. size_t end_off = strcspn(end_word + 1, delimiters);
  2274. memmove(p, end_word, end_off + 1);
  2275. p += end_off; /* p must correspond to end_word - 1 */
  2276. end_word += end_off + 1;
  2277. } else {
  2278. *p = '\0';
  2279. break;
  2280. }
  2281. }
  2282. for (p++; p < end_word; p++) {
  2283. *p = '\0';
  2284. }
  2285. }
  2286. if (*end_word == '\0') {
  2287. *buf = end_word;
  2288. } else {
  2289. #if defined(__GNUC__) || defined(__MINGW32__)
  2290. /* Disable spurious conversion warning for GCC */
  2291. #pragma GCC diagnostic push
  2292. #pragma GCC diagnostic ignored "-Wsign-conversion"
  2293. #endif
  2294. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  2295. #if defined(__GNUC__) || defined(__MINGW32__)
  2296. #pragma GCC diagnostic pop
  2297. #endif
  2298. for (p = end_word; p < end_whitespace; p++) {
  2299. *p = '\0';
  2300. }
  2301. *buf = end_whitespace;
  2302. }
  2303. return begin_word;
  2304. }
  2305. /* Simplified version of skip_quoted without quote char
  2306. * and whitespace == delimiters */
  2307. static char *
  2308. skip(char **buf, const char *delimiters)
  2309. {
  2310. return skip_quoted(buf, delimiters, delimiters, 0);
  2311. }
  2312. /* Return HTTP header value, or NULL if not found. */
  2313. static const char *
  2314. get_header(const struct mg_request_info *ri, const char *name)
  2315. {
  2316. int i;
  2317. if (ri) {
  2318. for (i = 0; i < ri->num_headers; i++) {
  2319. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  2320. return ri->http_headers[i].value;
  2321. }
  2322. }
  2323. }
  2324. return NULL;
  2325. }
  2326. const char *
  2327. mg_get_header(const struct mg_connection *conn, const char *name)
  2328. {
  2329. if (!conn) {
  2330. return NULL;
  2331. }
  2332. return get_header(&conn->request_info, name);
  2333. }
  2334. /* A helper function for traversing a comma separated list of values.
  2335. * It returns a list pointer shifted to the next value, or NULL if the end
  2336. * of the list found.
  2337. * Value is stored in val vector. If value has form "x=y", then eq_val
  2338. * vector is initialized to point to the "y" part, and val vector length
  2339. * is adjusted to point only to "x". */
  2340. static const char *
  2341. next_option(const char *list, struct vec *val, struct vec *eq_val)
  2342. {
  2343. int end;
  2344. reparse:
  2345. if (val == NULL || list == NULL || *list == '\0') {
  2346. /* End of the list */
  2347. list = NULL;
  2348. } else {
  2349. /* Skip over leading LWS */
  2350. while (*list == ' ' || *list == '\t')
  2351. list++;
  2352. val->ptr = list;
  2353. if ((list = strchr(val->ptr, ',')) != NULL) {
  2354. /* Comma found. Store length and shift the list ptr */
  2355. val->len = ((size_t)(list - val->ptr));
  2356. list++;
  2357. } else {
  2358. /* This value is the last one */
  2359. list = val->ptr + strlen(val->ptr);
  2360. val->len = ((size_t)(list - val->ptr));
  2361. }
  2362. /* Adjust length for trailing LWS */
  2363. end = (int)val->len - 1;
  2364. while (end >= 0 && (val->ptr[end] == ' ' || val->ptr[end] == '\t'))
  2365. end--;
  2366. val->len = (size_t)(end + 1);
  2367. if (val->len == 0) {
  2368. /* Ignore any empty entries. */
  2369. goto reparse;
  2370. }
  2371. if (eq_val != NULL) {
  2372. /* Value has form "x=y", adjust pointers and lengths
  2373. * so that val points to "x", and eq_val points to "y". */
  2374. eq_val->len = 0;
  2375. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  2376. if (eq_val->ptr != NULL) {
  2377. eq_val->ptr++; /* Skip over '=' character */
  2378. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  2379. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  2380. }
  2381. }
  2382. }
  2383. return list;
  2384. }
  2385. /* A helper function for checking if a comma separated list of values contains
  2386. * the given option (case insensitvely).
  2387. * 'header' can be NULL, in which case false is returned. */
  2388. static int
  2389. header_has_option(const char *header, const char *option)
  2390. {
  2391. struct vec opt_vec;
  2392. struct vec eq_vec;
  2393. assert(option != NULL);
  2394. assert(option[0] != '\0');
  2395. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  2396. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  2397. return 1;
  2398. }
  2399. return 0;
  2400. }
  2401. /* Perform case-insensitive match of string against pattern */
  2402. static int
  2403. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  2404. {
  2405. const char *or_str;
  2406. size_t i;
  2407. int j, len, res;
  2408. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  2409. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  2410. return (res > 0) ? res : match_prefix(or_str + 1,
  2411. (size_t)((pattern + pattern_len)
  2412. - (or_str + 1)),
  2413. str);
  2414. }
  2415. for (i = 0, j = 0; i < pattern_len; i++, j++) {
  2416. if (pattern[i] == '?' && str[j] != '\0') {
  2417. continue;
  2418. } else if (pattern[i] == '$') {
  2419. return (str[j] == '\0') ? j : -1;
  2420. } else if (pattern[i] == '*') {
  2421. i++;
  2422. if (pattern[i] == '*') {
  2423. i++;
  2424. len = (int)strlen(str + j);
  2425. } else {
  2426. len = (int)strcspn(str + j, "/");
  2427. }
  2428. if (i == pattern_len) {
  2429. return j + len;
  2430. }
  2431. do {
  2432. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  2433. } while (res == -1 && len-- > 0);
  2434. return (res == -1) ? -1 : j + res + len;
  2435. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2436. return -1;
  2437. }
  2438. }
  2439. return j;
  2440. }
  2441. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  2442. * This function must tolerate situations when connection info is not
  2443. * set up, for example if request parsing failed. */
  2444. static int
  2445. should_keep_alive(const struct mg_connection *conn)
  2446. {
  2447. if (conn != NULL) {
  2448. const char *http_version = conn->request_info.http_version;
  2449. const char *header = mg_get_header(conn, "Connection");
  2450. if (conn->must_close || conn->status_code == 401
  2451. || mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0
  2452. || (header != NULL && !header_has_option(header, "keep-alive"))
  2453. || (header == NULL && http_version
  2454. && 0 != strcmp(http_version, "1.1"))) {
  2455. return 0;
  2456. }
  2457. return 1;
  2458. }
  2459. return 0;
  2460. }
  2461. static int
  2462. should_decode_url(const struct mg_connection *conn)
  2463. {
  2464. if (!conn || !conn->ctx) {
  2465. return 0;
  2466. }
  2467. return (mg_strcasecmp(conn->ctx->config[DECODE_URL], "yes") == 0);
  2468. }
  2469. static const char *
  2470. suggest_connection_header(const struct mg_connection *conn)
  2471. {
  2472. return should_keep_alive(conn) ? "keep-alive" : "close";
  2473. }
  2474. static int
  2475. send_no_cache_header(struct mg_connection *conn)
  2476. {
  2477. /* Send all current and obsolete cache opt-out directives. */
  2478. return mg_printf(conn,
  2479. "Cache-Control: no-cache, no-store, "
  2480. "must-revalidate, private, max-age=0\r\n"
  2481. "Pragma: no-cache\r\n"
  2482. "Expires: 0\r\n");
  2483. }
  2484. static int
  2485. send_static_cache_header(struct mg_connection *conn)
  2486. {
  2487. #if !defined(NO_CACHING)
  2488. /* Read the server config to check how long a file may be cached.
  2489. * The configuration is in seconds. */
  2490. int max_age = atoi(conn->ctx->config[STATIC_FILE_MAX_AGE]);
  2491. if (max_age <= 0) {
  2492. /* 0 means "do not cache". All values <0 are reserved
  2493. * and may be used differently in the future. */
  2494. /* If a file should not be cached, do not only send
  2495. * max-age=0, but also pragmas and Expires headers. */
  2496. return send_no_cache_header(conn);
  2497. }
  2498. /* Use "Cache-Control: max-age" instead of "Expires" header.
  2499. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  2500. /* See also https://www.mnot.net/cache_docs/ */
  2501. /* According to RFC 2616, Section 14.21, caching times should not exceed
  2502. * one year. A year with 365 days corresponds to 31536000 seconds, a leap
  2503. * year to 31622400 seconds. For the moment, we just send whatever has
  2504. * been configured, still the behavior for >1 year should be considered
  2505. * as undefined. */
  2506. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  2507. #else /* NO_CACHING */
  2508. return send_no_cache_header(conn);
  2509. #endif /* !NO_CACHING */
  2510. }
  2511. static void handle_file_based_request(struct mg_connection *conn,
  2512. const char *path,
  2513. struct mg_file *filep);
  2514. const char *
  2515. mg_get_response_code_text(struct mg_connection *conn, int response_code)
  2516. {
  2517. /* See IANA HTTP status code assignment:
  2518. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  2519. */
  2520. switch (response_code) {
  2521. /* RFC2616 Section 10.1 - Informational 1xx */
  2522. case 100:
  2523. return "Continue"; /* RFC2616 Section 10.1.1 */
  2524. case 101:
  2525. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  2526. case 102:
  2527. return "Processing"; /* RFC2518 Section 10.1 */
  2528. /* RFC2616 Section 10.2 - Successful 2xx */
  2529. case 200:
  2530. return "OK"; /* RFC2616 Section 10.2.1 */
  2531. case 201:
  2532. return "Created"; /* RFC2616 Section 10.2.2 */
  2533. case 202:
  2534. return "Accepted"; /* RFC2616 Section 10.2.3 */
  2535. case 203:
  2536. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  2537. case 204:
  2538. return "No Content"; /* RFC2616 Section 10.2.5 */
  2539. case 205:
  2540. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  2541. case 206:
  2542. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  2543. case 207:
  2544. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */
  2545. case 208:
  2546. return "Already Reported"; /* RFC5842 Section 7.1 */
  2547. case 226:
  2548. return "IM used"; /* RFC3229 Section 10.4.1 */
  2549. /* RFC2616 Section 10.3 - Redirection 3xx */
  2550. case 300:
  2551. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  2552. case 301:
  2553. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  2554. case 302:
  2555. return "Found"; /* RFC2616 Section 10.3.3 */
  2556. case 303:
  2557. return "See Other"; /* RFC2616 Section 10.3.4 */
  2558. case 304:
  2559. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  2560. case 305:
  2561. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  2562. case 307:
  2563. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  2564. case 308:
  2565. return "Permanent Redirect"; /* RFC7238 Section 3 */
  2566. /* RFC2616 Section 10.4 - Client Error 4xx */
  2567. case 400:
  2568. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  2569. case 401:
  2570. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  2571. case 402:
  2572. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  2573. case 403:
  2574. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  2575. case 404:
  2576. return "Not Found"; /* RFC2616 Section 10.4.5 */
  2577. case 405:
  2578. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  2579. case 406:
  2580. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  2581. case 407:
  2582. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  2583. case 408:
  2584. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  2585. case 409:
  2586. return "Conflict"; /* RFC2616 Section 10.4.10 */
  2587. case 410:
  2588. return "Gone"; /* RFC2616 Section 10.4.11 */
  2589. case 411:
  2590. return "Length Required"; /* RFC2616 Section 10.4.12 */
  2591. case 412:
  2592. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  2593. case 413:
  2594. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  2595. case 414:
  2596. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  2597. case 415:
  2598. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  2599. case 416:
  2600. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */
  2601. case 417:
  2602. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  2603. case 421:
  2604. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  2605. case 422:
  2606. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  2607. * Section 11.2 */
  2608. case 423:
  2609. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  2610. case 424:
  2611. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  2612. * Section 11.4 */
  2613. case 426:
  2614. return "Upgrade Required"; /* RFC 2817 Section 4 */
  2615. case 428:
  2616. return "Precondition Required"; /* RFC 6585, Section 3 */
  2617. case 429:
  2618. return "Too Many Requests"; /* RFC 6585, Section 4 */
  2619. case 431:
  2620. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  2621. case 451:
  2622. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  2623. * Section 3 */
  2624. /* RFC2616 Section 10.5 - Server Error 5xx */
  2625. case 500:
  2626. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  2627. case 501:
  2628. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  2629. case 502:
  2630. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  2631. case 503:
  2632. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  2633. case 504:
  2634. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  2635. case 505:
  2636. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  2637. case 506:
  2638. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  2639. case 507:
  2640. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  2641. * Section 11.5 */
  2642. case 508:
  2643. return "Loop Detected"; /* RFC5842 Section 7.1 */
  2644. case 510:
  2645. return "Not Extended"; /* RFC 2774, Section 7 */
  2646. case 511:
  2647. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  2648. /* Other status codes, not shown in the IANA HTTP status code assignment.
  2649. * E.g., "de facto" standards due to common use, ... */
  2650. case 418:
  2651. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  2652. case 419:
  2653. return "Authentication Timeout"; /* common use */
  2654. case 420:
  2655. return "Enhance Your Calm"; /* common use */
  2656. case 440:
  2657. return "Login Timeout"; /* common use */
  2658. case 509:
  2659. return "Bandwidth Limit Exceeded"; /* common use */
  2660. default:
  2661. /* This error code is unknown. This should not happen. */
  2662. if (conn) {
  2663. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  2664. }
  2665. /* Return at least a category according to RFC 2616 Section 10. */
  2666. if (response_code >= 100 && response_code < 200) {
  2667. /* Unknown informational status code */
  2668. return "Information";
  2669. }
  2670. if (response_code >= 200 && response_code < 300) {
  2671. /* Unknown success code */
  2672. return "Success";
  2673. }
  2674. if (response_code >= 300 && response_code < 400) {
  2675. /* Unknown redirection code */
  2676. return "Redirection";
  2677. }
  2678. if (response_code >= 400 && response_code < 500) {
  2679. /* Unknown request error code */
  2680. return "Client Error";
  2681. }
  2682. if (response_code >= 500 && response_code < 600) {
  2683. /* Unknown server error code */
  2684. return "Server Error";
  2685. }
  2686. /* Response code not even within reasonable range */
  2687. return "";
  2688. }
  2689. }
  2690. static void send_http_error(struct mg_connection *,
  2691. int,
  2692. PRINTF_FORMAT_STRING(const char *fmt),
  2693. ...) PRINTF_ARGS(3, 4);
  2694. static void
  2695. send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  2696. {
  2697. char buf[MG_BUF_LEN];
  2698. va_list ap;
  2699. int len, i, page_handler_found, scope, truncated, has_body;
  2700. char date[64];
  2701. time_t curtime = time(NULL);
  2702. const char *error_handler = NULL;
  2703. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  2704. const char *error_page_file_ext, *tstr;
  2705. const char *status_text = mg_get_response_code_text(conn, status);
  2706. if (conn == NULL) {
  2707. return;
  2708. }
  2709. conn->status_code = status;
  2710. if (conn->in_error_handler || conn->ctx->callbacks.http_error == NULL
  2711. || conn->ctx->callbacks.http_error(conn, status)) {
  2712. if (!conn->in_error_handler) {
  2713. /* Send user defined error pages, if defined */
  2714. error_handler = conn->ctx->config[ERROR_PAGES];
  2715. error_page_file_ext = conn->ctx->config[INDEX_FILES];
  2716. page_handler_found = 0;
  2717. if (error_handler != NULL) {
  2718. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  2719. switch (scope) {
  2720. case 1: /* Handler for specific error, e.g. 404 error */
  2721. mg_snprintf(conn,
  2722. &truncated,
  2723. buf,
  2724. sizeof(buf) - 32,
  2725. "%serror%03u.",
  2726. error_handler,
  2727. status);
  2728. break;
  2729. case 2: /* Handler for error group, e.g., 5xx error handler
  2730. * for all server errors (500-599) */
  2731. mg_snprintf(conn,
  2732. &truncated,
  2733. buf,
  2734. sizeof(buf) - 32,
  2735. "%serror%01uxx.",
  2736. error_handler,
  2737. status / 100);
  2738. break;
  2739. default: /* Handler for all errors */
  2740. mg_snprintf(conn,
  2741. &truncated,
  2742. buf,
  2743. sizeof(buf) - 32,
  2744. "%serror.",
  2745. error_handler);
  2746. break;
  2747. }
  2748. /* String truncation in buf may only occur if error_handler
  2749. * is too long. This string is from the config, not from a
  2750. * client. */
  2751. (void)truncated;
  2752. len = (int)strlen(buf);
  2753. tstr = strchr(error_page_file_ext, '.');
  2754. while (tstr) {
  2755. for (i = 1; i < 32 && tstr[i] != 0 && tstr[i] != ',';
  2756. i++)
  2757. buf[len + i - 1] = tstr[i];
  2758. buf[len + i - 1] = 0;
  2759. if (mg_stat(conn, buf, &error_page_file.stat)) {
  2760. page_handler_found = 1;
  2761. break;
  2762. }
  2763. tstr = strchr(tstr + i, '.');
  2764. }
  2765. }
  2766. }
  2767. if (page_handler_found) {
  2768. conn->in_error_handler = 1;
  2769. handle_file_based_request(conn, buf, &error_page_file);
  2770. conn->in_error_handler = 0;
  2771. return;
  2772. }
  2773. }
  2774. /* No custom error page. Send default error page. */
  2775. gmt_time_string(date, sizeof(date), &curtime);
  2776. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2777. has_body = (status > 199 && status != 204 && status != 304);
  2778. conn->must_close = 1;
  2779. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  2780. send_no_cache_header(conn);
  2781. if (has_body) {
  2782. mg_printf(conn,
  2783. "%s",
  2784. "Content-Type: text/plain; charset=utf-8\r\n");
  2785. }
  2786. mg_printf(conn,
  2787. "Date: %s\r\n"
  2788. "Connection: close\r\n\r\n",
  2789. date);
  2790. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  2791. if (has_body) {
  2792. mg_printf(conn, "Error %d: %s\n", status, status_text);
  2793. if (fmt != NULL) {
  2794. va_start(ap, fmt);
  2795. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  2796. va_end(ap);
  2797. mg_write(conn, buf, strlen(buf));
  2798. DEBUG_TRACE("Error %i - [%s]", status, buf);
  2799. }
  2800. } else {
  2801. /* No body allowed. Close the connection. */
  2802. DEBUG_TRACE("Error %i", status);
  2803. }
  2804. }
  2805. }
  2806. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  2807. /* Create substitutes for POSIX functions in Win32. */
  2808. #if defined(__MINGW32__)
  2809. /* Show no warning in case system functions are not used. */
  2810. #pragma GCC diagnostic push
  2811. #pragma GCC diagnostic ignored "-Wunused-function"
  2812. #endif
  2813. static int
  2814. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  2815. {
  2816. (void)unused;
  2817. *mutex = CreateMutex(NULL, FALSE, NULL);
  2818. return (*mutex == NULL) ? -1 : 0;
  2819. }
  2820. static int
  2821. pthread_mutex_destroy(pthread_mutex_t *mutex)
  2822. {
  2823. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  2824. }
  2825. static int
  2826. pthread_mutex_lock(pthread_mutex_t *mutex)
  2827. {
  2828. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0) ? 0 : -1;
  2829. }
  2830. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  2831. static int
  2832. pthread_mutex_trylock(pthread_mutex_t *mutex)
  2833. {
  2834. switch (WaitForSingleObject(*mutex, 0)) {
  2835. case WAIT_OBJECT_0:
  2836. return 0;
  2837. case WAIT_TIMEOUT:
  2838. return -2; /* EBUSY */
  2839. }
  2840. return -1;
  2841. }
  2842. #endif
  2843. static int
  2844. pthread_mutex_unlock(pthread_mutex_t *mutex)
  2845. {
  2846. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  2847. }
  2848. static int
  2849. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  2850. {
  2851. (void)unused;
  2852. InitializeCriticalSection(&cv->threadIdSec);
  2853. cv->waiting_thread = NULL;
  2854. return 0;
  2855. }
  2856. static int
  2857. pthread_cond_timedwait(pthread_cond_t *cv,
  2858. pthread_mutex_t *mutex,
  2859. const struct timespec *abstime)
  2860. {
  2861. struct mg_workerTLS **ptls,
  2862. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2863. int ok;
  2864. struct timespec tsnow;
  2865. int64_t nsnow, nswaitabs, nswaitrel;
  2866. DWORD mswaitrel;
  2867. EnterCriticalSection(&cv->threadIdSec);
  2868. /* Add this thread to cv's waiting list */
  2869. ptls = &cv->waiting_thread;
  2870. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  2871. ;
  2872. tls->next_waiting_thread = NULL;
  2873. *ptls = tls;
  2874. LeaveCriticalSection(&cv->threadIdSec);
  2875. if (abstime) {
  2876. clock_gettime(CLOCK_REALTIME, &tsnow);
  2877. nsnow = (((int64_t)tsnow.tv_sec) * 1000000000) + tsnow.tv_nsec;
  2878. nswaitabs =
  2879. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  2880. nswaitrel = nswaitabs - nsnow;
  2881. if (nswaitrel < 0) {
  2882. nswaitrel = 0;
  2883. }
  2884. mswaitrel = (DWORD)(nswaitrel / 1000000);
  2885. } else {
  2886. mswaitrel = INFINITE;
  2887. }
  2888. pthread_mutex_unlock(mutex);
  2889. ok = (WAIT_OBJECT_0
  2890. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  2891. if (!ok) {
  2892. ok = 1;
  2893. EnterCriticalSection(&cv->threadIdSec);
  2894. ptls = &cv->waiting_thread;
  2895. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  2896. if (*ptls == tls) {
  2897. *ptls = tls->next_waiting_thread;
  2898. ok = 0;
  2899. break;
  2900. }
  2901. }
  2902. LeaveCriticalSection(&cv->threadIdSec);
  2903. if (ok) {
  2904. WaitForSingleObject(tls->pthread_cond_helper_mutex, INFINITE);
  2905. }
  2906. }
  2907. /* This thread has been removed from cv's waiting list */
  2908. pthread_mutex_lock(mutex);
  2909. return ok ? 0 : -1;
  2910. }
  2911. static int
  2912. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  2913. {
  2914. return pthread_cond_timedwait(cv, mutex, NULL);
  2915. }
  2916. static int
  2917. pthread_cond_signal(pthread_cond_t *cv)
  2918. {
  2919. HANDLE wkup = NULL;
  2920. BOOL ok = FALSE;
  2921. EnterCriticalSection(&cv->threadIdSec);
  2922. if (cv->waiting_thread) {
  2923. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  2924. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  2925. ok = SetEvent(wkup);
  2926. assert(ok);
  2927. }
  2928. LeaveCriticalSection(&cv->threadIdSec);
  2929. return ok ? 0 : 1;
  2930. }
  2931. static int
  2932. pthread_cond_broadcast(pthread_cond_t *cv)
  2933. {
  2934. EnterCriticalSection(&cv->threadIdSec);
  2935. while (cv->waiting_thread) {
  2936. pthread_cond_signal(cv);
  2937. }
  2938. LeaveCriticalSection(&cv->threadIdSec);
  2939. return 0;
  2940. }
  2941. static int
  2942. pthread_cond_destroy(pthread_cond_t *cv)
  2943. {
  2944. EnterCriticalSection(&cv->threadIdSec);
  2945. assert(cv->waiting_thread == NULL);
  2946. LeaveCriticalSection(&cv->threadIdSec);
  2947. DeleteCriticalSection(&cv->threadIdSec);
  2948. return 0;
  2949. }
  2950. #ifdef ALTERNATIVE_QUEUE
  2951. static void *
  2952. event_create(void)
  2953. {
  2954. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  2955. }
  2956. static int
  2957. event_wait(void *eventhdl)
  2958. {
  2959. int res = WaitForSingleObject((HANDLE)eventhdl, INFINITE);
  2960. return (res == WAIT_OBJECT_0);
  2961. }
  2962. static int
  2963. event_signal(void *eventhdl)
  2964. {
  2965. return (int)SetEvent((HANDLE)eventhdl);
  2966. }
  2967. static void
  2968. event_destroy(void *eventhdl)
  2969. {
  2970. CloseHandle((HANDLE)eventhdl);
  2971. }
  2972. #endif
  2973. #if defined(__MINGW32__)
  2974. /* Enable unused function warning again */
  2975. #pragma GCC diagnostic pop
  2976. #endif
  2977. /* For Windows, change all slashes to backslashes in path names. */
  2978. static void
  2979. change_slashes_to_backslashes(char *path)
  2980. {
  2981. int i;
  2982. for (i = 0; path[i] != '\0'; i++) {
  2983. if (path[i] == '/') {
  2984. path[i] = '\\';
  2985. }
  2986. /* remove double backslash (check i > 0 to preserve UNC paths,
  2987. * like \\server\file.txt) */
  2988. if ((path[i] == '\\') && (i > 0)) {
  2989. while (path[i + 1] == '\\' || path[i + 1] == '/') {
  2990. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  2991. }
  2992. }
  2993. }
  2994. }
  2995. static int
  2996. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  2997. {
  2998. int diff;
  2999. do {
  3000. diff = tolower(*s1) - tolower(*s2);
  3001. s1++;
  3002. s2++;
  3003. } while (diff == 0 && s1[-1] != '\0');
  3004. return diff;
  3005. }
  3006. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3007. * wbuf and wbuf_len is a target buffer and its length. */
  3008. static void
  3009. path_to_unicode(const struct mg_connection *conn,
  3010. const char *path,
  3011. wchar_t *wbuf,
  3012. size_t wbuf_len)
  3013. {
  3014. char buf[PATH_MAX], buf2[PATH_MAX];
  3015. wchar_t wbuf2[MAX_PATH + 1];
  3016. DWORD long_len, err;
  3017. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3018. mg_strlcpy(buf, path, sizeof(buf));
  3019. change_slashes_to_backslashes(buf);
  3020. /* Convert to Unicode and back. If doubly-converted string does not
  3021. * match the original, something is fishy, reject. */
  3022. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3023. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3024. WideCharToMultiByte(
  3025. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3026. if (strcmp(buf, buf2) != 0) {
  3027. wbuf[0] = L'\0';
  3028. }
  3029. /* Windows file systems are not case sensitive, but you can still use
  3030. * uppercase and lowercase letters (on all modern file systems).
  3031. * The server can check if the URI uses the same upper/lowercase
  3032. * letters an the file system, effectively making Windows servers
  3033. * case sensitive (like Linux servers are). It is still not possible
  3034. * to use two files with the same name in different cases on Windows
  3035. * (like /a and /A) - this would be possible in Linux.
  3036. * As a default, Windows is not case sensitive, but the case sensitive
  3037. * file name check can be activated by an additional configuration. */
  3038. if (conn) {
  3039. if (conn->ctx->config[CASE_SENSITIVE_FILES]
  3040. && !mg_strcasecmp(conn->ctx->config[CASE_SENSITIVE_FILES], "yes")) {
  3041. /* Use case sensitive compare function */
  3042. fcompare = wcscmp;
  3043. }
  3044. }
  3045. (void)conn; /* conn is currently unused */
  3046. #if !defined(_WIN32_WCE)
  3047. /* Only accept a full file path, not a Windows short (8.3) path. */
  3048. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3049. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3050. if (long_len == 0) {
  3051. err = GetLastError();
  3052. if (err == ERROR_FILE_NOT_FOUND) {
  3053. /* File does not exist. This is not always a problem here. */
  3054. return;
  3055. }
  3056. }
  3057. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3058. /* Short name is used. */
  3059. wbuf[0] = L'\0';
  3060. }
  3061. #else
  3062. (void)long_len;
  3063. (void)wbuf2;
  3064. (void)err;
  3065. if (strchr(path, '~')) {
  3066. wbuf[0] = L'\0';
  3067. }
  3068. #endif
  3069. }
  3070. /* Windows happily opens files with some garbage at the end of file name.
  3071. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3072. * "a.cgi", despite one would expect an error back.
  3073. * This function returns non-0 if path ends with some garbage. */
  3074. static int
  3075. path_cannot_disclose_cgi(const char *path)
  3076. {
  3077. static const char *allowed_last_characters = "_-";
  3078. int last = path[strlen(path) - 1];
  3079. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3080. }
  3081. static int
  3082. mg_stat(const struct mg_connection *conn,
  3083. const char *path,
  3084. struct mg_file_stat *filep)
  3085. {
  3086. wchar_t wbuf[PATH_MAX];
  3087. WIN32_FILE_ATTRIBUTE_DATA info;
  3088. time_t creation_time;
  3089. if (!filep) {
  3090. return 0;
  3091. }
  3092. memset(filep, 0, sizeof(*filep));
  3093. if (conn && is_file_in_memory(conn, path)) {
  3094. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  3095. * memset */
  3096. filep->last_modified = time(NULL); /* xxxxxxxx */
  3097. /* last_modified = now ... assumes the file may change during runtime,
  3098. * so every mg_fopen call may return different data */
  3099. /* last_modified = conn->ctx.start_time;
  3100. * May be used it the data does not change during runtime. This allows
  3101. * browser caching. Since we do not know, we have to assume the file
  3102. * in memory may change. */
  3103. return 1;
  3104. }
  3105. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3106. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  3107. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  3108. filep->last_modified =
  3109. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  3110. info.ftLastWriteTime.dwHighDateTime);
  3111. /* On Windows, the file creation time can be higher than the
  3112. * modification time, e.g. when a file is copied.
  3113. * Since the Last-Modified timestamp is used for caching
  3114. * it should be based on the most recent timestamp. */
  3115. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  3116. info.ftCreationTime.dwHighDateTime);
  3117. if (creation_time > filep->last_modified) {
  3118. filep->last_modified = creation_time;
  3119. }
  3120. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  3121. /* If file name is fishy, reset the file structure and return
  3122. * error.
  3123. * Note it is important to reset, not just return the error, cause
  3124. * functions like is_file_opened() check the struct. */
  3125. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  3126. memset(filep, 0, sizeof(*filep));
  3127. return 0;
  3128. }
  3129. return 1;
  3130. }
  3131. return 0;
  3132. }
  3133. static int
  3134. mg_remove(const struct mg_connection *conn, const char *path)
  3135. {
  3136. wchar_t wbuf[PATH_MAX];
  3137. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3138. return DeleteFileW(wbuf) ? 0 : -1;
  3139. }
  3140. static int
  3141. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  3142. {
  3143. wchar_t wbuf[PATH_MAX];
  3144. (void)mode;
  3145. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  3146. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  3147. }
  3148. /* Create substitutes for POSIX functions in Win32. */
  3149. #if defined(__MINGW32__)
  3150. /* Show no warning in case system functions are not used. */
  3151. #pragma GCC diagnostic push
  3152. #pragma GCC diagnostic ignored "-Wunused-function"
  3153. #endif
  3154. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  3155. static DIR *
  3156. mg_opendir(const struct mg_connection *conn, const char *name)
  3157. {
  3158. DIR *dir = NULL;
  3159. wchar_t wpath[PATH_MAX];
  3160. DWORD attrs;
  3161. if (name == NULL) {
  3162. SetLastError(ERROR_BAD_ARGUMENTS);
  3163. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  3164. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3165. } else {
  3166. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  3167. attrs = GetFileAttributesW(wpath);
  3168. if (attrs != 0xFFFFFFFF && ((attrs & FILE_ATTRIBUTE_DIRECTORY)
  3169. == FILE_ATTRIBUTE_DIRECTORY)) {
  3170. (void)wcscat(wpath, L"\\*");
  3171. dir->handle = FindFirstFileW(wpath, &dir->info);
  3172. dir->result.d_name[0] = '\0';
  3173. } else {
  3174. mg_free(dir);
  3175. dir = NULL;
  3176. }
  3177. }
  3178. return dir;
  3179. }
  3180. static int
  3181. mg_closedir(DIR *dir)
  3182. {
  3183. int result = 0;
  3184. if (dir != NULL) {
  3185. if (dir->handle != INVALID_HANDLE_VALUE)
  3186. result = FindClose(dir->handle) ? 0 : -1;
  3187. mg_free(dir);
  3188. } else {
  3189. result = -1;
  3190. SetLastError(ERROR_BAD_ARGUMENTS);
  3191. }
  3192. return result;
  3193. }
  3194. static struct dirent *
  3195. mg_readdir(DIR *dir)
  3196. {
  3197. struct dirent *result = 0;
  3198. if (dir) {
  3199. if (dir->handle != INVALID_HANDLE_VALUE) {
  3200. result = &dir->result;
  3201. (void)WideCharToMultiByte(CP_UTF8,
  3202. 0,
  3203. dir->info.cFileName,
  3204. -1,
  3205. result->d_name,
  3206. sizeof(result->d_name),
  3207. NULL,
  3208. NULL);
  3209. if (!FindNextFileW(dir->handle, &dir->info)) {
  3210. (void)FindClose(dir->handle);
  3211. dir->handle = INVALID_HANDLE_VALUE;
  3212. }
  3213. } else {
  3214. SetLastError(ERROR_FILE_NOT_FOUND);
  3215. }
  3216. } else {
  3217. SetLastError(ERROR_BAD_ARGUMENTS);
  3218. }
  3219. return result;
  3220. }
  3221. #ifndef HAVE_POLL
  3222. static int
  3223. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  3224. {
  3225. struct timeval tv;
  3226. fd_set set;
  3227. unsigned int i;
  3228. int result;
  3229. SOCKET maxfd = 0;
  3230. memset(&tv, 0, sizeof(tv));
  3231. tv.tv_sec = milliseconds / 1000;
  3232. tv.tv_usec = (milliseconds % 1000) * 1000;
  3233. FD_ZERO(&set);
  3234. for (i = 0; i < n; i++) {
  3235. FD_SET((SOCKET)pfd[i].fd, &set);
  3236. pfd[i].revents = 0;
  3237. if (pfd[i].fd > maxfd) {
  3238. maxfd = pfd[i].fd;
  3239. }
  3240. }
  3241. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  3242. for (i = 0; i < n; i++) {
  3243. if (FD_ISSET(pfd[i].fd, &set)) {
  3244. pfd[i].revents = POLLIN;
  3245. }
  3246. }
  3247. }
  3248. /* We should subtract the time used in select from remaining
  3249. * "milliseconds", in particular if called from mg_poll with a
  3250. * timeout quantum.
  3251. * Unfortunately, the remaining time is not stored in "tv" in all
  3252. * implementations, so the result in "tv" must be considered undefined.
  3253. * See http://man7.org/linux/man-pages/man2/select.2.html */
  3254. return result;
  3255. }
  3256. #endif /* HAVE_POLL */
  3257. #if defined(__MINGW32__)
  3258. /* Enable unused function warning again */
  3259. #pragma GCC diagnostic pop
  3260. #endif
  3261. static void
  3262. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  3263. {
  3264. (void)conn; /* Unused. */
  3265. #if defined(_WIN32_WCE)
  3266. (void)sock;
  3267. #else
  3268. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  3269. #endif
  3270. }
  3271. int
  3272. mg_start_thread(mg_thread_func_t f, void *p)
  3273. {
  3274. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3275. /* Compile-time option to control stack size, e.g. -DUSE_STACK_SIZE=16384
  3276. */
  3277. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  3278. == ((uintptr_t)(-1L)))
  3279. ? -1
  3280. : 0);
  3281. #else
  3282. return (
  3283. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  3284. ? -1
  3285. : 0);
  3286. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3287. }
  3288. /* Start a thread storing the thread context. */
  3289. static int
  3290. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  3291. void *p,
  3292. pthread_t *threadidptr)
  3293. {
  3294. uintptr_t uip;
  3295. HANDLE threadhandle;
  3296. int result = -1;
  3297. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  3298. threadhandle = (HANDLE)uip;
  3299. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  3300. *threadidptr = threadhandle;
  3301. result = 0;
  3302. }
  3303. return result;
  3304. }
  3305. /* Wait for a thread to finish. */
  3306. static int
  3307. mg_join_thread(pthread_t threadid)
  3308. {
  3309. int result;
  3310. DWORD dwevent;
  3311. result = -1;
  3312. dwevent = WaitForSingleObject(threadid, INFINITE);
  3313. if (dwevent == WAIT_FAILED) {
  3314. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  3315. } else {
  3316. if (dwevent == WAIT_OBJECT_0) {
  3317. CloseHandle(threadid);
  3318. result = 0;
  3319. }
  3320. }
  3321. return result;
  3322. }
  3323. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  3324. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  3325. /* Create substitutes for POSIX functions in Win32. */
  3326. #if defined(__MINGW32__)
  3327. /* Show no warning in case system functions are not used. */
  3328. #pragma GCC diagnostic push
  3329. #pragma GCC diagnostic ignored "-Wunused-function"
  3330. #endif
  3331. static HANDLE
  3332. dlopen(const char *dll_name, int flags)
  3333. {
  3334. wchar_t wbuf[PATH_MAX];
  3335. (void)flags;
  3336. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  3337. return LoadLibraryW(wbuf);
  3338. }
  3339. static int
  3340. dlclose(void *handle)
  3341. {
  3342. int result;
  3343. if (FreeLibrary((HMODULE)handle) != 0) {
  3344. result = 0;
  3345. } else {
  3346. result = -1;
  3347. }
  3348. return result;
  3349. }
  3350. #if defined(__MINGW32__)
  3351. /* Enable unused function warning again */
  3352. #pragma GCC diagnostic pop
  3353. #endif
  3354. #endif
  3355. #if !defined(NO_CGI)
  3356. #define SIGKILL (0)
  3357. static int
  3358. kill(pid_t pid, int sig_num)
  3359. {
  3360. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  3361. (void)CloseHandle((HANDLE)pid);
  3362. return 0;
  3363. }
  3364. static void
  3365. trim_trailing_whitespaces(char *s)
  3366. {
  3367. char *e = s + strlen(s) - 1;
  3368. while (e > s && isspace(*(unsigned char *)e)) {
  3369. *e-- = '\0';
  3370. }
  3371. }
  3372. static pid_t
  3373. spawn_process(struct mg_connection *conn,
  3374. const char *prog,
  3375. char *envblk,
  3376. char *envp[],
  3377. int fdin[2],
  3378. int fdout[2],
  3379. int fderr[2],
  3380. const char *dir)
  3381. {
  3382. HANDLE me;
  3383. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  3384. cmdline[PATH_MAX], buf[PATH_MAX];
  3385. int truncated;
  3386. struct mg_file file = STRUCT_FILE_INITIALIZER;
  3387. STARTUPINFOA si;
  3388. PROCESS_INFORMATION pi = {0};
  3389. (void)envp;
  3390. memset(&si, 0, sizeof(si));
  3391. si.cb = sizeof(si);
  3392. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  3393. si.wShowWindow = SW_HIDE;
  3394. me = GetCurrentProcess();
  3395. DuplicateHandle(me,
  3396. (HANDLE)_get_osfhandle(fdin[0]),
  3397. me,
  3398. &si.hStdInput,
  3399. 0,
  3400. TRUE,
  3401. DUPLICATE_SAME_ACCESS);
  3402. DuplicateHandle(me,
  3403. (HANDLE)_get_osfhandle(fdout[1]),
  3404. me,
  3405. &si.hStdOutput,
  3406. 0,
  3407. TRUE,
  3408. DUPLICATE_SAME_ACCESS);
  3409. DuplicateHandle(me,
  3410. (HANDLE)_get_osfhandle(fderr[1]),
  3411. me,
  3412. &si.hStdError,
  3413. 0,
  3414. TRUE,
  3415. DUPLICATE_SAME_ACCESS);
  3416. /* Mark handles that should not be inherited. See
  3417. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  3418. */
  3419. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  3420. HANDLE_FLAG_INHERIT,
  3421. 0);
  3422. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  3423. HANDLE_FLAG_INHERIT,
  3424. 0);
  3425. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  3426. HANDLE_FLAG_INHERIT,
  3427. 0);
  3428. /* If CGI file is a script, try to read the interpreter line */
  3429. interp = conn->ctx->config[CGI_INTERPRETER];
  3430. if (interp == NULL) {
  3431. buf[0] = buf[1] = '\0';
  3432. /* Read the first line of the script into the buffer */
  3433. mg_snprintf(
  3434. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  3435. if (truncated) {
  3436. pi.hProcess = (pid_t)-1;
  3437. goto spawn_cleanup;
  3438. }
  3439. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  3440. p = (char *)file.access.membuf;
  3441. mg_fgets(buf, sizeof(buf), &file, &p);
  3442. (void)mg_fclose(&file.access); /* ignore error on read only file */
  3443. buf[sizeof(buf) - 1] = '\0';
  3444. }
  3445. if (buf[0] == '#' && buf[1] == '!') {
  3446. trim_trailing_whitespaces(buf + 2);
  3447. } else {
  3448. buf[2] = '\0';
  3449. }
  3450. interp = buf + 2;
  3451. }
  3452. if (interp[0] != '\0') {
  3453. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  3454. interp = full_interp;
  3455. }
  3456. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  3457. if (interp[0] != '\0') {
  3458. mg_snprintf(conn,
  3459. &truncated,
  3460. cmdline,
  3461. sizeof(cmdline),
  3462. "\"%s\" \"%s\\%s\"",
  3463. interp,
  3464. full_dir,
  3465. prog);
  3466. } else {
  3467. mg_snprintf(conn,
  3468. &truncated,
  3469. cmdline,
  3470. sizeof(cmdline),
  3471. "\"%s\\%s\"",
  3472. full_dir,
  3473. prog);
  3474. }
  3475. if (truncated) {
  3476. pi.hProcess = (pid_t)-1;
  3477. goto spawn_cleanup;
  3478. }
  3479. DEBUG_TRACE("Running [%s]", cmdline);
  3480. if (CreateProcessA(NULL,
  3481. cmdline,
  3482. NULL,
  3483. NULL,
  3484. TRUE,
  3485. CREATE_NEW_PROCESS_GROUP,
  3486. envblk,
  3487. NULL,
  3488. &si,
  3489. &pi) == 0) {
  3490. mg_cry(
  3491. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  3492. pi.hProcess = (pid_t)-1;
  3493. /* goto spawn_cleanup; */
  3494. }
  3495. spawn_cleanup:
  3496. (void)CloseHandle(si.hStdOutput);
  3497. (void)CloseHandle(si.hStdError);
  3498. (void)CloseHandle(si.hStdInput);
  3499. if (pi.hThread != NULL) {
  3500. (void)CloseHandle(pi.hThread);
  3501. }
  3502. return (pid_t)pi.hProcess;
  3503. }
  3504. #endif /* !NO_CGI */
  3505. static int
  3506. set_blocking_mode(SOCKET sock, int blocking)
  3507. {
  3508. unsigned long non_blocking = !blocking;
  3509. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  3510. }
  3511. #else
  3512. static int
  3513. mg_stat(const struct mg_connection *conn,
  3514. const char *path,
  3515. struct mg_file_stat *filep)
  3516. {
  3517. struct stat st;
  3518. if (!filep) {
  3519. return 0;
  3520. }
  3521. memset(filep, 0, sizeof(*filep));
  3522. if (conn && is_file_in_memory(conn, path)) {
  3523. return 1;
  3524. }
  3525. if (0 == stat(path, &st)) {
  3526. filep->size = (uint64_t)(st.st_size);
  3527. filep->last_modified = st.st_mtime;
  3528. filep->is_directory = S_ISDIR(st.st_mode);
  3529. return 1;
  3530. }
  3531. return 0;
  3532. }
  3533. static void
  3534. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  3535. {
  3536. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  3537. if (conn) {
  3538. mg_cry(conn,
  3539. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  3540. __func__,
  3541. strerror(ERRNO));
  3542. }
  3543. }
  3544. }
  3545. int
  3546. mg_start_thread(mg_thread_func_t func, void *param)
  3547. {
  3548. pthread_t thread_id;
  3549. pthread_attr_t attr;
  3550. int result;
  3551. (void)pthread_attr_init(&attr);
  3552. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  3553. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3554. /* Compile-time option to control stack size,
  3555. * e.g. -DUSE_STACK_SIZE=16384 */
  3556. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3557. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  3558. result = pthread_create(&thread_id, &attr, func, param);
  3559. pthread_attr_destroy(&attr);
  3560. return result;
  3561. }
  3562. /* Start a thread storing the thread context. */
  3563. static int
  3564. mg_start_thread_with_id(mg_thread_func_t func,
  3565. void *param,
  3566. pthread_t *threadidptr)
  3567. {
  3568. pthread_t thread_id;
  3569. pthread_attr_t attr;
  3570. int result;
  3571. (void)pthread_attr_init(&attr);
  3572. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  3573. /* Compile-time option to control stack size,
  3574. * e.g. -DUSE_STACK_SIZE=16384 */
  3575. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  3576. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  3577. result = pthread_create(&thread_id, &attr, func, param);
  3578. pthread_attr_destroy(&attr);
  3579. if ((result == 0) && (threadidptr != NULL)) {
  3580. *threadidptr = thread_id;
  3581. }
  3582. return result;
  3583. }
  3584. /* Wait for a thread to finish. */
  3585. static int
  3586. mg_join_thread(pthread_t threadid)
  3587. {
  3588. int result;
  3589. result = pthread_join(threadid, NULL);
  3590. return result;
  3591. }
  3592. #ifndef NO_CGI
  3593. static pid_t
  3594. spawn_process(struct mg_connection *conn,
  3595. const char *prog,
  3596. char *envblk,
  3597. char *envp[],
  3598. int fdin[2],
  3599. int fdout[2],
  3600. int fderr[2],
  3601. const char *dir)
  3602. {
  3603. pid_t pid;
  3604. const char *interp;
  3605. (void)envblk;
  3606. if (conn == NULL) {
  3607. return 0;
  3608. }
  3609. if ((pid = fork()) == -1) {
  3610. /* Parent */
  3611. send_http_error(conn,
  3612. 500,
  3613. "Error: Creating CGI process\nfork(): %s",
  3614. strerror(ERRNO));
  3615. } else if (pid == 0) {
  3616. /* Child */
  3617. if (chdir(dir) != 0) {
  3618. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  3619. } else if (dup2(fdin[0], 0) == -1) {
  3620. mg_cry(conn,
  3621. "%s: dup2(%d, 0): %s",
  3622. __func__,
  3623. fdin[0],
  3624. strerror(ERRNO));
  3625. } else if (dup2(fdout[1], 1) == -1) {
  3626. mg_cry(conn,
  3627. "%s: dup2(%d, 1): %s",
  3628. __func__,
  3629. fdout[1],
  3630. strerror(ERRNO));
  3631. } else if (dup2(fderr[1], 2) == -1) {
  3632. mg_cry(conn,
  3633. "%s: dup2(%d, 2): %s",
  3634. __func__,
  3635. fderr[1],
  3636. strerror(ERRNO));
  3637. } else {
  3638. /* Keep stderr and stdout in two different pipes.
  3639. * Stdout will be sent back to the client,
  3640. * stderr should go into a server error log. */
  3641. (void)close(fdin[0]);
  3642. (void)close(fdout[1]);
  3643. (void)close(fderr[1]);
  3644. /* Close write end fdin and read end fdout and fderr */
  3645. (void)close(fdin[1]);
  3646. (void)close(fdout[0]);
  3647. (void)close(fderr[0]);
  3648. /* After exec, all signal handlers are restored to their default
  3649. * values, with one exception of SIGCHLD. According to
  3650. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  3651. * leave unchanged after exec if it was set to be ignored. Restore
  3652. * it to default action. */
  3653. signal(SIGCHLD, SIG_DFL);
  3654. interp = conn->ctx->config[CGI_INTERPRETER];
  3655. if (interp == NULL) {
  3656. (void)execle(prog, prog, NULL, envp);
  3657. mg_cry(conn,
  3658. "%s: execle(%s): %s",
  3659. __func__,
  3660. prog,
  3661. strerror(ERRNO));
  3662. } else {
  3663. (void)execle(interp, interp, prog, NULL, envp);
  3664. mg_cry(conn,
  3665. "%s: execle(%s %s): %s",
  3666. __func__,
  3667. interp,
  3668. prog,
  3669. strerror(ERRNO));
  3670. }
  3671. }
  3672. exit(EXIT_FAILURE);
  3673. }
  3674. return pid;
  3675. }
  3676. #endif /* !NO_CGI */
  3677. static int
  3678. set_blocking_mode(SOCKET sock, int blocking)
  3679. {
  3680. int flags;
  3681. flags = fcntl(sock, F_GETFL, 0);
  3682. if (blocking) {
  3683. (void)fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  3684. } else {
  3685. (void)fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK)));
  3686. }
  3687. return 0;
  3688. }
  3689. #endif /* _WIN32 */
  3690. /* End of initial operating system specific define block. */
  3691. /* Get a random number (independent of C rand function) */
  3692. static uint64_t
  3693. get_random(void)
  3694. {
  3695. static uint64_t lfsr = 0; /* Linear feedback shift register */
  3696. static uint64_t lcg = 0; /* Linear congruential generator */
  3697. struct timespec now;
  3698. memset(&now, 0, sizeof(now));
  3699. clock_gettime(CLOCK_MONOTONIC, &now);
  3700. if (lfsr == 0) {
  3701. /* lfsr will be only 0 if has not been initialized,
  3702. * so this code is called only once. */
  3703. lfsr = (((uint64_t)now.tv_sec) << 21) ^ ((uint64_t)now.tv_nsec)
  3704. ^ ((uint64_t)(ptrdiff_t)&now) ^ (((uint64_t)time(NULL)) << 33);
  3705. lcg = (((uint64_t)now.tv_sec) << 25) + (uint64_t)now.tv_nsec
  3706. + (uint64_t)(ptrdiff_t)&now;
  3707. } else {
  3708. /* Get the next step of both random number generators. */
  3709. lfsr = (lfsr >> 1)
  3710. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  3711. << 63);
  3712. lcg = lcg * 6364136223846793005 + 1442695040888963407;
  3713. }
  3714. /* Combining two pseudo-random number generators and a high resolution part
  3715. * of the current server time will make it hard (impossible?) to guess the
  3716. * next number. */
  3717. return (lfsr ^ lcg ^ (uint64_t)now.tv_nsec);
  3718. }
  3719. static int
  3720. mg_poll(struct pollfd *pfd,
  3721. unsigned int n,
  3722. int milliseconds,
  3723. volatile int *stop_server)
  3724. {
  3725. int ms_now, result;
  3726. /* Call poll, but only for a maximum time of a few seconds.
  3727. * This will allow to stop the server after some seconds, instead
  3728. * of having to wait for a long socket timeout. */
  3729. ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  3730. do {
  3731. if (*stop_server) {
  3732. /* Shut down signal */
  3733. return -2;
  3734. }
  3735. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  3736. ms_now = milliseconds;
  3737. }
  3738. result = poll(pfd, n, ms_now);
  3739. if (result != 0) {
  3740. /* Poll returned either success (1) or error (-1).
  3741. * Forward both to the caller. */
  3742. return result;
  3743. }
  3744. /* Poll returned timeout (0). */
  3745. if (milliseconds > 0) {
  3746. milliseconds -= ms_now;
  3747. }
  3748. } while (milliseconds != 0);
  3749. return result;
  3750. }
  3751. /* Write data to the IO channel - opened file descriptor, socket or SSL
  3752. * descriptor. Return number of bytes written. */
  3753. static int
  3754. push(struct mg_context *ctx,
  3755. FILE *fp,
  3756. SOCKET sock,
  3757. SSL *ssl,
  3758. const char *buf,
  3759. int len,
  3760. double timeout)
  3761. {
  3762. struct timespec start, now;
  3763. int n, err;
  3764. #ifdef _WIN32
  3765. typedef int len_t;
  3766. #else
  3767. typedef size_t len_t;
  3768. #endif
  3769. if (timeout > 0) {
  3770. memset(&start, 0, sizeof(start));
  3771. memset(&now, 0, sizeof(now));
  3772. clock_gettime(CLOCK_MONOTONIC, &start);
  3773. }
  3774. if (ctx == NULL) {
  3775. return -1;
  3776. }
  3777. #ifdef NO_SSL
  3778. if (ssl) {
  3779. return -1;
  3780. }
  3781. #endif
  3782. do {
  3783. #ifndef NO_SSL
  3784. if (ssl != NULL) {
  3785. n = SSL_write(ssl, buf, len);
  3786. if (n <= 0) {
  3787. err = SSL_get_error(ssl, n);
  3788. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  3789. err = ERRNO;
  3790. } else if ((err == SSL_ERROR_WANT_READ)
  3791. || (err == SSL_ERROR_WANT_WRITE)) {
  3792. n = 0;
  3793. } else {
  3794. DEBUG_TRACE("SSL_write() failed, error %d", err);
  3795. return -1;
  3796. }
  3797. } else {
  3798. err = 0;
  3799. }
  3800. } else
  3801. #endif
  3802. if (fp != NULL) {
  3803. n = (int)fwrite(buf, 1, (size_t)len, fp);
  3804. if (ferror(fp)) {
  3805. n = -1;
  3806. err = ERRNO;
  3807. } else {
  3808. err = 0;
  3809. }
  3810. } else {
  3811. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  3812. err = (n < 0) ? ERRNO : 0;
  3813. if (n <= 0) {
  3814. /* shutdown of the socket at client side */
  3815. return -1;
  3816. }
  3817. #if defined(TEMPORARY_INSTRUMENTATION)
  3818. {
  3819. FILE *f = fopen("r:\\all.txt", "ab");
  3820. fprintf(f, "\r\n%010u SEND:\r\n", GetTickCount());
  3821. fwrite(buf, 1, n, f);
  3822. fclose(f);
  3823. }
  3824. #endif
  3825. }
  3826. if (ctx->stop_flag) {
  3827. return -1;
  3828. }
  3829. if ((n > 0) || (n == 0 && len == 0)) {
  3830. /* some data has been read, or no data was requested */
  3831. return n;
  3832. }
  3833. if (n < 0) {
  3834. /* socket error - check errno */
  3835. DEBUG_TRACE("send() failed, error %d", err);
  3836. /* TODO: error handling depending on the error code.
  3837. * These codes are different between Windows and Linux.
  3838. */
  3839. return -1;
  3840. }
  3841. /* Only in case n=0 (timeout), repeat calling the write function */
  3842. if (timeout > 0) {
  3843. clock_gettime(CLOCK_MONOTONIC, &now);
  3844. }
  3845. } while ((timeout <= 0) || (mg_difftimespec(&now, &start) <= timeout));
  3846. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  3847. used */
  3848. return -1;
  3849. }
  3850. static int64_t
  3851. push_all(struct mg_context *ctx,
  3852. FILE *fp,
  3853. SOCKET sock,
  3854. SSL *ssl,
  3855. const char *buf,
  3856. int64_t len)
  3857. {
  3858. double timeout = -1.0;
  3859. int64_t n, nwritten = 0;
  3860. if (ctx == NULL) {
  3861. return -1;
  3862. }
  3863. if (ctx->config[REQUEST_TIMEOUT]) {
  3864. timeout = atoi(ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  3865. }
  3866. while (len > 0 && ctx->stop_flag == 0) {
  3867. n = push(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  3868. if (n < 0) {
  3869. if (nwritten == 0) {
  3870. nwritten = n; /* Propagate the error */
  3871. }
  3872. break;
  3873. } else if (n == 0) {
  3874. break; /* No more data to write */
  3875. } else {
  3876. nwritten += n;
  3877. len -= n;
  3878. }
  3879. }
  3880. return nwritten;
  3881. }
  3882. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  3883. * Return negative value on error, or number of bytes read on success. */
  3884. static int
  3885. pull(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout)
  3886. {
  3887. int nread, err = 0;
  3888. #ifdef _WIN32
  3889. typedef int len_t;
  3890. #else
  3891. typedef size_t len_t;
  3892. #endif
  3893. if (fp != NULL) {
  3894. #if !defined(_WIN32_WCE)
  3895. /* Use read() instead of fread(), because if we're reading from the
  3896. * CGI pipe, fread() may block until IO buffer is filled up. We
  3897. * cannot afford to block and must pass all read bytes immediately
  3898. * to the client. */
  3899. nread = (int)read(fileno(fp), buf, (size_t)len);
  3900. #else
  3901. /* WinCE does not support CGI pipes */
  3902. nread = (int)fread(buf, 1, (size_t)len, fp);
  3903. #endif
  3904. err = (nread < 0) ? ERRNO : 0;
  3905. #ifndef NO_SSL
  3906. } else if (conn->ssl != NULL) {
  3907. struct pollfd pfd[1];
  3908. int pollres;
  3909. pfd[0].fd = conn->client.sock;
  3910. pfd[0].events = POLLIN;
  3911. pollres =
  3912. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3913. if (conn->ctx->stop_flag) {
  3914. return -1;
  3915. }
  3916. if (pollres > 0) {
  3917. nread = SSL_read(conn->ssl, buf, len);
  3918. if (nread <= 0) {
  3919. err = SSL_get_error(conn->ssl, nread);
  3920. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  3921. err = ERRNO;
  3922. } else if ((err == SSL_ERROR_WANT_READ)
  3923. || (err == SSL_ERROR_WANT_WRITE)) {
  3924. nread = 0;
  3925. } else {
  3926. DEBUG_TRACE("SSL_read() failed, error %d", err);
  3927. return -1;
  3928. }
  3929. } else {
  3930. err = 0;
  3931. }
  3932. } else if (pollres < 0) {
  3933. /* Error */
  3934. return -1;
  3935. } else {
  3936. /* pollres = 0 means timeout */
  3937. nread = 0;
  3938. }
  3939. #endif
  3940. } else {
  3941. struct pollfd pfd[1];
  3942. int pollres;
  3943. pfd[0].fd = conn->client.sock;
  3944. pfd[0].events = POLLIN;
  3945. pollres =
  3946. mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->ctx->stop_flag));
  3947. if (conn->ctx->stop_flag) {
  3948. return -1;
  3949. }
  3950. if (pollres > 0) {
  3951. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  3952. err = (nread < 0) ? ERRNO : 0;
  3953. if (nread <= 0) {
  3954. /* shutdown of the socket at client side */
  3955. return -1;
  3956. }
  3957. #if defined(TEMPORARY_INSTRUMENTATION)
  3958. {
  3959. FILE *f = fopen("r:\\all.txt", "ab");
  3960. fprintf(f, "\r\n%010u RECV:\r\n", GetTickCount());
  3961. fwrite(buf, 1, nread, f);
  3962. fclose(f);
  3963. }
  3964. #endif
  3965. } else if (pollres < 0) {
  3966. /* error callint poll */
  3967. return -1;
  3968. } else {
  3969. /* pollres = 0 means timeout */
  3970. nread = 0;
  3971. }
  3972. }
  3973. if (conn->ctx->stop_flag) {
  3974. return -1;
  3975. }
  3976. if ((nread > 0) || (nread == 0 && len == 0)) {
  3977. /* some data has been read, or no data was requested */
  3978. return nread;
  3979. }
  3980. if (nread < 0) {
  3981. /* socket error - check errno */
  3982. #ifdef _WIN32
  3983. if (err == WSAEWOULDBLOCK) {
  3984. /* TODO: check if this is still required */
  3985. /* standard case if called from close_socket_gracefully */
  3986. return -1;
  3987. } else if (err == WSAETIMEDOUT) {
  3988. /* TODO: check if this is still required */
  3989. /* timeout is handled by the while loop */
  3990. return 0;
  3991. } else if (err == WSAECONNABORTED) {
  3992. /* See https://www.chilkatsoft.com/p/p_299.asp */
  3993. return -1;
  3994. } else {
  3995. DEBUG_TRACE("recv() failed, error %d", err);
  3996. return -1;
  3997. }
  3998. #else
  3999. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  4000. * if the timeout is reached and if the socket was set to non-
  4001. * blocking in close_socket_gracefully, so we can not distinguish
  4002. * here. We have to wait for the timeout in both cases for now.
  4003. */
  4004. if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) {
  4005. /* TODO: check if this is still required */
  4006. /* EAGAIN/EWOULDBLOCK:
  4007. * standard case if called from close_socket_gracefully
  4008. * => should return -1 */
  4009. /* or timeout occured
  4010. * => the code must stay in the while loop */
  4011. /* EINTR can be generated on a socket with a timeout set even
  4012. * when SA_RESTART is effective for all relevant signals
  4013. * (see signal(7)).
  4014. * => stay in the while loop */
  4015. } else {
  4016. DEBUG_TRACE("recv() failed, error %d", err);
  4017. return -1;
  4018. }
  4019. #endif
  4020. }
  4021. /* Timeout occured, but no data available. */
  4022. return -1;
  4023. }
  4024. static int
  4025. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  4026. {
  4027. int n, nread = 0;
  4028. double timeout = -1.0;
  4029. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  4030. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  4031. }
  4032. while (len > 0 && conn->ctx->stop_flag == 0) {
  4033. n = pull(fp, conn, buf + nread, len, timeout);
  4034. if (n < 0) {
  4035. if (nread == 0) {
  4036. nread = n; /* Propagate the error */
  4037. }
  4038. break;
  4039. } else if (n == 0) {
  4040. break; /* No more data to read */
  4041. } else {
  4042. conn->consumed_content += n;
  4043. nread += n;
  4044. len -= n;
  4045. }
  4046. }
  4047. return nread;
  4048. }
  4049. static void
  4050. discard_unread_request_data(struct mg_connection *conn)
  4051. {
  4052. char buf[MG_BUF_LEN];
  4053. size_t to_read;
  4054. int nread;
  4055. if (conn == NULL) {
  4056. return;
  4057. }
  4058. to_read = sizeof(buf);
  4059. if (conn->is_chunked) {
  4060. /* Chunked encoding: 1=chunk not read completely, 2=chunk read
  4061. * completely */
  4062. while (conn->is_chunked == 1) {
  4063. nread = mg_read(conn, buf, to_read);
  4064. if (nread <= 0) {
  4065. break;
  4066. }
  4067. }
  4068. } else {
  4069. /* Not chunked: content length is known */
  4070. while (conn->consumed_content < conn->content_len) {
  4071. if (to_read
  4072. > (size_t)(conn->content_len - conn->consumed_content)) {
  4073. to_read = (size_t)(conn->content_len - conn->consumed_content);
  4074. }
  4075. nread = mg_read(conn, buf, to_read);
  4076. if (nread <= 0) {
  4077. break;
  4078. }
  4079. }
  4080. }
  4081. }
  4082. static int
  4083. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  4084. {
  4085. int64_t n, buffered_len, nread;
  4086. int64_t len64 =
  4087. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  4088. * int, we may not read more
  4089. * bytes */
  4090. const char *body;
  4091. if (conn == NULL) {
  4092. return 0;
  4093. }
  4094. /* If Content-Length is not set for a PUT or POST request, read until
  4095. * socket is closed */
  4096. if (conn->consumed_content == 0 && conn->content_len == -1) {
  4097. conn->content_len = INT64_MAX;
  4098. conn->must_close = 1;
  4099. }
  4100. nread = 0;
  4101. if (conn->consumed_content < conn->content_len) {
  4102. /* Adjust number of bytes to read. */
  4103. int64_t left_to_read = conn->content_len - conn->consumed_content;
  4104. if (left_to_read < len64) {
  4105. /* Do not read more than the total content length of the request.
  4106. */
  4107. len64 = left_to_read;
  4108. }
  4109. /* Return buffered data */
  4110. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  4111. - conn->consumed_content;
  4112. if (buffered_len > 0) {
  4113. if (len64 < buffered_len) {
  4114. buffered_len = len64;
  4115. }
  4116. body = conn->buf + conn->request_len + conn->consumed_content;
  4117. memcpy(buf, body, (size_t)buffered_len);
  4118. len64 -= buffered_len;
  4119. conn->consumed_content += buffered_len;
  4120. nread += buffered_len;
  4121. buf = (char *)buf + buffered_len;
  4122. }
  4123. /* We have returned all buffered data. Read new data from the remote
  4124. * socket.
  4125. */
  4126. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  4127. nread += n;
  4128. } else {
  4129. nread = ((nread > 0) ? nread : n);
  4130. }
  4131. }
  4132. return (int)nread;
  4133. }
  4134. static char
  4135. mg_getc(struct mg_connection *conn)
  4136. {
  4137. char c;
  4138. if (conn == NULL) {
  4139. return 0;
  4140. }
  4141. conn->content_len++;
  4142. if (mg_read_inner(conn, &c, 1) <= 0) {
  4143. return (char)0;
  4144. }
  4145. return c;
  4146. }
  4147. int
  4148. mg_read(struct mg_connection *conn, void *buf, size_t len)
  4149. {
  4150. if (len > INT_MAX) {
  4151. len = INT_MAX;
  4152. }
  4153. if (conn == NULL) {
  4154. return 0;
  4155. }
  4156. if (conn->is_chunked) {
  4157. size_t all_read = 0;
  4158. while (len > 0) {
  4159. if (conn->is_chunked == 2) {
  4160. /* No more data left to read */
  4161. return 0;
  4162. }
  4163. if (conn->chunk_remainder) {
  4164. /* copy from the remainder of the last received chunk */
  4165. long read_ret;
  4166. size_t read_now =
  4167. ((conn->chunk_remainder > len) ? (len)
  4168. : (conn->chunk_remainder));
  4169. conn->content_len += (int)read_now;
  4170. read_ret =
  4171. mg_read_inner(conn, (char *)buf + all_read, read_now);
  4172. if (read_ret < 1) {
  4173. /* read error */
  4174. return -1;
  4175. }
  4176. all_read += (size_t)read_ret;
  4177. conn->chunk_remainder -= (size_t)read_ret;
  4178. len -= (size_t)read_ret;
  4179. if (conn->chunk_remainder == 0) {
  4180. /* Add data bytes in the current chunk have been read,
  4181. * so we are expecting \r\n now. */
  4182. char x1 = mg_getc(conn);
  4183. char x2 = mg_getc(conn);
  4184. if ((x1 != '\r') || (x2 != '\n')) {
  4185. /* Protocol violation */
  4186. return -1;
  4187. }
  4188. }
  4189. } else {
  4190. /* fetch a new chunk */
  4191. int i = 0;
  4192. char lenbuf[64];
  4193. char *end = 0;
  4194. unsigned long chunkSize = 0;
  4195. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  4196. lenbuf[i] = mg_getc(conn);
  4197. if (i > 0 && lenbuf[i] == '\r' && lenbuf[i - 1] != '\r') {
  4198. continue;
  4199. }
  4200. if (i > 1 && lenbuf[i] == '\n' && lenbuf[i - 1] == '\r') {
  4201. lenbuf[i + 1] = 0;
  4202. chunkSize = strtoul(lenbuf, &end, 16);
  4203. if (chunkSize == 0) {
  4204. /* regular end of content */
  4205. conn->is_chunked = 2;
  4206. }
  4207. break;
  4208. }
  4209. if (!isxdigit(lenbuf[i])) {
  4210. /* illegal character for chunk length */
  4211. return -1;
  4212. }
  4213. }
  4214. if ((end == NULL) || (*end != '\r')) {
  4215. /* chunksize not set correctly */
  4216. return -1;
  4217. }
  4218. if (chunkSize == 0) {
  4219. break;
  4220. }
  4221. conn->chunk_remainder = chunkSize;
  4222. }
  4223. }
  4224. return (int)all_read;
  4225. }
  4226. return mg_read_inner(conn, buf, len);
  4227. }
  4228. int
  4229. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  4230. {
  4231. time_t now;
  4232. int64_t n, total, allowed;
  4233. if (conn == NULL) {
  4234. return 0;
  4235. }
  4236. if (conn->throttle > 0) {
  4237. if ((now = time(NULL)) != conn->last_throttle_time) {
  4238. conn->last_throttle_time = now;
  4239. conn->last_throttle_bytes = 0;
  4240. }
  4241. allowed = conn->throttle - conn->last_throttle_bytes;
  4242. if (allowed > (int64_t)len) {
  4243. allowed = (int64_t)len;
  4244. }
  4245. if ((total = push_all(conn->ctx,
  4246. NULL,
  4247. conn->client.sock,
  4248. conn->ssl,
  4249. (const char *)buf,
  4250. (int64_t)allowed)) == allowed) {
  4251. buf = (const char *)buf + total;
  4252. conn->last_throttle_bytes += total;
  4253. while (total < (int64_t)len && conn->ctx->stop_flag == 0) {
  4254. allowed = (conn->throttle > ((int64_t)len - total))
  4255. ? (int64_t)len - total
  4256. : conn->throttle;
  4257. if ((n = push_all(conn->ctx,
  4258. NULL,
  4259. conn->client.sock,
  4260. conn->ssl,
  4261. (const char *)buf,
  4262. (int64_t)allowed)) != allowed) {
  4263. break;
  4264. }
  4265. sleep(1);
  4266. conn->last_throttle_bytes = allowed;
  4267. conn->last_throttle_time = time(NULL);
  4268. buf = (const char *)buf + n;
  4269. total += n;
  4270. }
  4271. }
  4272. } else {
  4273. total = push_all(conn->ctx,
  4274. NULL,
  4275. conn->client.sock,
  4276. conn->ssl,
  4277. (const char *)buf,
  4278. (int64_t)len);
  4279. }
  4280. return (int)total;
  4281. }
  4282. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  4283. static int
  4284. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  4285. {
  4286. va_list ap_copy;
  4287. size_t size = MG_BUF_LEN / 4;
  4288. int len = -1;
  4289. *buf = NULL;
  4290. while (len < 0) {
  4291. if (*buf) {
  4292. mg_free(*buf);
  4293. }
  4294. size *= 4;
  4295. *buf = (char *)mg_malloc(size);
  4296. if (!*buf) {
  4297. break;
  4298. }
  4299. va_copy(ap_copy, ap);
  4300. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  4301. va_end(ap_copy);
  4302. (*buf)[size - 1] = 0;
  4303. }
  4304. return len;
  4305. }
  4306. /* Print message to buffer. If buffer is large enough to hold the message,
  4307. * return buffer. If buffer is to small, allocate large enough buffer on heap,
  4308. * and return allocated buffer. */
  4309. static int
  4310. alloc_vprintf(char **out_buf,
  4311. char *prealloc_buf,
  4312. size_t prealloc_size,
  4313. const char *fmt,
  4314. va_list ap)
  4315. {
  4316. va_list ap_copy;
  4317. int len;
  4318. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  4319. * buffer is too small. Also, older versions of msvcrt.dll do not have
  4320. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  4321. * Therefore, we make two passes: on first pass, get required message
  4322. * length.
  4323. * On second pass, actually print the message. */
  4324. va_copy(ap_copy, ap);
  4325. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  4326. va_end(ap_copy);
  4327. if (len < 0) {
  4328. /* C runtime is not standard compliant, vsnprintf() returned -1.
  4329. * Switch to alternative code path that uses incremental allocations.
  4330. */
  4331. va_copy(ap_copy, ap);
  4332. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  4333. va_end(ap_copy);
  4334. } else if ((size_t)(len) >= prealloc_size) {
  4335. /* The pre-allocated buffer not large enough. */
  4336. /* Allocate a new buffer. */
  4337. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  4338. if (!*out_buf) {
  4339. /* Allocation failed. Return -1 as "out of memory" error. */
  4340. return -1;
  4341. }
  4342. /* Buffer allocation successful. Store the string there. */
  4343. va_copy(ap_copy, ap);
  4344. IGNORE_UNUSED_RESULT(
  4345. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  4346. va_end(ap_copy);
  4347. } else {
  4348. /* The pre-allocated buffer is large enough.
  4349. * Use it to store the string and return the address. */
  4350. va_copy(ap_copy, ap);
  4351. IGNORE_UNUSED_RESULT(
  4352. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  4353. va_end(ap_copy);
  4354. *out_buf = prealloc_buf;
  4355. }
  4356. return len;
  4357. }
  4358. static int
  4359. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  4360. {
  4361. char mem[MG_BUF_LEN];
  4362. char *buf = NULL;
  4363. int len;
  4364. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  4365. len = mg_write(conn, buf, (size_t)len);
  4366. }
  4367. if (buf != mem && buf != NULL) {
  4368. mg_free(buf);
  4369. }
  4370. return len;
  4371. }
  4372. int
  4373. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  4374. {
  4375. va_list ap;
  4376. int result;
  4377. va_start(ap, fmt);
  4378. result = mg_vprintf(conn, fmt, ap);
  4379. va_end(ap);
  4380. return result;
  4381. }
  4382. int
  4383. mg_url_decode(const char *src,
  4384. int src_len,
  4385. char *dst,
  4386. int dst_len,
  4387. int is_form_url_encoded)
  4388. {
  4389. int i, j, a, b;
  4390. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  4391. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  4392. if (i < src_len - 2 && src[i] == '%'
  4393. && isxdigit(*(const unsigned char *)(src + i + 1))
  4394. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  4395. a = tolower(*(const unsigned char *)(src + i + 1));
  4396. b = tolower(*(const unsigned char *)(src + i + 2));
  4397. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  4398. i += 2;
  4399. } else if (is_form_url_encoded && src[i] == '+') {
  4400. dst[j] = ' ';
  4401. } else {
  4402. dst[j] = src[i];
  4403. }
  4404. }
  4405. dst[j] = '\0'; /* Null-terminate the destination */
  4406. return (i >= src_len) ? j : -1;
  4407. }
  4408. int
  4409. mg_get_var(const char *data,
  4410. size_t data_len,
  4411. const char *name,
  4412. char *dst,
  4413. size_t dst_len)
  4414. {
  4415. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  4416. }
  4417. int
  4418. mg_get_var2(const char *data,
  4419. size_t data_len,
  4420. const char *name,
  4421. char *dst,
  4422. size_t dst_len,
  4423. size_t occurrence)
  4424. {
  4425. const char *p, *e, *s;
  4426. size_t name_len;
  4427. int len;
  4428. if (dst == NULL || dst_len == 0) {
  4429. len = -2;
  4430. } else if (data == NULL || name == NULL || data_len == 0) {
  4431. len = -1;
  4432. dst[0] = '\0';
  4433. } else {
  4434. name_len = strlen(name);
  4435. e = data + data_len;
  4436. len = -1;
  4437. dst[0] = '\0';
  4438. /* data is "var1=val1&var2=val2...". Find variable first */
  4439. for (p = data; p + name_len < e; p++) {
  4440. if ((p == data || p[-1] == '&') && p[name_len] == '='
  4441. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  4442. /* Point p to variable value */
  4443. p += name_len + 1;
  4444. /* Point s to the end of the value */
  4445. s = (const char *)memchr(p, '&', (size_t)(e - p));
  4446. if (s == NULL) {
  4447. s = e;
  4448. }
  4449. /* assert(s >= p); */
  4450. if (s < p) {
  4451. return -3;
  4452. }
  4453. /* Decode variable into destination buffer */
  4454. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  4455. /* Redirect error code from -1 to -2 (destination buffer too
  4456. * small). */
  4457. if (len == -1) {
  4458. len = -2;
  4459. }
  4460. break;
  4461. }
  4462. }
  4463. }
  4464. return len;
  4465. }
  4466. /* HCP24: some changes to compare hole var_name */
  4467. int
  4468. mg_get_cookie(const char *cookie_header,
  4469. const char *var_name,
  4470. char *dst,
  4471. size_t dst_size)
  4472. {
  4473. const char *s, *p, *end;
  4474. int name_len, len = -1;
  4475. if (dst == NULL || dst_size == 0) {
  4476. return -2;
  4477. }
  4478. dst[0] = '\0';
  4479. if (var_name == NULL || (s = cookie_header) == NULL) {
  4480. return -1;
  4481. }
  4482. name_len = (int)strlen(var_name);
  4483. end = s + strlen(s);
  4484. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  4485. if (s[name_len] == '=') {
  4486. /* HCP24: now check is it a substring or a full cookie name */
  4487. if ((s == cookie_header) || (s[-1] == ' ')) {
  4488. s += name_len + 1;
  4489. if ((p = strchr(s, ' ')) == NULL) {
  4490. p = end;
  4491. }
  4492. if (p[-1] == ';') {
  4493. p--;
  4494. }
  4495. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  4496. s++;
  4497. p--;
  4498. }
  4499. if ((size_t)(p - s) < dst_size) {
  4500. len = (int)(p - s);
  4501. mg_strlcpy(dst, s, (size_t)len + 1);
  4502. } else {
  4503. len = -3;
  4504. }
  4505. break;
  4506. }
  4507. }
  4508. }
  4509. return len;
  4510. }
  4511. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  4512. static void
  4513. base64_encode(const unsigned char *src, int src_len, char *dst)
  4514. {
  4515. static const char *b64 =
  4516. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  4517. int i, j, a, b, c;
  4518. for (i = j = 0; i < src_len; i += 3) {
  4519. a = src[i];
  4520. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  4521. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  4522. dst[j++] = b64[a >> 2];
  4523. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  4524. if (i + 1 < src_len) {
  4525. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  4526. }
  4527. if (i + 2 < src_len) {
  4528. dst[j++] = b64[c & 63];
  4529. }
  4530. }
  4531. while (j % 4 != 0) {
  4532. dst[j++] = '=';
  4533. }
  4534. dst[j++] = '\0';
  4535. }
  4536. #endif
  4537. #if defined(USE_LUA)
  4538. static unsigned char
  4539. b64reverse(char letter)
  4540. {
  4541. if (letter >= 'A' && letter <= 'Z') {
  4542. return letter - 'A';
  4543. }
  4544. if (letter >= 'a' && letter <= 'z') {
  4545. return letter - 'a' + 26;
  4546. }
  4547. if (letter >= '0' && letter <= '9') {
  4548. return letter - '0' + 52;
  4549. }
  4550. if (letter == '+') {
  4551. return 62;
  4552. }
  4553. if (letter == '/') {
  4554. return 63;
  4555. }
  4556. if (letter == '=') {
  4557. return 255; /* normal end */
  4558. }
  4559. return 254; /* error */
  4560. }
  4561. static int
  4562. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  4563. {
  4564. int i;
  4565. unsigned char a, b, c, d;
  4566. *dst_len = 0;
  4567. for (i = 0; i < src_len; i += 4) {
  4568. a = b64reverse(src[i]);
  4569. if (a >= 254) {
  4570. return i;
  4571. }
  4572. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  4573. if (b >= 254) {
  4574. return i + 1;
  4575. }
  4576. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  4577. if (c == 254) {
  4578. return i + 2;
  4579. }
  4580. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  4581. if (d == 254) {
  4582. return i + 3;
  4583. }
  4584. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  4585. if (c != 255) {
  4586. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  4587. if (d != 255) {
  4588. dst[(*dst_len)++] = (c << 6) + d;
  4589. }
  4590. }
  4591. }
  4592. return -1;
  4593. }
  4594. #endif
  4595. static int
  4596. is_put_or_delete_method(const struct mg_connection *conn)
  4597. {
  4598. if (conn) {
  4599. const char *s = conn->request_info.request_method;
  4600. return s != NULL && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  4601. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  4602. }
  4603. return 0;
  4604. }
  4605. static void
  4606. interpret_uri(struct mg_connection *conn, /* in: request (must be valid) */
  4607. char *filename, /* out: filename */
  4608. size_t filename_buf_len, /* in: size of filename buffer */
  4609. struct mg_file_stat *filestat, /* out: file structure */
  4610. int *is_found, /* out: file found (directly) */
  4611. int *is_script_resource, /* out: handled by a script? */
  4612. int *is_websocket_request, /* out: websocket connetion? */
  4613. int *is_put_or_delete_request /* out: put/delete a file? */
  4614. )
  4615. {
  4616. /* TODO (high): Restructure this function */
  4617. #if !defined(NO_FILES)
  4618. const char *uri = conn->request_info.local_uri;
  4619. const char *root = conn->ctx->config[DOCUMENT_ROOT];
  4620. const char *rewrite;
  4621. struct vec a, b;
  4622. int match_len;
  4623. char gz_path[PATH_MAX];
  4624. char const *accept_encoding;
  4625. int truncated;
  4626. #if !defined(NO_CGI) || defined(USE_LUA)
  4627. char *p;
  4628. #endif
  4629. #else
  4630. (void)filename_buf_len; /* unused if NO_FILES is defined */
  4631. #endif
  4632. memset(filestat, 0, sizeof(*filestat));
  4633. *filename = 0;
  4634. *is_found = 0;
  4635. *is_script_resource = 0;
  4636. *is_put_or_delete_request = is_put_or_delete_method(conn);
  4637. #if defined(USE_WEBSOCKET)
  4638. *is_websocket_request = is_websocket_protocol(conn);
  4639. #if !defined(NO_FILES)
  4640. if (*is_websocket_request && conn->ctx->config[WEBSOCKET_ROOT]) {
  4641. root = conn->ctx->config[WEBSOCKET_ROOT];
  4642. }
  4643. #endif /* !NO_FILES */
  4644. #else /* USE_WEBSOCKET */
  4645. *is_websocket_request = 0;
  4646. #endif /* USE_WEBSOCKET */
  4647. #if !defined(NO_FILES)
  4648. /* Note that root == NULL is a regular use case here. This occurs,
  4649. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  4650. * config is not required. */
  4651. if (root == NULL) {
  4652. /* all file related outputs have already been set to 0, just return
  4653. */
  4654. return;
  4655. }
  4656. /* Using buf_len - 1 because memmove() for PATH_INFO may shift part
  4657. * of the path one byte on the right.
  4658. * If document_root is NULL, leave the file empty. */
  4659. mg_snprintf(
  4660. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  4661. if (truncated) {
  4662. goto interpret_cleanup;
  4663. }
  4664. rewrite = conn->ctx->config[REWRITE];
  4665. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  4666. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  4667. mg_snprintf(conn,
  4668. &truncated,
  4669. filename,
  4670. filename_buf_len - 1,
  4671. "%.*s%s",
  4672. (int)b.len,
  4673. b.ptr,
  4674. uri + match_len);
  4675. break;
  4676. }
  4677. }
  4678. if (truncated) {
  4679. goto interpret_cleanup;
  4680. }
  4681. /* Local file path and name, corresponding to requested URI
  4682. * is now stored in "filename" variable. */
  4683. if (mg_stat(conn, filename, filestat)) {
  4684. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4685. /* File exists. Check if it is a script type. */
  4686. if (0
  4687. #if !defined(NO_CGI)
  4688. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4689. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4690. filename) > 0
  4691. #endif
  4692. #if defined(USE_LUA)
  4693. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4694. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4695. filename) > 0
  4696. #endif
  4697. #if defined(USE_DUKTAPE)
  4698. || match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4699. strlen(
  4700. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4701. filename) > 0
  4702. #endif
  4703. ) {
  4704. /* The request addresses a CGI script or a Lua script. The URI
  4705. * corresponds to the script itself (like /path/script.cgi),
  4706. * and there is no additional resource path
  4707. * (like /path/script.cgi/something).
  4708. * Requests that modify (replace or delete) a resource, like
  4709. * PUT and DELETE requests, should replace/delete the script
  4710. * file.
  4711. * Requests that read or write from/to a resource, like GET and
  4712. * POST requests, should call the script and return the
  4713. * generated response. */
  4714. *is_script_resource = !*is_put_or_delete_request;
  4715. }
  4716. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4717. *is_found = 1;
  4718. return;
  4719. }
  4720. /* If we can't find the actual file, look for the file
  4721. * with the same name but a .gz extension. If we find it,
  4722. * use that and set the gzipped flag in the file struct
  4723. * to indicate that the response need to have the content-
  4724. * encoding: gzip header.
  4725. * We can only do this if the browser declares support. */
  4726. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  4727. if (strstr(accept_encoding, "gzip") != NULL) {
  4728. mg_snprintf(
  4729. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  4730. if (truncated) {
  4731. goto interpret_cleanup;
  4732. }
  4733. if (mg_stat(conn, gz_path, filestat)) {
  4734. if (filestat) {
  4735. filestat->is_gzipped = 1;
  4736. *is_found = 1;
  4737. }
  4738. /* Currently gz files can not be scripts. */
  4739. return;
  4740. }
  4741. }
  4742. }
  4743. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  4744. /* Support PATH_INFO for CGI scripts. */
  4745. for (p = filename + strlen(filename); p > filename + 1; p--) {
  4746. if (*p == '/') {
  4747. *p = '\0';
  4748. if ((0
  4749. #if !defined(NO_CGI)
  4750. || match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  4751. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  4752. filename) > 0
  4753. #endif
  4754. #if defined(USE_LUA)
  4755. || match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  4756. strlen(
  4757. conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  4758. filename) > 0
  4759. #endif
  4760. #if defined(USE_DUKTAPE)
  4761. || match_prefix(
  4762. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  4763. strlen(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  4764. filename) > 0
  4765. #endif
  4766. ) && mg_stat(conn, filename, filestat)) {
  4767. /* Shift PATH_INFO block one character right, e.g.
  4768. * "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  4769. * conn->path_info is pointing to the local variable "path"
  4770. * declared in handle_request(), so PATH_INFO is not valid
  4771. * after handle_request returns. */
  4772. conn->path_info = p + 1;
  4773. memmove(p + 2, p + 1, strlen(p + 1) + 1); /* +1 is for
  4774. * trailing \0 */
  4775. p[1] = '/';
  4776. *is_script_resource = 1;
  4777. break;
  4778. } else {
  4779. *p = '/';
  4780. }
  4781. }
  4782. }
  4783. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  4784. #endif /* !defined(NO_FILES) */
  4785. return;
  4786. #if !defined(NO_FILES)
  4787. /* Reset all outputs */
  4788. interpret_cleanup:
  4789. memset(filestat, 0, sizeof(*filestat));
  4790. *filename = 0;
  4791. *is_found = 0;
  4792. *is_script_resource = 0;
  4793. *is_websocket_request = 0;
  4794. *is_put_or_delete_request = 0;
  4795. #endif /* !defined(NO_FILES) */
  4796. }
  4797. /* Check whether full request is buffered. Return:
  4798. * -1 if request is malformed
  4799. * 0 if request is not yet fully buffered
  4800. * >0 actual request length, including last \r\n\r\n */
  4801. static int
  4802. get_request_len(const char *buf, int buflen)
  4803. {
  4804. const char *s, *e;
  4805. int len = 0;
  4806. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  4807. /* Control characters are not allowed but >=128 is. */
  4808. if (!isprint(*(const unsigned char *)s) && *s != '\r' && *s != '\n'
  4809. && *(const unsigned char *)s < 128) {
  4810. len = -1;
  4811. break; /* [i_a] abort scan as soon as one malformed character is
  4812. * found; */
  4813. /* don't let subsequent \r\n\r\n win us over anyhow */
  4814. } else if (s[0] == '\n' && s[1] == '\n') {
  4815. len = (int)(s - buf) + 2;
  4816. } else if (s[0] == '\n' && &s[1] < e && s[1] == '\r' && s[2] == '\n') {
  4817. len = (int)(s - buf) + 3;
  4818. }
  4819. return len;
  4820. }
  4821. #if !defined(NO_CACHING)
  4822. /* Convert month to the month number. Return -1 on error, or month number */
  4823. static int
  4824. get_month_index(const char *s)
  4825. {
  4826. size_t i;
  4827. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  4828. if (!strcmp(s, month_names[i])) {
  4829. return (int)i;
  4830. }
  4831. }
  4832. return -1;
  4833. }
  4834. /* Parse UTC date-time string, and return the corresponding time_t value. */
  4835. static time_t
  4836. parse_date_string(const char *datetime)
  4837. {
  4838. char month_str[32] = {0};
  4839. int second, minute, hour, day, month, year;
  4840. time_t result = (time_t)0;
  4841. struct tm tm;
  4842. if ((sscanf(datetime,
  4843. "%d/%3s/%d %d:%d:%d",
  4844. &day,
  4845. month_str,
  4846. &year,
  4847. &hour,
  4848. &minute,
  4849. &second) == 6) || (sscanf(datetime,
  4850. "%d %3s %d %d:%d:%d",
  4851. &day,
  4852. month_str,
  4853. &year,
  4854. &hour,
  4855. &minute,
  4856. &second) == 6)
  4857. || (sscanf(datetime,
  4858. "%*3s, %d %3s %d %d:%d:%d",
  4859. &day,
  4860. month_str,
  4861. &year,
  4862. &hour,
  4863. &minute,
  4864. &second) == 6) || (sscanf(datetime,
  4865. "%d-%3s-%d %d:%d:%d",
  4866. &day,
  4867. month_str,
  4868. &year,
  4869. &hour,
  4870. &minute,
  4871. &second) == 6)) {
  4872. month = get_month_index(month_str);
  4873. if ((month >= 0) && (year >= 1970)) {
  4874. memset(&tm, 0, sizeof(tm));
  4875. tm.tm_year = year - 1900;
  4876. tm.tm_mon = month;
  4877. tm.tm_mday = day;
  4878. tm.tm_hour = hour;
  4879. tm.tm_min = minute;
  4880. tm.tm_sec = second;
  4881. result = timegm(&tm);
  4882. }
  4883. }
  4884. return result;
  4885. }
  4886. #endif /* !NO_CACHING */
  4887. /* Protect against directory disclosure attack by removing '..',
  4888. * excessive '/' and '\' characters */
  4889. static void
  4890. remove_double_dots_and_double_slashes(char *s)
  4891. {
  4892. char *p = s;
  4893. while ((s[0] == '.') && (s[1] == '.')) {
  4894. s++;
  4895. }
  4896. while (*s != '\0') {
  4897. *p++ = *s++;
  4898. if (s[-1] == '/' || s[-1] == '\\') {
  4899. /* Skip all following slashes, backslashes and double-dots */
  4900. while (s[0] != '\0') {
  4901. if (s[0] == '/' || s[0] == '\\') {
  4902. s++;
  4903. } else if (s[0] == '.' && s[1] == '.') {
  4904. s += 2;
  4905. } else {
  4906. break;
  4907. }
  4908. }
  4909. }
  4910. }
  4911. *p = '\0';
  4912. }
  4913. static const struct {
  4914. const char *extension;
  4915. size_t ext_len;
  4916. const char *mime_type;
  4917. } builtin_mime_types[] = {
  4918. /* IANA registered MIME types (http://www.iana.org/assignments/media-types)
  4919. * application types */
  4920. {".doc", 4, "application/msword"},
  4921. {".eps", 4, "application/postscript"},
  4922. {".exe", 4, "application/octet-stream"},
  4923. {".js", 3, "application/javascript"},
  4924. {".json", 5, "application/json"},
  4925. {".pdf", 4, "application/pdf"},
  4926. {".ps", 3, "application/postscript"},
  4927. {".rtf", 4, "application/rtf"},
  4928. {".xhtml", 6, "application/xhtml+xml"},
  4929. {".xsl", 4, "application/xml"},
  4930. {".xslt", 5, "application/xml"},
  4931. /* fonts */
  4932. {".ttf", 4, "application/font-sfnt"},
  4933. {".cff", 4, "application/font-sfnt"},
  4934. {".otf", 4, "application/font-sfnt"},
  4935. {".aat", 4, "application/font-sfnt"},
  4936. {".sil", 4, "application/font-sfnt"},
  4937. {".pfr", 4, "application/font-tdpfr"},
  4938. {".woff", 5, "application/font-woff"},
  4939. /* audio */
  4940. {".mp3", 4, "audio/mpeg"},
  4941. {".oga", 4, "audio/ogg"},
  4942. {".ogg", 4, "audio/ogg"},
  4943. /* image */
  4944. {".gif", 4, "image/gif"},
  4945. {".ief", 4, "image/ief"},
  4946. {".jpeg", 5, "image/jpeg"},
  4947. {".jpg", 4, "image/jpeg"},
  4948. {".jpm", 4, "image/jpm"},
  4949. {".jpx", 4, "image/jpx"},
  4950. {".png", 4, "image/png"},
  4951. {".svg", 4, "image/svg+xml"},
  4952. {".tif", 4, "image/tiff"},
  4953. {".tiff", 5, "image/tiff"},
  4954. /* model */
  4955. {".wrl", 4, "model/vrml"},
  4956. /* text */
  4957. {".css", 4, "text/css"},
  4958. {".csv", 4, "text/csv"},
  4959. {".htm", 4, "text/html"},
  4960. {".html", 5, "text/html"},
  4961. {".sgm", 4, "text/sgml"},
  4962. {".shtm", 5, "text/html"},
  4963. {".shtml", 6, "text/html"},
  4964. {".txt", 4, "text/plain"},
  4965. {".xml", 4, "text/xml"},
  4966. /* video */
  4967. {".mov", 4, "video/quicktime"},
  4968. {".mp4", 4, "video/mp4"},
  4969. {".mpeg", 5, "video/mpeg"},
  4970. {".mpg", 4, "video/mpeg"},
  4971. {".ogv", 4, "video/ogg"},
  4972. {".qt", 3, "video/quicktime"},
  4973. /* not registered types
  4974. * (http://reference.sitepoint.com/html/mime-types-full,
  4975. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  4976. {".arj", 4, "application/x-arj-compressed"},
  4977. {".gz", 3, "application/x-gunzip"},
  4978. {".rar", 4, "application/x-arj-compressed"},
  4979. {".swf", 4, "application/x-shockwave-flash"},
  4980. {".tar", 4, "application/x-tar"},
  4981. {".tgz", 4, "application/x-tar-gz"},
  4982. {".torrent", 8, "application/x-bittorrent"},
  4983. {".ppt", 4, "application/x-mspowerpoint"},
  4984. {".xls", 4, "application/x-msexcel"},
  4985. {".zip", 4, "application/x-zip-compressed"},
  4986. {".aac",
  4987. 4,
  4988. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  4989. {".aif", 4, "audio/x-aif"},
  4990. {".m3u", 4, "audio/x-mpegurl"},
  4991. {".mid", 4, "audio/x-midi"},
  4992. {".ra", 3, "audio/x-pn-realaudio"},
  4993. {".ram", 4, "audio/x-pn-realaudio"},
  4994. {".wav", 4, "audio/x-wav"},
  4995. {".bmp", 4, "image/bmp"},
  4996. {".ico", 4, "image/x-icon"},
  4997. {".pct", 4, "image/x-pct"},
  4998. {".pict", 5, "image/pict"},
  4999. {".rgb", 4, "image/x-rgb"},
  5000. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  5001. {".asf", 4, "video/x-ms-asf"},
  5002. {".avi", 4, "video/x-msvideo"},
  5003. {".m4v", 4, "video/x-m4v"},
  5004. {NULL, 0, NULL}};
  5005. const char *
  5006. mg_get_builtin_mime_type(const char *path)
  5007. {
  5008. const char *ext;
  5009. size_t i, path_len;
  5010. path_len = strlen(path);
  5011. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  5012. ext = path + (path_len - builtin_mime_types[i].ext_len);
  5013. if (path_len > builtin_mime_types[i].ext_len
  5014. && mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  5015. return builtin_mime_types[i].mime_type;
  5016. }
  5017. }
  5018. return "text/plain";
  5019. }
  5020. /* Look at the "path" extension and figure what mime type it has.
  5021. * Store mime type in the vector. */
  5022. static void
  5023. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  5024. {
  5025. struct vec ext_vec, mime_vec;
  5026. const char *list, *ext;
  5027. size_t path_len;
  5028. path_len = strlen(path);
  5029. if (ctx == NULL || vec == NULL) {
  5030. return;
  5031. }
  5032. /* Scan user-defined mime types first, in case user wants to
  5033. * override default mime types. */
  5034. list = ctx->config[EXTRA_MIME_TYPES];
  5035. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  5036. /* ext now points to the path suffix */
  5037. ext = path + path_len - ext_vec.len;
  5038. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  5039. *vec = mime_vec;
  5040. return;
  5041. }
  5042. }
  5043. vec->ptr = mg_get_builtin_mime_type(path);
  5044. vec->len = strlen(vec->ptr);
  5045. }
  5046. /* Stringify binary data. Output buffer must be twice as big as input,
  5047. * because each byte takes 2 bytes in string representation */
  5048. static void
  5049. bin2str(char *to, const unsigned char *p, size_t len)
  5050. {
  5051. static const char *hex = "0123456789abcdef";
  5052. for (; len--; p++) {
  5053. *to++ = hex[p[0] >> 4];
  5054. *to++ = hex[p[0] & 0x0f];
  5055. }
  5056. *to = '\0';
  5057. }
  5058. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */
  5059. char *
  5060. mg_md5(char buf[33], ...)
  5061. {
  5062. md5_byte_t hash[16];
  5063. const char *p;
  5064. va_list ap;
  5065. md5_state_t ctx;
  5066. md5_init(&ctx);
  5067. va_start(ap, buf);
  5068. while ((p = va_arg(ap, const char *)) != NULL) {
  5069. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  5070. }
  5071. va_end(ap);
  5072. md5_finish(&ctx, hash);
  5073. bin2str(buf, hash, sizeof(hash));
  5074. return buf;
  5075. }
  5076. /* Check the user's password, return 1 if OK */
  5077. static int
  5078. check_password(const char *method,
  5079. const char *ha1,
  5080. const char *uri,
  5081. const char *nonce,
  5082. const char *nc,
  5083. const char *cnonce,
  5084. const char *qop,
  5085. const char *response)
  5086. {
  5087. char ha2[32 + 1], expected_response[32 + 1];
  5088. /* Some of the parameters may be NULL */
  5089. if (method == NULL || nonce == NULL || nc == NULL || cnonce == NULL
  5090. || qop == NULL
  5091. || response == NULL) {
  5092. return 0;
  5093. }
  5094. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  5095. if (strlen(response) != 32) {
  5096. return 0;
  5097. }
  5098. mg_md5(ha2, method, ":", uri, NULL);
  5099. mg_md5(expected_response,
  5100. ha1,
  5101. ":",
  5102. nonce,
  5103. ":",
  5104. nc,
  5105. ":",
  5106. cnonce,
  5107. ":",
  5108. qop,
  5109. ":",
  5110. ha2,
  5111. NULL);
  5112. return mg_strcasecmp(response, expected_response) == 0;
  5113. }
  5114. /* Use the global passwords file, if specified by auth_gpass option,
  5115. * or search for .htpasswd in the requested directory. */
  5116. static void
  5117. open_auth_file(struct mg_connection *conn,
  5118. const char *path,
  5119. struct mg_file *filep)
  5120. {
  5121. if (conn != NULL && conn->ctx != NULL) {
  5122. char name[PATH_MAX];
  5123. const char *p, *e, *gpass = conn->ctx->config[GLOBAL_PASSWORDS_FILE];
  5124. int truncated;
  5125. if (gpass != NULL) {
  5126. /* Use global passwords file */
  5127. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  5128. #ifdef DEBUG
  5129. /* Use mg_cry here, since gpass has been configured. */
  5130. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  5131. #endif
  5132. }
  5133. /* Important: using local struct mg_file to test path for
  5134. * is_directory
  5135. * flag. If filep is used, mg_stat() makes it appear as if auth file
  5136. * was opened. TODO: mg_stat must not make anything appear to be
  5137. * opened */
  5138. } else if (mg_stat(conn, path, &filep->stat)
  5139. && filep->stat.is_directory) {
  5140. mg_snprintf(conn,
  5141. &truncated,
  5142. name,
  5143. sizeof(name),
  5144. "%s/%s",
  5145. path,
  5146. PASSWORDS_FILE_NAME);
  5147. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5148. #ifdef DEBUG
  5149. /* Don't use mg_cry here, but only a trace, since this is
  5150. * a typical case. It will occur for every directory
  5151. * without a password file. */
  5152. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5153. #endif
  5154. }
  5155. } else {
  5156. /* Try to find .htpasswd in requested directory. */
  5157. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  5158. if (e[0] == '/') {
  5159. break;
  5160. }
  5161. }
  5162. mg_snprintf(conn,
  5163. &truncated,
  5164. name,
  5165. sizeof(name),
  5166. "%.*s/%s",
  5167. (int)(e - p),
  5168. p,
  5169. PASSWORDS_FILE_NAME);
  5170. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  5171. #ifdef DEBUG
  5172. /* Don't use mg_cry here, but only a trace, since this is
  5173. * a typical case. It will occur for every directory
  5174. * without a password file. */
  5175. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  5176. #endif
  5177. }
  5178. }
  5179. }
  5180. }
  5181. /* Parsed Authorization header */
  5182. struct ah {
  5183. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  5184. };
  5185. /* Return 1 on success. Always initializes the ah structure. */
  5186. static int
  5187. parse_auth_header(struct mg_connection *conn,
  5188. char *buf,
  5189. size_t buf_size,
  5190. struct ah *ah)
  5191. {
  5192. char *name, *value, *s;
  5193. const char *auth_header;
  5194. uint64_t nonce;
  5195. if (!ah || !conn) {
  5196. return 0;
  5197. }
  5198. (void)memset(ah, 0, sizeof(*ah));
  5199. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL
  5200. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  5201. return 0;
  5202. }
  5203. /* Make modifiable copy of the auth header */
  5204. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  5205. s = buf;
  5206. /* Parse authorization header */
  5207. for (;;) {
  5208. /* Gobble initial spaces */
  5209. while (isspace(*(unsigned char *)s)) {
  5210. s++;
  5211. }
  5212. name = skip_quoted(&s, "=", " ", 0);
  5213. /* Value is either quote-delimited, or ends at first comma or space. */
  5214. if (s[0] == '\"') {
  5215. s++;
  5216. value = skip_quoted(&s, "\"", " ", '\\');
  5217. if (s[0] == ',') {
  5218. s++;
  5219. }
  5220. } else {
  5221. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  5222. * spaces */
  5223. }
  5224. if (*name == '\0') {
  5225. break;
  5226. }
  5227. if (!strcmp(name, "username")) {
  5228. ah->user = value;
  5229. } else if (!strcmp(name, "cnonce")) {
  5230. ah->cnonce = value;
  5231. } else if (!strcmp(name, "response")) {
  5232. ah->response = value;
  5233. } else if (!strcmp(name, "uri")) {
  5234. ah->uri = value;
  5235. } else if (!strcmp(name, "qop")) {
  5236. ah->qop = value;
  5237. } else if (!strcmp(name, "nc")) {
  5238. ah->nc = value;
  5239. } else if (!strcmp(name, "nonce")) {
  5240. ah->nonce = value;
  5241. }
  5242. }
  5243. #ifndef NO_NONCE_CHECK
  5244. /* Read the nonce from the response. */
  5245. if (ah->nonce == NULL) {
  5246. return 0;
  5247. }
  5248. s = NULL;
  5249. nonce = strtoull(ah->nonce, &s, 10);
  5250. if ((s == NULL) || (*s != 0)) {
  5251. return 0;
  5252. }
  5253. /* Convert the nonce from the client to a number. */
  5254. nonce ^= conn->ctx->auth_nonce_mask;
  5255. /* The converted number corresponds to the time the nounce has been
  5256. * created. This should not be earlier than the server start. */
  5257. /* Server side nonce check is valuable in all situations but one:
  5258. * if the server restarts frequently, but the client should not see
  5259. * that, so the server should accept nonces from previous starts. */
  5260. /* However, the reasonable default is to not accept a nonce from a
  5261. * previous start, so if anyone changed the access rights between
  5262. * two restarts, a new login is required. */
  5263. if (nonce < (uint64_t)conn->ctx->start_time) {
  5264. /* nonce is from a previous start of the server and no longer valid
  5265. * (replay attack?) */
  5266. return 0;
  5267. }
  5268. /* Check if the nonce is too high, so it has not (yet) been used by the
  5269. * server. */
  5270. if (nonce >= ((uint64_t)conn->ctx->start_time + conn->ctx->nonce_count)) {
  5271. return 0;
  5272. }
  5273. #else
  5274. (void)nonce;
  5275. #endif
  5276. /* CGI needs it as REMOTE_USER */
  5277. if (ah->user != NULL) {
  5278. conn->request_info.remote_user = mg_strdup(ah->user);
  5279. } else {
  5280. return 0;
  5281. }
  5282. return 1;
  5283. }
  5284. static const char *
  5285. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  5286. {
  5287. const char *eof;
  5288. size_t len;
  5289. const char *memend;
  5290. if (!filep) {
  5291. return NULL;
  5292. }
  5293. if (filep->access.membuf != NULL && *p != NULL) {
  5294. memend = (const char *)&filep->access.membuf[filep->stat.size];
  5295. /* Search for \n from p till the end of stream */
  5296. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  5297. if (eof != NULL) {
  5298. eof += 1; /* Include \n */
  5299. } else {
  5300. eof = memend; /* Copy remaining data */
  5301. }
  5302. len =
  5303. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  5304. memcpy(buf, *p, len);
  5305. buf[len] = '\0';
  5306. *p += len;
  5307. return len ? eof : NULL;
  5308. } else if (filep->access.fp != NULL) {
  5309. return fgets(buf, (int)size, filep->access.fp);
  5310. } else {
  5311. return NULL;
  5312. }
  5313. }
  5314. /* Define the initial recursion depth for procesesing htpasswd files that
  5315. * include other htpasswd
  5316. * (or even the same) files. It is not difficult to provide a file or files
  5317. * s.t. they force civetweb
  5318. * to infinitely recurse and then crash.
  5319. */
  5320. #define INITIAL_DEPTH 9
  5321. #if INITIAL_DEPTH <= 0
  5322. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  5323. #endif
  5324. struct read_auth_file_struct {
  5325. struct mg_connection *conn;
  5326. struct ah ah;
  5327. char *domain;
  5328. char buf[256 + 256 + 40];
  5329. char *f_user;
  5330. char *f_domain;
  5331. char *f_ha1;
  5332. };
  5333. static int
  5334. read_auth_file(struct mg_file *filep,
  5335. struct read_auth_file_struct *workdata,
  5336. int depth)
  5337. {
  5338. char *p;
  5339. int is_authorized = 0;
  5340. struct mg_file fp;
  5341. size_t l;
  5342. if (!filep || !workdata || 0 == depth) {
  5343. return 0;
  5344. }
  5345. /* Loop over passwords file */
  5346. p = (char *)filep->access.membuf;
  5347. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  5348. l = strlen(workdata->buf);
  5349. while (l > 0) {
  5350. if (isspace(workdata->buf[l - 1])
  5351. || iscntrl(workdata->buf[l - 1])) {
  5352. l--;
  5353. workdata->buf[l] = 0;
  5354. } else
  5355. break;
  5356. }
  5357. if (l < 1) {
  5358. continue;
  5359. }
  5360. workdata->f_user = workdata->buf;
  5361. if (workdata->f_user[0] == ':') {
  5362. /* user names may not contain a ':' and may not be empty,
  5363. * so lines starting with ':' may be used for a special purpose */
  5364. if (workdata->f_user[1] == '#') {
  5365. /* :# is a comment */
  5366. continue;
  5367. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  5368. if (mg_fopen(workdata->conn,
  5369. workdata->f_user + 9,
  5370. MG_FOPEN_MODE_READ,
  5371. &fp)) {
  5372. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  5373. (void)mg_fclose(
  5374. &fp.access); /* ignore error on read only file */
  5375. /* No need to continue processing files once we have a
  5376. * match, since nothing will reset it back
  5377. * to 0.
  5378. */
  5379. if (is_authorized) {
  5380. return is_authorized;
  5381. }
  5382. } else {
  5383. mg_cry(workdata->conn,
  5384. "%s: cannot open authorization file: %s",
  5385. __func__,
  5386. workdata->buf);
  5387. }
  5388. continue;
  5389. }
  5390. /* everything is invalid for the moment (might change in the
  5391. * future) */
  5392. mg_cry(workdata->conn,
  5393. "%s: syntax error in authorization file: %s",
  5394. __func__,
  5395. workdata->buf);
  5396. continue;
  5397. }
  5398. workdata->f_domain = strchr(workdata->f_user, ':');
  5399. if (workdata->f_domain == NULL) {
  5400. mg_cry(workdata->conn,
  5401. "%s: syntax error in authorization file: %s",
  5402. __func__,
  5403. workdata->buf);
  5404. continue;
  5405. }
  5406. *(workdata->f_domain) = 0;
  5407. (workdata->f_domain)++;
  5408. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  5409. if (workdata->f_ha1 == NULL) {
  5410. mg_cry(workdata->conn,
  5411. "%s: syntax error in authorization file: %s",
  5412. __func__,
  5413. workdata->buf);
  5414. continue;
  5415. }
  5416. *(workdata->f_ha1) = 0;
  5417. (workdata->f_ha1)++;
  5418. if (!strcmp(workdata->ah.user, workdata->f_user)
  5419. && !strcmp(workdata->domain, workdata->f_domain)) {
  5420. return check_password(workdata->conn->request_info.request_method,
  5421. workdata->f_ha1,
  5422. workdata->ah.uri,
  5423. workdata->ah.nonce,
  5424. workdata->ah.nc,
  5425. workdata->ah.cnonce,
  5426. workdata->ah.qop,
  5427. workdata->ah.response);
  5428. }
  5429. }
  5430. return is_authorized;
  5431. }
  5432. /* Authorize against the opened passwords file. Return 1 if authorized. */
  5433. static int
  5434. authorize(struct mg_connection *conn, struct mg_file *filep)
  5435. {
  5436. struct read_auth_file_struct workdata;
  5437. char buf[MG_BUF_LEN];
  5438. if (!conn || !conn->ctx) {
  5439. return 0;
  5440. }
  5441. memset(&workdata, 0, sizeof(workdata));
  5442. workdata.conn = conn;
  5443. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  5444. return 0;
  5445. }
  5446. workdata.domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  5447. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  5448. }
  5449. /* Return 1 if request is authorised, 0 otherwise. */
  5450. static int
  5451. check_authorization(struct mg_connection *conn, const char *path)
  5452. {
  5453. char fname[PATH_MAX];
  5454. struct vec uri_vec, filename_vec;
  5455. const char *list;
  5456. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5457. int authorized = 1, truncated;
  5458. if (!conn || !conn->ctx) {
  5459. return 0;
  5460. }
  5461. list = conn->ctx->config[PROTECT_URI];
  5462. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  5463. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  5464. mg_snprintf(conn,
  5465. &truncated,
  5466. fname,
  5467. sizeof(fname),
  5468. "%.*s",
  5469. (int)filename_vec.len,
  5470. filename_vec.ptr);
  5471. if (truncated
  5472. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  5473. mg_cry(conn,
  5474. "%s: cannot open %s: %s",
  5475. __func__,
  5476. fname,
  5477. strerror(errno));
  5478. }
  5479. break;
  5480. }
  5481. }
  5482. if (!is_file_opened(&file.access)) {
  5483. open_auth_file(conn, path, &file);
  5484. }
  5485. if (is_file_opened(&file.access)) {
  5486. authorized = authorize(conn, &file);
  5487. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5488. }
  5489. return authorized;
  5490. }
  5491. static void
  5492. send_authorization_request(struct mg_connection *conn)
  5493. {
  5494. char date[64];
  5495. time_t curtime = time(NULL);
  5496. if (conn && conn->ctx) {
  5497. uint64_t nonce = (uint64_t)(conn->ctx->start_time);
  5498. (void)pthread_mutex_lock(&conn->ctx->nonce_mutex);
  5499. nonce += conn->ctx->nonce_count;
  5500. ++conn->ctx->nonce_count;
  5501. (void)pthread_mutex_unlock(&conn->ctx->nonce_mutex);
  5502. nonce ^= conn->ctx->auth_nonce_mask;
  5503. conn->status_code = 401;
  5504. conn->must_close = 1;
  5505. gmt_time_string(date, sizeof(date), &curtime);
  5506. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  5507. send_no_cache_header(conn);
  5508. mg_printf(conn,
  5509. "Date: %s\r\n"
  5510. "Connection: %s\r\n"
  5511. "Content-Length: 0\r\n"
  5512. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  5513. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  5514. date,
  5515. suggest_connection_header(conn),
  5516. conn->ctx->config[AUTHENTICATION_DOMAIN],
  5517. nonce);
  5518. }
  5519. }
  5520. #if !defined(NO_FILES)
  5521. static int
  5522. is_authorized_for_put(struct mg_connection *conn)
  5523. {
  5524. if (conn) {
  5525. struct mg_file file = STRUCT_FILE_INITIALIZER;
  5526. const char *passfile = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE];
  5527. int ret = 0;
  5528. if (passfile != NULL
  5529. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  5530. ret = authorize(conn, &file);
  5531. (void)mg_fclose(&file.access); /* ignore error on read only file */
  5532. }
  5533. return ret;
  5534. }
  5535. return 0;
  5536. }
  5537. #endif
  5538. int
  5539. mg_modify_passwords_file(const char *fname,
  5540. const char *domain,
  5541. const char *user,
  5542. const char *pass)
  5543. {
  5544. int found, i;
  5545. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  5546. FILE *fp, *fp2;
  5547. found = 0;
  5548. fp = fp2 = NULL;
  5549. /* Regard empty password as no password - remove user record. */
  5550. if (pass != NULL && pass[0] == '\0') {
  5551. pass = NULL;
  5552. }
  5553. /* Other arguments must not be empty */
  5554. if (fname == NULL || domain == NULL || user == NULL) {
  5555. return 0;
  5556. }
  5557. /* Using the given file format, user name and domain must not contain ':'
  5558. */
  5559. if (strchr(user, ':') != NULL) {
  5560. return 0;
  5561. }
  5562. if (strchr(domain, ':') != NULL) {
  5563. return 0;
  5564. }
  5565. /* Do not allow control characters like newline in user name and domain.
  5566. * Do not allow excessively long names either. */
  5567. for (i = 0; i < 255 && user[i] != 0; i++) {
  5568. if (iscntrl(user[i])) {
  5569. return 0;
  5570. }
  5571. }
  5572. if (user[i]) {
  5573. return 0;
  5574. }
  5575. for (i = 0; i < 255 && domain[i] != 0; i++) {
  5576. if (iscntrl(domain[i])) {
  5577. return 0;
  5578. }
  5579. }
  5580. if (domain[i]) {
  5581. return 0;
  5582. }
  5583. /* The maximum length of the path to the password file is limited */
  5584. if ((strlen(fname) + 4) >= PATH_MAX) {
  5585. return 0;
  5586. }
  5587. /* Create a temporary file name. Length has been checked before. */
  5588. strcpy(tmp, fname);
  5589. strcat(tmp, ".tmp");
  5590. /* Create the file if does not exist */
  5591. /* Use of fopen here is OK, since fname is only ASCII */
  5592. if ((fp = fopen(fname, "a+")) != NULL) {
  5593. (void)fclose(fp);
  5594. }
  5595. /* Open the given file and temporary file */
  5596. if ((fp = fopen(fname, "r")) == NULL) {
  5597. return 0;
  5598. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  5599. fclose(fp);
  5600. return 0;
  5601. }
  5602. /* Copy the stuff to temporary file */
  5603. while (fgets(line, sizeof(line), fp) != NULL) {
  5604. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  5605. continue;
  5606. }
  5607. u[255] = 0;
  5608. d[255] = 0;
  5609. if (!strcmp(u, user) && !strcmp(d, domain)) {
  5610. found++;
  5611. if (pass != NULL) {
  5612. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5613. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5614. }
  5615. } else {
  5616. fprintf(fp2, "%s", line);
  5617. }
  5618. }
  5619. /* If new user, just add it */
  5620. if (!found && pass != NULL) {
  5621. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  5622. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  5623. }
  5624. /* Close files */
  5625. fclose(fp);
  5626. fclose(fp2);
  5627. /* Put the temp file in place of real file */
  5628. IGNORE_UNUSED_RESULT(remove(fname));
  5629. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  5630. return 1;
  5631. }
  5632. static int
  5633. is_valid_port(unsigned long port)
  5634. {
  5635. return port < 0xffff;
  5636. }
  5637. static int
  5638. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  5639. {
  5640. struct addrinfo hints, *res, *ressave;
  5641. int func_ret = 0;
  5642. int gai_ret;
  5643. memset(&hints, 0, sizeof(struct addrinfo));
  5644. hints.ai_family = af;
  5645. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  5646. if (gai_ret != 0) {
  5647. /* gai_strerror could be used to convert gai_ret to a string */
  5648. /* POSIX return values: see
  5649. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  5650. */
  5651. /* Windows return values: see
  5652. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  5653. */
  5654. return 0;
  5655. }
  5656. ressave = res;
  5657. while (res) {
  5658. if (dstlen >= res->ai_addrlen) {
  5659. memcpy(dst, res->ai_addr, res->ai_addrlen);
  5660. func_ret = 1;
  5661. }
  5662. res = res->ai_next;
  5663. }
  5664. freeaddrinfo(ressave);
  5665. return func_ret;
  5666. }
  5667. static int
  5668. connect_socket(struct mg_context *ctx /* may be NULL */,
  5669. const char *host,
  5670. int port,
  5671. int use_ssl,
  5672. char *ebuf,
  5673. size_t ebuf_len,
  5674. SOCKET *sock /* output: socket, must not be NULL */,
  5675. union usa *sa /* output: socket address, must not be NULL */
  5676. )
  5677. {
  5678. int ip_ver = 0;
  5679. *sock = INVALID_SOCKET;
  5680. memset(sa, 0, sizeof(*sa));
  5681. if (ebuf_len > 0) {
  5682. *ebuf = 0;
  5683. }
  5684. if (host == NULL) {
  5685. mg_snprintf(NULL,
  5686. NULL, /* No truncation check for ebuf */
  5687. ebuf,
  5688. ebuf_len,
  5689. "%s",
  5690. "NULL host");
  5691. return 0;
  5692. }
  5693. if (port < 0 || !is_valid_port((unsigned)port)) {
  5694. mg_snprintf(NULL,
  5695. NULL, /* No truncation check for ebuf */
  5696. ebuf,
  5697. ebuf_len,
  5698. "%s",
  5699. "invalid port");
  5700. return 0;
  5701. }
  5702. #if !defined(NO_SSL)
  5703. if (use_ssl && (SSLv23_client_method == NULL)) {
  5704. mg_snprintf(NULL,
  5705. NULL, /* No truncation check for ebuf */
  5706. ebuf,
  5707. ebuf_len,
  5708. "%s",
  5709. "SSL is not initialized");
  5710. return 0;
  5711. }
  5712. #else
  5713. (void)use_ssl;
  5714. #endif
  5715. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  5716. sa->sin.sin_port = htons((uint16_t)port);
  5717. ip_ver = 4;
  5718. #ifdef USE_IPV6
  5719. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  5720. sa->sin6.sin6_port = htons((uint16_t)port);
  5721. ip_ver = 6;
  5722. } else if (host[0] == '[') {
  5723. /* While getaddrinfo on Windows will work with [::1],
  5724. * getaddrinfo on Linux only works with ::1 (without []). */
  5725. size_t l = strlen(host + 1);
  5726. char *h = (l > 1) ? mg_strdup(host + 1) : NULL;
  5727. if (h) {
  5728. h[l - 1] = 0;
  5729. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  5730. sa->sin6.sin6_port = htons((uint16_t)port);
  5731. ip_ver = 6;
  5732. }
  5733. mg_free(h);
  5734. }
  5735. #endif
  5736. }
  5737. if (ip_ver == 0) {
  5738. mg_snprintf(NULL,
  5739. NULL, /* No truncation check for ebuf */
  5740. ebuf,
  5741. ebuf_len,
  5742. "%s",
  5743. "host not found");
  5744. return 0;
  5745. }
  5746. if (ip_ver == 4) {
  5747. *sock = socket(PF_INET, SOCK_STREAM, 0);
  5748. }
  5749. #ifdef USE_IPV6
  5750. else if (ip_ver == 6) {
  5751. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  5752. }
  5753. #endif
  5754. if (*sock == INVALID_SOCKET) {
  5755. mg_snprintf(NULL,
  5756. NULL, /* No truncation check for ebuf */
  5757. ebuf,
  5758. ebuf_len,
  5759. "socket(): %s",
  5760. strerror(ERRNO));
  5761. return 0;
  5762. }
  5763. set_close_on_exec(*sock, fc(ctx));
  5764. if ((ip_ver == 4)
  5765. && (connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin))
  5766. == 0)) {
  5767. /* connected with IPv4 */
  5768. set_blocking_mode(*sock, 0);
  5769. return 1;
  5770. }
  5771. #ifdef USE_IPV6
  5772. if ((ip_ver == 6)
  5773. && (connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6))
  5774. == 0)) {
  5775. /* connected with IPv6 */
  5776. set_blocking_mode(*sock, 0);
  5777. return 1;
  5778. }
  5779. #endif
  5780. /* Not connected */
  5781. mg_snprintf(NULL,
  5782. NULL, /* No truncation check for ebuf */
  5783. ebuf,
  5784. ebuf_len,
  5785. "connect(%s:%d): %s",
  5786. host,
  5787. port,
  5788. strerror(ERRNO));
  5789. closesocket(*sock);
  5790. *sock = INVALID_SOCKET;
  5791. return 0;
  5792. }
  5793. int
  5794. mg_url_encode(const char *src, char *dst, size_t dst_len)
  5795. {
  5796. static const char *dont_escape = "._-$,;~()";
  5797. static const char *hex = "0123456789abcdef";
  5798. char *pos = dst;
  5799. const char *end = dst + dst_len - 1;
  5800. for (; *src != '\0' && pos < end; src++, pos++) {
  5801. if (isalnum(*(const unsigned char *)src)
  5802. || strchr(dont_escape, *(const unsigned char *)src) != NULL) {
  5803. *pos = *src;
  5804. } else if (pos + 2 < end) {
  5805. pos[0] = '%';
  5806. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  5807. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  5808. pos += 2;
  5809. } else {
  5810. break;
  5811. }
  5812. }
  5813. *pos = '\0';
  5814. return (*src == '\0') ? (int)(pos - dst) : -1;
  5815. }
  5816. static void
  5817. print_dir_entry(struct de *de)
  5818. {
  5819. char size[64], mod[64], href[PATH_MAX * 3 /* worst case */];
  5820. struct tm *tm;
  5821. if (de->file.is_directory) {
  5822. mg_snprintf(de->conn,
  5823. NULL, /* Buffer is big enough */
  5824. size,
  5825. sizeof(size),
  5826. "%s",
  5827. "[DIRECTORY]");
  5828. } else {
  5829. /* We use (signed) cast below because MSVC 6 compiler cannot
  5830. * convert unsigned __int64 to double. Sigh. */
  5831. if (de->file.size < 1024) {
  5832. mg_snprintf(de->conn,
  5833. NULL, /* Buffer is big enough */
  5834. size,
  5835. sizeof(size),
  5836. "%d",
  5837. (int)de->file.size);
  5838. } else if (de->file.size < 0x100000) {
  5839. mg_snprintf(de->conn,
  5840. NULL, /* Buffer is big enough */
  5841. size,
  5842. sizeof(size),
  5843. "%.1fk",
  5844. (double)de->file.size / 1024.0);
  5845. } else if (de->file.size < 0x40000000) {
  5846. mg_snprintf(de->conn,
  5847. NULL, /* Buffer is big enough */
  5848. size,
  5849. sizeof(size),
  5850. "%.1fM",
  5851. (double)de->file.size / 1048576);
  5852. } else {
  5853. mg_snprintf(de->conn,
  5854. NULL, /* Buffer is big enough */
  5855. size,
  5856. sizeof(size),
  5857. "%.1fG",
  5858. (double)de->file.size / 1073741824);
  5859. }
  5860. }
  5861. /* Note: mg_snprintf will not cause a buffer overflow above.
  5862. * So, string truncation checks are not required here. */
  5863. tm = localtime(&de->file.last_modified);
  5864. if (tm != NULL) {
  5865. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  5866. } else {
  5867. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  5868. mod[sizeof(mod) - 1] = '\0';
  5869. }
  5870. mg_url_encode(de->file_name, href, sizeof(href));
  5871. de->conn->num_bytes_sent +=
  5872. mg_printf(de->conn,
  5873. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  5874. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  5875. de->conn->request_info.local_uri,
  5876. href,
  5877. de->file.is_directory ? "/" : "",
  5878. de->file_name,
  5879. de->file.is_directory ? "/" : "",
  5880. mod,
  5881. size);
  5882. }
  5883. /* This function is called from send_directory() and used for
  5884. * sorting directory entries by size, or name, or modification time.
  5885. * On windows, __cdecl specification is needed in case if project is built
  5886. * with __stdcall convention. qsort always requires __cdels callback. */
  5887. static int WINCDECL
  5888. compare_dir_entries(const void *p1, const void *p2)
  5889. {
  5890. if (p1 && p2) {
  5891. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  5892. const char *query_string = a->conn->request_info.query_string;
  5893. int cmp_result = 0;
  5894. if (query_string == NULL) {
  5895. query_string = "na";
  5896. }
  5897. if (a->file.is_directory && !b->file.is_directory) {
  5898. return -1; /* Always put directories on top */
  5899. } else if (!a->file.is_directory && b->file.is_directory) {
  5900. return 1; /* Always put directories on top */
  5901. } else if (*query_string == 'n') {
  5902. cmp_result = strcmp(a->file_name, b->file_name);
  5903. } else if (*query_string == 's') {
  5904. cmp_result = (a->file.size == b->file.size)
  5905. ? 0
  5906. : ((a->file.size > b->file.size) ? 1 : -1);
  5907. } else if (*query_string == 'd') {
  5908. cmp_result =
  5909. (a->file.last_modified == b->file.last_modified)
  5910. ? 0
  5911. : ((a->file.last_modified > b->file.last_modified) ? 1
  5912. : -1);
  5913. }
  5914. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  5915. }
  5916. return 0;
  5917. }
  5918. static int
  5919. must_hide_file(struct mg_connection *conn, const char *path)
  5920. {
  5921. if (conn && conn->ctx) {
  5922. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  5923. const char *pattern = conn->ctx->config[HIDE_FILES];
  5924. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0
  5925. || (pattern != NULL
  5926. && match_prefix(pattern, strlen(pattern), path) > 0);
  5927. }
  5928. return 0;
  5929. }
  5930. static int
  5931. scan_directory(struct mg_connection *conn,
  5932. const char *dir,
  5933. void *data,
  5934. void (*cb)(struct de *, void *))
  5935. {
  5936. char path[PATH_MAX];
  5937. struct dirent *dp;
  5938. DIR *dirp;
  5939. struct de de;
  5940. int truncated;
  5941. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5942. return 0;
  5943. } else {
  5944. de.conn = conn;
  5945. while ((dp = mg_readdir(dirp)) != NULL) {
  5946. /* Do not show current dir and hidden files */
  5947. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  5948. || must_hide_file(conn, dp->d_name)) {
  5949. continue;
  5950. }
  5951. mg_snprintf(
  5952. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5953. /* If we don't memset stat structure to zero, mtime will have
  5954. * garbage and strftime() will segfault later on in
  5955. * print_dir_entry(). memset is required only if mg_stat()
  5956. * fails. For more details, see
  5957. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  5958. memset(&de.file, 0, sizeof(de.file));
  5959. if (truncated) {
  5960. /* If the path is not complete, skip processing. */
  5961. continue;
  5962. }
  5963. if (!mg_stat(conn, path, &de.file)) {
  5964. mg_cry(conn,
  5965. "%s: mg_stat(%s) failed: %s",
  5966. __func__,
  5967. path,
  5968. strerror(ERRNO));
  5969. }
  5970. de.file_name = dp->d_name;
  5971. cb(&de, data);
  5972. }
  5973. (void)mg_closedir(dirp);
  5974. }
  5975. return 1;
  5976. }
  5977. #if !defined(NO_FILES)
  5978. static int
  5979. remove_directory(struct mg_connection *conn, const char *dir)
  5980. {
  5981. char path[PATH_MAX];
  5982. struct dirent *dp;
  5983. DIR *dirp;
  5984. struct de de;
  5985. int truncated;
  5986. int ok = 1;
  5987. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  5988. return 0;
  5989. } else {
  5990. de.conn = conn;
  5991. while ((dp = mg_readdir(dirp)) != NULL) {
  5992. /* Do not show current dir (but show hidden files as they will
  5993. * also be removed) */
  5994. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  5995. continue;
  5996. }
  5997. mg_snprintf(
  5998. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  5999. /* If we don't memset stat structure to zero, mtime will have
  6000. * garbage and strftime() will segfault later on in
  6001. * print_dir_entry(). memset is required only if mg_stat()
  6002. * fails. For more details, see
  6003. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  6004. memset(&de.file, 0, sizeof(de.file));
  6005. if (truncated) {
  6006. /* Do not delete anything shorter */
  6007. ok = 0;
  6008. continue;
  6009. }
  6010. if (!mg_stat(conn, path, &de.file)) {
  6011. mg_cry(conn,
  6012. "%s: mg_stat(%s) failed: %s",
  6013. __func__,
  6014. path,
  6015. strerror(ERRNO));
  6016. ok = 0;
  6017. }
  6018. if (de.file.is_directory) {
  6019. if (remove_directory(conn, path) == 0) {
  6020. ok = 0;
  6021. }
  6022. } else {
  6023. /* This will fail file is the file is in memory */
  6024. if (mg_remove(conn, path) == 0) {
  6025. ok = 0;
  6026. }
  6027. }
  6028. }
  6029. (void)mg_closedir(dirp);
  6030. IGNORE_UNUSED_RESULT(rmdir(dir));
  6031. }
  6032. return ok;
  6033. }
  6034. #endif
  6035. struct dir_scan_data {
  6036. struct de *entries;
  6037. unsigned int num_entries;
  6038. unsigned int arr_size;
  6039. };
  6040. /* Behaves like realloc(), but frees original pointer on failure */
  6041. static void *
  6042. realloc2(void *ptr, size_t size)
  6043. {
  6044. void *new_ptr = mg_realloc(ptr, size);
  6045. if (new_ptr == NULL) {
  6046. mg_free(ptr);
  6047. }
  6048. return new_ptr;
  6049. }
  6050. static void
  6051. dir_scan_callback(struct de *de, void *data)
  6052. {
  6053. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  6054. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  6055. dsd->arr_size *= 2;
  6056. dsd->entries =
  6057. (struct de *)realloc2(dsd->entries,
  6058. dsd->arr_size * sizeof(dsd->entries[0]));
  6059. }
  6060. if (dsd->entries == NULL) {
  6061. /* TODO(lsm, low): propagate an error to the caller */
  6062. dsd->num_entries = 0;
  6063. } else {
  6064. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  6065. dsd->entries[dsd->num_entries].file = de->file;
  6066. dsd->entries[dsd->num_entries].conn = de->conn;
  6067. dsd->num_entries++;
  6068. }
  6069. }
  6070. static void
  6071. handle_directory_request(struct mg_connection *conn, const char *dir)
  6072. {
  6073. unsigned int i;
  6074. int sort_direction;
  6075. struct dir_scan_data data = {NULL, 0, 128};
  6076. char date[64];
  6077. time_t curtime = time(NULL);
  6078. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  6079. send_http_error(conn,
  6080. 500,
  6081. "Error: Cannot open directory\nopendir(%s): %s",
  6082. dir,
  6083. strerror(ERRNO));
  6084. return;
  6085. }
  6086. gmt_time_string(date, sizeof(date), &curtime);
  6087. if (!conn) {
  6088. return;
  6089. }
  6090. sort_direction = ((conn->request_info.query_string != NULL)
  6091. && (conn->request_info.query_string[1] == 'd'))
  6092. ? 'a'
  6093. : 'd';
  6094. conn->must_close = 1;
  6095. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  6096. send_static_cache_header(conn);
  6097. mg_printf(conn,
  6098. "Date: %s\r\n"
  6099. "Connection: close\r\n"
  6100. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  6101. date);
  6102. conn->num_bytes_sent +=
  6103. mg_printf(conn,
  6104. "<html><head><title>Index of %s</title>"
  6105. "<style>th {text-align: left;}</style></head>"
  6106. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  6107. "<tr><th><a href=\"?n%c\">Name</a></th>"
  6108. "<th><a href=\"?d%c\">Modified</a></th>"
  6109. "<th><a href=\"?s%c\">Size</a></th></tr>"
  6110. "<tr><td colspan=\"3\"><hr></td></tr>",
  6111. conn->request_info.local_uri,
  6112. conn->request_info.local_uri,
  6113. sort_direction,
  6114. sort_direction,
  6115. sort_direction);
  6116. /* Print first entry - link to a parent directory */
  6117. conn->num_bytes_sent +=
  6118. mg_printf(conn,
  6119. "<tr><td><a href=\"%s%s\">%s</a></td>"
  6120. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  6121. conn->request_info.local_uri,
  6122. "..",
  6123. "Parent directory",
  6124. "-",
  6125. "-");
  6126. /* Sort and print directory entries */
  6127. if (data.entries != NULL) {
  6128. qsort(data.entries,
  6129. (size_t)data.num_entries,
  6130. sizeof(data.entries[0]),
  6131. compare_dir_entries);
  6132. for (i = 0; i < data.num_entries; i++) {
  6133. print_dir_entry(&data.entries[i]);
  6134. mg_free(data.entries[i].file_name);
  6135. }
  6136. mg_free(data.entries);
  6137. }
  6138. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  6139. conn->status_code = 200;
  6140. }
  6141. /* Send len bytes from the opened file to the client. */
  6142. static void
  6143. send_file_data(struct mg_connection *conn,
  6144. struct mg_file *filep,
  6145. int64_t offset,
  6146. int64_t len)
  6147. {
  6148. char buf[MG_BUF_LEN];
  6149. int to_read, num_read, num_written;
  6150. int64_t size;
  6151. if (!filep || !conn) {
  6152. return;
  6153. }
  6154. /* Sanity check the offset */
  6155. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  6156. : (int64_t)(filep->stat.size);
  6157. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  6158. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  6159. /* file stored in memory */
  6160. if (len > size - offset) {
  6161. len = size - offset;
  6162. }
  6163. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  6164. } else if (len > 0 && filep->access.fp != NULL) {
  6165. /* file stored on disk */
  6166. #if defined(__linux__)
  6167. /* sendfile is only available for Linux */
  6168. if ((conn->ssl == 0) && (conn->throttle == 0)
  6169. && (!mg_strcasecmp(conn->ctx->config[ALLOW_SENDFILE_CALL],
  6170. "yes"))) {
  6171. off_t sf_offs = (off_t)offset;
  6172. ssize_t sf_sent;
  6173. int sf_file = fileno(filep->access.fp);
  6174. int loop_cnt = 0;
  6175. do {
  6176. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  6177. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  6178. size_t sf_tosend =
  6179. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  6180. sf_sent =
  6181. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  6182. if (sf_sent > 0) {
  6183. conn->num_bytes_sent += sf_sent;
  6184. len -= sf_sent;
  6185. offset += sf_sent;
  6186. } else if (loop_cnt == 0) {
  6187. /* This file can not be sent using sendfile.
  6188. * This might be the case for pseudo-files in the
  6189. * /sys/ and /proc/ file system.
  6190. * Use the regular user mode copy code instead. */
  6191. break;
  6192. } else if (sf_sent == 0) {
  6193. /* No error, but 0 bytes sent. May be EOF? */
  6194. return;
  6195. }
  6196. loop_cnt++;
  6197. } while ((len > 0) && (sf_sent >= 0));
  6198. if (sf_sent > 0) {
  6199. return; /* OK */
  6200. }
  6201. /* sf_sent<0 means error, thus fall back to the classic way */
  6202. /* This is always the case, if sf_file is not a "normal" file,
  6203. * e.g., for sending data from the output of a CGI process. */
  6204. offset = (int64_t)sf_offs;
  6205. }
  6206. #endif
  6207. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  6208. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  6209. send_http_error(
  6210. conn,
  6211. 500,
  6212. "%s",
  6213. "Error: Unable to access file at requested position.");
  6214. } else {
  6215. while (len > 0) {
  6216. /* Calculate how much to read from the file in the buffer */
  6217. to_read = sizeof(buf);
  6218. if ((int64_t)to_read > len) {
  6219. to_read = (int)len;
  6220. }
  6221. /* Read from file, exit the loop on error */
  6222. if ((num_read =
  6223. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  6224. <= 0) {
  6225. break;
  6226. }
  6227. /* Send read bytes to the client, exit the loop on error */
  6228. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  6229. != num_read) {
  6230. break;
  6231. }
  6232. /* Both read and were successful, adjust counters */
  6233. conn->num_bytes_sent += num_written;
  6234. len -= num_written;
  6235. }
  6236. }
  6237. }
  6238. }
  6239. static int
  6240. parse_range_header(const char *header, int64_t *a, int64_t *b)
  6241. {
  6242. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  6243. }
  6244. static void
  6245. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  6246. {
  6247. if (filestat != NULL && buf != NULL) {
  6248. mg_snprintf(NULL,
  6249. NULL, /* All calls to construct_etag use 64 byte buffer */
  6250. buf,
  6251. buf_len,
  6252. "\"%lx.%" INT64_FMT "\"",
  6253. (unsigned long)filestat->last_modified,
  6254. filestat->size);
  6255. }
  6256. }
  6257. static void
  6258. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  6259. {
  6260. if (filep != NULL && filep->fp != NULL) {
  6261. #ifdef _WIN32
  6262. (void)conn; /* Unused. */
  6263. #else
  6264. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  6265. mg_cry(conn,
  6266. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  6267. __func__,
  6268. strerror(ERRNO));
  6269. }
  6270. #endif
  6271. }
  6272. }
  6273. static void
  6274. handle_static_file_request(struct mg_connection *conn,
  6275. const char *path,
  6276. struct mg_file *filep,
  6277. const char *mime_type,
  6278. const char *additional_headers)
  6279. {
  6280. char date[64], lm[64], etag[64];
  6281. char range[128]; /* large enough, so there will be no overflow */
  6282. const char *msg = "OK", *hdr;
  6283. time_t curtime = time(NULL);
  6284. int64_t cl, r1, r2;
  6285. struct vec mime_vec;
  6286. int n, truncated;
  6287. char gz_path[PATH_MAX];
  6288. const char *encoding = "";
  6289. const char *cors1, *cors2, *cors3;
  6290. if (conn == NULL || conn->ctx == NULL || filep == NULL) {
  6291. return;
  6292. }
  6293. if (mime_type == NULL) {
  6294. get_mime_type(conn->ctx, path, &mime_vec);
  6295. } else {
  6296. mime_vec.ptr = mime_type;
  6297. mime_vec.len = strlen(mime_type);
  6298. }
  6299. if (filep->stat.size > INT64_MAX) {
  6300. send_http_error(conn,
  6301. 500,
  6302. "Error: File size is too large to send\n%" INT64_FMT,
  6303. filep->stat.size);
  6304. }
  6305. cl = (int64_t)filep->stat.size;
  6306. conn->status_code = 200;
  6307. range[0] = '\0';
  6308. /* if this file is in fact a pre-gzipped file, rewrite its filename
  6309. * it's important to rewrite the filename after resolving
  6310. * the mime type from it, to preserve the actual file's type */
  6311. if (filep->stat.is_gzipped) {
  6312. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  6313. if (truncated) {
  6314. send_http_error(conn,
  6315. 500,
  6316. "Error: Path of zipped file too long (%s)",
  6317. path);
  6318. return;
  6319. }
  6320. path = gz_path;
  6321. encoding = "Content-Encoding: gzip\r\n";
  6322. }
  6323. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  6324. send_http_error(conn,
  6325. 500,
  6326. "Error: Cannot open file\nfopen(%s): %s",
  6327. path,
  6328. strerror(ERRNO));
  6329. return;
  6330. }
  6331. fclose_on_exec(&filep->access, conn);
  6332. /* If Range: header specified, act accordingly */
  6333. r1 = r2 = 0;
  6334. hdr = mg_get_header(conn, "Range");
  6335. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 && r1 >= 0
  6336. && r2 >= 0) {
  6337. /* actually, range requests don't play well with a pre-gzipped
  6338. * file (since the range is specified in the uncompressed space) */
  6339. if (filep->stat.is_gzipped) {
  6340. send_http_error(
  6341. conn,
  6342. 501,
  6343. "%s",
  6344. "Error: Range requests in gzipped files are not supported");
  6345. (void)mg_fclose(
  6346. &filep->access); /* ignore error on read only file */
  6347. return;
  6348. }
  6349. conn->status_code = 206;
  6350. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  6351. mg_snprintf(conn,
  6352. NULL, /* range buffer is big enough */
  6353. range,
  6354. sizeof(range),
  6355. "Content-Range: bytes "
  6356. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  6357. r1,
  6358. r1 + cl - 1,
  6359. filep->stat.size);
  6360. msg = "Partial Content";
  6361. }
  6362. hdr = mg_get_header(conn, "Origin");
  6363. if (hdr) {
  6364. /* Cross-origin resource sharing (CORS), see
  6365. * http://www.html5rocks.com/en/tutorials/cors/,
  6366. * http://www.html5rocks.com/static/images/cors_server_flowchart.png -
  6367. * preflight is not supported for files. */
  6368. cors1 = "Access-Control-Allow-Origin: ";
  6369. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  6370. cors3 = "\r\n";
  6371. } else {
  6372. cors1 = cors2 = cors3 = "";
  6373. }
  6374. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  6375. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  6376. gmt_time_string(date, sizeof(date), &curtime);
  6377. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6378. construct_etag(etag, sizeof(etag), &filep->stat);
  6379. (void)mg_printf(conn,
  6380. "HTTP/1.1 %d %s\r\n"
  6381. "%s%s%s"
  6382. "Date: %s\r\n",
  6383. conn->status_code,
  6384. msg,
  6385. cors1,
  6386. cors2,
  6387. cors3,
  6388. date);
  6389. send_static_cache_header(conn);
  6390. (void)mg_printf(conn,
  6391. "Last-Modified: %s\r\n"
  6392. "Etag: %s\r\n"
  6393. "Content-Type: %.*s\r\n"
  6394. "Content-Length: %" INT64_FMT "\r\n"
  6395. "Connection: %s\r\n"
  6396. "Accept-Ranges: bytes\r\n"
  6397. "%s%s",
  6398. lm,
  6399. etag,
  6400. (int)mime_vec.len,
  6401. mime_vec.ptr,
  6402. cl,
  6403. suggest_connection_header(conn),
  6404. range,
  6405. encoding);
  6406. /* The previous code must not add any header starting with X- to make
  6407. * sure no one of the additional_headers is included twice */
  6408. if (additional_headers != NULL) {
  6409. (void)mg_printf(conn,
  6410. "%.*s\r\n\r\n",
  6411. (int)strlen(additional_headers),
  6412. additional_headers);
  6413. } else {
  6414. (void)mg_printf(conn, "\r\n");
  6415. }
  6416. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  6417. send_file_data(conn, filep, r1, cl);
  6418. }
  6419. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  6420. }
  6421. #if !defined(NO_CACHING)
  6422. static void
  6423. handle_not_modified_static_file_request(struct mg_connection *conn,
  6424. struct mg_file *filep)
  6425. {
  6426. char date[64], lm[64], etag[64];
  6427. time_t curtime = time(NULL);
  6428. if (conn == NULL || filep == NULL) {
  6429. return;
  6430. }
  6431. conn->status_code = 304;
  6432. gmt_time_string(date, sizeof(date), &curtime);
  6433. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  6434. construct_etag(etag, sizeof(etag), &filep->stat);
  6435. (void)mg_printf(conn,
  6436. "HTTP/1.1 %d %s\r\n"
  6437. "Date: %s\r\n",
  6438. conn->status_code,
  6439. mg_get_response_code_text(conn, conn->status_code),
  6440. date);
  6441. send_static_cache_header(conn);
  6442. (void)mg_printf(conn,
  6443. "Last-Modified: %s\r\n"
  6444. "Etag: %s\r\n"
  6445. "Connection: %s\r\n"
  6446. "\r\n",
  6447. lm,
  6448. etag,
  6449. suggest_connection_header(conn));
  6450. }
  6451. #endif
  6452. void
  6453. mg_send_file(struct mg_connection *conn, const char *path)
  6454. {
  6455. mg_send_mime_file(conn, path, NULL);
  6456. }
  6457. void
  6458. mg_send_mime_file(struct mg_connection *conn,
  6459. const char *path,
  6460. const char *mime_type)
  6461. {
  6462. mg_send_mime_file2(conn, path, mime_type, NULL);
  6463. }
  6464. void
  6465. mg_send_mime_file2(struct mg_connection *conn,
  6466. const char *path,
  6467. const char *mime_type,
  6468. const char *additional_headers)
  6469. {
  6470. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6471. if (mg_stat(conn, path, &file.stat)) {
  6472. if (file.stat.is_directory) {
  6473. if (!conn) {
  6474. return;
  6475. }
  6476. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  6477. "yes")) {
  6478. handle_directory_request(conn, path);
  6479. } else {
  6480. send_http_error(conn,
  6481. 403,
  6482. "%s",
  6483. "Error: Directory listing denied");
  6484. }
  6485. } else {
  6486. handle_static_file_request(
  6487. conn, path, &file, mime_type, additional_headers);
  6488. }
  6489. } else {
  6490. send_http_error(conn, 404, "%s", "Error: File not found");
  6491. }
  6492. }
  6493. /* For a given PUT path, create all intermediate subdirectories.
  6494. * Return 0 if the path itself is a directory.
  6495. * Return 1 if the path leads to a file.
  6496. * Return -1 for if the path is too long.
  6497. * Return -2 if path can not be created.
  6498. */
  6499. static int
  6500. put_dir(struct mg_connection *conn, const char *path)
  6501. {
  6502. char buf[PATH_MAX];
  6503. const char *s, *p;
  6504. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6505. size_t len;
  6506. int res = 1;
  6507. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  6508. len = (size_t)(p - path);
  6509. if (len >= sizeof(buf)) {
  6510. /* path too long */
  6511. res = -1;
  6512. break;
  6513. }
  6514. memcpy(buf, path, len);
  6515. buf[len] = '\0';
  6516. /* Try to create intermediate directory */
  6517. DEBUG_TRACE("mkdir(%s)", buf);
  6518. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  6519. /* path does not exixt and can not be created */
  6520. res = -2;
  6521. break;
  6522. }
  6523. /* Is path itself a directory? */
  6524. if (p[1] == '\0') {
  6525. res = 0;
  6526. }
  6527. }
  6528. return res;
  6529. }
  6530. static void
  6531. remove_bad_file(const struct mg_connection *conn, const char *path)
  6532. {
  6533. int r = mg_remove(conn, path);
  6534. if (r != 0) {
  6535. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  6536. }
  6537. }
  6538. long long
  6539. mg_store_body(struct mg_connection *conn, const char *path)
  6540. {
  6541. char buf[MG_BUF_LEN];
  6542. long long len = 0;
  6543. int ret, n;
  6544. struct mg_file fi;
  6545. if (conn->consumed_content != 0) {
  6546. mg_cry(conn, "%s: Contents already consumed", __func__);
  6547. return -11;
  6548. }
  6549. ret = put_dir(conn, path);
  6550. if (ret < 0) {
  6551. /* -1 for path too long,
  6552. * -2 for path can not be created. */
  6553. return ret;
  6554. }
  6555. if (ret != 1) {
  6556. /* Return 0 means, path itself is a directory. */
  6557. return 0;
  6558. }
  6559. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  6560. return -12;
  6561. }
  6562. ret = mg_read(conn, buf, sizeof(buf));
  6563. while (ret > 0) {
  6564. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  6565. if (n != ret) {
  6566. (void)mg_fclose(
  6567. &fi.access); /* File is bad and will be removed anyway. */
  6568. remove_bad_file(conn, path);
  6569. return -13;
  6570. }
  6571. ret = mg_read(conn, buf, sizeof(buf));
  6572. }
  6573. /* File is open for writing. If fclose fails, there was probably an
  6574. * error flushing the buffer to disk, so the file on disk might be
  6575. * broken. Delete it and return an error to the caller. */
  6576. if (mg_fclose(&fi.access) != 0) {
  6577. remove_bad_file(conn, path);
  6578. return -14;
  6579. }
  6580. return len;
  6581. }
  6582. /* Parse HTTP headers from the given buffer, advance buf pointer
  6583. * to the point where parsing stopped.
  6584. * All parameters must be valid pointers (not NULL).
  6585. * Return <0 on error. */
  6586. static int
  6587. parse_http_headers(char **buf, struct mg_request_info *ri)
  6588. {
  6589. int i;
  6590. ri->num_headers = 0;
  6591. for (i = 0; i < (int)ARRAY_SIZE(ri->http_headers); i++) {
  6592. char *dp = *buf;
  6593. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  6594. dp++;
  6595. }
  6596. if (dp == *buf) {
  6597. /* End of headers reached. */
  6598. break;
  6599. }
  6600. if (*dp != ':') {
  6601. /* This is not a valid field. */
  6602. return -1;
  6603. }
  6604. /* End of header key (*dp == ':') */
  6605. /* Truncate here and set the key name */
  6606. *dp = 0;
  6607. ri->http_headers[i].name = *buf;
  6608. do {
  6609. dp++;
  6610. } while (*dp == ' ');
  6611. /* The rest of the line is the value */
  6612. ri->http_headers[i].value = dp;
  6613. *buf = dp + strcspn(dp, "\r\n");
  6614. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  6615. *buf = NULL;
  6616. }
  6617. ri->num_headers = i + 1;
  6618. if (*buf) {
  6619. (*buf)[0] = 0;
  6620. (*buf)[1] = 0;
  6621. *buf += 2;
  6622. } else {
  6623. *buf = dp;
  6624. break;
  6625. }
  6626. if ((*buf)[0] == '\r') {
  6627. /* This is the end of the header */
  6628. break;
  6629. }
  6630. }
  6631. return ri->num_headers;
  6632. }
  6633. static int
  6634. is_valid_http_method(const char *method)
  6635. {
  6636. return !strcmp(method, "GET") /* HTTP (RFC 2616) */
  6637. || !strcmp(method, "POST") /* HTTP (RFC 2616) */
  6638. || !strcmp(method, "HEAD") /* HTTP (RFC 2616) */
  6639. || !strcmp(method, "PUT") /* HTTP (RFC 2616) */
  6640. || !strcmp(method, "DELETE") /* HTTP (RFC 2616) */
  6641. || !strcmp(method, "OPTIONS") /* HTTP (RFC 2616) */
  6642. /* TRACE method (RFC 2616) is not supported for security reasons */
  6643. || !strcmp(method, "CONNECT") /* HTTP (RFC 2616) */
  6644. || !strcmp(method, "PROPFIND") /* WEBDAV (RFC 2518) */
  6645. || !strcmp(method, "MKCOL") /* WEBDAV (RFC 2518) */
  6646. /* Unsupported WEBDAV Methods: */
  6647. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  6648. /* + 11 methods from RFC 3253 */
  6649. /* ORDERPATCH (RFC 3648) */
  6650. /* ACL (RFC 3744) */
  6651. /* SEARCH (RFC 5323) */
  6652. /* + MicroSoft extensions
  6653. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  6654. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  6655. || !strcmp(method, "PATCH"); /* PATCH method (RFC 5789) */
  6656. }
  6657. /* Parse HTTP request, fill in mg_request_info structure.
  6658. * This function modifies the buffer by NUL-terminating
  6659. * HTTP request components, header names and header values.
  6660. * Parameters:
  6661. * buf (in/out): pointer to the HTTP header to parse and split
  6662. * len (in): length of HTTP header buffer
  6663. * re (out): parsed header as mg_request_info
  6664. * buf and ri must be valid pointers (not NULL), len>0.
  6665. * Returns <0 on error. */
  6666. static int
  6667. parse_http_message(char *buf, int len, struct mg_request_info *ri)
  6668. {
  6669. int is_request, request_length;
  6670. char *start_line;
  6671. request_length = get_request_len(buf, len);
  6672. if (request_length > 0) {
  6673. /* Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_addr,
  6674. * remote_port */
  6675. ri->remote_user = ri->request_method = ri->request_uri =
  6676. ri->http_version = NULL;
  6677. ri->num_headers = 0;
  6678. buf[request_length - 1] = '\0';
  6679. /* RFC says that all initial whitespaces should be ingored */
  6680. while (*buf != '\0' && isspace(*(unsigned char *)buf)) {
  6681. buf++;
  6682. }
  6683. start_line = skip(&buf, "\r\n");
  6684. ri->request_method = skip(&start_line, " ");
  6685. ri->request_uri = skip(&start_line, " ");
  6686. ri->http_version = start_line;
  6687. /* HTTP message could be either HTTP request:
  6688. * "GET / HTTP/1.0 ..."
  6689. * or a HTTP response:
  6690. * "HTTP/1.0 200 OK ..."
  6691. * otherwise it is invalid.
  6692. */
  6693. is_request = is_valid_http_method(ri->request_method);
  6694. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0)
  6695. || (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  6696. /* Not a valid request or response: invalid */
  6697. return -1;
  6698. }
  6699. if (is_request) {
  6700. ri->http_version += 5;
  6701. }
  6702. if (parse_http_headers(&buf, ri) < 0) {
  6703. /* Error while parsing headers */
  6704. return -1;
  6705. }
  6706. }
  6707. return request_length;
  6708. }
  6709. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  6710. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  6711. * buffer (which marks the end of HTTP request). Buffer buf may already
  6712. * have some data. The length of the data is stored in nread.
  6713. * Upon every read operation, increase nread by the number of bytes read. */
  6714. static int
  6715. read_request(FILE *fp,
  6716. struct mg_connection *conn,
  6717. char *buf,
  6718. int bufsiz,
  6719. int *nread)
  6720. {
  6721. int request_len, n = 0;
  6722. struct timespec last_action_time;
  6723. double request_timeout;
  6724. if (!conn) {
  6725. return 0;
  6726. }
  6727. memset(&last_action_time, 0, sizeof(last_action_time));
  6728. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6729. /* value of request_timeout is in seconds, config in milliseconds */
  6730. request_timeout = atof(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6731. } else {
  6732. request_timeout = -1.0;
  6733. }
  6734. if (conn->handled_requests > 0) {
  6735. if (conn->ctx->config[KEEP_ALIVE_TIMEOUT]) {
  6736. request_timeout =
  6737. atof(conn->ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  6738. }
  6739. }
  6740. request_len = get_request_len(buf, *nread);
  6741. /* first time reading from this connection */
  6742. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6743. while (request_len == 0) {
  6744. /* Full request not yet received */
  6745. if (conn->ctx->stop_flag != 0) {
  6746. /* Server is to be stopped. */
  6747. return -1;
  6748. }
  6749. if (*nread >= bufsiz) {
  6750. /* Request too long */
  6751. return -2;
  6752. }
  6753. n = pull(fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  6754. if (n < 0) {
  6755. /* Receive error */
  6756. return -1;
  6757. }
  6758. *nread += n;
  6759. request_len = get_request_len(buf, *nread);
  6760. if ((request_len == 0) && (request_timeout >= 0)) {
  6761. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  6762. > request_timeout) {
  6763. /* Timeout */
  6764. return -1;
  6765. }
  6766. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  6767. }
  6768. }
  6769. return request_len;
  6770. }
  6771. #if !defined(NO_FILES)
  6772. /* For given directory path, substitute it to valid index file.
  6773. * Return 1 if index file has been found, 0 if not found.
  6774. * If the file is found, it's stats is returned in stp. */
  6775. static int
  6776. substitute_index_file(struct mg_connection *conn,
  6777. char *path,
  6778. size_t path_len,
  6779. struct mg_file *filep)
  6780. {
  6781. if (conn && conn->ctx) {
  6782. const char *list = conn->ctx->config[INDEX_FILES];
  6783. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6784. struct vec filename_vec;
  6785. size_t n = strlen(path);
  6786. int found = 0;
  6787. /* The 'path' given to us points to the directory. Remove all trailing
  6788. * directory separator characters from the end of the path, and
  6789. * then append single directory separator character. */
  6790. while (n > 0 && path[n - 1] == '/') {
  6791. n--;
  6792. }
  6793. path[n] = '/';
  6794. /* Traverse index files list. For each entry, append it to the given
  6795. * path and see if the file exists. If it exists, break the loop */
  6796. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6797. /* Ignore too long entries that may overflow path buffer */
  6798. if (filename_vec.len > path_len - (n + 2)) {
  6799. continue;
  6800. }
  6801. /* Prepare full path to the index file */
  6802. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6803. /* Does it exist? */
  6804. if (mg_stat(conn, path, &file.stat)) {
  6805. /* Yes it does, break the loop */
  6806. *filep = file;
  6807. found = 1;
  6808. break;
  6809. }
  6810. }
  6811. /* If no index file exists, restore directory path */
  6812. if (!found) {
  6813. path[n] = '\0';
  6814. }
  6815. return found;
  6816. }
  6817. return 0;
  6818. }
  6819. #endif
  6820. #if !defined(NO_CACHING)
  6821. /* Return True if we should reply 304 Not Modified. */
  6822. static int
  6823. is_not_modified(const struct mg_connection *conn,
  6824. const struct mg_file_stat *filestat)
  6825. {
  6826. char etag[64];
  6827. const char *ims = mg_get_header(conn, "If-Modified-Since");
  6828. const char *inm = mg_get_header(conn, "If-None-Match");
  6829. construct_etag(etag, sizeof(etag), filestat);
  6830. return (inm != NULL && !mg_strcasecmp(etag, inm))
  6831. || ((ims != NULL)
  6832. && (filestat->last_modified <= parse_date_string(ims)));
  6833. }
  6834. #endif /* !NO_CACHING */
  6835. #if !defined(NO_CGI) || !defined(NO_FILES)
  6836. static int
  6837. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  6838. {
  6839. const char *expect, *body;
  6840. char buf[MG_BUF_LEN];
  6841. int to_read, nread, success = 0;
  6842. int64_t buffered_len;
  6843. double timeout = -1.0;
  6844. if (!conn) {
  6845. return 0;
  6846. }
  6847. if (conn->ctx->config[REQUEST_TIMEOUT]) {
  6848. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  6849. }
  6850. expect = mg_get_header(conn, "Expect");
  6851. /* assert(fp != NULL); */
  6852. if (!fp) {
  6853. send_http_error(conn, 500, "%s", "Error: NULL File");
  6854. return 0;
  6855. }
  6856. if (conn->content_len == -1 && !conn->is_chunked) {
  6857. /* Content length is not specified by the client. */
  6858. send_http_error(conn,
  6859. 411,
  6860. "%s",
  6861. "Error: Client did not specify content length");
  6862. } else if ((expect != NULL)
  6863. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  6864. /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */
  6865. send_http_error(conn,
  6866. 417,
  6867. "Error: Can not fulfill expectation %s",
  6868. expect);
  6869. } else {
  6870. if (expect != NULL) {
  6871. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  6872. conn->status_code = 100;
  6873. } else {
  6874. conn->status_code = 200;
  6875. }
  6876. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  6877. - conn->consumed_content;
  6878. /* assert(buffered_len >= 0); */
  6879. /* assert(conn->consumed_content == 0); */
  6880. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  6881. send_http_error(conn, 500, "%s", "Error: Size mismatch");
  6882. return 0;
  6883. }
  6884. if (buffered_len > 0) {
  6885. if ((int64_t)buffered_len > conn->content_len) {
  6886. buffered_len = (int)conn->content_len;
  6887. }
  6888. body = conn->buf + conn->request_len + conn->consumed_content;
  6889. push_all(conn->ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  6890. conn->consumed_content += buffered_len;
  6891. }
  6892. nread = 0;
  6893. while (conn->consumed_content < conn->content_len) {
  6894. to_read = sizeof(buf);
  6895. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  6896. to_read = (int)(conn->content_len - conn->consumed_content);
  6897. }
  6898. nread = pull(NULL, conn, buf, to_read, timeout);
  6899. if (nread <= 0
  6900. || push_all(conn->ctx, fp, sock, ssl, buf, nread) != nread) {
  6901. break;
  6902. }
  6903. conn->consumed_content += nread;
  6904. }
  6905. if (conn->consumed_content == conn->content_len) {
  6906. success = (nread >= 0);
  6907. }
  6908. /* Each error code path in this function must send an error */
  6909. if (!success) {
  6910. /* NOTE: Maybe some data has already been sent. */
  6911. /* TODO (low): If some data has been sent, a correct error
  6912. * reply can no longer be sent, so just close the connection */
  6913. send_http_error(conn, 500, "%s", "");
  6914. }
  6915. }
  6916. return success;
  6917. }
  6918. #endif
  6919. #if !defined(NO_CGI)
  6920. /* This structure helps to create an environment for the spawned CGI program.
  6921. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  6922. * last element must be NULL.
  6923. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  6924. * strings must reside in a contiguous buffer. The end of the buffer is
  6925. * marked by two '\0' characters.
  6926. * We satisfy both worlds: we create an envp array (which is vars), all
  6927. * entries are actually pointers inside buf. */
  6928. struct cgi_environment {
  6929. struct mg_connection *conn;
  6930. /* Data block */
  6931. char *buf; /* Environment buffer */
  6932. size_t buflen; /* Space available in buf */
  6933. size_t bufused; /* Space taken in buf */
  6934. /* Index block */
  6935. char **var; /* char **envp */
  6936. size_t varlen; /* Number of variables available in var */
  6937. size_t varused; /* Number of variables stored in var */
  6938. };
  6939. static void addenv(struct cgi_environment *env,
  6940. PRINTF_FORMAT_STRING(const char *fmt),
  6941. ...) PRINTF_ARGS(2, 3);
  6942. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  6943. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  6944. static void
  6945. addenv(struct cgi_environment *env, const char *fmt, ...)
  6946. {
  6947. size_t n, space;
  6948. int truncated = 0;
  6949. char *added;
  6950. va_list ap;
  6951. /* Calculate how much space is left in the buffer */
  6952. space = (env->buflen - env->bufused);
  6953. /* Calculate an estimate for the required space */
  6954. n = strlen(fmt) + 2 + 128;
  6955. do {
  6956. if (space <= n) {
  6957. /* Allocate new buffer */
  6958. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  6959. added = (char *)mg_realloc(env->buf, n);
  6960. if (!added) {
  6961. /* Out of memory */
  6962. mg_cry(env->conn,
  6963. "%s: Cannot allocate memory for CGI variable [%s]",
  6964. __func__,
  6965. fmt);
  6966. return;
  6967. }
  6968. env->buf = added;
  6969. env->buflen = n;
  6970. space = (env->buflen - env->bufused);
  6971. }
  6972. /* Make a pointer to the free space int the buffer */
  6973. added = env->buf + env->bufused;
  6974. /* Copy VARIABLE=VALUE\0 string into the free space */
  6975. va_start(ap, fmt);
  6976. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  6977. va_end(ap);
  6978. /* Do not add truncated strings to the environment */
  6979. if (truncated) {
  6980. /* Reallocate the buffer */
  6981. space = 0;
  6982. n = 1;
  6983. }
  6984. } while (truncated);
  6985. /* Calculate number of bytes added to the environment */
  6986. n = strlen(added) + 1;
  6987. env->bufused += n;
  6988. /* Now update the variable index */
  6989. space = (env->varlen - env->varused);
  6990. if (space < 2) {
  6991. mg_cry(env->conn,
  6992. "%s: Cannot register CGI variable [%s]",
  6993. __func__,
  6994. fmt);
  6995. return;
  6996. }
  6997. /* Append a pointer to the added string into the envp array */
  6998. env->var[env->varused] = added;
  6999. env->varused++;
  7000. }
  7001. static void
  7002. prepare_cgi_environment(struct mg_connection *conn,
  7003. const char *prog,
  7004. struct cgi_environment *env)
  7005. {
  7006. const char *s;
  7007. struct vec var_vec;
  7008. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  7009. int i, truncated, uri_len;
  7010. if (conn == NULL || prog == NULL || env == NULL) {
  7011. return;
  7012. }
  7013. env->conn = conn;
  7014. env->buflen = CGI_ENVIRONMENT_SIZE;
  7015. env->bufused = 0;
  7016. env->buf = (char *)mg_malloc(env->buflen);
  7017. env->varlen = MAX_CGI_ENVIR_VARS;
  7018. env->varused = 0;
  7019. env->var = (char **)mg_malloc(env->buflen * sizeof(char *));
  7020. addenv(env, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  7021. addenv(env, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7022. addenv(env, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7023. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  7024. /* Prepare the environment block */
  7025. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  7026. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  7027. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  7028. #if defined(USE_IPV6)
  7029. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  7030. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  7031. } else
  7032. #endif
  7033. {
  7034. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  7035. }
  7036. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  7037. addenv(env, "REMOTE_ADDR=%s", src_addr);
  7038. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  7039. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  7040. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  7041. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  7042. /* SCRIPT_NAME */
  7043. uri_len = (int)strlen(conn->request_info.local_uri);
  7044. if (conn->path_info == NULL) {
  7045. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  7046. /* URI: /path_to_script/script.cgi */
  7047. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  7048. } else {
  7049. /* URI: /path_to_script/ ... using index.cgi */
  7050. char *index_file = strrchr(prog, '/');
  7051. if (index_file) {
  7052. addenv(env,
  7053. "SCRIPT_NAME=%s%s",
  7054. conn->request_info.local_uri,
  7055. index_file + 1);
  7056. }
  7057. }
  7058. } else {
  7059. /* URI: /path_to_script/script.cgi/path_info */
  7060. addenv(env,
  7061. "SCRIPT_NAME=%.*s",
  7062. uri_len - (int)strlen(conn->path_info),
  7063. conn->request_info.local_uri);
  7064. }
  7065. addenv(env, "SCRIPT_FILENAME=%s", prog);
  7066. if (conn->path_info == NULL) {
  7067. addenv(env, "PATH_TRANSLATED=%s", conn->ctx->config[DOCUMENT_ROOT]);
  7068. } else {
  7069. addenv(env,
  7070. "PATH_TRANSLATED=%s%s",
  7071. conn->ctx->config[DOCUMENT_ROOT],
  7072. conn->path_info);
  7073. }
  7074. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  7075. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  7076. addenv(env, "CONTENT_TYPE=%s", s);
  7077. }
  7078. if (conn->request_info.query_string != NULL) {
  7079. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  7080. }
  7081. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  7082. addenv(env, "CONTENT_LENGTH=%s", s);
  7083. }
  7084. if ((s = getenv("PATH")) != NULL) {
  7085. addenv(env, "PATH=%s", s);
  7086. }
  7087. if (conn->path_info != NULL) {
  7088. addenv(env, "PATH_INFO=%s", conn->path_info);
  7089. }
  7090. if (conn->status_code > 0) {
  7091. /* CGI error handler should show the status code */
  7092. addenv(env, "STATUS=%d", conn->status_code);
  7093. }
  7094. #if defined(_WIN32)
  7095. if ((s = getenv("COMSPEC")) != NULL) {
  7096. addenv(env, "COMSPEC=%s", s);
  7097. }
  7098. if ((s = getenv("SYSTEMROOT")) != NULL) {
  7099. addenv(env, "SYSTEMROOT=%s", s);
  7100. }
  7101. if ((s = getenv("SystemDrive")) != NULL) {
  7102. addenv(env, "SystemDrive=%s", s);
  7103. }
  7104. if ((s = getenv("ProgramFiles")) != NULL) {
  7105. addenv(env, "ProgramFiles=%s", s);
  7106. }
  7107. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  7108. addenv(env, "ProgramFiles(x86)=%s", s);
  7109. }
  7110. #else
  7111. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  7112. addenv(env, "LD_LIBRARY_PATH=%s", s);
  7113. }
  7114. #endif /* _WIN32 */
  7115. if ((s = getenv("PERLLIB")) != NULL) {
  7116. addenv(env, "PERLLIB=%s", s);
  7117. }
  7118. if (conn->request_info.remote_user != NULL) {
  7119. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  7120. addenv(env, "%s", "AUTH_TYPE=Digest");
  7121. }
  7122. /* Add all headers as HTTP_* variables */
  7123. for (i = 0; i < conn->request_info.num_headers; i++) {
  7124. (void)mg_snprintf(conn,
  7125. &truncated,
  7126. http_var_name,
  7127. sizeof(http_var_name),
  7128. "HTTP_%s",
  7129. conn->request_info.http_headers[i].name);
  7130. if (truncated) {
  7131. mg_cry(conn,
  7132. "%s: HTTP header variable too long [%s]",
  7133. __func__,
  7134. conn->request_info.http_headers[i].name);
  7135. continue;
  7136. }
  7137. /* Convert variable name into uppercase, and change - to _ */
  7138. for (p = http_var_name; *p != '\0'; p++) {
  7139. if (*p == '-') {
  7140. *p = '_';
  7141. }
  7142. *p = (char)toupper(*(unsigned char *)p);
  7143. }
  7144. addenv(env,
  7145. "%s=%s",
  7146. http_var_name,
  7147. conn->request_info.http_headers[i].value);
  7148. }
  7149. /* Add user-specified variables */
  7150. s = conn->ctx->config[CGI_ENVIRONMENT];
  7151. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  7152. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  7153. }
  7154. env->var[env->varused] = NULL;
  7155. env->buf[env->bufused] = '\0';
  7156. }
  7157. static void
  7158. handle_cgi_request(struct mg_connection *conn, const char *prog)
  7159. {
  7160. char *buf;
  7161. size_t buflen;
  7162. int headers_len, data_len, i, truncated;
  7163. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  7164. const char *status, *status_text, *connection_state;
  7165. char *pbuf, dir[PATH_MAX], *p;
  7166. struct mg_request_info ri;
  7167. struct cgi_environment blk;
  7168. FILE *in = NULL, *out = NULL, *err = NULL;
  7169. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  7170. pid_t pid = (pid_t)-1;
  7171. if (conn == NULL) {
  7172. return;
  7173. }
  7174. buf = NULL;
  7175. buflen = 16384;
  7176. prepare_cgi_environment(conn, prog, &blk);
  7177. /* CGI must be executed in its own directory. 'dir' must point to the
  7178. * directory containing executable program, 'p' must point to the
  7179. * executable program name relative to 'dir'. */
  7180. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  7181. if (truncated) {
  7182. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  7183. send_http_error(conn, 500, "Error: %s", "CGI path too long");
  7184. goto done;
  7185. }
  7186. if ((p = strrchr(dir, '/')) != NULL) {
  7187. *p++ = '\0';
  7188. } else {
  7189. dir[0] = '.', dir[1] = '\0';
  7190. p = (char *)prog;
  7191. }
  7192. if (pipe(fdin) != 0 || pipe(fdout) != 0 || pipe(fderr) != 0) {
  7193. status = strerror(ERRNO);
  7194. mg_cry(conn,
  7195. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  7196. prog,
  7197. status);
  7198. send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status);
  7199. goto done;
  7200. }
  7201. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  7202. if (pid == (pid_t)-1) {
  7203. status = strerror(ERRNO);
  7204. mg_cry(conn,
  7205. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  7206. prog,
  7207. status);
  7208. send_http_error(conn,
  7209. 500,
  7210. "Error: Cannot spawn CGI process [%s]: %s",
  7211. prog,
  7212. status);
  7213. goto done;
  7214. }
  7215. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  7216. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  7217. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  7218. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  7219. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  7220. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  7221. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  7222. /* Parent closes only one side of the pipes.
  7223. * If we don't mark them as closed, close() attempt before
  7224. * return from this function throws an exception on Windows.
  7225. * Windows does not like when closed descriptor is closed again. */
  7226. (void)close(fdin[0]);
  7227. (void)close(fdout[1]);
  7228. (void)close(fderr[1]);
  7229. fdin[0] = fdout[1] = fderr[1] = -1;
  7230. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  7231. status = strerror(ERRNO);
  7232. mg_cry(conn,
  7233. "Error: CGI program \"%s\": Can not open stdin: %s",
  7234. prog,
  7235. status);
  7236. send_http_error(conn,
  7237. 500,
  7238. "Error: CGI can not open fdin\nfopen: %s",
  7239. status);
  7240. goto done;
  7241. }
  7242. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  7243. status = strerror(ERRNO);
  7244. mg_cry(conn,
  7245. "Error: CGI program \"%s\": Can not open stdout: %s",
  7246. prog,
  7247. status);
  7248. send_http_error(conn,
  7249. 500,
  7250. "Error: CGI can not open fdout\nfopen: %s",
  7251. status);
  7252. goto done;
  7253. }
  7254. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  7255. status = strerror(ERRNO);
  7256. mg_cry(conn,
  7257. "Error: CGI program \"%s\": Can not open stderr: %s",
  7258. prog,
  7259. status);
  7260. send_http_error(conn,
  7261. 500,
  7262. "Error: CGI can not open fdout\nfopen: %s",
  7263. status);
  7264. goto done;
  7265. }
  7266. setbuf(in, NULL);
  7267. setbuf(out, NULL);
  7268. setbuf(err, NULL);
  7269. fout.access.fp = out;
  7270. if ((conn->request_info.content_length > 0) || conn->is_chunked) {
  7271. /* This is a POST/PUT request, or another request with body data. */
  7272. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  7273. /* Error sending the body data */
  7274. mg_cry(conn,
  7275. "Error: CGI program \"%s\": Forward body data failed",
  7276. prog);
  7277. goto done;
  7278. }
  7279. }
  7280. /* Close so child gets an EOF. */
  7281. fclose(in);
  7282. in = NULL;
  7283. fdin[1] = -1;
  7284. /* Now read CGI reply into a buffer. We need to set correct
  7285. * status code, thus we need to see all HTTP headers first.
  7286. * Do not send anything back to client, until we buffer in all
  7287. * HTTP headers. */
  7288. data_len = 0;
  7289. buf = (char *)mg_malloc(buflen);
  7290. if (buf == NULL) {
  7291. send_http_error(conn,
  7292. 500,
  7293. "Error: Not enough memory for CGI buffer (%u bytes)",
  7294. (unsigned int)buflen);
  7295. mg_cry(conn,
  7296. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  7297. "bytes)",
  7298. prog,
  7299. (unsigned int)buflen);
  7300. goto done;
  7301. }
  7302. headers_len = read_request(out, conn, buf, (int)buflen, &data_len);
  7303. if (headers_len <= 0) {
  7304. /* Could not parse the CGI response. Check if some error message on
  7305. * stderr. */
  7306. i = pull_all(err, conn, buf, (int)buflen);
  7307. if (i > 0) {
  7308. mg_cry(conn,
  7309. "Error: CGI program \"%s\" sent error "
  7310. "message: [%.*s]",
  7311. prog,
  7312. i,
  7313. buf);
  7314. send_http_error(conn,
  7315. 500,
  7316. "Error: CGI program \"%s\" sent error "
  7317. "message: [%.*s]",
  7318. prog,
  7319. i,
  7320. buf);
  7321. } else {
  7322. mg_cry(conn,
  7323. "Error: CGI program sent malformed or too big "
  7324. "(>%u bytes) HTTP headers: [%.*s]",
  7325. (unsigned)buflen,
  7326. data_len,
  7327. buf);
  7328. send_http_error(conn,
  7329. 500,
  7330. "Error: CGI program sent malformed or too big "
  7331. "(>%u bytes) HTTP headers: [%.*s]",
  7332. (unsigned)buflen,
  7333. data_len,
  7334. buf);
  7335. }
  7336. goto done;
  7337. }
  7338. pbuf = buf;
  7339. buf[headers_len - 1] = '\0';
  7340. parse_http_headers(&pbuf, &ri);
  7341. /* Make up and send the status line */
  7342. status_text = "OK";
  7343. if ((status = get_header(&ri, "Status")) != NULL) {
  7344. conn->status_code = atoi(status);
  7345. status_text = status;
  7346. while (isdigit(*(const unsigned char *)status_text)
  7347. || *status_text == ' ') {
  7348. status_text++;
  7349. }
  7350. } else if (get_header(&ri, "Location") != NULL) {
  7351. conn->status_code = 302;
  7352. } else {
  7353. conn->status_code = 200;
  7354. }
  7355. connection_state = get_header(&ri, "Connection");
  7356. if (!header_has_option(connection_state, "keep-alive")) {
  7357. conn->must_close = 1;
  7358. }
  7359. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  7360. /* Send headers */
  7361. for (i = 0; i < ri.num_headers; i++) {
  7362. mg_printf(conn,
  7363. "%s: %s\r\n",
  7364. ri.http_headers[i].name,
  7365. ri.http_headers[i].value);
  7366. }
  7367. mg_write(conn, "\r\n", 2);
  7368. /* Send chunk of data that may have been read after the headers */
  7369. conn->num_bytes_sent +=
  7370. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  7371. /* Read the rest of CGI output and send to the client */
  7372. send_file_data(conn, &fout, 0, INT64_MAX);
  7373. done:
  7374. mg_free(blk.var);
  7375. mg_free(blk.buf);
  7376. if (pid != (pid_t)-1) {
  7377. kill(pid, SIGKILL);
  7378. #if !defined(_WIN32)
  7379. {
  7380. int st;
  7381. while (waitpid(pid, &st, 0) != -1)
  7382. ; /* clean zombies */
  7383. }
  7384. #endif
  7385. }
  7386. if (fdin[0] != -1) {
  7387. close(fdin[0]);
  7388. }
  7389. if (fdout[1] != -1) {
  7390. close(fdout[1]);
  7391. }
  7392. if (in != NULL) {
  7393. fclose(in);
  7394. } else if (fdin[1] != -1) {
  7395. close(fdin[1]);
  7396. }
  7397. if (out != NULL) {
  7398. fclose(out);
  7399. } else if (fdout[0] != -1) {
  7400. close(fdout[0]);
  7401. }
  7402. if (err != NULL) {
  7403. fclose(err);
  7404. } else if (fderr[0] != -1) {
  7405. close(fderr[0]);
  7406. }
  7407. if (buf != NULL) {
  7408. mg_free(buf);
  7409. }
  7410. }
  7411. #endif /* !NO_CGI */
  7412. #if !defined(NO_FILES)
  7413. static void
  7414. mkcol(struct mg_connection *conn, const char *path)
  7415. {
  7416. int rc, body_len;
  7417. struct de de;
  7418. char date[64];
  7419. time_t curtime = time(NULL);
  7420. if (conn == NULL) {
  7421. return;
  7422. }
  7423. /* TODO (mid): Check the send_http_error situations in this function */
  7424. memset(&de.file, 0, sizeof(de.file));
  7425. if (!mg_stat(conn, path, &de.file)) {
  7426. mg_cry(conn,
  7427. "%s: mg_stat(%s) failed: %s",
  7428. __func__,
  7429. path,
  7430. strerror(ERRNO));
  7431. }
  7432. if (de.file.last_modified) {
  7433. /* TODO (high): This check does not seem to make any sense ! */
  7434. send_http_error(
  7435. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7436. return;
  7437. }
  7438. body_len = conn->data_len - conn->request_len;
  7439. if (body_len > 0) {
  7440. send_http_error(
  7441. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7442. return;
  7443. }
  7444. rc = mg_mkdir(conn, path, 0755);
  7445. if (rc == 0) {
  7446. conn->status_code = 201;
  7447. gmt_time_string(date, sizeof(date), &curtime);
  7448. mg_printf(conn,
  7449. "HTTP/1.1 %d Created\r\n"
  7450. "Date: %s\r\n",
  7451. conn->status_code,
  7452. date);
  7453. send_static_cache_header(conn);
  7454. mg_printf(conn,
  7455. "Content-Length: 0\r\n"
  7456. "Connection: %s\r\n\r\n",
  7457. suggest_connection_header(conn));
  7458. } else if (rc == -1) {
  7459. if (errno == EEXIST) {
  7460. send_http_error(
  7461. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7462. } else if (errno == EACCES) {
  7463. send_http_error(
  7464. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7465. } else if (errno == ENOENT) {
  7466. send_http_error(
  7467. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  7468. } else {
  7469. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  7470. }
  7471. }
  7472. }
  7473. static void
  7474. put_file(struct mg_connection *conn, const char *path)
  7475. {
  7476. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7477. const char *range;
  7478. int64_t r1, r2;
  7479. int rc;
  7480. char date[64];
  7481. time_t curtime = time(NULL);
  7482. if (conn == NULL) {
  7483. return;
  7484. }
  7485. if (mg_stat(conn, path, &file.stat)) {
  7486. /* File already exists */
  7487. conn->status_code = 200;
  7488. if (file.stat.is_directory) {
  7489. /* This is an already existing directory,
  7490. * so there is nothing to do for the server. */
  7491. rc = 0;
  7492. } else {
  7493. /* File exists and is not a directory. */
  7494. /* Can it be replaced? */
  7495. if (file.access.membuf != NULL) {
  7496. /* This is an "in-memory" file, that can not be replaced */
  7497. send_http_error(
  7498. conn,
  7499. 405,
  7500. "Error: Put not possible\nReplacing %s is not supported",
  7501. path);
  7502. return;
  7503. }
  7504. /* Check if the server may write this file */
  7505. if (access(path, W_OK) == 0) {
  7506. /* Access granted */
  7507. conn->status_code = 200;
  7508. rc = 1;
  7509. } else {
  7510. send_http_error(
  7511. conn,
  7512. 403,
  7513. "Error: Put not possible\nReplacing %s is not allowed",
  7514. path);
  7515. return;
  7516. }
  7517. }
  7518. } else {
  7519. /* File should be created */
  7520. conn->status_code = 201;
  7521. rc = put_dir(conn, path);
  7522. }
  7523. if (rc == 0) {
  7524. /* put_dir returns 0 if path is a directory */
  7525. gmt_time_string(date, sizeof(date), &curtime);
  7526. mg_printf(conn,
  7527. "HTTP/1.1 %d %s\r\n",
  7528. conn->status_code,
  7529. mg_get_response_code_text(NULL, conn->status_code));
  7530. send_no_cache_header(conn);
  7531. mg_printf(conn,
  7532. "Date: %s\r\n"
  7533. "Content-Length: 0\r\n"
  7534. "Connection: %s\r\n\r\n",
  7535. date,
  7536. suggest_connection_header(conn));
  7537. /* Request to create a directory has been fulfilled successfully.
  7538. * No need to put a file. */
  7539. return;
  7540. }
  7541. if (rc == -1) {
  7542. /* put_dir returns -1 if the path is too long */
  7543. send_http_error(conn,
  7544. 414,
  7545. "Error: Path too long\nput_dir(%s): %s",
  7546. path,
  7547. strerror(ERRNO));
  7548. return;
  7549. }
  7550. if (rc == -2) {
  7551. /* put_dir returns -2 if the directory can not be created */
  7552. send_http_error(conn,
  7553. 500,
  7554. "Error: Can not create directory\nput_dir(%s): %s",
  7555. path,
  7556. strerror(ERRNO));
  7557. return;
  7558. }
  7559. /* A file should be created or overwritten. */
  7560. /* TODO: Test if write or write+read is required. */
  7561. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  7562. || file.access.fp == NULL) {
  7563. (void)mg_fclose(&file.access);
  7564. send_http_error(conn,
  7565. 500,
  7566. "Error: Can not create file\nfopen(%s): %s",
  7567. path,
  7568. strerror(ERRNO));
  7569. return;
  7570. }
  7571. fclose_on_exec(&file.access, conn);
  7572. range = mg_get_header(conn, "Content-Range");
  7573. r1 = r2 = 0;
  7574. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  7575. conn->status_code = 206; /* Partial content */
  7576. fseeko(file.access.fp, r1, SEEK_SET);
  7577. }
  7578. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  7579. /* forward_body_data failed.
  7580. * The error code has already been sent to the client,
  7581. * and conn->status_code is already set. */
  7582. (void)mg_fclose(&file.access);
  7583. return;
  7584. }
  7585. if (mg_fclose(&file.access) != 0) {
  7586. /* fclose failed. This might have different reasons, but a likely
  7587. * one is "no space on disk", http 507. */
  7588. conn->status_code = 507;
  7589. }
  7590. gmt_time_string(date, sizeof(date), &curtime);
  7591. mg_printf(conn,
  7592. "HTTP/1.1 %d %s\r\n",
  7593. conn->status_code,
  7594. mg_get_response_code_text(NULL, conn->status_code));
  7595. send_no_cache_header(conn);
  7596. mg_printf(conn,
  7597. "Date: %s\r\n"
  7598. "Content-Length: 0\r\n"
  7599. "Connection: %s\r\n\r\n",
  7600. date,
  7601. suggest_connection_header(conn));
  7602. }
  7603. static void
  7604. delete_file(struct mg_connection *conn, const char *path)
  7605. {
  7606. struct de de;
  7607. memset(&de.file, 0, sizeof(de.file));
  7608. if (!mg_stat(conn, path, &de.file)) {
  7609. /* mg_stat returns 0 if the file does not exist */
  7610. send_http_error(conn,
  7611. 404,
  7612. "Error: Cannot delete file\nFile %s not found",
  7613. path);
  7614. return;
  7615. }
  7616. #if 0 /* Ignore if a file in memory is inside a folder */
  7617. if (de.access.membuf != NULL) {
  7618. /* the file is cached in memory */
  7619. send_http_error(
  7620. conn,
  7621. 405,
  7622. "Error: Delete not possible\nDeleting %s is not supported",
  7623. path);
  7624. return;
  7625. }
  7626. #endif
  7627. if (de.file.is_directory) {
  7628. if (remove_directory(conn, path)) {
  7629. /* Delete is successful: Return 204 without content. */
  7630. send_http_error(conn, 204, "%s", "");
  7631. } else {
  7632. /* Delete is not successful: Return 500 (Server error). */
  7633. send_http_error(conn, 500, "Error: Could not delete %s", path);
  7634. }
  7635. return;
  7636. }
  7637. /* This is an existing file (not a directory).
  7638. * Check if write permission is granted. */
  7639. if (access(path, W_OK) != 0) {
  7640. /* File is read only */
  7641. send_http_error(
  7642. conn,
  7643. 403,
  7644. "Error: Delete not possible\nDeleting %s is not allowed",
  7645. path);
  7646. return;
  7647. }
  7648. /* Try to delete it. */
  7649. if (mg_remove(conn, path) == 0) {
  7650. /* Delete was successful: Return 204 without content. */
  7651. send_http_error(conn, 204, "%s", "");
  7652. } else {
  7653. /* Delete not successful (file locked). */
  7654. send_http_error(conn,
  7655. 423,
  7656. "Error: Cannot delete file\nremove(%s): %s",
  7657. path,
  7658. strerror(ERRNO));
  7659. }
  7660. }
  7661. #endif /* !NO_FILES */
  7662. static void
  7663. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  7664. static void
  7665. do_ssi_include(struct mg_connection *conn,
  7666. const char *ssi,
  7667. char *tag,
  7668. int include_level)
  7669. {
  7670. char file_name[MG_BUF_LEN], path[512], *p;
  7671. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7672. size_t len;
  7673. int truncated = 0;
  7674. if (conn == NULL) {
  7675. return;
  7676. }
  7677. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  7678. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  7679. * always < MG_BUF_LEN. */
  7680. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  7681. /* File name is relative to the webserver root */
  7682. file_name[511] = 0;
  7683. (void)mg_snprintf(conn,
  7684. &truncated,
  7685. path,
  7686. sizeof(path),
  7687. "%s/%s",
  7688. conn->ctx->config[DOCUMENT_ROOT],
  7689. file_name);
  7690. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  7691. /* File name is relative to the webserver working directory
  7692. * or it is absolute system path */
  7693. file_name[511] = 0;
  7694. (void)
  7695. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  7696. } else if (sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1
  7697. || sscanf(tag, " \"%511[^\"]\"", file_name) == 1) {
  7698. /* File name is relative to the currect document */
  7699. file_name[511] = 0;
  7700. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  7701. if (!truncated) {
  7702. if ((p = strrchr(path, '/')) != NULL) {
  7703. p[1] = '\0';
  7704. }
  7705. len = strlen(path);
  7706. (void)mg_snprintf(conn,
  7707. &truncated,
  7708. path + len,
  7709. sizeof(path) - len,
  7710. "%s",
  7711. file_name);
  7712. }
  7713. } else {
  7714. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  7715. return;
  7716. }
  7717. if (truncated) {
  7718. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  7719. return;
  7720. }
  7721. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  7722. mg_cry(conn,
  7723. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  7724. tag,
  7725. path,
  7726. strerror(ERRNO));
  7727. } else {
  7728. fclose_on_exec(&file.access, conn);
  7729. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  7730. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  7731. path) > 0) {
  7732. send_ssi_file(conn, path, &file, include_level + 1);
  7733. } else {
  7734. send_file_data(conn, &file, 0, INT64_MAX);
  7735. }
  7736. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  7737. }
  7738. }
  7739. #if !defined(NO_POPEN)
  7740. static void
  7741. do_ssi_exec(struct mg_connection *conn, char *tag)
  7742. {
  7743. char cmd[1024] = "";
  7744. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7745. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  7746. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  7747. } else {
  7748. cmd[1023] = 0;
  7749. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  7750. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  7751. } else {
  7752. send_file_data(conn, &file, 0, INT64_MAX);
  7753. pclose(file.access.fp);
  7754. }
  7755. }
  7756. }
  7757. #endif /* !NO_POPEN */
  7758. static int
  7759. mg_fgetc(struct mg_file *filep, int offset)
  7760. {
  7761. if (filep == NULL) {
  7762. return EOF;
  7763. }
  7764. if (filep->access.membuf != NULL && offset >= 0
  7765. && ((unsigned int)(offset)) < filep->stat.size) {
  7766. return ((const unsigned char *)filep->access.membuf)[offset];
  7767. } else if (filep->access.fp != NULL) {
  7768. return fgetc(filep->access.fp);
  7769. } else {
  7770. return EOF;
  7771. }
  7772. }
  7773. static void
  7774. send_ssi_file(struct mg_connection *conn,
  7775. const char *path,
  7776. struct mg_file *filep,
  7777. int include_level)
  7778. {
  7779. char buf[MG_BUF_LEN];
  7780. int ch, offset, len, in_ssi_tag;
  7781. if (include_level > 10) {
  7782. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  7783. return;
  7784. }
  7785. in_ssi_tag = len = offset = 0;
  7786. while ((ch = mg_fgetc(filep, offset)) != EOF) {
  7787. if (in_ssi_tag && ch == '>') {
  7788. in_ssi_tag = 0;
  7789. buf[len++] = (char)ch;
  7790. buf[len] = '\0';
  7791. /* assert(len <= (int) sizeof(buf)); */
  7792. if (len > (int)sizeof(buf)) {
  7793. break;
  7794. }
  7795. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  7796. /* Not an SSI tag, pass it */
  7797. (void)mg_write(conn, buf, (size_t)len);
  7798. } else {
  7799. if (!memcmp(buf + 5, "include", 7)) {
  7800. do_ssi_include(conn, path, buf + 12, include_level);
  7801. #if !defined(NO_POPEN)
  7802. } else if (!memcmp(buf + 5, "exec", 4)) {
  7803. do_ssi_exec(conn, buf + 9);
  7804. #endif /* !NO_POPEN */
  7805. } else {
  7806. mg_cry(conn,
  7807. "%s: unknown SSI "
  7808. "command: \"%s\"",
  7809. path,
  7810. buf);
  7811. }
  7812. }
  7813. len = 0;
  7814. } else if (in_ssi_tag) {
  7815. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  7816. /* Not an SSI tag */
  7817. in_ssi_tag = 0;
  7818. } else if (len == (int)sizeof(buf) - 2) {
  7819. mg_cry(conn, "%s: SSI tag is too large", path);
  7820. len = 0;
  7821. }
  7822. buf[len++] = (char)(ch & 0xff);
  7823. } else if (ch == '<') {
  7824. in_ssi_tag = 1;
  7825. if (len > 0) {
  7826. mg_write(conn, buf, (size_t)len);
  7827. }
  7828. len = 0;
  7829. buf[len++] = (char)(ch & 0xff);
  7830. } else {
  7831. buf[len++] = (char)(ch & 0xff);
  7832. if (len == (int)sizeof(buf)) {
  7833. mg_write(conn, buf, (size_t)len);
  7834. len = 0;
  7835. }
  7836. }
  7837. }
  7838. /* Send the rest of buffered data */
  7839. if (len > 0) {
  7840. mg_write(conn, buf, (size_t)len);
  7841. }
  7842. }
  7843. static void
  7844. handle_ssi_file_request(struct mg_connection *conn,
  7845. const char *path,
  7846. struct mg_file *filep)
  7847. {
  7848. char date[64];
  7849. time_t curtime = time(NULL);
  7850. const char *cors1, *cors2, *cors3;
  7851. if (conn == NULL || path == NULL || filep == NULL) {
  7852. return;
  7853. }
  7854. if (mg_get_header(conn, "Origin")) {
  7855. /* Cross-origin resource sharing (CORS). */
  7856. cors1 = "Access-Control-Allow-Origin: ";
  7857. cors2 = conn->ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7858. cors3 = "\r\n";
  7859. } else {
  7860. cors1 = cors2 = cors3 = "";
  7861. }
  7862. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7863. /* File exists (precondition for calling this function),
  7864. * but can not be opened by the server. */
  7865. send_http_error(conn,
  7866. 500,
  7867. "Error: Cannot read file\nfopen(%s): %s",
  7868. path,
  7869. strerror(ERRNO));
  7870. } else {
  7871. conn->must_close = 1;
  7872. gmt_time_string(date, sizeof(date), &curtime);
  7873. fclose_on_exec(&filep->access, conn);
  7874. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7875. send_no_cache_header(conn);
  7876. mg_printf(conn,
  7877. "%s%s%s"
  7878. "Date: %s\r\n"
  7879. "Content-Type: text/html\r\n"
  7880. "Connection: %s\r\n\r\n",
  7881. cors1,
  7882. cors2,
  7883. cors3,
  7884. date,
  7885. suggest_connection_header(conn));
  7886. send_ssi_file(conn, path, filep, 0);
  7887. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  7888. }
  7889. }
  7890. #if !defined(NO_FILES)
  7891. static void
  7892. send_options(struct mg_connection *conn)
  7893. {
  7894. char date[64];
  7895. time_t curtime = time(NULL);
  7896. if (!conn) {
  7897. return;
  7898. }
  7899. conn->status_code = 200;
  7900. conn->must_close = 1;
  7901. gmt_time_string(date, sizeof(date), &curtime);
  7902. mg_printf(conn,
  7903. "HTTP/1.1 200 OK\r\n"
  7904. "Date: %s\r\n"
  7905. /* TODO: "Cache-Control" (?) */
  7906. "Connection: %s\r\n"
  7907. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  7908. "PROPFIND, MKCOL\r\n"
  7909. "DAV: 1\r\n\r\n",
  7910. date,
  7911. suggest_connection_header(conn));
  7912. }
  7913. /* Writes PROPFIND properties for a collection element */
  7914. static void
  7915. print_props(struct mg_connection *conn,
  7916. const char *uri,
  7917. struct mg_file_stat *filep)
  7918. {
  7919. char mtime[64];
  7920. if (conn == NULL || uri == NULL || filep == NULL) {
  7921. return;
  7922. }
  7923. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  7924. conn->num_bytes_sent +=
  7925. mg_printf(conn,
  7926. "<d:response>"
  7927. "<d:href>%s</d:href>"
  7928. "<d:propstat>"
  7929. "<d:prop>"
  7930. "<d:resourcetype>%s</d:resourcetype>"
  7931. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  7932. "<d:getlastmodified>%s</d:getlastmodified>"
  7933. "</d:prop>"
  7934. "<d:status>HTTP/1.1 200 OK</d:status>"
  7935. "</d:propstat>"
  7936. "</d:response>\n",
  7937. uri,
  7938. filep->is_directory ? "<d:collection/>" : "",
  7939. filep->size,
  7940. mtime);
  7941. }
  7942. static void
  7943. print_dav_dir_entry(struct de *de, void *data)
  7944. {
  7945. char href[PATH_MAX];
  7946. char href_encoded[PATH_MAX * 3 /* worst case */];
  7947. int truncated;
  7948. struct mg_connection *conn = (struct mg_connection *)data;
  7949. if (!de || !conn) {
  7950. return;
  7951. }
  7952. mg_snprintf(conn,
  7953. &truncated,
  7954. href,
  7955. sizeof(href),
  7956. "%s%s",
  7957. conn->request_info.local_uri,
  7958. de->file_name);
  7959. if (!truncated) {
  7960. mg_url_encode(href, href_encoded, PATH_MAX * 3);
  7961. print_props(conn, href_encoded, &de->file);
  7962. }
  7963. }
  7964. static void
  7965. handle_propfind(struct mg_connection *conn,
  7966. const char *path,
  7967. struct mg_file_stat *filep)
  7968. {
  7969. const char *depth = mg_get_header(conn, "Depth");
  7970. char date[64];
  7971. time_t curtime = time(NULL);
  7972. gmt_time_string(date, sizeof(date), &curtime);
  7973. if (!conn || !path || !filep || !conn->ctx) {
  7974. return;
  7975. }
  7976. conn->must_close = 1;
  7977. conn->status_code = 207;
  7978. mg_printf(conn,
  7979. "HTTP/1.1 207 Multi-Status\r\n"
  7980. "Date: %s\r\n",
  7981. date);
  7982. send_static_cache_header(conn);
  7983. mg_printf(conn,
  7984. "Connection: %s\r\n"
  7985. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  7986. suggest_connection_header(conn));
  7987. conn->num_bytes_sent +=
  7988. mg_printf(conn,
  7989. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  7990. "<d:multistatus xmlns:d='DAV:'>\n");
  7991. /* Print properties for the requested resource itself */
  7992. print_props(conn, conn->request_info.local_uri, filep);
  7993. /* If it is a directory, print directory entries too if Depth is not 0 */
  7994. if (filep && filep->is_directory
  7995. && !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")
  7996. && (depth == NULL || strcmp(depth, "0") != 0)) {
  7997. scan_directory(conn, path, conn, &print_dav_dir_entry);
  7998. }
  7999. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  8000. }
  8001. #endif
  8002. void
  8003. mg_lock_connection(struct mg_connection *conn)
  8004. {
  8005. if (conn) {
  8006. (void)pthread_mutex_lock(&conn->mutex);
  8007. }
  8008. }
  8009. void
  8010. mg_unlock_connection(struct mg_connection *conn)
  8011. {
  8012. if (conn) {
  8013. (void)pthread_mutex_unlock(&conn->mutex);
  8014. }
  8015. }
  8016. void
  8017. mg_lock_context(struct mg_context *ctx)
  8018. {
  8019. if (ctx) {
  8020. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  8021. }
  8022. }
  8023. void
  8024. mg_unlock_context(struct mg_context *ctx)
  8025. {
  8026. if (ctx) {
  8027. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  8028. }
  8029. }
  8030. #if defined(USE_TIMERS)
  8031. #include "timer.inl"
  8032. #endif /* USE_TIMERS */
  8033. #ifdef USE_LUA
  8034. #include "mod_lua.inl"
  8035. #endif /* USE_LUA */
  8036. #ifdef USE_DUKTAPE
  8037. #include "mod_duktape.inl"
  8038. #endif /* USE_DUKTAPE */
  8039. #if defined(USE_WEBSOCKET)
  8040. #define SHA_API static
  8041. #include "sha1.inl"
  8042. static int
  8043. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  8044. {
  8045. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  8046. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  8047. SHA1_CTX sha_ctx;
  8048. int truncated;
  8049. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  8050. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  8051. if (truncated) {
  8052. conn->must_close = 1;
  8053. return 0;
  8054. }
  8055. SHA1_Init(&sha_ctx);
  8056. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  8057. SHA1_Final(&sha_ctx, (unsigned char *)sha);
  8058. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  8059. mg_printf(conn,
  8060. "HTTP/1.1 101 Switching Protocols\r\n"
  8061. "Upgrade: websocket\r\n"
  8062. "Connection: Upgrade\r\n"
  8063. "Sec-WebSocket-Accept: %s\r\n",
  8064. b64_sha);
  8065. if (conn->request_info.acceptedWebSocketSubprotocol) {
  8066. mg_printf(conn,
  8067. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  8068. conn->request_info.acceptedWebSocketSubprotocol);
  8069. } else {
  8070. mg_printf(conn, "%s", "\r\n");
  8071. }
  8072. return 1;
  8073. }
  8074. static void
  8075. read_websocket(struct mg_connection *conn,
  8076. mg_websocket_data_handler ws_data_handler,
  8077. void *callback_data)
  8078. {
  8079. /* Pointer to the beginning of the portion of the incoming websocket
  8080. * message queue.
  8081. * The original websocket upgrade request is never removed, so the queue
  8082. * begins after it. */
  8083. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  8084. int n, error, exit_by_callback;
  8085. /* body_len is the length of the entire queue in bytes
  8086. * len is the length of the current message
  8087. * data_len is the length of the current message's data payload
  8088. * header_len is the length of the current message's header */
  8089. size_t i, len, mask_len = 0, data_len = 0, header_len, body_len;
  8090. /* "The masking key is a 32-bit value chosen at random by the client."
  8091. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  8092. */
  8093. unsigned char mask[4];
  8094. /* data points to the place where the message is stored when passed to
  8095. * the
  8096. * websocket_data callback. This is either mem on the stack, or a
  8097. * dynamically allocated buffer if it is too large. */
  8098. unsigned char mem[4096];
  8099. unsigned char *data = mem;
  8100. unsigned char mop; /* mask flag and opcode */
  8101. double timeout = -1.0;
  8102. if (conn->ctx->config[WEBSOCKET_TIMEOUT]) {
  8103. timeout = atoi(conn->ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  8104. }
  8105. if ((timeout <= 0.0) && (conn->ctx->config[REQUEST_TIMEOUT])) {
  8106. timeout = atoi(conn->ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8107. }
  8108. mg_set_thread_name("wsock");
  8109. /* Loop continuously, reading messages from the socket, invoking the
  8110. * callback, and waiting repeatedly until an error occurs. */
  8111. while (!conn->ctx->stop_flag) {
  8112. header_len = 0;
  8113. assert(conn->data_len >= conn->request_len);
  8114. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  8115. len = buf[1] & 127;
  8116. mask_len = (buf[1] & 128) ? 4 : 0;
  8117. if ((len < 126) && (body_len >= mask_len)) {
  8118. data_len = len;
  8119. header_len = 2 + mask_len;
  8120. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  8121. header_len = 4 + mask_len;
  8122. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  8123. } else if (body_len >= (10 + mask_len)) {
  8124. header_len = 10 + mask_len;
  8125. data_len = (((uint64_t)ntohl(*(uint32_t *)(void *)&buf[2]))
  8126. << 32) + ntohl(*(uint32_t *)(void *)&buf[6]);
  8127. }
  8128. }
  8129. if (header_len > 0 && body_len >= header_len) {
  8130. /* Allocate space to hold websocket payload */
  8131. data = mem;
  8132. if (data_len > sizeof(mem)) {
  8133. data = (unsigned char *)mg_malloc(data_len);
  8134. if (data == NULL) {
  8135. /* Allocation failed, exit the loop and then close the
  8136. * connection */
  8137. mg_cry(conn, "websocket out of memory; closing connection");
  8138. break;
  8139. }
  8140. }
  8141. /* Copy the mask before we shift the queue and destroy it */
  8142. if (mask_len > 0) {
  8143. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  8144. } else {
  8145. memset(mask, 0, sizeof(mask));
  8146. }
  8147. /* Read frame payload from the first message in the queue into
  8148. * data and advance the queue by moving the memory in place. */
  8149. assert(body_len >= header_len);
  8150. if (data_len + header_len > body_len) {
  8151. mop = buf[0]; /* current mask and opcode */
  8152. /* Overflow case */
  8153. len = body_len - header_len;
  8154. memcpy(data, buf + header_len, len);
  8155. error = 0;
  8156. while (len < data_len) {
  8157. n = pull(NULL,
  8158. conn,
  8159. (char *)(data + len),
  8160. (int)(data_len - len),
  8161. timeout);
  8162. if (n <= 0) {
  8163. error = 1;
  8164. break;
  8165. }
  8166. len += (size_t)n;
  8167. }
  8168. if (error) {
  8169. mg_cry(conn, "Websocket pull failed; closing connection");
  8170. break;
  8171. }
  8172. conn->data_len = conn->request_len;
  8173. } else {
  8174. mop = buf[0]; /* current mask and opcode, overwritten by
  8175. * memmove() */
  8176. /* Length of the message being read at the front of the
  8177. * queue */
  8178. len = data_len + header_len;
  8179. /* Copy the data payload into the data pointer for the
  8180. * callback */
  8181. memcpy(data, buf + header_len, data_len);
  8182. /* Move the queue forward len bytes */
  8183. memmove(buf, buf + len, body_len - len);
  8184. /* Mark the queue as advanced */
  8185. conn->data_len -= (int)len;
  8186. }
  8187. /* Apply mask if necessary */
  8188. if (mask_len > 0) {
  8189. for (i = 0; i < data_len; ++i) {
  8190. data[i] ^= mask[i & 3];
  8191. }
  8192. }
  8193. /* Exit the loop if callback signals to exit (server side),
  8194. * or "connection close" opcode received (client side). */
  8195. exit_by_callback = 0;
  8196. if ((ws_data_handler != NULL)
  8197. && !ws_data_handler(
  8198. conn, mop, (char *)data, data_len, callback_data)) {
  8199. exit_by_callback = 1;
  8200. }
  8201. if (data != mem) {
  8202. mg_free(data);
  8203. }
  8204. if (exit_by_callback
  8205. || ((mop & 0xf) == WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  8206. /* Opcode == 8, connection close */
  8207. break;
  8208. }
  8209. /* Not breaking the loop, process next websocket frame. */
  8210. } else {
  8211. /* Read from the socket into the next available location in the
  8212. * message queue. */
  8213. if ((n = pull(NULL,
  8214. conn,
  8215. conn->buf + conn->data_len,
  8216. conn->buf_size - conn->data_len,
  8217. timeout)) <= 0) {
  8218. /* Error, no bytes read */
  8219. break;
  8220. }
  8221. conn->data_len += n;
  8222. }
  8223. }
  8224. mg_set_thread_name("worker");
  8225. }
  8226. static int
  8227. mg_websocket_write_exec(struct mg_connection *conn,
  8228. int opcode,
  8229. const char *data,
  8230. size_t dataLen,
  8231. uint32_t masking_key)
  8232. {
  8233. unsigned char header[14];
  8234. size_t headerLen = 1;
  8235. int retval = -1;
  8236. #if defined(__GNUC__) || defined(__MINGW32__)
  8237. /* Disable spurious conversion warning for GCC */
  8238. #pragma GCC diagnostic push
  8239. #pragma GCC diagnostic ignored "-Wconversion"
  8240. #endif
  8241. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  8242. #if defined(__GNUC__) || defined(__MINGW32__)
  8243. #pragma GCC diagnostic pop
  8244. #endif
  8245. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  8246. if (dataLen < 126) {
  8247. /* inline 7-bit length field */
  8248. header[1] = (unsigned char)dataLen;
  8249. headerLen = 2;
  8250. } else if (dataLen <= 0xFFFF) {
  8251. /* 16-bit length field */
  8252. uint16_t len = htons((uint16_t)dataLen);
  8253. header[1] = 126;
  8254. memcpy(header + 2, &len, 2);
  8255. headerLen = 4;
  8256. } else {
  8257. /* 64-bit length field */
  8258. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  8259. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  8260. header[1] = 127;
  8261. memcpy(header + 2, &len1, 4);
  8262. memcpy(header + 6, &len2, 4);
  8263. headerLen = 10;
  8264. }
  8265. if (masking_key) {
  8266. /* add mask */
  8267. header[1] |= 0x80;
  8268. memcpy(header + headerLen, &masking_key, 4);
  8269. headerLen += 4;
  8270. }
  8271. /* Note that POSIX/Winsock's send() is threadsafe
  8272. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  8273. * but mongoose's mg_printf/mg_write is not (because of the loop in
  8274. * push(), although that is only a problem if the packet is large or
  8275. * outgoing buffer is full). */
  8276. (void)mg_lock_connection(conn);
  8277. retval = mg_write(conn, header, headerLen);
  8278. if (dataLen > 0) {
  8279. retval = mg_write(conn, data, dataLen);
  8280. }
  8281. mg_unlock_connection(conn);
  8282. return retval;
  8283. }
  8284. int
  8285. mg_websocket_write(struct mg_connection *conn,
  8286. int opcode,
  8287. const char *data,
  8288. size_t dataLen)
  8289. {
  8290. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  8291. }
  8292. static void
  8293. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  8294. {
  8295. size_t i = 0;
  8296. i = 0;
  8297. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  8298. /* Convert in 32 bit words, if data is 4 byte aligned */
  8299. while (i < (in_len - 3)) {
  8300. *(uint32_t *)(void *)(out + i) =
  8301. *(uint32_t *)(void *)(in + i) ^ masking_key;
  8302. i += 4;
  8303. }
  8304. }
  8305. if (i != in_len) {
  8306. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  8307. while (i < in_len) {
  8308. *(uint8_t *)(void *)(out + i) =
  8309. *(uint8_t *)(void *)(in + i)
  8310. ^ *(((uint8_t *)&masking_key) + (i % 4));
  8311. i++;
  8312. }
  8313. }
  8314. }
  8315. int
  8316. mg_websocket_client_write(struct mg_connection *conn,
  8317. int opcode,
  8318. const char *data,
  8319. size_t dataLen)
  8320. {
  8321. int retval = -1;
  8322. char *masked_data = (char *)mg_malloc(((dataLen + 7) / 4) * 4);
  8323. uint32_t masking_key = (uint32_t)get_random();
  8324. if (masked_data == NULL) {
  8325. /* Return -1 in an error case */
  8326. mg_cry(conn,
  8327. "Cannot allocate buffer for masked websocket response: "
  8328. "Out of memory");
  8329. return -1;
  8330. }
  8331. mask_data(data, dataLen, masking_key, masked_data);
  8332. retval = mg_websocket_write_exec(
  8333. conn, opcode, masked_data, dataLen, masking_key);
  8334. mg_free(masked_data);
  8335. return retval;
  8336. }
  8337. static void
  8338. handle_websocket_request(struct mg_connection *conn,
  8339. const char *path,
  8340. int is_callback_resource,
  8341. struct mg_websocket_subprotocols *subprotocols,
  8342. mg_websocket_connect_handler ws_connect_handler,
  8343. mg_websocket_ready_handler ws_ready_handler,
  8344. mg_websocket_data_handler ws_data_handler,
  8345. mg_websocket_close_handler ws_close_handler,
  8346. void *cbData)
  8347. {
  8348. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  8349. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  8350. int lua_websock = 0;
  8351. #if !defined(USE_LUA)
  8352. (void)path;
  8353. #endif
  8354. /* Step 1: Check websocket protocol version. */
  8355. /* Step 1.1: Check Sec-WebSocket-Key. */
  8356. if (!websock_key) {
  8357. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  8358. * requires a Sec-WebSocket-Key header.
  8359. */
  8360. /* It could be the hixie draft version
  8361. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  8362. */
  8363. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  8364. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  8365. char key3[8];
  8366. if ((key1 != NULL) && (key2 != NULL)) {
  8367. /* This version uses 8 byte body data in a GET request */
  8368. conn->content_len = 8;
  8369. if (8 == mg_read(conn, key3, 8)) {
  8370. /* This is the hixie version */
  8371. send_http_error(conn,
  8372. 426,
  8373. "%s",
  8374. "Protocol upgrade to RFC 6455 required");
  8375. return;
  8376. }
  8377. }
  8378. /* This is an unknown version */
  8379. send_http_error(conn, 400, "%s", "Malformed websocket request");
  8380. return;
  8381. }
  8382. /* Step 1.2: Check websocket protocol version. */
  8383. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  8384. if (version == NULL || strcmp(version, "13") != 0) {
  8385. /* Reject wrong versions */
  8386. send_http_error(conn, 426, "%s", "Protocol upgrade required");
  8387. return;
  8388. }
  8389. /* Step 1.3: Could check for "Host", but we do not really nead this
  8390. * value for anything, so just ignore it. */
  8391. /* Step 2: If a callback is responsible, call it. */
  8392. if (is_callback_resource) {
  8393. /* Step 2.1 check and select subprotocol */
  8394. const char *protocol = mg_get_header(conn, "Sec-WebSocket-Protocol");
  8395. if (protocol && subprotocols) {
  8396. int idx;
  8397. unsigned long len;
  8398. const char *sep, *curSubProtocol,
  8399. *acceptedWebSocketSubprotocol = NULL;
  8400. /* look for matching subprotocol */
  8401. do {
  8402. sep = strchr(protocol, ',');
  8403. curSubProtocol = protocol;
  8404. len = sep ? (unsigned long)(sep - protocol)
  8405. : (unsigned long)strlen(protocol);
  8406. while (sep && isspace(*++sep))
  8407. ; // ignore leading whitespaces
  8408. protocol = sep;
  8409. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  8410. if ((strlen(subprotocols->subprotocols[idx]) == len)
  8411. && (strncmp(curSubProtocol,
  8412. subprotocols->subprotocols[idx],
  8413. len) == 0)) {
  8414. acceptedWebSocketSubprotocol =
  8415. subprotocols->subprotocols[idx];
  8416. break;
  8417. }
  8418. }
  8419. } while (sep && !acceptedWebSocketSubprotocol);
  8420. conn->request_info.acceptedWebSocketSubprotocol =
  8421. acceptedWebSocketSubprotocol;
  8422. } else if (protocol) {
  8423. /* keep legacy behavior */
  8424. /* The protocol is a comma seperated list of names. */
  8425. /* The server must only return one value from this list. */
  8426. /* First check if it is a list or just a single value. */
  8427. const char *sep = strrchr(protocol, ',');
  8428. if (sep == NULL) {
  8429. /* Just a single protocol -> accept it. */
  8430. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  8431. } else {
  8432. /* Multiple protocols -> accept the last one. */
  8433. /* This is just a quick fix if the client offers multiple
  8434. * protocols. The handler should have a list of accepted
  8435. * protocols on his own
  8436. * and use it to select one protocol among those the client has
  8437. * offered.
  8438. */
  8439. while (isspace(*++sep))
  8440. ; // ignore leading whitespaces
  8441. conn->request_info.acceptedWebSocketSubprotocol = sep;
  8442. }
  8443. }
  8444. if (ws_connect_handler != NULL
  8445. && ws_connect_handler(conn, cbData) != 0) {
  8446. /* C callback has returned non-zero, do not proceed with
  8447. * handshake.
  8448. */
  8449. /* Note that C callbacks are no longer called when Lua is
  8450. * responsible, so C can no longer filter callbacks for Lua. */
  8451. return;
  8452. }
  8453. }
  8454. #if defined(USE_LUA)
  8455. /* Step 3: No callback. Check if Lua is responsible. */
  8456. else {
  8457. /* Step 3.1: Check if Lua is responsible. */
  8458. if (conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  8459. lua_websock =
  8460. match_prefix(conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  8461. strlen(
  8462. conn->ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  8463. path);
  8464. }
  8465. if (lua_websock) {
  8466. /* Step 3.2: Lua is responsible: call it. */
  8467. conn->lua_websocket_state = lua_websocket_new(path, conn);
  8468. if (!conn->lua_websocket_state) {
  8469. /* Lua rejected the new client */
  8470. return;
  8471. }
  8472. }
  8473. }
  8474. #endif
  8475. /* Step 4: Check if there is a responsible websocket handler. */
  8476. if (!is_callback_resource && !lua_websock) {
  8477. /* There is no callback, and Lua is not responsible either. */
  8478. /* Reply with a 404 Not Found or with nothing at all?
  8479. * TODO (mid): check the websocket standards, how to reply to
  8480. * requests to invalid websocket addresses. */
  8481. send_http_error(conn, 404, "%s", "Not found");
  8482. return;
  8483. }
  8484. /* Step 5: The websocket connection has been accepted */
  8485. if (!send_websocket_handshake(conn, websock_key)) {
  8486. send_http_error(conn, 500, "%s", "Websocket handshake failed");
  8487. return;
  8488. }
  8489. /* Step 6: Call the ready handler */
  8490. if (is_callback_resource) {
  8491. if (ws_ready_handler != NULL) {
  8492. ws_ready_handler(conn, cbData);
  8493. }
  8494. #if defined(USE_LUA)
  8495. } else if (lua_websock) {
  8496. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  8497. /* the ready handler returned false */
  8498. return;
  8499. }
  8500. #endif
  8501. }
  8502. /* Step 7: Enter the read loop */
  8503. if (is_callback_resource) {
  8504. read_websocket(conn, ws_data_handler, cbData);
  8505. #if defined(USE_LUA)
  8506. } else if (lua_websock) {
  8507. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  8508. #endif
  8509. }
  8510. /* Step 8: Call the close handler */
  8511. if (ws_close_handler) {
  8512. ws_close_handler(conn, cbData);
  8513. }
  8514. }
  8515. static int
  8516. is_websocket_protocol(const struct mg_connection *conn)
  8517. {
  8518. const char *upgrade, *connection;
  8519. /* A websocket protocoll has the following HTTP headers:
  8520. *
  8521. * Connection: Upgrade
  8522. * Upgrade: Websocket
  8523. */
  8524. upgrade = mg_get_header(conn, "Upgrade");
  8525. if (upgrade == NULL) {
  8526. return 0; /* fail early, don't waste time checking other header
  8527. * fields
  8528. */
  8529. }
  8530. if (!mg_strcasestr(upgrade, "websocket")) {
  8531. return 0;
  8532. }
  8533. connection = mg_get_header(conn, "Connection");
  8534. if (connection == NULL) {
  8535. return 0;
  8536. }
  8537. if (!mg_strcasestr(connection, "upgrade")) {
  8538. return 0;
  8539. }
  8540. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  8541. * "Sec-WebSocket-Version" are also required.
  8542. * Don't check them here, since even an unsupported websocket protocol
  8543. * request still IS a websocket request (in contrast to a standard HTTP
  8544. * request). It will fail later in handle_websocket_request.
  8545. */
  8546. return 1;
  8547. }
  8548. #endif /* !USE_WEBSOCKET */
  8549. static int
  8550. isbyte(int n)
  8551. {
  8552. return n >= 0 && n <= 255;
  8553. }
  8554. static int
  8555. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  8556. {
  8557. int n, a, b, c, d, slash = 32, len = 0;
  8558. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5
  8559. || sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) && isbyte(a)
  8560. && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0
  8561. && slash < 33) {
  8562. len = n;
  8563. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  8564. | (uint32_t)d;
  8565. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  8566. }
  8567. return len;
  8568. }
  8569. static int
  8570. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  8571. {
  8572. int throttle = 0;
  8573. struct vec vec, val;
  8574. uint32_t net, mask;
  8575. char mult;
  8576. double v;
  8577. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  8578. mult = ',';
  8579. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  8580. || (v < 0) || ((lowercase(&mult) != 'k')
  8581. && (lowercase(&mult) != 'm') && (mult != ','))) {
  8582. continue;
  8583. }
  8584. v *= (lowercase(&mult) == 'k')
  8585. ? 1024
  8586. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  8587. if (vec.len == 1 && vec.ptr[0] == '*') {
  8588. throttle = (int)v;
  8589. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  8590. if ((remote_ip & mask) == net) {
  8591. throttle = (int)v;
  8592. }
  8593. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  8594. throttle = (int)v;
  8595. }
  8596. }
  8597. return throttle;
  8598. }
  8599. static uint32_t
  8600. get_remote_ip(const struct mg_connection *conn)
  8601. {
  8602. if (!conn) {
  8603. return 0;
  8604. }
  8605. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  8606. }
  8607. /* The mg_upload function is superseeded by mg_handle_form_request. */
  8608. #include "handle_form.inl"
  8609. #if defined(MG_LEGACY_INTERFACE)
  8610. /* Implement the deprecated mg_upload function by calling the new
  8611. * mg_handle_form_request function. While mg_upload could only handle
  8612. * HTML forms sent as POST request in multipart/form-data format
  8613. * containing only file input elements, mg_handle_form_request can
  8614. * handle all form input elements and all standard request methods. */
  8615. struct mg_upload_user_data {
  8616. struct mg_connection *conn;
  8617. const char *destination_dir;
  8618. int num_uploaded_files;
  8619. };
  8620. /* Helper function for deprecated mg_upload. */
  8621. static int
  8622. mg_upload_field_found(const char *key,
  8623. const char *filename,
  8624. char *path,
  8625. size_t pathlen,
  8626. void *user_data)
  8627. {
  8628. int truncated = 0;
  8629. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8630. (void)key;
  8631. if (!filename) {
  8632. mg_cry(fud->conn, "%s: No filename set", __func__);
  8633. return FORM_FIELD_STORAGE_ABORT;
  8634. }
  8635. mg_snprintf(fud->conn,
  8636. &truncated,
  8637. path,
  8638. pathlen - 1,
  8639. "%s/%s",
  8640. fud->destination_dir,
  8641. filename);
  8642. if (!truncated) {
  8643. mg_cry(fud->conn, "%s: File path too long", __func__);
  8644. return FORM_FIELD_STORAGE_ABORT;
  8645. }
  8646. return FORM_FIELD_STORAGE_STORE;
  8647. }
  8648. /* Helper function for deprecated mg_upload. */
  8649. static int
  8650. mg_upload_field_get(const char *key,
  8651. const char *value,
  8652. size_t value_size,
  8653. void *user_data)
  8654. {
  8655. /* Function should never be called */
  8656. (void)key;
  8657. (void)value;
  8658. (void)value_size;
  8659. (void)user_data;
  8660. return 0;
  8661. }
  8662. /* Helper function for deprecated mg_upload. */
  8663. static int
  8664. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  8665. {
  8666. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  8667. (void)file_size;
  8668. fud->num_uploaded_files++;
  8669. fud->conn->ctx->callbacks.upload(fud->conn, path);
  8670. return 0;
  8671. }
  8672. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  8673. int
  8674. mg_upload(struct mg_connection *conn, const char *destination_dir)
  8675. {
  8676. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  8677. struct mg_form_data_handler fdh = {mg_upload_field_found,
  8678. mg_upload_field_get,
  8679. mg_upload_field_stored,
  8680. 0};
  8681. int ret;
  8682. fdh.user_data = (void *)&fud;
  8683. ret = mg_handle_form_request(conn, &fdh);
  8684. if (ret < 0) {
  8685. mg_cry(conn, "%s: Error while parsing the request", __func__);
  8686. }
  8687. return fud.num_uploaded_files;
  8688. }
  8689. #endif
  8690. static int
  8691. get_first_ssl_listener_index(const struct mg_context *ctx)
  8692. {
  8693. unsigned int i;
  8694. int idx = -1;
  8695. if (ctx) {
  8696. for (i = 0; idx == -1 && i < ctx->num_listening_sockets; i++) {
  8697. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  8698. }
  8699. }
  8700. return idx;
  8701. }
  8702. static void
  8703. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  8704. {
  8705. char host[1025];
  8706. const char *host_header;
  8707. size_t hostlen;
  8708. host_header = mg_get_header(conn, "Host");
  8709. hostlen = sizeof(host);
  8710. if (host_header != NULL) {
  8711. char *pos;
  8712. mg_strlcpy(host, host_header, hostlen);
  8713. host[hostlen - 1] = '\0';
  8714. pos = strchr(host, ':');
  8715. if (pos != NULL) {
  8716. *pos = '\0';
  8717. }
  8718. } else {
  8719. /* Cannot get host from the Host: header.
  8720. * Fallback to our IP address. */
  8721. if (conn) {
  8722. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  8723. }
  8724. }
  8725. /* Send host, port, uri and (if it exists) ?query_string */
  8726. if (conn) {
  8727. mg_printf(conn,
  8728. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  8729. host,
  8730. #if defined(USE_IPV6)
  8731. (conn->ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  8732. == AF_INET6)
  8733. ? (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8734. .lsa.sin6.sin6_port)
  8735. :
  8736. #endif
  8737. (int)ntohs(conn->ctx->listening_sockets[ssl_index]
  8738. .lsa.sin.sin_port),
  8739. conn->request_info.local_uri,
  8740. (conn->request_info.query_string == NULL) ? "" : "?",
  8741. (conn->request_info.query_string == NULL)
  8742. ? ""
  8743. : conn->request_info.query_string);
  8744. }
  8745. }
  8746. static void
  8747. mg_set_handler_type(struct mg_context *ctx,
  8748. const char *uri,
  8749. int handler_type,
  8750. int is_delete_request,
  8751. mg_request_handler handler,
  8752. struct mg_websocket_subprotocols *subprotocols,
  8753. mg_websocket_connect_handler connect_handler,
  8754. mg_websocket_ready_handler ready_handler,
  8755. mg_websocket_data_handler data_handler,
  8756. mg_websocket_close_handler close_handler,
  8757. mg_authorization_handler auth_handler,
  8758. void *cbdata)
  8759. {
  8760. struct mg_handler_info *tmp_rh, **lastref;
  8761. size_t urilen = strlen(uri);
  8762. if (handler_type == WEBSOCKET_HANDLER) {
  8763. /* assert(handler == NULL); */
  8764. /* assert(is_delete_request || connect_handler!=NULL ||
  8765. * ready_handler!=NULL || data_handler!=NULL ||
  8766. * close_handler!=NULL);
  8767. */
  8768. /* assert(auth_handler == NULL); */
  8769. if (handler != NULL) {
  8770. return;
  8771. }
  8772. if (!is_delete_request && connect_handler == NULL
  8773. && ready_handler == NULL
  8774. && data_handler == NULL
  8775. && close_handler == NULL) {
  8776. return;
  8777. }
  8778. if (auth_handler != NULL) {
  8779. return;
  8780. }
  8781. } else if (handler_type == REQUEST_HANDLER) {
  8782. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8783. * data_handler==NULL && close_handler==NULL); */
  8784. /* assert(is_delete_request || (handler!=NULL));
  8785. */
  8786. /* assert(auth_handler == NULL); */
  8787. if (connect_handler != NULL || ready_handler != NULL
  8788. || data_handler != NULL
  8789. || close_handler != NULL) {
  8790. return;
  8791. }
  8792. if (!is_delete_request && (handler == NULL)) {
  8793. return;
  8794. }
  8795. if (auth_handler != NULL) {
  8796. return;
  8797. }
  8798. } else { /* AUTH_HANDLER */
  8799. /* assert(handler == NULL); */
  8800. /* assert(connect_handler==NULL && ready_handler==NULL &&
  8801. * data_handler==NULL && close_handler==NULL); */
  8802. /* assert(auth_handler != NULL); */
  8803. if (handler != NULL) {
  8804. return;
  8805. }
  8806. if (connect_handler != NULL || ready_handler != NULL
  8807. || data_handler != NULL
  8808. || close_handler != NULL) {
  8809. return;
  8810. }
  8811. if (!is_delete_request && (auth_handler == NULL)) {
  8812. return;
  8813. }
  8814. }
  8815. if (!ctx) {
  8816. return;
  8817. }
  8818. mg_lock_context(ctx);
  8819. /* first try to find an existing handler */
  8820. lastref = &(ctx->handlers);
  8821. for (tmp_rh = ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  8822. if (tmp_rh->handler_type == handler_type) {
  8823. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8824. if (!is_delete_request) {
  8825. /* update existing handler */
  8826. if (handler_type == REQUEST_HANDLER) {
  8827. tmp_rh->handler = handler;
  8828. } else if (handler_type == WEBSOCKET_HANDLER) {
  8829. tmp_rh->subprotocols = subprotocols;
  8830. tmp_rh->connect_handler = connect_handler;
  8831. tmp_rh->ready_handler = ready_handler;
  8832. tmp_rh->data_handler = data_handler;
  8833. tmp_rh->close_handler = close_handler;
  8834. } else { /* AUTH_HANDLER */
  8835. tmp_rh->auth_handler = auth_handler;
  8836. }
  8837. tmp_rh->cbdata = cbdata;
  8838. } else {
  8839. /* remove existing handler */
  8840. *lastref = tmp_rh->next;
  8841. mg_free(tmp_rh->uri);
  8842. mg_free(tmp_rh);
  8843. }
  8844. mg_unlock_context(ctx);
  8845. return;
  8846. }
  8847. }
  8848. lastref = &(tmp_rh->next);
  8849. }
  8850. if (is_delete_request) {
  8851. /* no handler to set, this was a remove request to a non-existing
  8852. * handler */
  8853. mg_unlock_context(ctx);
  8854. return;
  8855. }
  8856. tmp_rh =
  8857. (struct mg_handler_info *)mg_calloc(sizeof(struct mg_handler_info), 1);
  8858. if (tmp_rh == NULL) {
  8859. mg_unlock_context(ctx);
  8860. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8861. return;
  8862. }
  8863. tmp_rh->uri = mg_strdup(uri);
  8864. if (!tmp_rh->uri) {
  8865. mg_unlock_context(ctx);
  8866. mg_free(tmp_rh);
  8867. mg_cry(fc(ctx), "%s", "Cannot create new request handler struct, OOM");
  8868. return;
  8869. }
  8870. tmp_rh->uri_len = urilen;
  8871. if (handler_type == REQUEST_HANDLER) {
  8872. tmp_rh->handler = handler;
  8873. } else if (handler_type == WEBSOCKET_HANDLER) {
  8874. tmp_rh->subprotocols = subprotocols;
  8875. tmp_rh->connect_handler = connect_handler;
  8876. tmp_rh->ready_handler = ready_handler;
  8877. tmp_rh->data_handler = data_handler;
  8878. tmp_rh->close_handler = close_handler;
  8879. } else { /* AUTH_HANDLER */
  8880. tmp_rh->auth_handler = auth_handler;
  8881. }
  8882. tmp_rh->cbdata = cbdata;
  8883. tmp_rh->handler_type = handler_type;
  8884. tmp_rh->next = NULL;
  8885. *lastref = tmp_rh;
  8886. mg_unlock_context(ctx);
  8887. }
  8888. void
  8889. mg_set_request_handler(struct mg_context *ctx,
  8890. const char *uri,
  8891. mg_request_handler handler,
  8892. void *cbdata)
  8893. {
  8894. mg_set_handler_type(ctx,
  8895. uri,
  8896. REQUEST_HANDLER,
  8897. handler == NULL,
  8898. handler,
  8899. NULL,
  8900. NULL,
  8901. NULL,
  8902. NULL,
  8903. NULL,
  8904. NULL,
  8905. cbdata);
  8906. }
  8907. void
  8908. mg_set_websocket_handler(struct mg_context *ctx,
  8909. const char *uri,
  8910. mg_websocket_connect_handler connect_handler,
  8911. mg_websocket_ready_handler ready_handler,
  8912. mg_websocket_data_handler data_handler,
  8913. mg_websocket_close_handler close_handler,
  8914. void *cbdata)
  8915. {
  8916. mg_set_websocket_handler_with_subprotocols(ctx,
  8917. uri,
  8918. NULL,
  8919. connect_handler,
  8920. ready_handler,
  8921. data_handler,
  8922. close_handler,
  8923. cbdata);
  8924. }
  8925. void
  8926. mg_set_websocket_handler_with_subprotocols(
  8927. struct mg_context *ctx,
  8928. const char *uri,
  8929. struct mg_websocket_subprotocols *subprotocols,
  8930. mg_websocket_connect_handler connect_handler,
  8931. mg_websocket_ready_handler ready_handler,
  8932. mg_websocket_data_handler data_handler,
  8933. mg_websocket_close_handler close_handler,
  8934. void *cbdata)
  8935. {
  8936. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  8937. && (data_handler == NULL)
  8938. && (close_handler == NULL);
  8939. mg_set_handler_type(ctx,
  8940. uri,
  8941. WEBSOCKET_HANDLER,
  8942. is_delete_request,
  8943. NULL,
  8944. subprotocols,
  8945. connect_handler,
  8946. ready_handler,
  8947. data_handler,
  8948. close_handler,
  8949. NULL,
  8950. cbdata);
  8951. }
  8952. void
  8953. mg_set_auth_handler(struct mg_context *ctx,
  8954. const char *uri,
  8955. mg_request_handler handler,
  8956. void *cbdata)
  8957. {
  8958. mg_set_handler_type(ctx,
  8959. uri,
  8960. AUTH_HANDLER,
  8961. handler == NULL,
  8962. NULL,
  8963. NULL,
  8964. NULL,
  8965. NULL,
  8966. NULL,
  8967. NULL,
  8968. handler,
  8969. cbdata);
  8970. }
  8971. static int
  8972. get_request_handler(struct mg_connection *conn,
  8973. int handler_type,
  8974. mg_request_handler *handler,
  8975. struct mg_websocket_subprotocols **subprotocols,
  8976. mg_websocket_connect_handler *connect_handler,
  8977. mg_websocket_ready_handler *ready_handler,
  8978. mg_websocket_data_handler *data_handler,
  8979. mg_websocket_close_handler *close_handler,
  8980. mg_authorization_handler *auth_handler,
  8981. void **cbdata)
  8982. {
  8983. const struct mg_request_info *request_info = mg_get_request_info(conn);
  8984. if (request_info) {
  8985. const char *uri = request_info->local_uri;
  8986. size_t urilen = strlen(uri);
  8987. struct mg_handler_info *tmp_rh;
  8988. if (!conn || !conn->ctx) {
  8989. return 0;
  8990. }
  8991. mg_lock_context(conn->ctx);
  8992. /* first try for an exact match */
  8993. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  8994. tmp_rh = tmp_rh->next) {
  8995. if (tmp_rh->handler_type == handler_type) {
  8996. if (urilen == tmp_rh->uri_len && !strcmp(tmp_rh->uri, uri)) {
  8997. if (handler_type == WEBSOCKET_HANDLER) {
  8998. *subprotocols = tmp_rh->subprotocols;
  8999. *connect_handler = tmp_rh->connect_handler;
  9000. *ready_handler = tmp_rh->ready_handler;
  9001. *data_handler = tmp_rh->data_handler;
  9002. *close_handler = tmp_rh->close_handler;
  9003. } else if (handler_type == REQUEST_HANDLER) {
  9004. *handler = tmp_rh->handler;
  9005. } else { /* AUTH_HANDLER */
  9006. *auth_handler = tmp_rh->auth_handler;
  9007. }
  9008. *cbdata = tmp_rh->cbdata;
  9009. mg_unlock_context(conn->ctx);
  9010. return 1;
  9011. }
  9012. }
  9013. }
  9014. /* next try for a partial match, we will accept uri/something */
  9015. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9016. tmp_rh = tmp_rh->next) {
  9017. if (tmp_rh->handler_type == handler_type) {
  9018. if (tmp_rh->uri_len < urilen && uri[tmp_rh->uri_len] == '/'
  9019. && memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0) {
  9020. if (handler_type == WEBSOCKET_HANDLER) {
  9021. *subprotocols = tmp_rh->subprotocols;
  9022. *connect_handler = tmp_rh->connect_handler;
  9023. *ready_handler = tmp_rh->ready_handler;
  9024. *data_handler = tmp_rh->data_handler;
  9025. *close_handler = tmp_rh->close_handler;
  9026. } else if (handler_type == REQUEST_HANDLER) {
  9027. *handler = tmp_rh->handler;
  9028. } else { /* AUTH_HANDLER */
  9029. *auth_handler = tmp_rh->auth_handler;
  9030. }
  9031. *cbdata = tmp_rh->cbdata;
  9032. mg_unlock_context(conn->ctx);
  9033. return 1;
  9034. }
  9035. }
  9036. }
  9037. /* finally try for pattern match */
  9038. for (tmp_rh = conn->ctx->handlers; tmp_rh != NULL;
  9039. tmp_rh = tmp_rh->next) {
  9040. if (tmp_rh->handler_type == handler_type) {
  9041. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  9042. if (handler_type == WEBSOCKET_HANDLER) {
  9043. *subprotocols = tmp_rh->subprotocols;
  9044. *connect_handler = tmp_rh->connect_handler;
  9045. *ready_handler = tmp_rh->ready_handler;
  9046. *data_handler = tmp_rh->data_handler;
  9047. *close_handler = tmp_rh->close_handler;
  9048. } else if (handler_type == REQUEST_HANDLER) {
  9049. *handler = tmp_rh->handler;
  9050. } else { /* AUTH_HANDLER */
  9051. *auth_handler = tmp_rh->auth_handler;
  9052. }
  9053. *cbdata = tmp_rh->cbdata;
  9054. mg_unlock_context(conn->ctx);
  9055. return 1;
  9056. }
  9057. }
  9058. }
  9059. mg_unlock_context(conn->ctx);
  9060. }
  9061. return 0; /* none found */
  9062. }
  9063. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  9064. static int
  9065. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  9066. void *cbdata)
  9067. {
  9068. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9069. if (pcallbacks->websocket_connect) {
  9070. return pcallbacks->websocket_connect(conn);
  9071. }
  9072. /* No handler set - assume "OK" */
  9073. return 0;
  9074. }
  9075. static void
  9076. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  9077. {
  9078. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9079. if (pcallbacks->websocket_ready) {
  9080. pcallbacks->websocket_ready(conn);
  9081. }
  9082. }
  9083. static int
  9084. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  9085. int bits,
  9086. char *data,
  9087. size_t len,
  9088. void *cbdata)
  9089. {
  9090. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  9091. if (pcallbacks->websocket_data) {
  9092. return pcallbacks->websocket_data(conn, bits, data, len);
  9093. }
  9094. /* No handler set - assume "OK" */
  9095. return 1;
  9096. }
  9097. #endif
  9098. /* This is the heart of the Civetweb's logic.
  9099. * This function is called when the request is read, parsed and validated,
  9100. * and Civetweb must decide what action to take: serve a file, or
  9101. * a directory, or call embedded function, etcetera. */
  9102. static void
  9103. handle_request(struct mg_connection *conn)
  9104. {
  9105. if (conn) {
  9106. struct mg_request_info *ri = &conn->request_info;
  9107. char path[PATH_MAX];
  9108. int uri_len, ssl_index;
  9109. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  9110. is_put_or_delete_request = 0, is_callback_resource = 0;
  9111. int i;
  9112. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9113. mg_request_handler callback_handler = NULL;
  9114. struct mg_websocket_subprotocols *subprotocols;
  9115. mg_websocket_connect_handler ws_connect_handler = NULL;
  9116. mg_websocket_ready_handler ws_ready_handler = NULL;
  9117. mg_websocket_data_handler ws_data_handler = NULL;
  9118. mg_websocket_close_handler ws_close_handler = NULL;
  9119. void *callback_data = NULL;
  9120. mg_authorization_handler auth_handler = NULL;
  9121. void *auth_callback_data = NULL;
  9122. #if !defined(NO_FILES)
  9123. time_t curtime = time(NULL);
  9124. char date[64];
  9125. #endif
  9126. path[0] = 0;
  9127. if (!ri) {
  9128. return;
  9129. }
  9130. /* 1. get the request url */
  9131. /* 1.1. split into url and query string */
  9132. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  9133. != NULL) {
  9134. *((char *)conn->request_info.query_string++) = '\0';
  9135. }
  9136. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  9137. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  9138. ssl_index = get_first_ssl_listener_index(conn->ctx);
  9139. if (ssl_index >= 0) {
  9140. redirect_to_https_port(conn, ssl_index);
  9141. } else {
  9142. /* A http to https forward port has been specified,
  9143. * but no https port to forward to. */
  9144. send_http_error(conn,
  9145. 503,
  9146. "%s",
  9147. "Error: SSL forward not configured properly");
  9148. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  9149. }
  9150. return;
  9151. }
  9152. uri_len = (int)strlen(ri->local_uri);
  9153. /* 1.3. decode url (if config says so) */
  9154. if (should_decode_url(conn)) {
  9155. mg_url_decode(
  9156. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  9157. }
  9158. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  9159. * not possible */
  9160. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  9161. /* step 1. completed, the url is known now */
  9162. uri_len = (int)strlen(ri->local_uri);
  9163. DEBUG_TRACE("URL: %s", ri->local_uri);
  9164. /* 3. if this ip has limited speed, set it for this connection */
  9165. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  9166. get_remote_ip(conn),
  9167. ri->local_uri);
  9168. /* 4. call a "handle everything" callback, if registered */
  9169. if (conn->ctx->callbacks.begin_request != NULL) {
  9170. /* Note that since V1.7 the "begin_request" function is called
  9171. * before an authorization check. If an authorization check is
  9172. * required, use a request_handler instead. */
  9173. i = conn->ctx->callbacks.begin_request(conn);
  9174. if (i > 0) {
  9175. /* callback already processed the request. Store the
  9176. return value as a status code for the access log. */
  9177. conn->status_code = i;
  9178. discard_unread_request_data(conn);
  9179. return;
  9180. } else if (i == 0) {
  9181. /* civetweb should process the request */
  9182. } else {
  9183. /* unspecified - may change with the next version */
  9184. return;
  9185. }
  9186. }
  9187. /* request not yet handled by a handler or redirect, so the request
  9188. * is processed here */
  9189. /* 5. interpret the url to find out how the request must be handled
  9190. */
  9191. /* 5.1. first test, if the request targets the regular http(s)://
  9192. * protocol namespace or the websocket ws(s):// protocol namespace.
  9193. */
  9194. is_websocket_request = is_websocket_protocol(conn);
  9195. /* 5.2. check if the request will be handled by a callback */
  9196. if (get_request_handler(conn,
  9197. is_websocket_request ? WEBSOCKET_HANDLER
  9198. : REQUEST_HANDLER,
  9199. &callback_handler,
  9200. &subprotocols,
  9201. &ws_connect_handler,
  9202. &ws_ready_handler,
  9203. &ws_data_handler,
  9204. &ws_close_handler,
  9205. NULL,
  9206. &callback_data)) {
  9207. /* 5.2.1. A callback will handle this request. All requests
  9208. * handled
  9209. * by a callback have to be considered as requests to a script
  9210. * resource. */
  9211. is_callback_resource = 1;
  9212. is_script_resource = 1;
  9213. is_put_or_delete_request = is_put_or_delete_method(conn);
  9214. } else {
  9215. no_callback_resource:
  9216. /* 5.2.2. No callback is responsible for this request. The URI
  9217. * addresses a file based resource (static content or Lua/cgi
  9218. * scripts in the file system). */
  9219. is_callback_resource = 0;
  9220. interpret_uri(conn,
  9221. path,
  9222. sizeof(path),
  9223. &file.stat,
  9224. &is_found,
  9225. &is_script_resource,
  9226. &is_websocket_request,
  9227. &is_put_or_delete_request);
  9228. }
  9229. /* 6. authorization check */
  9230. /* 6.1. a custom authorization handler is installed */
  9231. if (get_request_handler(conn,
  9232. AUTH_HANDLER,
  9233. NULL,
  9234. NULL,
  9235. NULL,
  9236. NULL,
  9237. NULL,
  9238. NULL,
  9239. &auth_handler,
  9240. &auth_callback_data)) {
  9241. if (!auth_handler(conn, auth_callback_data)) {
  9242. return;
  9243. }
  9244. } else if (is_put_or_delete_request && !is_script_resource
  9245. && !is_callback_resource) {
  9246. /* 6.2. this request is a PUT/DELETE to a real file */
  9247. /* 6.2.1. thus, the server must have real files */
  9248. #if defined(NO_FILES)
  9249. if (1) {
  9250. #else
  9251. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9252. #endif
  9253. /* This server does not have any real files, thus the
  9254. * PUT/DELETE methods are not valid. */
  9255. send_http_error(conn,
  9256. 405,
  9257. "%s method not allowed",
  9258. conn->request_info.request_method);
  9259. return;
  9260. }
  9261. #if !defined(NO_FILES)
  9262. /* 6.2.2. Check if put authorization for static files is
  9263. * available.
  9264. */
  9265. if (!is_authorized_for_put(conn)) {
  9266. send_authorization_request(conn);
  9267. return;
  9268. }
  9269. #endif
  9270. } else {
  9271. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  9272. * or it is a PUT or DELETE request to a resource that does not
  9273. * correspond to a file. Check authorization. */
  9274. if (!check_authorization(conn, path)) {
  9275. send_authorization_request(conn);
  9276. return;
  9277. }
  9278. }
  9279. /* request is authorized or does not need authorization */
  9280. /* 7. check if there are request handlers for this uri */
  9281. if (is_callback_resource) {
  9282. if (!is_websocket_request) {
  9283. i = callback_handler(conn, callback_data);
  9284. if (i > 0) {
  9285. /* Do nothing, callback has served the request. Store
  9286. * the
  9287. * return value as status code for the log and discard
  9288. * all
  9289. * data from the client not used by the callback. */
  9290. conn->status_code = i;
  9291. discard_unread_request_data(conn);
  9292. } else {
  9293. /* TODO (high): what if the handler did NOT handle the
  9294. * request */
  9295. /* The last version did handle this as a file request,
  9296. * but
  9297. * since a file request is not always a script resource,
  9298. * the authorization check might be different */
  9299. interpret_uri(conn,
  9300. path,
  9301. sizeof(path),
  9302. &file.stat,
  9303. &is_found,
  9304. &is_script_resource,
  9305. &is_websocket_request,
  9306. &is_put_or_delete_request);
  9307. callback_handler = NULL;
  9308. /* TODO (very low): goto is deprecated but for the
  9309. * moment,
  9310. * a goto is simpler than some curious loop. */
  9311. /* The situation "callback does not handle the request"
  9312. * needs to be reconsidered anyway. */
  9313. goto no_callback_resource;
  9314. }
  9315. } else {
  9316. #if defined(USE_WEBSOCKET)
  9317. handle_websocket_request(conn,
  9318. path,
  9319. is_callback_resource,
  9320. subprotocols,
  9321. ws_connect_handler,
  9322. ws_ready_handler,
  9323. ws_data_handler,
  9324. ws_close_handler,
  9325. callback_data);
  9326. #endif
  9327. }
  9328. return;
  9329. }
  9330. /* 8. handle websocket requests */
  9331. #if defined(USE_WEBSOCKET)
  9332. if (is_websocket_request) {
  9333. if (is_script_resource) {
  9334. /* Websocket Lua script */
  9335. handle_websocket_request(conn,
  9336. path,
  9337. 0 /* Lua Script */,
  9338. NULL,
  9339. NULL,
  9340. NULL,
  9341. NULL,
  9342. NULL,
  9343. &conn->ctx->callbacks);
  9344. } else {
  9345. #if defined(MG_LEGACY_INTERFACE)
  9346. handle_websocket_request(
  9347. conn,
  9348. path,
  9349. !is_script_resource /* could be deprecated global callback */,
  9350. NULL,
  9351. deprecated_websocket_connect_wrapper,
  9352. deprecated_websocket_ready_wrapper,
  9353. deprecated_websocket_data_wrapper,
  9354. NULL,
  9355. &conn->ctx->callbacks);
  9356. #else
  9357. send_http_error(conn, 404, "%s", "Not found");
  9358. #endif
  9359. }
  9360. return;
  9361. } else
  9362. #endif
  9363. #if defined(NO_FILES)
  9364. /* 9a. In case the server uses only callbacks, this uri is
  9365. * unknown.
  9366. * Then, all request handling ends here. */
  9367. send_http_error(conn, 404, "%s", "Not Found");
  9368. #else
  9369. /* 9b. This request is either for a static file or resource handled
  9370. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  9371. if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  9372. send_http_error(conn, 404, "%s", "Not Found");
  9373. return;
  9374. }
  9375. /* 10. File is handled by a script. */
  9376. if (is_script_resource) {
  9377. handle_file_based_request(conn, path, &file);
  9378. return;
  9379. }
  9380. /* 11. Handle put/delete/mkcol requests */
  9381. if (is_put_or_delete_request) {
  9382. /* 11.1. PUT method */
  9383. if (!strcmp(ri->request_method, "PUT")) {
  9384. put_file(conn, path);
  9385. return;
  9386. }
  9387. /* 11.2. DELETE method */
  9388. if (!strcmp(ri->request_method, "DELETE")) {
  9389. delete_file(conn, path);
  9390. return;
  9391. }
  9392. /* 11.3. MKCOL method */
  9393. if (!strcmp(ri->request_method, "MKCOL")) {
  9394. mkcol(conn, path);
  9395. return;
  9396. }
  9397. /* 11.4. PATCH method
  9398. * This method is not supported for static resources,
  9399. * only for scripts (Lua, CGI) and callbacks. */
  9400. send_http_error(conn,
  9401. 405,
  9402. "%s method not allowed",
  9403. conn->request_info.request_method);
  9404. return;
  9405. }
  9406. /* 11. File does not exist, or it was configured that it should be
  9407. * hidden */
  9408. if (!is_found || (must_hide_file(conn, path))) {
  9409. send_http_error(conn, 404, "%s", "Not found");
  9410. return;
  9411. }
  9412. /* 12. Directory uris should end with a slash */
  9413. if (file.stat.is_directory && (uri_len > 0)
  9414. && (ri->local_uri[uri_len - 1] != '/')) {
  9415. gmt_time_string(date, sizeof(date), &curtime);
  9416. mg_printf(conn,
  9417. "HTTP/1.1 301 Moved Permanently\r\n"
  9418. "Location: %s/\r\n"
  9419. "Date: %s\r\n"
  9420. /* "Cache-Control: private\r\n" (= default) */
  9421. "Content-Length: 0\r\n"
  9422. "Connection: %s\r\n\r\n",
  9423. ri->request_uri,
  9424. date,
  9425. suggest_connection_header(conn));
  9426. return;
  9427. }
  9428. /* 13. Handle other methods than GET/HEAD */
  9429. /* 13.1. Handle PROPFIND */
  9430. if (!strcmp(ri->request_method, "PROPFIND")) {
  9431. handle_propfind(conn, path, &file.stat);
  9432. return;
  9433. }
  9434. /* 13.2. Handle OPTIONS for files */
  9435. if (!strcmp(ri->request_method, "OPTIONS")) {
  9436. /* This standard handler is only used for real files.
  9437. * Scripts should support the OPTIONS method themselves, to allow a
  9438. * maximum flexibility.
  9439. * Lua and CGI scripts may fully support CORS this way (including
  9440. * preflights). */
  9441. send_options(conn);
  9442. return;
  9443. }
  9444. /* 13.3. everything but GET and HEAD (e.g. POST) */
  9445. if (0 != strcmp(ri->request_method, "GET")
  9446. && 0 != strcmp(ri->request_method, "HEAD")) {
  9447. send_http_error(conn,
  9448. 405,
  9449. "%s method not allowed",
  9450. conn->request_info.request_method);
  9451. return;
  9452. }
  9453. /* 14. directories */
  9454. if (file.stat.is_directory) {
  9455. if (substitute_index_file(conn, path, sizeof(path), &file)) {
  9456. /* 14.1. use a substitute file */
  9457. /* TODO (high): substitute index may be a script resource.
  9458. * define what should be possible in this case. */
  9459. } else {
  9460. /* 14.2. no substitute file */
  9461. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING],
  9462. "yes")) {
  9463. handle_directory_request(conn, path);
  9464. } else {
  9465. send_http_error(conn,
  9466. 403,
  9467. "%s",
  9468. "Error: Directory listing denied");
  9469. }
  9470. return;
  9471. }
  9472. }
  9473. handle_file_based_request(conn, path, &file);
  9474. #endif /* !defined(NO_FILES) */
  9475. #if 0
  9476. /* Perform redirect and auth checks before calling begin_request()
  9477. * handler.
  9478. * Otherwise, begin_request() would need to perform auth checks and
  9479. * redirects. */
  9480. #endif
  9481. }
  9482. return;
  9483. }
  9484. static void
  9485. handle_file_based_request(struct mg_connection *conn,
  9486. const char *path,
  9487. struct mg_file *file)
  9488. {
  9489. if (!conn || !conn->ctx) {
  9490. return;
  9491. }
  9492. if (0) {
  9493. #ifdef USE_LUA
  9494. } else if (match_prefix(conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  9495. strlen(
  9496. conn->ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  9497. path) > 0) {
  9498. /* Lua server page: an SSI like page containing mostly plain html
  9499. * code
  9500. * plus some tags with server generated contents. */
  9501. handle_lsp_request(conn, path, file, NULL);
  9502. } else if (match_prefix(conn->ctx->config[LUA_SCRIPT_EXTENSIONS],
  9503. strlen(conn->ctx->config[LUA_SCRIPT_EXTENSIONS]),
  9504. path) > 0) {
  9505. /* Lua in-server module script: a CGI like script used to generate
  9506. * the
  9507. * entire reply. */
  9508. mg_exec_lua_script(conn, path, NULL);
  9509. #endif
  9510. #if defined(USE_DUKTAPE)
  9511. } else if (match_prefix(conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  9512. strlen(
  9513. conn->ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  9514. path) > 0) {
  9515. /* Call duktape to generate the page */
  9516. mg_exec_duktape_script(conn, path);
  9517. #endif
  9518. #if !defined(NO_CGI)
  9519. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  9520. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  9521. path) > 0) {
  9522. /* CGI scripts may support all HTTP methods */
  9523. handle_cgi_request(conn, path);
  9524. #endif /* !NO_CGI */
  9525. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  9526. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  9527. path) > 0) {
  9528. handle_ssi_file_request(conn, path, file);
  9529. #if !defined(NO_CACHING)
  9530. } else if ((!conn->in_error_handler)
  9531. && is_not_modified(conn, &file->stat)) {
  9532. /* Send 304 "Not Modified" - this must not send any body data */
  9533. handle_not_modified_static_file_request(conn, file);
  9534. #endif /* !NO_CACHING */
  9535. } else {
  9536. handle_static_file_request(conn, path, file, NULL, NULL);
  9537. }
  9538. }
  9539. static void
  9540. close_all_listening_sockets(struct mg_context *ctx)
  9541. {
  9542. unsigned int i;
  9543. if (!ctx) {
  9544. return;
  9545. }
  9546. for (i = 0; i < ctx->num_listening_sockets; i++) {
  9547. closesocket(ctx->listening_sockets[i].sock);
  9548. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  9549. }
  9550. mg_free(ctx->listening_sockets);
  9551. ctx->listening_sockets = NULL;
  9552. mg_free(ctx->listening_socket_fds);
  9553. ctx->listening_socket_fds = NULL;
  9554. }
  9555. /* Valid listening port specification is: [ip_address:]port[s]
  9556. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  9557. * Examples for IPv6: [::]:80, [::1]:80,
  9558. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  9559. * see https://tools.ietf.org/html/rfc3513#section-2.2
  9560. * In order to bind to both, IPv4 and IPv6, you can either add
  9561. * both ports using 8080,[::]:8080, or the short form +8080.
  9562. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  9563. * one only accepting IPv4 the other only IPv6. +8080 creates
  9564. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  9565. * environment, they might work differently, or might not work
  9566. * at all - it must be tested what options work best in the
  9567. * relevant network environment.
  9568. */
  9569. static int
  9570. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  9571. {
  9572. unsigned int a, b, c, d, port;
  9573. int ch, len;
  9574. #if defined(USE_IPV6)
  9575. char buf[100] = {0};
  9576. #endif
  9577. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  9578. * Also, all-zeroes in the socket address means binding to all addresses
  9579. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  9580. memset(so, 0, sizeof(*so));
  9581. so->lsa.sin.sin_family = AF_INET;
  9582. *ip_version = 0;
  9583. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  9584. == 5) {
  9585. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  9586. so->lsa.sin.sin_addr.s_addr =
  9587. htonl((a << 24) | (b << 16) | (c << 8) | d);
  9588. so->lsa.sin.sin_port = htons((uint16_t)port);
  9589. *ip_version = 4;
  9590. #if defined(USE_IPV6)
  9591. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  9592. && mg_inet_pton(
  9593. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  9594. /* IPv6 address, examples: see above */
  9595. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  9596. */
  9597. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9598. *ip_version = 6;
  9599. #endif
  9600. } else if ((vec->ptr[0] == '+')
  9601. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  9602. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  9603. /* Add 1 to len for the + character we skipped before */
  9604. len++;
  9605. #if defined(USE_IPV6)
  9606. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  9607. so->lsa.sin6.sin6_family = AF_INET6;
  9608. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  9609. *ip_version = 4 + 6;
  9610. #else
  9611. /* Bind to IPv4 only, since IPv6 is not built in. */
  9612. so->lsa.sin.sin_port = htons((uint16_t)port);
  9613. *ip_version = 4;
  9614. #endif
  9615. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  9616. /* If only port is specified, bind to IPv4, INADDR_ANY */
  9617. so->lsa.sin.sin_port = htons((uint16_t)port);
  9618. *ip_version = 4;
  9619. } else {
  9620. /* Parsing failure. Make port invalid. */
  9621. port = 0;
  9622. len = 0;
  9623. }
  9624. /* sscanf and the option splitting code ensure the following condition
  9625. */
  9626. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  9627. *ip_version = 0;
  9628. return 0;
  9629. }
  9630. ch = vec->ptr[len]; /* Next character after the port number */
  9631. so->is_ssl = (ch == 's');
  9632. so->ssl_redir = (ch == 'r');
  9633. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  9634. if (is_valid_port(port)
  9635. && (ch == '\0' || ch == 's' || ch == 'r' || ch == ',')) {
  9636. return 1;
  9637. }
  9638. /* Reset ip_version to 0 of there is an error */
  9639. *ip_version = 0;
  9640. return 0;
  9641. }
  9642. static int
  9643. set_ports_option(struct mg_context *ctx)
  9644. {
  9645. const char *list;
  9646. int on = 1;
  9647. #if defined(USE_IPV6)
  9648. int off = 0;
  9649. #endif
  9650. struct vec vec;
  9651. struct socket so, *ptr;
  9652. struct pollfd *pfd;
  9653. union usa usa;
  9654. socklen_t len;
  9655. int ip_version;
  9656. int portsTotal = 0;
  9657. int portsOk = 0;
  9658. if (!ctx) {
  9659. return 0;
  9660. }
  9661. memset(&so, 0, sizeof(so));
  9662. memset(&usa, 0, sizeof(usa));
  9663. len = sizeof(usa);
  9664. list = ctx->config[LISTENING_PORTS];
  9665. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9666. portsTotal++;
  9667. if (!parse_port_string(&vec, &so, &ip_version)) {
  9668. mg_cry(fc(ctx),
  9669. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  9670. (int)vec.len,
  9671. vec.ptr,
  9672. portsTotal,
  9673. "[IP_ADDRESS:]PORT[s|r]");
  9674. continue;
  9675. }
  9676. #if !defined(NO_SSL)
  9677. if (so.is_ssl && ctx->ssl_ctx == NULL) {
  9678. mg_cry(fc(ctx),
  9679. "Cannot add SSL socket (entry %i). Is -ssl_certificate "
  9680. "option set?",
  9681. portsTotal);
  9682. continue;
  9683. }
  9684. #endif
  9685. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  9686. == INVALID_SOCKET) {
  9687. mg_cry(fc(ctx), "cannot create socket (entry %i)", portsTotal);
  9688. continue;
  9689. }
  9690. #ifdef _WIN32
  9691. /* Windows SO_REUSEADDR lets many procs binds to a
  9692. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  9693. * if someone already has the socket -- DTL */
  9694. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  9695. * Windows might need a few seconds before
  9696. * the same port can be used again in the
  9697. * same process, so a short Sleep may be
  9698. * required between mg_stop and mg_start.
  9699. */
  9700. if (setsockopt(so.sock,
  9701. SOL_SOCKET,
  9702. SO_EXCLUSIVEADDRUSE,
  9703. (SOCK_OPT_TYPE)&on,
  9704. sizeof(on)) != 0) {
  9705. /* Set reuse option, but don't abort on errors. */
  9706. mg_cry(fc(ctx),
  9707. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  9708. portsTotal);
  9709. }
  9710. #else
  9711. if (setsockopt(so.sock,
  9712. SOL_SOCKET,
  9713. SO_REUSEADDR,
  9714. (SOCK_OPT_TYPE)&on,
  9715. sizeof(on)) != 0) {
  9716. /* Set reuse option, but don't abort on errors. */
  9717. mg_cry(fc(ctx),
  9718. "cannot set socket option SO_REUSEADDR (entry %i)",
  9719. portsTotal);
  9720. }
  9721. #endif
  9722. if (ip_version > 4) {
  9723. #if defined(USE_IPV6)
  9724. if (ip_version == 6) {
  9725. if (so.lsa.sa.sa_family == AF_INET6
  9726. && setsockopt(so.sock,
  9727. IPPROTO_IPV6,
  9728. IPV6_V6ONLY,
  9729. (void *)&off,
  9730. sizeof(off)) != 0) {
  9731. /* Set IPv6 only option, but don't abort on errors. */
  9732. mg_cry(fc(ctx),
  9733. "cannot set socket option IPV6_V6ONLY (entry %i)",
  9734. portsTotal);
  9735. }
  9736. }
  9737. #else
  9738. mg_cry(fc(ctx), "IPv6 not available");
  9739. closesocket(so.sock);
  9740. so.sock = INVALID_SOCKET;
  9741. continue;
  9742. #endif
  9743. }
  9744. if (so.lsa.sa.sa_family == AF_INET) {
  9745. len = sizeof(so.lsa.sin);
  9746. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9747. mg_cry(fc(ctx),
  9748. "cannot bind to %.*s: %d (%s)",
  9749. (int)vec.len,
  9750. vec.ptr,
  9751. (int)ERRNO,
  9752. strerror(errno));
  9753. closesocket(so.sock);
  9754. so.sock = INVALID_SOCKET;
  9755. continue;
  9756. }
  9757. }
  9758. #if defined(USE_IPV6)
  9759. else if (so.lsa.sa.sa_family == AF_INET6) {
  9760. len = sizeof(so.lsa.sin6);
  9761. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  9762. mg_cry(fc(ctx),
  9763. "cannot bind to IPv6 %.*s: %d (%s)",
  9764. (int)vec.len,
  9765. vec.ptr,
  9766. (int)ERRNO,
  9767. strerror(errno));
  9768. closesocket(so.sock);
  9769. so.sock = INVALID_SOCKET;
  9770. continue;
  9771. }
  9772. }
  9773. #endif
  9774. else {
  9775. mg_cry(fc(ctx),
  9776. "cannot bind: address family not supported (entry %i)",
  9777. portsTotal);
  9778. continue;
  9779. }
  9780. if (listen(so.sock, SOMAXCONN) != 0) {
  9781. mg_cry(fc(ctx),
  9782. "cannot listen to %.*s: %d (%s)",
  9783. (int)vec.len,
  9784. vec.ptr,
  9785. (int)ERRNO,
  9786. strerror(errno));
  9787. closesocket(so.sock);
  9788. so.sock = INVALID_SOCKET;
  9789. continue;
  9790. }
  9791. if (getsockname(so.sock, &(usa.sa), &len) != 0
  9792. || usa.sa.sa_family != so.lsa.sa.sa_family) {
  9793. int err = (int)ERRNO;
  9794. mg_cry(fc(ctx),
  9795. "call to getsockname failed %.*s: %d (%s)",
  9796. (int)vec.len,
  9797. vec.ptr,
  9798. err,
  9799. strerror(errno));
  9800. closesocket(so.sock);
  9801. so.sock = INVALID_SOCKET;
  9802. continue;
  9803. }
  9804. /* Update lsa port in case of random free ports */
  9805. #if defined(USE_IPV6)
  9806. if (so.lsa.sa.sa_family == AF_INET6) {
  9807. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  9808. } else
  9809. #endif
  9810. {
  9811. so.lsa.sin.sin_port = usa.sin.sin_port;
  9812. }
  9813. if ((ptr = (struct socket *)
  9814. mg_realloc(ctx->listening_sockets,
  9815. (ctx->num_listening_sockets + 1)
  9816. * sizeof(ctx->listening_sockets[0]))) == NULL) {
  9817. mg_cry(fc(ctx), "%s", "Out of memory");
  9818. closesocket(so.sock);
  9819. so.sock = INVALID_SOCKET;
  9820. continue;
  9821. }
  9822. if ((pfd = (struct pollfd *)mg_realloc(
  9823. ctx->listening_socket_fds,
  9824. (ctx->num_listening_sockets + 1)
  9825. * sizeof(ctx->listening_socket_fds[0]))) == NULL) {
  9826. mg_cry(fc(ctx), "%s", "Out of memory");
  9827. closesocket(so.sock);
  9828. so.sock = INVALID_SOCKET;
  9829. mg_free(ptr);
  9830. continue;
  9831. }
  9832. set_close_on_exec(so.sock, fc(ctx));
  9833. ctx->listening_sockets = ptr;
  9834. ctx->listening_sockets[ctx->num_listening_sockets] = so;
  9835. ctx->listening_socket_fds = pfd;
  9836. ctx->num_listening_sockets++;
  9837. portsOk++;
  9838. }
  9839. if (portsOk != portsTotal) {
  9840. close_all_listening_sockets(ctx);
  9841. portsOk = 0;
  9842. }
  9843. return portsOk;
  9844. }
  9845. static const char *
  9846. header_val(const struct mg_connection *conn, const char *header)
  9847. {
  9848. const char *header_value;
  9849. if ((header_value = mg_get_header(conn, header)) == NULL) {
  9850. return "-";
  9851. } else {
  9852. return header_value;
  9853. }
  9854. }
  9855. static void
  9856. log_access(const struct mg_connection *conn)
  9857. {
  9858. const struct mg_request_info *ri;
  9859. struct mg_file fi;
  9860. char date[64], src_addr[IP_ADDR_STR_LEN];
  9861. struct tm *tm;
  9862. const char *referer;
  9863. const char *user_agent;
  9864. char buf[4096];
  9865. if (!conn || !conn->ctx) {
  9866. return;
  9867. }
  9868. if (conn->ctx->config[ACCESS_LOG_FILE] != NULL) {
  9869. if (mg_fopen(conn,
  9870. conn->ctx->config[ACCESS_LOG_FILE],
  9871. MG_FOPEN_MODE_APPEND,
  9872. &fi) == 0) {
  9873. fi.access.fp = NULL;
  9874. }
  9875. } else {
  9876. fi.access.fp = NULL;
  9877. }
  9878. /* Log is written to a file and/or a callback. If both are not set,
  9879. * executing the rest of the function is pointless. */
  9880. if ((fi.access.fp == NULL) && (conn->ctx->callbacks.log_access == NULL)) {
  9881. return;
  9882. }
  9883. tm = localtime(&conn->conn_birth_time);
  9884. if (tm != NULL) {
  9885. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  9886. } else {
  9887. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  9888. date[sizeof(date) - 1] = '\0';
  9889. }
  9890. ri = &conn->request_info;
  9891. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9892. referer = header_val(conn, "Referer");
  9893. user_agent = header_val(conn, "User-Agent");
  9894. mg_snprintf(conn,
  9895. NULL, /* Ignore truncation in access log */
  9896. buf,
  9897. sizeof(buf),
  9898. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  9899. src_addr,
  9900. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  9901. date,
  9902. ri->request_method ? ri->request_method : "-",
  9903. ri->request_uri ? ri->request_uri : "-",
  9904. ri->query_string ? "?" : "",
  9905. ri->query_string ? ri->query_string : "",
  9906. ri->http_version,
  9907. conn->status_code,
  9908. conn->num_bytes_sent,
  9909. referer,
  9910. user_agent);
  9911. if (conn->ctx->callbacks.log_access) {
  9912. conn->ctx->callbacks.log_access(conn, buf);
  9913. }
  9914. if (fi.access.fp) {
  9915. int ok = 1;
  9916. flockfile(fi.access.fp);
  9917. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  9918. ok = 0;
  9919. }
  9920. if (fflush(fi.access.fp) != 0) {
  9921. ok = 0;
  9922. }
  9923. funlockfile(fi.access.fp);
  9924. if (mg_fclose(&fi.access) != 0) {
  9925. ok = 0;
  9926. }
  9927. if (!ok) {
  9928. mg_cry(conn,
  9929. "Error writing log file %s",
  9930. conn->ctx->config[ACCESS_LOG_FILE]);
  9931. }
  9932. }
  9933. }
  9934. /* Verify given socket address against the ACL.
  9935. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  9936. */
  9937. static int
  9938. check_acl(struct mg_context *ctx, uint32_t remote_ip)
  9939. {
  9940. int allowed, flag;
  9941. uint32_t net, mask;
  9942. struct vec vec;
  9943. if (ctx) {
  9944. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  9945. /* If any ACL is set, deny by default */
  9946. allowed = (list == NULL) ? '+' : '-';
  9947. while ((list = next_option(list, &vec, NULL)) != NULL) {
  9948. flag = vec.ptr[0];
  9949. if ((flag != '+' && flag != '-')
  9950. || parse_net(&vec.ptr[1], &net, &mask) == 0) {
  9951. mg_cry(fc(ctx),
  9952. "%s: subnet must be [+|-]x.x.x.x[/x]",
  9953. __func__);
  9954. return -1;
  9955. }
  9956. if (net == (remote_ip & mask)) {
  9957. allowed = flag;
  9958. }
  9959. }
  9960. return allowed == '+';
  9961. }
  9962. return -1;
  9963. }
  9964. #if !defined(_WIN32)
  9965. static int
  9966. set_uid_option(struct mg_context *ctx)
  9967. {
  9968. struct passwd *pw;
  9969. if (ctx) {
  9970. const char *uid = ctx->config[RUN_AS_USER];
  9971. int success = 0;
  9972. if (uid == NULL) {
  9973. success = 1;
  9974. } else {
  9975. if ((pw = getpwnam(uid)) == NULL) {
  9976. mg_cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  9977. } else if (setgid(pw->pw_gid) == -1) {
  9978. mg_cry(fc(ctx),
  9979. "%s: setgid(%s): %s",
  9980. __func__,
  9981. uid,
  9982. strerror(errno));
  9983. } else if (setgroups(0, NULL)) {
  9984. mg_cry(fc(ctx),
  9985. "%s: setgroups(): %s",
  9986. __func__,
  9987. strerror(errno));
  9988. } else if (setuid(pw->pw_uid) == -1) {
  9989. mg_cry(fc(ctx),
  9990. "%s: setuid(%s): %s",
  9991. __func__,
  9992. uid,
  9993. strerror(errno));
  9994. } else {
  9995. success = 1;
  9996. }
  9997. }
  9998. return success;
  9999. }
  10000. return 0;
  10001. }
  10002. #endif /* !_WIN32 */
  10003. static void
  10004. tls_dtor(void *key)
  10005. {
  10006. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  10007. /* key == pthread_getspecific(sTlsKey); */
  10008. if (tls) {
  10009. if (tls->is_master == 2) {
  10010. tls->is_master = -3; /* Mark memory as dead */
  10011. mg_free(tls);
  10012. }
  10013. }
  10014. pthread_setspecific(sTlsKey, NULL);
  10015. }
  10016. #if !defined(NO_SSL)
  10017. static int ssl_use_pem_file(struct mg_context *ctx, const char *pem);
  10018. static const char *ssl_error(void);
  10019. static int
  10020. refresh_trust(struct mg_connection *conn)
  10021. {
  10022. static int reload_lock = 0;
  10023. static long int data_check = 0;
  10024. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  10025. struct stat cert_buf;
  10026. long int t;
  10027. char *pem;
  10028. int should_verify_peer;
  10029. if ((pem = conn->ctx->config[SSL_CERTIFICATE]) == NULL) {
  10030. /* If peem is NULL and conn->ctx->callbacks.init_ssl is not,
  10031. * refresh_trust still can not work. */
  10032. return 0;
  10033. }
  10034. t = data_check;
  10035. if (stat(pem, &cert_buf) != -1) {
  10036. t = (long int)cert_buf.st_mtime;
  10037. }
  10038. if (data_check != t) {
  10039. data_check = t;
  10040. should_verify_peer =
  10041. (conn->ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10042. && (mg_strcasecmp(conn->ctx->config[SSL_DO_VERIFY_PEER], "yes")
  10043. == 0);
  10044. if (should_verify_peer) {
  10045. char *ca_path = conn->ctx->config[SSL_CA_PATH];
  10046. char *ca_file = conn->ctx->config[SSL_CA_FILE];
  10047. if (SSL_CTX_load_verify_locations(conn->ctx->ssl_ctx,
  10048. ca_file,
  10049. ca_path) != 1) {
  10050. mg_cry(fc(conn->ctx),
  10051. "SSL_CTX_load_verify_locations error: %s "
  10052. "ssl_verify_peer requires setting "
  10053. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10054. "present in "
  10055. "the .conf file?",
  10056. ssl_error());
  10057. return 0;
  10058. }
  10059. }
  10060. if (1 == mg_atomic_inc(p_reload_lock)) {
  10061. if (ssl_use_pem_file(conn->ctx, pem) == 0) {
  10062. return 0;
  10063. }
  10064. *p_reload_lock = 0;
  10065. }
  10066. }
  10067. /* lock while cert is reloading */
  10068. while (*p_reload_lock) {
  10069. sleep(1);
  10070. }
  10071. return 1;
  10072. }
  10073. static pthread_mutex_t *ssl_mutexes;
  10074. static int
  10075. sslize(struct mg_connection *conn,
  10076. SSL_CTX *s,
  10077. int (*func)(SSL *),
  10078. volatile int *stop_server)
  10079. {
  10080. int ret, err;
  10081. int short_trust;
  10082. unsigned i;
  10083. if (!conn) {
  10084. return 0;
  10085. }
  10086. short_trust =
  10087. (conn->ctx->config[SSL_SHORT_TRUST] != NULL)
  10088. && (mg_strcasecmp(conn->ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  10089. if (short_trust) {
  10090. int trust_ret = refresh_trust(conn);
  10091. if (!trust_ret) {
  10092. return trust_ret;
  10093. }
  10094. }
  10095. conn->ssl = SSL_new(s);
  10096. if (conn->ssl == NULL) {
  10097. return 0;
  10098. }
  10099. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  10100. if (ret != 1) {
  10101. err = SSL_get_error(conn->ssl, ret);
  10102. (void)err; /* TODO: set some error message */
  10103. SSL_free(conn->ssl);
  10104. conn->ssl = NULL;
  10105. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10106. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10107. ERR_remove_state(0);
  10108. return 0;
  10109. }
  10110. /* SSL functions may fail and require to be called again:
  10111. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  10112. * Here "func" could be SSL_connect or SSL_accept. */
  10113. for (i = 16; i <= 1024; i *= 2) {
  10114. ret = func(conn->ssl);
  10115. if (ret != 1) {
  10116. err = SSL_get_error(conn->ssl, ret);
  10117. if ((err == SSL_ERROR_WANT_CONNECT)
  10118. || (err == SSL_ERROR_WANT_ACCEPT)
  10119. || (err == SSL_ERROR_WANT_READ)
  10120. || (err == SSL_ERROR_WANT_WRITE)) {
  10121. /* Need to retry the function call "later".
  10122. * See https://linux.die.net/man/3/ssl_get_error
  10123. * This is typical for non-blocking sockets. */
  10124. if (*stop_server) {
  10125. /* Don't wait if the server is going to be stopped. */
  10126. break;
  10127. }
  10128. mg_sleep(i);
  10129. } else if (err == SSL_ERROR_SYSCALL) {
  10130. /* This is an IO error. Look at errno. */
  10131. err = errno;
  10132. /* TODO: set some error message */
  10133. break;
  10134. } else {
  10135. /* This is an SSL specific error */
  10136. /* TODO: set some error message */
  10137. break;
  10138. }
  10139. } else {
  10140. /* success */
  10141. break;
  10142. }
  10143. }
  10144. if (ret != 1) {
  10145. SSL_free(conn->ssl);
  10146. conn->ssl = NULL;
  10147. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10148. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10149. ERR_remove_state(0);
  10150. return 0;
  10151. }
  10152. return 1;
  10153. }
  10154. /* Return OpenSSL error message (from CRYPTO lib) */
  10155. static const char *
  10156. ssl_error(void)
  10157. {
  10158. unsigned long err;
  10159. err = ERR_get_error();
  10160. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  10161. }
  10162. static int
  10163. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  10164. {
  10165. int i;
  10166. const char hexdigit[] = "0123456789abcdef";
  10167. if (memlen <= 0 || buflen <= 0) {
  10168. return 0;
  10169. }
  10170. if (buflen < (3 * memlen)) {
  10171. return 0;
  10172. }
  10173. for (i = 0; i < memlen; i++) {
  10174. if (i > 0) {
  10175. buf[3 * i - 1] = ' ';
  10176. }
  10177. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  10178. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  10179. }
  10180. buf[3 * memlen - 1] = 0;
  10181. return 1;
  10182. }
  10183. static void
  10184. ssl_get_client_cert_info(struct mg_connection *conn)
  10185. {
  10186. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  10187. if (cert) {
  10188. char str_subject[1024];
  10189. char str_issuer[1024];
  10190. char str_serial[1024];
  10191. char str_finger[1024];
  10192. unsigned char buf[256];
  10193. int len;
  10194. unsigned int ulen;
  10195. /* Handle to algorithm used for fingerprint */
  10196. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  10197. /* Get Subject and issuer */
  10198. X509_NAME *subj = X509_get_subject_name(cert);
  10199. X509_NAME *iss = X509_get_issuer_name(cert);
  10200. /* Get serial number */
  10201. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  10202. /* Translate subject and issuer to a string */
  10203. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  10204. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  10205. /* Translate serial number to a hex string */
  10206. len = i2c_ASN1_INTEGER(serial, NULL);
  10207. if ((len > 0) && ((unsigned)len < (unsigned)sizeof(buf))) {
  10208. unsigned char *pbuf = buf;
  10209. int len2 = i2c_ASN1_INTEGER(serial, &pbuf);
  10210. if (!hexdump2string(
  10211. buf, len2, str_serial, (int)sizeof(str_serial))) {
  10212. *str_serial = 0;
  10213. }
  10214. } else {
  10215. *str_serial = 0;
  10216. }
  10217. /* Calculate SHA1 fingerprint and store as a hex string */
  10218. ulen = 0;
  10219. ASN1_digest((int (*)())i2d_X509, digest, (char *)cert, buf, &ulen);
  10220. if (!hexdump2string(
  10221. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  10222. *str_finger = 0;
  10223. }
  10224. conn->request_info.client_cert =
  10225. (struct client_cert *)mg_malloc(sizeof(struct client_cert));
  10226. if (conn->request_info.client_cert) {
  10227. conn->request_info.client_cert->subject = mg_strdup(str_subject);
  10228. conn->request_info.client_cert->issuer = mg_strdup(str_issuer);
  10229. conn->request_info.client_cert->serial = mg_strdup(str_serial);
  10230. conn->request_info.client_cert->finger = mg_strdup(str_finger);
  10231. } else {
  10232. /* TODO: write some OOM message */
  10233. }
  10234. X509_free(cert);
  10235. }
  10236. }
  10237. static void
  10238. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  10239. {
  10240. (void)line;
  10241. (void)file;
  10242. if (mode & 1) {
  10243. /* 1 is CRYPTO_LOCK */
  10244. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  10245. } else {
  10246. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  10247. }
  10248. }
  10249. #if !defined(NO_SSL_DL)
  10250. static void *
  10251. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  10252. {
  10253. union {
  10254. void *p;
  10255. void (*fp)(void);
  10256. } u;
  10257. void *dll_handle;
  10258. struct ssl_func *fp;
  10259. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  10260. mg_cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  10261. return NULL;
  10262. }
  10263. for (fp = sw; fp->name != NULL; fp++) {
  10264. #ifdef _WIN32
  10265. /* GetProcAddress() returns pointer to function */
  10266. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  10267. #else
  10268. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  10269. * pointers to function pointers. We need to use a union to make a
  10270. * cast. */
  10271. u.p = dlsym(dll_handle, fp->name);
  10272. #endif /* _WIN32 */
  10273. if (u.fp == NULL) {
  10274. mg_cry(fc(ctx),
  10275. "%s: %s: cannot find %s",
  10276. __func__,
  10277. dll_name,
  10278. fp->name);
  10279. dlclose(dll_handle);
  10280. return NULL;
  10281. } else {
  10282. fp->ptr = u.fp;
  10283. }
  10284. }
  10285. return dll_handle;
  10286. }
  10287. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  10288. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  10289. #endif /* NO_SSL_DL */
  10290. #if defined(SSL_ALREADY_INITIALIZED)
  10291. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  10292. #else
  10293. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  10294. #endif
  10295. static int
  10296. initialize_ssl(struct mg_context *ctx)
  10297. {
  10298. int i;
  10299. size_t size;
  10300. #if !defined(NO_SSL_DL)
  10301. if (!cryptolib_dll_handle) {
  10302. cryptolib_dll_handle = load_dll(ctx, CRYPTO_LIB, crypto_sw);
  10303. if (!cryptolib_dll_handle) {
  10304. return 0;
  10305. }
  10306. }
  10307. #endif /* NO_SSL_DL */
  10308. if (mg_atomic_inc(&cryptolib_users) > 1) {
  10309. return 1;
  10310. }
  10311. /* Initialize locking callbacks, needed for thread safety.
  10312. * http://www.openssl.org/support/faq.html#PROG1
  10313. */
  10314. i = CRYPTO_num_locks();
  10315. if (i < 0) {
  10316. i = 0;
  10317. }
  10318. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  10319. if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  10320. mg_cry(fc(ctx),
  10321. "%s: cannot allocate mutexes: %s",
  10322. __func__,
  10323. ssl_error());
  10324. return 0;
  10325. }
  10326. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10327. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  10328. }
  10329. CRYPTO_set_locking_callback(&ssl_locking_callback);
  10330. CRYPTO_set_id_callback(&mg_current_thread_id);
  10331. return 1;
  10332. }
  10333. static int
  10334. ssl_use_pem_file(struct mg_context *ctx, const char *pem)
  10335. {
  10336. if (SSL_CTX_use_certificate_file(ctx->ssl_ctx, pem, 1) == 0) {
  10337. mg_cry(fc(ctx),
  10338. "%s: cannot open certificate file %s: %s",
  10339. __func__,
  10340. pem,
  10341. ssl_error());
  10342. return 0;
  10343. }
  10344. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  10345. if (SSL_CTX_use_PrivateKey_file(ctx->ssl_ctx, pem, 1) == 0) {
  10346. mg_cry(fc(ctx),
  10347. "%s: cannot open private key file %s: %s",
  10348. __func__,
  10349. pem,
  10350. ssl_error());
  10351. return 0;
  10352. }
  10353. if (SSL_CTX_check_private_key(ctx->ssl_ctx) == 0) {
  10354. mg_cry(fc(ctx),
  10355. "%s: certificate and private key do not match: %s",
  10356. __func__,
  10357. pem);
  10358. return 0;
  10359. }
  10360. if (SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem) == 0) {
  10361. mg_cry(fc(ctx),
  10362. "%s: cannot use certificate chain file %s: %s",
  10363. __func__,
  10364. pem,
  10365. ssl_error());
  10366. return 0;
  10367. }
  10368. return 1;
  10369. }
  10370. static long
  10371. ssl_get_protocol(int version_id)
  10372. {
  10373. long ret = SSL_OP_ALL;
  10374. if (version_id > 0)
  10375. ret |= SSL_OP_NO_SSLv2;
  10376. if (version_id > 1)
  10377. ret |= SSL_OP_NO_SSLv3;
  10378. if (version_id > 2)
  10379. ret |= SSL_OP_NO_TLSv1;
  10380. if (version_id > 3)
  10381. ret |= SSL_OP_NO_TLSv1_1;
  10382. return ret;
  10383. }
  10384. /* Dynamically load SSL library. Set up ctx->ssl_ctx pointer. */
  10385. static int
  10386. set_ssl_option(struct mg_context *ctx)
  10387. {
  10388. const char *pem;
  10389. int callback_ret;
  10390. int should_verify_peer;
  10391. const char *ca_path;
  10392. const char *ca_file;
  10393. int use_default_verify_paths;
  10394. int verify_depth;
  10395. time_t now_rt = time(NULL);
  10396. struct timespec now_mt;
  10397. md5_byte_t ssl_context_id[16];
  10398. md5_state_t md5state;
  10399. int protocol_ver;
  10400. /* If PEM file is not specified and the init_ssl callback
  10401. * is not specified, skip SSL initialization. */
  10402. if (!ctx) {
  10403. return 0;
  10404. }
  10405. if ((pem = ctx->config[SSL_CERTIFICATE]) == NULL
  10406. && ctx->callbacks.init_ssl == NULL) {
  10407. return 1;
  10408. }
  10409. if (!initialize_ssl(ctx)) {
  10410. return 0;
  10411. }
  10412. #if !defined(NO_SSL_DL)
  10413. if (!ssllib_dll_handle) {
  10414. ssllib_dll_handle = load_dll(ctx, SSL_LIB, ssl_sw);
  10415. if (!ssllib_dll_handle) {
  10416. return 0;
  10417. }
  10418. }
  10419. #endif /* NO_SSL_DL */
  10420. /* Initialize SSL library */
  10421. SSL_library_init();
  10422. SSL_load_error_strings();
  10423. if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  10424. mg_cry(fc(ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  10425. return 0;
  10426. }
  10427. SSL_CTX_clear_options(ctx->ssl_ctx,
  10428. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  10429. | SSL_OP_NO_TLSv1_1);
  10430. protocol_ver = atoi(ctx->config[SSL_PROTOCOL_VERSION]);
  10431. SSL_CTX_set_options(ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  10432. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  10433. SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  10434. SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
  10435. /* If a callback has been specified, call it. */
  10436. callback_ret =
  10437. (ctx->callbacks.init_ssl == NULL)
  10438. ? 0
  10439. : (ctx->callbacks.init_ssl(ctx->ssl_ctx, ctx->user_data));
  10440. /* If callback returns 0, civetweb sets up the SSL certificate.
  10441. * If it returns 1, civetweb assumes the calback already did this.
  10442. * If it returns -1, initializing ssl fails. */
  10443. if (callback_ret < 0) {
  10444. mg_cry(fc(ctx), "SSL callback returned error: %i", callback_ret);
  10445. return 0;
  10446. }
  10447. if (callback_ret > 0) {
  10448. if (pem != NULL) {
  10449. (void)SSL_CTX_use_certificate_chain_file(ctx->ssl_ctx, pem);
  10450. }
  10451. return 1;
  10452. }
  10453. /* Use some UID as session context ID. */
  10454. md5_init(&md5state);
  10455. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  10456. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  10457. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  10458. md5_append(&md5state,
  10459. (const md5_byte_t *)ctx->config[LISTENING_PORTS],
  10460. strlen(ctx->config[LISTENING_PORTS]));
  10461. md5_append(&md5state, (const md5_byte_t *)ctx, sizeof(*ctx));
  10462. md5_finish(&md5state, ssl_context_id);
  10463. SSL_CTX_set_session_id_context(ctx->ssl_ctx,
  10464. (const unsigned char *)&ssl_context_id,
  10465. sizeof(ssl_context_id));
  10466. if (pem != NULL) {
  10467. if (!ssl_use_pem_file(ctx, pem)) {
  10468. return 0;
  10469. }
  10470. }
  10471. should_verify_peer =
  10472. (ctx->config[SSL_DO_VERIFY_PEER] != NULL)
  10473. && (mg_strcasecmp(ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0);
  10474. use_default_verify_paths =
  10475. (ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  10476. && (mg_strcasecmp(ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0);
  10477. if (should_verify_peer) {
  10478. ca_path = ctx->config[SSL_CA_PATH];
  10479. ca_file = ctx->config[SSL_CA_FILE];
  10480. if (SSL_CTX_load_verify_locations(ctx->ssl_ctx, ca_file, ca_path)
  10481. != 1) {
  10482. mg_cry(fc(ctx),
  10483. "SSL_CTX_load_verify_locations error: %s "
  10484. "ssl_verify_peer requires setting "
  10485. "either ssl_ca_path or ssl_ca_file. Is any of them "
  10486. "present in "
  10487. "the .conf file?",
  10488. ssl_error());
  10489. return 0;
  10490. }
  10491. SSL_CTX_set_verify(ctx->ssl_ctx,
  10492. SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  10493. NULL);
  10494. if (use_default_verify_paths
  10495. && SSL_CTX_set_default_verify_paths(ctx->ssl_ctx) != 1) {
  10496. mg_cry(fc(ctx),
  10497. "SSL_CTX_set_default_verify_paths error: %s",
  10498. ssl_error());
  10499. return 0;
  10500. }
  10501. if (ctx->config[SSL_VERIFY_DEPTH]) {
  10502. verify_depth = atoi(ctx->config[SSL_VERIFY_DEPTH]);
  10503. SSL_CTX_set_verify_depth(ctx->ssl_ctx, verify_depth);
  10504. }
  10505. }
  10506. if (ctx->config[SSL_CIPHER_LIST] != NULL) {
  10507. if (SSL_CTX_set_cipher_list(ctx->ssl_ctx, ctx->config[SSL_CIPHER_LIST])
  10508. != 1) {
  10509. mg_cry(fc(ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error());
  10510. }
  10511. }
  10512. return 1;
  10513. }
  10514. static void
  10515. uninitialize_ssl(struct mg_context *ctx)
  10516. {
  10517. int i;
  10518. (void)ctx;
  10519. if (mg_atomic_dec(&cryptolib_users) == 0) {
  10520. /* Shutdown according to
  10521. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  10522. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  10523. */
  10524. CRYPTO_set_locking_callback(NULL);
  10525. CRYPTO_set_id_callback(NULL);
  10526. ENGINE_cleanup();
  10527. CONF_modules_unload(1);
  10528. ERR_free_strings();
  10529. EVP_cleanup();
  10530. CRYPTO_cleanup_all_ex_data();
  10531. ERR_remove_state(0);
  10532. for (i = 0; i < CRYPTO_num_locks(); i++) {
  10533. pthread_mutex_destroy(&ssl_mutexes[i]);
  10534. }
  10535. mg_free(ssl_mutexes);
  10536. ssl_mutexes = NULL;
  10537. }
  10538. }
  10539. #endif /* !NO_SSL */
  10540. static int
  10541. set_gpass_option(struct mg_context *ctx)
  10542. {
  10543. if (ctx) {
  10544. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10545. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  10546. if (path != NULL && !mg_stat(fc(ctx), path, &file.stat)) {
  10547. mg_cry(fc(ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  10548. return 0;
  10549. }
  10550. return 1;
  10551. }
  10552. return 0;
  10553. }
  10554. static int
  10555. set_acl_option(struct mg_context *ctx)
  10556. {
  10557. return check_acl(ctx, (uint32_t)0x7f000001UL) != -1;
  10558. }
  10559. static void
  10560. reset_per_request_attributes(struct mg_connection *conn)
  10561. {
  10562. if (!conn) {
  10563. return;
  10564. }
  10565. conn->path_info = NULL;
  10566. conn->num_bytes_sent = conn->consumed_content = 0;
  10567. conn->status_code = -1;
  10568. conn->is_chunked = 0;
  10569. conn->must_close = conn->request_len = conn->throttle = 0;
  10570. conn->request_info.content_length = -1;
  10571. conn->request_info.remote_user = NULL;
  10572. conn->request_info.request_method = NULL;
  10573. conn->request_info.request_uri = NULL;
  10574. conn->request_info.local_uri = NULL;
  10575. conn->request_info.uri = NULL; /* TODO: cleanup uri,
  10576. * local_uri and request_uri */
  10577. conn->request_info.http_version = NULL;
  10578. conn->request_info.num_headers = 0;
  10579. conn->data_len = 0;
  10580. conn->chunk_remainder = 0;
  10581. }
  10582. #if 0
  10583. /* Note: set_sock_timeout is not required for non-blocking sockets.
  10584. * Leave this function here (commented out) for reference until
  10585. * CivetWeb 1.9 is tested, and the tests confirme this function is
  10586. * no longer required.
  10587. */
  10588. static int
  10589. set_sock_timeout(SOCKET sock, int milliseconds)
  10590. {
  10591. int r0 = 0, r1, r2;
  10592. #ifdef _WIN32
  10593. /* Windows specific */
  10594. DWORD tv = (DWORD)milliseconds;
  10595. #else
  10596. /* Linux, ... (not Windows) */
  10597. struct timeval tv;
  10598. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  10599. * max. time waiting for the acknowledged of TCP data before the connection
  10600. * will be forcefully closed and ETIMEDOUT is returned to the application.
  10601. * If this option is not set, the default timeout of 20-30 minutes is used.
  10602. */
  10603. /* #define TCP_USER_TIMEOUT (18) */
  10604. #if defined(TCP_USER_TIMEOUT)
  10605. unsigned int uto = (unsigned int)milliseconds;
  10606. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  10607. #endif
  10608. memset(&tv, 0, sizeof(tv));
  10609. tv.tv_sec = milliseconds / 1000;
  10610. tv.tv_usec = (milliseconds * 1000) % 1000000;
  10611. #endif /* _WIN32 */
  10612. r1 = setsockopt(
  10613. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10614. r2 = setsockopt(
  10615. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  10616. return r0 || r1 || r2;
  10617. }
  10618. #endif
  10619. static int
  10620. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  10621. {
  10622. if (setsockopt(sock,
  10623. IPPROTO_TCP,
  10624. TCP_NODELAY,
  10625. (SOCK_OPT_TYPE)&nodelay_on,
  10626. sizeof(nodelay_on)) != 0) {
  10627. /* Error */
  10628. return 1;
  10629. }
  10630. /* OK */
  10631. return 0;
  10632. }
  10633. static void
  10634. close_socket_gracefully(struct mg_connection *conn)
  10635. {
  10636. #if defined(_WIN32)
  10637. char buf[MG_BUF_LEN];
  10638. int n;
  10639. #endif
  10640. struct linger linger;
  10641. int error_code = 0;
  10642. int linger_timeout = -2;
  10643. socklen_t opt_len = sizeof(error_code);
  10644. if (!conn) {
  10645. return;
  10646. }
  10647. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  10648. * "Note that enabling a nonzero timeout on a nonblocking socket
  10649. * is not recommended.", so set it to blocking now */
  10650. set_blocking_mode(conn->client.sock, 1);
  10651. /* Send FIN to the client */
  10652. shutdown(conn->client.sock, SHUTDOWN_WR);
  10653. #if defined(_WIN32)
  10654. /* Read and discard pending incoming data. If we do not do that and
  10655. * close
  10656. * the socket, the data in the send buffer may be discarded. This
  10657. * behaviour is seen on Windows, when client keeps sending data
  10658. * when server decides to close the connection; then when client
  10659. * does recv() it gets no data back. */
  10660. do {
  10661. n = pull(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  10662. } while (n > 0);
  10663. #endif
  10664. if (conn->ctx->config[LINGER_TIMEOUT]) {
  10665. linger_timeout = atoi(conn->ctx->config[LINGER_TIMEOUT]);
  10666. }
  10667. /* Set linger option according to configuration */
  10668. if (linger_timeout >= 0) {
  10669. /* Set linger option to avoid socket hanging out after close. This
  10670. * prevent ephemeral port exhaust problem under high QPS. */
  10671. linger.l_onoff = 1;
  10672. #if defined(_MSC_VER)
  10673. #pragma warning(push)
  10674. #pragma warning(disable : 4244)
  10675. #endif
  10676. linger.l_linger = (linger_timeout + 999) / 1000;
  10677. #if defined(_MSC_VER)
  10678. #pragma warning(pop)
  10679. #endif
  10680. } else {
  10681. linger.l_onoff = 0;
  10682. linger.l_linger = 0;
  10683. }
  10684. if (linger_timeout < -1) {
  10685. /* Default: don't configure any linger */
  10686. } else if (getsockopt(conn->client.sock,
  10687. SOL_SOCKET,
  10688. SO_ERROR,
  10689. (char *)&error_code,
  10690. &opt_len) != 0) {
  10691. /* Cannot determine if socket is already closed. This should
  10692. * not occur and never did in a test. Log an error message
  10693. * and continue. */
  10694. mg_cry(conn,
  10695. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  10696. __func__,
  10697. strerror(ERRNO));
  10698. } else if (error_code == ECONNRESET) {
  10699. /* Socket already closed by client/peer, close socket without linger */
  10700. } else {
  10701. /* Set linger timeout */
  10702. if (setsockopt(conn->client.sock,
  10703. SOL_SOCKET,
  10704. SO_LINGER,
  10705. (char *)&linger,
  10706. sizeof(linger)) != 0) {
  10707. mg_cry(conn,
  10708. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  10709. __func__,
  10710. linger.l_onoff,
  10711. linger.l_linger,
  10712. strerror(ERRNO));
  10713. }
  10714. }
  10715. /* Now we know that our FIN is ACK-ed, safe to close */
  10716. closesocket(conn->client.sock);
  10717. conn->client.sock = INVALID_SOCKET;
  10718. }
  10719. static void
  10720. close_connection(struct mg_connection *conn)
  10721. {
  10722. if (!conn || !conn->ctx) {
  10723. return;
  10724. }
  10725. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  10726. if (conn->lua_websocket_state) {
  10727. lua_websocket_close(conn, conn->lua_websocket_state);
  10728. conn->lua_websocket_state = NULL;
  10729. }
  10730. #endif
  10731. /* call the connection_close callback if assigned */
  10732. if ((conn->ctx->callbacks.connection_close != NULL)
  10733. && (conn->ctx->context_type == 1)) {
  10734. conn->ctx->callbacks.connection_close(conn);
  10735. }
  10736. mg_lock_connection(conn);
  10737. conn->must_close = 1;
  10738. #ifndef NO_SSL
  10739. if (conn->ssl != NULL) {
  10740. /* Run SSL_shutdown twice to ensure completly close SSL connection
  10741. */
  10742. SSL_shutdown(conn->ssl);
  10743. SSL_free(conn->ssl);
  10744. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  10745. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  10746. ERR_remove_state(0);
  10747. conn->ssl = NULL;
  10748. }
  10749. #endif
  10750. if (conn->client.sock != INVALID_SOCKET) {
  10751. close_socket_gracefully(conn);
  10752. conn->client.sock = INVALID_SOCKET;
  10753. }
  10754. mg_unlock_connection(conn);
  10755. }
  10756. void
  10757. mg_close_connection(struct mg_connection *conn)
  10758. {
  10759. struct mg_context *client_ctx = NULL;
  10760. if (conn == NULL) {
  10761. return;
  10762. }
  10763. #if defined(USE_WEBSOCKET)
  10764. if (conn->ctx->context_type == 2) {
  10765. unsigned int i;
  10766. /* ws/wss client */
  10767. client_ctx = conn->ctx;
  10768. /* client context: loops must end */
  10769. conn->ctx->stop_flag = 1;
  10770. /* We need to get the client thread out of the select/recv call here. */
  10771. /* Since we use a sleep quantum of some seconds to check for recv
  10772. * timeouts, we will just wait a few seconds in mg_join_thread. */
  10773. /* join worker thread */
  10774. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  10775. if (client_ctx->worker_threadids[i] != 0) {
  10776. mg_join_thread(client_ctx->worker_threadids[i]);
  10777. }
  10778. }
  10779. }
  10780. #else
  10781. (void)client_ctx;
  10782. #endif
  10783. close_connection(conn);
  10784. #ifndef NO_SSL
  10785. if (conn->client_ssl_ctx != NULL) {
  10786. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  10787. }
  10788. #endif
  10789. if (client_ctx != NULL) {
  10790. /* free context */
  10791. mg_free(client_ctx->worker_threadids);
  10792. mg_free(client_ctx);
  10793. (void)pthread_mutex_destroy(&conn->mutex);
  10794. mg_free(conn);
  10795. }
  10796. }
  10797. static struct mg_connection *
  10798. mg_connect_client_impl(const struct mg_client_options *client_options,
  10799. int use_ssl,
  10800. char *ebuf,
  10801. size_t ebuf_len)
  10802. {
  10803. static struct mg_context fake_ctx;
  10804. struct mg_connection *conn = NULL;
  10805. SOCKET sock;
  10806. union usa sa;
  10807. if (!connect_socket(&fake_ctx,
  10808. client_options->host,
  10809. client_options->port,
  10810. use_ssl,
  10811. ebuf,
  10812. ebuf_len,
  10813. &sock,
  10814. &sa)) {
  10815. ;
  10816. } else if ((conn = (struct mg_connection *)
  10817. mg_calloc(1, sizeof(*conn) + MAX_REQUEST_SIZE)) == NULL) {
  10818. mg_snprintf(NULL,
  10819. NULL, /* No truncation check for ebuf */
  10820. ebuf,
  10821. ebuf_len,
  10822. "calloc(): %s",
  10823. strerror(ERRNO));
  10824. closesocket(sock);
  10825. #ifndef NO_SSL
  10826. } else if (use_ssl
  10827. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  10828. == NULL) {
  10829. mg_snprintf(NULL,
  10830. NULL, /* No truncation check for ebuf */
  10831. ebuf,
  10832. ebuf_len,
  10833. "SSL_CTX_new error");
  10834. closesocket(sock);
  10835. mg_free(conn);
  10836. conn = NULL;
  10837. #endif /* NO_SSL */
  10838. } else {
  10839. #ifdef USE_IPV6
  10840. socklen_t len = (sa.sa.sa_family == AF_INET)
  10841. ? sizeof(conn->client.rsa.sin)
  10842. : sizeof(conn->client.rsa.sin6);
  10843. struct sockaddr *psa =
  10844. (sa.sa.sa_family == AF_INET)
  10845. ? (struct sockaddr *)&(conn->client.rsa.sin)
  10846. : (struct sockaddr *)&(conn->client.rsa.sin6);
  10847. #else
  10848. socklen_t len = sizeof(conn->client.rsa.sin);
  10849. struct sockaddr *psa = (struct sockaddr *)&(conn->client.rsa.sin);
  10850. #endif
  10851. conn->buf_size = MAX_REQUEST_SIZE;
  10852. conn->buf = (char *)(conn + 1);
  10853. conn->ctx = &fake_ctx;
  10854. conn->client.sock = sock;
  10855. conn->client.lsa = sa;
  10856. if (getsockname(sock, psa, &len) != 0) {
  10857. mg_cry(conn,
  10858. "%s: getsockname() failed: %s",
  10859. __func__,
  10860. strerror(ERRNO));
  10861. }
  10862. conn->client.is_ssl = use_ssl ? 1 : 0;
  10863. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  10864. #ifndef NO_SSL
  10865. if (use_ssl) {
  10866. fake_ctx.ssl_ctx = conn->client_ssl_ctx;
  10867. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  10868. * SSL_CTX_set_verify call is needed to switch off server
  10869. * certificate checking, which is off by default in OpenSSL and
  10870. * on in yaSSL. */
  10871. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  10872. * SSL_VERIFY_PEER, verify_ssl_server); */
  10873. if (client_options->client_cert) {
  10874. if (!ssl_use_pem_file(&fake_ctx, client_options->client_cert)) {
  10875. mg_snprintf(NULL,
  10876. NULL, /* No truncation check for ebuf */
  10877. ebuf,
  10878. ebuf_len,
  10879. "Can not use SSL client certificate");
  10880. SSL_CTX_free(conn->client_ssl_ctx);
  10881. closesocket(sock);
  10882. mg_free(conn);
  10883. conn = NULL;
  10884. }
  10885. }
  10886. if (client_options->server_cert) {
  10887. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  10888. client_options->server_cert,
  10889. NULL);
  10890. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  10891. } else {
  10892. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  10893. }
  10894. if (!sslize(conn,
  10895. conn->client_ssl_ctx,
  10896. SSL_connect,
  10897. &(conn->ctx->stop_flag))) {
  10898. mg_snprintf(NULL,
  10899. NULL, /* No truncation check for ebuf */
  10900. ebuf,
  10901. ebuf_len,
  10902. "SSL connection error");
  10903. SSL_CTX_free(conn->client_ssl_ctx);
  10904. closesocket(sock);
  10905. mg_free(conn);
  10906. conn = NULL;
  10907. }
  10908. }
  10909. #endif
  10910. }
  10911. if (conn) {
  10912. set_blocking_mode(sock, 0);
  10913. }
  10914. return conn;
  10915. }
  10916. CIVETWEB_API struct mg_connection *
  10917. mg_connect_client_secure(const struct mg_client_options *client_options,
  10918. char *error_buffer,
  10919. size_t error_buffer_size)
  10920. {
  10921. return mg_connect_client_impl(client_options,
  10922. 1,
  10923. error_buffer,
  10924. error_buffer_size);
  10925. }
  10926. struct mg_connection *
  10927. mg_connect_client(const char *host,
  10928. int port,
  10929. int use_ssl,
  10930. char *error_buffer,
  10931. size_t error_buffer_size)
  10932. {
  10933. struct mg_client_options opts;
  10934. memset(&opts, 0, sizeof(opts));
  10935. opts.host = host;
  10936. opts.port = port;
  10937. return mg_connect_client_impl(&opts,
  10938. use_ssl,
  10939. error_buffer,
  10940. error_buffer_size);
  10941. }
  10942. static const struct {
  10943. const char *proto;
  10944. size_t proto_len;
  10945. unsigned default_port;
  10946. } abs_uri_protocols[] = {{"http://", 7, 80},
  10947. {"https://", 8, 443},
  10948. {"ws://", 5, 80},
  10949. {"wss://", 6, 443},
  10950. {NULL, 0, 0}};
  10951. /* Check if the uri is valid.
  10952. * return 0 for invalid uri,
  10953. * return 1 for *,
  10954. * return 2 for relative uri,
  10955. * return 3 for absolute uri without port,
  10956. * return 4 for absolute uri with port */
  10957. static int
  10958. get_uri_type(const char *uri)
  10959. {
  10960. int i;
  10961. char *hostend, *portbegin, *portend;
  10962. unsigned long port;
  10963. /* According to the HTTP standard
  10964. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  10965. * URI can be an asterisk (*) or should start with slash (relative uri),
  10966. * or it should start with the protocol (absolute uri). */
  10967. if (uri[0] == '*' && uri[1] == '\0') {
  10968. /* asterisk */
  10969. return 1;
  10970. }
  10971. /* Valid URIs according to RFC 3986
  10972. * (https://www.ietf.org/rfc/rfc3986.txt)
  10973. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  10974. * and unreserved characters A-Z a-z 0-9 and -._~
  10975. * and % encoded symbols.
  10976. */
  10977. for (i = 0; uri[i] != 0; i++) {
  10978. if (uri[i] < 33) {
  10979. /* control characters and spaces are invalid */
  10980. return 0;
  10981. }
  10982. if (uri[i] > 126) {
  10983. /* non-ascii characters must be % encoded */
  10984. return 0;
  10985. } else {
  10986. switch (uri[i]) {
  10987. case '"': /* 34 */
  10988. case '<': /* 60 */
  10989. case '>': /* 62 */
  10990. case '\\': /* 92 */
  10991. case '^': /* 94 */
  10992. case '`': /* 96 */
  10993. case '{': /* 123 */
  10994. case '|': /* 124 */
  10995. case '}': /* 125 */
  10996. return 0;
  10997. default:
  10998. /* character is ok */
  10999. break;
  11000. }
  11001. }
  11002. }
  11003. /* A relative uri starts with a / character */
  11004. if (uri[0] == '/') {
  11005. /* relative uri */
  11006. return 2;
  11007. }
  11008. /* It could be an absolute uri: */
  11009. /* This function only checks if the uri is valid, not if it is
  11010. * addressing the current server. So civetweb can also be used
  11011. * as a proxy server. */
  11012. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11013. if (mg_strncasecmp(uri,
  11014. abs_uri_protocols[i].proto,
  11015. abs_uri_protocols[i].proto_len) == 0) {
  11016. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  11017. if (!hostend) {
  11018. return 0;
  11019. }
  11020. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  11021. if (!portbegin) {
  11022. return 3;
  11023. }
  11024. port = strtoul(portbegin + 1, &portend, 10);
  11025. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11026. return 0;
  11027. }
  11028. return 4;
  11029. }
  11030. }
  11031. return 0;
  11032. }
  11033. /* Return NULL or the relative uri at the current server */
  11034. static const char *
  11035. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  11036. {
  11037. const char *server_domain;
  11038. size_t server_domain_len;
  11039. size_t request_domain_len = 0;
  11040. unsigned long port = 0;
  11041. int i;
  11042. const char *hostbegin = NULL;
  11043. const char *hostend = NULL;
  11044. const char *portbegin;
  11045. char *portend;
  11046. /* DNS is case insensitive, so use case insensitive string compare here
  11047. */
  11048. server_domain = conn->ctx->config[AUTHENTICATION_DOMAIN];
  11049. if (!server_domain) {
  11050. return 0;
  11051. }
  11052. server_domain_len = strlen(server_domain);
  11053. if (!server_domain_len) {
  11054. return 0;
  11055. }
  11056. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  11057. if (mg_strncasecmp(uri,
  11058. abs_uri_protocols[i].proto,
  11059. abs_uri_protocols[i].proto_len) == 0) {
  11060. hostbegin = uri + abs_uri_protocols[i].proto_len;
  11061. hostend = strchr(hostbegin, '/');
  11062. if (!hostend) {
  11063. return 0;
  11064. }
  11065. portbegin = strchr(hostbegin, ':');
  11066. if ((!portbegin) || (portbegin > hostend)) {
  11067. port = abs_uri_protocols[i].default_port;
  11068. request_domain_len = (size_t)(hostend - hostbegin);
  11069. } else {
  11070. port = strtoul(portbegin + 1, &portend, 10);
  11071. if ((portend != hostend) || !port || !is_valid_port(port)) {
  11072. return 0;
  11073. }
  11074. request_domain_len = (size_t)(portbegin - hostbegin);
  11075. }
  11076. /* protocol found, port set */
  11077. break;
  11078. }
  11079. }
  11080. if (!port) {
  11081. /* port remains 0 if the protocol is not found */
  11082. return 0;
  11083. }
  11084. /* Check if the request is directed to a different server. */
  11085. /* First check if the port is the same (IPv4 and IPv6). */
  11086. #if defined(USE_IPV6)
  11087. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  11088. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  11089. /* Request is directed to a different port */
  11090. return 0;
  11091. }
  11092. } else
  11093. #endif
  11094. {
  11095. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  11096. /* Request is directed to a different port */
  11097. return 0;
  11098. }
  11099. }
  11100. /* Finally check if the server corresponds to the authentication
  11101. * domain of the server (the server domain).
  11102. * Allow full matches (like http://mydomain.com/path/file.ext), and
  11103. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  11104. * but do not allow substrings (like http://notmydomain.com/path/file.ext
  11105. * or http://mydomain.com.fake/path/file.ext).
  11106. */
  11107. if ((request_domain_len == server_domain_len)
  11108. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  11109. /* Request is directed to this server - full name match. */
  11110. } else {
  11111. if (request_domain_len < (server_domain_len + 2)) {
  11112. /* Request is directed to another server: The server name is longer
  11113. * than
  11114. * the request name. Drop this case here to avoid overflows in the
  11115. * following checks. */
  11116. return 0;
  11117. }
  11118. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  11119. /* Request is directed to another server: It could be a substring
  11120. * like notmyserver.com */
  11121. return 0;
  11122. }
  11123. if (0 != memcmp(server_domain,
  11124. hostbegin + request_domain_len - server_domain_len,
  11125. server_domain_len)) {
  11126. /* Request is directed to another server:
  11127. * The server name is different. */
  11128. return 0;
  11129. }
  11130. }
  11131. return hostend;
  11132. }
  11133. static int
  11134. getreq(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  11135. {
  11136. const char *cl;
  11137. if (ebuf_len > 0) {
  11138. ebuf[0] = '\0';
  11139. }
  11140. *err = 0;
  11141. reset_per_request_attributes(conn);
  11142. if (!conn) {
  11143. mg_snprintf(conn,
  11144. NULL, /* No truncation check for ebuf */
  11145. ebuf,
  11146. ebuf_len,
  11147. "%s",
  11148. "Internal error");
  11149. *err = 500;
  11150. return 0;
  11151. }
  11152. /* Set the time the request was received. This value should be used for
  11153. * timeouts. */
  11154. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  11155. conn->request_len =
  11156. read_request(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  11157. /* assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  11158. */
  11159. if (conn->request_len >= 0 && conn->data_len < conn->request_len) {
  11160. mg_snprintf(conn,
  11161. NULL, /* No truncation check for ebuf */
  11162. ebuf,
  11163. ebuf_len,
  11164. "%s",
  11165. "Invalid request size");
  11166. *err = 500;
  11167. return 0;
  11168. }
  11169. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  11170. mg_snprintf(conn,
  11171. NULL, /* No truncation check for ebuf */
  11172. ebuf,
  11173. ebuf_len,
  11174. "%s",
  11175. "Request Too Large");
  11176. *err = 413;
  11177. return 0;
  11178. } else if (conn->request_len <= 0) {
  11179. if (conn->data_len > 0) {
  11180. mg_snprintf(conn,
  11181. NULL, /* No truncation check for ebuf */
  11182. ebuf,
  11183. ebuf_len,
  11184. "%s",
  11185. "Client sent malformed request");
  11186. *err = 400;
  11187. } else {
  11188. /* Server did not recv anything -> just close the connection */
  11189. conn->must_close = 1;
  11190. mg_snprintf(conn,
  11191. NULL, /* No truncation check for ebuf */
  11192. ebuf,
  11193. ebuf_len,
  11194. "%s",
  11195. "Client did not send a request");
  11196. *err = 0;
  11197. }
  11198. return 0;
  11199. } else if (parse_http_message(conn->buf,
  11200. conn->buf_size,
  11201. &conn->request_info) <= 0) {
  11202. mg_snprintf(conn,
  11203. NULL, /* No truncation check for ebuf */
  11204. ebuf,
  11205. ebuf_len,
  11206. "%s",
  11207. "Bad Request");
  11208. *err = 400;
  11209. return 0;
  11210. } else {
  11211. /* Message is a valid request or response */
  11212. if ((cl = get_header(&conn->request_info, "Content-Length")) != NULL) {
  11213. /* Request/response has content length set */
  11214. char *endptr = NULL;
  11215. conn->content_len = strtoll(cl, &endptr, 10);
  11216. if (endptr == cl) {
  11217. mg_snprintf(conn,
  11218. NULL, /* No truncation check for ebuf */
  11219. ebuf,
  11220. ebuf_len,
  11221. "%s",
  11222. "Bad Request");
  11223. *err = 411;
  11224. return 0;
  11225. }
  11226. /* Publish the content length back to the request info. */
  11227. conn->request_info.content_length = conn->content_len;
  11228. } else if ((cl = get_header(&conn->request_info, "Transfer-Encoding"))
  11229. != NULL
  11230. && !mg_strcasecmp(cl, "chunked")) {
  11231. conn->is_chunked = 1;
  11232. } else if (!mg_strcasecmp(conn->request_info.request_method, "POST")
  11233. || !mg_strcasecmp(conn->request_info.request_method,
  11234. "PUT")) {
  11235. /* POST or PUT request without content length set */
  11236. conn->content_len = -1;
  11237. } else if (!mg_strncasecmp(conn->request_info.request_method,
  11238. "HTTP/",
  11239. 5)) {
  11240. /* Response without content length set */
  11241. conn->content_len = -1;
  11242. } else {
  11243. /* Other request */
  11244. conn->content_len = 0;
  11245. }
  11246. }
  11247. return 1;
  11248. }
  11249. int
  11250. mg_get_response(struct mg_connection *conn,
  11251. char *ebuf,
  11252. size_t ebuf_len,
  11253. int timeout)
  11254. {
  11255. if (conn) {
  11256. /* Implementation of API function for HTTP clients */
  11257. int err, ret;
  11258. struct mg_context *octx = conn->ctx;
  11259. struct mg_context rctx = *(conn->ctx);
  11260. char txt[32]; /* will not overflow */
  11261. if (timeout >= 0) {
  11262. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  11263. rctx.config[REQUEST_TIMEOUT] = txt;
  11264. /* Not required for non-blocking sockets.
  11265. set_sock_timeout(conn->client.sock, timeout);
  11266. */
  11267. } else {
  11268. rctx.config[REQUEST_TIMEOUT] = NULL;
  11269. }
  11270. conn->ctx = &rctx;
  11271. ret = getreq(conn, ebuf, ebuf_len, &err);
  11272. conn->ctx = octx;
  11273. /* TODO: 1) uri is deprecated;
  11274. * 2) here, ri.uri is the http response code */
  11275. conn->request_info.uri = conn->request_info.request_uri;
  11276. /* TODO (mid): Define proper return values - maybe return length?
  11277. * For the first test use <0 for error and >0 for OK */
  11278. return (ret == 0) ? -1 : +1;
  11279. }
  11280. return -1;
  11281. }
  11282. struct mg_connection *
  11283. mg_download(const char *host,
  11284. int port,
  11285. int use_ssl,
  11286. char *ebuf,
  11287. size_t ebuf_len,
  11288. const char *fmt,
  11289. ...)
  11290. {
  11291. struct mg_connection *conn;
  11292. va_list ap;
  11293. int i;
  11294. int reqerr;
  11295. va_start(ap, fmt);
  11296. ebuf[0] = '\0';
  11297. /* open a connection */
  11298. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  11299. if (conn != NULL) {
  11300. i = mg_vprintf(conn, fmt, ap);
  11301. if (i <= 0) {
  11302. mg_snprintf(conn,
  11303. NULL, /* No truncation check for ebuf */
  11304. ebuf,
  11305. ebuf_len,
  11306. "%s",
  11307. "Error sending request");
  11308. } else {
  11309. getreq(conn, ebuf, ebuf_len, &reqerr);
  11310. /* TODO: 1) uri is deprecated;
  11311. * 2) here, ri.uri is the http response code */
  11312. conn->request_info.uri = conn->request_info.request_uri;
  11313. }
  11314. }
  11315. /* if an error occured, close the connection */
  11316. if (ebuf[0] != '\0' && conn != NULL) {
  11317. mg_close_connection(conn);
  11318. conn = NULL;
  11319. }
  11320. va_end(ap);
  11321. return conn;
  11322. }
  11323. struct websocket_client_thread_data {
  11324. struct mg_connection *conn;
  11325. mg_websocket_data_handler data_handler;
  11326. mg_websocket_close_handler close_handler;
  11327. void *callback_data;
  11328. };
  11329. #if defined(USE_WEBSOCKET)
  11330. #ifdef _WIN32
  11331. static unsigned __stdcall websocket_client_thread(void *data)
  11332. #else
  11333. static void *
  11334. websocket_client_thread(void *data)
  11335. #endif
  11336. {
  11337. struct websocket_client_thread_data *cdata =
  11338. (struct websocket_client_thread_data *)data;
  11339. mg_set_thread_name("ws-clnt");
  11340. if (cdata->conn->ctx) {
  11341. if (cdata->conn->ctx->callbacks.init_thread) {
  11342. /* 3 indicates a websocket client thread */
  11343. /* TODO: check if conn->ctx can be set */
  11344. cdata->conn->ctx->callbacks.init_thread(cdata->conn->ctx, 3);
  11345. }
  11346. }
  11347. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  11348. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  11349. if (cdata->close_handler != NULL) {
  11350. cdata->close_handler(cdata->conn, cdata->callback_data);
  11351. }
  11352. /* The websocket_client context has only this thread. If it runs out,
  11353. set the stop_flag to 2 (= "stopped"). */
  11354. cdata->conn->ctx->stop_flag = 2;
  11355. mg_free((void *)cdata);
  11356. #ifdef _WIN32
  11357. return 0;
  11358. #else
  11359. return NULL;
  11360. #endif
  11361. }
  11362. #endif
  11363. struct mg_connection *
  11364. mg_connect_websocket_client(const char *host,
  11365. int port,
  11366. int use_ssl,
  11367. char *error_buffer,
  11368. size_t error_buffer_size,
  11369. const char *path,
  11370. const char *origin,
  11371. mg_websocket_data_handler data_func,
  11372. mg_websocket_close_handler close_func,
  11373. void *user_data)
  11374. {
  11375. struct mg_connection *conn = NULL;
  11376. #if defined(USE_WEBSOCKET)
  11377. struct mg_context *newctx = NULL;
  11378. struct websocket_client_thread_data *thread_data;
  11379. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  11380. static const char *handshake_req;
  11381. if (origin != NULL) {
  11382. handshake_req = "GET %s HTTP/1.1\r\n"
  11383. "Host: %s\r\n"
  11384. "Upgrade: websocket\r\n"
  11385. "Connection: Upgrade\r\n"
  11386. "Sec-WebSocket-Key: %s\r\n"
  11387. "Sec-WebSocket-Version: 13\r\n"
  11388. "Origin: %s\r\n"
  11389. "\r\n";
  11390. } else {
  11391. handshake_req = "GET %s HTTP/1.1\r\n"
  11392. "Host: %s\r\n"
  11393. "Upgrade: websocket\r\n"
  11394. "Connection: Upgrade\r\n"
  11395. "Sec-WebSocket-Key: %s\r\n"
  11396. "Sec-WebSocket-Version: 13\r\n"
  11397. "\r\n";
  11398. }
  11399. /* Establish the client connection and request upgrade */
  11400. conn = mg_download(host,
  11401. port,
  11402. use_ssl,
  11403. error_buffer,
  11404. error_buffer_size,
  11405. handshake_req,
  11406. path,
  11407. host,
  11408. magic,
  11409. origin);
  11410. /* Connection object will be null if something goes wrong */
  11411. if (conn == NULL || (strcmp(conn->request_info.request_uri, "101") != 0)) {
  11412. if (!*error_buffer) {
  11413. /* if there is a connection, but it did not return 101,
  11414. * error_buffer is not yet set */
  11415. mg_snprintf(conn,
  11416. NULL, /* No truncation check for ebuf */
  11417. error_buffer,
  11418. error_buffer_size,
  11419. "Unexpected server reply");
  11420. }
  11421. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  11422. if (conn != NULL) {
  11423. mg_free(conn);
  11424. conn = NULL;
  11425. }
  11426. return conn;
  11427. }
  11428. /* For client connections, mg_context is fake. Since we need to set a
  11429. * callback function, we need to create a copy and modify it. */
  11430. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  11431. memcpy(newctx, conn->ctx, sizeof(struct mg_context));
  11432. newctx->user_data = user_data;
  11433. newctx->context_type = 2; /* ws/wss client context type */
  11434. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  11435. newctx->worker_threadids =
  11436. (pthread_t *)mg_calloc(newctx->cfg_worker_threads, sizeof(pthread_t));
  11437. conn->ctx = newctx;
  11438. thread_data = (struct websocket_client_thread_data *)
  11439. mg_calloc(sizeof(struct websocket_client_thread_data), 1);
  11440. thread_data->conn = conn;
  11441. thread_data->data_handler = data_func;
  11442. thread_data->close_handler = close_func;
  11443. thread_data->callback_data = NULL;
  11444. /* Start a thread to read the websocket client connection
  11445. * This thread will automatically stop when mg_disconnect is
  11446. * called on the client connection */
  11447. if (mg_start_thread_with_id(websocket_client_thread,
  11448. (void *)thread_data,
  11449. newctx->worker_threadids) != 0) {
  11450. mg_free((void *)thread_data);
  11451. mg_free((void *)newctx->worker_threadids);
  11452. mg_free((void *)newctx);
  11453. mg_free((void *)conn);
  11454. conn = NULL;
  11455. DEBUG_TRACE("%s",
  11456. "Websocket client connect thread could not be started\r\n");
  11457. }
  11458. #else
  11459. /* Appease "unused parameter" warnings */
  11460. (void)host;
  11461. (void)port;
  11462. (void)use_ssl;
  11463. (void)error_buffer;
  11464. (void)error_buffer_size;
  11465. (void)path;
  11466. (void)origin;
  11467. (void)user_data;
  11468. (void)data_func;
  11469. (void)close_func;
  11470. #endif
  11471. return conn;
  11472. }
  11473. static void
  11474. process_new_connection(struct mg_connection *conn)
  11475. {
  11476. if (conn && conn->ctx) {
  11477. struct mg_request_info *ri = &conn->request_info;
  11478. int keep_alive_enabled, keep_alive, discard_len;
  11479. char ebuf[100];
  11480. const char *hostend;
  11481. int reqerr, uri_type;
  11482. keep_alive_enabled =
  11483. !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  11484. /* Important: on new connection, reset the receiving buffer. Credit
  11485. * goes to crule42. */
  11486. conn->data_len = 0;
  11487. conn->handled_requests = 0;
  11488. do {
  11489. DEBUG_TRACE("calling getreq (%i times for this connection)",
  11490. conn->handled_requests + 1);
  11491. if (!getreq(conn, ebuf, sizeof(ebuf), &reqerr)) {
  11492. /* The request sent by the client could not be understood by
  11493. * the server, or it was incomplete or a timeout. Send an
  11494. * error message and close the connection. */
  11495. if (reqerr > 0) {
  11496. /*assert(ebuf[0] != '\0');*/
  11497. send_http_error(conn, reqerr, "%s", ebuf);
  11498. }
  11499. } else if (strcmp(ri->http_version, "1.0")
  11500. && strcmp(ri->http_version, "1.1")) {
  11501. mg_snprintf(conn,
  11502. NULL, /* No truncation check for ebuf */
  11503. ebuf,
  11504. sizeof(ebuf),
  11505. "Bad HTTP version: [%s]",
  11506. ri->http_version);
  11507. send_http_error(conn, 505, "%s", ebuf);
  11508. }
  11509. if (ebuf[0] == '\0') {
  11510. uri_type = get_uri_type(conn->request_info.request_uri);
  11511. switch (uri_type) {
  11512. case 1:
  11513. /* Asterisk */
  11514. conn->request_info.local_uri = NULL;
  11515. break;
  11516. case 2:
  11517. /* relative uri */
  11518. conn->request_info.local_uri =
  11519. conn->request_info.request_uri;
  11520. break;
  11521. case 3:
  11522. case 4:
  11523. /* absolute uri (with/without port) */
  11524. hostend = get_rel_url_at_current_server(
  11525. conn->request_info.request_uri, conn);
  11526. if (hostend) {
  11527. conn->request_info.local_uri = hostend;
  11528. } else {
  11529. conn->request_info.local_uri = NULL;
  11530. }
  11531. break;
  11532. default:
  11533. mg_snprintf(conn,
  11534. NULL, /* No truncation check for ebuf */
  11535. ebuf,
  11536. sizeof(ebuf),
  11537. "Invalid URI");
  11538. send_http_error(conn, 400, "%s", ebuf);
  11539. conn->request_info.local_uri = NULL;
  11540. break;
  11541. }
  11542. /* TODO: cleanup uri, local_uri and request_uri */
  11543. conn->request_info.uri = conn->request_info.local_uri;
  11544. }
  11545. DEBUG_TRACE("http: %s, error: %s",
  11546. (ri->http_version ? ri->http_version : "none"),
  11547. (ebuf[0] ? ebuf : "none"));
  11548. if (ebuf[0] == '\0') {
  11549. if (conn->request_info.local_uri) {
  11550. /* handle request to local server */
  11551. handle_request(conn);
  11552. DEBUG_TRACE("%s", "handle_request done");
  11553. if (conn->ctx->callbacks.end_request != NULL) {
  11554. conn->ctx->callbacks.end_request(conn,
  11555. conn->status_code);
  11556. DEBUG_TRACE("%s", "end_request callback done");
  11557. }
  11558. log_access(conn);
  11559. } else {
  11560. /* TODO: handle non-local request (PROXY) */
  11561. conn->must_close = 1;
  11562. }
  11563. } else {
  11564. conn->must_close = 1;
  11565. }
  11566. if (ri->remote_user != NULL) {
  11567. mg_free((void *)ri->remote_user);
  11568. /* Important! When having connections with and without auth
  11569. * would cause double free and then crash */
  11570. ri->remote_user = NULL;
  11571. }
  11572. /* NOTE(lsm): order is important here. should_keep_alive() call
  11573. * is
  11574. * using parsed request, which will be invalid after memmove's
  11575. * below.
  11576. * Therefore, memorize should_keep_alive() result now for later
  11577. * use
  11578. * in loop exit condition. */
  11579. keep_alive = (conn->ctx->stop_flag == 0) && keep_alive_enabled
  11580. && (conn->content_len >= 0) && should_keep_alive(conn);
  11581. /* Discard all buffered data for this request */
  11582. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  11583. && ((conn->request_len + conn->content_len)
  11584. < (int64_t)conn->data_len))
  11585. ? (int)(conn->request_len + conn->content_len)
  11586. : conn->data_len;
  11587. /*assert(discard_len >= 0);*/
  11588. if (discard_len < 0) {
  11589. DEBUG_TRACE("internal error: discard_len = %li",
  11590. (long int)discard_len);
  11591. break;
  11592. }
  11593. conn->data_len -= discard_len;
  11594. if (conn->data_len > 0) {
  11595. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  11596. memmove(conn->buf,
  11597. conn->buf + discard_len,
  11598. (size_t)conn->data_len);
  11599. }
  11600. /* assert(conn->data_len >= 0); */
  11601. /* assert(conn->data_len <= conn->buf_size); */
  11602. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  11603. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  11604. (long int)conn->data_len,
  11605. (long int)conn->buf_size);
  11606. break;
  11607. }
  11608. conn->handled_requests++;
  11609. } while (keep_alive);
  11610. }
  11611. }
  11612. #if defined(ALTERNATIVE_QUEUE)
  11613. static void
  11614. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11615. {
  11616. unsigned int i;
  11617. for (;;) {
  11618. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11619. /* find a free worker slot and signal it */
  11620. if (ctx->client_socks[i].in_use == 0) {
  11621. ctx->client_socks[i] = *sp;
  11622. ctx->client_socks[i].in_use = 1;
  11623. event_signal(ctx->client_wait_events[i]);
  11624. return;
  11625. }
  11626. }
  11627. /* queue is full */
  11628. mg_sleep(1);
  11629. }
  11630. }
  11631. static int
  11632. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11633. {
  11634. DEBUG_TRACE("%s", "going idle");
  11635. ctx->client_socks[thread_index].in_use = 0;
  11636. event_wait(ctx->client_wait_events[thread_index]);
  11637. *sp = ctx->client_socks[thread_index];
  11638. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11639. return !ctx->stop_flag;
  11640. }
  11641. #else /* ALTERNATIVE_QUEUE */
  11642. /* Worker threads take accepted socket from the queue */
  11643. static int
  11644. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  11645. {
  11646. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11647. (void)thread_index;
  11648. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11649. DEBUG_TRACE("%s", "going idle");
  11650. /* If the queue is empty, wait. We're idle at this point. */
  11651. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  11652. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  11653. }
  11654. /* If we're stopping, sq_head may be equal to sq_tail. */
  11655. if (ctx->sq_head > ctx->sq_tail) {
  11656. /* Copy socket from the queue and increment tail */
  11657. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  11658. ctx->sq_tail++;
  11659. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  11660. /* Wrap pointers if needed */
  11661. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  11662. ctx->sq_tail -= QUEUE_SIZE(ctx);
  11663. ctx->sq_head -= QUEUE_SIZE(ctx);
  11664. }
  11665. }
  11666. (void)pthread_cond_signal(&ctx->sq_empty);
  11667. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11668. return !ctx->stop_flag;
  11669. #undef QUEUE_SIZE
  11670. }
  11671. /* Master thread adds accepted socket to a queue */
  11672. static void
  11673. produce_socket(struct mg_context *ctx, const struct socket *sp)
  11674. {
  11675. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  11676. if (!ctx) {
  11677. return;
  11678. }
  11679. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11680. /* If the queue is full, wait */
  11681. while (ctx->stop_flag == 0
  11682. && ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx)) {
  11683. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  11684. }
  11685. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  11686. /* Copy socket to the queue and increment head */
  11687. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  11688. ctx->sq_head++;
  11689. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  11690. }
  11691. (void)pthread_cond_signal(&ctx->sq_full);
  11692. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11693. #undef QUEUE_SIZE
  11694. }
  11695. #endif /* ALTERNATIVE_QUEUE */
  11696. struct worker_thread_args {
  11697. struct mg_context *ctx;
  11698. int index;
  11699. };
  11700. static void *
  11701. worker_thread_run(struct worker_thread_args *thread_args)
  11702. {
  11703. struct mg_context *ctx = thread_args->ctx;
  11704. struct mg_connection *conn;
  11705. struct mg_workerTLS tls;
  11706. #if defined(MG_LEGACY_INTERFACE)
  11707. uint32_t addr;
  11708. #endif
  11709. mg_set_thread_name("worker");
  11710. tls.is_master = 0;
  11711. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  11712. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11713. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11714. #endif
  11715. if (ctx->callbacks.init_thread) {
  11716. /* call init_thread for a worker thread (type 1) */
  11717. ctx->callbacks.init_thread(ctx, 1);
  11718. }
  11719. conn = &ctx->worker_connections[thread_args->index];
  11720. pthread_setspecific(sTlsKey, &tls);
  11721. conn->buf_size = MAX_REQUEST_SIZE;
  11722. conn->buf = (char *)(conn + 1);
  11723. conn->ctx = ctx;
  11724. conn->thread_index = thread_args->index;
  11725. conn->request_info.user_data = ctx->user_data;
  11726. /* Allocate a mutex for this connection to allow communication both
  11727. * within the request handler and from elsewhere in the application
  11728. */
  11729. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  11730. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  11731. * signal sq_empty condvar to wake up the master waiting in
  11732. * produce_socket() */
  11733. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  11734. conn->conn_birth_time = time(NULL);
  11735. /* Fill in IP, port info early so even if SSL setup below fails,
  11736. * error handler would have the corresponding info.
  11737. * Thanks to Johannes Winkelmann for the patch.
  11738. */
  11739. #if defined(USE_IPV6)
  11740. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  11741. conn->request_info.remote_port =
  11742. ntohs(conn->client.rsa.sin6.sin6_port);
  11743. } else
  11744. #endif
  11745. {
  11746. conn->request_info.remote_port =
  11747. ntohs(conn->client.rsa.sin.sin_port);
  11748. }
  11749. sockaddr_to_string(conn->request_info.remote_addr,
  11750. sizeof(conn->request_info.remote_addr),
  11751. &conn->client.rsa);
  11752. DEBUG_TRACE("Start processing connection from %s",
  11753. conn->request_info.remote_addr);
  11754. #if defined(MG_LEGACY_INTERFACE)
  11755. /* This legacy interface only works for the IPv4 case */
  11756. addr = ntohl(conn->client.rsa.sin.sin_addr.s_addr);
  11757. memcpy(&conn->request_info.remote_ip, &addr, 4);
  11758. #endif
  11759. conn->request_info.is_ssl = conn->client.is_ssl;
  11760. if (conn->client.is_ssl) {
  11761. #ifndef NO_SSL
  11762. /* HTTPS connection */
  11763. if (sslize(conn,
  11764. conn->ctx->ssl_ctx,
  11765. SSL_accept,
  11766. &(conn->ctx->stop_flag))) {
  11767. /* Get SSL client certificate information (if set) */
  11768. ssl_get_client_cert_info(conn);
  11769. /* process HTTPS connection */
  11770. process_new_connection(conn);
  11771. /* Free client certificate info */
  11772. if (conn->request_info.client_cert) {
  11773. mg_free((void *)(conn->request_info.client_cert->subject));
  11774. mg_free((void *)(conn->request_info.client_cert->issuer));
  11775. mg_free((void *)(conn->request_info.client_cert->serial));
  11776. mg_free((void *)(conn->request_info.client_cert->finger));
  11777. conn->request_info.client_cert->subject = 0;
  11778. conn->request_info.client_cert->issuer = 0;
  11779. conn->request_info.client_cert->serial = 0;
  11780. conn->request_info.client_cert->finger = 0;
  11781. mg_free(conn->request_info.client_cert);
  11782. conn->request_info.client_cert = 0;
  11783. }
  11784. }
  11785. #endif
  11786. } else {
  11787. /* process HTTP connection */
  11788. process_new_connection(conn);
  11789. }
  11790. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  11791. conn->request_info.remote_addr,
  11792. difftime(time(NULL), conn->conn_birth_time));
  11793. close_connection(conn);
  11794. DEBUG_TRACE("%s", "Connection closed");
  11795. }
  11796. pthread_setspecific(sTlsKey, NULL);
  11797. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11798. CloseHandle(tls.pthread_cond_helper_mutex);
  11799. #endif
  11800. pthread_mutex_destroy(&conn->mutex);
  11801. DEBUG_TRACE("%s", "exiting");
  11802. return NULL;
  11803. }
  11804. /* Threads have different return types on Windows and Unix. */
  11805. #ifdef _WIN32
  11806. static unsigned __stdcall worker_thread(void *thread_func_param)
  11807. {
  11808. struct worker_thread_args *pwta =
  11809. (struct worker_thread_args *)thread_func_param;
  11810. worker_thread_run(pwta);
  11811. mg_free(thread_func_param);
  11812. return 0;
  11813. }
  11814. #else
  11815. static void *
  11816. worker_thread(void *thread_func_param)
  11817. {
  11818. struct worker_thread_args *pwta =
  11819. (struct worker_thread_args *)thread_func_param;
  11820. worker_thread_run(pwta);
  11821. mg_free(thread_func_param);
  11822. return NULL;
  11823. }
  11824. #endif /* _WIN32 */
  11825. static void
  11826. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  11827. {
  11828. struct socket so;
  11829. char src_addr[IP_ADDR_STR_LEN];
  11830. socklen_t len = sizeof(so.rsa);
  11831. int on = 1;
  11832. int timeout;
  11833. if (!listener) {
  11834. return;
  11835. }
  11836. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  11837. == INVALID_SOCKET) {
  11838. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  11839. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  11840. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  11841. closesocket(so.sock);
  11842. so.sock = INVALID_SOCKET;
  11843. } else {
  11844. /* Put so socket structure into the queue */
  11845. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  11846. set_close_on_exec(so.sock, fc(ctx));
  11847. so.is_ssl = listener->is_ssl;
  11848. so.ssl_redir = listener->ssl_redir;
  11849. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  11850. mg_cry(fc(ctx),
  11851. "%s: getsockname() failed: %s",
  11852. __func__,
  11853. strerror(ERRNO));
  11854. }
  11855. /* Set TCP keep-alive. This is needed because if HTTP-level
  11856. * keep-alive
  11857. * is enabled, and client resets the connection, server won't get
  11858. * TCP FIN or RST and will keep the connection open forever. With
  11859. * TCP keep-alive, next keep-alive handshake will figure out that
  11860. * the client is down and will close the server end.
  11861. * Thanks to Igor Klopov who suggested the patch. */
  11862. if (setsockopt(so.sock,
  11863. SOL_SOCKET,
  11864. SO_KEEPALIVE,
  11865. (SOCK_OPT_TYPE)&on,
  11866. sizeof(on)) != 0) {
  11867. mg_cry(fc(ctx),
  11868. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  11869. __func__,
  11870. strerror(ERRNO));
  11871. }
  11872. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  11873. * to effectively fill up the underlying IP packet payload and
  11874. * reduce the overhead of sending lots of small buffers. However
  11875. * this hurts the server's throughput (ie. operations per second)
  11876. * when HTTP 1.1 persistent connections are used and the responses
  11877. * are relatively small (eg. less than 1400 bytes).
  11878. */
  11879. if ((ctx != NULL) && (ctx->config[CONFIG_TCP_NODELAY] != NULL)
  11880. && (!strcmp(ctx->config[CONFIG_TCP_NODELAY], "1"))) {
  11881. if (set_tcp_nodelay(so.sock, 1) != 0) {
  11882. mg_cry(fc(ctx),
  11883. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  11884. __func__,
  11885. strerror(ERRNO));
  11886. }
  11887. }
  11888. if (ctx && ctx->config[REQUEST_TIMEOUT]) {
  11889. timeout = atoi(ctx->config[REQUEST_TIMEOUT]);
  11890. } else {
  11891. timeout = -1;
  11892. }
  11893. /* TODO: if non blocking sockets are used, timeouts are implemented
  11894. * differently */
  11895. // if (timeout > 0) {
  11896. // set_sock_timeout(so.sock, timeout);
  11897. //}
  11898. (void)timeout;
  11899. set_blocking_mode(so.sock, 0);
  11900. produce_socket(ctx, &so);
  11901. }
  11902. }
  11903. static void
  11904. master_thread_run(void *thread_func_param)
  11905. {
  11906. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  11907. struct mg_workerTLS tls;
  11908. struct pollfd *pfd;
  11909. unsigned int i;
  11910. unsigned int workerthreadcount;
  11911. if (!ctx) {
  11912. return;
  11913. }
  11914. mg_set_thread_name("master");
  11915. /* Increase priority of the master thread */
  11916. #if defined(_WIN32)
  11917. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  11918. #elif defined(USE_MASTER_THREAD_PRIORITY)
  11919. int min_prio = sched_get_priority_min(SCHED_RR);
  11920. int max_prio = sched_get_priority_max(SCHED_RR);
  11921. if ((min_prio >= 0) && (max_prio >= 0)
  11922. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  11923. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  11924. struct sched_param sched_param = {0};
  11925. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  11926. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  11927. }
  11928. #endif
  11929. /* Initialize thread local storage */
  11930. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  11931. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  11932. #endif
  11933. tls.is_master = 1;
  11934. pthread_setspecific(sTlsKey, &tls);
  11935. if (ctx->callbacks.init_thread) {
  11936. /* Callback for the master thread (type 0) */
  11937. ctx->callbacks.init_thread(ctx, 0);
  11938. }
  11939. /* Server starts *now* */
  11940. ctx->start_time = time(NULL);
  11941. /* Start the server */
  11942. pfd = ctx->listening_socket_fds;
  11943. while (ctx->stop_flag == 0) {
  11944. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11945. pfd[i].fd = ctx->listening_sockets[i].sock;
  11946. pfd[i].events = POLLIN;
  11947. }
  11948. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  11949. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11950. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  11951. * successful poll, and POLLIN is defined as
  11952. * (POLLRDNORM | POLLRDBAND)
  11953. * Therefore, we're checking pfd[i].revents & POLLIN, not
  11954. * pfd[i].revents == POLLIN. */
  11955. if (ctx->stop_flag == 0 && (pfd[i].revents & POLLIN)) {
  11956. accept_new_connection(&ctx->listening_sockets[i], ctx);
  11957. }
  11958. }
  11959. }
  11960. }
  11961. /* Here stop_flag is 1 - Initiate shutdown. */
  11962. DEBUG_TRACE("%s", "stopping workers");
  11963. /* Stop signal received: somebody called mg_stop. Quit. */
  11964. close_all_listening_sockets(ctx);
  11965. /* Wakeup workers that are waiting for connections to handle. */
  11966. (void)pthread_mutex_lock(&ctx->thread_mutex);
  11967. #if defined(ALTERNATIVE_QUEUE)
  11968. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  11969. event_signal(ctx->client_wait_events[i]);
  11970. /* Since we know all sockets, we can shutdown the connections. */
  11971. if (ctx->client_socks[i].in_use) {
  11972. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  11973. }
  11974. }
  11975. #else
  11976. pthread_cond_broadcast(&ctx->sq_full);
  11977. #endif
  11978. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  11979. /* Join all worker threads to avoid leaking threads. */
  11980. workerthreadcount = ctx->cfg_worker_threads;
  11981. for (i = 0; i < workerthreadcount; i++) {
  11982. if (ctx->worker_threadids[i] != 0) {
  11983. mg_join_thread(ctx->worker_threadids[i]);
  11984. }
  11985. }
  11986. #if defined(USE_LUA)
  11987. /* Free Lua state of lua background task */
  11988. if (ctx->lua_background_state) {
  11989. lua_close((lua_State *)ctx->lua_background_state);
  11990. ctx->lua_background_state = 0;
  11991. }
  11992. #endif
  11993. #if !defined(NO_SSL)
  11994. if (ctx->ssl_ctx != NULL) {
  11995. uninitialize_ssl(ctx);
  11996. }
  11997. #endif
  11998. DEBUG_TRACE("%s", "exiting");
  11999. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12000. CloseHandle(tls.pthread_cond_helper_mutex);
  12001. #endif
  12002. pthread_setspecific(sTlsKey, NULL);
  12003. /* Signal mg_stop() that we're done.
  12004. * WARNING: This must be the very last thing this
  12005. * thread does, as ctx becomes invalid after this line. */
  12006. ctx->stop_flag = 2;
  12007. }
  12008. /* Threads have different return types on Windows and Unix. */
  12009. #ifdef _WIN32
  12010. static unsigned __stdcall master_thread(void *thread_func_param)
  12011. {
  12012. master_thread_run(thread_func_param);
  12013. return 0;
  12014. }
  12015. #else
  12016. static void *
  12017. master_thread(void *thread_func_param)
  12018. {
  12019. master_thread_run(thread_func_param);
  12020. return NULL;
  12021. }
  12022. #endif /* _WIN32 */
  12023. static void
  12024. free_context(struct mg_context *ctx)
  12025. {
  12026. int i;
  12027. struct mg_handler_info *tmp_rh;
  12028. if (ctx == NULL) {
  12029. return;
  12030. }
  12031. if (ctx->callbacks.exit_context) {
  12032. ctx->callbacks.exit_context(ctx);
  12033. }
  12034. /* All threads exited, no sync is needed. Destroy thread mutex and
  12035. * condvars
  12036. */
  12037. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  12038. #if defined(ALTERNATIVE_QUEUE)
  12039. mg_free(ctx->client_socks);
  12040. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12041. event_destroy(ctx->client_wait_events[i]);
  12042. }
  12043. mg_free(ctx->client_wait_events);
  12044. #else
  12045. (void)pthread_cond_destroy(&ctx->sq_empty);
  12046. (void)pthread_cond_destroy(&ctx->sq_full);
  12047. #endif
  12048. /* Destroy other context global data structures mutex */
  12049. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  12050. #if defined(USE_TIMERS)
  12051. timers_exit(ctx);
  12052. #endif
  12053. /* Deallocate config parameters */
  12054. for (i = 0; i < NUM_OPTIONS; i++) {
  12055. if (ctx->config[i] != NULL) {
  12056. #if defined(_MSC_VER)
  12057. #pragma warning(suppress : 6001)
  12058. #endif
  12059. mg_free(ctx->config[i]);
  12060. }
  12061. }
  12062. /* Deallocate request handlers */
  12063. while (ctx->handlers) {
  12064. tmp_rh = ctx->handlers;
  12065. ctx->handlers = tmp_rh->next;
  12066. mg_free(tmp_rh->uri);
  12067. mg_free(tmp_rh);
  12068. }
  12069. #ifndef NO_SSL
  12070. /* Deallocate SSL context */
  12071. if (ctx->ssl_ctx != NULL) {
  12072. SSL_CTX_free(ctx->ssl_ctx);
  12073. }
  12074. #endif /* !NO_SSL */
  12075. /* Deallocate worker thread ID array */
  12076. if (ctx->worker_threadids != NULL) {
  12077. mg_free(ctx->worker_threadids);
  12078. }
  12079. /* Deallocate worker thread ID array */
  12080. if (ctx->worker_connections != NULL) {
  12081. mg_free(ctx->worker_connections);
  12082. }
  12083. /* Deallocate the tls variable */
  12084. if (mg_atomic_dec(&sTlsInit) == 0) {
  12085. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12086. DeleteCriticalSection(&global_log_file_lock);
  12087. #endif /* _WIN32 && !__SYMBIAN32__ */
  12088. #if !defined(_WIN32)
  12089. pthread_mutexattr_destroy(&pthread_mutex_attr);
  12090. #endif
  12091. pthread_key_delete(sTlsKey);
  12092. #if defined(USE_LUA)
  12093. lua_exit_optional_libraries();
  12094. #endif
  12095. }
  12096. /* deallocate system name string */
  12097. mg_free(ctx->systemName);
  12098. /* Deallocate context itself */
  12099. mg_free(ctx);
  12100. }
  12101. void
  12102. mg_stop(struct mg_context *ctx)
  12103. {
  12104. pthread_t mt;
  12105. if (!ctx) {
  12106. return;
  12107. }
  12108. /* We don't use a lock here. Calling mg_stop with the same ctx from
  12109. * two threads is not allowed. */
  12110. mt = ctx->masterthreadid;
  12111. if (mt == 0) {
  12112. return;
  12113. }
  12114. ctx->masterthreadid = 0;
  12115. /* Set stop flag, so all threads know they have to exit. */
  12116. ctx->stop_flag = 1;
  12117. /* Wait until everything has stopped. */
  12118. while (ctx->stop_flag != 2) {
  12119. (void)mg_sleep(10);
  12120. }
  12121. mg_join_thread(mt);
  12122. free_context(ctx);
  12123. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12124. (void)WSACleanup();
  12125. #endif /* _WIN32 && !__SYMBIAN32__ */
  12126. }
  12127. static void
  12128. get_system_name(char **sysName)
  12129. {
  12130. #if defined(_WIN32)
  12131. #if !defined(__SYMBIAN32__)
  12132. #if defined(_WIN32_WCE)
  12133. *sysName = mg_strdup("WinCE");
  12134. #else
  12135. char name[128];
  12136. DWORD dwVersion = 0;
  12137. DWORD dwMajorVersion = 0;
  12138. DWORD dwMinorVersion = 0;
  12139. DWORD dwBuild = 0;
  12140. #ifdef _MSC_VER
  12141. #pragma warning(push)
  12142. /* GetVersion was declared deprecated */
  12143. #pragma warning(disable : 4996)
  12144. #endif
  12145. dwVersion = GetVersion();
  12146. #ifdef _MSC_VER
  12147. #pragma warning(pop)
  12148. #endif
  12149. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12150. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12151. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  12152. (void)dwBuild;
  12153. sprintf(name,
  12154. "Windows %u.%u",
  12155. (unsigned)dwMajorVersion,
  12156. (unsigned)dwMinorVersion);
  12157. *sysName = mg_strdup(name);
  12158. #endif
  12159. #else
  12160. *sysName = mg_strdup("Symbian");
  12161. #endif
  12162. #else
  12163. struct utsname name;
  12164. memset(&name, 0, sizeof(name));
  12165. uname(&name);
  12166. *sysName = mg_strdup(name.sysname);
  12167. #endif
  12168. }
  12169. struct mg_context *
  12170. mg_start(const struct mg_callbacks *callbacks,
  12171. void *user_data,
  12172. const char **options)
  12173. {
  12174. struct mg_context *ctx;
  12175. const char *name, *value, *default_value;
  12176. int idx, ok, workerthreadcount;
  12177. unsigned int i;
  12178. void (*exit_callback)(const struct mg_context *ctx) = 0;
  12179. struct mg_workerTLS tls;
  12180. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12181. WSADATA data;
  12182. WSAStartup(MAKEWORD(2, 2), &data);
  12183. #endif /* _WIN32 && !__SYMBIAN32__ */
  12184. /* Allocate context and initialize reasonable general case defaults. */
  12185. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  12186. return NULL;
  12187. }
  12188. /* Random number generator will initialize at the first call */
  12189. ctx->auth_nonce_mask =
  12190. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  12191. if (mg_atomic_inc(&sTlsInit) == 1) {
  12192. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12193. InitializeCriticalSection(&global_log_file_lock);
  12194. #endif /* _WIN32 && !__SYMBIAN32__ */
  12195. #if !defined(_WIN32)
  12196. pthread_mutexattr_init(&pthread_mutex_attr);
  12197. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  12198. #endif
  12199. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  12200. /* Fatal error - abort start. However, this situation should
  12201. * never
  12202. * occur in practice. */
  12203. mg_atomic_dec(&sTlsInit);
  12204. mg_cry(fc(ctx), "Cannot initialize thread local storage");
  12205. mg_free(ctx);
  12206. return NULL;
  12207. }
  12208. #if defined(USE_LUA)
  12209. lua_init_optional_libraries();
  12210. #endif
  12211. } else {
  12212. /* TODO (low): istead of sleeping, check if sTlsKey is already
  12213. * initialized. */
  12214. mg_sleep(1);
  12215. }
  12216. tls.is_master = -1;
  12217. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  12218. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  12219. tls.pthread_cond_helper_mutex = NULL;
  12220. #endif
  12221. pthread_setspecific(sTlsKey, &tls);
  12222. /* Dummy use this function - in some #ifdef combinations it's used,
  12223. * while it's not used in others, but GCC seems to stupid to understand
  12224. * #pragma GCC diagnostic ignored "-Wunused-function"
  12225. * in cases the function is unused, and it also complains on
  12226. * __attribute((unused))__ in cases it is used.
  12227. * So dummy use it, to have our peace. */
  12228. (void)mg_current_thread_id();
  12229. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  12230. #if !defined(ALTERNATIVE_QUEUE)
  12231. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  12232. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  12233. #endif
  12234. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  12235. if (!ok) {
  12236. /* Fatal error - abort start. However, this situation should never
  12237. * occur in practice. */
  12238. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  12239. mg_free(ctx);
  12240. pthread_setspecific(sTlsKey, NULL);
  12241. return NULL;
  12242. }
  12243. if (callbacks) {
  12244. ctx->callbacks = *callbacks;
  12245. exit_callback = callbacks->exit_context;
  12246. ctx->callbacks.exit_context = 0;
  12247. }
  12248. ctx->user_data = user_data;
  12249. ctx->handlers = NULL;
  12250. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  12251. ctx->shared_lua_websockets = 0;
  12252. #endif
  12253. while (options && (name = *options++) != NULL) {
  12254. if ((idx = get_option_index(name)) == -1) {
  12255. mg_cry(fc(ctx), "Invalid option: %s", name);
  12256. free_context(ctx);
  12257. pthread_setspecific(sTlsKey, NULL);
  12258. return NULL;
  12259. } else if ((value = *options++) == NULL) {
  12260. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  12261. free_context(ctx);
  12262. pthread_setspecific(sTlsKey, NULL);
  12263. return NULL;
  12264. }
  12265. if (ctx->config[idx] != NULL) {
  12266. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  12267. mg_free(ctx->config[idx]);
  12268. }
  12269. ctx->config[idx] = mg_strdup(value);
  12270. DEBUG_TRACE("[%s] -> [%s]", name, value);
  12271. }
  12272. /* Set default value if needed */
  12273. for (i = 0; config_options[i].name != NULL; i++) {
  12274. default_value = config_options[i].default_value;
  12275. if (ctx->config[i] == NULL && default_value != NULL) {
  12276. ctx->config[i] = mg_strdup(default_value);
  12277. }
  12278. }
  12279. workerthreadcount = atoi(ctx->config[NUM_THREADS]);
  12280. if (workerthreadcount > MAX_WORKER_THREADS) {
  12281. mg_cry(fc(ctx), "Too many worker threads");
  12282. free_context(ctx);
  12283. pthread_setspecific(sTlsKey, NULL);
  12284. return NULL;
  12285. }
  12286. if (workerthreadcount <= 0) {
  12287. mg_cry(fc(ctx), "Invalid number of worker threads");
  12288. free_context(ctx);
  12289. pthread_setspecific(sTlsKey, NULL);
  12290. return NULL;
  12291. }
  12292. #if defined(NO_FILES)
  12293. if (ctx->config[DOCUMENT_ROOT] != NULL) {
  12294. mg_cry(fc(ctx), "%s", "Document root must not be set");
  12295. free_context(ctx);
  12296. pthread_setspecific(sTlsKey, NULL);
  12297. return NULL;
  12298. }
  12299. #endif
  12300. get_system_name(&ctx->systemName);
  12301. #if defined(USE_LUA)
  12302. /* If a Lua background script has been configured, start it. */
  12303. if (ctx->config[LUA_BACKGROUND_SCRIPT] != NULL) {
  12304. char ebuf[256];
  12305. void *state = (void *)mg_prepare_lua_context_script(
  12306. ctx->config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  12307. if (!state) {
  12308. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  12309. free_context(ctx);
  12310. pthread_setspecific(sTlsKey, NULL);
  12311. return NULL;
  12312. }
  12313. ctx->lua_background_state = state;
  12314. } else {
  12315. ctx->lua_background_state = 0;
  12316. }
  12317. #endif
  12318. /* NOTE(lsm): order is important here. SSL certificates must
  12319. * be initialized before listening ports. UID must be set last. */
  12320. if (!set_gpass_option(ctx) ||
  12321. #if !defined(NO_SSL)
  12322. !set_ssl_option(ctx) ||
  12323. #endif
  12324. !set_ports_option(ctx) ||
  12325. #if !defined(_WIN32)
  12326. !set_uid_option(ctx) ||
  12327. #endif
  12328. !set_acl_option(ctx)) {
  12329. free_context(ctx);
  12330. pthread_setspecific(sTlsKey, NULL);
  12331. return NULL;
  12332. }
  12333. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  12334. /* Ignore SIGPIPE signal, so if browser cancels the request, it
  12335. * won't kill the whole process. */
  12336. (void)signal(SIGPIPE, SIG_IGN);
  12337. #endif /* !_WIN32 && !__SYMBIAN32__ */
  12338. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  12339. ctx->worker_threadids =
  12340. (pthread_t *)mg_calloc(ctx->cfg_worker_threads, sizeof(pthread_t));
  12341. if (ctx->worker_threadids == NULL) {
  12342. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12343. free_context(ctx);
  12344. pthread_setspecific(sTlsKey, NULL);
  12345. return NULL;
  12346. }
  12347. ctx->worker_connections =
  12348. (struct mg_connection *)mg_calloc(ctx->cfg_worker_threads,
  12349. sizeof(struct mg_connection));
  12350. if (ctx->worker_connections == NULL) {
  12351. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  12352. free_context(ctx);
  12353. pthread_setspecific(sTlsKey, NULL);
  12354. return NULL;
  12355. }
  12356. #if defined(ALTERNATIVE_QUEUE)
  12357. ctx->client_wait_events =
  12358. mg_calloc(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads);
  12359. if (ctx->client_wait_events == NULL) {
  12360. mg_cry(fc(ctx), "Not enough memory for worker event array");
  12361. mg_free(ctx->worker_threadids);
  12362. free_context(ctx);
  12363. pthread_setspecific(sTlsKey, NULL);
  12364. return NULL;
  12365. }
  12366. ctx->client_socks =
  12367. mg_calloc(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads);
  12368. if (ctx->client_wait_events == NULL) {
  12369. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  12370. mg_free(ctx->client_socks);
  12371. mg_free(ctx->worker_threadids);
  12372. free_context(ctx);
  12373. pthread_setspecific(sTlsKey, NULL);
  12374. return NULL;
  12375. }
  12376. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  12377. ctx->client_wait_events[i] = event_create();
  12378. if (ctx->client_wait_events[i] == 0) {
  12379. mg_cry(fc(ctx), "Error creating worker event %i", i);
  12380. /* TODO: clean all and exit */
  12381. }
  12382. }
  12383. #endif
  12384. #if defined(USE_TIMERS)
  12385. if (timers_init(ctx) != 0) {
  12386. mg_cry(fc(ctx), "Error creating timers");
  12387. free_context(ctx);
  12388. pthread_setspecific(sTlsKey, NULL);
  12389. return NULL;
  12390. }
  12391. #endif
  12392. /* Context has been created - init user libraries */
  12393. if (ctx->callbacks.init_context) {
  12394. ctx->callbacks.init_context(ctx);
  12395. }
  12396. ctx->callbacks.exit_context = exit_callback;
  12397. ctx->context_type = 1; /* server context */
  12398. /* Start master (listening) thread */
  12399. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  12400. /* Start worker threads */
  12401. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  12402. struct worker_thread_args *wta =
  12403. mg_malloc(sizeof(struct worker_thread_args));
  12404. if (wta) {
  12405. wta->ctx = ctx;
  12406. wta->index = (int)i;
  12407. }
  12408. if ((wta == NULL)
  12409. || (mg_start_thread_with_id(worker_thread,
  12410. wta,
  12411. &ctx->worker_threadids[i]) != 0)) {
  12412. /* thread was not created */
  12413. if (wta != NULL) {
  12414. mg_free(wta);
  12415. }
  12416. if (i > 0) {
  12417. mg_cry(fc(ctx),
  12418. "Cannot start worker thread %i: error %ld",
  12419. i + 1,
  12420. (long)ERRNO);
  12421. } else {
  12422. mg_cry(fc(ctx),
  12423. "Cannot create threads: error %ld",
  12424. (long)ERRNO);
  12425. free_context(ctx);
  12426. pthread_setspecific(sTlsKey, NULL);
  12427. return NULL;
  12428. }
  12429. break;
  12430. }
  12431. }
  12432. pthread_setspecific(sTlsKey, NULL);
  12433. return ctx;
  12434. }
  12435. /* Feature check API function */
  12436. unsigned
  12437. mg_check_feature(unsigned feature)
  12438. {
  12439. static const unsigned feature_set = 0
  12440. /* Set bits for available features according to API documentation.
  12441. * This bit mask is created at compile time, according to the active
  12442. * preprocessor defines. It is a single const value at runtime. */
  12443. #if !defined(NO_FILES)
  12444. | 0x0001u
  12445. #endif
  12446. #if !defined(NO_SSL)
  12447. | 0x0002u
  12448. #endif
  12449. #if !defined(NO_CGI)
  12450. | 0x0004u
  12451. #endif
  12452. #if defined(USE_IPV6)
  12453. | 0x0008u
  12454. #endif
  12455. #if defined(USE_WEBSOCKET)
  12456. | 0x0010u
  12457. #endif
  12458. #if defined(USE_LUA)
  12459. | 0x0020u
  12460. #endif
  12461. #if defined(USE_DUKTAPE)
  12462. | 0x0040u
  12463. #endif
  12464. #if !defined(NO_CACHING)
  12465. | 0x0080u
  12466. #endif
  12467. /* Set some extra bits not defined in the API documentation.
  12468. * These bits may change without further notice. */
  12469. #if defined(MG_LEGACY_INTERFACE)
  12470. | 0x8000u
  12471. #endif
  12472. #if defined(MEMORY_DEBUGGING)
  12473. | 0x0100u
  12474. #endif
  12475. #if defined(USE_TIMERS)
  12476. | 0x0200u
  12477. #endif
  12478. #if !defined(NO_NONCE_CHECK)
  12479. | 0x0400u
  12480. #endif
  12481. #if !defined(NO_POPEN)
  12482. | 0x0800u
  12483. #endif
  12484. ;
  12485. return (feature & feature_set);
  12486. }
  12487. /* Print system information.
  12488. * TODO: define parameters. */
  12489. int
  12490. mg_print_system_info(int prm1, char *prm2)
  12491. {
  12492. char buf[256];
  12493. const char *version = mg_version();
  12494. #if defined(_WIN32)
  12495. #if !defined(__SYMBIAN32__)
  12496. DWORD dwVersion = 0;
  12497. DWORD dwMajorVersion = 0;
  12498. DWORD dwMinorVersion = 0;
  12499. SYSTEM_INFO si;
  12500. GetSystemInfo(&si);
  12501. #ifdef _MSC_VER
  12502. #pragma warning(push)
  12503. // GetVersion was declared deprecated
  12504. #pragma warning(disable : 4996)
  12505. #endif
  12506. dwVersion = GetVersion();
  12507. #ifdef _MSC_VER
  12508. #pragma warning(pop)
  12509. #endif
  12510. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  12511. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  12512. mg_snprintf(NULL,
  12513. NULL,
  12514. buf,
  12515. sizeof(buf),
  12516. "Windows %u.%u",
  12517. (unsigned)dwMajorVersion,
  12518. (unsigned)dwMinorVersion);
  12519. if (prm1 == 0) {
  12520. puts(buf);
  12521. }
  12522. mg_snprintf(NULL,
  12523. NULL,
  12524. buf,
  12525. sizeof(buf),
  12526. "CPU: type %u, cores %u, mask %x",
  12527. (unsigned)si.wProcessorArchitecture,
  12528. (unsigned)si.dwNumberOfProcessors,
  12529. (unsigned)si.dwActiveProcessorMask);
  12530. if (prm1 == 0) {
  12531. puts(buf);
  12532. }
  12533. #else
  12534. mg_snprintf(NULL, NULL, buf, sizeof(buf), "%s - Symbian");
  12535. if (prm1 == 0) {
  12536. puts(buf);
  12537. }
  12538. #endif
  12539. #else
  12540. struct utsname name;
  12541. memset(&name, 0, sizeof(name));
  12542. uname(&name);
  12543. mg_snprintf(NULL,
  12544. NULL,
  12545. buf,
  12546. sizeof(buf),
  12547. "%s %s (%s) - %s",
  12548. name.sysname,
  12549. name.version,
  12550. name.release,
  12551. name.machine);
  12552. if (prm1 == 0) {
  12553. puts(buf);
  12554. }
  12555. #endif
  12556. mg_snprintf(NULL,
  12557. NULL,
  12558. buf,
  12559. sizeof(buf),
  12560. "Features: %X%s%s%s%s%s%s",
  12561. mg_check_feature(0xFFFFFFFFu),
  12562. mg_check_feature(1) ? " Files" : "",
  12563. mg_check_feature(2) ? " HTTPS" : "",
  12564. mg_check_feature(4) ? " CGI" : "",
  12565. mg_check_feature(8) ? " IPv6" : "",
  12566. mg_check_feature(16) ? " WebSockets" : "",
  12567. mg_check_feature(32) ? " Lua" : "");
  12568. if (prm1 == 0) {
  12569. puts(buf);
  12570. }
  12571. #ifdef USE_LUA
  12572. mg_snprintf(NULL,
  12573. NULL,
  12574. buf,
  12575. sizeof(buf),
  12576. "Lua Version: %u (%s)",
  12577. (unsigned)LUA_VERSION_NUM,
  12578. LUA_RELEASE);
  12579. if (prm1 == 0) {
  12580. puts(buf);
  12581. }
  12582. #endif
  12583. mg_snprintf(NULL, NULL, buf, sizeof(buf), "Version: %s", version);
  12584. if (prm1 == 0) {
  12585. puts(buf);
  12586. }
  12587. mg_snprintf(NULL, NULL, buf, sizeof(buf), "Build: %s", __DATE__);
  12588. if (prm1 == 0) {
  12589. puts(buf);
  12590. }
  12591. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  12592. #if defined(_MSC_VER)
  12593. mg_snprintf(NULL,
  12594. NULL,
  12595. buf,
  12596. sizeof(buf),
  12597. "MSC: %u (%u)",
  12598. (unsigned)_MSC_VER,
  12599. (unsigned)_MSC_FULL_VER);
  12600. if (prm1 == 0) {
  12601. puts(buf);
  12602. }
  12603. #elif defined(__MINGW64__)
  12604. mg_snprintf(NULL,
  12605. NULL,
  12606. buf,
  12607. sizeof(buf),
  12608. "MinGW64: %u.%u",
  12609. (unsigned)__MINGW64_VERSION_MAJOR,
  12610. (unsigned)__MINGW64_VERSION_MINOR);
  12611. if (prm1 == 0) {
  12612. puts(buf);
  12613. }
  12614. mg_snprintf(NULL,
  12615. NULL,
  12616. buf,
  12617. sizeof(buf),
  12618. "MinGW32: %u.%u",
  12619. (unsigned)__MINGW32_MAJOR_VERSION,
  12620. (unsigned)__MINGW32_MINOR_VERSION);
  12621. if (prm1 == 0) {
  12622. puts(buf);
  12623. }
  12624. #elif defined(__MINGW32__)
  12625. mg_snprintf(NULL,
  12626. NULL,
  12627. buf,
  12628. sizeof(buf),
  12629. "MinGW32: %u.%u",
  12630. (unsigned)__MINGW32_MAJOR_VERSION,
  12631. (unsigned)__MINGW32_MINOR_VERSION);
  12632. if (prm1 == 0) {
  12633. puts(buf);
  12634. }
  12635. #elif defined(__clang__)
  12636. mg_snprintf(NULL,
  12637. NULL,
  12638. buf,
  12639. sizeof(buf),
  12640. "clang: %u.%u.%u (%s)",
  12641. __clang_major__,
  12642. __clang_minor__,
  12643. __clang_patchlevel__,
  12644. __clang_version__);
  12645. if (prm1 == 0) {
  12646. puts(buf);
  12647. }
  12648. #elif defined(__GNUC__)
  12649. mg_snprintf(NULL,
  12650. NULL,
  12651. buf,
  12652. sizeof(buf),
  12653. "gcc: %u.%u.%u",
  12654. (unsigned)__GNUC__,
  12655. (unsigned)__GNUC_MINOR__,
  12656. (unsigned)__GNUC_PATCHLEVEL__);
  12657. if (prm1 == 0) {
  12658. puts(buf);
  12659. }
  12660. #elif defined(__INTEL_COMPILER)
  12661. mg_snprintf(NULL,
  12662. NULL,
  12663. buf,
  12664. sizeof(buf),
  12665. "Intel C/C++: %u",
  12666. (unsigned)__INTEL_COMPILER);
  12667. if (prm1 == 0) {
  12668. puts(buf);
  12669. }
  12670. #elif defined(__BORLANDC__)
  12671. mg_snprintf(NULL,
  12672. NULL,
  12673. buf,
  12674. sizeof(buf),
  12675. "Borland C: 0x%x",
  12676. (unsigned)__BORLANDC__);
  12677. if (prm1 == 0) {
  12678. puts(buf);
  12679. }
  12680. #elif defined(__SUNPRO_C)
  12681. mg_snprintf(
  12682. NULL, NULL, buf, sizeof(buf), "Solaris: 0x%x", (unsigned)__SUNPRO_C);
  12683. if (prm1 == 0) {
  12684. puts(buf);
  12685. }
  12686. #else
  12687. mg_snprintf(NULL, NULL, buf, sizeof(buf), "Other");
  12688. if (prm1 == 0) {
  12689. puts(buf);
  12690. }
  12691. #endif
  12692. /* Determine 32/64 bit data mode.
  12693. * see https://en.wikipedia.org/wiki/64-bit_computing */
  12694. mg_snprintf(NULL,
  12695. NULL,
  12696. buf,
  12697. sizeof(buf),
  12698. "Data model: int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  12699. "ptr:%u, size:%u, time:%u",
  12700. (unsigned)sizeof(short),
  12701. (unsigned)sizeof(int),
  12702. (unsigned)sizeof(long),
  12703. (unsigned)sizeof(long long),
  12704. (unsigned)sizeof(float),
  12705. (unsigned)sizeof(double),
  12706. (unsigned)sizeof(long double),
  12707. (unsigned)sizeof(char),
  12708. (unsigned)sizeof(wchar_t),
  12709. (unsigned)sizeof(void *),
  12710. (unsigned)sizeof(size_t),
  12711. (unsigned)sizeof(time_t));
  12712. if (prm1 == 0) {
  12713. puts(buf);
  12714. }
  12715. // WARNING: these parameters are not being used
  12716. (void)prm2;
  12717. return 0;
  12718. }
  12719. /* mg_init_library counter */
  12720. static int mg_init_library_called = 0;
  12721. /* Initialize this library. This function does not need to be thread safe. */
  12722. unsigned
  12723. mg_init_library(unsigned features)
  12724. {
  12725. /* Currently we do nothing here. This is planned for Version 1.10.
  12726. * For now, we just add this function, so clients can be changed early. */
  12727. if (mg_init_library_called <= 0) {
  12728. mg_init_library_called = 1;
  12729. return mg_check_feature(features & 0xFFu);
  12730. }
  12731. return 0;
  12732. }
  12733. /* Un-initialize this library. */
  12734. unsigned
  12735. mg_exit_library(void)
  12736. {
  12737. if (mg_init_library_called <= 0) {
  12738. return 0;
  12739. }
  12740. mg_init_library_called--;
  12741. return 1;
  12742. }
  12743. /* End of civetweb.c */