civetweb.c 530 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895
  1. /* Copyright (c) 2013-2018 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(__GNUC__) || defined(__MINGW32__)
  23. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0501
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Alternative queue is well tested and should be the new default */
  123. #if defined(NO_ALTERNATIVE_QUEUE)
  124. #if defined(ALTERNATIVE_QUEUE)
  125. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  126. #endif
  127. #else
  128. #define ALTERNATIVE_QUEUE
  129. #endif
  130. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  131. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  132. #endif
  133. /* DTL -- including winsock2.h works better if lean and mean */
  134. #if !defined(WIN32_LEAN_AND_MEAN)
  135. #define WIN32_LEAN_AND_MEAN
  136. #endif
  137. #if defined(__SYMBIAN32__)
  138. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  139. * Symbian is no longer maintained since 2014-01-01.
  140. * Recent versions of CivetWeb are no longer tested for Symbian.
  141. * It makes no sense, to support an abandoned operating system.
  142. */
  143. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  144. #define NO_SSL /* SSL is not supported */
  145. #define NO_CGI /* CGI is not supported */
  146. #define PATH_MAX FILENAME_MAX
  147. #endif /* __SYMBIAN32__ */
  148. #if defined(__ZEPHYR__)
  149. #include <time.h>
  150. #include <ctype.h>
  151. #include <net/socket.h>
  152. #include <posix/pthread.h>
  153. #include <posix/time.h>
  154. #include <stdio.h>
  155. #include <stdlib.h>
  156. #include <string.h>
  157. #include <zephyr.h>
  158. #include <fcntl.h>
  159. #include <libc_extensions.h>
  160. /* Max worker threads is the max of pthreads minus the main application thread
  161. * and minus the main civetweb thread, thus -2
  162. */
  163. #define MAX_WORKER_THREADS (CONFIG_MAX_PTHREAD_COUNT - 2)
  164. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  165. #define ZEPHYR_STACK_SIZE USE_STACK_SIZE
  166. #else
  167. #define ZEPHYR_STACK_SIZE 8096
  168. #endif
  169. K_THREAD_STACK_DEFINE(civetweb_main_stack, ZEPHYR_STACK_SIZE);
  170. K_THREAD_STACK_ARRAY_DEFINE(civetweb_worker_stacks,
  171. MAX_WORKER_THREADS,
  172. ZEPHYR_STACK_SIZE);
  173. static int zephyr_worker_stack_index;
  174. #endif
  175. #if !defined(CIVETWEB_HEADER_INCLUDED)
  176. /* Include the header file here, so the CivetWeb interface is defined for the
  177. * entire implementation, including the following forward definitions. */
  178. #include "civetweb.h"
  179. #endif
  180. #if !defined(DEBUG_TRACE)
  181. #if defined(DEBUG)
  182. static void DEBUG_TRACE_FUNC(const char *func,
  183. unsigned line,
  184. PRINTF_FORMAT_STRING(const char *fmt),
  185. ...) PRINTF_ARGS(3, 4);
  186. #define DEBUG_TRACE(fmt, ...) \
  187. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  188. #define NEED_DEBUG_TRACE_FUNC
  189. #else
  190. #define DEBUG_TRACE(fmt, ...) \
  191. do { \
  192. } while (0)
  193. #endif /* DEBUG */
  194. #endif /* DEBUG_TRACE */
  195. #if !defined(DEBUG_ASSERT)
  196. #if defined(DEBUG)
  197. #define DEBUG_ASSERT(cond) \
  198. do { \
  199. if (!(cond)) { \
  200. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  201. exit(2); /* Exit with error */ \
  202. } \
  203. } while (0)
  204. #else
  205. #define DEBUG_ASSERT(cond)
  206. #endif /* DEBUG */
  207. #endif
  208. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  209. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  210. __attribute__((no_instrument_function));
  211. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  212. __attribute__((no_instrument_function));
  213. void
  214. __cyg_profile_func_enter(void *this_fn, void *call_site)
  215. {
  216. if ((void *)this_fn != (void *)printf) {
  217. printf("E %p %p\n", this_fn, call_site);
  218. }
  219. }
  220. void
  221. __cyg_profile_func_exit(void *this_fn, void *call_site)
  222. {
  223. if ((void *)this_fn != (void *)printf) {
  224. printf("X %p %p\n", this_fn, call_site);
  225. }
  226. }
  227. #endif
  228. #if !defined(IGNORE_UNUSED_RESULT)
  229. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  230. #endif
  231. #if defined(__GNUC__) || defined(__MINGW32__)
  232. /* GCC unused function attribute seems fundamentally broken.
  233. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  234. * OR UNUSED" for individual functions failed.
  235. * Either the compiler creates an "unused-function" warning if a
  236. * function is not marked with __attribute__((unused)).
  237. * On the other hand, if the function is marked with this attribute,
  238. * but is used, the compiler raises a completely idiotic
  239. * "used-but-marked-unused" warning - and
  240. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  241. * raises error: unknown option after "#pragma GCC diagnostic".
  242. * Disable this warning completely, until the GCC guys sober up
  243. * again.
  244. */
  245. #pragma GCC diagnostic ignored "-Wunused-function"
  246. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  247. #else
  248. #define FUNCTION_MAY_BE_UNUSED
  249. #endif
  250. /* Some ANSI #includes are not available on Windows CE */
  251. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  252. #include <errno.h>
  253. #include <fcntl.h>
  254. #include <signal.h>
  255. #include <stdlib.h>
  256. #include <sys/stat.h>
  257. #include <sys/types.h>
  258. #endif /* !_WIN32_WCE */
  259. #if defined(__clang__)
  260. /* When using -Weverything, clang does not accept it's own headers
  261. * in a release build configuration. Disable what is too much in
  262. * -Weverything. */
  263. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  264. #endif
  265. #if defined(__GNUC__) || defined(__MINGW32__)
  266. /* Who on earth came to the conclusion, using __DATE__ should rise
  267. * an "expansion of date or time macro is not reproducible"
  268. * warning. That's exactly what was intended by using this macro.
  269. * Just disable this nonsense warning. */
  270. /* And disabling them does not work either:
  271. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  272. * #pragma clang diagnostic ignored "-Wdate-time"
  273. * So we just have to disable ALL warnings for some lines
  274. * of code.
  275. * This seems to be a known GCC bug, not resolved since 2012:
  276. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  277. */
  278. #endif
  279. #if defined(__MACH__) /* Apple OSX section */
  280. #if defined(__clang__)
  281. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  282. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  283. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  284. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  285. #endif
  286. #endif
  287. #define CLOCK_MONOTONIC (1)
  288. #define CLOCK_REALTIME (2)
  289. #include <mach/clock.h>
  290. #include <mach/mach.h>
  291. #include <mach/mach_time.h>
  292. #include <sys/errno.h>
  293. #include <sys/time.h>
  294. /* clock_gettime is not implemented on OSX prior to 10.12 */
  295. static int
  296. _civet_clock_gettime(int clk_id, struct timespec *t)
  297. {
  298. memset(t, 0, sizeof(*t));
  299. if (clk_id == CLOCK_REALTIME) {
  300. struct timeval now;
  301. int rv = gettimeofday(&now, NULL);
  302. if (rv) {
  303. return rv;
  304. }
  305. t->tv_sec = now.tv_sec;
  306. t->tv_nsec = now.tv_usec * 1000;
  307. return 0;
  308. } else if (clk_id == CLOCK_MONOTONIC) {
  309. static uint64_t clock_start_time = 0;
  310. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  311. uint64_t now = mach_absolute_time();
  312. if (clock_start_time == 0) {
  313. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  314. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  315. /* appease "unused variable" warning for release builds */
  316. (void)mach_status;
  317. clock_start_time = now;
  318. }
  319. now = (uint64_t)((double)(now - clock_start_time)
  320. * (double)timebase_ifo.numer
  321. / (double)timebase_ifo.denom);
  322. t->tv_sec = now / 1000000000;
  323. t->tv_nsec = now % 1000000000;
  324. return 0;
  325. }
  326. return -1; /* EINVAL - Clock ID is unknown */
  327. }
  328. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  329. #if defined(__CLOCK_AVAILABILITY)
  330. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  331. * declared but it may be NULL at runtime. So we need to check before using
  332. * it. */
  333. static int
  334. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  335. {
  336. if (clock_gettime) {
  337. return clock_gettime(clk_id, t);
  338. }
  339. return _civet_clock_gettime(clk_id, t);
  340. }
  341. #define clock_gettime _civet_safe_clock_gettime
  342. #else
  343. #define clock_gettime _civet_clock_gettime
  344. #endif
  345. #endif
  346. /********************************************************************/
  347. /* CivetWeb configuration defines */
  348. /********************************************************************/
  349. /* Maximum number of threads that can be configured.
  350. * The number of threads actually created depends on the "num_threads"
  351. * configuration parameter, but this is the upper limit. */
  352. #if !defined(MAX_WORKER_THREADS)
  353. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  354. #endif
  355. /* Timeout interval for select/poll calls.
  356. * The timeouts depend on "*_timeout_ms" configuration values, but long
  357. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  358. * This reduces the time required to stop the server. */
  359. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  360. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  361. #endif
  362. /* Do not try to compress files smaller than this limit. */
  363. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  364. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  365. #endif
  366. #if !defined(PASSWORDS_FILE_NAME)
  367. #define PASSWORDS_FILE_NAME ".htpasswd"
  368. #endif
  369. /* Initial buffer size for all CGI environment variables. In case there is
  370. * not enough space, another block is allocated. */
  371. #if !defined(CGI_ENVIRONMENT_SIZE)
  372. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  373. #endif
  374. /* Maximum number of environment variables. */
  375. #if !defined(MAX_CGI_ENVIR_VARS)
  376. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  377. #endif
  378. /* General purpose buffer size. */
  379. #if !defined(MG_BUF_LEN) /* in bytes */
  380. #define MG_BUF_LEN (1024 * 8)
  381. #endif
  382. /* Size of the accepted socket queue (in case the old queue implementation
  383. * is used). */
  384. #if !defined(MGSQLEN)
  385. #define MGSQLEN (20) /* count */
  386. #endif
  387. /********************************************************************/
  388. /* Helper makros */
  389. #if !defined(ARRAY_SIZE)
  390. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  391. #endif
  392. #include <stdint.h>
  393. /* Standard defines */
  394. #if !defined(INT64_MAX)
  395. #define INT64_MAX (9223372036854775807)
  396. #endif
  397. #define SHUTDOWN_RD (0)
  398. #define SHUTDOWN_WR (1)
  399. #define SHUTDOWN_BOTH (2)
  400. mg_static_assert(MAX_WORKER_THREADS >= 1,
  401. "worker threads must be a positive number");
  402. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  403. "size_t data type size check");
  404. #if defined(_WIN32) /* WINDOWS include block */
  405. #include <malloc.h> /* *alloc( */
  406. #include <stdlib.h> /* *alloc( */
  407. #include <time.h> /* struct timespec */
  408. #include <windows.h>
  409. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  410. #include <ws2tcpip.h>
  411. typedef const char *SOCK_OPT_TYPE;
  412. #if !defined(PATH_MAX)
  413. #define W_PATH_MAX (MAX_PATH)
  414. /* at most three UTF-8 chars per wchar_t */
  415. #define PATH_MAX (W_PATH_MAX * 3)
  416. #else
  417. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  418. #endif
  419. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  420. #if !defined(_IN_PORT_T)
  421. #if !defined(in_port_t)
  422. #define in_port_t u_short
  423. #endif
  424. #endif
  425. #if !defined(_WIN32_WCE)
  426. #include <direct.h>
  427. #include <io.h>
  428. #include <process.h>
  429. #else /* _WIN32_WCE */
  430. #define NO_CGI /* WinCE has no pipes */
  431. #define NO_POPEN /* WinCE has no popen */
  432. typedef long off_t;
  433. #define errno ((int)(GetLastError()))
  434. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  435. #endif /* _WIN32_WCE */
  436. #define MAKEUQUAD(lo, hi) \
  437. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  438. #define RATE_DIFF (10000000) /* 100 nsecs */
  439. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  440. #define SYS2UNIX_TIME(lo, hi) \
  441. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  442. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  443. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  444. * Also use _strtoui64 on modern M$ compilers */
  445. #if defined(_MSC_VER)
  446. #if (_MSC_VER < 1300)
  447. #define STRX(x) #x
  448. #define STR(x) STRX(x)
  449. #define __func__ __FILE__ ":" STR(__LINE__)
  450. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  451. #define strtoll(x, y, z) (_atoi64(x))
  452. #else
  453. #define __func__ __FUNCTION__
  454. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  455. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  456. #endif
  457. #endif /* _MSC_VER */
  458. #define ERRNO ((int)(GetLastError()))
  459. #define NO_SOCKLEN_T
  460. #if defined(_WIN64) || defined(__MINGW64__)
  461. #if !defined(SSL_LIB)
  462. #define SSL_LIB "ssleay64.dll"
  463. #endif
  464. #if !defined(CRYPTO_LIB)
  465. #define CRYPTO_LIB "libeay64.dll"
  466. #endif
  467. #else
  468. #if !defined(SSL_LIB)
  469. #define SSL_LIB "ssleay32.dll"
  470. #endif
  471. #if !defined(CRYPTO_LIB)
  472. #define CRYPTO_LIB "libeay32.dll"
  473. #endif
  474. #endif
  475. #define O_NONBLOCK (0)
  476. #if !defined(W_OK)
  477. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  478. #endif
  479. #define _POSIX_
  480. #define INT64_FMT "I64d"
  481. #define UINT64_FMT "I64u"
  482. #define WINCDECL __cdecl
  483. #define vsnprintf_impl _vsnprintf
  484. #define access _access
  485. #define mg_sleep(x) (Sleep(x))
  486. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  487. #if !defined(popen)
  488. #define popen(x, y) (_popen(x, y))
  489. #endif
  490. #if !defined(pclose)
  491. #define pclose(x) (_pclose(x))
  492. #endif
  493. #define close(x) (_close(x))
  494. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  495. #define RTLD_LAZY (0)
  496. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  497. #define fdopen(x, y) (_fdopen((x), (y)))
  498. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  499. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  500. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  501. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  502. #define sleep(x) (Sleep((x)*1000))
  503. #define rmdir(x) (_rmdir(x))
  504. #if defined(_WIN64) || !defined(__MINGW32__)
  505. /* Only MinGW 32 bit is missing this function */
  506. #define timegm(x) (_mkgmtime(x))
  507. #else
  508. time_t timegm(struct tm *tm);
  509. #define NEED_TIMEGM
  510. #endif
  511. #if !defined(fileno)
  512. #define fileno(x) (_fileno(x))
  513. #endif /* !fileno MINGW #defines fileno */
  514. typedef struct {
  515. CRITICAL_SECTION sec; /* Immovable */
  516. } pthread_mutex_t;
  517. typedef DWORD pthread_key_t;
  518. typedef HANDLE pthread_t;
  519. typedef struct {
  520. pthread_mutex_t threadIdSec;
  521. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  522. } pthread_cond_t;
  523. #if !defined(__clockid_t_defined)
  524. typedef DWORD clockid_t;
  525. #endif
  526. #if !defined(CLOCK_MONOTONIC)
  527. #define CLOCK_MONOTONIC (1)
  528. #endif
  529. #if !defined(CLOCK_REALTIME)
  530. #define CLOCK_REALTIME (2)
  531. #endif
  532. #if !defined(CLOCK_THREAD)
  533. #define CLOCK_THREAD (3)
  534. #endif
  535. #if !defined(CLOCK_PROCESS)
  536. #define CLOCK_PROCESS (4)
  537. #endif
  538. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  539. #define _TIMESPEC_DEFINED
  540. #endif
  541. #if !defined(_TIMESPEC_DEFINED)
  542. struct timespec {
  543. time_t tv_sec; /* seconds */
  544. long tv_nsec; /* nanoseconds */
  545. };
  546. #endif
  547. #if !defined(WIN_PTHREADS_TIME_H)
  548. #define MUST_IMPLEMENT_CLOCK_GETTIME
  549. #endif
  550. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  551. #define clock_gettime mg_clock_gettime
  552. static int
  553. clock_gettime(clockid_t clk_id, struct timespec *tp)
  554. {
  555. FILETIME ft;
  556. ULARGE_INTEGER li, li2;
  557. BOOL ok = FALSE;
  558. double d;
  559. static double perfcnt_per_sec = 0.0;
  560. static BOOL initialized = FALSE;
  561. if (!initialized) {
  562. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  563. perfcnt_per_sec = 1.0 / li.QuadPart;
  564. initialized = TRUE;
  565. }
  566. if (tp) {
  567. memset(tp, 0, sizeof(*tp));
  568. if (clk_id == CLOCK_REALTIME) {
  569. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  570. GetSystemTimeAsFileTime(&ft);
  571. li.LowPart = ft.dwLowDateTime;
  572. li.HighPart = ft.dwHighDateTime;
  573. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  574. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  575. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  576. ok = TRUE;
  577. /* END: CLOCK_REALTIME */
  578. } else if (clk_id == CLOCK_MONOTONIC) {
  579. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  580. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  581. d = li.QuadPart * perfcnt_per_sec;
  582. tp->tv_sec = (time_t)d;
  583. d -= (double)tp->tv_sec;
  584. tp->tv_nsec = (long)(d * 1.0E9);
  585. ok = TRUE;
  586. /* END: CLOCK_MONOTONIC */
  587. } else if (clk_id == CLOCK_THREAD) {
  588. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  589. FILETIME t_create, t_exit, t_kernel, t_user;
  590. if (GetThreadTimes(GetCurrentThread(),
  591. &t_create,
  592. &t_exit,
  593. &t_kernel,
  594. &t_user)) {
  595. li.LowPart = t_user.dwLowDateTime;
  596. li.HighPart = t_user.dwHighDateTime;
  597. li2.LowPart = t_kernel.dwLowDateTime;
  598. li2.HighPart = t_kernel.dwHighDateTime;
  599. li.QuadPart += li2.QuadPart;
  600. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  601. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  602. ok = TRUE;
  603. }
  604. /* END: CLOCK_THREAD */
  605. } else if (clk_id == CLOCK_PROCESS) {
  606. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  607. FILETIME t_create, t_exit, t_kernel, t_user;
  608. if (GetProcessTimes(GetCurrentProcess(),
  609. &t_create,
  610. &t_exit,
  611. &t_kernel,
  612. &t_user)) {
  613. li.LowPart = t_user.dwLowDateTime;
  614. li.HighPart = t_user.dwHighDateTime;
  615. li2.LowPart = t_kernel.dwLowDateTime;
  616. li2.HighPart = t_kernel.dwHighDateTime;
  617. li.QuadPart += li2.QuadPart;
  618. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  619. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  620. ok = TRUE;
  621. }
  622. /* END: CLOCK_PROCESS */
  623. } else {
  624. /* BEGIN: unknown clock */
  625. /* ok = FALSE; already set by init */
  626. /* END: unknown clock */
  627. }
  628. }
  629. return ok ? 0 : -1;
  630. }
  631. #endif
  632. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  633. static int pthread_mutex_lock(pthread_mutex_t *);
  634. static int pthread_mutex_unlock(pthread_mutex_t *);
  635. static void path_to_unicode(const struct mg_connection *conn,
  636. const char *path,
  637. wchar_t *wbuf,
  638. size_t wbuf_len);
  639. /* All file operations need to be rewritten to solve #246. */
  640. struct mg_file;
  641. static const char *
  642. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  643. /* POSIX dirent interface */
  644. struct dirent {
  645. char d_name[PATH_MAX];
  646. };
  647. typedef struct DIR {
  648. HANDLE handle;
  649. WIN32_FIND_DATAW info;
  650. struct dirent result;
  651. } DIR;
  652. #if defined(HAVE_POLL)
  653. #define mg_pollfd pollfd
  654. #else
  655. struct mg_pollfd {
  656. SOCKET fd;
  657. short events;
  658. short revents;
  659. };
  660. #endif
  661. /* Mark required libraries */
  662. #if defined(_MSC_VER)
  663. #pragma comment(lib, "Ws2_32.lib")
  664. #endif
  665. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  666. #include <inttypes.h>
  667. typedef const void *SOCK_OPT_TYPE;
  668. #if defined(ANDROID)
  669. typedef unsigned short int in_port_t;
  670. #endif
  671. #if !defined(__ZEPHYR__)
  672. #include <arpa/inet.h>
  673. #include <ctype.h>
  674. #include <dirent.h>
  675. #include <grp.h>
  676. #include <limits.h>
  677. #include <netdb.h>
  678. #include <netinet/in.h>
  679. #include <netinet/tcp.h>
  680. #include <pthread.h>
  681. #include <pwd.h>
  682. #include <stdarg.h>
  683. #include <stddef.h>
  684. #include <stdio.h>
  685. #include <stdlib.h>
  686. #include <string.h>
  687. #include <sys/poll.h>
  688. #include <sys/socket.h>
  689. #include <sys/time.h>
  690. #include <sys/utsname.h>
  691. #include <sys/wait.h>
  692. #include <time.h>
  693. #include <unistd.h>
  694. #endif
  695. #define vsnprintf_impl vsnprintf
  696. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  697. #include <dlfcn.h>
  698. #endif
  699. #if defined(__MACH__)
  700. #define SSL_LIB "libssl.dylib"
  701. #define CRYPTO_LIB "libcrypto.dylib"
  702. #else
  703. #if !defined(SSL_LIB)
  704. #define SSL_LIB "libssl.so"
  705. #endif
  706. #if !defined(CRYPTO_LIB)
  707. #define CRYPTO_LIB "libcrypto.so"
  708. #endif
  709. #endif
  710. #if !defined(O_BINARY)
  711. #define O_BINARY (0)
  712. #endif /* O_BINARY */
  713. #define closesocket(a) (close(a))
  714. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  715. #define mg_remove(conn, x) (remove(x))
  716. #define mg_sleep(x) (usleep((x)*1000))
  717. #define mg_opendir(conn, x) (opendir(x))
  718. #define mg_closedir(x) (closedir(x))
  719. #define mg_readdir(x) (readdir(x))
  720. #define ERRNO (errno)
  721. #define INVALID_SOCKET (-1)
  722. #define INT64_FMT PRId64
  723. #define UINT64_FMT PRIu64
  724. typedef int SOCKET;
  725. #define WINCDECL
  726. #if defined(__hpux)
  727. /* HPUX 11 does not have monotonic, fall back to realtime */
  728. #if !defined(CLOCK_MONOTONIC)
  729. #define CLOCK_MONOTONIC CLOCK_REALTIME
  730. #endif
  731. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  732. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  733. * the prototypes use int* rather than socklen_t* which matches the
  734. * actual library expectation. When called with the wrong size arg
  735. * accept() returns a zero client inet addr and check_acl() always
  736. * fails. Since socklen_t is widely used below, just force replace
  737. * their typedef with int. - DTL
  738. */
  739. #define socklen_t int
  740. #endif /* hpux */
  741. #define mg_pollfd pollfd
  742. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  743. /* In case our C library is missing "timegm", provide an implementation */
  744. #if defined(NEED_TIMEGM)
  745. static inline int
  746. is_leap(int y)
  747. {
  748. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  749. }
  750. static inline int
  751. count_leap(int y)
  752. {
  753. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  754. }
  755. time_t
  756. timegm(struct tm *tm)
  757. {
  758. static const unsigned short ydays[] = {
  759. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  760. int year = tm->tm_year + 1900;
  761. int mon = tm->tm_mon;
  762. int mday = tm->tm_mday - 1;
  763. int hour = tm->tm_hour;
  764. int min = tm->tm_min;
  765. int sec = tm->tm_sec;
  766. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  767. || (mday >= ydays[mon + 1] - ydays[mon]
  768. + (mon == 1 && is_leap(year) ? 1 : 0))
  769. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  770. return -1;
  771. time_t res = year - 1970;
  772. res *= 365;
  773. res += mday;
  774. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  775. res += count_leap(year);
  776. res *= 24;
  777. res += hour;
  778. res *= 60;
  779. res += min;
  780. res *= 60;
  781. res += sec;
  782. return res;
  783. }
  784. #endif /* NEED_TIMEGM */
  785. /* va_copy should always be a macro, C99 and C++11 - DTL */
  786. #if !defined(va_copy)
  787. #define va_copy(x, y) ((x) = (y))
  788. #endif
  789. #if defined(_WIN32)
  790. /* Create substitutes for POSIX functions in Win32. */
  791. #if defined(GCC_DIAGNOSTIC)
  792. /* Show no warning in case system functions are not used. */
  793. #pragma GCC diagnostic push
  794. #pragma GCC diagnostic ignored "-Wunused-function"
  795. #endif
  796. static pthread_mutex_t global_log_file_lock;
  797. FUNCTION_MAY_BE_UNUSED
  798. static DWORD
  799. pthread_self(void)
  800. {
  801. return GetCurrentThreadId();
  802. }
  803. FUNCTION_MAY_BE_UNUSED
  804. static int
  805. pthread_key_create(
  806. pthread_key_t *key,
  807. void (*_ignored)(void *) /* destructor not supported for Windows */
  808. )
  809. {
  810. (void)_ignored;
  811. if ((key != 0)) {
  812. *key = TlsAlloc();
  813. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  814. }
  815. return -2;
  816. }
  817. FUNCTION_MAY_BE_UNUSED
  818. static int
  819. pthread_key_delete(pthread_key_t key)
  820. {
  821. return TlsFree(key) ? 0 : 1;
  822. }
  823. FUNCTION_MAY_BE_UNUSED
  824. static int
  825. pthread_setspecific(pthread_key_t key, void *value)
  826. {
  827. return TlsSetValue(key, value) ? 0 : 1;
  828. }
  829. FUNCTION_MAY_BE_UNUSED
  830. static void *
  831. pthread_getspecific(pthread_key_t key)
  832. {
  833. return TlsGetValue(key);
  834. }
  835. #if defined(GCC_DIAGNOSTIC)
  836. /* Enable unused function warning again */
  837. #pragma GCC diagnostic pop
  838. #endif
  839. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  840. #else
  841. static pthread_mutexattr_t pthread_mutex_attr;
  842. #endif /* _WIN32 */
  843. #if defined(_WIN32_WCE)
  844. /* Create substitutes for POSIX functions in Win32. */
  845. #if defined(GCC_DIAGNOSTIC)
  846. /* Show no warning in case system functions are not used. */
  847. #pragma GCC diagnostic push
  848. #pragma GCC diagnostic ignored "-Wunused-function"
  849. #endif
  850. FUNCTION_MAY_BE_UNUSED
  851. static time_t
  852. time(time_t *ptime)
  853. {
  854. time_t t;
  855. SYSTEMTIME st;
  856. FILETIME ft;
  857. GetSystemTime(&st);
  858. SystemTimeToFileTime(&st, &ft);
  859. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  860. if (ptime != NULL) {
  861. *ptime = t;
  862. }
  863. return t;
  864. }
  865. FUNCTION_MAY_BE_UNUSED
  866. static struct tm *
  867. localtime_s(const time_t *ptime, struct tm *ptm)
  868. {
  869. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  870. FILETIME ft, lft;
  871. SYSTEMTIME st;
  872. TIME_ZONE_INFORMATION tzinfo;
  873. if (ptm == NULL) {
  874. return NULL;
  875. }
  876. *(int64_t *)&ft = t;
  877. FileTimeToLocalFileTime(&ft, &lft);
  878. FileTimeToSystemTime(&lft, &st);
  879. ptm->tm_year = st.wYear - 1900;
  880. ptm->tm_mon = st.wMonth - 1;
  881. ptm->tm_wday = st.wDayOfWeek;
  882. ptm->tm_mday = st.wDay;
  883. ptm->tm_hour = st.wHour;
  884. ptm->tm_min = st.wMinute;
  885. ptm->tm_sec = st.wSecond;
  886. ptm->tm_yday = 0; /* hope nobody uses this */
  887. ptm->tm_isdst =
  888. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  889. return ptm;
  890. }
  891. FUNCTION_MAY_BE_UNUSED
  892. static struct tm *
  893. gmtime_s(const time_t *ptime, struct tm *ptm)
  894. {
  895. /* FIXME(lsm): fix this. */
  896. return localtime_s(ptime, ptm);
  897. }
  898. static int mg_atomic_inc(volatile int *addr);
  899. static struct tm tm_array[MAX_WORKER_THREADS];
  900. static int tm_index = 0;
  901. FUNCTION_MAY_BE_UNUSED
  902. static struct tm *
  903. localtime(const time_t *ptime)
  904. {
  905. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  906. return localtime_s(ptime, tm_array + i);
  907. }
  908. FUNCTION_MAY_BE_UNUSED
  909. static struct tm *
  910. gmtime(const time_t *ptime)
  911. {
  912. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  913. return gmtime_s(ptime, tm_array + i);
  914. }
  915. FUNCTION_MAY_BE_UNUSED
  916. static size_t
  917. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  918. {
  919. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  920. * for WinCE"); */
  921. return 0;
  922. }
  923. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  924. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  925. #define remove(f) mg_remove(NULL, f)
  926. FUNCTION_MAY_BE_UNUSED
  927. static int
  928. rename(const char *a, const char *b)
  929. {
  930. wchar_t wa[W_PATH_MAX];
  931. wchar_t wb[W_PATH_MAX];
  932. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  933. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  934. return MoveFileW(wa, wb) ? 0 : -1;
  935. }
  936. struct stat {
  937. int64_t st_size;
  938. time_t st_mtime;
  939. };
  940. FUNCTION_MAY_BE_UNUSED
  941. static int
  942. stat(const char *name, struct stat *st)
  943. {
  944. wchar_t wbuf[W_PATH_MAX];
  945. WIN32_FILE_ATTRIBUTE_DATA attr;
  946. time_t creation_time, write_time;
  947. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  948. memset(&attr, 0, sizeof(attr));
  949. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  950. st->st_size =
  951. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  952. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  953. attr.ftLastWriteTime.dwHighDateTime);
  954. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  955. attr.ftCreationTime.dwHighDateTime);
  956. if (creation_time > write_time) {
  957. st->st_mtime = creation_time;
  958. } else {
  959. st->st_mtime = write_time;
  960. }
  961. return 0;
  962. }
  963. #define access(x, a) 1 /* not required anyway */
  964. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  965. /* Values from errno.h in Windows SDK (Visual Studio). */
  966. #define EEXIST 17
  967. #define EACCES 13
  968. #define ENOENT 2
  969. #if defined(GCC_DIAGNOSTIC)
  970. /* Enable unused function warning again */
  971. #pragma GCC diagnostic pop
  972. #endif
  973. #endif /* defined(_WIN32_WCE) */
  974. #if defined(GCC_DIAGNOSTIC)
  975. /* Show no warning in case system functions are not used. */
  976. #pragma GCC diagnostic push
  977. #pragma GCC diagnostic ignored "-Wunused-function"
  978. #endif /* defined(GCC_DIAGNOSTIC) */
  979. #if defined(__clang__)
  980. /* Show no warning in case system functions are not used. */
  981. #pragma clang diagnostic push
  982. #pragma clang diagnostic ignored "-Wunused-function"
  983. #endif
  984. static pthread_mutex_t global_lock_mutex;
  985. FUNCTION_MAY_BE_UNUSED
  986. static void
  987. mg_global_lock(void)
  988. {
  989. (void)pthread_mutex_lock(&global_lock_mutex);
  990. }
  991. FUNCTION_MAY_BE_UNUSED
  992. static void
  993. mg_global_unlock(void)
  994. {
  995. (void)pthread_mutex_unlock(&global_lock_mutex);
  996. }
  997. FUNCTION_MAY_BE_UNUSED
  998. static int
  999. mg_atomic_inc(volatile int *addr)
  1000. {
  1001. int ret;
  1002. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1003. /* Depending on the SDK, this function uses either
  1004. * (volatile unsigned int *) or (volatile LONG *),
  1005. * so whatever you use, the other SDK is likely to raise a warning. */
  1006. ret = InterlockedIncrement((volatile long *)addr);
  1007. #elif defined(__GNUC__) \
  1008. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1009. && !defined(NO_ATOMICS)
  1010. ret = __sync_add_and_fetch(addr, 1);
  1011. #else
  1012. mg_global_lock();
  1013. ret = (++(*addr));
  1014. mg_global_unlock();
  1015. #endif
  1016. return ret;
  1017. }
  1018. FUNCTION_MAY_BE_UNUSED
  1019. static int
  1020. mg_atomic_dec(volatile int *addr)
  1021. {
  1022. int ret;
  1023. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1024. /* Depending on the SDK, this function uses either
  1025. * (volatile unsigned int *) or (volatile LONG *),
  1026. * so whatever you use, the other SDK is likely to raise a warning. */
  1027. ret = InterlockedDecrement((volatile long *)addr);
  1028. #elif defined(__GNUC__) \
  1029. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1030. && !defined(NO_ATOMICS)
  1031. ret = __sync_sub_and_fetch(addr, 1);
  1032. #else
  1033. mg_global_lock();
  1034. ret = (--(*addr));
  1035. mg_global_unlock();
  1036. #endif
  1037. return ret;
  1038. }
  1039. #if defined(USE_SERVER_STATS)
  1040. static int64_t
  1041. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1042. {
  1043. int64_t ret;
  1044. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1045. ret = InterlockedAdd64(addr, value);
  1046. #elif defined(__GNUC__) \
  1047. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1048. && !defined(NO_ATOMICS)
  1049. ret = __sync_add_and_fetch(addr, value);
  1050. #else
  1051. mg_global_lock();
  1052. *addr += value;
  1053. ret = (*addr);
  1054. mg_global_unlock();
  1055. #endif
  1056. return ret;
  1057. }
  1058. #endif
  1059. #if defined(GCC_DIAGNOSTIC)
  1060. /* Show no warning in case system functions are not used. */
  1061. #pragma GCC diagnostic pop
  1062. #endif /* defined(GCC_DIAGNOSTIC) */
  1063. #if defined(__clang__)
  1064. /* Show no warning in case system functions are not used. */
  1065. #pragma clang diagnostic pop
  1066. #endif
  1067. #if defined(USE_SERVER_STATS)
  1068. struct mg_memory_stat {
  1069. volatile int64_t totalMemUsed;
  1070. volatile int64_t maxMemUsed;
  1071. volatile int blockCount;
  1072. };
  1073. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1074. static void *
  1075. mg_malloc_ex(size_t size,
  1076. struct mg_context *ctx,
  1077. const char *file,
  1078. unsigned line)
  1079. {
  1080. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1081. void *memory = 0;
  1082. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1083. #if defined(MEMORY_DEBUGGING)
  1084. char mallocStr[256];
  1085. #else
  1086. (void)file;
  1087. (void)line;
  1088. #endif
  1089. if (data) {
  1090. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1091. if (mmem > mstat->maxMemUsed) {
  1092. /* could use atomic compare exchange, but this
  1093. * seems overkill for statistics data */
  1094. mstat->maxMemUsed = mmem;
  1095. }
  1096. mg_atomic_inc(&mstat->blockCount);
  1097. ((uintptr_t *)data)[0] = size;
  1098. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1099. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1100. }
  1101. #if defined(MEMORY_DEBUGGING)
  1102. sprintf(mallocStr,
  1103. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1104. memory,
  1105. (unsigned long)size,
  1106. (unsigned long)mstat->totalMemUsed,
  1107. (unsigned long)mstat->blockCount,
  1108. file,
  1109. line);
  1110. #if defined(_WIN32)
  1111. OutputDebugStringA(mallocStr);
  1112. #else
  1113. DEBUG_TRACE("%s", mallocStr);
  1114. #endif
  1115. #endif
  1116. return memory;
  1117. }
  1118. static void *
  1119. mg_calloc_ex(size_t count,
  1120. size_t size,
  1121. struct mg_context *ctx,
  1122. const char *file,
  1123. unsigned line)
  1124. {
  1125. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1126. if (data) {
  1127. memset(data, 0, size * count);
  1128. }
  1129. return data;
  1130. }
  1131. static void
  1132. mg_free_ex(void *memory, const char *file, unsigned line)
  1133. {
  1134. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1135. #if defined(MEMORY_DEBUGGING)
  1136. char mallocStr[256];
  1137. #else
  1138. (void)file;
  1139. (void)line;
  1140. #endif
  1141. if (memory) {
  1142. uintptr_t size = ((uintptr_t *)data)[0];
  1143. struct mg_memory_stat *mstat =
  1144. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1145. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1146. mg_atomic_dec(&mstat->blockCount);
  1147. #if defined(MEMORY_DEBUGGING)
  1148. sprintf(mallocStr,
  1149. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1150. memory,
  1151. (unsigned long)size,
  1152. (unsigned long)mstat->totalMemUsed,
  1153. (unsigned long)mstat->blockCount,
  1154. file,
  1155. line);
  1156. #if defined(_WIN32)
  1157. OutputDebugStringA(mallocStr);
  1158. #else
  1159. DEBUG_TRACE("%s", mallocStr);
  1160. #endif
  1161. #endif
  1162. free(data);
  1163. }
  1164. }
  1165. static void *
  1166. mg_realloc_ex(void *memory,
  1167. size_t newsize,
  1168. struct mg_context *ctx,
  1169. const char *file,
  1170. unsigned line)
  1171. {
  1172. void *data;
  1173. void *_realloc;
  1174. uintptr_t oldsize;
  1175. #if defined(MEMORY_DEBUGGING)
  1176. char mallocStr[256];
  1177. #else
  1178. (void)file;
  1179. (void)line;
  1180. #endif
  1181. if (newsize) {
  1182. if (memory) {
  1183. /* Reallocate existing block */
  1184. struct mg_memory_stat *mstat;
  1185. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1186. oldsize = ((uintptr_t *)data)[0];
  1187. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1188. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1189. if (_realloc) {
  1190. data = _realloc;
  1191. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1192. #if defined(MEMORY_DEBUGGING)
  1193. sprintf(mallocStr,
  1194. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1195. memory,
  1196. (unsigned long)oldsize,
  1197. (unsigned long)mstat->totalMemUsed,
  1198. (unsigned long)mstat->blockCount,
  1199. file,
  1200. line);
  1201. #if defined(_WIN32)
  1202. OutputDebugStringA(mallocStr);
  1203. #else
  1204. DEBUG_TRACE("%s", mallocStr);
  1205. #endif
  1206. #endif
  1207. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1208. #if defined(MEMORY_DEBUGGING)
  1209. sprintf(mallocStr,
  1210. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1211. memory,
  1212. (unsigned long)newsize,
  1213. (unsigned long)mstat->totalMemUsed,
  1214. (unsigned long)mstat->blockCount,
  1215. file,
  1216. line);
  1217. #if defined(_WIN32)
  1218. OutputDebugStringA(mallocStr);
  1219. #else
  1220. DEBUG_TRACE("%s", mallocStr);
  1221. #endif
  1222. #endif
  1223. *(uintptr_t *)data = newsize;
  1224. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1225. } else {
  1226. #if defined(MEMORY_DEBUGGING)
  1227. #if defined(_WIN32)
  1228. OutputDebugStringA("MEM: realloc failed\n");
  1229. #else
  1230. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1231. #endif
  1232. #endif
  1233. return _realloc;
  1234. }
  1235. } else {
  1236. /* Allocate new block */
  1237. data = mg_malloc_ex(newsize, ctx, file, line);
  1238. }
  1239. } else {
  1240. /* Free existing block */
  1241. data = 0;
  1242. mg_free_ex(memory, file, line);
  1243. }
  1244. return data;
  1245. }
  1246. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1247. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1248. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1249. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1250. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1251. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1252. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1253. #else /* USE_SERVER_STATS */
  1254. static __inline void *
  1255. mg_malloc(size_t a)
  1256. {
  1257. return malloc(a);
  1258. }
  1259. static __inline void *
  1260. mg_calloc(size_t a, size_t b)
  1261. {
  1262. return calloc(a, b);
  1263. }
  1264. static __inline void *
  1265. mg_realloc(void *a, size_t b)
  1266. {
  1267. return realloc(a, b);
  1268. }
  1269. static __inline void
  1270. mg_free(void *a)
  1271. {
  1272. free(a);
  1273. }
  1274. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1275. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1276. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1277. #define mg_free_ctx(a, c) mg_free(a)
  1278. #endif /* USE_SERVER_STATS */
  1279. static void mg_vsnprintf(const struct mg_connection *conn,
  1280. int *truncated,
  1281. char *buf,
  1282. size_t buflen,
  1283. const char *fmt,
  1284. va_list ap);
  1285. static void mg_snprintf(const struct mg_connection *conn,
  1286. int *truncated,
  1287. char *buf,
  1288. size_t buflen,
  1289. PRINTF_FORMAT_STRING(const char *fmt),
  1290. ...) PRINTF_ARGS(5, 6);
  1291. /* This following lines are just meant as a reminder to use the mg-functions
  1292. * for memory management */
  1293. #if defined(malloc)
  1294. #undef malloc
  1295. #endif
  1296. #if defined(calloc)
  1297. #undef calloc
  1298. #endif
  1299. #if defined(realloc)
  1300. #undef realloc
  1301. #endif
  1302. #if defined(free)
  1303. #undef free
  1304. #endif
  1305. #if defined(snprintf)
  1306. #undef snprintf
  1307. #endif
  1308. #if defined(vsnprintf)
  1309. #undef vsnprintf
  1310. #endif
  1311. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1312. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1313. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1314. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1315. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1316. #if defined(_WIN32)
  1317. /* vsnprintf must not be used in any system,
  1318. * but this define only works well for Windows. */
  1319. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1320. #endif
  1321. /* mg_init_library counter */
  1322. static int mg_init_library_called = 0;
  1323. #if !defined(NO_SSL)
  1324. static int mg_ssl_initialized = 0;
  1325. #endif
  1326. static pthread_key_t sTlsKey; /* Thread local storage index */
  1327. static int thread_idx_max = 0;
  1328. #if defined(MG_LEGACY_INTERFACE)
  1329. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1330. #endif
  1331. struct mg_workerTLS {
  1332. int is_master;
  1333. unsigned long thread_idx;
  1334. void *user_ptr;
  1335. #if defined(_WIN32)
  1336. HANDLE pthread_cond_helper_mutex;
  1337. struct mg_workerTLS *next_waiting_thread;
  1338. #endif
  1339. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1340. char txtbuf[4];
  1341. #endif
  1342. };
  1343. #if defined(GCC_DIAGNOSTIC)
  1344. /* Show no warning in case system functions are not used. */
  1345. #pragma GCC diagnostic push
  1346. #pragma GCC diagnostic ignored "-Wunused-function"
  1347. #endif /* defined(GCC_DIAGNOSTIC) */
  1348. #if defined(__clang__)
  1349. /* Show no warning in case system functions are not used. */
  1350. #pragma clang diagnostic push
  1351. #pragma clang diagnostic ignored "-Wunused-function"
  1352. #endif
  1353. /* Get a unique thread ID as unsigned long, independent from the data type
  1354. * of thread IDs defined by the operating system API.
  1355. * If two calls to mg_current_thread_id return the same value, they calls
  1356. * are done from the same thread. If they return different values, they are
  1357. * done from different threads. (Provided this function is used in the same
  1358. * process context and threads are not repeatedly created and deleted, but
  1359. * CivetWeb does not do that).
  1360. * This function must match the signature required for SSL id callbacks:
  1361. * CRYPTO_set_id_callback
  1362. */
  1363. FUNCTION_MAY_BE_UNUSED
  1364. static unsigned long
  1365. mg_current_thread_id(void)
  1366. {
  1367. #if defined(_WIN32)
  1368. return GetCurrentThreadId();
  1369. #else
  1370. #if defined(__clang__)
  1371. #pragma clang diagnostic push
  1372. #pragma clang diagnostic ignored "-Wunreachable-code"
  1373. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1374. * or not, so one of the two conditions will be unreachable by construction.
  1375. * Unfortunately the C standard does not define a way to check this at
  1376. * compile time, since the #if preprocessor conditions can not use the sizeof
  1377. * operator as an argument. */
  1378. #endif
  1379. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1380. /* This is the problematic case for CRYPTO_set_id_callback:
  1381. * The OS pthread_t can not be cast to unsigned long. */
  1382. struct mg_workerTLS *tls =
  1383. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1384. if (tls == NULL) {
  1385. /* SSL called from an unknown thread: Create some thread index.
  1386. */
  1387. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1388. tls->is_master = -2; /* -2 means "3rd party thread" */
  1389. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1390. pthread_setspecific(sTlsKey, tls);
  1391. }
  1392. return tls->thread_idx;
  1393. } else {
  1394. /* pthread_t may be any data type, so a simple cast to unsigned long
  1395. * can rise a warning/error, depending on the platform.
  1396. * Here memcpy is used as an anything-to-anything cast. */
  1397. unsigned long ret = 0;
  1398. pthread_t t = pthread_self();
  1399. memcpy(&ret, &t, sizeof(pthread_t));
  1400. return ret;
  1401. }
  1402. #if defined(__clang__)
  1403. #pragma clang diagnostic pop
  1404. #endif
  1405. #endif
  1406. }
  1407. FUNCTION_MAY_BE_UNUSED
  1408. static uint64_t
  1409. mg_get_current_time_ns(void)
  1410. {
  1411. struct timespec tsnow;
  1412. clock_gettime(CLOCK_REALTIME, &tsnow);
  1413. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1414. }
  1415. #if defined(GCC_DIAGNOSTIC)
  1416. /* Show no warning in case system functions are not used. */
  1417. #pragma GCC diagnostic pop
  1418. #endif /* defined(GCC_DIAGNOSTIC) */
  1419. #if defined(__clang__)
  1420. /* Show no warning in case system functions are not used. */
  1421. #pragma clang diagnostic pop
  1422. #endif
  1423. #if defined(NEED_DEBUG_TRACE_FUNC)
  1424. static void
  1425. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1426. {
  1427. va_list args;
  1428. uint64_t nsnow;
  1429. static uint64_t nslast;
  1430. struct timespec tsnow;
  1431. /* Get some operating system independent thread id */
  1432. unsigned long thread_id = mg_current_thread_id();
  1433. clock_gettime(CLOCK_REALTIME, &tsnow);
  1434. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1435. + ((uint64_t)tsnow.tv_nsec);
  1436. if (!nslast) {
  1437. nslast = nsnow;
  1438. }
  1439. flockfile(stdout);
  1440. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1441. (unsigned long)tsnow.tv_sec,
  1442. (unsigned long)tsnow.tv_nsec,
  1443. nsnow - nslast,
  1444. thread_id,
  1445. func,
  1446. line);
  1447. va_start(args, fmt);
  1448. vprintf(fmt, args);
  1449. va_end(args);
  1450. putchar('\n');
  1451. fflush(stdout);
  1452. funlockfile(stdout);
  1453. nslast = nsnow;
  1454. }
  1455. #endif /* NEED_DEBUG_TRACE_FUNC */
  1456. #define MD5_STATIC static
  1457. #include "md5.inl"
  1458. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1459. #if defined(NO_SOCKLEN_T)
  1460. typedef int socklen_t;
  1461. #endif /* NO_SOCKLEN_T */
  1462. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1463. #if !defined(MSG_NOSIGNAL)
  1464. #define MSG_NOSIGNAL (0)
  1465. #endif
  1466. #if defined(NO_SSL)
  1467. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1468. typedef struct SSL_CTX SSL_CTX;
  1469. #else
  1470. #if defined(NO_SSL_DL)
  1471. #include <openssl/bn.h>
  1472. #include <openssl/conf.h>
  1473. #include <openssl/crypto.h>
  1474. #include <openssl/dh.h>
  1475. #include <openssl/engine.h>
  1476. #include <openssl/err.h>
  1477. #include <openssl/opensslv.h>
  1478. #include <openssl/pem.h>
  1479. #include <openssl/ssl.h>
  1480. #include <openssl/tls1.h>
  1481. #include <openssl/x509.h>
  1482. #if defined(WOLFSSL_VERSION)
  1483. /* Additional defines for WolfSSL, see
  1484. * https://github.com/civetweb/civetweb/issues/583 */
  1485. #include "wolfssl_extras.inl"
  1486. #endif
  1487. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1488. /* If OpenSSL headers are included, automatically select the API version */
  1489. #if !defined(OPENSSL_API_1_1)
  1490. #define OPENSSL_API_1_1
  1491. #endif
  1492. #define OPENSSL_REMOVE_THREAD_STATE()
  1493. #else
  1494. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1495. #endif
  1496. #else
  1497. /* SSL loaded dynamically from DLL.
  1498. * I put the prototypes here to be independent from OpenSSL source
  1499. * installation. */
  1500. typedef struct ssl_st SSL;
  1501. typedef struct ssl_method_st SSL_METHOD;
  1502. typedef struct ssl_ctx_st SSL_CTX;
  1503. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1504. typedef struct x509_name X509_NAME;
  1505. typedef struct asn1_integer ASN1_INTEGER;
  1506. typedef struct bignum BIGNUM;
  1507. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1508. typedef struct evp_md EVP_MD;
  1509. typedef struct x509 X509;
  1510. #define SSL_CTRL_OPTIONS (32)
  1511. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1512. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1513. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1514. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1515. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1516. #define SSL_VERIFY_NONE (0)
  1517. #define SSL_VERIFY_PEER (1)
  1518. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1519. #define SSL_VERIFY_CLIENT_ONCE (4)
  1520. #define SSL_OP_ALL (0x80000BFFul)
  1521. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1522. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1523. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1524. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1525. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1526. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1527. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1528. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1529. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1530. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1531. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1532. #define SSL_CB_HANDSHAKE_START (0x10)
  1533. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1534. #define SSL_ERROR_NONE (0)
  1535. #define SSL_ERROR_SSL (1)
  1536. #define SSL_ERROR_WANT_READ (2)
  1537. #define SSL_ERROR_WANT_WRITE (3)
  1538. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1539. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1540. #define SSL_ERROR_ZERO_RETURN (6)
  1541. #define SSL_ERROR_WANT_CONNECT (7)
  1542. #define SSL_ERROR_WANT_ACCEPT (8)
  1543. #define TLSEXT_TYPE_server_name (0)
  1544. #define TLSEXT_NAMETYPE_host_name (0)
  1545. #define SSL_TLSEXT_ERR_OK (0)
  1546. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1547. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1548. #define SSL_TLSEXT_ERR_NOACK (3)
  1549. struct ssl_func {
  1550. const char *name; /* SSL function name */
  1551. void (*ptr)(void); /* Function pointer */
  1552. };
  1553. #if defined(OPENSSL_API_1_1)
  1554. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1555. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1556. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1557. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1558. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1559. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1560. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1561. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1562. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1563. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1564. #define OPENSSL_init_ssl \
  1565. (*(int (*)(uint64_t opts, \
  1566. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1567. .ptr)
  1568. #define SSL_CTX_use_PrivateKey_file \
  1569. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1570. #define SSL_CTX_use_certificate_file \
  1571. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1572. #define SSL_CTX_set_default_passwd_cb \
  1573. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1574. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1575. #define SSL_CTX_use_certificate_chain_file \
  1576. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1577. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1578. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1579. #define SSL_CTX_set_verify \
  1580. (*(void (*)(SSL_CTX *, \
  1581. int, \
  1582. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1583. .ptr)
  1584. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1585. #define SSL_CTX_load_verify_locations \
  1586. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1587. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1588. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1589. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1590. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1591. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1592. #define SSL_CIPHER_get_name \
  1593. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1594. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1595. #define SSL_CTX_set_session_id_context \
  1596. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1597. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1598. #define SSL_CTX_set_cipher_list \
  1599. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1600. #define SSL_CTX_set_options \
  1601. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1602. #define SSL_CTX_set_info_callback \
  1603. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1604. ssl_sw[32] \
  1605. .ptr)
  1606. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1607. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1608. #define SSL_CTX_callback_ctrl \
  1609. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1610. #define SSL_get_servername \
  1611. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1612. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1613. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1614. #define SSL_CTX_clear_options(ctx, op) \
  1615. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1616. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1617. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1618. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1619. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1620. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1621. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1622. SSL_CTX_callback_ctrl(ctx, \
  1623. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1624. (void (*)(void))cb)
  1625. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1626. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1627. #define SSL_set_tlsext_host_name(ctx, arg) \
  1628. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1629. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1630. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1631. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1632. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1633. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1634. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1635. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1636. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1637. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1638. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1639. #define X509_NAME_oneline \
  1640. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1641. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1642. #define EVP_get_digestbyname \
  1643. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1644. #define EVP_Digest \
  1645. (*(int (*)( \
  1646. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1647. crypto_sw[9] \
  1648. .ptr)
  1649. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1650. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1651. #define ASN1_INTEGER_to_BN \
  1652. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1653. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1654. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1655. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1656. #define OPENSSL_free(a) CRYPTO_free(a)
  1657. #define OPENSSL_REMOVE_THREAD_STATE()
  1658. /* init_ssl_ctx() function updates this array.
  1659. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1660. * of respective functions. The macros above (like SSL_connect()) are really
  1661. * just calling these functions indirectly via the pointer. */
  1662. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1663. {"SSL_accept", NULL},
  1664. {"SSL_connect", NULL},
  1665. {"SSL_read", NULL},
  1666. {"SSL_write", NULL},
  1667. {"SSL_get_error", NULL},
  1668. {"SSL_set_fd", NULL},
  1669. {"SSL_new", NULL},
  1670. {"SSL_CTX_new", NULL},
  1671. {"TLS_server_method", NULL},
  1672. {"OPENSSL_init_ssl", NULL},
  1673. {"SSL_CTX_use_PrivateKey_file", NULL},
  1674. {"SSL_CTX_use_certificate_file", NULL},
  1675. {"SSL_CTX_set_default_passwd_cb", NULL},
  1676. {"SSL_CTX_free", NULL},
  1677. {"SSL_CTX_use_certificate_chain_file", NULL},
  1678. {"TLS_client_method", NULL},
  1679. {"SSL_pending", NULL},
  1680. {"SSL_CTX_set_verify", NULL},
  1681. {"SSL_shutdown", NULL},
  1682. {"SSL_CTX_load_verify_locations", NULL},
  1683. {"SSL_CTX_set_default_verify_paths", NULL},
  1684. {"SSL_CTX_set_verify_depth", NULL},
  1685. {"SSL_get_peer_certificate", NULL},
  1686. {"SSL_get_version", NULL},
  1687. {"SSL_get_current_cipher", NULL},
  1688. {"SSL_CIPHER_get_name", NULL},
  1689. {"SSL_CTX_check_private_key", NULL},
  1690. {"SSL_CTX_set_session_id_context", NULL},
  1691. {"SSL_CTX_ctrl", NULL},
  1692. {"SSL_CTX_set_cipher_list", NULL},
  1693. {"SSL_CTX_set_options", NULL},
  1694. {"SSL_CTX_set_info_callback", NULL},
  1695. {"SSL_get_ex_data", NULL},
  1696. {"SSL_set_ex_data", NULL},
  1697. {"SSL_CTX_callback_ctrl", NULL},
  1698. {"SSL_get_servername", NULL},
  1699. {"SSL_set_SSL_CTX", NULL},
  1700. {"SSL_ctrl", NULL},
  1701. {NULL, NULL}};
  1702. /* Similar array as ssl_sw. These functions could be located in different
  1703. * lib. */
  1704. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1705. {"ERR_error_string", NULL},
  1706. {"CONF_modules_unload", NULL},
  1707. {"X509_free", NULL},
  1708. {"X509_get_subject_name", NULL},
  1709. {"X509_get_issuer_name", NULL},
  1710. {"X509_NAME_oneline", NULL},
  1711. {"X509_get_serialNumber", NULL},
  1712. {"EVP_get_digestbyname", NULL},
  1713. {"EVP_Digest", NULL},
  1714. {"i2d_X509", NULL},
  1715. {"BN_bn2hex", NULL},
  1716. {"ASN1_INTEGER_to_BN", NULL},
  1717. {"BN_free", NULL},
  1718. {"CRYPTO_free", NULL},
  1719. {"ERR_clear_error", NULL},
  1720. {NULL, NULL}};
  1721. #else
  1722. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1723. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1724. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1725. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1726. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1727. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1728. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1729. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1730. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1731. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1732. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1733. #define SSL_CTX_use_PrivateKey_file \
  1734. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1735. #define SSL_CTX_use_certificate_file \
  1736. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1737. #define SSL_CTX_set_default_passwd_cb \
  1738. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1739. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1740. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1741. #define SSL_CTX_use_certificate_chain_file \
  1742. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1743. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1744. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1745. #define SSL_CTX_set_verify \
  1746. (*(void (*)(SSL_CTX *, \
  1747. int, \
  1748. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1749. .ptr)
  1750. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1751. #define SSL_CTX_load_verify_locations \
  1752. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1753. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1754. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1755. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1756. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1757. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1758. #define SSL_CIPHER_get_name \
  1759. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1760. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1761. #define SSL_CTX_set_session_id_context \
  1762. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1763. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1764. #define SSL_CTX_set_cipher_list \
  1765. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1766. #define SSL_CTX_set_info_callback \
  1767. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1768. .ptr)
  1769. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1770. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1771. #define SSL_CTX_callback_ctrl \
  1772. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1773. #define SSL_get_servername \
  1774. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1775. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1776. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1777. #define SSL_CTX_set_options(ctx, op) \
  1778. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1779. #define SSL_CTX_clear_options(ctx, op) \
  1780. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1781. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1782. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1783. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1784. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1785. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1786. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1787. SSL_CTX_callback_ctrl(ctx, \
  1788. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1789. (void (*)(void))cb)
  1790. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1791. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1792. #define SSL_set_tlsext_host_name(ctx, arg) \
  1793. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1794. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1795. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1796. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1797. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1798. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1799. #define CRYPTO_set_locking_callback \
  1800. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1801. #define CRYPTO_set_id_callback \
  1802. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1803. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1804. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1805. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1806. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1807. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1808. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1809. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1810. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1811. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1812. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1813. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1814. #define X509_NAME_oneline \
  1815. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1816. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1817. #define i2c_ASN1_INTEGER \
  1818. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1819. #define EVP_get_digestbyname \
  1820. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1821. #define EVP_Digest \
  1822. (*(int (*)( \
  1823. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1824. crypto_sw[18] \
  1825. .ptr)
  1826. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1827. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1828. #define ASN1_INTEGER_to_BN \
  1829. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1830. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1831. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1832. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1833. #define OPENSSL_free(a) CRYPTO_free(a)
  1834. /* use here ERR_remove_state,
  1835. * while on some platforms function is not included into library due to
  1836. * deprication */
  1837. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1838. /* init_ssl_ctx() function updates this array.
  1839. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1840. * of respective functions. The macros above (like SSL_connect()) are really
  1841. * just calling these functions indirectly via the pointer. */
  1842. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1843. {"SSL_accept", NULL},
  1844. {"SSL_connect", NULL},
  1845. {"SSL_read", NULL},
  1846. {"SSL_write", NULL},
  1847. {"SSL_get_error", NULL},
  1848. {"SSL_set_fd", NULL},
  1849. {"SSL_new", NULL},
  1850. {"SSL_CTX_new", NULL},
  1851. {"SSLv23_server_method", NULL},
  1852. {"SSL_library_init", NULL},
  1853. {"SSL_CTX_use_PrivateKey_file", NULL},
  1854. {"SSL_CTX_use_certificate_file", NULL},
  1855. {"SSL_CTX_set_default_passwd_cb", NULL},
  1856. {"SSL_CTX_free", NULL},
  1857. {"SSL_load_error_strings", NULL},
  1858. {"SSL_CTX_use_certificate_chain_file", NULL},
  1859. {"SSLv23_client_method", NULL},
  1860. {"SSL_pending", NULL},
  1861. {"SSL_CTX_set_verify", NULL},
  1862. {"SSL_shutdown", NULL},
  1863. {"SSL_CTX_load_verify_locations", NULL},
  1864. {"SSL_CTX_set_default_verify_paths", NULL},
  1865. {"SSL_CTX_set_verify_depth", NULL},
  1866. {"SSL_get_peer_certificate", NULL},
  1867. {"SSL_get_version", NULL},
  1868. {"SSL_get_current_cipher", NULL},
  1869. {"SSL_CIPHER_get_name", NULL},
  1870. {"SSL_CTX_check_private_key", NULL},
  1871. {"SSL_CTX_set_session_id_context", NULL},
  1872. {"SSL_CTX_ctrl", NULL},
  1873. {"SSL_CTX_set_cipher_list", NULL},
  1874. {"SSL_CTX_set_info_callback", NULL},
  1875. {"SSL_get_ex_data", NULL},
  1876. {"SSL_set_ex_data", NULL},
  1877. {"SSL_CTX_callback_ctrl", NULL},
  1878. {"SSL_get_servername", NULL},
  1879. {"SSL_set_SSL_CTX", NULL},
  1880. {"SSL_ctrl", NULL},
  1881. {NULL, NULL}};
  1882. /* Similar array as ssl_sw. These functions could be located in different
  1883. * lib. */
  1884. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1885. {"CRYPTO_set_locking_callback", NULL},
  1886. {"CRYPTO_set_id_callback", NULL},
  1887. {"ERR_get_error", NULL},
  1888. {"ERR_error_string", NULL},
  1889. {"ERR_remove_state", NULL},
  1890. {"ERR_free_strings", NULL},
  1891. {"ENGINE_cleanup", NULL},
  1892. {"CONF_modules_unload", NULL},
  1893. {"CRYPTO_cleanup_all_ex_data", NULL},
  1894. {"EVP_cleanup", NULL},
  1895. {"X509_free", NULL},
  1896. {"X509_get_subject_name", NULL},
  1897. {"X509_get_issuer_name", NULL},
  1898. {"X509_NAME_oneline", NULL},
  1899. {"X509_get_serialNumber", NULL},
  1900. {"i2c_ASN1_INTEGER", NULL},
  1901. {"EVP_get_digestbyname", NULL},
  1902. {"EVP_Digest", NULL},
  1903. {"i2d_X509", NULL},
  1904. {"BN_bn2hex", NULL},
  1905. {"ASN1_INTEGER_to_BN", NULL},
  1906. {"BN_free", NULL},
  1907. {"CRYPTO_free", NULL},
  1908. {"ERR_clear_error", NULL},
  1909. {NULL, NULL}};
  1910. #endif /* OPENSSL_API_1_1 */
  1911. #endif /* NO_SSL_DL */
  1912. #endif /* NO_SSL */
  1913. #if !defined(NO_CACHING)
  1914. static const char month_names[][4] = {"Jan",
  1915. "Feb",
  1916. "Mar",
  1917. "Apr",
  1918. "May",
  1919. "Jun",
  1920. "Jul",
  1921. "Aug",
  1922. "Sep",
  1923. "Oct",
  1924. "Nov",
  1925. "Dec"};
  1926. #endif /* !NO_CACHING */
  1927. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1928. * the
  1929. * union u. */
  1930. union usa {
  1931. struct sockaddr sa;
  1932. struct sockaddr_in sin;
  1933. #if defined(USE_IPV6)
  1934. struct sockaddr_in6 sin6;
  1935. #endif
  1936. };
  1937. /* Describes a string (chunk of memory). */
  1938. struct vec {
  1939. const char *ptr;
  1940. size_t len;
  1941. };
  1942. struct mg_file_stat {
  1943. /* File properties filled by mg_stat: */
  1944. uint64_t size;
  1945. time_t last_modified;
  1946. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1947. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1948. * case we need a "Content-Eencoding: gzip" header */
  1949. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1950. };
  1951. struct mg_file_in_memory {
  1952. char *p;
  1953. uint32_t pos;
  1954. char mode;
  1955. };
  1956. struct mg_file_access {
  1957. /* File properties filled by mg_fopen: */
  1958. FILE *fp;
  1959. #if defined(MG_USE_OPEN_FILE)
  1960. /* TODO (low): Remove obsolete "file in memory" implementation.
  1961. * In an "early 2017" discussion at Google groups
  1962. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1963. * we decided to get rid of this feature (after some fade-out
  1964. * phase). */
  1965. const char *membuf;
  1966. #endif
  1967. };
  1968. struct mg_file {
  1969. struct mg_file_stat stat;
  1970. struct mg_file_access access;
  1971. };
  1972. #if defined(MG_USE_OPEN_FILE)
  1973. #define STRUCT_FILE_INITIALIZER \
  1974. { \
  1975. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1976. { \
  1977. (FILE *)NULL, (const char *)NULL \
  1978. } \
  1979. }
  1980. #else
  1981. #define STRUCT_FILE_INITIALIZER \
  1982. { \
  1983. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1984. { \
  1985. (FILE *)NULL \
  1986. } \
  1987. }
  1988. #endif
  1989. /* Describes listening socket, or socket which was accept()-ed by the master
  1990. * thread and queued for future handling by the worker thread. */
  1991. struct socket {
  1992. SOCKET sock; /* Listening socket */
  1993. union usa lsa; /* Local socket address */
  1994. union usa rsa; /* Remote socket address */
  1995. unsigned char is_ssl; /* Is port SSL-ed */
  1996. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1997. * port */
  1998. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1999. };
  2000. /* Enum const for all options must be in sync with
  2001. * static struct mg_option config_options[]
  2002. * This is tested in the unit test (test/private.c)
  2003. * "Private Config Options"
  2004. */
  2005. enum {
  2006. /* Once for each server */
  2007. LISTENING_PORTS,
  2008. NUM_THREADS,
  2009. RUN_AS_USER,
  2010. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2011. * socket option typedef TCP_NODELAY. */
  2012. MAX_REQUEST_SIZE,
  2013. LINGER_TIMEOUT,
  2014. MAX_CONNECTIONS,
  2015. #if defined(__linux__)
  2016. ALLOW_SENDFILE_CALL,
  2017. #endif
  2018. #if defined(_WIN32)
  2019. CASE_SENSITIVE_FILES,
  2020. #endif
  2021. THROTTLE,
  2022. ACCESS_LOG_FILE,
  2023. ERROR_LOG_FILE,
  2024. ENABLE_KEEP_ALIVE,
  2025. REQUEST_TIMEOUT,
  2026. KEEP_ALIVE_TIMEOUT,
  2027. #if defined(USE_WEBSOCKET)
  2028. WEBSOCKET_TIMEOUT,
  2029. ENABLE_WEBSOCKET_PING_PONG,
  2030. #endif
  2031. DECODE_URL,
  2032. #if defined(USE_LUA)
  2033. LUA_BACKGROUND_SCRIPT,
  2034. LUA_BACKGROUND_SCRIPT_PARAMS,
  2035. #endif
  2036. #if defined(USE_TIMERS)
  2037. CGI_TIMEOUT,
  2038. #endif
  2039. /* Once for each domain */
  2040. DOCUMENT_ROOT,
  2041. CGI_EXTENSIONS,
  2042. CGI_ENVIRONMENT,
  2043. PUT_DELETE_PASSWORDS_FILE,
  2044. CGI_INTERPRETER,
  2045. PROTECT_URI,
  2046. AUTHENTICATION_DOMAIN,
  2047. ENABLE_AUTH_DOMAIN_CHECK,
  2048. SSI_EXTENSIONS,
  2049. ENABLE_DIRECTORY_LISTING,
  2050. GLOBAL_PASSWORDS_FILE,
  2051. INDEX_FILES,
  2052. ACCESS_CONTROL_LIST,
  2053. EXTRA_MIME_TYPES,
  2054. SSL_CERTIFICATE,
  2055. SSL_CERTIFICATE_CHAIN,
  2056. URL_REWRITE_PATTERN,
  2057. HIDE_FILES,
  2058. SSL_DO_VERIFY_PEER,
  2059. SSL_CA_PATH,
  2060. SSL_CA_FILE,
  2061. SSL_VERIFY_DEPTH,
  2062. SSL_DEFAULT_VERIFY_PATHS,
  2063. SSL_CIPHER_LIST,
  2064. SSL_PROTOCOL_VERSION,
  2065. SSL_SHORT_TRUST,
  2066. #if defined(USE_LUA)
  2067. LUA_PRELOAD_FILE,
  2068. LUA_SCRIPT_EXTENSIONS,
  2069. LUA_SERVER_PAGE_EXTENSIONS,
  2070. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2071. LUA_DEBUG_PARAMS,
  2072. #endif
  2073. #endif
  2074. #if defined(USE_DUKTAPE)
  2075. DUKTAPE_SCRIPT_EXTENSIONS,
  2076. #endif
  2077. #if defined(USE_WEBSOCKET)
  2078. WEBSOCKET_ROOT,
  2079. #endif
  2080. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2081. LUA_WEBSOCKET_EXTENSIONS,
  2082. #endif
  2083. ACCESS_CONTROL_ALLOW_ORIGIN,
  2084. ACCESS_CONTROL_ALLOW_METHODS,
  2085. ACCESS_CONTROL_ALLOW_HEADERS,
  2086. ERROR_PAGES,
  2087. #if !defined(NO_CACHING)
  2088. STATIC_FILE_MAX_AGE,
  2089. STATIC_FILE_CACHE_CONTROL,
  2090. #endif
  2091. #if !defined(NO_SSL)
  2092. STRICT_HTTPS_MAX_AGE,
  2093. #endif
  2094. ADDITIONAL_HEADER,
  2095. ALLOW_INDEX_SCRIPT_SUB_RES,
  2096. #if defined(DAEMONIZE)
  2097. ENABLE_DAEMONIZE,
  2098. #endif
  2099. NUM_OPTIONS
  2100. };
  2101. /* Config option name, config types, default value.
  2102. * Must be in the same order as the enum const above.
  2103. */
  2104. static const struct mg_option config_options[] = {
  2105. /* Once for each server */
  2106. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2107. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2108. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2109. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2110. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2111. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2112. {"max_connections", MG_CONFIG_TYPE_NUMBER, "100"},
  2113. #if defined(__linux__)
  2114. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2115. #endif
  2116. #if defined(_WIN32)
  2117. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2118. #endif
  2119. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2120. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2121. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2122. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2123. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2124. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2125. #if defined(USE_WEBSOCKET)
  2126. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2127. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2128. #endif
  2129. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2130. #if defined(USE_LUA)
  2131. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2132. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2133. #endif
  2134. #if defined(USE_TIMERS)
  2135. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2136. #endif
  2137. /* Once for each domain */
  2138. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2139. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2140. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2141. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2142. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2143. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2144. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2145. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2146. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2147. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2148. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2149. {"index_files",
  2150. MG_CONFIG_TYPE_STRING_LIST,
  2151. #if defined(USE_LUA)
  2152. "index.xhtml,index.html,index.htm,"
  2153. "index.lp,index.lsp,index.lua,index.cgi,"
  2154. "index.shtml,index.php"},
  2155. #else
  2156. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2157. #endif
  2158. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2159. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2160. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2161. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2162. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2163. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2164. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2165. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2166. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2167. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2168. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2169. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2170. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2171. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2172. #if defined(USE_LUA)
  2173. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2174. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2175. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2176. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2177. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2178. #endif
  2179. #endif
  2180. #if defined(USE_DUKTAPE)
  2181. /* The support for duktape is still in alpha version state.
  2182. * The name of this config option might change. */
  2183. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2184. #endif
  2185. #if defined(USE_WEBSOCKET)
  2186. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2187. #endif
  2188. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2189. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2190. #endif
  2191. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2192. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2193. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2194. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2195. #if !defined(NO_CACHING)
  2196. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2197. {"static_file_cache_control", MG_CONFIG_TYPE_STRING, NULL},
  2198. #endif
  2199. #if !defined(NO_SSL)
  2200. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2201. #endif
  2202. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2203. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2204. #if defined(DAEMONIZE)
  2205. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2206. #endif
  2207. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2208. /* Check if the config_options and the corresponding enum have compatible
  2209. * sizes. */
  2210. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2211. == (NUM_OPTIONS + 1),
  2212. "config_options and enum not sync");
  2213. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2214. struct mg_handler_info {
  2215. /* Name/Pattern of the URI. */
  2216. char *uri;
  2217. size_t uri_len;
  2218. /* handler type */
  2219. int handler_type;
  2220. /* Handler for http/https or authorization requests. */
  2221. mg_request_handler handler;
  2222. unsigned int refcount;
  2223. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2224. pthread_cond_t
  2225. refcount_cond; /* Signaled when handler refcount is decremented */
  2226. /* Handler for ws/wss (websocket) requests. */
  2227. mg_websocket_connect_handler connect_handler;
  2228. mg_websocket_ready_handler ready_handler;
  2229. mg_websocket_data_handler data_handler;
  2230. mg_websocket_close_handler close_handler;
  2231. /* accepted subprotocols for ws/wss requests. */
  2232. struct mg_websocket_subprotocols *subprotocols;
  2233. /* Handler for authorization requests */
  2234. mg_authorization_handler auth_handler;
  2235. /* User supplied argument for the handler function. */
  2236. void *cbdata;
  2237. /* next handler in a linked list */
  2238. struct mg_handler_info *next;
  2239. };
  2240. enum {
  2241. CONTEXT_INVALID,
  2242. CONTEXT_SERVER,
  2243. CONTEXT_HTTP_CLIENT,
  2244. CONTEXT_WS_CLIENT
  2245. };
  2246. struct mg_domain_context {
  2247. SSL_CTX *ssl_ctx; /* SSL context */
  2248. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2249. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2250. /* Server nonce */
  2251. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2252. unsigned long nonce_count; /* Used nonces, used for authentication */
  2253. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2254. /* linked list of shared lua websockets */
  2255. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2256. #endif
  2257. /* Linked list of domains */
  2258. struct mg_domain_context *next;
  2259. };
  2260. struct mg_context {
  2261. /* Part 1 - Physical context:
  2262. * This holds threads, ports, timeouts, ...
  2263. * set for the entire server, independent from the
  2264. * addressed hostname.
  2265. */
  2266. /* Connection related */
  2267. int context_type; /* See CONTEXT_* above */
  2268. struct socket *listening_sockets;
  2269. struct mg_pollfd *listening_socket_fds;
  2270. unsigned int num_listening_sockets;
  2271. struct mg_connection *worker_connections; /* The connection struct, pre-
  2272. * allocated for each worker */
  2273. #if defined(USE_SERVER_STATS)
  2274. int active_connections;
  2275. int max_connections;
  2276. int64_t total_connections;
  2277. int64_t total_requests;
  2278. int64_t total_data_read;
  2279. int64_t total_data_written;
  2280. #endif
  2281. /* Thread related */
  2282. volatile int stop_flag; /* Should we stop event loop */
  2283. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2284. pthread_t masterthreadid; /* The master thread ID */
  2285. unsigned int
  2286. cfg_worker_threads; /* The number of configured worker threads. */
  2287. pthread_t *worker_threadids; /* The worker thread IDs */
  2288. /* Connection to thread dispatching */
  2289. #if defined(ALTERNATIVE_QUEUE)
  2290. struct socket *client_socks;
  2291. void **client_wait_events;
  2292. #else
  2293. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2294. volatile int sq_head; /* Head of the socket queue */
  2295. volatile int sq_tail; /* Tail of the socket queue */
  2296. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2297. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2298. #endif
  2299. /* Memory related */
  2300. unsigned int max_request_size; /* The max request size */
  2301. #if defined(USE_SERVER_STATS)
  2302. struct mg_memory_stat ctx_memory;
  2303. #endif
  2304. /* Operating system related */
  2305. char *systemName; /* What operating system is running */
  2306. time_t start_time; /* Server start time, used for authentication
  2307. * and for diagnstics. */
  2308. #if defined(USE_TIMERS)
  2309. struct ttimers *timers;
  2310. #endif
  2311. /* Lua specific: Background operations and shared websockets */
  2312. #if defined(USE_LUA)
  2313. void *lua_background_state;
  2314. #endif
  2315. /* Server nonce */
  2316. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2317. /* Server callbacks */
  2318. struct mg_callbacks callbacks; /* User-defined callback function */
  2319. void *user_data; /* User-defined data */
  2320. /* Part 2 - Logical domain:
  2321. * This holds hostname, TLS certificate, document root, ...
  2322. * set for a domain hosted at the server.
  2323. * There may be multiple domains hosted at one physical server.
  2324. * The default domain "dd" is the first element of a list of
  2325. * domains.
  2326. */
  2327. struct mg_domain_context dd; /* default domain */
  2328. };
  2329. #if defined(USE_SERVER_STATS)
  2330. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2331. static struct mg_memory_stat *
  2332. get_memory_stat(struct mg_context *ctx)
  2333. {
  2334. if (ctx) {
  2335. return &(ctx->ctx_memory);
  2336. }
  2337. return &mg_common_memory;
  2338. }
  2339. #endif
  2340. enum {
  2341. CONNECTION_TYPE_INVALID,
  2342. CONNECTION_TYPE_REQUEST,
  2343. CONNECTION_TYPE_RESPONSE
  2344. };
  2345. struct mg_connection {
  2346. int connection_type; /* see CONNECTION_TYPE_* above */
  2347. struct mg_request_info request_info;
  2348. struct mg_response_info response_info;
  2349. struct mg_context *phys_ctx;
  2350. struct mg_domain_context *dom_ctx;
  2351. #if defined(USE_SERVER_STATS)
  2352. int conn_state; /* 0 = undef, numerical value may change in different
  2353. * versions. For the current definition, see
  2354. * mg_get_connection_info_impl */
  2355. #endif
  2356. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2357. SSL *ssl; /* SSL descriptor */
  2358. struct socket client; /* Connected client */
  2359. time_t conn_birth_time; /* Time (wall clock) when connection was
  2360. * established */
  2361. struct timespec req_time; /* Time (since system start) when the request
  2362. * was received */
  2363. int64_t num_bytes_sent; /* Total bytes sent to client */
  2364. int64_t content_len; /* How many bytes of content can be read
  2365. * !is_chunked: Content-Length header value
  2366. * or -1 (until connection closed,
  2367. * not allowed for a request)
  2368. * is_chunked: >= 0, appended gradually
  2369. */
  2370. int64_t consumed_content; /* How many bytes of content have been read */
  2371. int is_chunked; /* Transfer-Encoding is chunked:
  2372. * 0 = not chunked,
  2373. * 1 = chunked, not yet, or some data read,
  2374. * 2 = chunked, has error,
  2375. * 3 = chunked, all data read except trailer,
  2376. * 4 = chunked, all data read
  2377. */
  2378. char *buf; /* Buffer for received data */
  2379. char *path_info; /* PATH_INFO part of the URL */
  2380. int must_close; /* 1 if connection must be closed */
  2381. int accept_gzip; /* 1 if gzip encoding is accepted */
  2382. int in_error_handler; /* 1 if in handler for user defined error
  2383. * pages */
  2384. #if defined(USE_WEBSOCKET)
  2385. int in_websocket_handling; /* 1 if in read_websocket */
  2386. #endif
  2387. int handled_requests; /* Number of requests handled by this connection
  2388. */
  2389. int buf_size; /* Buffer size */
  2390. int request_len; /* Size of the request + headers in a buffer */
  2391. int data_len; /* Total size of data in a buffer */
  2392. int status_code; /* HTTP reply status code, e.g. 200 */
  2393. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2394. * throttle */
  2395. time_t last_throttle_time; /* Last time throttled data was sent */
  2396. int last_throttle_bytes; /* Bytes sent this second */
  2397. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2398. * atomic transmissions for websockets */
  2399. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2400. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2401. #endif
  2402. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2403. * for quick access */
  2404. };
  2405. /* Directory entry */
  2406. struct de {
  2407. struct mg_connection *conn;
  2408. char *file_name;
  2409. struct mg_file_stat file;
  2410. };
  2411. #if defined(USE_WEBSOCKET)
  2412. static int is_websocket_protocol(const struct mg_connection *conn);
  2413. #else
  2414. #define is_websocket_protocol(conn) (0)
  2415. #endif
  2416. #define mg_cry_internal(conn, fmt, ...) \
  2417. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2418. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2419. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2420. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2421. struct mg_context *ctx,
  2422. const char *func,
  2423. unsigned line,
  2424. const char *fmt,
  2425. ...) PRINTF_ARGS(5, 6);
  2426. #if !defined(NO_THREAD_NAME)
  2427. #if defined(_WIN32) && defined(_MSC_VER)
  2428. /* Set the thread name for debugging purposes in Visual Studio
  2429. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2430. */
  2431. #pragma pack(push, 8)
  2432. typedef struct tagTHREADNAME_INFO {
  2433. DWORD dwType; /* Must be 0x1000. */
  2434. LPCSTR szName; /* Pointer to name (in user addr space). */
  2435. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2436. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2437. } THREADNAME_INFO;
  2438. #pragma pack(pop)
  2439. #elif defined(__linux__)
  2440. #include <sys/prctl.h>
  2441. #include <sys/sendfile.h>
  2442. #if defined(ALTERNATIVE_QUEUE)
  2443. #include <sys/eventfd.h>
  2444. #endif /* ALTERNATIVE_QUEUE */
  2445. #if defined(ALTERNATIVE_QUEUE)
  2446. static void *
  2447. event_create(void)
  2448. {
  2449. int evhdl = eventfd(0, EFD_CLOEXEC);
  2450. int *ret;
  2451. if (evhdl == -1) {
  2452. /* Linux uses -1 on error, Windows NULL. */
  2453. /* However, Linux does not return 0 on success either. */
  2454. return 0;
  2455. }
  2456. ret = (int *)mg_malloc(sizeof(int));
  2457. if (ret) {
  2458. *ret = evhdl;
  2459. } else {
  2460. (void)close(evhdl);
  2461. }
  2462. return (void *)ret;
  2463. }
  2464. static int
  2465. event_wait(void *eventhdl)
  2466. {
  2467. uint64_t u;
  2468. int evhdl, s;
  2469. if (!eventhdl) {
  2470. /* error */
  2471. return 0;
  2472. }
  2473. evhdl = *(int *)eventhdl;
  2474. s = (int)read(evhdl, &u, sizeof(u));
  2475. if (s != sizeof(u)) {
  2476. /* error */
  2477. return 0;
  2478. }
  2479. (void)u; /* the value is not required */
  2480. return 1;
  2481. }
  2482. static int
  2483. event_signal(void *eventhdl)
  2484. {
  2485. uint64_t u = 1;
  2486. int evhdl, s;
  2487. if (!eventhdl) {
  2488. /* error */
  2489. return 0;
  2490. }
  2491. evhdl = *(int *)eventhdl;
  2492. s = (int)write(evhdl, &u, sizeof(u));
  2493. if (s != sizeof(u)) {
  2494. /* error */
  2495. return 0;
  2496. }
  2497. return 1;
  2498. }
  2499. static void
  2500. event_destroy(void *eventhdl)
  2501. {
  2502. int evhdl;
  2503. if (!eventhdl) {
  2504. /* error */
  2505. return;
  2506. }
  2507. evhdl = *(int *)eventhdl;
  2508. close(evhdl);
  2509. mg_free(eventhdl);
  2510. }
  2511. #endif
  2512. #endif
  2513. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2514. struct posix_event {
  2515. pthread_mutex_t mutex;
  2516. pthread_cond_t cond;
  2517. int signaled;
  2518. };
  2519. static void *
  2520. event_create(void)
  2521. {
  2522. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2523. if (ret == 0) {
  2524. /* out of memory */
  2525. return 0;
  2526. }
  2527. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2528. /* pthread mutex not available */
  2529. mg_free(ret);
  2530. return 0;
  2531. }
  2532. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2533. /* pthread cond not available */
  2534. pthread_mutex_destroy(&(ret->mutex));
  2535. mg_free(ret);
  2536. return 0;
  2537. }
  2538. ret->signaled = 0;
  2539. return (void *)ret;
  2540. }
  2541. static int
  2542. event_wait(void *eventhdl)
  2543. {
  2544. struct posix_event *ev = (struct posix_event *)eventhdl;
  2545. pthread_mutex_lock(&(ev->mutex));
  2546. while (!ev->signaled) {
  2547. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2548. }
  2549. ev->signaled = 0;
  2550. pthread_mutex_unlock(&(ev->mutex));
  2551. return 1;
  2552. }
  2553. static int
  2554. event_signal(void *eventhdl)
  2555. {
  2556. struct posix_event *ev = (struct posix_event *)eventhdl;
  2557. pthread_mutex_lock(&(ev->mutex));
  2558. pthread_cond_signal(&(ev->cond));
  2559. ev->signaled = 1;
  2560. pthread_mutex_unlock(&(ev->mutex));
  2561. return 1;
  2562. }
  2563. static void
  2564. event_destroy(void *eventhdl)
  2565. {
  2566. struct posix_event *ev = (struct posix_event *)eventhdl;
  2567. pthread_cond_destroy(&(ev->cond));
  2568. pthread_mutex_destroy(&(ev->mutex));
  2569. mg_free(ev);
  2570. }
  2571. #endif
  2572. static void
  2573. mg_set_thread_name(const char *name)
  2574. {
  2575. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2576. mg_snprintf(
  2577. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2578. #if defined(_WIN32)
  2579. #if defined(_MSC_VER)
  2580. /* Windows and Visual Studio Compiler */
  2581. __try {
  2582. THREADNAME_INFO info;
  2583. info.dwType = 0x1000;
  2584. info.szName = threadName;
  2585. info.dwThreadID = ~0U;
  2586. info.dwFlags = 0;
  2587. RaiseException(0x406D1388,
  2588. 0,
  2589. sizeof(info) / sizeof(ULONG_PTR),
  2590. (ULONG_PTR *)&info);
  2591. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2592. }
  2593. #elif defined(__MINGW32__)
  2594. /* No option known to set thread name for MinGW */
  2595. #endif
  2596. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2597. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2598. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2599. #if defined(__MACH__)
  2600. /* OS X only current thread name can be changed */
  2601. (void)pthread_setname_np(threadName);
  2602. #else
  2603. (void)pthread_setname_np(pthread_self(), threadName);
  2604. #endif
  2605. #elif defined(__linux__)
  2606. /* on linux we can use the old prctl function */
  2607. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2608. #endif
  2609. }
  2610. #else /* !defined(NO_THREAD_NAME) */
  2611. void
  2612. mg_set_thread_name(const char *threadName)
  2613. {
  2614. }
  2615. #endif
  2616. #if defined(MG_LEGACY_INTERFACE)
  2617. const char **
  2618. mg_get_valid_option_names(void)
  2619. {
  2620. /* This function is deprecated. Use mg_get_valid_options instead. */
  2621. static const char
  2622. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2623. int i;
  2624. for (i = 0; config_options[i].name != NULL; i++) {
  2625. data[i * 2] = config_options[i].name;
  2626. data[i * 2 + 1] = config_options[i].default_value;
  2627. }
  2628. return data;
  2629. }
  2630. #endif
  2631. const struct mg_option *
  2632. mg_get_valid_options(void)
  2633. {
  2634. return config_options;
  2635. }
  2636. /* Do not open file (used in is_file_in_memory) */
  2637. #define MG_FOPEN_MODE_NONE (0)
  2638. /* Open file for read only access */
  2639. #define MG_FOPEN_MODE_READ (1)
  2640. /* Open file for writing, create and overwrite */
  2641. #define MG_FOPEN_MODE_WRITE (2)
  2642. /* Open file for writing, create and append */
  2643. #define MG_FOPEN_MODE_APPEND (4)
  2644. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2645. * output filep and return 1, otherwise return 0 and don't modify anything.
  2646. */
  2647. static int
  2648. open_file_in_memory(const struct mg_connection *conn,
  2649. const char *path,
  2650. struct mg_file *filep,
  2651. int mode)
  2652. {
  2653. #if defined(MG_USE_OPEN_FILE)
  2654. size_t size = 0;
  2655. const char *buf = NULL;
  2656. if (!conn) {
  2657. return 0;
  2658. }
  2659. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2660. return 0;
  2661. }
  2662. if (conn->phys_ctx->callbacks.open_file) {
  2663. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2664. if (buf != NULL) {
  2665. if (filep == NULL) {
  2666. /* This is a file in memory, but we cannot store the
  2667. * properties
  2668. * now.
  2669. * Called from "is_file_in_memory" function. */
  2670. return 1;
  2671. }
  2672. /* NOTE: override filep->size only on success. Otherwise, it
  2673. * might
  2674. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2675. filep->access.membuf = buf;
  2676. filep->access.fp = NULL;
  2677. /* Size was set by the callback */
  2678. filep->stat.size = size;
  2679. /* Assume the data may change during runtime by setting
  2680. * last_modified = now */
  2681. filep->stat.last_modified = time(NULL);
  2682. filep->stat.is_directory = 0;
  2683. filep->stat.is_gzipped = 0;
  2684. }
  2685. }
  2686. return (buf != NULL);
  2687. #else
  2688. (void)conn;
  2689. (void)path;
  2690. (void)filep;
  2691. (void)mode;
  2692. return 0;
  2693. #endif
  2694. }
  2695. static int
  2696. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2697. {
  2698. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2699. }
  2700. static int
  2701. is_file_opened(const struct mg_file_access *fileacc)
  2702. {
  2703. if (!fileacc) {
  2704. return 0;
  2705. }
  2706. #if defined(MG_USE_OPEN_FILE)
  2707. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2708. #else
  2709. return (fileacc->fp != NULL);
  2710. #endif
  2711. }
  2712. #if !defined(NO_FILESYSTEMS)
  2713. static int mg_stat(const struct mg_connection *conn,
  2714. const char *path,
  2715. struct mg_file_stat *filep);
  2716. /* mg_fopen will open a file either in memory or on the disk.
  2717. * The input parameter path is a string in UTF-8 encoding.
  2718. * The input parameter mode is MG_FOPEN_MODE_*
  2719. * On success, either fp or membuf will be set in the output
  2720. * struct file. All status members will also be set.
  2721. * The function returns 1 on success, 0 on error. */
  2722. static int
  2723. mg_fopen(const struct mg_connection *conn,
  2724. const char *path,
  2725. int mode,
  2726. struct mg_file *filep)
  2727. {
  2728. int found;
  2729. if (!filep) {
  2730. return 0;
  2731. }
  2732. filep->access.fp = NULL;
  2733. #if defined(MG_USE_OPEN_FILE)
  2734. filep->access.membuf = NULL;
  2735. #endif
  2736. if (!is_file_in_memory(conn, path)) {
  2737. /* filep is initialized in mg_stat: all fields with memset to,
  2738. * some fields like size and modification date with values */
  2739. found = mg_stat(conn, path, &(filep->stat));
  2740. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2741. /* file does not exist and will not be created */
  2742. return 0;
  2743. }
  2744. #if defined(_WIN32)
  2745. {
  2746. wchar_t wbuf[W_PATH_MAX];
  2747. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2748. switch (mode) {
  2749. case MG_FOPEN_MODE_READ:
  2750. filep->access.fp = _wfopen(wbuf, L"rb");
  2751. break;
  2752. case MG_FOPEN_MODE_WRITE:
  2753. filep->access.fp = _wfopen(wbuf, L"wb");
  2754. break;
  2755. case MG_FOPEN_MODE_APPEND:
  2756. filep->access.fp = _wfopen(wbuf, L"ab");
  2757. break;
  2758. }
  2759. }
  2760. #else
  2761. /* Linux et al already use unicode. No need to convert. */
  2762. switch (mode) {
  2763. case MG_FOPEN_MODE_READ:
  2764. filep->access.fp = fopen(path, "r");
  2765. break;
  2766. case MG_FOPEN_MODE_WRITE:
  2767. filep->access.fp = fopen(path, "w");
  2768. break;
  2769. case MG_FOPEN_MODE_APPEND:
  2770. filep->access.fp = fopen(path, "a");
  2771. break;
  2772. }
  2773. #endif
  2774. if (!found) {
  2775. /* File did not exist before fopen was called.
  2776. * Maybe it has been created now. Get stat info
  2777. * like creation time now. */
  2778. found = mg_stat(conn, path, &(filep->stat));
  2779. (void)found;
  2780. }
  2781. /* file is on disk */
  2782. return (filep->access.fp != NULL);
  2783. } else {
  2784. #if defined(MG_USE_OPEN_FILE)
  2785. /* is_file_in_memory returned true */
  2786. if (open_file_in_memory(conn, path, filep, mode)) {
  2787. /* file is in memory */
  2788. return (filep->access.membuf != NULL);
  2789. }
  2790. #endif
  2791. }
  2792. /* Open failed */
  2793. return 0;
  2794. }
  2795. /* return 0 on success, just like fclose */
  2796. static int
  2797. mg_fclose(struct mg_file_access *fileacc)
  2798. {
  2799. int ret = -1;
  2800. if (fileacc != NULL) {
  2801. if (fileacc->fp != NULL) {
  2802. ret = fclose(fileacc->fp);
  2803. #if defined(MG_USE_OPEN_FILE)
  2804. } else if (fileacc->membuf != NULL) {
  2805. ret = 0;
  2806. #endif
  2807. }
  2808. /* reset all members of fileacc */
  2809. memset(fileacc, 0, sizeof(*fileacc));
  2810. }
  2811. return ret;
  2812. }
  2813. #endif /* NO_FILESYSTEMS */
  2814. static void
  2815. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2816. {
  2817. for (; *src != '\0' && n > 1; n--) {
  2818. *dst++ = *src++;
  2819. }
  2820. *dst = '\0';
  2821. }
  2822. static int
  2823. lowercase(const char *s)
  2824. {
  2825. return tolower((unsigned char)*s);
  2826. }
  2827. int
  2828. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2829. {
  2830. int diff = 0;
  2831. if (len > 0) {
  2832. do {
  2833. diff = lowercase(s1++) - lowercase(s2++);
  2834. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2835. }
  2836. return diff;
  2837. }
  2838. int
  2839. mg_strcasecmp(const char *s1, const char *s2)
  2840. {
  2841. int diff;
  2842. do {
  2843. diff = lowercase(s1++) - lowercase(s2++);
  2844. } while (diff == 0 && s1[-1] != '\0');
  2845. return diff;
  2846. }
  2847. static char *
  2848. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2849. {
  2850. char *p;
  2851. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2852. * defined */
  2853. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2854. mg_strlcpy(p, ptr, len + 1);
  2855. }
  2856. return p;
  2857. }
  2858. static char *
  2859. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2860. {
  2861. return mg_strndup_ctx(str, strlen(str), ctx);
  2862. }
  2863. static char *
  2864. mg_strdup(const char *str)
  2865. {
  2866. return mg_strndup_ctx(str, strlen(str), NULL);
  2867. }
  2868. static const char *
  2869. mg_strcasestr(const char *big_str, const char *small_str)
  2870. {
  2871. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2872. if (big_len >= small_len) {
  2873. for (i = 0; i <= (big_len - small_len); i++) {
  2874. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2875. return big_str + i;
  2876. }
  2877. }
  2878. }
  2879. return NULL;
  2880. }
  2881. /* Return null terminated string of given maximum length.
  2882. * Report errors if length is exceeded. */
  2883. static void
  2884. mg_vsnprintf(const struct mg_connection *conn,
  2885. int *truncated,
  2886. char *buf,
  2887. size_t buflen,
  2888. const char *fmt,
  2889. va_list ap)
  2890. {
  2891. int n, ok;
  2892. if (buflen == 0) {
  2893. if (truncated) {
  2894. *truncated = 1;
  2895. }
  2896. return;
  2897. }
  2898. #if defined(__clang__)
  2899. #pragma clang diagnostic push
  2900. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2901. /* Using fmt as a non-literal is intended here, since it is mostly called
  2902. * indirectly by mg_snprintf */
  2903. #endif
  2904. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2905. ok = (n >= 0) && ((size_t)n < buflen);
  2906. #if defined(__clang__)
  2907. #pragma clang diagnostic pop
  2908. #endif
  2909. if (ok) {
  2910. if (truncated) {
  2911. *truncated = 0;
  2912. }
  2913. } else {
  2914. if (truncated) {
  2915. *truncated = 1;
  2916. }
  2917. mg_cry_internal(conn,
  2918. "truncating vsnprintf buffer: [%.*s]",
  2919. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2920. buf);
  2921. n = (int)buflen - 1;
  2922. }
  2923. buf[n] = '\0';
  2924. }
  2925. static void
  2926. mg_snprintf(const struct mg_connection *conn,
  2927. int *truncated,
  2928. char *buf,
  2929. size_t buflen,
  2930. const char *fmt,
  2931. ...)
  2932. {
  2933. va_list ap;
  2934. va_start(ap, fmt);
  2935. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2936. va_end(ap);
  2937. }
  2938. static int
  2939. get_option_index(const char *name)
  2940. {
  2941. int i;
  2942. for (i = 0; config_options[i].name != NULL; i++) {
  2943. if (strcmp(config_options[i].name, name) == 0) {
  2944. return i;
  2945. }
  2946. }
  2947. return -1;
  2948. }
  2949. const char *
  2950. mg_get_option(const struct mg_context *ctx, const char *name)
  2951. {
  2952. int i;
  2953. if ((i = get_option_index(name)) == -1) {
  2954. return NULL;
  2955. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2956. return "";
  2957. } else {
  2958. return ctx->dd.config[i];
  2959. }
  2960. }
  2961. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2962. struct mg_context *
  2963. mg_get_context(const struct mg_connection *conn)
  2964. {
  2965. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2966. }
  2967. void *
  2968. mg_get_user_data(const struct mg_context *ctx)
  2969. {
  2970. return (ctx == NULL) ? NULL : ctx->user_data;
  2971. }
  2972. void *
  2973. mg_get_user_context_data(const struct mg_connection *conn)
  2974. {
  2975. return mg_get_user_data(mg_get_context(conn));
  2976. }
  2977. void *
  2978. mg_get_thread_pointer(const struct mg_connection *conn)
  2979. {
  2980. /* both methods should return the same pointer */
  2981. if (conn) {
  2982. /* quick access, in case conn is known */
  2983. return conn->tls_user_ptr;
  2984. } else {
  2985. /* otherwise get pointer from thread local storage (TLS) */
  2986. struct mg_workerTLS *tls =
  2987. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2988. return tls->user_ptr;
  2989. }
  2990. }
  2991. void
  2992. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2993. {
  2994. if (conn != NULL) {
  2995. conn->request_info.conn_data = data;
  2996. }
  2997. }
  2998. void *
  2999. mg_get_user_connection_data(const struct mg_connection *conn)
  3000. {
  3001. if (conn != NULL) {
  3002. return conn->request_info.conn_data;
  3003. }
  3004. return NULL;
  3005. }
  3006. #if defined(MG_LEGACY_INTERFACE)
  3007. /* Deprecated: Use mg_get_server_ports instead. */
  3008. size_t
  3009. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3010. {
  3011. size_t i;
  3012. if (!ctx) {
  3013. return 0;
  3014. }
  3015. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3016. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3017. ports[i] =
  3018. #if defined(USE_IPV6)
  3019. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3020. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3021. :
  3022. #endif
  3023. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3024. }
  3025. return i;
  3026. }
  3027. #endif
  3028. int
  3029. mg_get_server_ports(const struct mg_context *ctx,
  3030. int size,
  3031. struct mg_server_port *ports)
  3032. {
  3033. int i, cnt = 0;
  3034. if (size <= 0) {
  3035. return -1;
  3036. }
  3037. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3038. if (!ctx) {
  3039. return -1;
  3040. }
  3041. if (!ctx->listening_sockets) {
  3042. return -1;
  3043. }
  3044. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3045. ports[cnt].port =
  3046. #if defined(USE_IPV6)
  3047. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3048. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3049. :
  3050. #endif
  3051. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3052. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3053. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3054. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3055. /* IPv4 */
  3056. ports[cnt].protocol = 1;
  3057. cnt++;
  3058. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3059. /* IPv6 */
  3060. ports[cnt].protocol = 3;
  3061. cnt++;
  3062. }
  3063. }
  3064. return cnt;
  3065. }
  3066. static void
  3067. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3068. {
  3069. buf[0] = '\0';
  3070. if (!usa) {
  3071. return;
  3072. }
  3073. if (usa->sa.sa_family == AF_INET) {
  3074. getnameinfo(&usa->sa,
  3075. sizeof(usa->sin),
  3076. buf,
  3077. (unsigned)len,
  3078. NULL,
  3079. 0,
  3080. NI_NUMERICHOST);
  3081. }
  3082. #if defined(USE_IPV6)
  3083. else if (usa->sa.sa_family == AF_INET6) {
  3084. getnameinfo(&usa->sa,
  3085. sizeof(usa->sin6),
  3086. buf,
  3087. (unsigned)len,
  3088. NULL,
  3089. 0,
  3090. NI_NUMERICHOST);
  3091. }
  3092. #endif
  3093. }
  3094. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3095. * included in all responses other than 100, 101, 5xx. */
  3096. static void
  3097. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3098. {
  3099. #if !defined(REENTRANT_TIME)
  3100. struct tm *tm;
  3101. tm = ((t != NULL) ? gmtime(t) : NULL);
  3102. if (tm != NULL) {
  3103. #else
  3104. struct tm _tm;
  3105. struct tm *tm = &_tm;
  3106. if (t != NULL) {
  3107. gmtime_r(t, tm);
  3108. #endif
  3109. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3110. } else {
  3111. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3112. buf[buf_len - 1] = '\0';
  3113. }
  3114. }
  3115. /* difftime for struct timespec. Return value is in seconds. */
  3116. static double
  3117. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3118. {
  3119. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3120. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3121. }
  3122. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3123. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3124. const char *func,
  3125. unsigned line,
  3126. const char *fmt,
  3127. va_list ap);
  3128. #include "external_mg_cry_internal_impl.inl"
  3129. #elif !defined(NO_FILESYSTEMS)
  3130. /* Print error message to the opened error log stream. */
  3131. static void
  3132. mg_cry_internal_impl(const struct mg_connection *conn,
  3133. const char *func,
  3134. unsigned line,
  3135. const char *fmt,
  3136. va_list ap)
  3137. {
  3138. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3139. struct mg_file fi;
  3140. time_t timestamp;
  3141. /* Unused, in the RELEASE build */
  3142. (void)func;
  3143. (void)line;
  3144. #if defined(GCC_DIAGNOSTIC)
  3145. #pragma GCC diagnostic push
  3146. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3147. #endif
  3148. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3149. #if defined(GCC_DIAGNOSTIC)
  3150. #pragma GCC diagnostic pop
  3151. #endif
  3152. buf[sizeof(buf) - 1] = 0;
  3153. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3154. if (!conn) {
  3155. puts(buf);
  3156. return;
  3157. }
  3158. /* Do not lock when getting the callback value, here and below.
  3159. * I suppose this is fine, since function cannot disappear in the
  3160. * same way string option can. */
  3161. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3162. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3163. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3164. if (mg_fopen(conn,
  3165. conn->dom_ctx->config[ERROR_LOG_FILE],
  3166. MG_FOPEN_MODE_APPEND,
  3167. &fi)
  3168. == 0) {
  3169. fi.access.fp = NULL;
  3170. }
  3171. } else {
  3172. fi.access.fp = NULL;
  3173. }
  3174. if (fi.access.fp != NULL) {
  3175. flockfile(fi.access.fp);
  3176. timestamp = time(NULL);
  3177. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3178. fprintf(fi.access.fp,
  3179. "[%010lu] [error] [client %s] ",
  3180. (unsigned long)timestamp,
  3181. src_addr);
  3182. if (conn->request_info.request_method != NULL) {
  3183. fprintf(fi.access.fp,
  3184. "%s %s: ",
  3185. conn->request_info.request_method,
  3186. conn->request_info.request_uri
  3187. ? conn->request_info.request_uri
  3188. : "");
  3189. }
  3190. fprintf(fi.access.fp, "%s", buf);
  3191. fputc('\n', fi.access.fp);
  3192. fflush(fi.access.fp);
  3193. funlockfile(fi.access.fp);
  3194. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3195. * mg_cry here anyway ;-) */
  3196. }
  3197. }
  3198. }
  3199. #else
  3200. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3201. #endif /* Externally provided function */
  3202. /* Construct fake connection structure. Used for logging, if connection
  3203. * is not applicable at the moment of logging. */
  3204. static struct mg_connection *
  3205. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3206. {
  3207. static const struct mg_connection conn_zero = {0};
  3208. *fc = conn_zero;
  3209. fc->phys_ctx = ctx;
  3210. fc->dom_ctx = &(ctx->dd);
  3211. return fc;
  3212. }
  3213. static void
  3214. mg_cry_internal_wrap(const struct mg_connection *conn,
  3215. struct mg_context *ctx,
  3216. const char *func,
  3217. unsigned line,
  3218. const char *fmt,
  3219. ...)
  3220. {
  3221. va_list ap;
  3222. va_start(ap, fmt);
  3223. if (!conn && ctx) {
  3224. struct mg_connection fc;
  3225. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3226. } else {
  3227. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3228. }
  3229. va_end(ap);
  3230. }
  3231. void
  3232. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3233. {
  3234. va_list ap;
  3235. va_start(ap, fmt);
  3236. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3237. va_end(ap);
  3238. }
  3239. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3240. const char *
  3241. mg_version(void)
  3242. {
  3243. return CIVETWEB_VERSION;
  3244. }
  3245. const struct mg_request_info *
  3246. mg_get_request_info(const struct mg_connection *conn)
  3247. {
  3248. if (!conn) {
  3249. return NULL;
  3250. }
  3251. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3252. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3253. char txt[16];
  3254. struct mg_workerTLS *tls =
  3255. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3256. sprintf(txt, "%03i", conn->response_info.status_code);
  3257. if (strlen(txt) == 3) {
  3258. memcpy(tls->txtbuf, txt, 4);
  3259. } else {
  3260. strcpy(tls->txtbuf, "ERR");
  3261. }
  3262. ((struct mg_connection *)conn)->request_info.local_uri =
  3263. ((struct mg_connection *)conn)->request_info.request_uri =
  3264. tls->txtbuf; /* use thread safe buffer */
  3265. ((struct mg_connection *)conn)->request_info.num_headers =
  3266. conn->response_info.num_headers;
  3267. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3268. conn->response_info.http_headers,
  3269. sizeof(conn->response_info.http_headers));
  3270. } else
  3271. #endif
  3272. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3273. return NULL;
  3274. }
  3275. return &conn->request_info;
  3276. }
  3277. const struct mg_response_info *
  3278. mg_get_response_info(const struct mg_connection *conn)
  3279. {
  3280. if (!conn) {
  3281. return NULL;
  3282. }
  3283. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3284. return NULL;
  3285. }
  3286. return &conn->response_info;
  3287. }
  3288. static const char *
  3289. get_proto_name(const struct mg_connection *conn)
  3290. {
  3291. #if defined(__clang__)
  3292. #pragma clang diagnostic push
  3293. #pragma clang diagnostic ignored "-Wunreachable-code"
  3294. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3295. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3296. * unreachable, but splitting into four different #ifdef clauses here is more
  3297. * complicated.
  3298. */
  3299. #endif
  3300. const struct mg_request_info *ri = &conn->request_info;
  3301. const char *proto =
  3302. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3303. : (ri->is_ssl ? "https" : "http"));
  3304. return proto;
  3305. #if defined(__clang__)
  3306. #pragma clang diagnostic pop
  3307. #endif
  3308. }
  3309. int
  3310. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3311. {
  3312. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3313. return -1;
  3314. } else {
  3315. int truncated = 0;
  3316. const struct mg_request_info *ri = &conn->request_info;
  3317. const char *proto = get_proto_name(conn);
  3318. if (ri->local_uri == NULL) {
  3319. return -1;
  3320. }
  3321. if ((ri->request_uri != NULL)
  3322. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3323. /* The request uri is different from the local uri.
  3324. * This is usually if an absolute URI, including server
  3325. * name has been provided. */
  3326. mg_snprintf(conn,
  3327. &truncated,
  3328. buf,
  3329. buflen,
  3330. "%s://%s",
  3331. proto,
  3332. ri->request_uri);
  3333. if (truncated) {
  3334. return -1;
  3335. }
  3336. return 0;
  3337. } else {
  3338. /* The common case is a relative URI, so we have to
  3339. * construct an absolute URI from server name and port */
  3340. #if defined(USE_IPV6)
  3341. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3342. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3343. : htons(conn->client.lsa.sin.sin_port);
  3344. #else
  3345. int port = htons(conn->client.lsa.sin.sin_port);
  3346. #endif
  3347. int def_port = ri->is_ssl ? 443 : 80;
  3348. int auth_domain_check_enabled =
  3349. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3350. && (!mg_strcasecmp(
  3351. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3352. const char *server_domain =
  3353. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3354. char portstr[16];
  3355. char server_ip[48];
  3356. if (port != def_port) {
  3357. sprintf(portstr, ":%u", (unsigned)port);
  3358. } else {
  3359. portstr[0] = 0;
  3360. }
  3361. if (!auth_domain_check_enabled || !server_domain) {
  3362. sockaddr_to_string(server_ip,
  3363. sizeof(server_ip),
  3364. &conn->client.lsa);
  3365. server_domain = server_ip;
  3366. }
  3367. mg_snprintf(conn,
  3368. &truncated,
  3369. buf,
  3370. buflen,
  3371. "%s://%s%s%s",
  3372. proto,
  3373. server_domain,
  3374. portstr,
  3375. ri->local_uri);
  3376. if (truncated) {
  3377. return -1;
  3378. }
  3379. return 0;
  3380. }
  3381. }
  3382. }
  3383. /* Skip the characters until one of the delimiters characters found.
  3384. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3385. * Advance pointer to buffer to the next word. Return found 0-terminated
  3386. * word.
  3387. * Delimiters can be quoted with quotechar. */
  3388. static char *
  3389. skip_quoted(char **buf,
  3390. const char *delimiters,
  3391. const char *whitespace,
  3392. char quotechar)
  3393. {
  3394. char *p, *begin_word, *end_word, *end_whitespace;
  3395. begin_word = *buf;
  3396. end_word = begin_word + strcspn(begin_word, delimiters);
  3397. /* Check for quotechar */
  3398. if (end_word > begin_word) {
  3399. p = end_word - 1;
  3400. while (*p == quotechar) {
  3401. /* While the delimiter is quoted, look for the next delimiter.
  3402. */
  3403. /* This happens, e.g., in calls from parse_auth_header,
  3404. * if the user name contains a " character. */
  3405. /* If there is anything beyond end_word, copy it. */
  3406. if (*end_word != '\0') {
  3407. size_t end_off = strcspn(end_word + 1, delimiters);
  3408. memmove(p, end_word, end_off + 1);
  3409. p += end_off; /* p must correspond to end_word - 1 */
  3410. end_word += end_off + 1;
  3411. } else {
  3412. *p = '\0';
  3413. break;
  3414. }
  3415. }
  3416. for (p++; p < end_word; p++) {
  3417. *p = '\0';
  3418. }
  3419. }
  3420. if (*end_word == '\0') {
  3421. *buf = end_word;
  3422. } else {
  3423. #if defined(GCC_DIAGNOSTIC)
  3424. /* Disable spurious conversion warning for GCC */
  3425. #pragma GCC diagnostic push
  3426. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3427. #endif /* defined(GCC_DIAGNOSTIC) */
  3428. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3429. #if defined(GCC_DIAGNOSTIC)
  3430. #pragma GCC diagnostic pop
  3431. #endif /* defined(GCC_DIAGNOSTIC) */
  3432. for (p = end_word; p < end_whitespace; p++) {
  3433. *p = '\0';
  3434. }
  3435. *buf = end_whitespace;
  3436. }
  3437. return begin_word;
  3438. }
  3439. /* Return HTTP header value, or NULL if not found. */
  3440. static const char *
  3441. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3442. {
  3443. int i;
  3444. for (i = 0; i < num_hdr; i++) {
  3445. if (!mg_strcasecmp(name, hdr[i].name)) {
  3446. return hdr[i].value;
  3447. }
  3448. }
  3449. return NULL;
  3450. }
  3451. #if defined(USE_WEBSOCKET)
  3452. /* Retrieve requested HTTP header multiple values, and return the number of
  3453. * found occurrences */
  3454. static int
  3455. get_req_headers(const struct mg_request_info *ri,
  3456. const char *name,
  3457. const char **output,
  3458. int output_max_size)
  3459. {
  3460. int i;
  3461. int cnt = 0;
  3462. if (ri) {
  3463. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3464. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3465. output[cnt++] = ri->http_headers[i].value;
  3466. }
  3467. }
  3468. }
  3469. return cnt;
  3470. }
  3471. #endif
  3472. const char *
  3473. mg_get_header(const struct mg_connection *conn, const char *name)
  3474. {
  3475. if (!conn) {
  3476. return NULL;
  3477. }
  3478. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3479. return get_header(conn->request_info.http_headers,
  3480. conn->request_info.num_headers,
  3481. name);
  3482. }
  3483. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3484. return get_header(conn->response_info.http_headers,
  3485. conn->response_info.num_headers,
  3486. name);
  3487. }
  3488. return NULL;
  3489. }
  3490. static const char *
  3491. get_http_version(const struct mg_connection *conn)
  3492. {
  3493. if (!conn) {
  3494. return NULL;
  3495. }
  3496. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3497. return conn->request_info.http_version;
  3498. }
  3499. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3500. return conn->response_info.http_version;
  3501. }
  3502. return NULL;
  3503. }
  3504. /* A helper function for traversing a comma separated list of values.
  3505. * It returns a list pointer shifted to the next value, or NULL if the end
  3506. * of the list found.
  3507. * Value is stored in val vector. If value has form "x=y", then eq_val
  3508. * vector is initialized to point to the "y" part, and val vector length
  3509. * is adjusted to point only to "x". */
  3510. static const char *
  3511. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3512. {
  3513. int end;
  3514. reparse:
  3515. if (val == NULL || list == NULL || *list == '\0') {
  3516. /* End of the list */
  3517. return NULL;
  3518. }
  3519. /* Skip over leading LWS */
  3520. while (*list == ' ' || *list == '\t')
  3521. list++;
  3522. val->ptr = list;
  3523. if ((list = strchr(val->ptr, ',')) != NULL) {
  3524. /* Comma found. Store length and shift the list ptr */
  3525. val->len = ((size_t)(list - val->ptr));
  3526. list++;
  3527. } else {
  3528. /* This value is the last one */
  3529. list = val->ptr + strlen(val->ptr);
  3530. val->len = ((size_t)(list - val->ptr));
  3531. }
  3532. /* Adjust length for trailing LWS */
  3533. end = (int)val->len - 1;
  3534. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3535. end--;
  3536. val->len = (size_t)(end) + (size_t)(1);
  3537. if (val->len == 0) {
  3538. /* Ignore any empty entries. */
  3539. goto reparse;
  3540. }
  3541. if (eq_val != NULL) {
  3542. /* Value has form "x=y", adjust pointers and lengths
  3543. * so that val points to "x", and eq_val points to "y". */
  3544. eq_val->len = 0;
  3545. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3546. if (eq_val->ptr != NULL) {
  3547. eq_val->ptr++; /* Skip over '=' character */
  3548. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3549. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3550. }
  3551. }
  3552. return list;
  3553. }
  3554. /* A helper function for checking if a comma separated list of values
  3555. * contains
  3556. * the given option (case insensitvely).
  3557. * 'header' can be NULL, in which case false is returned. */
  3558. static int
  3559. header_has_option(const char *header, const char *option)
  3560. {
  3561. struct vec opt_vec;
  3562. struct vec eq_vec;
  3563. DEBUG_ASSERT(option != NULL);
  3564. DEBUG_ASSERT(option[0] != '\0');
  3565. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3566. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3567. return 1;
  3568. }
  3569. return 0;
  3570. }
  3571. /* Perform case-insensitive match of string against pattern */
  3572. static ptrdiff_t
  3573. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3574. {
  3575. const char *or_str;
  3576. ptrdiff_t i, j, len, res;
  3577. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3578. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3579. return (res > 0) ? res
  3580. : match_prefix(or_str + 1,
  3581. (size_t)((pattern + pattern_len)
  3582. - (or_str + 1)),
  3583. str);
  3584. }
  3585. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3586. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3587. continue;
  3588. } else if (pattern[i] == '$') {
  3589. return (str[j] == '\0') ? j : -1;
  3590. } else if (pattern[i] == '*') {
  3591. i++;
  3592. if (pattern[i] == '*') {
  3593. i++;
  3594. len = strlen(str + j);
  3595. } else {
  3596. len = strcspn(str + j, "/");
  3597. }
  3598. if (i == (ptrdiff_t)pattern_len) {
  3599. return j + len;
  3600. }
  3601. do {
  3602. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3603. } while (res == -1 && len-- > 0);
  3604. return (res == -1) ? -1 : j + res + len;
  3605. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3606. return -1;
  3607. }
  3608. }
  3609. return (ptrdiff_t)j;
  3610. }
  3611. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3612. * This function must tolerate situations when connection info is not
  3613. * set up, for example if request parsing failed. */
  3614. static int
  3615. should_keep_alive(const struct mg_connection *conn)
  3616. {
  3617. const char *http_version;
  3618. const char *header;
  3619. /* First satisfy needs of the server */
  3620. if ((conn == NULL) || conn->must_close) {
  3621. /* Close, if civetweb framework needs to close */
  3622. return 0;
  3623. }
  3624. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3625. /* Close, if keep alive is not enabled */
  3626. return 0;
  3627. }
  3628. /* Check explicit wish of the client */
  3629. header = mg_get_header(conn, "Connection");
  3630. if (header) {
  3631. /* If there is a connection header from the client, obey */
  3632. if (header_has_option(header, "keep-alive")) {
  3633. return 1;
  3634. }
  3635. return 0;
  3636. }
  3637. /* Use default of the standard */
  3638. http_version = get_http_version(conn);
  3639. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3640. /* HTTP 1.1 default is keep alive */
  3641. return 1;
  3642. }
  3643. /* HTTP 1.0 (and earlier) default is to close the connection */
  3644. return 0;
  3645. }
  3646. static int
  3647. should_decode_url(const struct mg_connection *conn)
  3648. {
  3649. if (!conn || !conn->dom_ctx) {
  3650. return 0;
  3651. }
  3652. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3653. }
  3654. static const char *
  3655. suggest_connection_header(const struct mg_connection *conn)
  3656. {
  3657. return should_keep_alive(conn) ? "keep-alive" : "close";
  3658. }
  3659. static int
  3660. send_no_cache_header(struct mg_connection *conn)
  3661. {
  3662. /* Send all current and obsolete cache opt-out directives. */
  3663. return mg_printf(conn,
  3664. "Cache-Control: no-cache, no-store, "
  3665. "must-revalidate, private, max-age=0\r\n"
  3666. "Pragma: no-cache\r\n"
  3667. "Expires: 0\r\n");
  3668. }
  3669. static int
  3670. send_static_cache_header(struct mg_connection *conn)
  3671. {
  3672. #if !defined(NO_CACHING)
  3673. int max_age;
  3674. const char *cache_control = conn->dom_ctx->config[STATIC_FILE_CACHE_CONTROL];
  3675. if (cache_control != NULL) {
  3676. return mg_printf(conn, "Cache-Control: %s\r\n", cache_control);
  3677. }
  3678. /* Read the server config to check how long a file may be cached.
  3679. * The configuration is in seconds. */
  3680. max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3681. if (max_age <= 0) {
  3682. /* 0 means "do not cache". All values <0 are reserved
  3683. * and may be used differently in the future. */
  3684. /* If a file should not be cached, do not only send
  3685. * max-age=0, but also pragmas and Expires headers. */
  3686. return send_no_cache_header(conn);
  3687. }
  3688. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3689. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3690. /* See also https://www.mnot.net/cache_docs/ */
  3691. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3692. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3693. * leap
  3694. * year to 31622400 seconds. For the moment, we just send whatever has
  3695. * been configured, still the behavior for >1 year should be considered
  3696. * as undefined. */
  3697. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3698. #else /* NO_CACHING */
  3699. return send_no_cache_header(conn);
  3700. #endif /* !NO_CACHING */
  3701. }
  3702. static int
  3703. send_additional_header(struct mg_connection *conn)
  3704. {
  3705. int i = 0;
  3706. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3707. #if !defined(NO_SSL)
  3708. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3709. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3710. if (max_age >= 0) {
  3711. i += mg_printf(conn,
  3712. "Strict-Transport-Security: max-age=%u\r\n",
  3713. (unsigned)max_age);
  3714. }
  3715. }
  3716. #endif
  3717. if (header && header[0]) {
  3718. i += mg_printf(conn, "%s\r\n", header);
  3719. }
  3720. return i;
  3721. }
  3722. #if !defined(NO_FILESYSTEMS)
  3723. static void handle_file_based_request(struct mg_connection *conn,
  3724. const char *path,
  3725. struct mg_file *filep);
  3726. #endif /* NO_FILESYSTEMS */
  3727. const char *
  3728. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3729. {
  3730. /* See IANA HTTP status code assignment:
  3731. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3732. */
  3733. switch (response_code) {
  3734. /* RFC2616 Section 10.1 - Informational 1xx */
  3735. case 100:
  3736. return "Continue"; /* RFC2616 Section 10.1.1 */
  3737. case 101:
  3738. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3739. case 102:
  3740. return "Processing"; /* RFC2518 Section 10.1 */
  3741. /* RFC2616 Section 10.2 - Successful 2xx */
  3742. case 200:
  3743. return "OK"; /* RFC2616 Section 10.2.1 */
  3744. case 201:
  3745. return "Created"; /* RFC2616 Section 10.2.2 */
  3746. case 202:
  3747. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3748. case 203:
  3749. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3750. case 204:
  3751. return "No Content"; /* RFC2616 Section 10.2.5 */
  3752. case 205:
  3753. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3754. case 206:
  3755. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3756. case 207:
  3757. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3758. */
  3759. case 208:
  3760. return "Already Reported"; /* RFC5842 Section 7.1 */
  3761. case 226:
  3762. return "IM used"; /* RFC3229 Section 10.4.1 */
  3763. /* RFC2616 Section 10.3 - Redirection 3xx */
  3764. case 300:
  3765. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3766. case 301:
  3767. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3768. case 302:
  3769. return "Found"; /* RFC2616 Section 10.3.3 */
  3770. case 303:
  3771. return "See Other"; /* RFC2616 Section 10.3.4 */
  3772. case 304:
  3773. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3774. case 305:
  3775. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3776. case 307:
  3777. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3778. case 308:
  3779. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3780. /* RFC2616 Section 10.4 - Client Error 4xx */
  3781. case 400:
  3782. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3783. case 401:
  3784. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3785. case 402:
  3786. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3787. case 403:
  3788. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3789. case 404:
  3790. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3791. case 405:
  3792. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3793. case 406:
  3794. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3795. case 407:
  3796. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3797. case 408:
  3798. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3799. case 409:
  3800. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3801. case 410:
  3802. return "Gone"; /* RFC2616 Section 10.4.11 */
  3803. case 411:
  3804. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3805. case 412:
  3806. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3807. case 413:
  3808. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3809. case 414:
  3810. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3811. case 415:
  3812. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3813. case 416:
  3814. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3815. */
  3816. case 417:
  3817. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3818. case 421:
  3819. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3820. case 422:
  3821. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3822. * Section 11.2 */
  3823. case 423:
  3824. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3825. case 424:
  3826. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3827. * Section 11.4 */
  3828. case 426:
  3829. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3830. case 428:
  3831. return "Precondition Required"; /* RFC 6585, Section 3 */
  3832. case 429:
  3833. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3834. case 431:
  3835. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3836. case 451:
  3837. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3838. * Section 3 */
  3839. /* RFC2616 Section 10.5 - Server Error 5xx */
  3840. case 500:
  3841. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3842. case 501:
  3843. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3844. case 502:
  3845. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3846. case 503:
  3847. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3848. case 504:
  3849. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3850. case 505:
  3851. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3852. case 506:
  3853. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3854. case 507:
  3855. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3856. * Section 11.5 */
  3857. case 508:
  3858. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3859. case 510:
  3860. return "Not Extended"; /* RFC 2774, Section 7 */
  3861. case 511:
  3862. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3863. /* Other status codes, not shown in the IANA HTTP status code
  3864. * assignment.
  3865. * E.g., "de facto" standards due to common use, ... */
  3866. case 418:
  3867. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3868. case 419:
  3869. return "Authentication Timeout"; /* common use */
  3870. case 420:
  3871. return "Enhance Your Calm"; /* common use */
  3872. case 440:
  3873. return "Login Timeout"; /* common use */
  3874. case 509:
  3875. return "Bandwidth Limit Exceeded"; /* common use */
  3876. default:
  3877. /* This error code is unknown. This should not happen. */
  3878. if (conn) {
  3879. mg_cry_internal(conn,
  3880. "Unknown HTTP response code: %u",
  3881. response_code);
  3882. }
  3883. /* Return at least a category according to RFC 2616 Section 10. */
  3884. if (response_code >= 100 && response_code < 200) {
  3885. /* Unknown informational status code */
  3886. return "Information";
  3887. }
  3888. if (response_code >= 200 && response_code < 300) {
  3889. /* Unknown success code */
  3890. return "Success";
  3891. }
  3892. if (response_code >= 300 && response_code < 400) {
  3893. /* Unknown redirection code */
  3894. return "Redirection";
  3895. }
  3896. if (response_code >= 400 && response_code < 500) {
  3897. /* Unknown request error code */
  3898. return "Client Error";
  3899. }
  3900. if (response_code >= 500 && response_code < 600) {
  3901. /* Unknown server error code */
  3902. return "Server Error";
  3903. }
  3904. /* Response code not even within reasonable range */
  3905. return "";
  3906. }
  3907. }
  3908. static int
  3909. mg_send_http_error_impl(struct mg_connection *conn,
  3910. int status,
  3911. const char *fmt,
  3912. va_list args)
  3913. {
  3914. char errmsg_buf[MG_BUF_LEN];
  3915. va_list ap;
  3916. int has_body;
  3917. char date[64];
  3918. time_t curtime = time(NULL);
  3919. #if !defined(NO_FILESYSTEMS)
  3920. char path_buf[PATH_MAX];
  3921. int len, i, page_handler_found, scope, truncated;
  3922. const char *error_handler = NULL;
  3923. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3924. const char *error_page_file_ext, *tstr;
  3925. #endif /* NO_FILESYSTEMS */
  3926. int handled_by_callback = 0;
  3927. const char *status_text = mg_get_response_code_text(conn, status);
  3928. if ((conn == NULL) || (fmt == NULL)) {
  3929. return -2;
  3930. }
  3931. /* Set status (for log) */
  3932. conn->status_code = status;
  3933. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3934. has_body = ((status > 199) && (status != 204) && (status != 304));
  3935. /* Prepare message in buf, if required */
  3936. if (has_body
  3937. || (!conn->in_error_handler
  3938. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3939. /* Store error message in errmsg_buf */
  3940. va_copy(ap, args);
  3941. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3942. va_end(ap);
  3943. /* In a debug build, print all html errors */
  3944. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3945. }
  3946. /* If there is a http_error callback, call it.
  3947. * But don't do it recursively, if callback calls mg_send_http_error again.
  3948. */
  3949. if (!conn->in_error_handler
  3950. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3951. /* Mark in_error_handler to avoid recursion and call user callback. */
  3952. conn->in_error_handler = 1;
  3953. handled_by_callback =
  3954. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3955. == 0);
  3956. conn->in_error_handler = 0;
  3957. }
  3958. if (!handled_by_callback) {
  3959. /* Check for recursion */
  3960. if (conn->in_error_handler) {
  3961. DEBUG_TRACE(
  3962. "Recursion when handling error %u - fall back to default",
  3963. status);
  3964. #if !defined(NO_FILESYSTEMS)
  3965. } else {
  3966. /* Send user defined error pages, if defined */
  3967. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3968. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3969. page_handler_found = 0;
  3970. if (error_handler != NULL) {
  3971. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3972. switch (scope) {
  3973. case 1: /* Handler for specific error, e.g. 404 error */
  3974. mg_snprintf(conn,
  3975. &truncated,
  3976. path_buf,
  3977. sizeof(path_buf) - 32,
  3978. "%serror%03u.",
  3979. error_handler,
  3980. status);
  3981. break;
  3982. case 2: /* Handler for error group, e.g., 5xx error
  3983. * handler
  3984. * for all server errors (500-599) */
  3985. mg_snprintf(conn,
  3986. &truncated,
  3987. path_buf,
  3988. sizeof(path_buf) - 32,
  3989. "%serror%01uxx.",
  3990. error_handler,
  3991. status / 100);
  3992. break;
  3993. default: /* Handler for all errors */
  3994. mg_snprintf(conn,
  3995. &truncated,
  3996. path_buf,
  3997. sizeof(path_buf) - 32,
  3998. "%serror.",
  3999. error_handler);
  4000. break;
  4001. }
  4002. /* String truncation in buf may only occur if
  4003. * error_handler is too long. This string is
  4004. * from the config, not from a client. */
  4005. (void)truncated;
  4006. len = (int)strlen(path_buf);
  4007. tstr = strchr(error_page_file_ext, '.');
  4008. while (tstr) {
  4009. for (i = 1;
  4010. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  4011. i++) {
  4012. /* buffer overrun is not possible here, since
  4013. * (i < 32) && (len < sizeof(path_buf) - 32)
  4014. * ==> (i + len) < sizeof(path_buf) */
  4015. path_buf[len + i - 1] = tstr[i];
  4016. }
  4017. /* buffer overrun is not possible here, since
  4018. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4019. * ==> (i + len) <= sizeof(path_buf) */
  4020. path_buf[len + i - 1] = 0;
  4021. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4022. DEBUG_TRACE("Check error page %s - found",
  4023. path_buf);
  4024. page_handler_found = 1;
  4025. break;
  4026. }
  4027. DEBUG_TRACE("Check error page %s - not found",
  4028. path_buf);
  4029. tstr = strchr(tstr + i, '.');
  4030. }
  4031. }
  4032. }
  4033. if (page_handler_found) {
  4034. conn->in_error_handler = 1;
  4035. handle_file_based_request(conn, path_buf, &error_page_file);
  4036. conn->in_error_handler = 0;
  4037. return 0;
  4038. }
  4039. #endif /* NO_FILESYSTEMS */
  4040. }
  4041. /* No custom error page. Send default error page. */
  4042. gmt_time_string(date, sizeof(date), &curtime);
  4043. conn->must_close = 1;
  4044. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4045. send_no_cache_header(conn);
  4046. send_additional_header(conn);
  4047. if (has_body) {
  4048. mg_printf(conn,
  4049. "%s",
  4050. "Content-Type: text/plain; charset=utf-8\r\n");
  4051. }
  4052. mg_printf(conn,
  4053. "Date: %s\r\n"
  4054. "Connection: close\r\n\r\n",
  4055. date);
  4056. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4057. if (has_body) {
  4058. /* For other errors, send a generic error message. */
  4059. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4060. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4061. } else {
  4062. /* No body allowed. Close the connection. */
  4063. DEBUG_TRACE("Error %i", status);
  4064. }
  4065. }
  4066. return 0;
  4067. }
  4068. int
  4069. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4070. {
  4071. va_list ap;
  4072. int ret;
  4073. va_start(ap, fmt);
  4074. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4075. va_end(ap);
  4076. return ret;
  4077. }
  4078. int
  4079. mg_send_http_ok(struct mg_connection *conn,
  4080. const char *mime_type,
  4081. long long content_length)
  4082. {
  4083. char date[64];
  4084. time_t curtime = time(NULL);
  4085. if ((mime_type == NULL) || (*mime_type == 0)) {
  4086. /* Parameter error */
  4087. return -2;
  4088. }
  4089. gmt_time_string(date, sizeof(date), &curtime);
  4090. mg_printf(conn,
  4091. "HTTP/1.1 200 OK\r\n"
  4092. "Content-Type: %s\r\n"
  4093. "Date: %s\r\n"
  4094. "Connection: %s\r\n",
  4095. mime_type,
  4096. date,
  4097. suggest_connection_header(conn));
  4098. send_no_cache_header(conn);
  4099. send_additional_header(conn);
  4100. if (content_length < 0) {
  4101. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4102. } else {
  4103. mg_printf(conn,
  4104. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4105. (uint64_t)content_length);
  4106. }
  4107. return 0;
  4108. }
  4109. int
  4110. mg_send_http_redirect(struct mg_connection *conn,
  4111. const char *target_url,
  4112. int redirect_code)
  4113. {
  4114. /* Send a 30x redirect response.
  4115. *
  4116. * Redirect types (status codes):
  4117. *
  4118. * Status | Perm/Temp | Method | Version
  4119. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4120. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4121. * 303 | temporary | always use GET | HTTP/1.1
  4122. * 307 | temporary | always keep method | HTTP/1.1
  4123. * 308 | permanent | always keep method | HTTP/1.1
  4124. */
  4125. const char *redirect_text;
  4126. int ret;
  4127. size_t content_len = 0;
  4128. char reply[MG_BUF_LEN];
  4129. /* In case redirect_code=0, use 307. */
  4130. if (redirect_code == 0) {
  4131. redirect_code = 307;
  4132. }
  4133. /* In case redirect_code is none of the above, return error. */
  4134. if ((redirect_code != 301) && (redirect_code != 302)
  4135. && (redirect_code != 303) && (redirect_code != 307)
  4136. && (redirect_code != 308)) {
  4137. /* Parameter error */
  4138. return -2;
  4139. }
  4140. /* Get proper text for response code */
  4141. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4142. /* If target_url is not defined, redirect to "/". */
  4143. if ((target_url == NULL) || (*target_url == 0)) {
  4144. target_url = "/";
  4145. }
  4146. #if defined(MG_SEND_REDIRECT_BODY)
  4147. /* TODO: condition name? */
  4148. /* Prepare a response body with a hyperlink.
  4149. *
  4150. * According to RFC2616 (and RFC1945 before):
  4151. * Unless the request method was HEAD, the entity of the
  4152. * response SHOULD contain a short hypertext note with a hyperlink to
  4153. * the new URI(s).
  4154. *
  4155. * However, this response body is not useful in M2M communication.
  4156. * Probably the original reason in the RFC was, clients not supporting
  4157. * a 30x HTTP redirect could still show the HTML page and let the user
  4158. * press the link. Since current browsers support 30x HTTP, the additional
  4159. * HTML body does not seem to make sense anymore.
  4160. *
  4161. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4162. * but it only notes:
  4163. * The server's response payload usually contains a short
  4164. * hypertext note with a hyperlink to the new URI(s).
  4165. *
  4166. * Deactivated by default. If you need the 30x body, set the define.
  4167. */
  4168. mg_snprintf(
  4169. conn,
  4170. NULL /* ignore truncation */,
  4171. reply,
  4172. sizeof(reply),
  4173. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4174. redirect_text,
  4175. target_url,
  4176. target_url);
  4177. content_len = strlen(reply);
  4178. #else
  4179. reply[0] = 0;
  4180. #endif
  4181. /* Do not send any additional header. For all other options,
  4182. * including caching, there are suitable defaults. */
  4183. ret = mg_printf(conn,
  4184. "HTTP/1.1 %i %s\r\n"
  4185. "Location: %s\r\n"
  4186. "Content-Length: %u\r\n"
  4187. "Connection: %s\r\n\r\n",
  4188. redirect_code,
  4189. redirect_text,
  4190. target_url,
  4191. (unsigned int)content_len,
  4192. suggest_connection_header(conn));
  4193. /* Send response body */
  4194. if (ret > 0) {
  4195. /* ... unless it is a HEAD request */
  4196. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4197. ret = mg_write(conn, reply, content_len);
  4198. }
  4199. }
  4200. return (ret > 0) ? ret : -1;
  4201. }
  4202. #if defined(_WIN32)
  4203. /* Create substitutes for POSIX functions in Win32. */
  4204. #if defined(GCC_DIAGNOSTIC)
  4205. /* Show no warning in case system functions are not used. */
  4206. #pragma GCC diagnostic push
  4207. #pragma GCC diagnostic ignored "-Wunused-function"
  4208. #endif
  4209. static int
  4210. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4211. {
  4212. (void)unused;
  4213. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4214. InitializeCriticalSection(&mutex->sec);
  4215. return 0;
  4216. }
  4217. static int
  4218. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4219. {
  4220. DeleteCriticalSection(&mutex->sec);
  4221. return 0;
  4222. }
  4223. static int
  4224. pthread_mutex_lock(pthread_mutex_t *mutex)
  4225. {
  4226. EnterCriticalSection(&mutex->sec);
  4227. return 0;
  4228. }
  4229. static int
  4230. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4231. {
  4232. LeaveCriticalSection(&mutex->sec);
  4233. return 0;
  4234. }
  4235. FUNCTION_MAY_BE_UNUSED
  4236. static int
  4237. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4238. {
  4239. (void)unused;
  4240. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4241. cv->waiting_thread = NULL;
  4242. return 0;
  4243. }
  4244. FUNCTION_MAY_BE_UNUSED
  4245. static int
  4246. pthread_cond_timedwait(pthread_cond_t *cv,
  4247. pthread_mutex_t *mutex,
  4248. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4249. {
  4250. struct mg_workerTLS **ptls,
  4251. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4252. int ok;
  4253. int64_t nsnow, nswaitabs, nswaitrel;
  4254. DWORD mswaitrel;
  4255. pthread_mutex_lock(&cv->threadIdSec);
  4256. /* Add this thread to cv's waiting list */
  4257. ptls = &cv->waiting_thread;
  4258. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4259. ;
  4260. tls->next_waiting_thread = NULL;
  4261. *ptls = tls;
  4262. pthread_mutex_unlock(&cv->threadIdSec);
  4263. if (abstime) {
  4264. nsnow = mg_get_current_time_ns();
  4265. nswaitabs =
  4266. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4267. nswaitrel = nswaitabs - nsnow;
  4268. if (nswaitrel < 0) {
  4269. nswaitrel = 0;
  4270. }
  4271. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4272. } else {
  4273. mswaitrel = (DWORD)INFINITE;
  4274. }
  4275. pthread_mutex_unlock(mutex);
  4276. ok = (WAIT_OBJECT_0
  4277. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4278. if (!ok) {
  4279. ok = 1;
  4280. pthread_mutex_lock(&cv->threadIdSec);
  4281. ptls = &cv->waiting_thread;
  4282. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4283. if (*ptls == tls) {
  4284. *ptls = tls->next_waiting_thread;
  4285. ok = 0;
  4286. break;
  4287. }
  4288. }
  4289. pthread_mutex_unlock(&cv->threadIdSec);
  4290. if (ok) {
  4291. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4292. (DWORD)INFINITE);
  4293. }
  4294. }
  4295. /* This thread has been removed from cv's waiting list */
  4296. pthread_mutex_lock(mutex);
  4297. return ok ? 0 : -1;
  4298. }
  4299. FUNCTION_MAY_BE_UNUSED
  4300. static int
  4301. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4302. {
  4303. return pthread_cond_timedwait(cv, mutex, NULL);
  4304. }
  4305. FUNCTION_MAY_BE_UNUSED
  4306. static int
  4307. pthread_cond_signal(pthread_cond_t *cv)
  4308. {
  4309. HANDLE wkup = NULL;
  4310. BOOL ok = FALSE;
  4311. pthread_mutex_lock(&cv->threadIdSec);
  4312. if (cv->waiting_thread) {
  4313. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4314. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4315. ok = SetEvent(wkup);
  4316. DEBUG_ASSERT(ok);
  4317. }
  4318. pthread_mutex_unlock(&cv->threadIdSec);
  4319. return ok ? 0 : 1;
  4320. }
  4321. FUNCTION_MAY_BE_UNUSED
  4322. static int
  4323. pthread_cond_broadcast(pthread_cond_t *cv)
  4324. {
  4325. pthread_mutex_lock(&cv->threadIdSec);
  4326. while (cv->waiting_thread) {
  4327. pthread_cond_signal(cv);
  4328. }
  4329. pthread_mutex_unlock(&cv->threadIdSec);
  4330. return 0;
  4331. }
  4332. FUNCTION_MAY_BE_UNUSED
  4333. static int
  4334. pthread_cond_destroy(pthread_cond_t *cv)
  4335. {
  4336. pthread_mutex_lock(&cv->threadIdSec);
  4337. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4338. pthread_mutex_unlock(&cv->threadIdSec);
  4339. pthread_mutex_destroy(&cv->threadIdSec);
  4340. return 0;
  4341. }
  4342. #if defined(ALTERNATIVE_QUEUE)
  4343. FUNCTION_MAY_BE_UNUSED
  4344. static void *
  4345. event_create(void)
  4346. {
  4347. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4348. }
  4349. FUNCTION_MAY_BE_UNUSED
  4350. static int
  4351. event_wait(void *eventhdl)
  4352. {
  4353. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4354. return (res == WAIT_OBJECT_0);
  4355. }
  4356. FUNCTION_MAY_BE_UNUSED
  4357. static int
  4358. event_signal(void *eventhdl)
  4359. {
  4360. return (int)SetEvent((HANDLE)eventhdl);
  4361. }
  4362. FUNCTION_MAY_BE_UNUSED
  4363. static void
  4364. event_destroy(void *eventhdl)
  4365. {
  4366. CloseHandle((HANDLE)eventhdl);
  4367. }
  4368. #endif
  4369. #if defined(GCC_DIAGNOSTIC)
  4370. /* Enable unused function warning again */
  4371. #pragma GCC diagnostic pop
  4372. #endif
  4373. /* For Windows, change all slashes to backslashes in path names. */
  4374. static void
  4375. change_slashes_to_backslashes(char *path)
  4376. {
  4377. int i;
  4378. for (i = 0; path[i] != '\0'; i++) {
  4379. if (path[i] == '/') {
  4380. path[i] = '\\';
  4381. }
  4382. /* remove double backslash (check i > 0 to preserve UNC paths,
  4383. * like \\server\file.txt) */
  4384. if ((path[i] == '\\') && (i > 0)) {
  4385. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4386. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4387. }
  4388. }
  4389. }
  4390. }
  4391. static int
  4392. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4393. {
  4394. int diff;
  4395. do {
  4396. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4397. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4398. s1++;
  4399. s2++;
  4400. } while ((diff == 0) && (s1[-1] != L'\0'));
  4401. return diff;
  4402. }
  4403. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4404. * wbuf and wbuf_len is a target buffer and its length. */
  4405. static void
  4406. path_to_unicode(const struct mg_connection *conn,
  4407. const char *path,
  4408. wchar_t *wbuf,
  4409. size_t wbuf_len)
  4410. {
  4411. char buf[PATH_MAX], buf2[PATH_MAX];
  4412. wchar_t wbuf2[W_PATH_MAX + 1];
  4413. DWORD long_len, err;
  4414. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4415. mg_strlcpy(buf, path, sizeof(buf));
  4416. change_slashes_to_backslashes(buf);
  4417. /* Convert to Unicode and back. If doubly-converted string does not
  4418. * match the original, something is fishy, reject. */
  4419. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4420. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4421. WideCharToMultiByte(
  4422. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4423. if (strcmp(buf, buf2) != 0) {
  4424. wbuf[0] = L'\0';
  4425. }
  4426. /* Windows file systems are not case sensitive, but you can still use
  4427. * uppercase and lowercase letters (on all modern file systems).
  4428. * The server can check if the URI uses the same upper/lowercase
  4429. * letters an the file system, effectively making Windows servers
  4430. * case sensitive (like Linux servers are). It is still not possible
  4431. * to use two files with the same name in different cases on Windows
  4432. * (like /a and /A) - this would be possible in Linux.
  4433. * As a default, Windows is not case sensitive, but the case sensitive
  4434. * file name check can be activated by an additional configuration. */
  4435. if (conn) {
  4436. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4437. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4438. "yes")) {
  4439. /* Use case sensitive compare function */
  4440. fcompare = wcscmp;
  4441. }
  4442. }
  4443. (void)conn; /* conn is currently unused */
  4444. #if !defined(_WIN32_WCE)
  4445. /* Only accept a full file path, not a Windows short (8.3) path. */
  4446. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4447. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4448. if (long_len == 0) {
  4449. err = GetLastError();
  4450. if (err == ERROR_FILE_NOT_FOUND) {
  4451. /* File does not exist. This is not always a problem here. */
  4452. return;
  4453. }
  4454. }
  4455. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4456. /* Short name is used. */
  4457. wbuf[0] = L'\0';
  4458. }
  4459. #else
  4460. (void)long_len;
  4461. (void)wbuf2;
  4462. (void)err;
  4463. if (strchr(path, '~')) {
  4464. wbuf[0] = L'\0';
  4465. }
  4466. #endif
  4467. }
  4468. #if !defined(NO_FILESYSTEMS)
  4469. static int
  4470. mg_stat(const struct mg_connection *conn,
  4471. const char *path,
  4472. struct mg_file_stat *filep)
  4473. {
  4474. wchar_t wbuf[W_PATH_MAX];
  4475. WIN32_FILE_ATTRIBUTE_DATA info;
  4476. time_t creation_time;
  4477. size_t len;
  4478. if (!filep) {
  4479. return 0;
  4480. }
  4481. memset(filep, 0, sizeof(*filep));
  4482. if (conn && is_file_in_memory(conn, path)) {
  4483. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4484. * memset */
  4485. /* Quick fix (for 1.9.x): */
  4486. /* mg_stat must fill all fields, also for files in memory */
  4487. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4488. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4489. filep->size = tmp_file.stat.size;
  4490. filep->location = 2;
  4491. /* TODO: for 1.10: restructure how files in memory are handled */
  4492. /* The "file in memory" feature is a candidate for deletion.
  4493. * Please join the discussion at
  4494. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4495. */
  4496. filep->last_modified = time(NULL); /* TODO */
  4497. /* last_modified = now ... assumes the file may change during
  4498. * runtime,
  4499. * so every mg_fopen call may return different data */
  4500. /* last_modified = conn->phys_ctx.start_time;
  4501. * May be used it the data does not change during runtime. This
  4502. * allows
  4503. * browser caching. Since we do not know, we have to assume the file
  4504. * in memory may change. */
  4505. return 1;
  4506. }
  4507. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4508. /* Windows happily opens files with some garbage at the end of file name.
  4509. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4510. * "a.cgi", despite one would expect an error back. */
  4511. len = strlen(path);
  4512. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4513. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4514. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4515. filep->last_modified =
  4516. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4517. info.ftLastWriteTime.dwHighDateTime);
  4518. /* On Windows, the file creation time can be higher than the
  4519. * modification time, e.g. when a file is copied.
  4520. * Since the Last-Modified timestamp is used for caching
  4521. * it should be based on the most recent timestamp. */
  4522. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4523. info.ftCreationTime.dwHighDateTime);
  4524. if (creation_time > filep->last_modified) {
  4525. filep->last_modified = creation_time;
  4526. }
  4527. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4528. return 1;
  4529. }
  4530. return 0;
  4531. }
  4532. #endif
  4533. static int
  4534. mg_remove(const struct mg_connection *conn, const char *path)
  4535. {
  4536. wchar_t wbuf[W_PATH_MAX];
  4537. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4538. return DeleteFileW(wbuf) ? 0 : -1;
  4539. }
  4540. static int
  4541. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4542. {
  4543. wchar_t wbuf[W_PATH_MAX];
  4544. (void)mode;
  4545. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4546. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4547. }
  4548. /* Create substitutes for POSIX functions in Win32. */
  4549. #if defined(GCC_DIAGNOSTIC)
  4550. /* Show no warning in case system functions are not used. */
  4551. #pragma GCC diagnostic push
  4552. #pragma GCC diagnostic ignored "-Wunused-function"
  4553. #endif
  4554. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4555. FUNCTION_MAY_BE_UNUSED
  4556. static DIR *
  4557. mg_opendir(const struct mg_connection *conn, const char *name)
  4558. {
  4559. DIR *dir = NULL;
  4560. wchar_t wpath[W_PATH_MAX];
  4561. DWORD attrs;
  4562. if (name == NULL) {
  4563. SetLastError(ERROR_BAD_ARGUMENTS);
  4564. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4565. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4566. } else {
  4567. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4568. attrs = GetFileAttributesW(wpath);
  4569. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4570. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4571. (void)wcscat(wpath, L"\\*");
  4572. dir->handle = FindFirstFileW(wpath, &dir->info);
  4573. dir->result.d_name[0] = '\0';
  4574. } else {
  4575. mg_free(dir);
  4576. dir = NULL;
  4577. }
  4578. }
  4579. return dir;
  4580. }
  4581. FUNCTION_MAY_BE_UNUSED
  4582. static int
  4583. mg_closedir(DIR *dir)
  4584. {
  4585. int result = 0;
  4586. if (dir != NULL) {
  4587. if (dir->handle != INVALID_HANDLE_VALUE)
  4588. result = FindClose(dir->handle) ? 0 : -1;
  4589. mg_free(dir);
  4590. } else {
  4591. result = -1;
  4592. SetLastError(ERROR_BAD_ARGUMENTS);
  4593. }
  4594. return result;
  4595. }
  4596. FUNCTION_MAY_BE_UNUSED
  4597. static struct dirent *
  4598. mg_readdir(DIR *dir)
  4599. {
  4600. struct dirent *result = 0;
  4601. if (dir) {
  4602. if (dir->handle != INVALID_HANDLE_VALUE) {
  4603. result = &dir->result;
  4604. (void)WideCharToMultiByte(CP_UTF8,
  4605. 0,
  4606. dir->info.cFileName,
  4607. -1,
  4608. result->d_name,
  4609. sizeof(result->d_name),
  4610. NULL,
  4611. NULL);
  4612. if (!FindNextFileW(dir->handle, &dir->info)) {
  4613. (void)FindClose(dir->handle);
  4614. dir->handle = INVALID_HANDLE_VALUE;
  4615. }
  4616. } else {
  4617. SetLastError(ERROR_FILE_NOT_FOUND);
  4618. }
  4619. } else {
  4620. SetLastError(ERROR_BAD_ARGUMENTS);
  4621. }
  4622. return result;
  4623. }
  4624. #if !defined(HAVE_POLL)
  4625. #undef POLLIN
  4626. #undef POLLPRI
  4627. #undef POLLOUT
  4628. #define POLLIN (1) /* Data ready - read will not block. */
  4629. #define POLLPRI (2) /* Priority data ready. */
  4630. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4631. FUNCTION_MAY_BE_UNUSED
  4632. static int
  4633. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4634. {
  4635. struct timeval tv;
  4636. fd_set rset;
  4637. fd_set wset;
  4638. unsigned int i;
  4639. int result;
  4640. SOCKET maxfd = 0;
  4641. memset(&tv, 0, sizeof(tv));
  4642. tv.tv_sec = milliseconds / 1000;
  4643. tv.tv_usec = (milliseconds % 1000) * 1000;
  4644. FD_ZERO(&rset);
  4645. FD_ZERO(&wset);
  4646. for (i = 0; i < n; i++) {
  4647. if (pfd[i].events & POLLIN) {
  4648. FD_SET(pfd[i].fd, &rset);
  4649. }
  4650. if (pfd[i].events & POLLOUT) {
  4651. FD_SET(pfd[i].fd, &wset);
  4652. }
  4653. pfd[i].revents = 0;
  4654. if (pfd[i].fd > maxfd) {
  4655. maxfd = pfd[i].fd;
  4656. }
  4657. }
  4658. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4659. for (i = 0; i < n; i++) {
  4660. if (FD_ISSET(pfd[i].fd, &rset)) {
  4661. pfd[i].revents |= POLLIN;
  4662. }
  4663. if (FD_ISSET(pfd[i].fd, &wset)) {
  4664. pfd[i].revents |= POLLOUT;
  4665. }
  4666. }
  4667. }
  4668. /* We should subtract the time used in select from remaining
  4669. * "milliseconds", in particular if called from mg_poll with a
  4670. * timeout quantum.
  4671. * Unfortunately, the remaining time is not stored in "tv" in all
  4672. * implementations, so the result in "tv" must be considered undefined.
  4673. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4674. return result;
  4675. }
  4676. #endif /* HAVE_POLL */
  4677. #if defined(GCC_DIAGNOSTIC)
  4678. /* Enable unused function warning again */
  4679. #pragma GCC diagnostic pop
  4680. #endif
  4681. static void
  4682. set_close_on_exec(SOCKET sock,
  4683. const struct mg_connection *conn /* may be null */,
  4684. struct mg_context *ctx /* may be null */)
  4685. {
  4686. (void)conn; /* Unused. */
  4687. (void)ctx;
  4688. #if defined(_WIN32_WCE)
  4689. (void)sock;
  4690. #else
  4691. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4692. #endif
  4693. }
  4694. int
  4695. mg_start_thread(mg_thread_func_t f, void *p)
  4696. {
  4697. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4698. /* Compile-time option to control stack size, e.g.
  4699. * -DUSE_STACK_SIZE=16384
  4700. */
  4701. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4702. == ((uintptr_t)(-1L)))
  4703. ? -1
  4704. : 0);
  4705. #else
  4706. return (
  4707. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4708. ? -1
  4709. : 0);
  4710. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4711. }
  4712. /* Start a thread storing the thread context. */
  4713. static int
  4714. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4715. void *p,
  4716. pthread_t *threadidptr)
  4717. {
  4718. uintptr_t uip;
  4719. HANDLE threadhandle;
  4720. int result = -1;
  4721. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4722. threadhandle = (HANDLE)uip;
  4723. if ((uip != 0) && (threadidptr != NULL)) {
  4724. *threadidptr = threadhandle;
  4725. result = 0;
  4726. }
  4727. return result;
  4728. }
  4729. /* Wait for a thread to finish. */
  4730. static int
  4731. mg_join_thread(pthread_t threadid)
  4732. {
  4733. int result;
  4734. DWORD dwevent;
  4735. result = -1;
  4736. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4737. if (dwevent == WAIT_FAILED) {
  4738. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4739. } else {
  4740. if (dwevent == WAIT_OBJECT_0) {
  4741. CloseHandle(threadid);
  4742. result = 0;
  4743. }
  4744. }
  4745. return result;
  4746. }
  4747. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4748. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4749. /* Create substitutes for POSIX functions in Win32. */
  4750. #if defined(GCC_DIAGNOSTIC)
  4751. /* Show no warning in case system functions are not used. */
  4752. #pragma GCC diagnostic push
  4753. #pragma GCC diagnostic ignored "-Wunused-function"
  4754. #endif
  4755. FUNCTION_MAY_BE_UNUSED
  4756. static HANDLE
  4757. dlopen(const char *dll_name, int flags)
  4758. {
  4759. wchar_t wbuf[W_PATH_MAX];
  4760. (void)flags;
  4761. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4762. return LoadLibraryW(wbuf);
  4763. }
  4764. FUNCTION_MAY_BE_UNUSED
  4765. static int
  4766. dlclose(void *handle)
  4767. {
  4768. int result;
  4769. if (FreeLibrary((HMODULE)handle) != 0) {
  4770. result = 0;
  4771. } else {
  4772. result = -1;
  4773. }
  4774. return result;
  4775. }
  4776. #if defined(GCC_DIAGNOSTIC)
  4777. /* Enable unused function warning again */
  4778. #pragma GCC diagnostic pop
  4779. #endif
  4780. #endif
  4781. #if !defined(NO_CGI)
  4782. #define SIGKILL (0)
  4783. static int
  4784. kill(pid_t pid, int sig_num)
  4785. {
  4786. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4787. (void)CloseHandle((HANDLE)pid);
  4788. return 0;
  4789. }
  4790. #if !defined(WNOHANG)
  4791. #define WNOHANG (1)
  4792. #endif
  4793. static pid_t
  4794. waitpid(pid_t pid, int *status, int flags)
  4795. {
  4796. DWORD timeout = INFINITE;
  4797. DWORD waitres;
  4798. (void)status; /* Currently not used by any client here */
  4799. if ((flags | WNOHANG) == WNOHANG) {
  4800. timeout = 0;
  4801. }
  4802. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4803. if (waitres == WAIT_OBJECT_0) {
  4804. return pid;
  4805. }
  4806. if (waitres == WAIT_TIMEOUT) {
  4807. return 0;
  4808. }
  4809. return (pid_t)-1;
  4810. }
  4811. static void
  4812. trim_trailing_whitespaces(char *s)
  4813. {
  4814. char *e = s + strlen(s);
  4815. while ((e > s) && isspace((unsigned char)e[-1])) {
  4816. *(--e) = '\0';
  4817. }
  4818. }
  4819. static pid_t
  4820. spawn_process(struct mg_connection *conn,
  4821. const char *prog,
  4822. char *envblk,
  4823. char *envp[],
  4824. int fdin[2],
  4825. int fdout[2],
  4826. int fderr[2],
  4827. const char *dir)
  4828. {
  4829. HANDLE me;
  4830. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4831. cmdline[PATH_MAX], buf[PATH_MAX];
  4832. int truncated;
  4833. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4834. STARTUPINFOA si;
  4835. PROCESS_INFORMATION pi = {0};
  4836. (void)envp;
  4837. memset(&si, 0, sizeof(si));
  4838. si.cb = sizeof(si);
  4839. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4840. si.wShowWindow = SW_HIDE;
  4841. me = GetCurrentProcess();
  4842. DuplicateHandle(me,
  4843. (HANDLE)_get_osfhandle(fdin[0]),
  4844. me,
  4845. &si.hStdInput,
  4846. 0,
  4847. TRUE,
  4848. DUPLICATE_SAME_ACCESS);
  4849. DuplicateHandle(me,
  4850. (HANDLE)_get_osfhandle(fdout[1]),
  4851. me,
  4852. &si.hStdOutput,
  4853. 0,
  4854. TRUE,
  4855. DUPLICATE_SAME_ACCESS);
  4856. DuplicateHandle(me,
  4857. (HANDLE)_get_osfhandle(fderr[1]),
  4858. me,
  4859. &si.hStdError,
  4860. 0,
  4861. TRUE,
  4862. DUPLICATE_SAME_ACCESS);
  4863. /* Mark handles that should not be inherited. See
  4864. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4865. */
  4866. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4867. HANDLE_FLAG_INHERIT,
  4868. 0);
  4869. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4870. HANDLE_FLAG_INHERIT,
  4871. 0);
  4872. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4873. HANDLE_FLAG_INHERIT,
  4874. 0);
  4875. /* If CGI file is a script, try to read the interpreter line */
  4876. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4877. if (interp == NULL) {
  4878. buf[0] = buf[1] = '\0';
  4879. /* Read the first line of the script into the buffer */
  4880. mg_snprintf(
  4881. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4882. if (truncated) {
  4883. pi.hProcess = (pid_t)-1;
  4884. goto spawn_cleanup;
  4885. }
  4886. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4887. #if defined(MG_USE_OPEN_FILE)
  4888. p = (char *)file.access.membuf;
  4889. #else
  4890. p = (char *)NULL;
  4891. #endif
  4892. mg_fgets(buf, sizeof(buf), &file, &p);
  4893. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4894. buf[sizeof(buf) - 1] = '\0';
  4895. }
  4896. if ((buf[0] == '#') && (buf[1] == '!')) {
  4897. trim_trailing_whitespaces(buf + 2);
  4898. } else {
  4899. buf[2] = '\0';
  4900. }
  4901. interp = buf + 2;
  4902. }
  4903. if (interp[0] != '\0') {
  4904. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4905. interp = full_interp;
  4906. }
  4907. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4908. if (interp[0] != '\0') {
  4909. mg_snprintf(conn,
  4910. &truncated,
  4911. cmdline,
  4912. sizeof(cmdline),
  4913. "\"%s\" \"%s\\%s\"",
  4914. interp,
  4915. full_dir,
  4916. prog);
  4917. } else {
  4918. mg_snprintf(conn,
  4919. &truncated,
  4920. cmdline,
  4921. sizeof(cmdline),
  4922. "\"%s\\%s\"",
  4923. full_dir,
  4924. prog);
  4925. }
  4926. if (truncated) {
  4927. pi.hProcess = (pid_t)-1;
  4928. goto spawn_cleanup;
  4929. }
  4930. DEBUG_TRACE("Running [%s]", cmdline);
  4931. if (CreateProcessA(NULL,
  4932. cmdline,
  4933. NULL,
  4934. NULL,
  4935. TRUE,
  4936. CREATE_NEW_PROCESS_GROUP,
  4937. envblk,
  4938. NULL,
  4939. &si,
  4940. &pi)
  4941. == 0) {
  4942. mg_cry_internal(
  4943. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4944. pi.hProcess = (pid_t)-1;
  4945. /* goto spawn_cleanup; */
  4946. }
  4947. spawn_cleanup:
  4948. (void)CloseHandle(si.hStdOutput);
  4949. (void)CloseHandle(si.hStdError);
  4950. (void)CloseHandle(si.hStdInput);
  4951. if (pi.hThread != NULL) {
  4952. (void)CloseHandle(pi.hThread);
  4953. }
  4954. return (pid_t)pi.hProcess;
  4955. }
  4956. #endif /* !NO_CGI */
  4957. static int
  4958. set_blocking_mode(SOCKET sock)
  4959. {
  4960. unsigned long non_blocking = 0;
  4961. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4962. }
  4963. static int
  4964. set_non_blocking_mode(SOCKET sock)
  4965. {
  4966. unsigned long non_blocking = 1;
  4967. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4968. }
  4969. #else
  4970. #if !defined(NO_FILESYSTEMS)
  4971. static int
  4972. mg_stat(const struct mg_connection *conn,
  4973. const char *path,
  4974. struct mg_file_stat *filep)
  4975. {
  4976. struct stat st;
  4977. if (!filep) {
  4978. return 0;
  4979. }
  4980. memset(filep, 0, sizeof(*filep));
  4981. if (conn && is_file_in_memory(conn, path)) {
  4982. /* Quick fix (for 1.9.x): */
  4983. /* mg_stat must fill all fields, also for files in memory */
  4984. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4985. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4986. filep->size = tmp_file.stat.size;
  4987. filep->last_modified = time(NULL);
  4988. filep->location = 2;
  4989. /* TODO: remove legacy "files in memory" feature */
  4990. return 1;
  4991. }
  4992. if (0 == stat(path, &st)) {
  4993. filep->size = (uint64_t)(st.st_size);
  4994. filep->last_modified = st.st_mtime;
  4995. filep->is_directory = S_ISDIR(st.st_mode);
  4996. return 1;
  4997. }
  4998. return 0;
  4999. }
  5000. #endif /* NO_FILESYSTEMS */
  5001. static void
  5002. set_close_on_exec(int fd,
  5003. const struct mg_connection *conn /* may be null */,
  5004. struct mg_context *ctx /* may be null */)
  5005. {
  5006. #if defined(__ZEPHYR__)
  5007. (void)fd;
  5008. (void)conn;
  5009. (void)ctx;
  5010. #else
  5011. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5012. if (conn || ctx) {
  5013. struct mg_connection fc;
  5014. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5015. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5016. __func__,
  5017. strerror(ERRNO));
  5018. }
  5019. }
  5020. #endif
  5021. }
  5022. int
  5023. mg_start_thread(mg_thread_func_t func, void *param)
  5024. {
  5025. pthread_t thread_id;
  5026. pthread_attr_t attr;
  5027. int result;
  5028. (void)pthread_attr_init(&attr);
  5029. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5030. #if defined(__ZEPHYR__)
  5031. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5032. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5033. /* Compile-time option to control stack size,
  5034. * e.g. -DUSE_STACK_SIZE=16384 */
  5035. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5036. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5037. result = pthread_create(&thread_id, &attr, func, param);
  5038. pthread_attr_destroy(&attr);
  5039. return result;
  5040. }
  5041. /* Start a thread storing the thread context. */
  5042. static int
  5043. mg_start_thread_with_id(mg_thread_func_t func,
  5044. void *param,
  5045. pthread_t *threadidptr)
  5046. {
  5047. pthread_t thread_id;
  5048. pthread_attr_t attr;
  5049. int result;
  5050. (void)pthread_attr_init(&attr);
  5051. #if defined(__ZEPHYR__)
  5052. pthread_attr_setstack(&attr,
  5053. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5054. ZEPHYR_STACK_SIZE);
  5055. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5056. /* Compile-time option to control stack size,
  5057. * e.g. -DUSE_STACK_SIZE=16384 */
  5058. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5059. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5060. result = pthread_create(&thread_id, &attr, func, param);
  5061. pthread_attr_destroy(&attr);
  5062. if ((result == 0) && (threadidptr != NULL)) {
  5063. *threadidptr = thread_id;
  5064. }
  5065. return result;
  5066. }
  5067. /* Wait for a thread to finish. */
  5068. static int
  5069. mg_join_thread(pthread_t threadid)
  5070. {
  5071. int result;
  5072. result = pthread_join(threadid, NULL);
  5073. return result;
  5074. }
  5075. #if !defined(NO_CGI)
  5076. static pid_t
  5077. spawn_process(struct mg_connection *conn,
  5078. const char *prog,
  5079. char *envblk,
  5080. char *envp[],
  5081. int fdin[2],
  5082. int fdout[2],
  5083. int fderr[2],
  5084. const char *dir)
  5085. {
  5086. pid_t pid;
  5087. const char *interp;
  5088. (void)envblk;
  5089. if ((pid = fork()) == -1) {
  5090. /* Parent */
  5091. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5092. } else if (pid != 0) {
  5093. /* Make sure children close parent-side descriptors.
  5094. * The caller will close the child-side immediately. */
  5095. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5096. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5097. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5098. } else {
  5099. /* Child */
  5100. if (chdir(dir) != 0) {
  5101. mg_cry_internal(
  5102. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5103. } else if (dup2(fdin[0], 0) == -1) {
  5104. mg_cry_internal(conn,
  5105. "%s: dup2(%d, 0): %s",
  5106. __func__,
  5107. fdin[0],
  5108. strerror(ERRNO));
  5109. } else if (dup2(fdout[1], 1) == -1) {
  5110. mg_cry_internal(conn,
  5111. "%s: dup2(%d, 1): %s",
  5112. __func__,
  5113. fdout[1],
  5114. strerror(ERRNO));
  5115. } else if (dup2(fderr[1], 2) == -1) {
  5116. mg_cry_internal(conn,
  5117. "%s: dup2(%d, 2): %s",
  5118. __func__,
  5119. fderr[1],
  5120. strerror(ERRNO));
  5121. } else {
  5122. struct sigaction sa;
  5123. /* Keep stderr and stdout in two different pipes.
  5124. * Stdout will be sent back to the client,
  5125. * stderr should go into a server error log. */
  5126. (void)close(fdin[0]);
  5127. (void)close(fdout[1]);
  5128. (void)close(fderr[1]);
  5129. /* Close write end fdin and read end fdout and fderr */
  5130. (void)close(fdin[1]);
  5131. (void)close(fdout[0]);
  5132. (void)close(fderr[0]);
  5133. /* After exec, all signal handlers are restored to their default
  5134. * values, with one exception of SIGCHLD. According to
  5135. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5136. * will leave unchanged after exec if it was set to be ignored.
  5137. * Restore it to default action. */
  5138. memset(&sa, 0, sizeof(sa));
  5139. sa.sa_handler = SIG_DFL;
  5140. sigaction(SIGCHLD, &sa, NULL);
  5141. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5142. if (interp == NULL) {
  5143. (void)execle(prog, prog, NULL, envp);
  5144. mg_cry_internal(conn,
  5145. "%s: execle(%s): %s",
  5146. __func__,
  5147. prog,
  5148. strerror(ERRNO));
  5149. } else {
  5150. (void)execle(interp, interp, prog, NULL, envp);
  5151. mg_cry_internal(conn,
  5152. "%s: execle(%s %s): %s",
  5153. __func__,
  5154. interp,
  5155. prog,
  5156. strerror(ERRNO));
  5157. }
  5158. }
  5159. exit(EXIT_FAILURE);
  5160. }
  5161. return pid;
  5162. }
  5163. #endif /* !NO_CGI */
  5164. static int
  5165. set_non_blocking_mode(SOCKET sock)
  5166. {
  5167. int flags = fcntl(sock, F_GETFL, 0);
  5168. if (flags < 0) {
  5169. return -1;
  5170. }
  5171. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5172. return -1;
  5173. }
  5174. return 0;
  5175. }
  5176. static int
  5177. set_blocking_mode(SOCKET sock)
  5178. {
  5179. int flags = fcntl(sock, F_GETFL, 0);
  5180. if (flags < 0) {
  5181. return -1;
  5182. }
  5183. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5184. return -1;
  5185. }
  5186. return 0;
  5187. }
  5188. #endif /* _WIN32 / else */
  5189. /* End of initial operating system specific define block. */
  5190. /* Get a random number (independent of C rand function) */
  5191. static uint64_t
  5192. get_random(void)
  5193. {
  5194. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5195. static uint64_t lcg = 0; /* Linear congruential generator */
  5196. uint64_t now = mg_get_current_time_ns();
  5197. if (lfsr == 0) {
  5198. /* lfsr will be only 0 if has not been initialized,
  5199. * so this code is called only once. */
  5200. lfsr = mg_get_current_time_ns();
  5201. lcg = mg_get_current_time_ns();
  5202. } else {
  5203. /* Get the next step of both random number generators. */
  5204. lfsr = (lfsr >> 1)
  5205. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5206. << 63);
  5207. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5208. }
  5209. /* Combining two pseudo-random number generators and a high resolution
  5210. * part
  5211. * of the current server time will make it hard (impossible?) to guess
  5212. * the
  5213. * next number. */
  5214. return (lfsr ^ lcg ^ now);
  5215. }
  5216. static int
  5217. mg_poll(struct mg_pollfd *pfd,
  5218. unsigned int n,
  5219. int milliseconds,
  5220. volatile int *stop_server)
  5221. {
  5222. /* Call poll, but only for a maximum time of a few seconds.
  5223. * This will allow to stop the server after some seconds, instead
  5224. * of having to wait for a long socket timeout. */
  5225. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5226. do {
  5227. int result;
  5228. if (*stop_server) {
  5229. /* Shut down signal */
  5230. return -2;
  5231. }
  5232. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5233. ms_now = milliseconds;
  5234. }
  5235. result = poll(pfd, n, ms_now);
  5236. if (result != 0) {
  5237. /* Poll returned either success (1) or error (-1).
  5238. * Forward both to the caller. */
  5239. return result;
  5240. }
  5241. /* Poll returned timeout (0). */
  5242. if (milliseconds > 0) {
  5243. milliseconds -= ms_now;
  5244. }
  5245. } while (milliseconds != 0);
  5246. /* timeout: return 0 */
  5247. return 0;
  5248. }
  5249. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5250. * descriptor.
  5251. * Return value:
  5252. * >=0 .. number of bytes successfully written
  5253. * -1 .. timeout
  5254. * -2 .. error
  5255. */
  5256. static int
  5257. push_inner(struct mg_context *ctx,
  5258. FILE *fp,
  5259. SOCKET sock,
  5260. SSL *ssl,
  5261. const char *buf,
  5262. int len,
  5263. double timeout)
  5264. {
  5265. uint64_t start = 0, now = 0, timeout_ns = 0;
  5266. int n, err;
  5267. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5268. #if defined(_WIN32)
  5269. typedef int len_t;
  5270. #else
  5271. typedef size_t len_t;
  5272. #endif
  5273. if (timeout > 0) {
  5274. now = mg_get_current_time_ns();
  5275. start = now;
  5276. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5277. }
  5278. if (ctx == NULL) {
  5279. return -2;
  5280. }
  5281. #if defined(NO_SSL)
  5282. if (ssl) {
  5283. return -2;
  5284. }
  5285. #endif
  5286. /* Try to read until it succeeds, fails, times out, or the server
  5287. * shuts down. */
  5288. for (;;) {
  5289. #if !defined(NO_SSL)
  5290. if (ssl != NULL) {
  5291. n = SSL_write(ssl, buf, len);
  5292. if (n <= 0) {
  5293. err = SSL_get_error(ssl, n);
  5294. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5295. err = ERRNO;
  5296. } else if ((err == SSL_ERROR_WANT_READ)
  5297. || (err == SSL_ERROR_WANT_WRITE)) {
  5298. n = 0;
  5299. } else {
  5300. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5301. return -2;
  5302. }
  5303. } else {
  5304. err = 0;
  5305. }
  5306. } else
  5307. #endif
  5308. if (fp != NULL) {
  5309. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5310. if (ferror(fp)) {
  5311. n = -1;
  5312. err = ERRNO;
  5313. } else {
  5314. err = 0;
  5315. }
  5316. } else {
  5317. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5318. err = (n < 0) ? ERRNO : 0;
  5319. #if defined(_WIN32)
  5320. if (err == WSAEWOULDBLOCK) {
  5321. err = 0;
  5322. n = 0;
  5323. }
  5324. #else
  5325. if (err == EWOULDBLOCK) {
  5326. err = 0;
  5327. n = 0;
  5328. }
  5329. #endif
  5330. if (n < 0) {
  5331. /* shutdown of the socket at client side */
  5332. return -2;
  5333. }
  5334. }
  5335. if (ctx->stop_flag) {
  5336. return -2;
  5337. }
  5338. if ((n > 0) || ((n == 0) && (len == 0))) {
  5339. /* some data has been read, or no data was requested */
  5340. return n;
  5341. }
  5342. if (n < 0) {
  5343. /* socket error - check errno */
  5344. DEBUG_TRACE("send() failed, error %d", err);
  5345. /* TODO (mid): error handling depending on the error code.
  5346. * These codes are different between Windows and Linux.
  5347. * Currently there is no problem with failing send calls,
  5348. * if there is a reproducible situation, it should be
  5349. * investigated in detail.
  5350. */
  5351. return -2;
  5352. }
  5353. /* Only in case n=0 (timeout), repeat calling the write function */
  5354. /* If send failed, wait before retry */
  5355. if (fp != NULL) {
  5356. /* For files, just wait a fixed time.
  5357. * Maybe it helps, maybe not. */
  5358. mg_sleep(5);
  5359. } else {
  5360. /* For sockets, wait for the socket using poll */
  5361. struct mg_pollfd pfd[1];
  5362. int pollres;
  5363. pfd[0].fd = sock;
  5364. pfd[0].events = POLLOUT;
  5365. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5366. if (ctx->stop_flag) {
  5367. return -2;
  5368. }
  5369. if (pollres > 0) {
  5370. continue;
  5371. }
  5372. }
  5373. if (timeout > 0) {
  5374. now = mg_get_current_time_ns();
  5375. if ((now - start) > timeout_ns) {
  5376. /* Timeout */
  5377. break;
  5378. }
  5379. }
  5380. }
  5381. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5382. used */
  5383. return -1;
  5384. }
  5385. static int
  5386. push_all(struct mg_context *ctx,
  5387. FILE *fp,
  5388. SOCKET sock,
  5389. SSL *ssl,
  5390. const char *buf,
  5391. int len)
  5392. {
  5393. double timeout = -1.0;
  5394. int n, nwritten = 0;
  5395. if (ctx == NULL) {
  5396. return -1;
  5397. }
  5398. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5399. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5400. }
  5401. while ((len > 0) && (ctx->stop_flag == 0)) {
  5402. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5403. if (n < 0) {
  5404. if (nwritten == 0) {
  5405. nwritten = -1; /* Propagate the error */
  5406. }
  5407. break;
  5408. } else if (n == 0) {
  5409. break; /* No more data to write */
  5410. } else {
  5411. nwritten += n;
  5412. len -= n;
  5413. }
  5414. }
  5415. return nwritten;
  5416. }
  5417. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5418. * Return value:
  5419. * >=0 .. number of bytes successfully read
  5420. * -1 .. timeout
  5421. * -2 .. error
  5422. */
  5423. static int
  5424. pull_inner(FILE *fp,
  5425. struct mg_connection *conn,
  5426. char *buf,
  5427. int len,
  5428. double timeout)
  5429. {
  5430. int nread, err = 0;
  5431. #if defined(_WIN32)
  5432. typedef int len_t;
  5433. #else
  5434. typedef size_t len_t;
  5435. #endif
  5436. #if !defined(NO_SSL)
  5437. int ssl_pending;
  5438. #endif
  5439. /* We need an additional wait loop around this, because in some cases
  5440. * with TLSwe may get data from the socket but not from SSL_read.
  5441. * In this case we need to repeat at least once.
  5442. */
  5443. if (fp != NULL) {
  5444. #if !defined(_WIN32_WCE)
  5445. /* Use read() instead of fread(), because if we're reading from the
  5446. * CGI pipe, fread() may block until IO buffer is filled up. We
  5447. * cannot afford to block and must pass all read bytes immediately
  5448. * to the client. */
  5449. nread = (int)read(fileno(fp), buf, (size_t)len);
  5450. #else
  5451. /* WinCE does not support CGI pipes */
  5452. nread = (int)fread(buf, 1, (size_t)len, fp);
  5453. #endif
  5454. err = (nread < 0) ? ERRNO : 0;
  5455. if ((nread == 0) && (len > 0)) {
  5456. /* Should get data, but got EOL */
  5457. return -2;
  5458. }
  5459. #if !defined(NO_SSL)
  5460. } else if ((conn->ssl != NULL)
  5461. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5462. /* We already know there is no more data buffered in conn->buf
  5463. * but there is more available in the SSL layer. So don't poll
  5464. * conn->client.sock yet. */
  5465. if (ssl_pending > len) {
  5466. ssl_pending = len;
  5467. }
  5468. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5469. if (nread <= 0) {
  5470. err = SSL_get_error(conn->ssl, nread);
  5471. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5472. err = ERRNO;
  5473. } else if ((err == SSL_ERROR_WANT_READ)
  5474. || (err == SSL_ERROR_WANT_WRITE)) {
  5475. nread = 0;
  5476. } else {
  5477. /* All errors should return -2 */
  5478. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5479. return -2;
  5480. }
  5481. ERR_clear_error();
  5482. } else {
  5483. err = 0;
  5484. }
  5485. } else if (conn->ssl != NULL) {
  5486. struct mg_pollfd pfd[1];
  5487. int pollres;
  5488. pfd[0].fd = conn->client.sock;
  5489. pfd[0].events = POLLIN;
  5490. pollres = mg_poll(pfd,
  5491. 1,
  5492. (int)(timeout * 1000.0),
  5493. &(conn->phys_ctx->stop_flag));
  5494. if (conn->phys_ctx->stop_flag) {
  5495. return -2;
  5496. }
  5497. if (pollres > 0) {
  5498. nread = SSL_read(conn->ssl, buf, len);
  5499. if (nread <= 0) {
  5500. err = SSL_get_error(conn->ssl, nread);
  5501. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5502. err = ERRNO;
  5503. } else if ((err == SSL_ERROR_WANT_READ)
  5504. || (err == SSL_ERROR_WANT_WRITE)) {
  5505. nread = 0;
  5506. } else {
  5507. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5508. return -2;
  5509. }
  5510. } else {
  5511. err = 0;
  5512. }
  5513. ERR_clear_error();
  5514. } else if (pollres < 0) {
  5515. /* Error */
  5516. return -2;
  5517. } else {
  5518. /* pollres = 0 means timeout */
  5519. nread = 0;
  5520. }
  5521. #endif
  5522. } else {
  5523. struct mg_pollfd pfd[1];
  5524. int pollres;
  5525. pfd[0].fd = conn->client.sock;
  5526. pfd[0].events = POLLIN;
  5527. pollres = mg_poll(pfd,
  5528. 1,
  5529. (int)(timeout * 1000.0),
  5530. &(conn->phys_ctx->stop_flag));
  5531. if (conn->phys_ctx->stop_flag) {
  5532. return -2;
  5533. }
  5534. if (pollres > 0) {
  5535. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5536. err = (nread < 0) ? ERRNO : 0;
  5537. if (nread <= 0) {
  5538. /* shutdown of the socket at client side */
  5539. return -2;
  5540. }
  5541. } else if (pollres < 0) {
  5542. /* error callint poll */
  5543. return -2;
  5544. } else {
  5545. /* pollres = 0 means timeout */
  5546. nread = 0;
  5547. }
  5548. }
  5549. if (conn->phys_ctx->stop_flag) {
  5550. return -2;
  5551. }
  5552. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5553. /* some data has been read, or no data was requested */
  5554. return nread;
  5555. }
  5556. if (nread < 0) {
  5557. /* socket error - check errno */
  5558. #if defined(_WIN32)
  5559. if (err == WSAEWOULDBLOCK) {
  5560. /* TODO (low): check if this is still required */
  5561. /* standard case if called from close_socket_gracefully */
  5562. return -2;
  5563. } else if (err == WSAETIMEDOUT) {
  5564. /* TODO (low): check if this is still required */
  5565. /* timeout is handled by the while loop */
  5566. return 0;
  5567. } else if (err == WSAECONNABORTED) {
  5568. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5569. return -2;
  5570. } else {
  5571. DEBUG_TRACE("recv() failed, error %d", err);
  5572. return -2;
  5573. }
  5574. #else
  5575. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5576. * if the timeout is reached and if the socket was set to non-
  5577. * blocking in close_socket_gracefully, so we can not distinguish
  5578. * here. We have to wait for the timeout in both cases for now.
  5579. */
  5580. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5581. /* TODO (low): check if this is still required */
  5582. /* EAGAIN/EWOULDBLOCK:
  5583. * standard case if called from close_socket_gracefully
  5584. * => should return -1 */
  5585. /* or timeout occurred
  5586. * => the code must stay in the while loop */
  5587. /* EINTR can be generated on a socket with a timeout set even
  5588. * when SA_RESTART is effective for all relevant signals
  5589. * (see signal(7)).
  5590. * => stay in the while loop */
  5591. } else {
  5592. DEBUG_TRACE("recv() failed, error %d", err);
  5593. return -2;
  5594. }
  5595. #endif
  5596. }
  5597. /* Timeout occurred, but no data available. */
  5598. return -1;
  5599. }
  5600. static int
  5601. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5602. {
  5603. int n, nread = 0;
  5604. double timeout = -1.0;
  5605. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5606. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5607. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5608. }
  5609. if (timeout >= 0.0) {
  5610. start_time = mg_get_current_time_ns();
  5611. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5612. }
  5613. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5614. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5615. if (n == -2) {
  5616. if (nread == 0) {
  5617. nread = -1; /* Propagate the error */
  5618. }
  5619. break;
  5620. } else if (n == -1) {
  5621. /* timeout */
  5622. if (timeout >= 0.0) {
  5623. now = mg_get_current_time_ns();
  5624. if ((now - start_time) <= timeout_ns) {
  5625. continue;
  5626. }
  5627. }
  5628. break;
  5629. } else if (n == 0) {
  5630. break; /* No more data to read */
  5631. } else {
  5632. nread += n;
  5633. len -= n;
  5634. }
  5635. }
  5636. return nread;
  5637. }
  5638. static void
  5639. discard_unread_request_data(struct mg_connection *conn)
  5640. {
  5641. char buf[MG_BUF_LEN];
  5642. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5643. ;
  5644. }
  5645. static int
  5646. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5647. {
  5648. int64_t content_len, n, buffered_len, nread;
  5649. int64_t len64 =
  5650. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5651. * int, we may not read more
  5652. * bytes */
  5653. const char *body;
  5654. if (conn == NULL) {
  5655. return 0;
  5656. }
  5657. /* If Content-Length is not set for a response with body data,
  5658. * we do not know in advance how much data should be read. */
  5659. content_len = conn->content_len;
  5660. if (content_len < 0) {
  5661. /* The body data is completed when the connection is closed. */
  5662. content_len = INT64_MAX;
  5663. }
  5664. nread = 0;
  5665. if (conn->consumed_content < content_len) {
  5666. /* Adjust number of bytes to read. */
  5667. int64_t left_to_read = content_len - conn->consumed_content;
  5668. if (left_to_read < len64) {
  5669. /* Do not read more than the total content length of the
  5670. * request.
  5671. */
  5672. len64 = left_to_read;
  5673. }
  5674. /* Return buffered data */
  5675. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5676. - conn->consumed_content;
  5677. if (buffered_len > 0) {
  5678. if (len64 < buffered_len) {
  5679. buffered_len = len64;
  5680. }
  5681. body = conn->buf + conn->request_len + conn->consumed_content;
  5682. memcpy(buf, body, (size_t)buffered_len);
  5683. len64 -= buffered_len;
  5684. conn->consumed_content += buffered_len;
  5685. nread += buffered_len;
  5686. buf = (char *)buf + buffered_len;
  5687. }
  5688. /* We have returned all buffered data. Read new data from the remote
  5689. * socket.
  5690. */
  5691. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5692. conn->consumed_content += n;
  5693. nread += n;
  5694. } else {
  5695. nread = ((nread > 0) ? nread : n);
  5696. }
  5697. }
  5698. return (int)nread;
  5699. }
  5700. int
  5701. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5702. {
  5703. if (len > INT_MAX) {
  5704. len = INT_MAX;
  5705. }
  5706. if (conn == NULL) {
  5707. return 0;
  5708. }
  5709. if (conn->is_chunked) {
  5710. size_t all_read = 0;
  5711. while (len > 0) {
  5712. if (conn->is_chunked >= 3) {
  5713. /* No more data left to read */
  5714. return 0;
  5715. }
  5716. if (conn->is_chunked != 1) {
  5717. /* Has error */
  5718. return -1;
  5719. }
  5720. if (conn->consumed_content != conn->content_len) {
  5721. /* copy from the current chunk */
  5722. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5723. if (read_ret < 1) {
  5724. /* read error */
  5725. conn->is_chunked = 2;
  5726. return -1;
  5727. }
  5728. all_read += (size_t)read_ret;
  5729. len -= (size_t)read_ret;
  5730. if (conn->consumed_content == conn->content_len) {
  5731. /* Add data bytes in the current chunk have been read,
  5732. * so we are expecting \r\n now. */
  5733. char x[2];
  5734. conn->content_len += 2;
  5735. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5736. || (x[1] != '\n')) {
  5737. /* Protocol violation */
  5738. conn->is_chunked = 2;
  5739. return -1;
  5740. }
  5741. }
  5742. } else {
  5743. /* fetch a new chunk */
  5744. size_t i;
  5745. char lenbuf[64];
  5746. char *end = NULL;
  5747. unsigned long chunkSize = 0;
  5748. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5749. conn->content_len++;
  5750. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5751. lenbuf[i] = 0;
  5752. }
  5753. if ((i > 0) && (lenbuf[i] == '\r')
  5754. && (lenbuf[i - 1] != '\r')) {
  5755. continue;
  5756. }
  5757. if ((i > 1) && (lenbuf[i] == '\n')
  5758. && (lenbuf[i - 1] == '\r')) {
  5759. lenbuf[i + 1] = 0;
  5760. chunkSize = strtoul(lenbuf, &end, 16);
  5761. if (chunkSize == 0) {
  5762. /* regular end of content */
  5763. conn->is_chunked = 3;
  5764. }
  5765. break;
  5766. }
  5767. if (!isxdigit((unsigned char)lenbuf[i])) {
  5768. /* illegal character for chunk length */
  5769. conn->is_chunked = 2;
  5770. return -1;
  5771. }
  5772. }
  5773. if ((end == NULL) || (*end != '\r')) {
  5774. /* chunksize not set correctly */
  5775. conn->is_chunked = 2;
  5776. return -1;
  5777. }
  5778. if (chunkSize == 0) {
  5779. /* try discarding trailer for keep-alive */
  5780. conn->content_len += 2;
  5781. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5782. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5783. conn->is_chunked = 4;
  5784. }
  5785. break;
  5786. }
  5787. /* append a new chunk */
  5788. conn->content_len += chunkSize;
  5789. }
  5790. }
  5791. return (int)all_read;
  5792. }
  5793. return mg_read_inner(conn, buf, len);
  5794. }
  5795. int
  5796. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5797. {
  5798. time_t now;
  5799. int n, total, allowed;
  5800. if (conn == NULL) {
  5801. return 0;
  5802. }
  5803. if (len > INT_MAX) {
  5804. return -1;
  5805. }
  5806. if (conn->throttle > 0) {
  5807. if ((now = time(NULL)) != conn->last_throttle_time) {
  5808. conn->last_throttle_time = now;
  5809. conn->last_throttle_bytes = 0;
  5810. }
  5811. allowed = conn->throttle - conn->last_throttle_bytes;
  5812. if (allowed > (int)len) {
  5813. allowed = (int)len;
  5814. }
  5815. if ((total = push_all(conn->phys_ctx,
  5816. NULL,
  5817. conn->client.sock,
  5818. conn->ssl,
  5819. (const char *)buf,
  5820. allowed))
  5821. == allowed) {
  5822. buf = (const char *)buf + total;
  5823. conn->last_throttle_bytes += total;
  5824. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5825. allowed = (conn->throttle > ((int)len - total))
  5826. ? (int)len - total
  5827. : conn->throttle;
  5828. if ((n = push_all(conn->phys_ctx,
  5829. NULL,
  5830. conn->client.sock,
  5831. conn->ssl,
  5832. (const char *)buf,
  5833. allowed))
  5834. != allowed) {
  5835. break;
  5836. }
  5837. sleep(1);
  5838. conn->last_throttle_bytes = allowed;
  5839. conn->last_throttle_time = time(NULL);
  5840. buf = (const char *)buf + n;
  5841. total += n;
  5842. }
  5843. }
  5844. } else {
  5845. total = push_all(conn->phys_ctx,
  5846. NULL,
  5847. conn->client.sock,
  5848. conn->ssl,
  5849. (const char *)buf,
  5850. (int)len);
  5851. }
  5852. if (total > 0) {
  5853. conn->num_bytes_sent += total;
  5854. }
  5855. return total;
  5856. }
  5857. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5858. int
  5859. mg_send_chunk(struct mg_connection *conn,
  5860. const char *chunk,
  5861. unsigned int chunk_len)
  5862. {
  5863. char lenbuf[16];
  5864. size_t lenbuf_len;
  5865. int ret;
  5866. int t;
  5867. /* First store the length information in a text buffer. */
  5868. sprintf(lenbuf, "%x\r\n", chunk_len);
  5869. lenbuf_len = strlen(lenbuf);
  5870. /* Then send length information, chunk and terminating \r\n. */
  5871. ret = mg_write(conn, lenbuf, lenbuf_len);
  5872. if (ret != (int)lenbuf_len) {
  5873. return -1;
  5874. }
  5875. t = ret;
  5876. ret = mg_write(conn, chunk, chunk_len);
  5877. if (ret != (int)chunk_len) {
  5878. return -1;
  5879. }
  5880. t += ret;
  5881. ret = mg_write(conn, "\r\n", 2);
  5882. if (ret != 2) {
  5883. return -1;
  5884. }
  5885. t += ret;
  5886. return t;
  5887. }
  5888. #if defined(GCC_DIAGNOSTIC)
  5889. /* This block forwards format strings to printf implementations,
  5890. * so we need to disable the format-nonliteral warning. */
  5891. #pragma GCC diagnostic push
  5892. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5893. #endif
  5894. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5895. static int
  5896. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5897. {
  5898. va_list ap_copy;
  5899. size_t size = MG_BUF_LEN / 4;
  5900. int len = -1;
  5901. *buf = NULL;
  5902. while (len < 0) {
  5903. if (*buf) {
  5904. mg_free(*buf);
  5905. }
  5906. size *= 4;
  5907. *buf = (char *)mg_malloc(size);
  5908. if (!*buf) {
  5909. break;
  5910. }
  5911. va_copy(ap_copy, ap);
  5912. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5913. va_end(ap_copy);
  5914. (*buf)[size - 1] = 0;
  5915. }
  5916. return len;
  5917. }
  5918. /* Print message to buffer. If buffer is large enough to hold the message,
  5919. * return buffer. If buffer is to small, allocate large enough buffer on
  5920. * heap,
  5921. * and return allocated buffer. */
  5922. static int
  5923. alloc_vprintf(char **out_buf,
  5924. char *prealloc_buf,
  5925. size_t prealloc_size,
  5926. const char *fmt,
  5927. va_list ap)
  5928. {
  5929. va_list ap_copy;
  5930. int len;
  5931. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5932. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5933. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5934. * Therefore, we make two passes: on first pass, get required message
  5935. * length.
  5936. * On second pass, actually print the message. */
  5937. va_copy(ap_copy, ap);
  5938. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5939. va_end(ap_copy);
  5940. if (len < 0) {
  5941. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5942. * Switch to alternative code path that uses incremental
  5943. * allocations.
  5944. */
  5945. va_copy(ap_copy, ap);
  5946. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5947. va_end(ap_copy);
  5948. } else if ((size_t)(len) >= prealloc_size) {
  5949. /* The pre-allocated buffer not large enough. */
  5950. /* Allocate a new buffer. */
  5951. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5952. if (!*out_buf) {
  5953. /* Allocation failed. Return -1 as "out of memory" error. */
  5954. return -1;
  5955. }
  5956. /* Buffer allocation successful. Store the string there. */
  5957. va_copy(ap_copy, ap);
  5958. IGNORE_UNUSED_RESULT(
  5959. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5960. va_end(ap_copy);
  5961. } else {
  5962. /* The pre-allocated buffer is large enough.
  5963. * Use it to store the string and return the address. */
  5964. va_copy(ap_copy, ap);
  5965. IGNORE_UNUSED_RESULT(
  5966. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5967. va_end(ap_copy);
  5968. *out_buf = prealloc_buf;
  5969. }
  5970. return len;
  5971. }
  5972. #if defined(GCC_DIAGNOSTIC)
  5973. /* Enable format-nonliteral warning again. */
  5974. #pragma GCC diagnostic pop
  5975. #endif
  5976. static int
  5977. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5978. {
  5979. char mem[MG_BUF_LEN];
  5980. char *buf = NULL;
  5981. int len;
  5982. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5983. len = mg_write(conn, buf, (size_t)len);
  5984. }
  5985. if (buf != mem) {
  5986. mg_free(buf);
  5987. }
  5988. return len;
  5989. }
  5990. int
  5991. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5992. {
  5993. va_list ap;
  5994. int result;
  5995. va_start(ap, fmt);
  5996. result = mg_vprintf(conn, fmt, ap);
  5997. va_end(ap);
  5998. return result;
  5999. }
  6000. int
  6001. mg_url_decode(const char *src,
  6002. int src_len,
  6003. char *dst,
  6004. int dst_len,
  6005. int is_form_url_encoded)
  6006. {
  6007. int i, j, a, b;
  6008. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  6009. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  6010. if ((i < src_len - 2) && (src[i] == '%')
  6011. && isxdigit((unsigned char)src[i + 1])
  6012. && isxdigit((unsigned char)src[i + 2])) {
  6013. a = tolower((unsigned char)src[i + 1]);
  6014. b = tolower((unsigned char)src[i + 2]);
  6015. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6016. i += 2;
  6017. } else if (is_form_url_encoded && (src[i] == '+')) {
  6018. dst[j] = ' ';
  6019. } else {
  6020. dst[j] = src[i];
  6021. }
  6022. }
  6023. dst[j] = '\0'; /* Null-terminate the destination */
  6024. return (i >= src_len) ? j : -1;
  6025. }
  6026. int
  6027. mg_get_var(const char *data,
  6028. size_t data_len,
  6029. const char *name,
  6030. char *dst,
  6031. size_t dst_len)
  6032. {
  6033. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6034. }
  6035. int
  6036. mg_get_var2(const char *data,
  6037. size_t data_len,
  6038. const char *name,
  6039. char *dst,
  6040. size_t dst_len,
  6041. size_t occurrence)
  6042. {
  6043. const char *p, *e, *s;
  6044. size_t name_len;
  6045. int len;
  6046. if ((dst == NULL) || (dst_len == 0)) {
  6047. len = -2;
  6048. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6049. len = -1;
  6050. dst[0] = '\0';
  6051. } else {
  6052. name_len = strlen(name);
  6053. e = data + data_len;
  6054. len = -1;
  6055. dst[0] = '\0';
  6056. /* data is "var1=val1&var2=val2...". Find variable first */
  6057. for (p = data; p + name_len < e; p++) {
  6058. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6059. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6060. /* Point p to variable value */
  6061. p += name_len + 1;
  6062. /* Point s to the end of the value */
  6063. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6064. if (s == NULL) {
  6065. s = e;
  6066. }
  6067. DEBUG_ASSERT(s >= p);
  6068. if (s < p) {
  6069. return -3;
  6070. }
  6071. /* Decode variable into destination buffer */
  6072. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6073. /* Redirect error code from -1 to -2 (destination buffer too
  6074. * small). */
  6075. if (len == -1) {
  6076. len = -2;
  6077. }
  6078. break;
  6079. }
  6080. }
  6081. }
  6082. return len;
  6083. }
  6084. /* HCP24: some changes to compare hole var_name */
  6085. int
  6086. mg_get_cookie(const char *cookie_header,
  6087. const char *var_name,
  6088. char *dst,
  6089. size_t dst_size)
  6090. {
  6091. const char *s, *p, *end;
  6092. int name_len, len = -1;
  6093. if ((dst == NULL) || (dst_size == 0)) {
  6094. return -2;
  6095. }
  6096. dst[0] = '\0';
  6097. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6098. return -1;
  6099. }
  6100. name_len = (int)strlen(var_name);
  6101. end = s + strlen(s);
  6102. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6103. if (s[name_len] == '=') {
  6104. /* HCP24: now check is it a substring or a full cookie name */
  6105. if ((s == cookie_header) || (s[-1] == ' ')) {
  6106. s += name_len + 1;
  6107. if ((p = strchr(s, ' ')) == NULL) {
  6108. p = end;
  6109. }
  6110. if (p[-1] == ';') {
  6111. p--;
  6112. }
  6113. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6114. s++;
  6115. p--;
  6116. }
  6117. if ((size_t)(p - s) < dst_size) {
  6118. len = (int)(p - s);
  6119. mg_strlcpy(dst, s, (size_t)len + 1);
  6120. } else {
  6121. len = -3;
  6122. }
  6123. break;
  6124. }
  6125. }
  6126. }
  6127. return len;
  6128. }
  6129. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6130. static void
  6131. base64_encode(const unsigned char *src, int src_len, char *dst)
  6132. {
  6133. static const char *b64 =
  6134. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6135. int i, j, a, b, c;
  6136. for (i = j = 0; i < src_len; i += 3) {
  6137. a = src[i];
  6138. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6139. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6140. dst[j++] = b64[a >> 2];
  6141. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6142. if (i + 1 < src_len) {
  6143. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6144. }
  6145. if (i + 2 < src_len) {
  6146. dst[j++] = b64[c & 63];
  6147. }
  6148. }
  6149. while (j % 4 != 0) {
  6150. dst[j++] = '=';
  6151. }
  6152. dst[j++] = '\0';
  6153. }
  6154. #endif
  6155. #if defined(USE_LUA)
  6156. static unsigned char
  6157. b64reverse(char letter)
  6158. {
  6159. if ((letter >= 'A') && (letter <= 'Z')) {
  6160. return letter - 'A';
  6161. }
  6162. if ((letter >= 'a') && (letter <= 'z')) {
  6163. return letter - 'a' + 26;
  6164. }
  6165. if ((letter >= '0') && (letter <= '9')) {
  6166. return letter - '0' + 52;
  6167. }
  6168. if (letter == '+') {
  6169. return 62;
  6170. }
  6171. if (letter == '/') {
  6172. return 63;
  6173. }
  6174. if (letter == '=') {
  6175. return 255; /* normal end */
  6176. }
  6177. return 254; /* error */
  6178. }
  6179. static int
  6180. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6181. {
  6182. int i;
  6183. unsigned char a, b, c, d;
  6184. *dst_len = 0;
  6185. for (i = 0; i < src_len; i += 4) {
  6186. a = b64reverse(src[i]);
  6187. if (a >= 254) {
  6188. return i;
  6189. }
  6190. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6191. if (b >= 254) {
  6192. return i + 1;
  6193. }
  6194. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6195. if (c == 254) {
  6196. return i + 2;
  6197. }
  6198. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6199. if (d == 254) {
  6200. return i + 3;
  6201. }
  6202. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6203. if (c != 255) {
  6204. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6205. if (d != 255) {
  6206. dst[(*dst_len)++] = (c << 6) + d;
  6207. }
  6208. }
  6209. }
  6210. return -1;
  6211. }
  6212. #endif
  6213. static int
  6214. is_put_or_delete_method(const struct mg_connection *conn)
  6215. {
  6216. if (conn) {
  6217. const char *s = conn->request_info.request_method;
  6218. return (s != NULL)
  6219. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6220. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6221. }
  6222. return 0;
  6223. }
  6224. #if !defined(NO_FILES)
  6225. static int
  6226. extention_matches_script(
  6227. struct mg_connection *conn, /* in: request (must be valid) */
  6228. const char *filename /* in: filename (must be valid) */
  6229. )
  6230. {
  6231. #if !defined(NO_CGI)
  6232. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6233. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6234. filename)
  6235. > 0) {
  6236. return 1;
  6237. }
  6238. #endif
  6239. #if defined(USE_LUA)
  6240. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6241. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6242. filename)
  6243. > 0) {
  6244. return 1;
  6245. }
  6246. #endif
  6247. #if defined(USE_DUKTAPE)
  6248. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6249. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6250. filename)
  6251. > 0) {
  6252. return 1;
  6253. }
  6254. #endif
  6255. /* filename and conn could be unused, if all preocessor conditions
  6256. * are false (no script language supported). */
  6257. (void)filename;
  6258. (void)conn;
  6259. return 0;
  6260. }
  6261. /* For given directory path, substitute it to valid index file.
  6262. * Return 1 if index file has been found, 0 if not found.
  6263. * If the file is found, it's stats is returned in stp. */
  6264. static int
  6265. substitute_index_file(struct mg_connection *conn,
  6266. char *path,
  6267. size_t path_len,
  6268. struct mg_file_stat *filestat)
  6269. {
  6270. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6271. struct vec filename_vec;
  6272. size_t n = strlen(path);
  6273. int found = 0;
  6274. /* The 'path' given to us points to the directory. Remove all trailing
  6275. * directory separator characters from the end of the path, and
  6276. * then append single directory separator character. */
  6277. while ((n > 0) && (path[n - 1] == '/')) {
  6278. n--;
  6279. }
  6280. path[n] = '/';
  6281. /* Traverse index files list. For each entry, append it to the given
  6282. * path and see if the file exists. If it exists, break the loop */
  6283. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6284. /* Ignore too long entries that may overflow path buffer */
  6285. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6286. continue;
  6287. }
  6288. /* Prepare full path to the index file */
  6289. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6290. /* Does it exist? */
  6291. if (mg_stat(conn, path, filestat)) {
  6292. /* Yes it does, break the loop */
  6293. found = 1;
  6294. break;
  6295. }
  6296. }
  6297. /* If no index file exists, restore directory path */
  6298. if (!found) {
  6299. path[n] = '\0';
  6300. }
  6301. return found;
  6302. }
  6303. #endif
  6304. static void
  6305. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6306. char *filename, /* out: filename */
  6307. size_t filename_buf_len, /* in: size of filename buffer */
  6308. struct mg_file_stat *filestat, /* out: file status structure */
  6309. int *is_found, /* out: file found (directly) */
  6310. int *is_script_resource, /* out: handled by a script? */
  6311. int *is_websocket_request, /* out: websocket connetion? */
  6312. int *is_put_or_delete_request /* out: put/delete a file? */
  6313. )
  6314. {
  6315. char const *accept_encoding;
  6316. #if !defined(NO_FILES)
  6317. const char *uri = conn->request_info.local_uri;
  6318. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6319. const char *rewrite;
  6320. struct vec a, b;
  6321. ptrdiff_t match_len;
  6322. char gz_path[PATH_MAX];
  6323. int truncated;
  6324. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6325. char *tmp_str;
  6326. size_t tmp_str_len, sep_pos;
  6327. int allow_substitute_script_subresources;
  6328. #endif
  6329. #else
  6330. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6331. #endif
  6332. /* Step 1: Set all initially unknown outputs to zero */
  6333. memset(filestat, 0, sizeof(*filestat));
  6334. *filename = 0;
  6335. *is_found = 0;
  6336. *is_script_resource = 0;
  6337. /* Step 2: Check if the request attempts to modify the file system */
  6338. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6339. /* Step 3: Check if it is a websocket request, and modify the document
  6340. * root if required */
  6341. #if defined(USE_WEBSOCKET)
  6342. *is_websocket_request = is_websocket_protocol(conn);
  6343. #if !defined(NO_FILES)
  6344. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6345. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6346. }
  6347. #endif /* !NO_FILES */
  6348. #else /* USE_WEBSOCKET */
  6349. *is_websocket_request = 0;
  6350. #endif /* USE_WEBSOCKET */
  6351. /* Step 4: Check if gzip encoded response is allowed */
  6352. conn->accept_gzip = 0;
  6353. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6354. if (strstr(accept_encoding, "gzip") != NULL) {
  6355. conn->accept_gzip = 1;
  6356. }
  6357. }
  6358. #if !defined(NO_FILES)
  6359. /* Step 5: If there is no root directory, don't look for files. */
  6360. /* Note that root == NULL is a regular use case here. This occurs,
  6361. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6362. * config is not required. */
  6363. if (root == NULL) {
  6364. /* all file related outputs have already been set to 0, just return
  6365. */
  6366. return;
  6367. }
  6368. /* Step 6: Determine the local file path from the root path and the
  6369. * request uri. */
  6370. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6371. * part of the path one byte on the right. */
  6372. mg_snprintf(
  6373. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6374. if (truncated) {
  6375. goto interpret_cleanup;
  6376. }
  6377. /* Step 7: URI rewriting */
  6378. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6379. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6380. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6381. mg_snprintf(conn,
  6382. &truncated,
  6383. filename,
  6384. filename_buf_len - 1,
  6385. "%.*s%s",
  6386. (int)b.len,
  6387. b.ptr,
  6388. uri + match_len);
  6389. break;
  6390. }
  6391. }
  6392. if (truncated) {
  6393. goto interpret_cleanup;
  6394. }
  6395. /* Step 8: Check if the file exists at the server */
  6396. /* Local file path and name, corresponding to requested URI
  6397. * is now stored in "filename" variable. */
  6398. if (mg_stat(conn, filename, filestat)) {
  6399. int uri_len = (int)strlen(uri);
  6400. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6401. /* 8.1: File exists. */
  6402. *is_found = 1;
  6403. /* 8.2: Check if it is a script type. */
  6404. if (extention_matches_script(conn, filename)) {
  6405. /* The request addresses a CGI resource, Lua script or
  6406. * server-side javascript.
  6407. * The URI corresponds to the script itself (like
  6408. * /path/script.cgi), and there is no additional resource
  6409. * path (like /path/script.cgi/something).
  6410. * Requests that modify (replace or delete) a resource, like
  6411. * PUT and DELETE requests, should replace/delete the script
  6412. * file.
  6413. * Requests that read or write from/to a resource, like GET and
  6414. * POST requests, should call the script and return the
  6415. * generated response. */
  6416. *is_script_resource = (!*is_put_or_delete_request);
  6417. }
  6418. /* 8.3: If the request target is a directory, there could be
  6419. * a substitute file (index.html, index.cgi, ...). */
  6420. if (filestat->is_directory && is_uri_end_slash) {
  6421. /* Use a local copy here, since substitute_index_file will
  6422. * change the content of the file status */
  6423. struct mg_file_stat tmp_filestat;
  6424. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6425. if (substitute_index_file(
  6426. conn, filename, filename_buf_len, &tmp_filestat)) {
  6427. /* Substitute file found. Copy stat to the output, then
  6428. * check if the file is a script file */
  6429. *filestat = tmp_filestat;
  6430. if (extention_matches_script(conn, filename)) {
  6431. /* Substitute file is a script file */
  6432. *is_script_resource = 1;
  6433. } else {
  6434. /* Substitute file is a regular file */
  6435. *is_script_resource = 0;
  6436. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6437. }
  6438. }
  6439. /* If there is no substitute file, the server could return
  6440. * a directory listing in a later step */
  6441. }
  6442. return;
  6443. }
  6444. /* Step 9: Check for zipped files: */
  6445. /* If we can't find the actual file, look for the file
  6446. * with the same name but a .gz extension. If we find it,
  6447. * use that and set the gzipped flag in the file struct
  6448. * to indicate that the response need to have the content-
  6449. * encoding: gzip header.
  6450. * We can only do this if the browser declares support. */
  6451. if (conn->accept_gzip) {
  6452. mg_snprintf(
  6453. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6454. if (truncated) {
  6455. goto interpret_cleanup;
  6456. }
  6457. if (mg_stat(conn, gz_path, filestat)) {
  6458. if (filestat) {
  6459. filestat->is_gzipped = 1;
  6460. *is_found = 1;
  6461. }
  6462. /* Currently gz files can not be scripts. */
  6463. return;
  6464. }
  6465. }
  6466. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6467. /* Step 10: Script resources may handle sub-resources */
  6468. /* Support PATH_INFO for CGI scripts. */
  6469. tmp_str_len = strlen(filename);
  6470. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6471. if (!tmp_str) {
  6472. /* Out of memory */
  6473. goto interpret_cleanup;
  6474. }
  6475. memcpy(tmp_str, filename, tmp_str_len + 1);
  6476. /* Check config, if index scripts may have sub-resources */
  6477. allow_substitute_script_subresources =
  6478. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6479. "yes");
  6480. sep_pos = tmp_str_len;
  6481. while (sep_pos > 0) {
  6482. sep_pos--;
  6483. if (tmp_str[sep_pos] == '/') {
  6484. int is_script = 0, does_exist = 0;
  6485. tmp_str[sep_pos] = 0;
  6486. if (tmp_str[0]) {
  6487. is_script = extention_matches_script(conn, tmp_str);
  6488. does_exist = mg_stat(conn, tmp_str, filestat);
  6489. }
  6490. if (does_exist && is_script) {
  6491. filename[sep_pos] = 0;
  6492. memmove(filename + sep_pos + 2,
  6493. filename + sep_pos + 1,
  6494. strlen(filename + sep_pos + 1) + 1);
  6495. conn->path_info = filename + sep_pos + 1;
  6496. filename[sep_pos + 1] = '/';
  6497. *is_script_resource = 1;
  6498. *is_found = 1;
  6499. break;
  6500. }
  6501. if (allow_substitute_script_subresources) {
  6502. if (substitute_index_file(
  6503. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6504. /* some intermediate directory has an index file */
  6505. if (extention_matches_script(conn, tmp_str)) {
  6506. char *tmp_str2;
  6507. DEBUG_TRACE("Substitute script %s serving path %s",
  6508. tmp_str,
  6509. filename);
  6510. /* this index file is a script */
  6511. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6512. conn->phys_ctx);
  6513. mg_snprintf(conn,
  6514. &truncated,
  6515. filename,
  6516. filename_buf_len,
  6517. "%s//%s",
  6518. tmp_str,
  6519. tmp_str2);
  6520. mg_free(tmp_str2);
  6521. if (truncated) {
  6522. mg_free(tmp_str);
  6523. goto interpret_cleanup;
  6524. }
  6525. sep_pos = strlen(tmp_str);
  6526. filename[sep_pos] = 0;
  6527. conn->path_info = filename + sep_pos + 1;
  6528. *is_script_resource = 1;
  6529. *is_found = 1;
  6530. break;
  6531. } else {
  6532. DEBUG_TRACE("Substitute file %s serving path %s",
  6533. tmp_str,
  6534. filename);
  6535. /* non-script files will not have sub-resources */
  6536. filename[sep_pos] = 0;
  6537. conn->path_info = 0;
  6538. *is_script_resource = 0;
  6539. *is_found = 0;
  6540. break;
  6541. }
  6542. }
  6543. }
  6544. tmp_str[sep_pos] = '/';
  6545. }
  6546. }
  6547. mg_free(tmp_str);
  6548. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6549. #endif /* !defined(NO_FILES) */
  6550. return;
  6551. #if !defined(NO_FILES)
  6552. /* Reset all outputs */
  6553. interpret_cleanup:
  6554. memset(filestat, 0, sizeof(*filestat));
  6555. *filename = 0;
  6556. *is_found = 0;
  6557. *is_script_resource = 0;
  6558. *is_websocket_request = 0;
  6559. *is_put_or_delete_request = 0;
  6560. #endif /* !defined(NO_FILES) */
  6561. }
  6562. /* Check whether full request is buffered. Return:
  6563. * -1 if request or response is malformed
  6564. * 0 if request or response is not yet fully buffered
  6565. * >0 actual request length, including last \r\n\r\n */
  6566. static int
  6567. get_http_header_len(const char *buf, int buflen)
  6568. {
  6569. int i;
  6570. for (i = 0; i < buflen; i++) {
  6571. /* Do an unsigned comparison in some conditions below */
  6572. const unsigned char c = (unsigned char)buf[i];
  6573. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6574. && !isprint(c)) {
  6575. /* abort scan as soon as one malformed character is found */
  6576. return -1;
  6577. }
  6578. if (i < buflen - 1) {
  6579. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6580. /* Two newline, no carriage return - not standard compliant,
  6581. * but
  6582. * it
  6583. * should be accepted */
  6584. return i + 2;
  6585. }
  6586. }
  6587. if (i < buflen - 3) {
  6588. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6589. && (buf[i + 3] == '\n')) {
  6590. /* Two \r\n - standard compliant */
  6591. return i + 4;
  6592. }
  6593. }
  6594. }
  6595. return 0;
  6596. }
  6597. #if !defined(NO_CACHING)
  6598. /* Convert month to the month number. Return -1 on error, or month number */
  6599. static int
  6600. get_month_index(const char *s)
  6601. {
  6602. size_t i;
  6603. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6604. if (!strcmp(s, month_names[i])) {
  6605. return (int)i;
  6606. }
  6607. }
  6608. return -1;
  6609. }
  6610. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6611. static time_t
  6612. parse_date_string(const char *datetime)
  6613. {
  6614. char month_str[32] = {0};
  6615. int second, minute, hour, day, month, year;
  6616. time_t result = (time_t)0;
  6617. struct tm tm;
  6618. if ((sscanf(datetime,
  6619. "%d/%3s/%d %d:%d:%d",
  6620. &day,
  6621. month_str,
  6622. &year,
  6623. &hour,
  6624. &minute,
  6625. &second)
  6626. == 6)
  6627. || (sscanf(datetime,
  6628. "%d %3s %d %d:%d:%d",
  6629. &day,
  6630. month_str,
  6631. &year,
  6632. &hour,
  6633. &minute,
  6634. &second)
  6635. == 6)
  6636. || (sscanf(datetime,
  6637. "%*3s, %d %3s %d %d:%d:%d",
  6638. &day,
  6639. month_str,
  6640. &year,
  6641. &hour,
  6642. &minute,
  6643. &second)
  6644. == 6)
  6645. || (sscanf(datetime,
  6646. "%d-%3s-%d %d:%d:%d",
  6647. &day,
  6648. month_str,
  6649. &year,
  6650. &hour,
  6651. &minute,
  6652. &second)
  6653. == 6)) {
  6654. month = get_month_index(month_str);
  6655. if ((month >= 0) && (year >= 1970)) {
  6656. memset(&tm, 0, sizeof(tm));
  6657. tm.tm_year = year - 1900;
  6658. tm.tm_mon = month;
  6659. tm.tm_mday = day;
  6660. tm.tm_hour = hour;
  6661. tm.tm_min = minute;
  6662. tm.tm_sec = second;
  6663. result = timegm(&tm);
  6664. }
  6665. }
  6666. return result;
  6667. }
  6668. #endif /* !NO_CACHING */
  6669. /* Protect against directory disclosure attack by removing '..',
  6670. * excessive '/' and '\' characters */
  6671. static void
  6672. remove_double_dots_and_double_slashes(char *s)
  6673. {
  6674. char *p = s;
  6675. while ((s[0] == '.') && (s[1] == '.')) {
  6676. s++;
  6677. }
  6678. while (*s != '\0') {
  6679. *p++ = *s++;
  6680. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6681. /* Skip all following slashes, backslashes and double-dots */
  6682. while (s[0] != '\0') {
  6683. if ((s[0] == '/') || (s[0] == '\\')) {
  6684. s++;
  6685. } else if ((s[0] == '.') && (s[1] == '.')) {
  6686. s += 2;
  6687. } else {
  6688. break;
  6689. }
  6690. }
  6691. }
  6692. }
  6693. *p = '\0';
  6694. }
  6695. static const struct {
  6696. const char *extension;
  6697. size_t ext_len;
  6698. const char *mime_type;
  6699. } builtin_mime_types[] = {
  6700. /* IANA registered MIME types
  6701. * (http://www.iana.org/assignments/media-types)
  6702. * application types */
  6703. {".doc", 4, "application/msword"},
  6704. {".eps", 4, "application/postscript"},
  6705. {".exe", 4, "application/octet-stream"},
  6706. {".js", 3, "application/javascript"},
  6707. {".json", 5, "application/json"},
  6708. {".pdf", 4, "application/pdf"},
  6709. {".ps", 3, "application/postscript"},
  6710. {".rtf", 4, "application/rtf"},
  6711. {".xhtml", 6, "application/xhtml+xml"},
  6712. {".xsl", 4, "application/xml"},
  6713. {".xslt", 5, "application/xml"},
  6714. /* fonts */
  6715. {".ttf", 4, "application/font-sfnt"},
  6716. {".cff", 4, "application/font-sfnt"},
  6717. {".otf", 4, "application/font-sfnt"},
  6718. {".aat", 4, "application/font-sfnt"},
  6719. {".sil", 4, "application/font-sfnt"},
  6720. {".pfr", 4, "application/font-tdpfr"},
  6721. {".woff", 5, "application/font-woff"},
  6722. /* audio */
  6723. {".mp3", 4, "audio/mpeg"},
  6724. {".oga", 4, "audio/ogg"},
  6725. {".ogg", 4, "audio/ogg"},
  6726. /* image */
  6727. {".gif", 4, "image/gif"},
  6728. {".ief", 4, "image/ief"},
  6729. {".jpeg", 5, "image/jpeg"},
  6730. {".jpg", 4, "image/jpeg"},
  6731. {".jpm", 4, "image/jpm"},
  6732. {".jpx", 4, "image/jpx"},
  6733. {".png", 4, "image/png"},
  6734. {".svg", 4, "image/svg+xml"},
  6735. {".tif", 4, "image/tiff"},
  6736. {".tiff", 5, "image/tiff"},
  6737. /* model */
  6738. {".wrl", 4, "model/vrml"},
  6739. /* text */
  6740. {".css", 4, "text/css"},
  6741. {".csv", 4, "text/csv"},
  6742. {".htm", 4, "text/html"},
  6743. {".html", 5, "text/html"},
  6744. {".sgm", 4, "text/sgml"},
  6745. {".shtm", 5, "text/html"},
  6746. {".shtml", 6, "text/html"},
  6747. {".txt", 4, "text/plain"},
  6748. {".xml", 4, "text/xml"},
  6749. /* video */
  6750. {".mov", 4, "video/quicktime"},
  6751. {".mp4", 4, "video/mp4"},
  6752. {".mpeg", 5, "video/mpeg"},
  6753. {".mpg", 4, "video/mpeg"},
  6754. {".ogv", 4, "video/ogg"},
  6755. {".qt", 3, "video/quicktime"},
  6756. /* not registered types
  6757. * (http://reference.sitepoint.com/html/mime-types-full,
  6758. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6759. {".arj", 4, "application/x-arj-compressed"},
  6760. {".gz", 3, "application/x-gunzip"},
  6761. {".rar", 4, "application/x-arj-compressed"},
  6762. {".swf", 4, "application/x-shockwave-flash"},
  6763. {".tar", 4, "application/x-tar"},
  6764. {".tgz", 4, "application/x-tar-gz"},
  6765. {".torrent", 8, "application/x-bittorrent"},
  6766. {".ppt", 4, "application/x-mspowerpoint"},
  6767. {".xls", 4, "application/x-msexcel"},
  6768. {".zip", 4, "application/x-zip-compressed"},
  6769. {".aac",
  6770. 4,
  6771. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6772. {".aif", 4, "audio/x-aif"},
  6773. {".m3u", 4, "audio/x-mpegurl"},
  6774. {".mid", 4, "audio/x-midi"},
  6775. {".ra", 3, "audio/x-pn-realaudio"},
  6776. {".ram", 4, "audio/x-pn-realaudio"},
  6777. {".wav", 4, "audio/x-wav"},
  6778. {".bmp", 4, "image/bmp"},
  6779. {".ico", 4, "image/x-icon"},
  6780. {".pct", 4, "image/x-pct"},
  6781. {".pict", 5, "image/pict"},
  6782. {".rgb", 4, "image/x-rgb"},
  6783. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6784. {".asf", 4, "video/x-ms-asf"},
  6785. {".avi", 4, "video/x-msvideo"},
  6786. {".m4v", 4, "video/x-m4v"},
  6787. {NULL, 0, NULL}};
  6788. const char *
  6789. mg_get_builtin_mime_type(const char *path)
  6790. {
  6791. const char *ext;
  6792. size_t i, path_len;
  6793. path_len = strlen(path);
  6794. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6795. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6796. if ((path_len > builtin_mime_types[i].ext_len)
  6797. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6798. return builtin_mime_types[i].mime_type;
  6799. }
  6800. }
  6801. return "text/plain";
  6802. }
  6803. /* Look at the "path" extension and figure what mime type it has.
  6804. * Store mime type in the vector. */
  6805. static void
  6806. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6807. {
  6808. struct vec ext_vec, mime_vec;
  6809. const char *list, *ext;
  6810. size_t path_len;
  6811. path_len = strlen(path);
  6812. if ((conn == NULL) || (vec == NULL)) {
  6813. if (vec != NULL) {
  6814. memset(vec, '\0', sizeof(struct vec));
  6815. }
  6816. return;
  6817. }
  6818. /* Scan user-defined mime types first, in case user wants to
  6819. * override default mime types. */
  6820. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6821. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6822. /* ext now points to the path suffix */
  6823. ext = path + path_len - ext_vec.len;
  6824. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6825. *vec = mime_vec;
  6826. return;
  6827. }
  6828. }
  6829. vec->ptr = mg_get_builtin_mime_type(path);
  6830. vec->len = strlen(vec->ptr);
  6831. }
  6832. /* Stringify binary data. Output buffer must be twice as big as input,
  6833. * because each byte takes 2 bytes in string representation */
  6834. static void
  6835. bin2str(char *to, const unsigned char *p, size_t len)
  6836. {
  6837. static const char *hex = "0123456789abcdef";
  6838. for (; len--; p++) {
  6839. *to++ = hex[p[0] >> 4];
  6840. *to++ = hex[p[0] & 0x0f];
  6841. }
  6842. *to = '\0';
  6843. }
  6844. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6845. */
  6846. char *
  6847. mg_md5(char buf[33], ...)
  6848. {
  6849. md5_byte_t hash[16];
  6850. const char *p;
  6851. va_list ap;
  6852. md5_state_t ctx;
  6853. md5_init(&ctx);
  6854. va_start(ap, buf);
  6855. while ((p = va_arg(ap, const char *)) != NULL) {
  6856. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6857. }
  6858. va_end(ap);
  6859. md5_finish(&ctx, hash);
  6860. bin2str(buf, hash, sizeof(hash));
  6861. return buf;
  6862. }
  6863. /* Check the user's password, return 1 if OK */
  6864. static int
  6865. check_password(const char *method,
  6866. const char *ha1,
  6867. const char *uri,
  6868. const char *nonce,
  6869. const char *nc,
  6870. const char *cnonce,
  6871. const char *qop,
  6872. const char *response)
  6873. {
  6874. char ha2[32 + 1], expected_response[32 + 1];
  6875. /* Some of the parameters may be NULL */
  6876. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6877. || (qop == NULL) || (response == NULL)) {
  6878. return 0;
  6879. }
  6880. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6881. if (strlen(response) != 32) {
  6882. return 0;
  6883. }
  6884. mg_md5(ha2, method, ":", uri, NULL);
  6885. mg_md5(expected_response,
  6886. ha1,
  6887. ":",
  6888. nonce,
  6889. ":",
  6890. nc,
  6891. ":",
  6892. cnonce,
  6893. ":",
  6894. qop,
  6895. ":",
  6896. ha2,
  6897. NULL);
  6898. return mg_strcasecmp(response, expected_response) == 0;
  6899. }
  6900. #if !defined(NO_FILESYSTEMS)
  6901. /* Use the global passwords file, if specified by auth_gpass option,
  6902. * or search for .htpasswd in the requested directory. */
  6903. static void
  6904. open_auth_file(struct mg_connection *conn,
  6905. const char *path,
  6906. struct mg_file *filep)
  6907. {
  6908. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6909. char name[PATH_MAX];
  6910. const char *p, *e,
  6911. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6912. int truncated;
  6913. if (gpass != NULL) {
  6914. /* Use global passwords file */
  6915. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6916. #if defined(DEBUG)
  6917. /* Use mg_cry_internal here, since gpass has been configured. */
  6918. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6919. #endif
  6920. }
  6921. /* Important: using local struct mg_file to test path for
  6922. * is_directory flag. If filep is used, mg_stat() makes it
  6923. * appear as if auth file was opened.
  6924. * TODO(mid): Check if this is still required after rewriting
  6925. * mg_stat */
  6926. } else if (mg_stat(conn, path, &filep->stat)
  6927. && filep->stat.is_directory) {
  6928. mg_snprintf(conn,
  6929. &truncated,
  6930. name,
  6931. sizeof(name),
  6932. "%s/%s",
  6933. path,
  6934. PASSWORDS_FILE_NAME);
  6935. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6936. #if defined(DEBUG)
  6937. /* Don't use mg_cry_internal here, but only a trace, since this
  6938. * is
  6939. * a typical case. It will occur for every directory
  6940. * without a password file. */
  6941. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6942. #endif
  6943. }
  6944. } else {
  6945. /* Try to find .htpasswd in requested directory. */
  6946. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6947. if (e[0] == '/') {
  6948. break;
  6949. }
  6950. }
  6951. mg_snprintf(conn,
  6952. &truncated,
  6953. name,
  6954. sizeof(name),
  6955. "%.*s/%s",
  6956. (int)(e - p),
  6957. p,
  6958. PASSWORDS_FILE_NAME);
  6959. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6960. #if defined(DEBUG)
  6961. /* Don't use mg_cry_internal here, but only a trace, since this
  6962. * is
  6963. * a typical case. It will occur for every directory
  6964. * without a password file. */
  6965. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6966. #endif
  6967. }
  6968. }
  6969. }
  6970. }
  6971. #endif /* NO_FILESYSTEMS */
  6972. /* Parsed Authorization header */
  6973. struct ah {
  6974. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6975. };
  6976. /* Return 1 on success. Always initializes the ah structure. */
  6977. static int
  6978. parse_auth_header(struct mg_connection *conn,
  6979. char *buf,
  6980. size_t buf_size,
  6981. struct ah *ah)
  6982. {
  6983. char *name, *value, *s;
  6984. const char *auth_header;
  6985. uint64_t nonce;
  6986. if (!ah || !conn) {
  6987. return 0;
  6988. }
  6989. (void)memset(ah, 0, sizeof(*ah));
  6990. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6991. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6992. return 0;
  6993. }
  6994. /* Make modifiable copy of the auth header */
  6995. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6996. s = buf;
  6997. /* Parse authorization header */
  6998. for (;;) {
  6999. /* Gobble initial spaces */
  7000. while (isspace((unsigned char)*s)) {
  7001. s++;
  7002. }
  7003. name = skip_quoted(&s, "=", " ", 0);
  7004. /* Value is either quote-delimited, or ends at first comma or space.
  7005. */
  7006. if (s[0] == '\"') {
  7007. s++;
  7008. value = skip_quoted(&s, "\"", " ", '\\');
  7009. if (s[0] == ',') {
  7010. s++;
  7011. }
  7012. } else {
  7013. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  7014. * spaces */
  7015. }
  7016. if (*name == '\0') {
  7017. break;
  7018. }
  7019. if (!strcmp(name, "username")) {
  7020. ah->user = value;
  7021. } else if (!strcmp(name, "cnonce")) {
  7022. ah->cnonce = value;
  7023. } else if (!strcmp(name, "response")) {
  7024. ah->response = value;
  7025. } else if (!strcmp(name, "uri")) {
  7026. ah->uri = value;
  7027. } else if (!strcmp(name, "qop")) {
  7028. ah->qop = value;
  7029. } else if (!strcmp(name, "nc")) {
  7030. ah->nc = value;
  7031. } else if (!strcmp(name, "nonce")) {
  7032. ah->nonce = value;
  7033. }
  7034. }
  7035. #if !defined(NO_NONCE_CHECK)
  7036. /* Read the nonce from the response. */
  7037. if (ah->nonce == NULL) {
  7038. return 0;
  7039. }
  7040. s = NULL;
  7041. nonce = strtoull(ah->nonce, &s, 10);
  7042. if ((s == NULL) || (*s != 0)) {
  7043. return 0;
  7044. }
  7045. /* Convert the nonce from the client to a number. */
  7046. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7047. /* The converted number corresponds to the time the nounce has been
  7048. * created. This should not be earlier than the server start. */
  7049. /* Server side nonce check is valuable in all situations but one:
  7050. * if the server restarts frequently, but the client should not see
  7051. * that, so the server should accept nonces from previous starts. */
  7052. /* However, the reasonable default is to not accept a nonce from a
  7053. * previous start, so if anyone changed the access rights between
  7054. * two restarts, a new login is required. */
  7055. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7056. /* nonce is from a previous start of the server and no longer valid
  7057. * (replay attack?) */
  7058. return 0;
  7059. }
  7060. /* Check if the nonce is too high, so it has not (yet) been used by the
  7061. * server. */
  7062. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7063. + conn->dom_ctx->nonce_count)) {
  7064. return 0;
  7065. }
  7066. #else
  7067. (void)nonce;
  7068. #endif
  7069. /* CGI needs it as REMOTE_USER */
  7070. if (ah->user != NULL) {
  7071. conn->request_info.remote_user =
  7072. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7073. } else {
  7074. return 0;
  7075. }
  7076. return 1;
  7077. }
  7078. static const char *
  7079. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7080. {
  7081. #if defined(MG_USE_OPEN_FILE)
  7082. const char *eof;
  7083. size_t len;
  7084. const char *memend;
  7085. #else
  7086. (void)p; /* parameter is unused */
  7087. #endif
  7088. if (!filep) {
  7089. return NULL;
  7090. }
  7091. #if defined(MG_USE_OPEN_FILE)
  7092. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7093. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7094. /* Search for \n from p till the end of stream */
  7095. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7096. if (eof != NULL) {
  7097. eof += 1; /* Include \n */
  7098. } else {
  7099. eof = memend; /* Copy remaining data */
  7100. }
  7101. len =
  7102. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7103. memcpy(buf, *p, len);
  7104. buf[len] = '\0';
  7105. *p += len;
  7106. return len ? eof : NULL;
  7107. } else /* filep->access.fp block below */
  7108. #endif
  7109. if (filep->access.fp != NULL) {
  7110. return fgets(buf, (int)size, filep->access.fp);
  7111. } else {
  7112. return NULL;
  7113. }
  7114. }
  7115. /* Define the initial recursion depth for procesesing htpasswd files that
  7116. * include other htpasswd
  7117. * (or even the same) files. It is not difficult to provide a file or files
  7118. * s.t. they force civetweb
  7119. * to infinitely recurse and then crash.
  7120. */
  7121. #define INITIAL_DEPTH 9
  7122. #if INITIAL_DEPTH <= 0
  7123. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7124. #endif
  7125. #if !defined(NO_FILESYSTEMS)
  7126. struct read_auth_file_struct {
  7127. struct mg_connection *conn;
  7128. struct ah ah;
  7129. const char *domain;
  7130. char buf[256 + 256 + 40];
  7131. const char *f_user;
  7132. const char *f_domain;
  7133. const char *f_ha1;
  7134. };
  7135. static int
  7136. read_auth_file(struct mg_file *filep,
  7137. struct read_auth_file_struct *workdata,
  7138. int depth)
  7139. {
  7140. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7141. int is_authorized = 0;
  7142. struct mg_file fp;
  7143. size_t l;
  7144. if (!filep || !workdata || (0 == depth)) {
  7145. return 0;
  7146. }
  7147. /* Loop over passwords file */
  7148. #if defined(MG_USE_OPEN_FILE)
  7149. p = (char *)filep->access.membuf;
  7150. #endif
  7151. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7152. l = strlen(workdata->buf);
  7153. while (l > 0) {
  7154. if (isspace((unsigned char)workdata->buf[l - 1])
  7155. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7156. l--;
  7157. workdata->buf[l] = 0;
  7158. } else
  7159. break;
  7160. }
  7161. if (l < 1) {
  7162. continue;
  7163. }
  7164. workdata->f_user = workdata->buf;
  7165. if (workdata->f_user[0] == ':') {
  7166. /* user names may not contain a ':' and may not be empty,
  7167. * so lines starting with ':' may be used for a special purpose
  7168. */
  7169. if (workdata->f_user[1] == '#') {
  7170. /* :# is a comment */
  7171. continue;
  7172. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7173. if (mg_fopen(workdata->conn,
  7174. workdata->f_user + 9,
  7175. MG_FOPEN_MODE_READ,
  7176. &fp)) {
  7177. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7178. (void)mg_fclose(
  7179. &fp.access); /* ignore error on read only file */
  7180. /* No need to continue processing files once we have a
  7181. * match, since nothing will reset it back
  7182. * to 0.
  7183. */
  7184. if (is_authorized) {
  7185. return is_authorized;
  7186. }
  7187. } else {
  7188. mg_cry_internal(workdata->conn,
  7189. "%s: cannot open authorization file: %s",
  7190. __func__,
  7191. workdata->buf);
  7192. }
  7193. continue;
  7194. }
  7195. /* everything is invalid for the moment (might change in the
  7196. * future) */
  7197. mg_cry_internal(workdata->conn,
  7198. "%s: syntax error in authorization file: %s",
  7199. __func__,
  7200. workdata->buf);
  7201. continue;
  7202. }
  7203. workdata->f_domain = strchr(workdata->f_user, ':');
  7204. if (workdata->f_domain == NULL) {
  7205. mg_cry_internal(workdata->conn,
  7206. "%s: syntax error in authorization file: %s",
  7207. __func__,
  7208. workdata->buf);
  7209. continue;
  7210. }
  7211. *(char *)(workdata->f_domain) = 0;
  7212. (workdata->f_domain)++;
  7213. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7214. if (workdata->f_ha1 == NULL) {
  7215. mg_cry_internal(workdata->conn,
  7216. "%s: syntax error in authorization file: %s",
  7217. __func__,
  7218. workdata->buf);
  7219. continue;
  7220. }
  7221. *(char *)(workdata->f_ha1) = 0;
  7222. (workdata->f_ha1)++;
  7223. if (!strcmp(workdata->ah.user, workdata->f_user)
  7224. && !strcmp(workdata->domain, workdata->f_domain)) {
  7225. return check_password(workdata->conn->request_info.request_method,
  7226. workdata->f_ha1,
  7227. workdata->ah.uri,
  7228. workdata->ah.nonce,
  7229. workdata->ah.nc,
  7230. workdata->ah.cnonce,
  7231. workdata->ah.qop,
  7232. workdata->ah.response);
  7233. }
  7234. }
  7235. return is_authorized;
  7236. }
  7237. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7238. static int
  7239. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7240. {
  7241. struct read_auth_file_struct workdata;
  7242. char buf[MG_BUF_LEN];
  7243. if (!conn || !conn->dom_ctx) {
  7244. return 0;
  7245. }
  7246. memset(&workdata, 0, sizeof(workdata));
  7247. workdata.conn = conn;
  7248. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7249. return 0;
  7250. }
  7251. if (realm) {
  7252. workdata.domain = realm;
  7253. } else {
  7254. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7255. }
  7256. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7257. }
  7258. /* Public function to check http digest authentication header */
  7259. int
  7260. mg_check_digest_access_authentication(struct mg_connection *conn,
  7261. const char *realm,
  7262. const char *filename)
  7263. {
  7264. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7265. int auth;
  7266. if (!conn || !filename) {
  7267. return -1;
  7268. }
  7269. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7270. return -2;
  7271. }
  7272. auth = authorize(conn, &file, realm);
  7273. mg_fclose(&file.access);
  7274. return auth;
  7275. }
  7276. #endif /* NO_FILESYSTEMS */
  7277. /* Return 1 if request is authorised, 0 otherwise. */
  7278. static int
  7279. check_authorization(struct mg_connection *conn, const char *path)
  7280. {
  7281. #if !defined(NO_FILESYSTEMS)
  7282. char fname[PATH_MAX];
  7283. struct vec uri_vec, filename_vec;
  7284. const char *list;
  7285. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7286. int authorized = 1, truncated;
  7287. if (!conn || !conn->dom_ctx) {
  7288. return 0;
  7289. }
  7290. list = conn->dom_ctx->config[PROTECT_URI];
  7291. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7292. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7293. mg_snprintf(conn,
  7294. &truncated,
  7295. fname,
  7296. sizeof(fname),
  7297. "%.*s",
  7298. (int)filename_vec.len,
  7299. filename_vec.ptr);
  7300. if (truncated
  7301. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7302. mg_cry_internal(conn,
  7303. "%s: cannot open %s: %s",
  7304. __func__,
  7305. fname,
  7306. strerror(errno));
  7307. }
  7308. break;
  7309. }
  7310. }
  7311. if (!is_file_opened(&file.access)) {
  7312. open_auth_file(conn, path, &file);
  7313. }
  7314. if (is_file_opened(&file.access)) {
  7315. authorized = authorize(conn, &file, NULL);
  7316. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7317. }
  7318. return authorized;
  7319. #else
  7320. (void)conn;
  7321. (void)path;
  7322. return 1;
  7323. #endif /* NO_FILESYSTEMS */
  7324. }
  7325. /* Internal function. Assumes conn is valid */
  7326. static void
  7327. send_authorization_request(struct mg_connection *conn, const char *realm)
  7328. {
  7329. char date[64];
  7330. time_t curtime = time(NULL);
  7331. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7332. if (!realm) {
  7333. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7334. }
  7335. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7336. nonce += conn->dom_ctx->nonce_count;
  7337. ++conn->dom_ctx->nonce_count;
  7338. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7339. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7340. conn->status_code = 401;
  7341. conn->must_close = 1;
  7342. gmt_time_string(date, sizeof(date), &curtime);
  7343. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7344. send_no_cache_header(conn);
  7345. send_additional_header(conn);
  7346. mg_printf(conn,
  7347. "Date: %s\r\n"
  7348. "Connection: %s\r\n"
  7349. "Content-Length: 0\r\n"
  7350. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7351. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7352. date,
  7353. suggest_connection_header(conn),
  7354. realm,
  7355. nonce);
  7356. }
  7357. /* Interface function. Parameters are provided by the user, so do
  7358. * at least some basic checks.
  7359. */
  7360. int
  7361. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7362. const char *realm)
  7363. {
  7364. if (conn && conn->dom_ctx) {
  7365. send_authorization_request(conn, realm);
  7366. return 0;
  7367. }
  7368. return -1;
  7369. }
  7370. #if !defined(NO_FILES)
  7371. static int
  7372. is_authorized_for_put(struct mg_connection *conn)
  7373. {
  7374. if (conn) {
  7375. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7376. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7377. int ret = 0;
  7378. if (passfile != NULL
  7379. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7380. ret = authorize(conn, &file, NULL);
  7381. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7382. }
  7383. return ret;
  7384. }
  7385. return 0;
  7386. }
  7387. #endif
  7388. int
  7389. mg_modify_passwords_file(const char *fname,
  7390. const char *domain,
  7391. const char *user,
  7392. const char *pass)
  7393. {
  7394. int found, i;
  7395. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7396. FILE *fp, *fp2;
  7397. found = 0;
  7398. fp = fp2 = NULL;
  7399. /* Regard empty password as no password - remove user record. */
  7400. if ((pass != NULL) && (pass[0] == '\0')) {
  7401. pass = NULL;
  7402. }
  7403. /* Other arguments must not be empty */
  7404. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7405. return 0;
  7406. }
  7407. /* Using the given file format, user name and domain must not contain
  7408. * ':'
  7409. */
  7410. if (strchr(user, ':') != NULL) {
  7411. return 0;
  7412. }
  7413. if (strchr(domain, ':') != NULL) {
  7414. return 0;
  7415. }
  7416. /* Do not allow control characters like newline in user name and domain.
  7417. * Do not allow excessively long names either. */
  7418. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7419. if (iscntrl((unsigned char)user[i])) {
  7420. return 0;
  7421. }
  7422. }
  7423. if (user[i]) {
  7424. return 0;
  7425. }
  7426. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7427. if (iscntrl((unsigned char)domain[i])) {
  7428. return 0;
  7429. }
  7430. }
  7431. if (domain[i]) {
  7432. return 0;
  7433. }
  7434. /* The maximum length of the path to the password file is limited */
  7435. if ((strlen(fname) + 4) >= PATH_MAX) {
  7436. return 0;
  7437. }
  7438. /* Create a temporary file name. Length has been checked before. */
  7439. strcpy(tmp, fname);
  7440. strcat(tmp, ".tmp");
  7441. /* Create the file if does not exist */
  7442. /* Use of fopen here is OK, since fname is only ASCII */
  7443. if ((fp = fopen(fname, "a+")) != NULL) {
  7444. (void)fclose(fp);
  7445. }
  7446. /* Open the given file and temporary file */
  7447. if ((fp = fopen(fname, "r")) == NULL) {
  7448. return 0;
  7449. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7450. fclose(fp);
  7451. return 0;
  7452. }
  7453. /* Copy the stuff to temporary file */
  7454. while (fgets(line, sizeof(line), fp) != NULL) {
  7455. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7456. continue;
  7457. }
  7458. u[255] = 0;
  7459. d[255] = 0;
  7460. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7461. found++;
  7462. if (pass != NULL) {
  7463. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7464. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7465. }
  7466. } else {
  7467. fprintf(fp2, "%s", line);
  7468. }
  7469. }
  7470. /* If new user, just add it */
  7471. if (!found && (pass != NULL)) {
  7472. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7473. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7474. }
  7475. /* Close files */
  7476. fclose(fp);
  7477. fclose(fp2);
  7478. /* Put the temp file in place of real file */
  7479. IGNORE_UNUSED_RESULT(remove(fname));
  7480. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7481. return 1;
  7482. }
  7483. static int
  7484. is_valid_port(unsigned long port)
  7485. {
  7486. return (port <= 0xffff);
  7487. }
  7488. static int
  7489. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7490. {
  7491. struct addrinfo hints, *res, *ressave;
  7492. int func_ret = 0;
  7493. int gai_ret;
  7494. memset(&hints, 0, sizeof(struct addrinfo));
  7495. hints.ai_family = af;
  7496. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7497. if (gai_ret != 0) {
  7498. /* gai_strerror could be used to convert gai_ret to a string */
  7499. /* POSIX return values: see
  7500. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7501. */
  7502. /* Windows return values: see
  7503. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7504. */
  7505. return 0;
  7506. }
  7507. ressave = res;
  7508. while (res) {
  7509. if (dstlen >= (size_t)res->ai_addrlen) {
  7510. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7511. func_ret = 1;
  7512. }
  7513. res = res->ai_next;
  7514. }
  7515. freeaddrinfo(ressave);
  7516. return func_ret;
  7517. }
  7518. static int
  7519. connect_socket(struct mg_context *ctx /* may be NULL */,
  7520. const char *host,
  7521. int port,
  7522. int use_ssl,
  7523. char *ebuf,
  7524. size_t ebuf_len,
  7525. SOCKET *sock /* output: socket, must not be NULL */,
  7526. union usa *sa /* output: socket address, must not be NULL */
  7527. )
  7528. {
  7529. int ip_ver = 0;
  7530. int conn_ret = -1;
  7531. int sockerr = 0;
  7532. *sock = INVALID_SOCKET;
  7533. memset(sa, 0, sizeof(*sa));
  7534. if (ebuf_len > 0) {
  7535. *ebuf = 0;
  7536. }
  7537. if (host == NULL) {
  7538. mg_snprintf(NULL,
  7539. NULL, /* No truncation check for ebuf */
  7540. ebuf,
  7541. ebuf_len,
  7542. "%s",
  7543. "NULL host");
  7544. return 0;
  7545. }
  7546. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7547. mg_snprintf(NULL,
  7548. NULL, /* No truncation check for ebuf */
  7549. ebuf,
  7550. ebuf_len,
  7551. "%s",
  7552. "invalid port");
  7553. return 0;
  7554. }
  7555. #if !defined(NO_SSL)
  7556. #if !defined(NO_SSL_DL)
  7557. #if defined(OPENSSL_API_1_1)
  7558. if (use_ssl && (TLS_client_method == NULL)) {
  7559. mg_snprintf(NULL,
  7560. NULL, /* No truncation check for ebuf */
  7561. ebuf,
  7562. ebuf_len,
  7563. "%s",
  7564. "SSL is not initialized");
  7565. return 0;
  7566. }
  7567. #else
  7568. if (use_ssl && (SSLv23_client_method == NULL)) {
  7569. mg_snprintf(NULL,
  7570. NULL, /* No truncation check for ebuf */
  7571. ebuf,
  7572. ebuf_len,
  7573. "%s",
  7574. "SSL is not initialized");
  7575. return 0;
  7576. }
  7577. #endif /* OPENSSL_API_1_1 */
  7578. #else
  7579. (void)use_ssl;
  7580. #endif /* NO_SSL_DL */
  7581. #else
  7582. (void)use_ssl;
  7583. #endif /* !defined(NO_SSL) */
  7584. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7585. sa->sin.sin_family = AF_INET;
  7586. sa->sin.sin_port = htons((uint16_t)port);
  7587. ip_ver = 4;
  7588. #if defined(USE_IPV6)
  7589. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7590. sa->sin6.sin6_family = AF_INET6;
  7591. sa->sin6.sin6_port = htons((uint16_t)port);
  7592. ip_ver = 6;
  7593. } else if (host[0] == '[') {
  7594. /* While getaddrinfo on Windows will work with [::1],
  7595. * getaddrinfo on Linux only works with ::1 (without []). */
  7596. size_t l = strlen(host + 1);
  7597. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7598. if (h) {
  7599. h[l - 1] = 0;
  7600. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7601. sa->sin6.sin6_family = AF_INET6;
  7602. sa->sin6.sin6_port = htons((uint16_t)port);
  7603. ip_ver = 6;
  7604. }
  7605. mg_free(h);
  7606. }
  7607. #endif
  7608. }
  7609. if (ip_ver == 0) {
  7610. mg_snprintf(NULL,
  7611. NULL, /* No truncation check for ebuf */
  7612. ebuf,
  7613. ebuf_len,
  7614. "%s",
  7615. "host not found");
  7616. return 0;
  7617. }
  7618. if (ip_ver == 4) {
  7619. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7620. }
  7621. #if defined(USE_IPV6)
  7622. else if (ip_ver == 6) {
  7623. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7624. }
  7625. #endif
  7626. if (*sock == INVALID_SOCKET) {
  7627. mg_snprintf(NULL,
  7628. NULL, /* No truncation check for ebuf */
  7629. ebuf,
  7630. ebuf_len,
  7631. "socket(): %s",
  7632. strerror(ERRNO));
  7633. return 0;
  7634. }
  7635. if (0 != set_non_blocking_mode(*sock)) {
  7636. mg_snprintf(NULL,
  7637. NULL, /* No truncation check for ebuf */
  7638. ebuf,
  7639. ebuf_len,
  7640. "Cannot set socket to non-blocking: %s",
  7641. strerror(ERRNO));
  7642. closesocket(*sock);
  7643. *sock = INVALID_SOCKET;
  7644. return 0;
  7645. }
  7646. set_close_on_exec(*sock, NULL, ctx);
  7647. if (ip_ver == 4) {
  7648. /* connected with IPv4 */
  7649. conn_ret = connect(*sock,
  7650. (struct sockaddr *)((void *)&sa->sin),
  7651. sizeof(sa->sin));
  7652. }
  7653. #if defined(USE_IPV6)
  7654. else if (ip_ver == 6) {
  7655. /* connected with IPv6 */
  7656. conn_ret = connect(*sock,
  7657. (struct sockaddr *)((void *)&sa->sin6),
  7658. sizeof(sa->sin6));
  7659. }
  7660. #endif
  7661. if (conn_ret != 0) {
  7662. sockerr = ERRNO;
  7663. }
  7664. #if defined(_WIN32)
  7665. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7666. #else
  7667. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7668. #endif
  7669. /* Data for getsockopt */
  7670. void *psockerr = &sockerr;
  7671. int ret;
  7672. #if defined(_WIN32)
  7673. int len = (int)sizeof(sockerr);
  7674. #else
  7675. socklen_t len = (socklen_t)sizeof(sockerr);
  7676. #endif
  7677. /* Data for poll */
  7678. struct mg_pollfd pfd[1];
  7679. int pollres;
  7680. int ms_wait = 10000; /* 10 second timeout */
  7681. int nonstop = 0;
  7682. /* For a non-blocking socket, the connect sequence is:
  7683. * 1) call connect (will not block)
  7684. * 2) wait until the socket is ready for writing (select or poll)
  7685. * 3) check connection state with getsockopt
  7686. */
  7687. pfd[0].fd = *sock;
  7688. pfd[0].events = POLLOUT;
  7689. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7690. if (pollres != 1) {
  7691. /* Not connected */
  7692. mg_snprintf(NULL,
  7693. NULL, /* No truncation check for ebuf */
  7694. ebuf,
  7695. ebuf_len,
  7696. "connect(%s:%d): timeout",
  7697. host,
  7698. port);
  7699. closesocket(*sock);
  7700. *sock = INVALID_SOCKET;
  7701. return 0;
  7702. }
  7703. #if defined(_WIN32)
  7704. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7705. #else
  7706. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7707. #endif
  7708. if ((ret == 0) && (sockerr == 0)) {
  7709. conn_ret = 0;
  7710. }
  7711. }
  7712. if (conn_ret != 0) {
  7713. /* Not connected */
  7714. mg_snprintf(NULL,
  7715. NULL, /* No truncation check for ebuf */
  7716. ebuf,
  7717. ebuf_len,
  7718. "connect(%s:%d): error %s",
  7719. host,
  7720. port,
  7721. strerror(sockerr));
  7722. closesocket(*sock);
  7723. *sock = INVALID_SOCKET;
  7724. return 0;
  7725. }
  7726. return 1;
  7727. }
  7728. int
  7729. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7730. {
  7731. static const char *dont_escape = "._-$,;~()";
  7732. static const char *hex = "0123456789abcdef";
  7733. char *pos = dst;
  7734. const char *end = dst + dst_len - 1;
  7735. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7736. if (isalnum((unsigned char)*src)
  7737. || (strchr(dont_escape, *src) != NULL)) {
  7738. *pos = *src;
  7739. } else if (pos + 2 < end) {
  7740. pos[0] = '%';
  7741. pos[1] = hex[(unsigned char)*src >> 4];
  7742. pos[2] = hex[(unsigned char)*src & 0xf];
  7743. pos += 2;
  7744. } else {
  7745. break;
  7746. }
  7747. }
  7748. *pos = '\0';
  7749. return (*src == '\0') ? (int)(pos - dst) : -1;
  7750. }
  7751. /* Return 0 on success, non-zero if an error occurs. */
  7752. static int
  7753. print_dir_entry(struct de *de)
  7754. {
  7755. size_t namesize, escsize, i;
  7756. char *href, *esc, *p;
  7757. char size[64], mod[64];
  7758. #if defined(REENTRANT_TIME)
  7759. struct tm _tm;
  7760. struct tm *tm = &_tm;
  7761. #else
  7762. struct tm *tm;
  7763. #endif
  7764. /* Estimate worst case size for encoding and escaping */
  7765. namesize = strlen(de->file_name) + 1;
  7766. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7767. href = (char *)mg_malloc(namesize * 3 + escsize);
  7768. if (href == NULL) {
  7769. return -1;
  7770. }
  7771. mg_url_encode(de->file_name, href, namesize * 3);
  7772. esc = NULL;
  7773. if (escsize > 0) {
  7774. /* HTML escaping needed */
  7775. esc = href + namesize * 3;
  7776. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7777. mg_strlcpy(p, de->file_name + i, 2);
  7778. if (*p == '&') {
  7779. strcpy(p, "&amp;");
  7780. } else if (*p == '<') {
  7781. strcpy(p, "&lt;");
  7782. } else if (*p == '>') {
  7783. strcpy(p, "&gt;");
  7784. }
  7785. }
  7786. }
  7787. if (de->file.is_directory) {
  7788. mg_snprintf(de->conn,
  7789. NULL, /* Buffer is big enough */
  7790. size,
  7791. sizeof(size),
  7792. "%s",
  7793. "[DIRECTORY]");
  7794. } else {
  7795. /* We use (signed) cast below because MSVC 6 compiler cannot
  7796. * convert unsigned __int64 to double. Sigh. */
  7797. if (de->file.size < 1024) {
  7798. mg_snprintf(de->conn,
  7799. NULL, /* Buffer is big enough */
  7800. size,
  7801. sizeof(size),
  7802. "%d",
  7803. (int)de->file.size);
  7804. } else if (de->file.size < 0x100000) {
  7805. mg_snprintf(de->conn,
  7806. NULL, /* Buffer is big enough */
  7807. size,
  7808. sizeof(size),
  7809. "%.1fk",
  7810. (double)de->file.size / 1024.0);
  7811. } else if (de->file.size < 0x40000000) {
  7812. mg_snprintf(de->conn,
  7813. NULL, /* Buffer is big enough */
  7814. size,
  7815. sizeof(size),
  7816. "%.1fM",
  7817. (double)de->file.size / 1048576);
  7818. } else {
  7819. mg_snprintf(de->conn,
  7820. NULL, /* Buffer is big enough */
  7821. size,
  7822. sizeof(size),
  7823. "%.1fG",
  7824. (double)de->file.size / 1073741824);
  7825. }
  7826. }
  7827. /* Note: mg_snprintf will not cause a buffer overflow above.
  7828. * So, string truncation checks are not required here. */
  7829. #if defined(REENTRANT_TIME)
  7830. localtime_r(&de->file.last_modified, tm);
  7831. #else
  7832. tm = localtime(&de->file.last_modified);
  7833. #endif
  7834. if (tm != NULL) {
  7835. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7836. } else {
  7837. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7838. mod[sizeof(mod) - 1] = '\0';
  7839. }
  7840. mg_printf(de->conn,
  7841. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7842. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7843. href,
  7844. de->file.is_directory ? "/" : "",
  7845. esc ? esc : de->file_name,
  7846. de->file.is_directory ? "/" : "",
  7847. mod,
  7848. size);
  7849. mg_free(href);
  7850. return 0;
  7851. }
  7852. /* This function is called from send_directory() and used for
  7853. * sorting directory entries by size, or name, or modification time.
  7854. * On windows, __cdecl specification is needed in case if project is built
  7855. * with __stdcall convention. qsort always requires __cdels callback. */
  7856. static int WINCDECL
  7857. compare_dir_entries(const void *p1, const void *p2)
  7858. {
  7859. if (p1 && p2) {
  7860. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7861. const char *query_string = a->conn->request_info.query_string;
  7862. int cmp_result = 0;
  7863. if ((query_string == NULL) || (query_string[0] == '\0')) {
  7864. query_string = "n";
  7865. }
  7866. if (a->file.is_directory && !b->file.is_directory) {
  7867. return -1; /* Always put directories on top */
  7868. } else if (!a->file.is_directory && b->file.is_directory) {
  7869. return 1; /* Always put directories on top */
  7870. } else if (*query_string == 'n') {
  7871. cmp_result = strcmp(a->file_name, b->file_name);
  7872. } else if (*query_string == 's') {
  7873. cmp_result = (a->file.size == b->file.size)
  7874. ? 0
  7875. : ((a->file.size > b->file.size) ? 1 : -1);
  7876. } else if (*query_string == 'd') {
  7877. cmp_result =
  7878. (a->file.last_modified == b->file.last_modified)
  7879. ? 0
  7880. : ((a->file.last_modified > b->file.last_modified) ? 1
  7881. : -1);
  7882. }
  7883. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7884. }
  7885. return 0;
  7886. }
  7887. static int
  7888. must_hide_file(struct mg_connection *conn, const char *path)
  7889. {
  7890. if (conn && conn->dom_ctx) {
  7891. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7892. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7893. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7894. || ((pattern != NULL)
  7895. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7896. }
  7897. return 0;
  7898. }
  7899. #if !defined(NO_FILESYSTEMS)
  7900. static int
  7901. scan_directory(struct mg_connection *conn,
  7902. const char *dir,
  7903. void *data,
  7904. int (*cb)(struct de *, void *))
  7905. {
  7906. char path[PATH_MAX];
  7907. struct dirent *dp;
  7908. DIR *dirp;
  7909. struct de de;
  7910. int truncated;
  7911. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7912. return 0;
  7913. } else {
  7914. de.conn = conn;
  7915. while ((dp = mg_readdir(dirp)) != NULL) {
  7916. /* Do not show current dir and hidden files */
  7917. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7918. || must_hide_file(conn, dp->d_name)) {
  7919. continue;
  7920. }
  7921. mg_snprintf(
  7922. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7923. /* If we don't memset stat structure to zero, mtime will have
  7924. * garbage and strftime() will segfault later on in
  7925. * print_dir_entry(). memset is required only if mg_stat()
  7926. * fails. For more details, see
  7927. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7928. memset(&de.file, 0, sizeof(de.file));
  7929. if (truncated) {
  7930. /* If the path is not complete, skip processing. */
  7931. continue;
  7932. }
  7933. if (!mg_stat(conn, path, &de.file)) {
  7934. mg_cry_internal(conn,
  7935. "%s: mg_stat(%s) failed: %s",
  7936. __func__,
  7937. path,
  7938. strerror(ERRNO));
  7939. }
  7940. de.file_name = dp->d_name;
  7941. cb(&de, data);
  7942. }
  7943. (void)mg_closedir(dirp);
  7944. }
  7945. return 1;
  7946. }
  7947. #endif /* NO_FILESYSTEMS */
  7948. #if !defined(NO_FILES)
  7949. static int
  7950. remove_directory(struct mg_connection *conn, const char *dir)
  7951. {
  7952. char path[PATH_MAX];
  7953. struct dirent *dp;
  7954. DIR *dirp;
  7955. struct de de;
  7956. int truncated;
  7957. int ok = 1;
  7958. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7959. return 0;
  7960. } else {
  7961. de.conn = conn;
  7962. while ((dp = mg_readdir(dirp)) != NULL) {
  7963. /* Do not show current dir (but show hidden files as they will
  7964. * also be removed) */
  7965. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7966. continue;
  7967. }
  7968. mg_snprintf(
  7969. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7970. /* If we don't memset stat structure to zero, mtime will have
  7971. * garbage and strftime() will segfault later on in
  7972. * print_dir_entry(). memset is required only if mg_stat()
  7973. * fails. For more details, see
  7974. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7975. memset(&de.file, 0, sizeof(de.file));
  7976. if (truncated) {
  7977. /* Do not delete anything shorter */
  7978. ok = 0;
  7979. continue;
  7980. }
  7981. if (!mg_stat(conn, path, &de.file)) {
  7982. mg_cry_internal(conn,
  7983. "%s: mg_stat(%s) failed: %s",
  7984. __func__,
  7985. path,
  7986. strerror(ERRNO));
  7987. ok = 0;
  7988. }
  7989. if (de.file.is_directory) {
  7990. if (remove_directory(conn, path) == 0) {
  7991. ok = 0;
  7992. }
  7993. } else {
  7994. /* This will fail file is the file is in memory */
  7995. if (mg_remove(conn, path) == 0) {
  7996. ok = 0;
  7997. }
  7998. }
  7999. }
  8000. (void)mg_closedir(dirp);
  8001. IGNORE_UNUSED_RESULT(rmdir(dir));
  8002. }
  8003. return ok;
  8004. }
  8005. #endif
  8006. struct dir_scan_data {
  8007. struct de *entries;
  8008. unsigned int num_entries;
  8009. unsigned int arr_size;
  8010. };
  8011. /* Behaves like realloc(), but frees original pointer on failure */
  8012. static void *
  8013. realloc2(void *ptr, size_t size)
  8014. {
  8015. void *new_ptr = mg_realloc(ptr, size);
  8016. if (new_ptr == NULL) {
  8017. mg_free(ptr);
  8018. }
  8019. return new_ptr;
  8020. }
  8021. #if !defined(NO_FILESYSTEMS)
  8022. static int
  8023. dir_scan_callback(struct de *de, void *data)
  8024. {
  8025. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8026. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8027. dsd->arr_size *= 2;
  8028. dsd->entries =
  8029. (struct de *)realloc2(dsd->entries,
  8030. dsd->arr_size * sizeof(dsd->entries[0]));
  8031. }
  8032. if (dsd->entries == NULL) {
  8033. /* TODO(lsm, low): propagate an error to the caller */
  8034. dsd->num_entries = 0;
  8035. } else {
  8036. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8037. dsd->entries[dsd->num_entries].file = de->file;
  8038. dsd->entries[dsd->num_entries].conn = de->conn;
  8039. dsd->num_entries++;
  8040. }
  8041. return 0;
  8042. }
  8043. static void
  8044. handle_directory_request(struct mg_connection *conn, const char *dir)
  8045. {
  8046. unsigned int i;
  8047. int sort_direction;
  8048. struct dir_scan_data data = {NULL, 0, 128};
  8049. char date[64], *esc, *p;
  8050. const char *title;
  8051. time_t curtime = time(NULL);
  8052. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8053. mg_send_http_error(conn,
  8054. 500,
  8055. "Error: Cannot open directory\nopendir(%s): %s",
  8056. dir,
  8057. strerror(ERRNO));
  8058. return;
  8059. }
  8060. gmt_time_string(date, sizeof(date), &curtime);
  8061. if (!conn) {
  8062. return;
  8063. }
  8064. esc = NULL;
  8065. title = conn->request_info.local_uri;
  8066. if (title[strcspn(title, "&<>")]) {
  8067. /* HTML escaping needed */
  8068. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8069. if (esc) {
  8070. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8071. mg_strlcpy(p, title + i, 2);
  8072. if (*p == '&') {
  8073. strcpy(p, "&amp;");
  8074. } else if (*p == '<') {
  8075. strcpy(p, "&lt;");
  8076. } else if (*p == '>') {
  8077. strcpy(p, "&gt;");
  8078. }
  8079. }
  8080. } else {
  8081. title = "";
  8082. }
  8083. }
  8084. sort_direction = ((conn->request_info.query_string != NULL)
  8085. && (conn->request_info.query_string[0] != '\0')
  8086. && (conn->request_info.query_string[1] == 'd'))
  8087. ? 'a'
  8088. : 'd';
  8089. conn->must_close = 1;
  8090. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8091. send_static_cache_header(conn);
  8092. send_additional_header(conn);
  8093. mg_printf(conn,
  8094. "Date: %s\r\n"
  8095. "Connection: close\r\n"
  8096. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8097. date);
  8098. mg_printf(conn,
  8099. "<html><head><title>Index of %s</title>"
  8100. "<style>th {text-align: left;}</style></head>"
  8101. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8102. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8103. "<th><a href=\"?d%c\">Modified</a></th>"
  8104. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8105. "<tr><td colspan=\"3\"><hr></td></tr>",
  8106. esc ? esc : title,
  8107. esc ? esc : title,
  8108. sort_direction,
  8109. sort_direction,
  8110. sort_direction);
  8111. mg_free(esc);
  8112. /* Print first entry - link to a parent directory */
  8113. mg_printf(conn,
  8114. "<tr><td><a href=\"%s\">%s</a></td>"
  8115. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8116. "..",
  8117. "Parent directory",
  8118. "-",
  8119. "-");
  8120. /* Sort and print directory entries */
  8121. if (data.entries != NULL) {
  8122. qsort(data.entries,
  8123. (size_t)data.num_entries,
  8124. sizeof(data.entries[0]),
  8125. compare_dir_entries);
  8126. for (i = 0; i < data.num_entries; i++) {
  8127. print_dir_entry(&data.entries[i]);
  8128. mg_free(data.entries[i].file_name);
  8129. }
  8130. mg_free(data.entries);
  8131. }
  8132. mg_printf(conn, "%s", "</table></pre></body></html>");
  8133. conn->status_code = 200;
  8134. }
  8135. #endif /* NO_FILESYSTEMS */
  8136. /* Send len bytes from the opened file to the client. */
  8137. static void
  8138. send_file_data(struct mg_connection *conn,
  8139. struct mg_file *filep,
  8140. int64_t offset,
  8141. int64_t len)
  8142. {
  8143. char buf[MG_BUF_LEN];
  8144. int to_read, num_read, num_written;
  8145. int64_t size;
  8146. if (!filep || !conn) {
  8147. return;
  8148. }
  8149. /* Sanity check the offset */
  8150. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8151. : (int64_t)(filep->stat.size);
  8152. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8153. #if defined(MG_USE_OPEN_FILE)
  8154. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8155. /* file stored in memory */
  8156. if (len > size - offset) {
  8157. len = size - offset;
  8158. }
  8159. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8160. } else /* else block below */
  8161. #endif
  8162. if (len > 0 && filep->access.fp != NULL) {
  8163. /* file stored on disk */
  8164. #if defined(__linux__)
  8165. /* sendfile is only available for Linux */
  8166. if ((conn->ssl == 0) && (conn->throttle == 0)
  8167. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8168. "yes"))) {
  8169. off_t sf_offs = (off_t)offset;
  8170. ssize_t sf_sent;
  8171. int sf_file = fileno(filep->access.fp);
  8172. int loop_cnt = 0;
  8173. do {
  8174. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8175. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8176. size_t sf_tosend =
  8177. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8178. sf_sent =
  8179. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8180. if (sf_sent > 0) {
  8181. len -= sf_sent;
  8182. offset += sf_sent;
  8183. } else if (loop_cnt == 0) {
  8184. /* This file can not be sent using sendfile.
  8185. * This might be the case for pseudo-files in the
  8186. * /sys/ and /proc/ file system.
  8187. * Use the regular user mode copy code instead. */
  8188. break;
  8189. } else if (sf_sent == 0) {
  8190. /* No error, but 0 bytes sent. May be EOF? */
  8191. return;
  8192. }
  8193. loop_cnt++;
  8194. } while ((len > 0) && (sf_sent >= 0));
  8195. if (sf_sent > 0) {
  8196. return; /* OK */
  8197. }
  8198. /* sf_sent<0 means error, thus fall back to the classic way */
  8199. /* This is always the case, if sf_file is not a "normal" file,
  8200. * e.g., for sending data from the output of a CGI process. */
  8201. offset = (int64_t)sf_offs;
  8202. }
  8203. #endif
  8204. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8205. mg_cry_internal(conn,
  8206. "%s: fseeko() failed: %s",
  8207. __func__,
  8208. strerror(ERRNO));
  8209. mg_send_http_error(
  8210. conn,
  8211. 500,
  8212. "%s",
  8213. "Error: Unable to access file at requested position.");
  8214. } else {
  8215. while (len > 0) {
  8216. /* Calculate how much to read from the file in the buffer */
  8217. to_read = sizeof(buf);
  8218. if ((int64_t)to_read > len) {
  8219. to_read = (int)len;
  8220. }
  8221. /* Read from file, exit the loop on error */
  8222. if ((num_read =
  8223. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8224. <= 0) {
  8225. break;
  8226. }
  8227. /* Send read bytes to the client, exit the loop on error */
  8228. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8229. != num_read) {
  8230. break;
  8231. }
  8232. /* Both read and were successful, adjust counters */
  8233. len -= num_written;
  8234. }
  8235. }
  8236. }
  8237. }
  8238. static int
  8239. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8240. {
  8241. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8242. }
  8243. static void
  8244. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8245. {
  8246. if ((filestat != NULL) && (buf != NULL)) {
  8247. mg_snprintf(NULL,
  8248. NULL, /* All calls to construct_etag use 64 byte buffer */
  8249. buf,
  8250. buf_len,
  8251. "\"%lx.%" INT64_FMT "\"",
  8252. (unsigned long)filestat->last_modified,
  8253. filestat->size);
  8254. }
  8255. }
  8256. static void
  8257. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8258. {
  8259. if (filep != NULL && filep->fp != NULL) {
  8260. #if defined(_WIN32)
  8261. (void)conn; /* Unused. */
  8262. #else
  8263. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8264. mg_cry_internal(conn,
  8265. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8266. __func__,
  8267. strerror(ERRNO));
  8268. }
  8269. #endif
  8270. }
  8271. }
  8272. #if defined(USE_ZLIB)
  8273. #include "mod_zlib.inl"
  8274. #endif
  8275. #if !defined(NO_FILESYSTEMS)
  8276. static void
  8277. handle_static_file_request(struct mg_connection *conn,
  8278. const char *path,
  8279. struct mg_file *filep,
  8280. const char *mime_type,
  8281. const char *additional_headers)
  8282. {
  8283. char date[64], lm[64], etag[64];
  8284. char range[128]; /* large enough, so there will be no overflow */
  8285. const char *msg = "OK";
  8286. const char *range_hdr;
  8287. time_t curtime = time(NULL);
  8288. int64_t cl, r1, r2;
  8289. struct vec mime_vec;
  8290. int n, truncated;
  8291. char gz_path[PATH_MAX];
  8292. const char *encoding = "";
  8293. const char *origin_hdr;
  8294. const char *cors_orig_cfg;
  8295. const char *cors1, *cors2, *cors3;
  8296. int is_head_request;
  8297. #if defined(USE_ZLIB)
  8298. /* Compression is allowed, unless there is a reason not to use compression.
  8299. * If the file is already compressed, too small or a "range" request was
  8300. * made, on the fly compression is not possible. */
  8301. int allow_on_the_fly_compression = 1;
  8302. #endif
  8303. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8304. return;
  8305. }
  8306. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8307. if (mime_type == NULL) {
  8308. get_mime_type(conn, path, &mime_vec);
  8309. } else {
  8310. mime_vec.ptr = mime_type;
  8311. mime_vec.len = strlen(mime_type);
  8312. }
  8313. if (filep->stat.size > INT64_MAX) {
  8314. mg_send_http_error(conn,
  8315. 500,
  8316. "Error: File size is too large to send\n%" INT64_FMT,
  8317. filep->stat.size);
  8318. return;
  8319. }
  8320. cl = (int64_t)filep->stat.size;
  8321. conn->status_code = 200;
  8322. range[0] = '\0';
  8323. #if defined(USE_ZLIB)
  8324. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8325. * it's important to rewrite the filename after resolving
  8326. * the mime type from it, to preserve the actual file's type */
  8327. if (!conn->accept_gzip) {
  8328. allow_on_the_fly_compression = 0;
  8329. }
  8330. #endif
  8331. /* Check if there is a range header */
  8332. range_hdr = mg_get_header(conn, "Range");
  8333. /* For gzipped files, add *.gz */
  8334. if (filep->stat.is_gzipped) {
  8335. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8336. if (truncated) {
  8337. mg_send_http_error(conn,
  8338. 500,
  8339. "Error: Path of zipped file too long (%s)",
  8340. path);
  8341. return;
  8342. }
  8343. path = gz_path;
  8344. encoding = "Content-Encoding: gzip\r\n";
  8345. #if defined(USE_ZLIB)
  8346. /* File is already compressed. No "on the fly" compression. */
  8347. allow_on_the_fly_compression = 0;
  8348. #endif
  8349. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8350. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8351. struct mg_file_stat file_stat;
  8352. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8353. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8354. && !file_stat.is_directory) {
  8355. file_stat.is_gzipped = 1;
  8356. filep->stat = file_stat;
  8357. cl = (int64_t)filep->stat.size;
  8358. path = gz_path;
  8359. encoding = "Content-Encoding: gzip\r\n";
  8360. #if defined(USE_ZLIB)
  8361. /* File is already compressed. No "on the fly" compression. */
  8362. allow_on_the_fly_compression = 0;
  8363. #endif
  8364. }
  8365. }
  8366. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8367. mg_send_http_error(conn,
  8368. 500,
  8369. "Error: Cannot open file\nfopen(%s): %s",
  8370. path,
  8371. strerror(ERRNO));
  8372. return;
  8373. }
  8374. fclose_on_exec(&filep->access, conn);
  8375. /* If "Range" request was made: parse header, send only selected part
  8376. * of the file. */
  8377. r1 = r2 = 0;
  8378. if ((range_hdr != NULL)
  8379. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8380. && (r2 >= 0)) {
  8381. /* actually, range requests don't play well with a pre-gzipped
  8382. * file (since the range is specified in the uncompressed space) */
  8383. if (filep->stat.is_gzipped) {
  8384. mg_send_http_error(
  8385. conn,
  8386. 416, /* 416 = Range Not Satisfiable */
  8387. "%s",
  8388. "Error: Range requests in gzipped files are not supported");
  8389. (void)mg_fclose(
  8390. &filep->access); /* ignore error on read only file */
  8391. return;
  8392. }
  8393. conn->status_code = 206;
  8394. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8395. mg_snprintf(conn,
  8396. NULL, /* range buffer is big enough */
  8397. range,
  8398. sizeof(range),
  8399. "Content-Range: bytes "
  8400. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8401. r1,
  8402. r1 + cl - 1,
  8403. filep->stat.size);
  8404. msg = "Partial Content";
  8405. #if defined(USE_ZLIB)
  8406. /* Do not compress ranges. */
  8407. allow_on_the_fly_compression = 0;
  8408. #endif
  8409. }
  8410. /* Do not compress small files. Small files do not benefit from file
  8411. * compression, but there is still some overhead. */
  8412. #if defined(USE_ZLIB)
  8413. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8414. /* File is below the size limit. */
  8415. allow_on_the_fly_compression = 0;
  8416. }
  8417. #endif
  8418. /* Standard CORS header */
  8419. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8420. origin_hdr = mg_get_header(conn, "Origin");
  8421. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8422. /* Cross-origin resource sharing (CORS), see
  8423. * http://www.html5rocks.com/en/tutorials/cors/,
  8424. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8425. * -
  8426. * preflight is not supported for files. */
  8427. cors1 = "Access-Control-Allow-Origin: ";
  8428. cors2 = cors_orig_cfg;
  8429. cors3 = "\r\n";
  8430. } else {
  8431. cors1 = cors2 = cors3 = "";
  8432. }
  8433. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8434. * according to
  8435. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8436. gmt_time_string(date, sizeof(date), &curtime);
  8437. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8438. construct_etag(etag, sizeof(etag), &filep->stat);
  8439. /* Send header */
  8440. (void)mg_printf(conn,
  8441. "HTTP/1.1 %d %s\r\n"
  8442. "%s%s%s" /* CORS */
  8443. "Date: %s\r\n"
  8444. "Last-Modified: %s\r\n"
  8445. "Etag: %s\r\n"
  8446. "Content-Type: %.*s\r\n"
  8447. "Connection: %s\r\n",
  8448. conn->status_code,
  8449. msg,
  8450. cors1,
  8451. cors2,
  8452. cors3,
  8453. date,
  8454. lm,
  8455. etag,
  8456. (int)mime_vec.len,
  8457. mime_vec.ptr,
  8458. suggest_connection_header(conn));
  8459. send_static_cache_header(conn);
  8460. send_additional_header(conn);
  8461. #if defined(USE_ZLIB)
  8462. /* On the fly compression allowed */
  8463. if (allow_on_the_fly_compression) {
  8464. /* For on the fly compression, we don't know the content size in
  8465. * advance, so we have to use chunked encoding */
  8466. (void)mg_printf(conn,
  8467. "Content-Encoding: gzip\r\n"
  8468. "Transfer-Encoding: chunked\r\n");
  8469. } else
  8470. #endif
  8471. {
  8472. /* Without on-the-fly compression, we know the content-length
  8473. * and we can use ranges (with on-the-fly compression we cannot).
  8474. * So we send these response headers only in this case. */
  8475. (void)mg_printf(conn,
  8476. "Content-Length: %" INT64_FMT "\r\n"
  8477. "Accept-Ranges: bytes\r\n"
  8478. "%s" /* range */
  8479. "%s" /* encoding */,
  8480. cl,
  8481. range,
  8482. encoding);
  8483. }
  8484. /* The previous code must not add any header starting with X- to make
  8485. * sure no one of the additional_headers is included twice */
  8486. if (additional_headers != NULL) {
  8487. (void)mg_printf(conn,
  8488. "%.*s\r\n\r\n",
  8489. (int)strlen(additional_headers),
  8490. additional_headers);
  8491. } else {
  8492. (void)mg_printf(conn, "\r\n");
  8493. }
  8494. if (!is_head_request) {
  8495. #if defined(USE_ZLIB)
  8496. if (allow_on_the_fly_compression) {
  8497. /* Compress and send */
  8498. send_compressed_data(conn, filep);
  8499. } else
  8500. #endif
  8501. {
  8502. /* Send file directly */
  8503. send_file_data(conn, filep, r1, cl);
  8504. }
  8505. }
  8506. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8507. }
  8508. int
  8509. mg_send_file_body(struct mg_connection *conn, const char *path)
  8510. {
  8511. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8512. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8513. return -1;
  8514. }
  8515. fclose_on_exec(&file.access, conn);
  8516. send_file_data(conn, &file, 0, INT64_MAX);
  8517. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8518. return 0; /* >= 0 for OK */
  8519. }
  8520. #endif /* NO_FILESYSTEMS */
  8521. #if !defined(NO_CACHING)
  8522. /* Return True if we should reply 304 Not Modified. */
  8523. static int
  8524. is_not_modified(const struct mg_connection *conn,
  8525. const struct mg_file_stat *filestat)
  8526. {
  8527. char etag[64];
  8528. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8529. const char *inm = mg_get_header(conn, "If-None-Match");
  8530. construct_etag(etag, sizeof(etag), filestat);
  8531. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8532. || ((ims != NULL)
  8533. && (filestat->last_modified <= parse_date_string(ims)));
  8534. }
  8535. static void
  8536. handle_not_modified_static_file_request(struct mg_connection *conn,
  8537. struct mg_file *filep)
  8538. {
  8539. char date[64], lm[64], etag[64];
  8540. time_t curtime = time(NULL);
  8541. if ((conn == NULL) || (filep == NULL)) {
  8542. return;
  8543. }
  8544. conn->status_code = 304;
  8545. gmt_time_string(date, sizeof(date), &curtime);
  8546. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8547. construct_etag(etag, sizeof(etag), &filep->stat);
  8548. (void)mg_printf(conn,
  8549. "HTTP/1.1 %d %s\r\n"
  8550. "Date: %s\r\n",
  8551. conn->status_code,
  8552. mg_get_response_code_text(conn, conn->status_code),
  8553. date);
  8554. send_static_cache_header(conn);
  8555. send_additional_header(conn);
  8556. (void)mg_printf(conn,
  8557. "Last-Modified: %s\r\n"
  8558. "Etag: %s\r\n"
  8559. "Connection: %s\r\n"
  8560. "\r\n",
  8561. lm,
  8562. etag,
  8563. suggest_connection_header(conn));
  8564. }
  8565. #endif
  8566. #if !defined(NO_FILESYSTEMS)
  8567. void
  8568. mg_send_file(struct mg_connection *conn, const char *path)
  8569. {
  8570. mg_send_mime_file2(conn, path, NULL, NULL);
  8571. }
  8572. void
  8573. mg_send_mime_file(struct mg_connection *conn,
  8574. const char *path,
  8575. const char *mime_type)
  8576. {
  8577. mg_send_mime_file2(conn, path, mime_type, NULL);
  8578. }
  8579. void
  8580. mg_send_mime_file2(struct mg_connection *conn,
  8581. const char *path,
  8582. const char *mime_type,
  8583. const char *additional_headers)
  8584. {
  8585. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8586. if (!conn) {
  8587. /* No conn */
  8588. return;
  8589. }
  8590. if (mg_stat(conn, path, &file.stat)) {
  8591. #if !defined(NO_CACHING)
  8592. if (is_not_modified(conn, &file.stat)) {
  8593. /* Send 304 "Not Modified" - this must not send any body data */
  8594. handle_not_modified_static_file_request(conn, &file);
  8595. } else
  8596. #endif /* NO_CACHING */
  8597. if (file.stat.is_directory) {
  8598. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8599. "yes")) {
  8600. handle_directory_request(conn, path);
  8601. } else {
  8602. mg_send_http_error(conn,
  8603. 403,
  8604. "%s",
  8605. "Error: Directory listing denied");
  8606. }
  8607. } else {
  8608. handle_static_file_request(
  8609. conn, path, &file, mime_type, additional_headers);
  8610. }
  8611. } else {
  8612. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8613. }
  8614. }
  8615. /* For a given PUT path, create all intermediate subdirectories.
  8616. * Return 0 if the path itself is a directory.
  8617. * Return 1 if the path leads to a file.
  8618. * Return -1 for if the path is too long.
  8619. * Return -2 if path can not be created.
  8620. */
  8621. static int
  8622. put_dir(struct mg_connection *conn, const char *path)
  8623. {
  8624. char buf[PATH_MAX];
  8625. const char *s, *p;
  8626. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8627. size_t len;
  8628. int res = 1;
  8629. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8630. len = (size_t)(p - path);
  8631. if (len >= sizeof(buf)) {
  8632. /* path too long */
  8633. res = -1;
  8634. break;
  8635. }
  8636. memcpy(buf, path, len);
  8637. buf[len] = '\0';
  8638. /* Try to create intermediate directory */
  8639. DEBUG_TRACE("mkdir(%s)", buf);
  8640. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8641. /* path does not exixt and can not be created */
  8642. res = -2;
  8643. break;
  8644. }
  8645. /* Is path itself a directory? */
  8646. if (p[1] == '\0') {
  8647. res = 0;
  8648. }
  8649. }
  8650. return res;
  8651. }
  8652. static void
  8653. remove_bad_file(const struct mg_connection *conn, const char *path)
  8654. {
  8655. int r = mg_remove(conn, path);
  8656. if (r != 0) {
  8657. mg_cry_internal(conn,
  8658. "%s: Cannot remove invalid file %s",
  8659. __func__,
  8660. path);
  8661. }
  8662. }
  8663. long long
  8664. mg_store_body(struct mg_connection *conn, const char *path)
  8665. {
  8666. char buf[MG_BUF_LEN];
  8667. long long len = 0;
  8668. int ret, n;
  8669. struct mg_file fi;
  8670. if (conn->consumed_content != 0) {
  8671. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8672. return -11;
  8673. }
  8674. ret = put_dir(conn, path);
  8675. if (ret < 0) {
  8676. /* -1 for path too long,
  8677. * -2 for path can not be created. */
  8678. return ret;
  8679. }
  8680. if (ret != 1) {
  8681. /* Return 0 means, path itself is a directory. */
  8682. return 0;
  8683. }
  8684. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8685. return -12;
  8686. }
  8687. ret = mg_read(conn, buf, sizeof(buf));
  8688. while (ret > 0) {
  8689. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8690. if (n != ret) {
  8691. (void)mg_fclose(
  8692. &fi.access); /* File is bad and will be removed anyway. */
  8693. remove_bad_file(conn, path);
  8694. return -13;
  8695. }
  8696. len += ret;
  8697. ret = mg_read(conn, buf, sizeof(buf));
  8698. }
  8699. /* File is open for writing. If fclose fails, there was probably an
  8700. * error flushing the buffer to disk, so the file on disk might be
  8701. * broken. Delete it and return an error to the caller. */
  8702. if (mg_fclose(&fi.access) != 0) {
  8703. remove_bad_file(conn, path);
  8704. return -14;
  8705. }
  8706. return len;
  8707. }
  8708. #endif /* NO_FILESYSTEMS */
  8709. /* Parse a buffer:
  8710. * Forward the string pointer till the end of a word, then
  8711. * terminate it and forward till the begin of the next word.
  8712. */
  8713. static int
  8714. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8715. {
  8716. /* Forward until a space is found - use isgraph here */
  8717. /* See http://www.cplusplus.com/reference/cctype/ */
  8718. while (isgraph((unsigned char)**ppw)) {
  8719. (*ppw)++;
  8720. }
  8721. /* Check end of word */
  8722. if (eol) {
  8723. /* must be a end of line */
  8724. if ((**ppw != '\r') && (**ppw != '\n')) {
  8725. return -1;
  8726. }
  8727. } else {
  8728. /* must be a end of a word, but not a line */
  8729. if (**ppw != ' ') {
  8730. return -1;
  8731. }
  8732. }
  8733. /* Terminate and forward to the next word */
  8734. do {
  8735. **ppw = 0;
  8736. (*ppw)++;
  8737. } while (isspace((unsigned char)**ppw));
  8738. /* Check after term */
  8739. if (!eol) {
  8740. /* if it's not the end of line, there must be a next word */
  8741. if (!isgraph((unsigned char)**ppw)) {
  8742. return -1;
  8743. }
  8744. }
  8745. /* ok */
  8746. return 1;
  8747. }
  8748. /* Parse HTTP headers from the given buffer, advance buf pointer
  8749. * to the point where parsing stopped.
  8750. * All parameters must be valid pointers (not NULL).
  8751. * Return <0 on error. */
  8752. static int
  8753. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8754. {
  8755. int i;
  8756. int num_headers = 0;
  8757. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8758. char *dp = *buf;
  8759. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  8760. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8761. dp++;
  8762. }
  8763. if (dp == *buf) {
  8764. /* End of headers reached. */
  8765. break;
  8766. }
  8767. if (*dp != ':') {
  8768. /* This is not a valid field. */
  8769. return -1;
  8770. }
  8771. /* End of header key (*dp == ':') */
  8772. /* Truncate here and set the key name */
  8773. *dp = 0;
  8774. hdr[i].name = *buf;
  8775. /* Skip all spaces */
  8776. do {
  8777. dp++;
  8778. } while ((*dp == ' ') || (*dp == '\t'));
  8779. /* The rest of the line is the value */
  8780. hdr[i].value = dp;
  8781. /* Find end of line */
  8782. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  8783. dp++;
  8784. };
  8785. /* eliminate \r */
  8786. if (*dp == '\r') {
  8787. *dp = 0;
  8788. dp++;
  8789. if (*dp != '\n') {
  8790. /* This is not a valid line. */
  8791. return -1;
  8792. }
  8793. }
  8794. /* here *dp is either 0 or '\n' */
  8795. /* in any case, we have a new header */
  8796. num_headers = i + 1;
  8797. if (*dp) {
  8798. *dp = 0;
  8799. dp++;
  8800. *buf = dp;
  8801. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  8802. /* This is the end of the header */
  8803. break;
  8804. }
  8805. } else {
  8806. *buf = dp;
  8807. break;
  8808. }
  8809. }
  8810. return num_headers;
  8811. }
  8812. struct mg_http_method_info {
  8813. const char *name;
  8814. int request_has_body;
  8815. int response_has_body;
  8816. int is_safe;
  8817. int is_idempotent;
  8818. int is_cacheable;
  8819. };
  8820. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8821. static struct mg_http_method_info http_methods[] = {
  8822. /* HTTP (RFC 2616) */
  8823. {"GET", 0, 1, 1, 1, 1},
  8824. {"POST", 1, 1, 0, 0, 0},
  8825. {"PUT", 1, 0, 0, 1, 0},
  8826. {"DELETE", 0, 0, 0, 1, 0},
  8827. {"HEAD", 0, 0, 1, 1, 1},
  8828. {"OPTIONS", 0, 0, 1, 1, 0},
  8829. {"CONNECT", 1, 1, 0, 0, 0},
  8830. /* TRACE method (RFC 2616) is not supported for security reasons */
  8831. /* PATCH method (RFC 5789) */
  8832. {"PATCH", 1, 0, 0, 0, 0},
  8833. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8834. /* WEBDAV (RFC 2518) */
  8835. {"PROPFIND", 0, 1, 1, 1, 0},
  8836. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8837. * Some PROPFIND results MAY be cached, with care,
  8838. * as there is no cache validation mechanism for
  8839. * most properties. This method is both safe and
  8840. * idempotent (see Section 9.1 of [RFC2616]). */
  8841. {"MKCOL", 0, 0, 0, 1, 0},
  8842. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8843. * When MKCOL is invoked without a request body,
  8844. * the newly created collection SHOULD have no
  8845. * members. A MKCOL request message may contain
  8846. * a message body. The precise behavior of a MKCOL
  8847. * request when the body is present is undefined,
  8848. * ... ==> We do not support MKCOL with body data.
  8849. * This method is idempotent, but not safe (see
  8850. * Section 9.1 of [RFC2616]). Responses to this
  8851. * method MUST NOT be cached. */
  8852. /* Unsupported WEBDAV Methods: */
  8853. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8854. /* + 11 methods from RFC 3253 */
  8855. /* ORDERPATCH (RFC 3648) */
  8856. /* ACL (RFC 3744) */
  8857. /* SEARCH (RFC 5323) */
  8858. /* + MicroSoft extensions
  8859. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8860. /* REPORT method (RFC 3253) */
  8861. {"REPORT", 1, 1, 1, 1, 1},
  8862. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8863. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8864. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8865. * to be useful for REST in case a "GET request with body" is
  8866. * required. */
  8867. {NULL, 0, 0, 0, 0, 0}
  8868. /* end of list */
  8869. };
  8870. static const struct mg_http_method_info *
  8871. get_http_method_info(const char *method)
  8872. {
  8873. /* Check if the method is known to the server. The list of all known
  8874. * HTTP methods can be found here at
  8875. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8876. */
  8877. const struct mg_http_method_info *m = http_methods;
  8878. while (m->name) {
  8879. if (!strcmp(m->name, method)) {
  8880. return m;
  8881. }
  8882. m++;
  8883. }
  8884. return NULL;
  8885. }
  8886. static int
  8887. is_valid_http_method(const char *method)
  8888. {
  8889. return (get_http_method_info(method) != NULL);
  8890. }
  8891. /* Parse HTTP request, fill in mg_request_info structure.
  8892. * This function modifies the buffer by NUL-terminating
  8893. * HTTP request components, header names and header values.
  8894. * Parameters:
  8895. * buf (in/out): pointer to the HTTP header to parse and split
  8896. * len (in): length of HTTP header buffer
  8897. * re (out): parsed header as mg_request_info
  8898. * buf and ri must be valid pointers (not NULL), len>0.
  8899. * Returns <0 on error. */
  8900. static int
  8901. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8902. {
  8903. int request_length;
  8904. int init_skip = 0;
  8905. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8906. * remote_port */
  8907. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8908. NULL;
  8909. ri->num_headers = 0;
  8910. /* RFC says that all initial whitespaces should be ingored */
  8911. /* This included all leading \r and \n (isspace) */
  8912. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8913. while ((len > 0) && isspace((unsigned char)*buf)) {
  8914. buf++;
  8915. len--;
  8916. init_skip++;
  8917. }
  8918. if (len == 0) {
  8919. /* Incomplete request */
  8920. return 0;
  8921. }
  8922. /* Control characters are not allowed, including zero */
  8923. if (iscntrl((unsigned char)*buf)) {
  8924. return -1;
  8925. }
  8926. /* Find end of HTTP header */
  8927. request_length = get_http_header_len(buf, len);
  8928. if (request_length <= 0) {
  8929. return request_length;
  8930. }
  8931. buf[request_length - 1] = '\0';
  8932. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8933. return -1;
  8934. }
  8935. /* The first word has to be the HTTP method */
  8936. ri->request_method = buf;
  8937. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8938. return -1;
  8939. }
  8940. /* Check for a valid http method */
  8941. if (!is_valid_http_method(ri->request_method)) {
  8942. return -1;
  8943. }
  8944. /* The second word is the URI */
  8945. ri->request_uri = buf;
  8946. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8947. return -1;
  8948. }
  8949. /* Next would be the HTTP version */
  8950. ri->http_version = buf;
  8951. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8952. return -1;
  8953. }
  8954. /* Check for a valid HTTP version key */
  8955. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8956. /* Invalid request */
  8957. return -1;
  8958. }
  8959. ri->http_version += 5;
  8960. /* Parse all HTTP headers */
  8961. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8962. if (ri->num_headers < 0) {
  8963. /* Error while parsing headers */
  8964. return -1;
  8965. }
  8966. return request_length + init_skip;
  8967. }
  8968. static int
  8969. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8970. {
  8971. int response_length;
  8972. int init_skip = 0;
  8973. char *tmp, *tmp2;
  8974. long l;
  8975. /* Initialize elements. */
  8976. ri->http_version = ri->status_text = NULL;
  8977. ri->num_headers = ri->status_code = 0;
  8978. /* RFC says that all initial whitespaces should be ingored */
  8979. /* This included all leading \r and \n (isspace) */
  8980. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8981. while ((len > 0) && isspace((unsigned char)*buf)) {
  8982. buf++;
  8983. len--;
  8984. init_skip++;
  8985. }
  8986. if (len == 0) {
  8987. /* Incomplete request */
  8988. return 0;
  8989. }
  8990. /* Control characters are not allowed, including zero */
  8991. if (iscntrl((unsigned char)*buf)) {
  8992. return -1;
  8993. }
  8994. /* Find end of HTTP header */
  8995. response_length = get_http_header_len(buf, len);
  8996. if (response_length <= 0) {
  8997. return response_length;
  8998. }
  8999. buf[response_length - 1] = '\0';
  9000. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  9001. return -1;
  9002. }
  9003. /* The first word is the HTTP version */
  9004. /* Check for a valid HTTP version key */
  9005. if (strncmp(buf, "HTTP/", 5) != 0) {
  9006. /* Invalid request */
  9007. return -1;
  9008. }
  9009. buf += 5;
  9010. if (!isgraph((unsigned char)buf[0])) {
  9011. /* Invalid request */
  9012. return -1;
  9013. }
  9014. ri->http_version = buf;
  9015. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9016. return -1;
  9017. }
  9018. /* The second word is the status as a number */
  9019. tmp = buf;
  9020. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9021. return -1;
  9022. }
  9023. l = strtol(tmp, &tmp2, 10);
  9024. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9025. /* Everything else but a 3 digit code is invalid */
  9026. return -1;
  9027. }
  9028. ri->status_code = (int)l;
  9029. /* The rest of the line is the status text */
  9030. ri->status_text = buf;
  9031. /* Find end of status text */
  9032. /* isgraph or isspace = isprint */
  9033. while (isprint((unsigned char)*buf)) {
  9034. buf++;
  9035. }
  9036. if ((*buf != '\r') && (*buf != '\n')) {
  9037. return -1;
  9038. }
  9039. /* Terminate string and forward buf to next line */
  9040. do {
  9041. *buf = 0;
  9042. buf++;
  9043. } while (isspace((unsigned char)*buf));
  9044. /* Parse all HTTP headers */
  9045. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9046. if (ri->num_headers < 0) {
  9047. /* Error while parsing headers */
  9048. return -1;
  9049. }
  9050. return response_length + init_skip;
  9051. }
  9052. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9053. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9054. * buffer (which marks the end of HTTP request). Buffer buf may already
  9055. * have some data. The length of the data is stored in nread.
  9056. * Upon every read operation, increase nread by the number of bytes read. */
  9057. static int
  9058. read_message(FILE *fp,
  9059. struct mg_connection *conn,
  9060. char *buf,
  9061. int bufsiz,
  9062. int *nread)
  9063. {
  9064. int request_len, n = 0;
  9065. struct timespec last_action_time;
  9066. double request_timeout;
  9067. if (!conn) {
  9068. return 0;
  9069. }
  9070. memset(&last_action_time, 0, sizeof(last_action_time));
  9071. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9072. /* value of request_timeout is in seconds, config in milliseconds */
  9073. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9074. } else {
  9075. request_timeout = -1.0;
  9076. }
  9077. if (conn->handled_requests > 0) {
  9078. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9079. request_timeout =
  9080. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9081. }
  9082. }
  9083. request_len = get_http_header_len(buf, *nread);
  9084. while (request_len == 0) {
  9085. /* Full request not yet received */
  9086. if (conn->phys_ctx->stop_flag != 0) {
  9087. /* Server is to be stopped. */
  9088. return -1;
  9089. }
  9090. if (*nread >= bufsiz) {
  9091. /* Request too long */
  9092. return -2;
  9093. }
  9094. n = pull_inner(
  9095. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9096. if (n == -2) {
  9097. /* Receive error */
  9098. return -1;
  9099. }
  9100. /* update clock after every read request */
  9101. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9102. if (n > 0) {
  9103. *nread += n;
  9104. request_len = get_http_header_len(buf, *nread);
  9105. } else {
  9106. request_len = 0;
  9107. }
  9108. if ((request_len == 0) && (request_timeout >= 0)) {
  9109. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9110. > request_timeout) {
  9111. /* Timeout */
  9112. return -1;
  9113. }
  9114. }
  9115. }
  9116. return request_len;
  9117. }
  9118. #if !defined(NO_CGI) || !defined(NO_FILES)
  9119. static int
  9120. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9121. {
  9122. const char *expect;
  9123. char buf[MG_BUF_LEN];
  9124. int success = 0;
  9125. if (!conn) {
  9126. return 0;
  9127. }
  9128. expect = mg_get_header(conn, "Expect");
  9129. DEBUG_ASSERT(fp != NULL);
  9130. if (!fp) {
  9131. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9132. return 0;
  9133. }
  9134. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9135. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9136. */
  9137. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9138. } else {
  9139. if (expect != NULL) {
  9140. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9141. conn->status_code = 100;
  9142. } else {
  9143. conn->status_code = 200;
  9144. }
  9145. DEBUG_ASSERT(conn->consumed_content == 0);
  9146. if (conn->consumed_content != 0) {
  9147. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9148. return 0;
  9149. }
  9150. for (;;) {
  9151. int nread = mg_read(conn, buf, sizeof(buf));
  9152. if (nread <= 0) {
  9153. success = (nread == 0);
  9154. break;
  9155. }
  9156. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9157. break;
  9158. }
  9159. }
  9160. /* Each error code path in this function must send an error */
  9161. if (!success) {
  9162. /* NOTE: Maybe some data has already been sent. */
  9163. /* TODO (low): If some data has been sent, a correct error
  9164. * reply can no longer be sent, so just close the connection */
  9165. mg_send_http_error(conn, 500, "%s", "");
  9166. }
  9167. }
  9168. return success;
  9169. }
  9170. #endif
  9171. #if defined(USE_TIMERS)
  9172. #define TIMER_API static
  9173. #include "timer.inl"
  9174. #endif /* USE_TIMERS */
  9175. #if !defined(NO_CGI)
  9176. /* This structure helps to create an environment for the spawned CGI
  9177. * program.
  9178. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9179. * last element must be NULL.
  9180. * However, on Windows there is a requirement that all these
  9181. * VARIABLE=VALUE\0
  9182. * strings must reside in a contiguous buffer. The end of the buffer is
  9183. * marked by two '\0' characters.
  9184. * We satisfy both worlds: we create an envp array (which is vars), all
  9185. * entries are actually pointers inside buf. */
  9186. struct cgi_environment {
  9187. struct mg_connection *conn;
  9188. /* Data block */
  9189. char *buf; /* Environment buffer */
  9190. size_t buflen; /* Space available in buf */
  9191. size_t bufused; /* Space taken in buf */
  9192. /* Index block */
  9193. char **var; /* char **envp */
  9194. size_t varlen; /* Number of variables available in var */
  9195. size_t varused; /* Number of variables stored in var */
  9196. };
  9197. static void addenv(struct cgi_environment *env,
  9198. PRINTF_FORMAT_STRING(const char *fmt),
  9199. ...) PRINTF_ARGS(2, 3);
  9200. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9201. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9202. static void
  9203. addenv(struct cgi_environment *env, const char *fmt, ...)
  9204. {
  9205. size_t i, n, space;
  9206. int truncated = 0;
  9207. char *added;
  9208. va_list ap;
  9209. if ((env->varlen - env->varused) < 2) {
  9210. mg_cry_internal(env->conn,
  9211. "%s: Cannot register CGI variable [%s]",
  9212. __func__,
  9213. fmt);
  9214. return;
  9215. }
  9216. /* Calculate how much space is left in the buffer */
  9217. space = (env->buflen - env->bufused);
  9218. do {
  9219. /* Space for "\0\0" is always needed. */
  9220. if (space <= 2) {
  9221. /* Allocate new buffer */
  9222. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9223. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9224. if (!added) {
  9225. /* Out of memory */
  9226. mg_cry_internal(
  9227. env->conn,
  9228. "%s: Cannot allocate memory for CGI variable [%s]",
  9229. __func__,
  9230. fmt);
  9231. return;
  9232. }
  9233. /* Retarget pointers */
  9234. env->buf = added;
  9235. env->buflen = n;
  9236. for (i = 0, n = 0; i < env->varused; i++) {
  9237. env->var[i] = added + n;
  9238. n += strlen(added + n) + 1;
  9239. }
  9240. space = (env->buflen - env->bufused);
  9241. }
  9242. /* Make a pointer to the free space int the buffer */
  9243. added = env->buf + env->bufused;
  9244. /* Copy VARIABLE=VALUE\0 string into the free space */
  9245. va_start(ap, fmt);
  9246. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9247. va_end(ap);
  9248. /* Do not add truncated strings to the environment */
  9249. if (truncated) {
  9250. /* Reallocate the buffer */
  9251. space = 0;
  9252. }
  9253. } while (truncated);
  9254. /* Calculate number of bytes added to the environment */
  9255. n = strlen(added) + 1;
  9256. env->bufused += n;
  9257. /* Append a pointer to the added string into the envp array */
  9258. env->var[env->varused] = added;
  9259. env->varused++;
  9260. }
  9261. /* Return 0 on success, non-zero if an error occurs. */
  9262. static int
  9263. prepare_cgi_environment(struct mg_connection *conn,
  9264. const char *prog,
  9265. struct cgi_environment *env)
  9266. {
  9267. const char *s;
  9268. struct vec var_vec;
  9269. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9270. int i, truncated, uri_len;
  9271. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9272. return -1;
  9273. }
  9274. env->conn = conn;
  9275. env->buflen = CGI_ENVIRONMENT_SIZE;
  9276. env->bufused = 0;
  9277. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9278. if (env->buf == NULL) {
  9279. mg_cry_internal(conn,
  9280. "%s: Not enough memory for environmental buffer",
  9281. __func__);
  9282. return -1;
  9283. }
  9284. env->varlen = MAX_CGI_ENVIR_VARS;
  9285. env->varused = 0;
  9286. env->var =
  9287. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9288. if (env->var == NULL) {
  9289. mg_cry_internal(conn,
  9290. "%s: Not enough memory for environmental variables",
  9291. __func__);
  9292. mg_free(env->buf);
  9293. return -1;
  9294. }
  9295. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9296. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9297. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9298. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9299. /* Prepare the environment block */
  9300. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9301. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9302. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9303. #if defined(USE_IPV6)
  9304. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9305. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9306. } else
  9307. #endif
  9308. {
  9309. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9310. }
  9311. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9312. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9313. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9314. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9315. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9316. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9317. /* SCRIPT_NAME */
  9318. uri_len = (int)strlen(conn->request_info.local_uri);
  9319. if (conn->path_info == NULL) {
  9320. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9321. /* URI: /path_to_script/script.cgi */
  9322. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9323. } else {
  9324. /* URI: /path_to_script/ ... using index.cgi */
  9325. const char *index_file = strrchr(prog, '/');
  9326. if (index_file) {
  9327. addenv(env,
  9328. "SCRIPT_NAME=%s%s",
  9329. conn->request_info.local_uri,
  9330. index_file + 1);
  9331. }
  9332. }
  9333. } else {
  9334. /* URI: /path_to_script/script.cgi/path_info */
  9335. addenv(env,
  9336. "SCRIPT_NAME=%.*s",
  9337. uri_len - (int)strlen(conn->path_info),
  9338. conn->request_info.local_uri);
  9339. }
  9340. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9341. if (conn->path_info == NULL) {
  9342. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9343. } else {
  9344. addenv(env,
  9345. "PATH_TRANSLATED=%s%s",
  9346. conn->dom_ctx->config[DOCUMENT_ROOT],
  9347. conn->path_info);
  9348. }
  9349. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9350. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9351. addenv(env, "CONTENT_TYPE=%s", s);
  9352. }
  9353. if (conn->request_info.query_string != NULL) {
  9354. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9355. }
  9356. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9357. addenv(env, "CONTENT_LENGTH=%s", s);
  9358. }
  9359. if ((s = getenv("PATH")) != NULL) {
  9360. addenv(env, "PATH=%s", s);
  9361. }
  9362. if (conn->path_info != NULL) {
  9363. addenv(env, "PATH_INFO=%s", conn->path_info);
  9364. }
  9365. if (conn->status_code > 0) {
  9366. /* CGI error handler should show the status code */
  9367. addenv(env, "STATUS=%d", conn->status_code);
  9368. }
  9369. #if defined(_WIN32)
  9370. if ((s = getenv("COMSPEC")) != NULL) {
  9371. addenv(env, "COMSPEC=%s", s);
  9372. }
  9373. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9374. addenv(env, "SYSTEMROOT=%s", s);
  9375. }
  9376. if ((s = getenv("SystemDrive")) != NULL) {
  9377. addenv(env, "SystemDrive=%s", s);
  9378. }
  9379. if ((s = getenv("ProgramFiles")) != NULL) {
  9380. addenv(env, "ProgramFiles=%s", s);
  9381. }
  9382. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9383. addenv(env, "ProgramFiles(x86)=%s", s);
  9384. }
  9385. #else
  9386. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9387. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9388. }
  9389. #endif /* _WIN32 */
  9390. if ((s = getenv("PERLLIB")) != NULL) {
  9391. addenv(env, "PERLLIB=%s", s);
  9392. }
  9393. if (conn->request_info.remote_user != NULL) {
  9394. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9395. addenv(env, "%s", "AUTH_TYPE=Digest");
  9396. }
  9397. /* Add all headers as HTTP_* variables */
  9398. for (i = 0; i < conn->request_info.num_headers; i++) {
  9399. (void)mg_snprintf(conn,
  9400. &truncated,
  9401. http_var_name,
  9402. sizeof(http_var_name),
  9403. "HTTP_%s",
  9404. conn->request_info.http_headers[i].name);
  9405. if (truncated) {
  9406. mg_cry_internal(conn,
  9407. "%s: HTTP header variable too long [%s]",
  9408. __func__,
  9409. conn->request_info.http_headers[i].name);
  9410. continue;
  9411. }
  9412. /* Convert variable name into uppercase, and change - to _ */
  9413. for (p = http_var_name; *p != '\0'; p++) {
  9414. if (*p == '-') {
  9415. *p = '_';
  9416. }
  9417. *p = (char)toupper((unsigned char)*p);
  9418. }
  9419. addenv(env,
  9420. "%s=%s",
  9421. http_var_name,
  9422. conn->request_info.http_headers[i].value);
  9423. }
  9424. /* Add user-specified variables */
  9425. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9426. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9427. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9428. }
  9429. env->var[env->varused] = NULL;
  9430. env->buf[env->bufused] = '\0';
  9431. return 0;
  9432. }
  9433. /* Data for CGI process control: PID and number of references */
  9434. struct process_control_data {
  9435. pid_t pid;
  9436. int references;
  9437. };
  9438. static int
  9439. abort_process(void *data)
  9440. {
  9441. /* Waitpid checks for child status and won't work for a pid that does not
  9442. * identify a child of the current process. Thus, if the pid is reused,
  9443. * we will not affect a different process. */
  9444. struct process_control_data *proc = (struct process_control_data *)data;
  9445. int status = 0;
  9446. int refs;
  9447. pid_t ret_pid;
  9448. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9449. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9450. /* Stop child process */
  9451. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9452. kill(proc->pid, SIGABRT);
  9453. /* Wait until process is terminated (don't leave zombies) */
  9454. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9455. ;
  9456. } else {
  9457. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9458. }
  9459. /* Dec reference counter */
  9460. refs = mg_atomic_dec(&proc->references);
  9461. if (refs == 0) {
  9462. /* no more references - free data */
  9463. mg_free(data);
  9464. }
  9465. return 0;
  9466. }
  9467. /* Local (static) function assumes all arguments are valid. */
  9468. static void
  9469. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9470. {
  9471. char *buf;
  9472. size_t buflen;
  9473. int headers_len, data_len, i, truncated;
  9474. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9475. const char *status, *status_text, *connection_state;
  9476. char *pbuf, dir[PATH_MAX], *p;
  9477. struct mg_request_info ri;
  9478. struct cgi_environment blk;
  9479. FILE *in = NULL, *out = NULL, *err = NULL;
  9480. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9481. pid_t pid = (pid_t)-1;
  9482. struct process_control_data *proc = NULL;
  9483. #if defined(USE_TIMERS)
  9484. double cgi_timeout = -1.0;
  9485. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9486. /* Get timeout in seconds */
  9487. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9488. }
  9489. #endif
  9490. buf = NULL;
  9491. buflen = conn->phys_ctx->max_request_size;
  9492. i = prepare_cgi_environment(conn, prog, &blk);
  9493. if (i != 0) {
  9494. blk.buf = NULL;
  9495. blk.var = NULL;
  9496. goto done;
  9497. }
  9498. /* CGI must be executed in its own directory. 'dir' must point to the
  9499. * directory containing executable program, 'p' must point to the
  9500. * executable program name relative to 'dir'. */
  9501. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9502. if (truncated) {
  9503. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9504. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9505. goto done;
  9506. }
  9507. if ((p = strrchr(dir, '/')) != NULL) {
  9508. *p++ = '\0';
  9509. } else {
  9510. dir[0] = '.';
  9511. dir[1] = '\0';
  9512. p = (char *)prog;
  9513. }
  9514. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9515. status = strerror(ERRNO);
  9516. mg_cry_internal(
  9517. conn,
  9518. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9519. prog,
  9520. status);
  9521. mg_send_http_error(conn,
  9522. 500,
  9523. "Error: Cannot create CGI pipe: %s",
  9524. status);
  9525. goto done;
  9526. }
  9527. proc = (struct process_control_data *)
  9528. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9529. if (proc == NULL) {
  9530. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9531. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9532. goto done;
  9533. }
  9534. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9535. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9536. if (pid == (pid_t)-1) {
  9537. status = strerror(ERRNO);
  9538. mg_cry_internal(
  9539. conn,
  9540. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9541. prog,
  9542. status);
  9543. mg_send_http_error(conn,
  9544. 500,
  9545. "Error: Cannot spawn CGI process [%s]: %s",
  9546. prog,
  9547. status);
  9548. mg_free(proc);
  9549. proc = NULL;
  9550. goto done;
  9551. }
  9552. /* Store data in shared process_control_data */
  9553. proc->pid = pid;
  9554. proc->references = 1;
  9555. #if defined(USE_TIMERS)
  9556. if (cgi_timeout > 0.0) {
  9557. proc->references = 2;
  9558. // Start a timer for CGI
  9559. timer_add(conn->phys_ctx,
  9560. cgi_timeout /* in seconds */,
  9561. 0.0,
  9562. 1,
  9563. abort_process,
  9564. (void *)proc);
  9565. }
  9566. #endif
  9567. /* Parent closes only one side of the pipes.
  9568. * If we don't mark them as closed, close() attempt before
  9569. * return from this function throws an exception on Windows.
  9570. * Windows does not like when closed descriptor is closed again. */
  9571. (void)close(fdin[0]);
  9572. (void)close(fdout[1]);
  9573. (void)close(fderr[1]);
  9574. fdin[0] = fdout[1] = fderr[1] = -1;
  9575. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9576. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9577. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9578. status = strerror(ERRNO);
  9579. mg_cry_internal(conn,
  9580. "Error: CGI program \"%s\": Can not open fd: %s",
  9581. prog,
  9582. status);
  9583. mg_send_http_error(conn,
  9584. 500,
  9585. "Error: CGI can not open fd\nfdopen: %s",
  9586. status);
  9587. goto done;
  9588. }
  9589. setbuf(in, NULL);
  9590. setbuf(out, NULL);
  9591. setbuf(err, NULL);
  9592. fout.access.fp = out;
  9593. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9594. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9595. conn->content_len);
  9596. /* This is a POST/PUT request, or another request with body data. */
  9597. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9598. /* Error sending the body data */
  9599. mg_cry_internal(
  9600. conn,
  9601. "Error: CGI program \"%s\": Forward body data failed",
  9602. prog);
  9603. goto done;
  9604. }
  9605. }
  9606. /* Close so child gets an EOF. */
  9607. fclose(in);
  9608. in = NULL;
  9609. fdin[1] = -1;
  9610. /* Now read CGI reply into a buffer. We need to set correct
  9611. * status code, thus we need to see all HTTP headers first.
  9612. * Do not send anything back to client, until we buffer in all
  9613. * HTTP headers. */
  9614. data_len = 0;
  9615. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9616. if (buf == NULL) {
  9617. mg_send_http_error(conn,
  9618. 500,
  9619. "Error: Not enough memory for CGI buffer (%u bytes)",
  9620. (unsigned int)buflen);
  9621. mg_cry_internal(
  9622. conn,
  9623. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9624. "bytes)",
  9625. prog,
  9626. (unsigned int)buflen);
  9627. goto done;
  9628. }
  9629. DEBUG_TRACE("CGI: %s", "wait for response");
  9630. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9631. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9632. if (headers_len <= 0) {
  9633. /* Could not parse the CGI response. Check if some error message on
  9634. * stderr. */
  9635. i = pull_all(err, conn, buf, (int)buflen);
  9636. if (i > 0) {
  9637. /* CGI program explicitly sent an error */
  9638. /* Write the error message to the internal log */
  9639. mg_cry_internal(conn,
  9640. "Error: CGI program \"%s\" sent error "
  9641. "message: [%.*s]",
  9642. prog,
  9643. i,
  9644. buf);
  9645. /* Don't send the error message back to the client */
  9646. mg_send_http_error(conn,
  9647. 500,
  9648. "Error: CGI program \"%s\" failed.",
  9649. prog);
  9650. } else {
  9651. /* CGI program did not explicitly send an error, but a broken
  9652. * respon header */
  9653. mg_cry_internal(conn,
  9654. "Error: CGI program sent malformed or too big "
  9655. "(>%u bytes) HTTP headers: [%.*s]",
  9656. (unsigned)buflen,
  9657. data_len,
  9658. buf);
  9659. mg_send_http_error(conn,
  9660. 500,
  9661. "Error: CGI program sent malformed or too big "
  9662. "(>%u bytes) HTTP headers: [%.*s]",
  9663. (unsigned)buflen,
  9664. data_len,
  9665. buf);
  9666. }
  9667. /* in both cases, abort processing CGI */
  9668. goto done;
  9669. }
  9670. pbuf = buf;
  9671. buf[headers_len - 1] = '\0';
  9672. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9673. /* Make up and send the status line */
  9674. status_text = "OK";
  9675. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9676. != NULL) {
  9677. conn->status_code = atoi(status);
  9678. status_text = status;
  9679. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9680. status_text++;
  9681. }
  9682. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9683. != NULL) {
  9684. conn->status_code = 307;
  9685. } else {
  9686. conn->status_code = 200;
  9687. }
  9688. connection_state =
  9689. get_header(ri.http_headers, ri.num_headers, "Connection");
  9690. if (!header_has_option(connection_state, "keep-alive")) {
  9691. conn->must_close = 1;
  9692. }
  9693. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9694. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9695. /* Send headers */
  9696. for (i = 0; i < ri.num_headers; i++) {
  9697. DEBUG_TRACE("CGI header: %s: %s",
  9698. ri.http_headers[i].name,
  9699. ri.http_headers[i].value);
  9700. mg_printf(conn,
  9701. "%s: %s\r\n",
  9702. ri.http_headers[i].name,
  9703. ri.http_headers[i].value);
  9704. }
  9705. mg_write(conn, "\r\n", 2);
  9706. /* Send chunk of data that may have been read after the headers */
  9707. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9708. /* Read the rest of CGI output and send to the client */
  9709. DEBUG_TRACE("CGI: %s", "forward all data");
  9710. send_file_data(conn, &fout, 0, INT64_MAX);
  9711. DEBUG_TRACE("CGI: %s", "all data sent");
  9712. done:
  9713. mg_free(blk.var);
  9714. mg_free(blk.buf);
  9715. if (pid != (pid_t)-1) {
  9716. abort_process((void *)proc);
  9717. }
  9718. if (fdin[0] != -1) {
  9719. close(fdin[0]);
  9720. }
  9721. if (fdout[1] != -1) {
  9722. close(fdout[1]);
  9723. }
  9724. if (fderr[1] != -1) {
  9725. close(fderr[1]);
  9726. }
  9727. if (in != NULL) {
  9728. fclose(in);
  9729. } else if (fdin[1] != -1) {
  9730. close(fdin[1]);
  9731. }
  9732. if (out != NULL) {
  9733. fclose(out);
  9734. } else if (fdout[0] != -1) {
  9735. close(fdout[0]);
  9736. }
  9737. if (err != NULL) {
  9738. fclose(err);
  9739. } else if (fderr[0] != -1) {
  9740. close(fderr[0]);
  9741. }
  9742. mg_free(buf);
  9743. }
  9744. #endif /* !NO_CGI */
  9745. #if !defined(NO_FILES)
  9746. static void
  9747. mkcol(struct mg_connection *conn, const char *path)
  9748. {
  9749. int rc, body_len;
  9750. struct de de;
  9751. char date[64];
  9752. time_t curtime = time(NULL);
  9753. if (conn == NULL) {
  9754. return;
  9755. }
  9756. /* TODO (mid): Check the mg_send_http_error situations in this function
  9757. */
  9758. memset(&de.file, 0, sizeof(de.file));
  9759. if (!mg_stat(conn, path, &de.file)) {
  9760. mg_cry_internal(conn,
  9761. "%s: mg_stat(%s) failed: %s",
  9762. __func__,
  9763. path,
  9764. strerror(ERRNO));
  9765. }
  9766. if (de.file.last_modified) {
  9767. /* TODO (mid): This check does not seem to make any sense ! */
  9768. /* TODO (mid): Add a webdav unit test first, before changing
  9769. * anything here. */
  9770. mg_send_http_error(
  9771. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9772. return;
  9773. }
  9774. body_len = conn->data_len - conn->request_len;
  9775. if (body_len > 0) {
  9776. mg_send_http_error(
  9777. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9778. return;
  9779. }
  9780. rc = mg_mkdir(conn, path, 0755);
  9781. if (rc == 0) {
  9782. conn->status_code = 201;
  9783. gmt_time_string(date, sizeof(date), &curtime);
  9784. mg_printf(conn,
  9785. "HTTP/1.1 %d Created\r\n"
  9786. "Date: %s\r\n",
  9787. conn->status_code,
  9788. date);
  9789. send_static_cache_header(conn);
  9790. send_additional_header(conn);
  9791. mg_printf(conn,
  9792. "Content-Length: 0\r\n"
  9793. "Connection: %s\r\n\r\n",
  9794. suggest_connection_header(conn));
  9795. } else {
  9796. if (errno == EEXIST) {
  9797. mg_send_http_error(
  9798. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9799. } else if (errno == EACCES) {
  9800. mg_send_http_error(
  9801. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9802. } else if (errno == ENOENT) {
  9803. mg_send_http_error(
  9804. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9805. } else {
  9806. mg_send_http_error(
  9807. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9808. }
  9809. }
  9810. }
  9811. static void
  9812. put_file(struct mg_connection *conn, const char *path)
  9813. {
  9814. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9815. const char *range;
  9816. int64_t r1, r2;
  9817. int rc;
  9818. char date[64];
  9819. time_t curtime = time(NULL);
  9820. if (conn == NULL) {
  9821. return;
  9822. }
  9823. if (mg_stat(conn, path, &file.stat)) {
  9824. /* File already exists */
  9825. conn->status_code = 200;
  9826. if (file.stat.is_directory) {
  9827. /* This is an already existing directory,
  9828. * so there is nothing to do for the server. */
  9829. rc = 0;
  9830. } else {
  9831. /* File exists and is not a directory. */
  9832. /* Can it be replaced? */
  9833. #if defined(MG_USE_OPEN_FILE)
  9834. if (file.access.membuf != NULL) {
  9835. /* This is an "in-memory" file, that can not be replaced */
  9836. mg_send_http_error(conn,
  9837. 405,
  9838. "Error: Put not possible\nReplacing %s "
  9839. "is not supported",
  9840. path);
  9841. return;
  9842. }
  9843. #endif
  9844. /* Check if the server may write this file */
  9845. if (access(path, W_OK) == 0) {
  9846. /* Access granted */
  9847. conn->status_code = 200;
  9848. rc = 1;
  9849. } else {
  9850. mg_send_http_error(
  9851. conn,
  9852. 403,
  9853. "Error: Put not possible\nReplacing %s is not allowed",
  9854. path);
  9855. return;
  9856. }
  9857. }
  9858. } else {
  9859. /* File should be created */
  9860. conn->status_code = 201;
  9861. rc = put_dir(conn, path);
  9862. }
  9863. if (rc == 0) {
  9864. /* put_dir returns 0 if path is a directory */
  9865. gmt_time_string(date, sizeof(date), &curtime);
  9866. mg_printf(conn,
  9867. "HTTP/1.1 %d %s\r\n",
  9868. conn->status_code,
  9869. mg_get_response_code_text(NULL, conn->status_code));
  9870. send_no_cache_header(conn);
  9871. send_additional_header(conn);
  9872. mg_printf(conn,
  9873. "Date: %s\r\n"
  9874. "Content-Length: 0\r\n"
  9875. "Connection: %s\r\n\r\n",
  9876. date,
  9877. suggest_connection_header(conn));
  9878. /* Request to create a directory has been fulfilled successfully.
  9879. * No need to put a file. */
  9880. return;
  9881. }
  9882. if (rc == -1) {
  9883. /* put_dir returns -1 if the path is too long */
  9884. mg_send_http_error(conn,
  9885. 414,
  9886. "Error: Path too long\nput_dir(%s): %s",
  9887. path,
  9888. strerror(ERRNO));
  9889. return;
  9890. }
  9891. if (rc == -2) {
  9892. /* put_dir returns -2 if the directory can not be created */
  9893. mg_send_http_error(conn,
  9894. 500,
  9895. "Error: Can not create directory\nput_dir(%s): %s",
  9896. path,
  9897. strerror(ERRNO));
  9898. return;
  9899. }
  9900. /* A file should be created or overwritten. */
  9901. /* Currently CivetWeb does not nead read+write access. */
  9902. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9903. || file.access.fp == NULL) {
  9904. (void)mg_fclose(&file.access);
  9905. mg_send_http_error(conn,
  9906. 500,
  9907. "Error: Can not create file\nfopen(%s): %s",
  9908. path,
  9909. strerror(ERRNO));
  9910. return;
  9911. }
  9912. fclose_on_exec(&file.access, conn);
  9913. range = mg_get_header(conn, "Content-Range");
  9914. r1 = r2 = 0;
  9915. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9916. conn->status_code = 206; /* Partial content */
  9917. fseeko(file.access.fp, r1, SEEK_SET);
  9918. }
  9919. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9920. /* forward_body_data failed.
  9921. * The error code has already been sent to the client,
  9922. * and conn->status_code is already set. */
  9923. (void)mg_fclose(&file.access);
  9924. return;
  9925. }
  9926. if (mg_fclose(&file.access) != 0) {
  9927. /* fclose failed. This might have different reasons, but a likely
  9928. * one is "no space on disk", http 507. */
  9929. conn->status_code = 507;
  9930. }
  9931. gmt_time_string(date, sizeof(date), &curtime);
  9932. mg_printf(conn,
  9933. "HTTP/1.1 %d %s\r\n",
  9934. conn->status_code,
  9935. mg_get_response_code_text(NULL, conn->status_code));
  9936. send_no_cache_header(conn);
  9937. send_additional_header(conn);
  9938. mg_printf(conn,
  9939. "Date: %s\r\n"
  9940. "Content-Length: 0\r\n"
  9941. "Connection: %s\r\n\r\n",
  9942. date,
  9943. suggest_connection_header(conn));
  9944. }
  9945. static void
  9946. delete_file(struct mg_connection *conn, const char *path)
  9947. {
  9948. struct de de;
  9949. memset(&de.file, 0, sizeof(de.file));
  9950. if (!mg_stat(conn, path, &de.file)) {
  9951. /* mg_stat returns 0 if the file does not exist */
  9952. mg_send_http_error(conn,
  9953. 404,
  9954. "Error: Cannot delete file\nFile %s not found",
  9955. path);
  9956. return;
  9957. }
  9958. #if 0 /* Ignore if a file in memory is inside a folder */
  9959. if (de.access.membuf != NULL) {
  9960. /* the file is cached in memory */
  9961. mg_send_http_error(
  9962. conn,
  9963. 405,
  9964. "Error: Delete not possible\nDeleting %s is not supported",
  9965. path);
  9966. return;
  9967. }
  9968. #endif
  9969. if (de.file.is_directory) {
  9970. if (remove_directory(conn, path)) {
  9971. /* Delete is successful: Return 204 without content. */
  9972. mg_send_http_error(conn, 204, "%s", "");
  9973. } else {
  9974. /* Delete is not successful: Return 500 (Server error). */
  9975. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9976. }
  9977. return;
  9978. }
  9979. /* This is an existing file (not a directory).
  9980. * Check if write permission is granted. */
  9981. if (access(path, W_OK) != 0) {
  9982. /* File is read only */
  9983. mg_send_http_error(
  9984. conn,
  9985. 403,
  9986. "Error: Delete not possible\nDeleting %s is not allowed",
  9987. path);
  9988. return;
  9989. }
  9990. /* Try to delete it. */
  9991. if (mg_remove(conn, path) == 0) {
  9992. /* Delete was successful: Return 204 without content. */
  9993. mg_send_http_error(conn, 204, "%s", "");
  9994. } else {
  9995. /* Delete not successful (file locked). */
  9996. mg_send_http_error(conn,
  9997. 423,
  9998. "Error: Cannot delete file\nremove(%s): %s",
  9999. path,
  10000. strerror(ERRNO));
  10001. }
  10002. }
  10003. #endif /* !NO_FILES */
  10004. #if !defined(NO_FILESYSTEMS)
  10005. static void
  10006. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  10007. static void
  10008. do_ssi_include(struct mg_connection *conn,
  10009. const char *ssi,
  10010. char *tag,
  10011. int include_level)
  10012. {
  10013. char file_name[MG_BUF_LEN], path[512], *p;
  10014. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10015. size_t len;
  10016. int truncated = 0;
  10017. if (conn == NULL) {
  10018. return;
  10019. }
  10020. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10021. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10022. * always < MG_BUF_LEN. */
  10023. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10024. /* File name is relative to the webserver root */
  10025. file_name[511] = 0;
  10026. (void)mg_snprintf(conn,
  10027. &truncated,
  10028. path,
  10029. sizeof(path),
  10030. "%s/%s",
  10031. conn->dom_ctx->config[DOCUMENT_ROOT],
  10032. file_name);
  10033. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10034. /* File name is relative to the webserver working directory
  10035. * or it is absolute system path */
  10036. file_name[511] = 0;
  10037. (void)
  10038. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10039. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10040. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10041. /* File name is relative to the currect document */
  10042. file_name[511] = 0;
  10043. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10044. if (!truncated) {
  10045. if ((p = strrchr(path, '/')) != NULL) {
  10046. p[1] = '\0';
  10047. }
  10048. len = strlen(path);
  10049. (void)mg_snprintf(conn,
  10050. &truncated,
  10051. path + len,
  10052. sizeof(path) - len,
  10053. "%s",
  10054. file_name);
  10055. }
  10056. } else {
  10057. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10058. return;
  10059. }
  10060. if (truncated) {
  10061. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10062. return;
  10063. }
  10064. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10065. mg_cry_internal(conn,
  10066. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10067. tag,
  10068. path,
  10069. strerror(ERRNO));
  10070. } else {
  10071. fclose_on_exec(&file.access, conn);
  10072. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10073. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10074. path)
  10075. > 0) {
  10076. send_ssi_file(conn, path, &file, include_level + 1);
  10077. } else {
  10078. send_file_data(conn, &file, 0, INT64_MAX);
  10079. }
  10080. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10081. }
  10082. }
  10083. #if !defined(NO_POPEN)
  10084. static void
  10085. do_ssi_exec(struct mg_connection *conn, char *tag)
  10086. {
  10087. char cmd[1024] = "";
  10088. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10089. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10090. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10091. } else {
  10092. cmd[1023] = 0;
  10093. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10094. mg_cry_internal(conn,
  10095. "Cannot SSI #exec: [%s]: %s",
  10096. cmd,
  10097. strerror(ERRNO));
  10098. } else {
  10099. send_file_data(conn, &file, 0, INT64_MAX);
  10100. pclose(file.access.fp);
  10101. }
  10102. }
  10103. }
  10104. #endif /* !NO_POPEN */
  10105. static int
  10106. mg_fgetc(struct mg_file *filep, int offset)
  10107. {
  10108. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10109. if (filep == NULL) {
  10110. return EOF;
  10111. }
  10112. #if defined(MG_USE_OPEN_FILE)
  10113. if ((filep->access.membuf != NULL) && (offset >= 0)
  10114. && (((unsigned int)(offset)) < filep->stat.size)) {
  10115. return ((const unsigned char *)filep->access.membuf)[offset];
  10116. } else /* else block below */
  10117. #endif
  10118. if (filep->access.fp != NULL) {
  10119. return fgetc(filep->access.fp);
  10120. } else {
  10121. return EOF;
  10122. }
  10123. }
  10124. static void
  10125. send_ssi_file(struct mg_connection *conn,
  10126. const char *path,
  10127. struct mg_file *filep,
  10128. int include_level)
  10129. {
  10130. char buf[MG_BUF_LEN];
  10131. int ch, offset, len, in_tag, in_ssi_tag;
  10132. if (include_level > 10) {
  10133. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10134. return;
  10135. }
  10136. in_tag = in_ssi_tag = len = offset = 0;
  10137. /* Read file, byte by byte, and look for SSI include tags */
  10138. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10139. if (in_tag) {
  10140. /* We are in a tag, either SSI tag or html tag */
  10141. if (ch == '>') {
  10142. /* Tag is closing */
  10143. buf[len++] = '>';
  10144. if (in_ssi_tag) {
  10145. /* Handle SSI tag */
  10146. buf[len] = 0;
  10147. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10148. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10149. #if !defined(NO_POPEN)
  10150. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10151. do_ssi_exec(conn, buf + 9);
  10152. #endif /* !NO_POPEN */
  10153. } else {
  10154. mg_cry_internal(conn,
  10155. "%s: unknown SSI "
  10156. "command: \"%s\"",
  10157. path,
  10158. buf);
  10159. }
  10160. len = 0;
  10161. in_ssi_tag = in_tag = 0;
  10162. } else {
  10163. /* Not an SSI tag */
  10164. /* Flush buffer */
  10165. (void)mg_write(conn, buf, (size_t)len);
  10166. len = 0;
  10167. in_tag = 0;
  10168. }
  10169. } else {
  10170. /* Tag is still open */
  10171. buf[len++] = (char)(ch & 0xff);
  10172. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10173. /* All SSI tags start with <!--# */
  10174. in_ssi_tag = 1;
  10175. }
  10176. if ((len + 2) > (int)sizeof(buf)) {
  10177. /* Tag to long for buffer */
  10178. mg_cry_internal(conn, "%s: tag is too large", path);
  10179. return;
  10180. }
  10181. }
  10182. } else {
  10183. /* We are not in a tag yet. */
  10184. if (ch == '<') {
  10185. /* Tag is opening */
  10186. in_tag = 1;
  10187. if (len > 0) {
  10188. /* Flush current buffer.
  10189. * Buffer is filled with "len" bytes. */
  10190. (void)mg_write(conn, buf, (size_t)len);
  10191. }
  10192. /* Store the < */
  10193. len = 1;
  10194. buf[0] = '<';
  10195. } else {
  10196. /* No Tag */
  10197. /* Add data to buffer */
  10198. buf[len++] = (char)(ch & 0xff);
  10199. /* Flush if buffer is full */
  10200. if (len == (int)sizeof(buf)) {
  10201. mg_write(conn, buf, (size_t)len);
  10202. len = 0;
  10203. }
  10204. }
  10205. }
  10206. }
  10207. /* Send the rest of buffered data */
  10208. if (len > 0) {
  10209. mg_write(conn, buf, (size_t)len);
  10210. }
  10211. }
  10212. static void
  10213. handle_ssi_file_request(struct mg_connection *conn,
  10214. const char *path,
  10215. struct mg_file *filep)
  10216. {
  10217. char date[64];
  10218. time_t curtime = time(NULL);
  10219. const char *cors_orig_cfg;
  10220. const char *cors1, *cors2, *cors3;
  10221. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10222. return;
  10223. }
  10224. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10225. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10226. /* Cross-origin resource sharing (CORS). */
  10227. cors1 = "Access-Control-Allow-Origin: ";
  10228. cors2 = cors_orig_cfg;
  10229. cors3 = "\r\n";
  10230. } else {
  10231. cors1 = cors2 = cors3 = "";
  10232. }
  10233. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10234. /* File exists (precondition for calling this function),
  10235. * but can not be opened by the server. */
  10236. mg_send_http_error(conn,
  10237. 500,
  10238. "Error: Cannot read file\nfopen(%s): %s",
  10239. path,
  10240. strerror(ERRNO));
  10241. } else {
  10242. conn->must_close = 1;
  10243. gmt_time_string(date, sizeof(date), &curtime);
  10244. fclose_on_exec(&filep->access, conn);
  10245. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10246. send_no_cache_header(conn);
  10247. send_additional_header(conn);
  10248. mg_printf(conn,
  10249. "%s%s%s"
  10250. "Date: %s\r\n"
  10251. "Content-Type: text/html\r\n"
  10252. "Connection: %s\r\n\r\n",
  10253. cors1,
  10254. cors2,
  10255. cors3,
  10256. date,
  10257. suggest_connection_header(conn));
  10258. send_ssi_file(conn, path, filep, 0);
  10259. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10260. }
  10261. }
  10262. #endif /* NO_FILESYSTEMS */
  10263. #if !defined(NO_FILES)
  10264. static void
  10265. send_options(struct mg_connection *conn)
  10266. {
  10267. char date[64];
  10268. time_t curtime = time(NULL);
  10269. if (!conn) {
  10270. return;
  10271. }
  10272. conn->status_code = 200;
  10273. conn->must_close = 1;
  10274. gmt_time_string(date, sizeof(date), &curtime);
  10275. /* We do not set a "Cache-Control" header here, but leave the default.
  10276. * Since browsers do not send an OPTIONS request, we can not test the
  10277. * effect anyway. */
  10278. mg_printf(conn,
  10279. "HTTP/1.1 200 OK\r\n"
  10280. "Date: %s\r\n"
  10281. "Connection: %s\r\n"
  10282. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10283. "PROPFIND, MKCOL\r\n"
  10284. "DAV: 1\r\n",
  10285. date,
  10286. suggest_connection_header(conn));
  10287. send_additional_header(conn);
  10288. mg_printf(conn, "\r\n");
  10289. }
  10290. /* Writes PROPFIND properties for a collection element */
  10291. static int
  10292. print_props(struct mg_connection *conn,
  10293. const char *uri,
  10294. const char *name,
  10295. struct mg_file_stat *filep)
  10296. {
  10297. size_t href_size, i, j;
  10298. int len;
  10299. char *href, mtime[64];
  10300. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10301. return 0;
  10302. }
  10303. /* Estimate worst case size for encoding */
  10304. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10305. href = (char *)mg_malloc(href_size);
  10306. if (href == NULL) {
  10307. return 0;
  10308. }
  10309. len = mg_url_encode(uri, href, href_size);
  10310. if (len >= 0) {
  10311. /* Append an extra string */
  10312. mg_url_encode(name, href + len, href_size - (size_t)len);
  10313. }
  10314. /* Directory separator should be preserved. */
  10315. for (i = j = 0; href[i]; j++) {
  10316. if (!strncmp(href + i, "%2f", 3)) {
  10317. href[j] = '/';
  10318. i += 3;
  10319. } else {
  10320. href[j] = href[i++];
  10321. }
  10322. }
  10323. href[j] = '\0';
  10324. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10325. mg_printf(conn,
  10326. "<d:response>"
  10327. "<d:href>%s</d:href>"
  10328. "<d:propstat>"
  10329. "<d:prop>"
  10330. "<d:resourcetype>%s</d:resourcetype>"
  10331. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10332. "<d:getlastmodified>%s</d:getlastmodified>"
  10333. "</d:prop>"
  10334. "<d:status>HTTP/1.1 200 OK</d:status>"
  10335. "</d:propstat>"
  10336. "</d:response>\n",
  10337. href,
  10338. filep->is_directory ? "<d:collection/>" : "",
  10339. filep->size,
  10340. mtime);
  10341. mg_free(href);
  10342. return 1;
  10343. }
  10344. static int
  10345. print_dav_dir_entry(struct de *de, void *data)
  10346. {
  10347. struct mg_connection *conn = (struct mg_connection *)data;
  10348. if (!de || !conn
  10349. || !print_props(
  10350. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10351. return -1;
  10352. }
  10353. return 0;
  10354. }
  10355. static void
  10356. handle_propfind(struct mg_connection *conn,
  10357. const char *path,
  10358. struct mg_file_stat *filep)
  10359. {
  10360. const char *depth = mg_get_header(conn, "Depth");
  10361. char date[64];
  10362. time_t curtime = time(NULL);
  10363. gmt_time_string(date, sizeof(date), &curtime);
  10364. if (!conn || !path || !filep || !conn->dom_ctx) {
  10365. return;
  10366. }
  10367. conn->must_close = 1;
  10368. conn->status_code = 207;
  10369. mg_printf(conn,
  10370. "HTTP/1.1 207 Multi-Status\r\n"
  10371. "Date: %s\r\n",
  10372. date);
  10373. send_static_cache_header(conn);
  10374. send_additional_header(conn);
  10375. mg_printf(conn,
  10376. "Connection: %s\r\n"
  10377. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10378. suggest_connection_header(conn));
  10379. mg_printf(conn,
  10380. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10381. "<d:multistatus xmlns:d='DAV:'>\n");
  10382. /* Print properties for the requested resource itself */
  10383. print_props(conn, conn->request_info.local_uri, "", filep);
  10384. /* If it is a directory, print directory entries too if Depth is not 0
  10385. */
  10386. if (filep->is_directory
  10387. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10388. "yes")
  10389. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10390. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10391. }
  10392. mg_printf(conn, "%s\n", "</d:multistatus>");
  10393. }
  10394. #endif
  10395. void
  10396. mg_lock_connection(struct mg_connection *conn)
  10397. {
  10398. if (conn) {
  10399. (void)pthread_mutex_lock(&conn->mutex);
  10400. }
  10401. }
  10402. void
  10403. mg_unlock_connection(struct mg_connection *conn)
  10404. {
  10405. if (conn) {
  10406. (void)pthread_mutex_unlock(&conn->mutex);
  10407. }
  10408. }
  10409. void
  10410. mg_lock_context(struct mg_context *ctx)
  10411. {
  10412. if (ctx) {
  10413. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10414. }
  10415. }
  10416. void
  10417. mg_unlock_context(struct mg_context *ctx)
  10418. {
  10419. if (ctx) {
  10420. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10421. }
  10422. }
  10423. #if defined(USE_LUA)
  10424. #include "mod_lua.inl"
  10425. #endif /* USE_LUA */
  10426. #if defined(USE_DUKTAPE)
  10427. #include "mod_duktape.inl"
  10428. #endif /* USE_DUKTAPE */
  10429. #if defined(USE_WEBSOCKET)
  10430. #if !defined(NO_SSL_DL)
  10431. #define SHA_API static
  10432. #include "sha1.inl"
  10433. #endif
  10434. static int
  10435. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10436. {
  10437. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10438. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10439. SHA_CTX sha_ctx;
  10440. int truncated;
  10441. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10442. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10443. if (truncated) {
  10444. conn->must_close = 1;
  10445. return 0;
  10446. }
  10447. DEBUG_TRACE("%s", "Send websocket handshake");
  10448. SHA1_Init(&sha_ctx);
  10449. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10450. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10451. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10452. mg_printf(conn,
  10453. "HTTP/1.1 101 Switching Protocols\r\n"
  10454. "Upgrade: websocket\r\n"
  10455. "Connection: Upgrade\r\n"
  10456. "Sec-WebSocket-Accept: %s\r\n",
  10457. b64_sha);
  10458. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10459. mg_printf(conn,
  10460. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10461. conn->request_info.acceptedWebSocketSubprotocol);
  10462. } else {
  10463. mg_printf(conn, "%s", "\r\n");
  10464. }
  10465. return 1;
  10466. }
  10467. #if !defined(MG_MAX_UNANSWERED_PING)
  10468. /* Configuration of the maximum number of websocket PINGs that might
  10469. * stay unanswered before the connection is considered broken.
  10470. * Note: The name of this define may still change (until it is
  10471. * defined as a compile parameter in a documentation).
  10472. */
  10473. #define MG_MAX_UNANSWERED_PING (5)
  10474. #endif
  10475. static void
  10476. read_websocket(struct mg_connection *conn,
  10477. mg_websocket_data_handler ws_data_handler,
  10478. void *callback_data)
  10479. {
  10480. /* Pointer to the beginning of the portion of the incoming websocket
  10481. * message queue.
  10482. * The original websocket upgrade request is never removed, so the queue
  10483. * begins after it. */
  10484. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10485. int n, error, exit_by_callback;
  10486. int ret;
  10487. /* body_len is the length of the entire queue in bytes
  10488. * len is the length of the current message
  10489. * data_len is the length of the current message's data payload
  10490. * header_len is the length of the current message's header */
  10491. size_t i, len, mask_len = 0, header_len, body_len;
  10492. uint64_t data_len = 0;
  10493. /* "The masking key is a 32-bit value chosen at random by the client."
  10494. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10495. */
  10496. unsigned char mask[4];
  10497. /* data points to the place where the message is stored when passed to
  10498. * the websocket_data callback. This is either mem on the stack, or a
  10499. * dynamically allocated buffer if it is too large. */
  10500. unsigned char mem[4096];
  10501. unsigned char mop; /* mask flag and opcode */
  10502. /* Variables used for connection monitoring */
  10503. double timeout = -1.0;
  10504. int enable_ping_pong = 0;
  10505. int ping_count = 0;
  10506. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10507. enable_ping_pong =
  10508. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10509. "yes");
  10510. }
  10511. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10512. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10513. }
  10514. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10515. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10516. }
  10517. /* Enter data processing loop */
  10518. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10519. conn->request_info.remote_addr,
  10520. conn->request_info.remote_port);
  10521. conn->in_websocket_handling = 1;
  10522. mg_set_thread_name("wsock");
  10523. /* Loop continuously, reading messages from the socket, invoking the
  10524. * callback, and waiting repeatedly until an error occurs. */
  10525. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10526. header_len = 0;
  10527. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10528. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10529. len = buf[1] & 127;
  10530. mask_len = (buf[1] & 128) ? 4 : 0;
  10531. if ((len < 126) && (body_len >= mask_len)) {
  10532. /* inline 7-bit length field */
  10533. data_len = len;
  10534. header_len = 2 + mask_len;
  10535. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10536. /* 16-bit length field */
  10537. header_len = 4 + mask_len;
  10538. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10539. } else if (body_len >= (10 + mask_len)) {
  10540. /* 64-bit length field */
  10541. uint32_t l1, l2;
  10542. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10543. memcpy(&l2, &buf[6], 4);
  10544. header_len = 10 + mask_len;
  10545. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10546. if (data_len > (uint64_t)0x7FFF0000ul) {
  10547. /* no can do */
  10548. mg_cry_internal(
  10549. conn,
  10550. "%s",
  10551. "websocket out of memory; closing connection");
  10552. break;
  10553. }
  10554. }
  10555. }
  10556. if ((header_len > 0) && (body_len >= header_len)) {
  10557. /* Allocate space to hold websocket payload */
  10558. unsigned char *data = mem;
  10559. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10560. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10561. conn->phys_ctx);
  10562. if (data == NULL) {
  10563. /* Allocation failed, exit the loop and then close the
  10564. * connection */
  10565. mg_cry_internal(
  10566. conn,
  10567. "%s",
  10568. "websocket out of memory; closing connection");
  10569. break;
  10570. }
  10571. }
  10572. /* Copy the mask before we shift the queue and destroy it */
  10573. if (mask_len > 0) {
  10574. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10575. } else {
  10576. memset(mask, 0, sizeof(mask));
  10577. }
  10578. /* Read frame payload from the first message in the queue into
  10579. * data and advance the queue by moving the memory in place. */
  10580. DEBUG_ASSERT(body_len >= header_len);
  10581. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10582. mop = buf[0]; /* current mask and opcode */
  10583. /* Overflow case */
  10584. len = body_len - header_len;
  10585. memcpy(data, buf + header_len, len);
  10586. error = 0;
  10587. while ((uint64_t)len < data_len) {
  10588. n = pull_inner(NULL,
  10589. conn,
  10590. (char *)(data + len),
  10591. (int)(data_len - len),
  10592. timeout);
  10593. if (n <= -2) {
  10594. error = 1;
  10595. break;
  10596. } else if (n > 0) {
  10597. len += (size_t)n;
  10598. } else {
  10599. /* Timeout: should retry */
  10600. /* TODO: retry condition */
  10601. }
  10602. }
  10603. if (error) {
  10604. mg_cry_internal(
  10605. conn,
  10606. "%s",
  10607. "Websocket pull failed; closing connection");
  10608. if (data != mem) {
  10609. mg_free(data);
  10610. }
  10611. break;
  10612. }
  10613. conn->data_len = conn->request_len;
  10614. } else {
  10615. mop = buf[0]; /* current mask and opcode, overwritten by
  10616. * memmove() */
  10617. /* Length of the message being read at the front of the
  10618. * queue. Cast to 31 bit is OK, since we limited
  10619. * data_len before. */
  10620. len = (size_t)data_len + header_len;
  10621. /* Copy the data payload into the data pointer for the
  10622. * callback. Cast to 31 bit is OK, since we
  10623. * limited data_len */
  10624. memcpy(data, buf + header_len, (size_t)data_len);
  10625. /* Move the queue forward len bytes */
  10626. memmove(buf, buf + len, body_len - len);
  10627. /* Mark the queue as advanced */
  10628. conn->data_len -= (int)len;
  10629. }
  10630. /* Apply mask if necessary */
  10631. if (mask_len > 0) {
  10632. for (i = 0; i < (size_t)data_len; i++) {
  10633. data[i] ^= mask[i & 3];
  10634. }
  10635. }
  10636. exit_by_callback = 0;
  10637. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10638. /* filter PONG messages */
  10639. DEBUG_TRACE("PONG from %s:%u",
  10640. conn->request_info.remote_addr,
  10641. conn->request_info.remote_port);
  10642. /* No unanwered PINGs left */
  10643. ping_count = 0;
  10644. } else if (enable_ping_pong
  10645. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10646. /* reply PING messages */
  10647. DEBUG_TRACE("Reply PING from %s:%u",
  10648. conn->request_info.remote_addr,
  10649. conn->request_info.remote_port);
  10650. ret = mg_websocket_write(conn,
  10651. MG_WEBSOCKET_OPCODE_PONG,
  10652. (char *)data,
  10653. (size_t)data_len);
  10654. if (ret <= 0) {
  10655. /* Error: send failed */
  10656. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10657. break;
  10658. }
  10659. } else {
  10660. /* Exit the loop if callback signals to exit (server side),
  10661. * or "connection close" opcode received (client side). */
  10662. if ((ws_data_handler != NULL)
  10663. && !ws_data_handler(conn,
  10664. mop,
  10665. (char *)data,
  10666. (size_t)data_len,
  10667. callback_data)) {
  10668. exit_by_callback = 1;
  10669. }
  10670. }
  10671. /* It a buffer has been allocated, free it again */
  10672. if (data != mem) {
  10673. mg_free(data);
  10674. }
  10675. if (exit_by_callback) {
  10676. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10677. conn->request_info.remote_addr,
  10678. conn->request_info.remote_port);
  10679. break;
  10680. }
  10681. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10682. /* Opcode == 8, connection close */
  10683. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10684. conn->request_info.remote_addr,
  10685. conn->request_info.remote_port);
  10686. break;
  10687. }
  10688. /* Not breaking the loop, process next websocket frame. */
  10689. } else {
  10690. /* Read from the socket into the next available location in the
  10691. * message queue. */
  10692. n = pull_inner(NULL,
  10693. conn,
  10694. conn->buf + conn->data_len,
  10695. conn->buf_size - conn->data_len,
  10696. timeout);
  10697. if (n <= -2) {
  10698. /* Error, no bytes read */
  10699. DEBUG_TRACE("PULL from %s:%u failed",
  10700. conn->request_info.remote_addr,
  10701. conn->request_info.remote_port);
  10702. break;
  10703. }
  10704. if (n > 0) {
  10705. conn->data_len += n;
  10706. /* Reset open PING count */
  10707. ping_count = 0;
  10708. } else {
  10709. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10710. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10711. /* Stop sending PING */
  10712. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10713. "- closing connection",
  10714. ping_count,
  10715. conn->request_info.remote_addr,
  10716. conn->request_info.remote_port);
  10717. break;
  10718. }
  10719. if (enable_ping_pong) {
  10720. /* Send Websocket PING message */
  10721. DEBUG_TRACE("PING to %s:%u",
  10722. conn->request_info.remote_addr,
  10723. conn->request_info.remote_port);
  10724. ret = mg_websocket_write(conn,
  10725. MG_WEBSOCKET_OPCODE_PING,
  10726. NULL,
  10727. 0);
  10728. if (ret <= 0) {
  10729. /* Error: send failed */
  10730. DEBUG_TRACE("Send PING failed (%i)", ret);
  10731. break;
  10732. }
  10733. ping_count++;
  10734. }
  10735. }
  10736. /* Timeout: should retry */
  10737. /* TODO: get timeout def */
  10738. }
  10739. }
  10740. }
  10741. /* Leave data processing loop */
  10742. mg_set_thread_name("worker");
  10743. conn->in_websocket_handling = 0;
  10744. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10745. conn->request_info.remote_addr,
  10746. conn->request_info.remote_port);
  10747. }
  10748. static int
  10749. mg_websocket_write_exec(struct mg_connection *conn,
  10750. int opcode,
  10751. const char *data,
  10752. size_t dataLen,
  10753. uint32_t masking_key)
  10754. {
  10755. unsigned char header[14];
  10756. size_t headerLen;
  10757. int retval;
  10758. #if defined(GCC_DIAGNOSTIC)
  10759. /* Disable spurious conversion warning for GCC */
  10760. #pragma GCC diagnostic push
  10761. #pragma GCC diagnostic ignored "-Wconversion"
  10762. #endif
  10763. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10764. #if defined(GCC_DIAGNOSTIC)
  10765. #pragma GCC diagnostic pop
  10766. #endif
  10767. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10768. if (dataLen < 126) {
  10769. /* inline 7-bit length field */
  10770. header[1] = (unsigned char)dataLen;
  10771. headerLen = 2;
  10772. } else if (dataLen <= 0xFFFF) {
  10773. /* 16-bit length field */
  10774. uint16_t len = htons((uint16_t)dataLen);
  10775. header[1] = 126;
  10776. memcpy(header + 2, &len, 2);
  10777. headerLen = 4;
  10778. } else {
  10779. /* 64-bit length field */
  10780. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10781. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10782. header[1] = 127;
  10783. memcpy(header + 2, &len1, 4);
  10784. memcpy(header + 6, &len2, 4);
  10785. headerLen = 10;
  10786. }
  10787. if (masking_key) {
  10788. /* add mask */
  10789. header[1] |= 0x80;
  10790. memcpy(header + headerLen, &masking_key, 4);
  10791. headerLen += 4;
  10792. }
  10793. /* Note that POSIX/Winsock's send() is threadsafe
  10794. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10795. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10796. * push(), although that is only a problem if the packet is large or
  10797. * outgoing buffer is full). */
  10798. /* TODO: Check if this lock should be moved to user land.
  10799. * Currently the server sets this lock for websockets, but
  10800. * not for any other connection. It must be set for every
  10801. * conn read/written by more than one thread, no matter if
  10802. * it is a websocket or regular connection. */
  10803. (void)mg_lock_connection(conn);
  10804. retval = mg_write(conn, header, headerLen);
  10805. if (retval != (int)headerLen) {
  10806. /* Did not send complete header */
  10807. retval = -1;
  10808. } else {
  10809. if (dataLen > 0) {
  10810. retval = mg_write(conn, data, dataLen);
  10811. }
  10812. /* if dataLen == 0, the header length (2) is returned */
  10813. }
  10814. /* TODO: Remove this unlock as well, when lock is removed. */
  10815. mg_unlock_connection(conn);
  10816. return retval;
  10817. }
  10818. int
  10819. mg_websocket_write(struct mg_connection *conn,
  10820. int opcode,
  10821. const char *data,
  10822. size_t dataLen)
  10823. {
  10824. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10825. }
  10826. static void
  10827. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10828. {
  10829. size_t i = 0;
  10830. i = 0;
  10831. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10832. /* Convert in 32 bit words, if data is 4 byte aligned */
  10833. while (i < (in_len - 3)) {
  10834. *(uint32_t *)(void *)(out + i) =
  10835. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10836. i += 4;
  10837. }
  10838. }
  10839. if (i != in_len) {
  10840. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10841. while (i < in_len) {
  10842. *(uint8_t *)(void *)(out + i) =
  10843. *(uint8_t *)(void *)(in + i)
  10844. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10845. i++;
  10846. }
  10847. }
  10848. }
  10849. int
  10850. mg_websocket_client_write(struct mg_connection *conn,
  10851. int opcode,
  10852. const char *data,
  10853. size_t dataLen)
  10854. {
  10855. int retval = -1;
  10856. char *masked_data =
  10857. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10858. uint32_t masking_key = 0;
  10859. if (masked_data == NULL) {
  10860. /* Return -1 in an error case */
  10861. mg_cry_internal(conn,
  10862. "%s",
  10863. "Cannot allocate buffer for masked websocket response: "
  10864. "Out of memory");
  10865. return -1;
  10866. }
  10867. do {
  10868. /* Get a masking key - but not 0 */
  10869. masking_key = (uint32_t)get_random();
  10870. } while (masking_key == 0);
  10871. mask_data(data, dataLen, masking_key, masked_data);
  10872. retval = mg_websocket_write_exec(
  10873. conn, opcode, masked_data, dataLen, masking_key);
  10874. mg_free(masked_data);
  10875. return retval;
  10876. }
  10877. static void
  10878. handle_websocket_request(struct mg_connection *conn,
  10879. const char *path,
  10880. int is_callback_resource,
  10881. struct mg_websocket_subprotocols *subprotocols,
  10882. mg_websocket_connect_handler ws_connect_handler,
  10883. mg_websocket_ready_handler ws_ready_handler,
  10884. mg_websocket_data_handler ws_data_handler,
  10885. mg_websocket_close_handler ws_close_handler,
  10886. void *cbData)
  10887. {
  10888. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10889. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10890. ptrdiff_t lua_websock = 0;
  10891. #if !defined(USE_LUA)
  10892. (void)path;
  10893. #endif
  10894. /* Step 1: Check websocket protocol version. */
  10895. /* Step 1.1: Check Sec-WebSocket-Key. */
  10896. if (!websock_key) {
  10897. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10898. * requires a Sec-WebSocket-Key header.
  10899. */
  10900. /* It could be the hixie draft version
  10901. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10902. */
  10903. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10904. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10905. char key3[8];
  10906. if ((key1 != NULL) && (key2 != NULL)) {
  10907. /* This version uses 8 byte body data in a GET request */
  10908. conn->content_len = 8;
  10909. if (8 == mg_read(conn, key3, 8)) {
  10910. /* This is the hixie version */
  10911. mg_send_http_error(conn,
  10912. 426,
  10913. "%s",
  10914. "Protocol upgrade to RFC 6455 required");
  10915. return;
  10916. }
  10917. }
  10918. /* This is an unknown version */
  10919. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10920. return;
  10921. }
  10922. /* Step 1.2: Check websocket protocol version. */
  10923. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10924. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10925. /* Reject wrong versions */
  10926. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10927. return;
  10928. }
  10929. /* Step 1.3: Could check for "Host", but we do not really nead this
  10930. * value for anything, so just ignore it. */
  10931. /* Step 2: If a callback is responsible, call it. */
  10932. if (is_callback_resource) {
  10933. /* Step 2.1 check and select subprotocol */
  10934. const char *protocols[64]; // max 64 headers
  10935. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10936. "Sec-WebSocket-Protocol",
  10937. protocols,
  10938. 64);
  10939. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10940. int cnt = 0;
  10941. int idx;
  10942. unsigned long len;
  10943. const char *sep, *curSubProtocol,
  10944. *acceptedWebSocketSubprotocol = NULL;
  10945. /* look for matching subprotocol */
  10946. do {
  10947. const char *protocol = protocols[cnt];
  10948. do {
  10949. sep = strchr(protocol, ',');
  10950. curSubProtocol = protocol;
  10951. len = sep ? (unsigned long)(sep - protocol)
  10952. : (unsigned long)strlen(protocol);
  10953. while (sep && isspace((unsigned char)*++sep))
  10954. ; // ignore leading whitespaces
  10955. protocol = sep;
  10956. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10957. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10958. && (strncmp(curSubProtocol,
  10959. subprotocols->subprotocols[idx],
  10960. len)
  10961. == 0)) {
  10962. acceptedWebSocketSubprotocol =
  10963. subprotocols->subprotocols[idx];
  10964. break;
  10965. }
  10966. }
  10967. } while (sep && !acceptedWebSocketSubprotocol);
  10968. } while (++cnt < nbSubprotocolHeader
  10969. && !acceptedWebSocketSubprotocol);
  10970. conn->request_info.acceptedWebSocketSubprotocol =
  10971. acceptedWebSocketSubprotocol;
  10972. } else if (nbSubprotocolHeader > 0) {
  10973. /* keep legacy behavior */
  10974. const char *protocol = protocols[0];
  10975. /* The protocol is a comma separated list of names. */
  10976. /* The server must only return one value from this list. */
  10977. /* First check if it is a list or just a single value. */
  10978. const char *sep = strrchr(protocol, ',');
  10979. if (sep == NULL) {
  10980. /* Just a single protocol -> accept it. */
  10981. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10982. } else {
  10983. /* Multiple protocols -> accept the last one. */
  10984. /* This is just a quick fix if the client offers multiple
  10985. * protocols. The handler should have a list of accepted
  10986. * protocols on his own
  10987. * and use it to select one protocol among those the client
  10988. * has
  10989. * offered.
  10990. */
  10991. while (isspace((unsigned char)*++sep)) {
  10992. ; /* ignore leading whitespaces */
  10993. }
  10994. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10995. }
  10996. }
  10997. if ((ws_connect_handler != NULL)
  10998. && (ws_connect_handler(conn, cbData) != 0)) {
  10999. /* C callback has returned non-zero, do not proceed with
  11000. * handshake.
  11001. */
  11002. /* Note that C callbacks are no longer called when Lua is
  11003. * responsible, so C can no longer filter callbacks for Lua. */
  11004. return;
  11005. }
  11006. }
  11007. #if defined(USE_LUA)
  11008. /* Step 3: No callback. Check if Lua is responsible. */
  11009. else {
  11010. /* Step 3.1: Check if Lua is responsible. */
  11011. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11012. lua_websock = match_prefix(
  11013. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11014. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11015. path);
  11016. }
  11017. if (lua_websock) {
  11018. /* Step 3.2: Lua is responsible: call it. */
  11019. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11020. if (!conn->lua_websocket_state) {
  11021. /* Lua rejected the new client */
  11022. return;
  11023. }
  11024. }
  11025. }
  11026. #endif
  11027. /* Step 4: Check if there is a responsible websocket handler. */
  11028. if (!is_callback_resource && !lua_websock) {
  11029. /* There is no callback, and Lua is not responsible either. */
  11030. /* Reply with a 404 Not Found. We are still at a standard
  11031. * HTTP request here, before the websocket handshake, so
  11032. * we can still send standard HTTP error replies. */
  11033. mg_send_http_error(conn, 404, "%s", "Not found");
  11034. return;
  11035. }
  11036. /* Step 5: The websocket connection has been accepted */
  11037. if (!send_websocket_handshake(conn, websock_key)) {
  11038. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11039. return;
  11040. }
  11041. /* Step 6: Call the ready handler */
  11042. if (is_callback_resource) {
  11043. if (ws_ready_handler != NULL) {
  11044. ws_ready_handler(conn, cbData);
  11045. }
  11046. #if defined(USE_LUA)
  11047. } else if (lua_websock) {
  11048. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11049. /* the ready handler returned false */
  11050. return;
  11051. }
  11052. #endif
  11053. }
  11054. /* Step 7: Enter the read loop */
  11055. if (is_callback_resource) {
  11056. read_websocket(conn, ws_data_handler, cbData);
  11057. #if defined(USE_LUA)
  11058. } else if (lua_websock) {
  11059. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11060. #endif
  11061. }
  11062. /* Step 8: Call the close handler */
  11063. if (ws_close_handler) {
  11064. ws_close_handler(conn, cbData);
  11065. }
  11066. }
  11067. static int
  11068. is_websocket_protocol(const struct mg_connection *conn)
  11069. {
  11070. const char *upgrade, *connection;
  11071. /* A websocket protocoll has the following HTTP headers:
  11072. *
  11073. * Connection: Upgrade
  11074. * Upgrade: Websocket
  11075. */
  11076. upgrade = mg_get_header(conn, "Upgrade");
  11077. if (upgrade == NULL) {
  11078. return 0; /* fail early, don't waste time checking other header
  11079. * fields
  11080. */
  11081. }
  11082. DEBUG_TRACE("Upgrade: %s", upgrade);
  11083. if (!mg_strcasestr(upgrade, "websocket")) {
  11084. return 0;
  11085. }
  11086. connection = mg_get_header(conn, "Connection");
  11087. if (connection == NULL) {
  11088. return 0;
  11089. }
  11090. if (!mg_strcasestr(connection, "upgrade")) {
  11091. return 0;
  11092. }
  11093. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11094. * "Sec-WebSocket-Version" are also required.
  11095. * Don't check them here, since even an unsupported websocket protocol
  11096. * request still IS a websocket request (in contrast to a standard HTTP
  11097. * request). It will fail later in handle_websocket_request.
  11098. */
  11099. return 1;
  11100. }
  11101. #endif /* !USE_WEBSOCKET */
  11102. static int
  11103. isbyte(int n)
  11104. {
  11105. return (n >= 0) && (n <= 255);
  11106. }
  11107. static int
  11108. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11109. {
  11110. int n, a, b, c, d, slash = 32, len = 0;
  11111. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11112. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11113. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11114. && (slash < 33)) {
  11115. len = n;
  11116. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11117. | (uint32_t)d;
  11118. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11119. }
  11120. return len;
  11121. }
  11122. static int
  11123. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11124. {
  11125. int throttle = 0;
  11126. struct vec vec, val;
  11127. uint32_t net, mask;
  11128. char mult;
  11129. double v;
  11130. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11131. mult = ',';
  11132. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11133. || (v < 0)
  11134. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11135. && (mult != ','))) {
  11136. continue;
  11137. }
  11138. v *= (lowercase(&mult) == 'k')
  11139. ? 1024
  11140. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11141. if (vec.len == 1 && vec.ptr[0] == '*') {
  11142. throttle = (int)v;
  11143. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11144. if ((remote_ip & mask) == net) {
  11145. throttle = (int)v;
  11146. }
  11147. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11148. throttle = (int)v;
  11149. }
  11150. }
  11151. return throttle;
  11152. }
  11153. static uint32_t
  11154. get_remote_ip(const struct mg_connection *conn)
  11155. {
  11156. if (!conn) {
  11157. return 0;
  11158. }
  11159. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11160. }
  11161. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11162. #include "handle_form.inl"
  11163. #if defined(MG_LEGACY_INTERFACE)
  11164. /* Implement the deprecated mg_upload function by calling the new
  11165. * mg_handle_form_request function. While mg_upload could only handle
  11166. * HTML forms sent as POST request in multipart/form-data format
  11167. * containing only file input elements, mg_handle_form_request can
  11168. * handle all form input elements and all standard request methods. */
  11169. struct mg_upload_user_data {
  11170. struct mg_connection *conn;
  11171. const char *destination_dir;
  11172. int num_uploaded_files;
  11173. };
  11174. /* Helper function for deprecated mg_upload. */
  11175. static int
  11176. mg_upload_field_found(const char *key,
  11177. const char *filename,
  11178. char *path,
  11179. size_t pathlen,
  11180. void *user_data)
  11181. {
  11182. int truncated = 0;
  11183. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11184. (void)key;
  11185. if (!filename) {
  11186. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11187. return FORM_FIELD_STORAGE_ABORT;
  11188. }
  11189. mg_snprintf(fud->conn,
  11190. &truncated,
  11191. path,
  11192. pathlen - 1,
  11193. "%s/%s",
  11194. fud->destination_dir,
  11195. filename);
  11196. if (truncated) {
  11197. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11198. return FORM_FIELD_STORAGE_ABORT;
  11199. }
  11200. return FORM_FIELD_STORAGE_STORE;
  11201. }
  11202. /* Helper function for deprecated mg_upload. */
  11203. static int
  11204. mg_upload_field_get(const char *key,
  11205. const char *value,
  11206. size_t value_size,
  11207. void *user_data)
  11208. {
  11209. /* Function should never be called */
  11210. (void)key;
  11211. (void)value;
  11212. (void)value_size;
  11213. (void)user_data;
  11214. return 0;
  11215. }
  11216. /* Helper function for deprecated mg_upload. */
  11217. static int
  11218. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11219. {
  11220. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11221. (void)file_size;
  11222. fud->num_uploaded_files++;
  11223. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11224. return 0;
  11225. }
  11226. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11227. int
  11228. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11229. {
  11230. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11231. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11232. mg_upload_field_get,
  11233. mg_upload_field_stored,
  11234. 0};
  11235. int ret;
  11236. fdh.user_data = (void *)&fud;
  11237. ret = mg_handle_form_request(conn, &fdh);
  11238. if (ret < 0) {
  11239. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11240. }
  11241. return fud.num_uploaded_files;
  11242. }
  11243. #endif
  11244. static int
  11245. get_first_ssl_listener_index(const struct mg_context *ctx)
  11246. {
  11247. unsigned int i;
  11248. int idx = -1;
  11249. if (ctx) {
  11250. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11251. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11252. }
  11253. }
  11254. return idx;
  11255. }
  11256. /* Return host (without port) */
  11257. /* Use mg_free to free the result */
  11258. static const char *
  11259. alloc_get_host(struct mg_connection *conn)
  11260. {
  11261. char buf[1025];
  11262. size_t buflen = sizeof(buf);
  11263. const char *host_header = get_header(conn->request_info.http_headers,
  11264. conn->request_info.num_headers,
  11265. "Host");
  11266. char *host;
  11267. if (host_header != NULL) {
  11268. char *pos;
  11269. /* Create a local copy of the "Host" header, since it might be
  11270. * modified here. */
  11271. mg_strlcpy(buf, host_header, buflen);
  11272. buf[buflen - 1] = '\0';
  11273. host = buf;
  11274. while (isspace((unsigned char)*host)) {
  11275. host++;
  11276. }
  11277. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11278. * is found. */
  11279. if (*host == '[') {
  11280. pos = strchr(host, ']');
  11281. if (!pos) {
  11282. /* Malformed hostname starts with '[', but no ']' found */
  11283. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11284. return NULL;
  11285. }
  11286. /* terminate after ']' */
  11287. pos[1] = 0;
  11288. } else {
  11289. /* Otherwise, a ':' separates hostname and port number */
  11290. pos = strchr(host, ':');
  11291. if (pos != NULL) {
  11292. *pos = '\0';
  11293. }
  11294. }
  11295. if (conn->ssl) {
  11296. /* This is a HTTPS connection, maybe we have a hostname
  11297. * from SNI (set in ssl_servername_callback). */
  11298. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11299. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11300. /* We are not using the default domain */
  11301. if (mg_strcasecmp(host, sslhost)) {
  11302. /* Mismatch between SNI domain and HTTP domain */
  11303. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11304. sslhost,
  11305. host);
  11306. return NULL;
  11307. }
  11308. }
  11309. DEBUG_TRACE("HTTPS Host: %s", host);
  11310. } else {
  11311. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11312. while (dom) {
  11313. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11314. /* Found matching domain */
  11315. DEBUG_TRACE("HTTP domain %s found",
  11316. dom->config[AUTHENTICATION_DOMAIN]);
  11317. /* TODO: Check if this is a HTTP or HTTPS domain */
  11318. conn->dom_ctx = dom;
  11319. break;
  11320. }
  11321. dom = dom->next;
  11322. }
  11323. DEBUG_TRACE("HTTP Host: %s", host);
  11324. }
  11325. } else {
  11326. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11327. host = buf;
  11328. DEBUG_TRACE("IP: %s", host);
  11329. }
  11330. return mg_strdup_ctx(host, conn->phys_ctx);
  11331. }
  11332. static void
  11333. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11334. {
  11335. char target_url[MG_BUF_LEN];
  11336. int truncated = 0;
  11337. conn->must_close = 1;
  11338. /* Send host, port, uri and (if it exists) ?query_string */
  11339. if (conn->host) {
  11340. /* Use "308 Permanent Redirect" */
  11341. int redirect_code = 308;
  11342. /* Create target URL */
  11343. mg_snprintf(
  11344. conn,
  11345. &truncated,
  11346. target_url,
  11347. sizeof(target_url),
  11348. "https://%s:%d%s%s%s",
  11349. conn->host,
  11350. #if defined(USE_IPV6)
  11351. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11352. == AF_INET6)
  11353. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11354. .lsa.sin6.sin6_port)
  11355. :
  11356. #endif
  11357. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11358. .lsa.sin.sin_port),
  11359. conn->request_info.local_uri,
  11360. (conn->request_info.query_string == NULL) ? "" : "?",
  11361. (conn->request_info.query_string == NULL)
  11362. ? ""
  11363. : conn->request_info.query_string);
  11364. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11365. * is used as buffer size) */
  11366. if (truncated) {
  11367. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11368. return;
  11369. }
  11370. /* Use redirect helper function */
  11371. mg_send_http_redirect(conn, target_url, redirect_code);
  11372. }
  11373. }
  11374. static void
  11375. handler_info_acquire(struct mg_handler_info *handler_info)
  11376. {
  11377. pthread_mutex_lock(&handler_info->refcount_mutex);
  11378. handler_info->refcount++;
  11379. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11380. }
  11381. static void
  11382. handler_info_release(struct mg_handler_info *handler_info)
  11383. {
  11384. pthread_mutex_lock(&handler_info->refcount_mutex);
  11385. handler_info->refcount--;
  11386. pthread_cond_signal(&handler_info->refcount_cond);
  11387. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11388. }
  11389. static void
  11390. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11391. {
  11392. pthread_mutex_lock(&handler_info->refcount_mutex);
  11393. while (handler_info->refcount) {
  11394. pthread_cond_wait(&handler_info->refcount_cond,
  11395. &handler_info->refcount_mutex);
  11396. }
  11397. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11398. }
  11399. static void
  11400. mg_set_handler_type(struct mg_context *phys_ctx,
  11401. struct mg_domain_context *dom_ctx,
  11402. const char *uri,
  11403. int handler_type,
  11404. int is_delete_request,
  11405. mg_request_handler handler,
  11406. struct mg_websocket_subprotocols *subprotocols,
  11407. mg_websocket_connect_handler connect_handler,
  11408. mg_websocket_ready_handler ready_handler,
  11409. mg_websocket_data_handler data_handler,
  11410. mg_websocket_close_handler close_handler,
  11411. mg_authorization_handler auth_handler,
  11412. void *cbdata)
  11413. {
  11414. struct mg_handler_info *tmp_rh, **lastref;
  11415. size_t urilen = strlen(uri);
  11416. if (handler_type == WEBSOCKET_HANDLER) {
  11417. DEBUG_ASSERT(handler == NULL);
  11418. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11419. || ready_handler != NULL || data_handler != NULL
  11420. || close_handler != NULL);
  11421. DEBUG_ASSERT(auth_handler == NULL);
  11422. if (handler != NULL) {
  11423. return;
  11424. }
  11425. if (!is_delete_request && (connect_handler == NULL)
  11426. && (ready_handler == NULL) && (data_handler == NULL)
  11427. && (close_handler == NULL)) {
  11428. return;
  11429. }
  11430. if (auth_handler != NULL) {
  11431. return;
  11432. }
  11433. } else if (handler_type == REQUEST_HANDLER) {
  11434. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11435. && data_handler == NULL && close_handler == NULL);
  11436. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11437. DEBUG_ASSERT(auth_handler == NULL);
  11438. if ((connect_handler != NULL) || (ready_handler != NULL)
  11439. || (data_handler != NULL) || (close_handler != NULL)) {
  11440. return;
  11441. }
  11442. if (!is_delete_request && (handler == NULL)) {
  11443. return;
  11444. }
  11445. if (auth_handler != NULL) {
  11446. return;
  11447. }
  11448. } else { /* AUTH_HANDLER */
  11449. DEBUG_ASSERT(handler == NULL);
  11450. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11451. && data_handler == NULL && close_handler == NULL);
  11452. DEBUG_ASSERT(auth_handler != NULL);
  11453. if (handler != NULL) {
  11454. return;
  11455. }
  11456. if ((connect_handler != NULL) || (ready_handler != NULL)
  11457. || (data_handler != NULL) || (close_handler != NULL)) {
  11458. return;
  11459. }
  11460. if (!is_delete_request && (auth_handler == NULL)) {
  11461. return;
  11462. }
  11463. }
  11464. if (!phys_ctx || !dom_ctx) {
  11465. return;
  11466. }
  11467. mg_lock_context(phys_ctx);
  11468. /* first try to find an existing handler */
  11469. lastref = &(dom_ctx->handlers);
  11470. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11471. if (tmp_rh->handler_type == handler_type) {
  11472. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11473. if (!is_delete_request) {
  11474. /* update existing handler */
  11475. if (handler_type == REQUEST_HANDLER) {
  11476. /* Wait for end of use before updating */
  11477. handler_info_wait_unused(tmp_rh);
  11478. /* Ok, the handler is no more use -> Update it */
  11479. tmp_rh->handler = handler;
  11480. } else if (handler_type == WEBSOCKET_HANDLER) {
  11481. tmp_rh->subprotocols = subprotocols;
  11482. tmp_rh->connect_handler = connect_handler;
  11483. tmp_rh->ready_handler = ready_handler;
  11484. tmp_rh->data_handler = data_handler;
  11485. tmp_rh->close_handler = close_handler;
  11486. } else { /* AUTH_HANDLER */
  11487. tmp_rh->auth_handler = auth_handler;
  11488. }
  11489. tmp_rh->cbdata = cbdata;
  11490. } else {
  11491. /* remove existing handler */
  11492. if (handler_type == REQUEST_HANDLER) {
  11493. /* Wait for end of use before removing */
  11494. handler_info_wait_unused(tmp_rh);
  11495. /* Ok, the handler is no more used -> Destroy resources
  11496. */
  11497. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11498. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11499. }
  11500. *lastref = tmp_rh->next;
  11501. mg_free(tmp_rh->uri);
  11502. mg_free(tmp_rh);
  11503. }
  11504. mg_unlock_context(phys_ctx);
  11505. return;
  11506. }
  11507. }
  11508. lastref = &(tmp_rh->next);
  11509. }
  11510. if (is_delete_request) {
  11511. /* no handler to set, this was a remove request to a non-existing
  11512. * handler */
  11513. mg_unlock_context(phys_ctx);
  11514. return;
  11515. }
  11516. tmp_rh =
  11517. (struct mg_handler_info *)mg_calloc_ctx(1,
  11518. sizeof(struct mg_handler_info),
  11519. phys_ctx);
  11520. if (tmp_rh == NULL) {
  11521. mg_unlock_context(phys_ctx);
  11522. mg_cry_ctx_internal(phys_ctx,
  11523. "%s",
  11524. "Cannot create new request handler struct, OOM");
  11525. return;
  11526. }
  11527. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11528. if (!tmp_rh->uri) {
  11529. mg_unlock_context(phys_ctx);
  11530. mg_free(tmp_rh);
  11531. mg_cry_ctx_internal(phys_ctx,
  11532. "%s",
  11533. "Cannot create new request handler struct, OOM");
  11534. return;
  11535. }
  11536. tmp_rh->uri_len = urilen;
  11537. if (handler_type == REQUEST_HANDLER) {
  11538. /* Init refcount mutex and condition */
  11539. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11540. mg_unlock_context(phys_ctx);
  11541. mg_free(tmp_rh);
  11542. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount mutex");
  11543. return;
  11544. }
  11545. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11546. mg_unlock_context(phys_ctx);
  11547. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11548. mg_free(tmp_rh);
  11549. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount cond");
  11550. return;
  11551. }
  11552. tmp_rh->refcount = 0;
  11553. tmp_rh->handler = handler;
  11554. } else if (handler_type == WEBSOCKET_HANDLER) {
  11555. tmp_rh->subprotocols = subprotocols;
  11556. tmp_rh->connect_handler = connect_handler;
  11557. tmp_rh->ready_handler = ready_handler;
  11558. tmp_rh->data_handler = data_handler;
  11559. tmp_rh->close_handler = close_handler;
  11560. } else { /* AUTH_HANDLER */
  11561. tmp_rh->auth_handler = auth_handler;
  11562. }
  11563. tmp_rh->cbdata = cbdata;
  11564. tmp_rh->handler_type = handler_type;
  11565. tmp_rh->next = NULL;
  11566. *lastref = tmp_rh;
  11567. mg_unlock_context(phys_ctx);
  11568. }
  11569. void
  11570. mg_set_request_handler(struct mg_context *ctx,
  11571. const char *uri,
  11572. mg_request_handler handler,
  11573. void *cbdata)
  11574. {
  11575. mg_set_handler_type(ctx,
  11576. &(ctx->dd),
  11577. uri,
  11578. REQUEST_HANDLER,
  11579. handler == NULL,
  11580. handler,
  11581. NULL,
  11582. NULL,
  11583. NULL,
  11584. NULL,
  11585. NULL,
  11586. NULL,
  11587. cbdata);
  11588. }
  11589. void
  11590. mg_set_websocket_handler(struct mg_context *ctx,
  11591. const char *uri,
  11592. mg_websocket_connect_handler connect_handler,
  11593. mg_websocket_ready_handler ready_handler,
  11594. mg_websocket_data_handler data_handler,
  11595. mg_websocket_close_handler close_handler,
  11596. void *cbdata)
  11597. {
  11598. mg_set_websocket_handler_with_subprotocols(ctx,
  11599. uri,
  11600. NULL,
  11601. connect_handler,
  11602. ready_handler,
  11603. data_handler,
  11604. close_handler,
  11605. cbdata);
  11606. }
  11607. void
  11608. mg_set_websocket_handler_with_subprotocols(
  11609. struct mg_context *ctx,
  11610. const char *uri,
  11611. struct mg_websocket_subprotocols *subprotocols,
  11612. mg_websocket_connect_handler connect_handler,
  11613. mg_websocket_ready_handler ready_handler,
  11614. mg_websocket_data_handler data_handler,
  11615. mg_websocket_close_handler close_handler,
  11616. void *cbdata)
  11617. {
  11618. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11619. && (data_handler == NULL)
  11620. && (close_handler == NULL);
  11621. mg_set_handler_type(ctx,
  11622. &(ctx->dd),
  11623. uri,
  11624. WEBSOCKET_HANDLER,
  11625. is_delete_request,
  11626. NULL,
  11627. subprotocols,
  11628. connect_handler,
  11629. ready_handler,
  11630. data_handler,
  11631. close_handler,
  11632. NULL,
  11633. cbdata);
  11634. }
  11635. void
  11636. mg_set_auth_handler(struct mg_context *ctx,
  11637. const char *uri,
  11638. mg_authorization_handler handler,
  11639. void *cbdata)
  11640. {
  11641. mg_set_handler_type(ctx,
  11642. &(ctx->dd),
  11643. uri,
  11644. AUTH_HANDLER,
  11645. handler == NULL,
  11646. NULL,
  11647. NULL,
  11648. NULL,
  11649. NULL,
  11650. NULL,
  11651. NULL,
  11652. handler,
  11653. cbdata);
  11654. }
  11655. static int
  11656. get_request_handler(struct mg_connection *conn,
  11657. int handler_type,
  11658. mg_request_handler *handler,
  11659. struct mg_websocket_subprotocols **subprotocols,
  11660. mg_websocket_connect_handler *connect_handler,
  11661. mg_websocket_ready_handler *ready_handler,
  11662. mg_websocket_data_handler *data_handler,
  11663. mg_websocket_close_handler *close_handler,
  11664. mg_authorization_handler *auth_handler,
  11665. void **cbdata,
  11666. struct mg_handler_info **handler_info)
  11667. {
  11668. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11669. if (request_info) {
  11670. const char *uri = request_info->local_uri;
  11671. size_t urilen = strlen(uri);
  11672. struct mg_handler_info *tmp_rh;
  11673. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11674. return 0;
  11675. }
  11676. mg_lock_context(conn->phys_ctx);
  11677. /* first try for an exact match */
  11678. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11679. tmp_rh = tmp_rh->next) {
  11680. if (tmp_rh->handler_type == handler_type) {
  11681. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11682. if (handler_type == WEBSOCKET_HANDLER) {
  11683. *subprotocols = tmp_rh->subprotocols;
  11684. *connect_handler = tmp_rh->connect_handler;
  11685. *ready_handler = tmp_rh->ready_handler;
  11686. *data_handler = tmp_rh->data_handler;
  11687. *close_handler = tmp_rh->close_handler;
  11688. } else if (handler_type == REQUEST_HANDLER) {
  11689. *handler = tmp_rh->handler;
  11690. /* Acquire handler and give it back */
  11691. handler_info_acquire(tmp_rh);
  11692. *handler_info = tmp_rh;
  11693. } else { /* AUTH_HANDLER */
  11694. *auth_handler = tmp_rh->auth_handler;
  11695. }
  11696. *cbdata = tmp_rh->cbdata;
  11697. mg_unlock_context(conn->phys_ctx);
  11698. return 1;
  11699. }
  11700. }
  11701. }
  11702. /* next try for a partial match, we will accept uri/something */
  11703. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11704. tmp_rh = tmp_rh->next) {
  11705. if (tmp_rh->handler_type == handler_type) {
  11706. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11707. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11708. if (handler_type == WEBSOCKET_HANDLER) {
  11709. *subprotocols = tmp_rh->subprotocols;
  11710. *connect_handler = tmp_rh->connect_handler;
  11711. *ready_handler = tmp_rh->ready_handler;
  11712. *data_handler = tmp_rh->data_handler;
  11713. *close_handler = tmp_rh->close_handler;
  11714. } else if (handler_type == REQUEST_HANDLER) {
  11715. *handler = tmp_rh->handler;
  11716. /* Acquire handler and give it back */
  11717. handler_info_acquire(tmp_rh);
  11718. *handler_info = tmp_rh;
  11719. } else { /* AUTH_HANDLER */
  11720. *auth_handler = tmp_rh->auth_handler;
  11721. }
  11722. *cbdata = tmp_rh->cbdata;
  11723. mg_unlock_context(conn->phys_ctx);
  11724. return 1;
  11725. }
  11726. }
  11727. }
  11728. /* finally try for pattern match */
  11729. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11730. tmp_rh = tmp_rh->next) {
  11731. if (tmp_rh->handler_type == handler_type) {
  11732. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11733. if (handler_type == WEBSOCKET_HANDLER) {
  11734. *subprotocols = tmp_rh->subprotocols;
  11735. *connect_handler = tmp_rh->connect_handler;
  11736. *ready_handler = tmp_rh->ready_handler;
  11737. *data_handler = tmp_rh->data_handler;
  11738. *close_handler = tmp_rh->close_handler;
  11739. } else if (handler_type == REQUEST_HANDLER) {
  11740. *handler = tmp_rh->handler;
  11741. /* Acquire handler and give it back */
  11742. handler_info_acquire(tmp_rh);
  11743. *handler_info = tmp_rh;
  11744. } else { /* AUTH_HANDLER */
  11745. *auth_handler = tmp_rh->auth_handler;
  11746. }
  11747. *cbdata = tmp_rh->cbdata;
  11748. mg_unlock_context(conn->phys_ctx);
  11749. return 1;
  11750. }
  11751. }
  11752. }
  11753. mg_unlock_context(conn->phys_ctx);
  11754. }
  11755. return 0; /* none found */
  11756. }
  11757. /* Check if the script file is in a path, allowed for script files.
  11758. * This can be used if uploading files is possible not only for the server
  11759. * admin, and the upload mechanism does not check the file extension.
  11760. */
  11761. static int
  11762. is_in_script_path(const struct mg_connection *conn, const char *path)
  11763. {
  11764. /* TODO (Feature): Add config value for allowed script path.
  11765. * Default: All allowed. */
  11766. (void)conn;
  11767. (void)path;
  11768. return 1;
  11769. }
  11770. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11771. static int
  11772. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11773. void *cbdata)
  11774. {
  11775. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11776. if (pcallbacks->websocket_connect) {
  11777. return pcallbacks->websocket_connect(conn);
  11778. }
  11779. /* No handler set - assume "OK" */
  11780. return 0;
  11781. }
  11782. static void
  11783. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11784. {
  11785. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11786. if (pcallbacks->websocket_ready) {
  11787. pcallbacks->websocket_ready(conn);
  11788. }
  11789. }
  11790. static int
  11791. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11792. int bits,
  11793. char *data,
  11794. size_t len,
  11795. void *cbdata)
  11796. {
  11797. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11798. if (pcallbacks->websocket_data) {
  11799. return pcallbacks->websocket_data(conn, bits, data, len);
  11800. }
  11801. /* No handler set - assume "OK" */
  11802. return 1;
  11803. }
  11804. #endif
  11805. /* This is the heart of the Civetweb's logic.
  11806. * This function is called when the request is read, parsed and validated,
  11807. * and Civetweb must decide what action to take: serve a file, or
  11808. * a directory, or call embedded function, etcetera. */
  11809. static void
  11810. handle_request(struct mg_connection *conn)
  11811. {
  11812. struct mg_request_info *ri = &conn->request_info;
  11813. char path[PATH_MAX];
  11814. int uri_len, ssl_index;
  11815. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11816. is_put_or_delete_request = 0, is_callback_resource = 0;
  11817. int i;
  11818. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11819. mg_request_handler callback_handler = NULL;
  11820. struct mg_handler_info *handler_info = NULL;
  11821. struct mg_websocket_subprotocols *subprotocols;
  11822. mg_websocket_connect_handler ws_connect_handler = NULL;
  11823. mg_websocket_ready_handler ws_ready_handler = NULL;
  11824. mg_websocket_data_handler ws_data_handler = NULL;
  11825. mg_websocket_close_handler ws_close_handler = NULL;
  11826. void *callback_data = NULL;
  11827. mg_authorization_handler auth_handler = NULL;
  11828. void *auth_callback_data = NULL;
  11829. int handler_type;
  11830. time_t curtime = time(NULL);
  11831. char date[64];
  11832. path[0] = 0;
  11833. /* 1. get the request url */
  11834. /* 1.1. split into url and query string */
  11835. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11836. != NULL) {
  11837. *((char *)conn->request_info.query_string++) = '\0';
  11838. }
  11839. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11840. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11841. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11842. if (ssl_index >= 0) {
  11843. redirect_to_https_port(conn, ssl_index);
  11844. } else {
  11845. /* A http to https forward port has been specified,
  11846. * but no https port to forward to. */
  11847. mg_send_http_error(conn,
  11848. 503,
  11849. "%s",
  11850. "Error: SSL forward not configured properly");
  11851. mg_cry_internal(conn,
  11852. "%s",
  11853. "Can not redirect to SSL, no SSL port available");
  11854. }
  11855. return;
  11856. }
  11857. uri_len = (int)strlen(ri->local_uri);
  11858. /* 1.3. decode url (if config says so) */
  11859. if (should_decode_url(conn)) {
  11860. mg_url_decode(
  11861. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11862. }
  11863. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11864. * not possible */
  11865. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11866. /* step 1. completed, the url is known now */
  11867. uri_len = (int)strlen(ri->local_uri);
  11868. DEBUG_TRACE("URL: %s", ri->local_uri);
  11869. /* 2. if this ip has limited speed, set it for this connection */
  11870. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11871. get_remote_ip(conn),
  11872. ri->local_uri);
  11873. /* 3. call a "handle everything" callback, if registered */
  11874. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11875. /* Note that since V1.7 the "begin_request" function is called
  11876. * before an authorization check. If an authorization check is
  11877. * required, use a request_handler instead. */
  11878. i = conn->phys_ctx->callbacks.begin_request(conn);
  11879. if (i > 0) {
  11880. /* callback already processed the request. Store the
  11881. return value as a status code for the access log. */
  11882. conn->status_code = i;
  11883. discard_unread_request_data(conn);
  11884. return;
  11885. } else if (i == 0) {
  11886. /* civetweb should process the request */
  11887. } else {
  11888. /* unspecified - may change with the next version */
  11889. return;
  11890. }
  11891. }
  11892. /* request not yet handled by a handler or redirect, so the request
  11893. * is processed here */
  11894. /* 4. Check for CORS preflight requests and handle them (if configured).
  11895. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11896. */
  11897. if (!strcmp(ri->request_method, "OPTIONS")) {
  11898. /* Send a response to CORS preflights only if
  11899. * access_control_allow_methods is not NULL and not an empty string.
  11900. * In this case, scripts can still handle CORS. */
  11901. const char *cors_meth_cfg =
  11902. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11903. const char *cors_orig_cfg =
  11904. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11905. const char *cors_origin =
  11906. get_header(ri->http_headers, ri->num_headers, "Origin");
  11907. const char *cors_acrm = get_header(ri->http_headers,
  11908. ri->num_headers,
  11909. "Access-Control-Request-Method");
  11910. /* Todo: check if cors_origin is in cors_orig_cfg.
  11911. * Or, let the client check this. */
  11912. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11913. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11914. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11915. /* This is a valid CORS preflight, and the server is configured
  11916. * to
  11917. * handle it automatically. */
  11918. const char *cors_acrh =
  11919. get_header(ri->http_headers,
  11920. ri->num_headers,
  11921. "Access-Control-Request-Headers");
  11922. gmt_time_string(date, sizeof(date), &curtime);
  11923. mg_printf(conn,
  11924. "HTTP/1.1 200 OK\r\n"
  11925. "Date: %s\r\n"
  11926. "Access-Control-Allow-Origin: %s\r\n"
  11927. "Access-Control-Allow-Methods: %s\r\n"
  11928. "Content-Length: 0\r\n"
  11929. "Connection: %s\r\n",
  11930. date,
  11931. cors_orig_cfg,
  11932. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11933. suggest_connection_header(conn));
  11934. if (cors_acrh != NULL) {
  11935. /* CORS request is asking for additional headers */
  11936. const char *cors_hdr_cfg =
  11937. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11938. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11939. /* Allow only if access_control_allow_headers is
  11940. * not NULL and not an empty string. If this
  11941. * configuration is set to *, allow everything.
  11942. * Otherwise this configuration must be a list
  11943. * of allowed HTTP header names. */
  11944. mg_printf(conn,
  11945. "Access-Control-Allow-Headers: %s\r\n",
  11946. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11947. : cors_hdr_cfg));
  11948. }
  11949. }
  11950. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11951. mg_printf(conn, "\r\n");
  11952. return;
  11953. }
  11954. }
  11955. /* 5. interpret the url to find out how the request must be handled
  11956. */
  11957. /* 5.1. first test, if the request targets the regular http(s)://
  11958. * protocol namespace or the websocket ws(s):// protocol namespace.
  11959. */
  11960. is_websocket_request = is_websocket_protocol(conn);
  11961. #if defined(USE_WEBSOCKET)
  11962. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11963. #else
  11964. handler_type = REQUEST_HANDLER;
  11965. #endif /* defined(USE_WEBSOCKET) */
  11966. /* 5.2. check if the request will be handled by a callback */
  11967. if (get_request_handler(conn,
  11968. handler_type,
  11969. &callback_handler,
  11970. &subprotocols,
  11971. &ws_connect_handler,
  11972. &ws_ready_handler,
  11973. &ws_data_handler,
  11974. &ws_close_handler,
  11975. NULL,
  11976. &callback_data,
  11977. &handler_info)) {
  11978. /* 5.2.1. A callback will handle this request. All requests
  11979. * handled
  11980. * by a callback have to be considered as requests to a script
  11981. * resource. */
  11982. is_callback_resource = 1;
  11983. is_script_resource = 1;
  11984. is_put_or_delete_request = is_put_or_delete_method(conn);
  11985. } else {
  11986. no_callback_resource:
  11987. /* 5.2.2. No callback is responsible for this request. The URI
  11988. * addresses a file based resource (static content or Lua/cgi
  11989. * scripts in the file system). */
  11990. is_callback_resource = 0;
  11991. interpret_uri(conn,
  11992. path,
  11993. sizeof(path),
  11994. &file.stat,
  11995. &is_found,
  11996. &is_script_resource,
  11997. &is_websocket_request,
  11998. &is_put_or_delete_request);
  11999. }
  12000. /* 6. authorization check */
  12001. /* 6.1. a custom authorization handler is installed */
  12002. if (get_request_handler(conn,
  12003. AUTH_HANDLER,
  12004. NULL,
  12005. NULL,
  12006. NULL,
  12007. NULL,
  12008. NULL,
  12009. NULL,
  12010. &auth_handler,
  12011. &auth_callback_data,
  12012. NULL)) {
  12013. if (!auth_handler(conn, auth_callback_data)) {
  12014. return;
  12015. }
  12016. } else if (is_put_or_delete_request && !is_script_resource
  12017. && !is_callback_resource) {
  12018. /* 6.2. this request is a PUT/DELETE to a real file */
  12019. /* 6.2.1. thus, the server must have real files */
  12020. #if defined(NO_FILES)
  12021. if (1) {
  12022. #else
  12023. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12024. #endif
  12025. /* This server does not have any real files, thus the
  12026. * PUT/DELETE methods are not valid. */
  12027. mg_send_http_error(conn,
  12028. 405,
  12029. "%s method not allowed",
  12030. conn->request_info.request_method);
  12031. return;
  12032. }
  12033. #if !defined(NO_FILES)
  12034. /* 6.2.2. Check if put authorization for static files is
  12035. * available.
  12036. */
  12037. if (!is_authorized_for_put(conn)) {
  12038. send_authorization_request(conn, NULL);
  12039. return;
  12040. }
  12041. #endif
  12042. } else {
  12043. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12044. * or it is a PUT or DELETE request to a resource that does not
  12045. * correspond to a file. Check authorization. */
  12046. if (!check_authorization(conn, path)) {
  12047. send_authorization_request(conn, NULL);
  12048. return;
  12049. }
  12050. }
  12051. /* request is authorized or does not need authorization */
  12052. /* 7. check if there are request handlers for this uri */
  12053. if (is_callback_resource) {
  12054. if (!is_websocket_request) {
  12055. i = callback_handler(conn, callback_data);
  12056. /* Callback handler will not be used anymore. Release it */
  12057. handler_info_release(handler_info);
  12058. if (i > 0) {
  12059. /* Do nothing, callback has served the request. Store
  12060. * then return value as status code for the log and discard
  12061. * all data from the client not used by the callback. */
  12062. conn->status_code = i;
  12063. discard_unread_request_data(conn);
  12064. } else {
  12065. /* The handler did NOT handle the request. */
  12066. /* Some proper reactions would be:
  12067. * a) close the connections without sending anything
  12068. * b) send a 404 not found
  12069. * c) try if there is a file matching the URI
  12070. * It would be possible to do a, b or c in the callback
  12071. * implementation, and return 1 - we cannot do anything
  12072. * here, that is not possible in the callback.
  12073. *
  12074. * TODO: What would be the best reaction here?
  12075. * (Note: The reaction may change, if there is a better
  12076. *idea.)
  12077. */
  12078. /* For the moment, use option c: We look for a proper file,
  12079. * but since a file request is not always a script resource,
  12080. * the authorization check might be different. */
  12081. interpret_uri(conn,
  12082. path,
  12083. sizeof(path),
  12084. &file.stat,
  12085. &is_found,
  12086. &is_script_resource,
  12087. &is_websocket_request,
  12088. &is_put_or_delete_request);
  12089. callback_handler = NULL;
  12090. /* Here we are at a dead end:
  12091. * According to URI matching, a callback should be
  12092. * responsible for handling the request,
  12093. * we called it, but the callback declared itself
  12094. * not responsible.
  12095. * We use a goto here, to get out of this dead end,
  12096. * and continue with the default handling.
  12097. * A goto here is simpler and better to understand
  12098. * than some curious loop. */
  12099. goto no_callback_resource;
  12100. }
  12101. } else {
  12102. #if defined(USE_WEBSOCKET)
  12103. handle_websocket_request(conn,
  12104. path,
  12105. is_callback_resource,
  12106. subprotocols,
  12107. ws_connect_handler,
  12108. ws_ready_handler,
  12109. ws_data_handler,
  12110. ws_close_handler,
  12111. callback_data);
  12112. #endif
  12113. }
  12114. return;
  12115. }
  12116. /* 8. handle websocket requests */
  12117. #if defined(USE_WEBSOCKET)
  12118. if (is_websocket_request) {
  12119. if (is_script_resource) {
  12120. if (is_in_script_path(conn, path)) {
  12121. /* Websocket Lua script */
  12122. handle_websocket_request(conn,
  12123. path,
  12124. 0 /* Lua Script */,
  12125. NULL,
  12126. NULL,
  12127. NULL,
  12128. NULL,
  12129. NULL,
  12130. conn->phys_ctx->user_data);
  12131. } else {
  12132. /* Script was in an illegal path */
  12133. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12134. }
  12135. } else {
  12136. #if defined(MG_LEGACY_INTERFACE)
  12137. handle_websocket_request(
  12138. conn,
  12139. path,
  12140. !is_script_resource /* could be deprecated global callback */,
  12141. NULL,
  12142. deprecated_websocket_connect_wrapper,
  12143. deprecated_websocket_ready_wrapper,
  12144. deprecated_websocket_data_wrapper,
  12145. NULL,
  12146. conn->phys_ctx->user_data);
  12147. #else
  12148. mg_send_http_error(conn, 404, "%s", "Not found");
  12149. #endif
  12150. }
  12151. return;
  12152. } else
  12153. #endif
  12154. #if defined(NO_FILES)
  12155. /* 9a. In case the server uses only callbacks, this uri is
  12156. * unknown.
  12157. * Then, all request handling ends here. */
  12158. mg_send_http_error(conn, 404, "%s", "Not Found");
  12159. #else
  12160. /* 9b. This request is either for a static file or resource handled
  12161. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12162. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12163. mg_send_http_error(conn, 404, "%s", "Not Found");
  12164. return;
  12165. }
  12166. /* 10. Request is handled by a script */
  12167. if (is_script_resource) {
  12168. handle_file_based_request(conn, path, &file);
  12169. return;
  12170. }
  12171. /* 11. Handle put/delete/mkcol requests */
  12172. if (is_put_or_delete_request) {
  12173. /* 11.1. PUT method */
  12174. if (!strcmp(ri->request_method, "PUT")) {
  12175. put_file(conn, path);
  12176. return;
  12177. }
  12178. /* 11.2. DELETE method */
  12179. if (!strcmp(ri->request_method, "DELETE")) {
  12180. delete_file(conn, path);
  12181. return;
  12182. }
  12183. /* 11.3. MKCOL method */
  12184. if (!strcmp(ri->request_method, "MKCOL")) {
  12185. mkcol(conn, path);
  12186. return;
  12187. }
  12188. /* 11.4. PATCH method
  12189. * This method is not supported for static resources,
  12190. * only for scripts (Lua, CGI) and callbacks. */
  12191. mg_send_http_error(conn,
  12192. 405,
  12193. "%s method not allowed",
  12194. conn->request_info.request_method);
  12195. return;
  12196. }
  12197. /* 11. File does not exist, or it was configured that it should be
  12198. * hidden */
  12199. if (!is_found || (must_hide_file(conn, path))) {
  12200. mg_send_http_error(conn, 404, "%s", "Not found");
  12201. return;
  12202. }
  12203. /* 12. Directory uris should end with a slash */
  12204. if (file.stat.is_directory && (uri_len > 0)
  12205. && (ri->local_uri[uri_len - 1] != '/')) {
  12206. gmt_time_string(date, sizeof(date), &curtime);
  12207. mg_printf(conn,
  12208. "HTTP/1.1 301 Moved Permanently\r\n"
  12209. "Location: %s/\r\n"
  12210. "Date: %s\r\n"
  12211. /* "Cache-Control: private\r\n" (= default) */
  12212. "Content-Length: 0\r\n"
  12213. "Connection: %s\r\n",
  12214. ri->request_uri,
  12215. date,
  12216. suggest_connection_header(conn));
  12217. send_additional_header(conn);
  12218. mg_printf(conn, "\r\n");
  12219. return;
  12220. }
  12221. /* 13. Handle other methods than GET/HEAD */
  12222. /* 13.1. Handle PROPFIND */
  12223. if (!strcmp(ri->request_method, "PROPFIND")) {
  12224. handle_propfind(conn, path, &file.stat);
  12225. return;
  12226. }
  12227. /* 13.2. Handle OPTIONS for files */
  12228. if (!strcmp(ri->request_method, "OPTIONS")) {
  12229. /* This standard handler is only used for real files.
  12230. * Scripts should support the OPTIONS method themselves, to allow a
  12231. * maximum flexibility.
  12232. * Lua and CGI scripts may fully support CORS this way (including
  12233. * preflights). */
  12234. send_options(conn);
  12235. return;
  12236. }
  12237. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12238. if ((0 != strcmp(ri->request_method, "GET"))
  12239. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12240. mg_send_http_error(conn,
  12241. 405,
  12242. "%s method not allowed",
  12243. conn->request_info.request_method);
  12244. return;
  12245. }
  12246. /* 14. directories */
  12247. if (file.stat.is_directory) {
  12248. /* Substitute files have already been handled above. */
  12249. /* Here we can either generate and send a directory listing,
  12250. * or send an "access denied" error. */
  12251. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12252. "yes")) {
  12253. handle_directory_request(conn, path);
  12254. } else {
  12255. mg_send_http_error(conn,
  12256. 403,
  12257. "%s",
  12258. "Error: Directory listing denied");
  12259. }
  12260. return;
  12261. }
  12262. /* 15. read a normal file with GET or HEAD */
  12263. handle_file_based_request(conn, path, &file);
  12264. #endif /* !defined(NO_FILES) */
  12265. }
  12266. #if !defined(NO_FILESYSTEMS)
  12267. static void
  12268. handle_file_based_request(struct mg_connection *conn,
  12269. const char *path,
  12270. struct mg_file *file)
  12271. {
  12272. if (!conn || !conn->dom_ctx) {
  12273. return;
  12274. }
  12275. if (0) {
  12276. #if defined(USE_LUA)
  12277. } else if (match_prefix(
  12278. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12279. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12280. path)
  12281. > 0) {
  12282. if (is_in_script_path(conn, path)) {
  12283. /* Lua server page: an SSI like page containing mostly plain
  12284. * html
  12285. * code
  12286. * plus some tags with server generated contents. */
  12287. handle_lsp_request(conn, path, file, NULL);
  12288. } else {
  12289. /* Script was in an illegal path */
  12290. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12291. }
  12292. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12293. strlen(
  12294. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12295. path)
  12296. > 0) {
  12297. if (is_in_script_path(conn, path)) {
  12298. /* Lua in-server module script: a CGI like script used to
  12299. * generate
  12300. * the
  12301. * entire reply. */
  12302. mg_exec_lua_script(conn, path, NULL);
  12303. } else {
  12304. /* Script was in an illegal path */
  12305. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12306. }
  12307. #endif
  12308. #if defined(USE_DUKTAPE)
  12309. } else if (match_prefix(
  12310. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12311. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12312. path)
  12313. > 0) {
  12314. if (is_in_script_path(conn, path)) {
  12315. /* Call duktape to generate the page */
  12316. mg_exec_duktape_script(conn, path);
  12317. } else {
  12318. /* Script was in an illegal path */
  12319. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12320. }
  12321. #endif
  12322. #if !defined(NO_CGI)
  12323. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12324. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12325. path)
  12326. > 0) {
  12327. if (is_in_script_path(conn, path)) {
  12328. /* CGI scripts may support all HTTP methods */
  12329. handle_cgi_request(conn, path);
  12330. } else {
  12331. /* Script was in an illegal path */
  12332. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12333. }
  12334. #endif /* !NO_CGI */
  12335. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12336. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12337. path)
  12338. > 0) {
  12339. if (is_in_script_path(conn, path)) {
  12340. handle_ssi_file_request(conn, path, file);
  12341. } else {
  12342. /* Script was in an illegal path */
  12343. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12344. }
  12345. #if !defined(NO_CACHING)
  12346. } else if ((!conn->in_error_handler)
  12347. && is_not_modified(conn, &file->stat)) {
  12348. /* Send 304 "Not Modified" - this must not send any body data */
  12349. handle_not_modified_static_file_request(conn, file);
  12350. #endif /* !NO_CACHING */
  12351. } else {
  12352. handle_static_file_request(conn, path, file, NULL, NULL);
  12353. }
  12354. }
  12355. #endif /* NO_FILESYSTEMS */
  12356. static void
  12357. close_all_listening_sockets(struct mg_context *ctx)
  12358. {
  12359. unsigned int i;
  12360. if (!ctx) {
  12361. return;
  12362. }
  12363. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12364. closesocket(ctx->listening_sockets[i].sock);
  12365. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12366. }
  12367. mg_free(ctx->listening_sockets);
  12368. ctx->listening_sockets = NULL;
  12369. mg_free(ctx->listening_socket_fds);
  12370. ctx->listening_socket_fds = NULL;
  12371. }
  12372. /* Valid listening port specification is: [ip_address:]port[s]
  12373. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12374. * Examples for IPv6: [::]:80, [::1]:80,
  12375. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12376. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12377. * In order to bind to both, IPv4 and IPv6, you can either add
  12378. * both ports using 8080,[::]:8080, or the short form +8080.
  12379. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12380. * one only accepting IPv4 the other only IPv6. +8080 creates
  12381. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12382. * environment, they might work differently, or might not work
  12383. * at all - it must be tested what options work best in the
  12384. * relevant network environment.
  12385. */
  12386. static int
  12387. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12388. {
  12389. unsigned int a, b, c, d, port;
  12390. int ch, len;
  12391. const char *cb;
  12392. char *endptr;
  12393. #if defined(USE_IPV6)
  12394. char buf[100] = {0};
  12395. #endif
  12396. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12397. * Also, all-zeroes in the socket address means binding to all addresses
  12398. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12399. memset(so, 0, sizeof(*so));
  12400. so->lsa.sin.sin_family = AF_INET;
  12401. *ip_version = 0;
  12402. /* Initialize port and len as invalid. */
  12403. port = 0;
  12404. len = 0;
  12405. /* Test for different ways to format this string */
  12406. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12407. == 5) {
  12408. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12409. so->lsa.sin.sin_addr.s_addr =
  12410. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12411. so->lsa.sin.sin_port = htons((uint16_t)port);
  12412. *ip_version = 4;
  12413. #if defined(USE_IPV6)
  12414. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12415. && mg_inet_pton(
  12416. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12417. /* IPv6 address, examples: see above */
  12418. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12419. */
  12420. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12421. *ip_version = 6;
  12422. #endif
  12423. } else if ((vec->ptr[0] == '+')
  12424. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12425. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12426. /* Add 1 to len for the + character we skipped before */
  12427. len++;
  12428. #if defined(USE_IPV6)
  12429. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12430. so->lsa.sin6.sin6_family = AF_INET6;
  12431. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12432. *ip_version = 4 + 6;
  12433. #else
  12434. /* Bind to IPv4 only, since IPv6 is not built in. */
  12435. so->lsa.sin.sin_port = htons((uint16_t)port);
  12436. *ip_version = 4;
  12437. #endif
  12438. } else if (is_valid_port(port = strtoul(vec->ptr, &endptr, 0))
  12439. && vec->ptr != endptr) {
  12440. len = endptr - vec->ptr;
  12441. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12442. so->lsa.sin.sin_port = htons((uint16_t)port);
  12443. *ip_version = 4;
  12444. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12445. /* String could be a hostname. This check algotithm
  12446. * will only work for RFC 952 compliant hostnames,
  12447. * starting with a letter, containing only letters,
  12448. * digits and hyphen ('-'). Newer specs may allow
  12449. * more, but this is not guaranteed here, since it
  12450. * may interfere with rules for port option lists. */
  12451. /* According to RFC 1035, hostnames are restricted to 255 characters
  12452. * in total (63 between two dots). */
  12453. char hostname[256];
  12454. size_t hostnlen = (size_t)(cb - vec->ptr);
  12455. if (hostnlen >= sizeof(hostname)) {
  12456. /* This would be invalid in any case */
  12457. *ip_version = 0;
  12458. return 0;
  12459. }
  12460. memcpy(hostname, vec->ptr, hostnlen);
  12461. hostname[hostnlen] = 0;
  12462. if (mg_inet_pton(
  12463. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12464. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12465. *ip_version = 4;
  12466. so->lsa.sin.sin_family = AF_INET;
  12467. so->lsa.sin.sin_port = htons((uint16_t)port);
  12468. len += (int)(hostnlen + 1);
  12469. } else {
  12470. port = 0;
  12471. len = 0;
  12472. }
  12473. #if defined(USE_IPV6)
  12474. } else if (mg_inet_pton(AF_INET6,
  12475. vec->ptr,
  12476. &so->lsa.sin6,
  12477. sizeof(so->lsa.sin6))) {
  12478. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12479. *ip_version = 6;
  12480. so->lsa.sin6.sin6_family = AF_INET6;
  12481. so->lsa.sin.sin_port = htons((uint16_t)port);
  12482. len += (int)(hostnlen + 1);
  12483. } else {
  12484. port = 0;
  12485. len = 0;
  12486. }
  12487. #endif
  12488. }
  12489. } else {
  12490. /* Parsing failure. */
  12491. }
  12492. /* sscanf and the option splitting code ensure the following condition
  12493. */
  12494. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12495. *ip_version = 0;
  12496. return 0;
  12497. }
  12498. ch = vec->ptr[len]; /* Next character after the port number */
  12499. so->is_ssl = (ch == 's');
  12500. so->ssl_redir = (ch == 'r');
  12501. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12502. if (is_valid_port(port)
  12503. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12504. return 1;
  12505. }
  12506. /* Reset ip_version to 0 if there is an error */
  12507. *ip_version = 0;
  12508. return 0;
  12509. }
  12510. /* Is there any SSL port in use? */
  12511. static int
  12512. is_ssl_port_used(const char *ports)
  12513. {
  12514. if (ports) {
  12515. /* There are several different allowed syntax variants:
  12516. * - "80" for a single port using every network interface
  12517. * - "localhost:80" for a single port using only localhost
  12518. * - "80,localhost:8080" for two ports, one bound to localhost
  12519. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12520. * to IPv4 localhost, one to IPv6 localhost
  12521. * - "+80" use port 80 for IPv4 and IPv6
  12522. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12523. * for both: IPv4 and IPv4
  12524. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12525. * additionally port 8080 bound to localhost connections
  12526. *
  12527. * If we just look for 's' anywhere in the string, "localhost:80"
  12528. * will be detected as SSL (false positive).
  12529. * Looking for 's' after a digit may cause false positives in
  12530. * "my24service:8080".
  12531. * Looking from 's' backward if there are only ':' and numbers
  12532. * before will not work for "24service:8080" (non SSL, port 8080)
  12533. * or "24s" (SSL, port 24).
  12534. *
  12535. * Remark: Initially hostnames were not allowed to start with a
  12536. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12537. * Section 2.1).
  12538. *
  12539. * To get this correct, the entire string must be parsed as a whole,
  12540. * reading it as a list element for element and parsing with an
  12541. * algorithm equivalent to parse_port_string.
  12542. *
  12543. * In fact, we use local interface names here, not arbitrary hostnames,
  12544. * so in most cases the only name will be "localhost".
  12545. *
  12546. * So, for now, we use this simple algorithm, that may still return
  12547. * a false positive in bizarre cases.
  12548. */
  12549. int i;
  12550. int portslen = (int)strlen(ports);
  12551. char prevIsNumber = 0;
  12552. for (i = 0; i < portslen; i++) {
  12553. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12554. return 1;
  12555. }
  12556. if (ports[i] >= '0' && ports[i] <= '9') {
  12557. prevIsNumber = 1;
  12558. } else {
  12559. prevIsNumber = 0;
  12560. }
  12561. }
  12562. }
  12563. return 0;
  12564. }
  12565. static int
  12566. set_ports_option(struct mg_context *phys_ctx)
  12567. {
  12568. const char *list;
  12569. int on = 1;
  12570. #if defined(USE_IPV6)
  12571. int off = 0;
  12572. #endif
  12573. struct vec vec;
  12574. struct socket so, *ptr;
  12575. struct mg_pollfd *pfd;
  12576. union usa usa;
  12577. socklen_t len;
  12578. int ip_version;
  12579. int portsTotal = 0;
  12580. int portsOk = 0;
  12581. const char *opt_txt;
  12582. long opt_max_connections;
  12583. if (!phys_ctx) {
  12584. return 0;
  12585. }
  12586. memset(&so, 0, sizeof(so));
  12587. memset(&usa, 0, sizeof(usa));
  12588. len = sizeof(usa);
  12589. list = phys_ctx->dd.config[LISTENING_PORTS];
  12590. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12591. portsTotal++;
  12592. if (!parse_port_string(&vec, &so, &ip_version)) {
  12593. mg_cry_ctx_internal(
  12594. phys_ctx,
  12595. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12596. (int)vec.len,
  12597. vec.ptr,
  12598. portsTotal,
  12599. "[IP_ADDRESS:]PORT[s|r]");
  12600. continue;
  12601. }
  12602. #if !defined(NO_SSL)
  12603. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12604. mg_cry_ctx_internal(phys_ctx,
  12605. "Cannot add SSL socket (entry %i)",
  12606. portsTotal);
  12607. continue;
  12608. }
  12609. #endif
  12610. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12611. == INVALID_SOCKET) {
  12612. mg_cry_ctx_internal(phys_ctx,
  12613. "cannot create socket (entry %i)",
  12614. portsTotal);
  12615. continue;
  12616. }
  12617. #if defined(_WIN32)
  12618. /* Windows SO_REUSEADDR lets many procs binds to a
  12619. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12620. * if someone already has the socket -- DTL */
  12621. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12622. * Windows might need a few seconds before
  12623. * the same port can be used again in the
  12624. * same process, so a short Sleep may be
  12625. * required between mg_stop and mg_start.
  12626. */
  12627. if (setsockopt(so.sock,
  12628. SOL_SOCKET,
  12629. SO_EXCLUSIVEADDRUSE,
  12630. (SOCK_OPT_TYPE)&on,
  12631. sizeof(on))
  12632. != 0) {
  12633. /* Set reuse option, but don't abort on errors. */
  12634. mg_cry_ctx_internal(
  12635. phys_ctx,
  12636. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12637. portsTotal);
  12638. }
  12639. #else
  12640. if (setsockopt(so.sock,
  12641. SOL_SOCKET,
  12642. SO_REUSEADDR,
  12643. (SOCK_OPT_TYPE)&on,
  12644. sizeof(on))
  12645. != 0) {
  12646. /* Set reuse option, but don't abort on errors. */
  12647. mg_cry_ctx_internal(
  12648. phys_ctx,
  12649. "cannot set socket option SO_REUSEADDR (entry %i)",
  12650. portsTotal);
  12651. }
  12652. #endif
  12653. if (ip_version > 4) {
  12654. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12655. #if defined(USE_IPV6)
  12656. if (ip_version > 6) {
  12657. if (so.lsa.sa.sa_family == AF_INET6
  12658. && setsockopt(so.sock,
  12659. IPPROTO_IPV6,
  12660. IPV6_V6ONLY,
  12661. (void *)&off,
  12662. sizeof(off))
  12663. != 0) {
  12664. /* Set IPv6 only option, but don't abort on errors. */
  12665. mg_cry_ctx_internal(
  12666. phys_ctx,
  12667. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12668. portsTotal);
  12669. }
  12670. } else {
  12671. if (so.lsa.sa.sa_family == AF_INET6
  12672. && setsockopt(so.sock,
  12673. IPPROTO_IPV6,
  12674. IPV6_V6ONLY,
  12675. (void *)&on,
  12676. sizeof(on))
  12677. != 0) {
  12678. /* Set IPv6 only option, but don't abort on errors. */
  12679. mg_cry_ctx_internal(
  12680. phys_ctx,
  12681. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12682. portsTotal);
  12683. }
  12684. }
  12685. #else
  12686. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12687. closesocket(so.sock);
  12688. so.sock = INVALID_SOCKET;
  12689. continue;
  12690. #endif
  12691. }
  12692. if (so.lsa.sa.sa_family == AF_INET) {
  12693. len = sizeof(so.lsa.sin);
  12694. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12695. mg_cry_ctx_internal(phys_ctx,
  12696. "cannot bind to %.*s: %d (%s)",
  12697. (int)vec.len,
  12698. vec.ptr,
  12699. (int)ERRNO,
  12700. strerror(errno));
  12701. closesocket(so.sock);
  12702. so.sock = INVALID_SOCKET;
  12703. continue;
  12704. }
  12705. }
  12706. #if defined(USE_IPV6)
  12707. else if (so.lsa.sa.sa_family == AF_INET6) {
  12708. len = sizeof(so.lsa.sin6);
  12709. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12710. mg_cry_ctx_internal(phys_ctx,
  12711. "cannot bind to IPv6 %.*s: %d (%s)",
  12712. (int)vec.len,
  12713. vec.ptr,
  12714. (int)ERRNO,
  12715. strerror(errno));
  12716. closesocket(so.sock);
  12717. so.sock = INVALID_SOCKET;
  12718. continue;
  12719. }
  12720. }
  12721. #endif
  12722. else {
  12723. mg_cry_ctx_internal(
  12724. phys_ctx,
  12725. "cannot bind: address family not supported (entry %i)",
  12726. portsTotal);
  12727. closesocket(so.sock);
  12728. so.sock = INVALID_SOCKET;
  12729. continue;
  12730. }
  12731. opt_txt = phys_ctx->dd.config[MAX_CONNECTIONS];
  12732. opt_max_connections = strtol(opt_txt, NULL, 10);
  12733. if ((opt_max_connections > INT_MAX) || (opt_max_connections < 1)) {
  12734. mg_cry_ctx_internal(phys_ctx,
  12735. "max_connections value \"%s\" is invalid",
  12736. opt_txt);
  12737. continue;
  12738. }
  12739. if (listen(so.sock, (int)opt_max_connections) != 0) {
  12740. mg_cry_ctx_internal(phys_ctx,
  12741. "cannot listen to %.*s: %d (%s)",
  12742. (int)vec.len,
  12743. vec.ptr,
  12744. (int)ERRNO,
  12745. strerror(errno));
  12746. closesocket(so.sock);
  12747. so.sock = INVALID_SOCKET;
  12748. continue;
  12749. }
  12750. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12751. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12752. int err = (int)ERRNO;
  12753. mg_cry_ctx_internal(phys_ctx,
  12754. "call to getsockname failed %.*s: %d (%s)",
  12755. (int)vec.len,
  12756. vec.ptr,
  12757. err,
  12758. strerror(errno));
  12759. closesocket(so.sock);
  12760. so.sock = INVALID_SOCKET;
  12761. continue;
  12762. }
  12763. /* Update lsa port in case of random free ports */
  12764. #if defined(USE_IPV6)
  12765. if (so.lsa.sa.sa_family == AF_INET6) {
  12766. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12767. } else
  12768. #endif
  12769. {
  12770. so.lsa.sin.sin_port = usa.sin.sin_port;
  12771. }
  12772. if ((ptr = (struct socket *)
  12773. mg_realloc_ctx(phys_ctx->listening_sockets,
  12774. (phys_ctx->num_listening_sockets + 1)
  12775. * sizeof(phys_ctx->listening_sockets[0]),
  12776. phys_ctx))
  12777. == NULL) {
  12778. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12779. closesocket(so.sock);
  12780. so.sock = INVALID_SOCKET;
  12781. continue;
  12782. }
  12783. if ((pfd = (struct mg_pollfd *)
  12784. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12785. (phys_ctx->num_listening_sockets + 1)
  12786. * sizeof(phys_ctx->listening_socket_fds[0]),
  12787. phys_ctx))
  12788. == NULL) {
  12789. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12790. closesocket(so.sock);
  12791. so.sock = INVALID_SOCKET;
  12792. mg_free(ptr);
  12793. continue;
  12794. }
  12795. set_close_on_exec(so.sock, NULL, phys_ctx);
  12796. phys_ctx->listening_sockets = ptr;
  12797. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12798. phys_ctx->listening_socket_fds = pfd;
  12799. phys_ctx->num_listening_sockets++;
  12800. portsOk++;
  12801. }
  12802. if (portsOk != portsTotal) {
  12803. close_all_listening_sockets(phys_ctx);
  12804. portsOk = 0;
  12805. }
  12806. return portsOk;
  12807. }
  12808. static const char *
  12809. header_val(const struct mg_connection *conn, const char *header)
  12810. {
  12811. const char *header_value;
  12812. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12813. return "-";
  12814. } else {
  12815. return header_value;
  12816. }
  12817. }
  12818. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12819. static void log_access(const struct mg_connection *conn);
  12820. #include "external_log_access.inl"
  12821. #elif !defined(NO_FILESYSTEMS)
  12822. static void
  12823. log_access(const struct mg_connection *conn)
  12824. {
  12825. const struct mg_request_info *ri;
  12826. struct mg_file fi;
  12827. char date[64], src_addr[IP_ADDR_STR_LEN];
  12828. struct tm *tm;
  12829. const char *referer;
  12830. const char *user_agent;
  12831. char buf[4096];
  12832. if (!conn || !conn->dom_ctx) {
  12833. return;
  12834. }
  12835. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12836. if (mg_fopen(conn,
  12837. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12838. MG_FOPEN_MODE_APPEND,
  12839. &fi)
  12840. == 0) {
  12841. fi.access.fp = NULL;
  12842. }
  12843. } else {
  12844. fi.access.fp = NULL;
  12845. }
  12846. /* Log is written to a file and/or a callback. If both are not set,
  12847. * executing the rest of the function is pointless. */
  12848. if ((fi.access.fp == NULL)
  12849. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12850. return;
  12851. }
  12852. tm = localtime(&conn->conn_birth_time);
  12853. if (tm != NULL) {
  12854. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12855. } else {
  12856. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12857. date[sizeof(date) - 1] = '\0';
  12858. }
  12859. ri = &conn->request_info;
  12860. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12861. referer = header_val(conn, "Referer");
  12862. user_agent = header_val(conn, "User-Agent");
  12863. mg_snprintf(conn,
  12864. NULL, /* Ignore truncation in access log */
  12865. buf,
  12866. sizeof(buf),
  12867. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12868. src_addr,
  12869. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12870. date,
  12871. ri->request_method ? ri->request_method : "-",
  12872. ri->request_uri ? ri->request_uri : "-",
  12873. ri->query_string ? "?" : "",
  12874. ri->query_string ? ri->query_string : "",
  12875. ri->http_version,
  12876. conn->status_code,
  12877. conn->num_bytes_sent,
  12878. referer,
  12879. user_agent);
  12880. if (conn->phys_ctx->callbacks.log_access) {
  12881. conn->phys_ctx->callbacks.log_access(conn, buf);
  12882. }
  12883. if (fi.access.fp) {
  12884. int ok = 1;
  12885. flockfile(fi.access.fp);
  12886. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12887. ok = 0;
  12888. }
  12889. if (fflush(fi.access.fp) != 0) {
  12890. ok = 0;
  12891. }
  12892. funlockfile(fi.access.fp);
  12893. if (mg_fclose(&fi.access) != 0) {
  12894. ok = 0;
  12895. }
  12896. if (!ok) {
  12897. mg_cry_internal(conn,
  12898. "Error writing log file %s",
  12899. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12900. }
  12901. }
  12902. }
  12903. #else
  12904. #error Must either enable filesystems or provide a custom log_access implementation
  12905. #endif /* Externally provided function */
  12906. /* Verify given socket address against the ACL.
  12907. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12908. */
  12909. static int
  12910. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12911. {
  12912. int allowed, flag;
  12913. uint32_t net, mask;
  12914. struct vec vec;
  12915. if (phys_ctx) {
  12916. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12917. /* If any ACL is set, deny by default */
  12918. allowed = (list == NULL) ? '+' : '-';
  12919. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12920. flag = vec.ptr[0];
  12921. if ((flag != '+' && flag != '-')
  12922. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12923. mg_cry_ctx_internal(phys_ctx,
  12924. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12925. __func__);
  12926. return -1;
  12927. }
  12928. if (net == (remote_ip & mask)) {
  12929. allowed = flag;
  12930. }
  12931. }
  12932. return allowed == '+';
  12933. }
  12934. return -1;
  12935. }
  12936. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  12937. static int
  12938. set_uid_option(struct mg_context *phys_ctx)
  12939. {
  12940. int success = 0;
  12941. if (phys_ctx) {
  12942. /* We are currently running as curr_uid. */
  12943. const uid_t curr_uid = getuid();
  12944. /* If set, we want to run as run_as_user. */
  12945. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12946. const struct passwd *to_pw = NULL;
  12947. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12948. /* run_as_user does not exist on the system. We can't proceed
  12949. * further. */
  12950. mg_cry_ctx_internal(phys_ctx,
  12951. "%s: unknown user [%s]",
  12952. __func__,
  12953. run_as_user);
  12954. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12955. /* There was either no request to change user, or we're already
  12956. * running as run_as_user. Nothing else to do.
  12957. */
  12958. success = 1;
  12959. } else {
  12960. /* Valid change request. */
  12961. if (setgid(to_pw->pw_gid) == -1) {
  12962. mg_cry_ctx_internal(phys_ctx,
  12963. "%s: setgid(%s): %s",
  12964. __func__,
  12965. run_as_user,
  12966. strerror(errno));
  12967. } else if (setgroups(0, NULL) == -1) {
  12968. mg_cry_ctx_internal(phys_ctx,
  12969. "%s: setgroups(): %s",
  12970. __func__,
  12971. strerror(errno));
  12972. } else if (setuid(to_pw->pw_uid) == -1) {
  12973. mg_cry_ctx_internal(phys_ctx,
  12974. "%s: setuid(%s): %s",
  12975. __func__,
  12976. run_as_user,
  12977. strerror(errno));
  12978. } else {
  12979. success = 1;
  12980. }
  12981. }
  12982. }
  12983. return success;
  12984. }
  12985. #endif /* !_WIN32 */
  12986. static void
  12987. tls_dtor(void *key)
  12988. {
  12989. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12990. /* key == pthread_getspecific(sTlsKey); */
  12991. if (tls) {
  12992. if (tls->is_master == 2) {
  12993. tls->is_master = -3; /* Mark memory as dead */
  12994. mg_free(tls);
  12995. }
  12996. }
  12997. pthread_setspecific(sTlsKey, NULL);
  12998. }
  12999. #if !defined(NO_SSL)
  13000. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  13001. struct mg_domain_context *dom_ctx,
  13002. const char *pem,
  13003. const char *chain);
  13004. static const char *ssl_error(void);
  13005. static int
  13006. refresh_trust(struct mg_connection *conn)
  13007. {
  13008. static int reload_lock = 0;
  13009. static long int data_check = 0;
  13010. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  13011. struct stat cert_buf;
  13012. long int t;
  13013. const char *pem;
  13014. const char *chain;
  13015. int should_verify_peer;
  13016. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13017. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13018. * refresh_trust still can not work. */
  13019. return 0;
  13020. }
  13021. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13022. if (chain == NULL) {
  13023. /* pem is not NULL here */
  13024. chain = pem;
  13025. }
  13026. if (*chain == 0) {
  13027. chain = NULL;
  13028. }
  13029. t = data_check;
  13030. if (stat(pem, &cert_buf) != -1) {
  13031. t = (long int)cert_buf.st_mtime;
  13032. }
  13033. if (data_check != t) {
  13034. data_check = t;
  13035. should_verify_peer = 0;
  13036. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13037. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13038. == 0) {
  13039. should_verify_peer = 1;
  13040. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13041. "optional")
  13042. == 0) {
  13043. should_verify_peer = 1;
  13044. }
  13045. }
  13046. if (should_verify_peer) {
  13047. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13048. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13049. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13050. ca_file,
  13051. ca_path)
  13052. != 1) {
  13053. mg_cry_ctx_internal(
  13054. conn->phys_ctx,
  13055. "SSL_CTX_load_verify_locations error: %s "
  13056. "ssl_verify_peer requires setting "
  13057. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13058. "present in "
  13059. "the .conf file?",
  13060. ssl_error());
  13061. return 0;
  13062. }
  13063. }
  13064. if (1 == mg_atomic_inc(p_reload_lock)) {
  13065. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13066. == 0) {
  13067. return 0;
  13068. }
  13069. *p_reload_lock = 0;
  13070. }
  13071. }
  13072. /* lock while cert is reloading */
  13073. while (*p_reload_lock) {
  13074. sleep(1);
  13075. }
  13076. return 1;
  13077. }
  13078. #if defined(OPENSSL_API_1_1)
  13079. #else
  13080. static pthread_mutex_t *ssl_mutexes;
  13081. #endif /* OPENSSL_API_1_1 */
  13082. static int
  13083. sslize(struct mg_connection *conn,
  13084. SSL_CTX *s,
  13085. int (*func)(SSL *),
  13086. volatile int *stop_server,
  13087. const struct mg_client_options *client_options)
  13088. {
  13089. int ret, err;
  13090. int short_trust;
  13091. unsigned timeout = 1024;
  13092. unsigned i;
  13093. if (!conn) {
  13094. return 0;
  13095. }
  13096. short_trust =
  13097. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13098. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13099. if (short_trust) {
  13100. int trust_ret = refresh_trust(conn);
  13101. if (!trust_ret) {
  13102. return trust_ret;
  13103. }
  13104. }
  13105. conn->ssl = SSL_new(s);
  13106. if (conn->ssl == NULL) {
  13107. return 0;
  13108. }
  13109. SSL_set_app_data(conn->ssl, (char *)conn);
  13110. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13111. if (ret != 1) {
  13112. err = SSL_get_error(conn->ssl, ret);
  13113. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13114. SSL_free(conn->ssl);
  13115. conn->ssl = NULL;
  13116. OPENSSL_REMOVE_THREAD_STATE();
  13117. return 0;
  13118. }
  13119. if (client_options) {
  13120. if (client_options->host_name) {
  13121. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13122. }
  13123. }
  13124. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13125. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13126. /* NOTE: The loop below acts as a back-off, so we can end
  13127. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13128. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13129. }
  13130. /* SSL functions may fail and require to be called again:
  13131. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13132. * Here "func" could be SSL_connect or SSL_accept. */
  13133. for (i = 0; i <= timeout; i += 50) {
  13134. ret = func(conn->ssl);
  13135. if (ret != 1) {
  13136. err = SSL_get_error(conn->ssl, ret);
  13137. if ((err == SSL_ERROR_WANT_CONNECT)
  13138. || (err == SSL_ERROR_WANT_ACCEPT)
  13139. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13140. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13141. if (*stop_server) {
  13142. /* Don't wait if the server is going to be stopped. */
  13143. break;
  13144. }
  13145. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13146. /* Simply retry the function call. */
  13147. mg_sleep(50);
  13148. } else {
  13149. /* Need to retry the function call "later".
  13150. * See https://linux.die.net/man/3/ssl_get_error
  13151. * This is typical for non-blocking sockets. */
  13152. struct mg_pollfd pfd;
  13153. int pollres;
  13154. pfd.fd = conn->client.sock;
  13155. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13156. || (err == SSL_ERROR_WANT_WRITE))
  13157. ? POLLOUT
  13158. : POLLIN;
  13159. pollres = mg_poll(&pfd, 1, 50, stop_server);
  13160. if (pollres < 0) {
  13161. /* Break if error occured (-1)
  13162. * or server shutdown (-2) */
  13163. break;
  13164. }
  13165. }
  13166. } else if (err == SSL_ERROR_SYSCALL) {
  13167. /* This is an IO error. Look at errno. */
  13168. err = errno;
  13169. mg_cry_internal(conn, "SSL syscall error %i", err);
  13170. break;
  13171. } else {
  13172. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13173. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13174. break;
  13175. }
  13176. ERR_clear_error();
  13177. } else {
  13178. /* success */
  13179. break;
  13180. }
  13181. }
  13182. if (ret != 1) {
  13183. SSL_free(conn->ssl);
  13184. conn->ssl = NULL;
  13185. OPENSSL_REMOVE_THREAD_STATE();
  13186. return 0;
  13187. }
  13188. return 1;
  13189. }
  13190. /* Return OpenSSL error message (from CRYPTO lib) */
  13191. static const char *
  13192. ssl_error(void)
  13193. {
  13194. unsigned long err;
  13195. err = ERR_get_error();
  13196. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13197. }
  13198. static int
  13199. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13200. {
  13201. int i;
  13202. const char hexdigit[] = "0123456789abcdef";
  13203. if ((memlen <= 0) || (buflen <= 0)) {
  13204. return 0;
  13205. }
  13206. if (buflen < (3 * memlen)) {
  13207. return 0;
  13208. }
  13209. for (i = 0; i < memlen; i++) {
  13210. if (i > 0) {
  13211. buf[3 * i - 1] = ' ';
  13212. }
  13213. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13214. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13215. }
  13216. buf[3 * memlen - 1] = 0;
  13217. return 1;
  13218. }
  13219. static void
  13220. ssl_get_client_cert_info(struct mg_connection *conn)
  13221. {
  13222. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13223. if (cert) {
  13224. char str_subject[1024];
  13225. char str_issuer[1024];
  13226. char str_finger[1024];
  13227. unsigned char buf[256];
  13228. char *str_serial = NULL;
  13229. unsigned int ulen;
  13230. int ilen;
  13231. unsigned char *tmp_buf;
  13232. unsigned char *tmp_p;
  13233. /* Handle to algorithm used for fingerprint */
  13234. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13235. /* Get Subject and issuer */
  13236. X509_NAME *subj = X509_get_subject_name(cert);
  13237. X509_NAME *iss = X509_get_issuer_name(cert);
  13238. /* Get serial number */
  13239. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13240. /* Translate serial number to a hex string */
  13241. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13242. str_serial = BN_bn2hex(serial_bn);
  13243. BN_free(serial_bn);
  13244. /* Translate subject and issuer to a string */
  13245. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13246. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13247. /* Calculate SHA1 fingerprint and store as a hex string */
  13248. ulen = 0;
  13249. /* ASN1_digest is deprecated. Do the calculation manually,
  13250. * using EVP_Digest. */
  13251. ilen = i2d_X509(cert, NULL);
  13252. tmp_buf = (ilen > 0)
  13253. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13254. conn->phys_ctx)
  13255. : NULL;
  13256. if (tmp_buf) {
  13257. tmp_p = tmp_buf;
  13258. (void)i2d_X509(cert, &tmp_p);
  13259. if (!EVP_Digest(
  13260. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13261. ulen = 0;
  13262. }
  13263. mg_free(tmp_buf);
  13264. }
  13265. if (!hexdump2string(
  13266. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13267. *str_finger = 0;
  13268. }
  13269. conn->request_info.client_cert = (struct mg_client_cert *)
  13270. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13271. if (conn->request_info.client_cert) {
  13272. conn->request_info.client_cert->peer_cert = (void *)cert;
  13273. conn->request_info.client_cert->subject =
  13274. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13275. conn->request_info.client_cert->issuer =
  13276. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13277. conn->request_info.client_cert->serial =
  13278. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13279. conn->request_info.client_cert->finger =
  13280. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13281. } else {
  13282. mg_cry_internal(conn,
  13283. "%s",
  13284. "Out of memory: Cannot allocate memory for client "
  13285. "certificate");
  13286. }
  13287. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13288. * see https://linux.die.net/man/3/bn_bn2hex */
  13289. OPENSSL_free(str_serial);
  13290. }
  13291. }
  13292. #if defined(OPENSSL_API_1_1)
  13293. #else
  13294. static void
  13295. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13296. {
  13297. (void)line;
  13298. (void)file;
  13299. if (mode & 1) {
  13300. /* 1 is CRYPTO_LOCK */
  13301. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13302. } else {
  13303. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13304. }
  13305. }
  13306. #endif /* OPENSSL_API_1_1 */
  13307. #if !defined(NO_SSL_DL)
  13308. static void *
  13309. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13310. {
  13311. union {
  13312. void *p;
  13313. void (*fp)(void);
  13314. } u;
  13315. void *dll_handle;
  13316. struct ssl_func *fp;
  13317. int ok;
  13318. int truncated = 0;
  13319. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13320. mg_snprintf(NULL,
  13321. NULL, /* No truncation check for ebuf */
  13322. ebuf,
  13323. ebuf_len,
  13324. "%s: cannot load %s",
  13325. __func__,
  13326. dll_name);
  13327. return NULL;
  13328. }
  13329. ok = 1;
  13330. for (fp = sw; fp->name != NULL; fp++) {
  13331. #if defined(_WIN32)
  13332. /* GetProcAddress() returns pointer to function */
  13333. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13334. #else
  13335. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13336. * pointers to function pointers. We need to use a union to make a
  13337. * cast. */
  13338. u.p = dlsym(dll_handle, fp->name);
  13339. #endif /* _WIN32 */
  13340. if (u.fp == NULL) {
  13341. if (ok) {
  13342. mg_snprintf(NULL,
  13343. &truncated,
  13344. ebuf,
  13345. ebuf_len,
  13346. "%s: %s: cannot find %s",
  13347. __func__,
  13348. dll_name,
  13349. fp->name);
  13350. ok = 0;
  13351. } else {
  13352. size_t cur_len = strlen(ebuf);
  13353. if (!truncated) {
  13354. mg_snprintf(NULL,
  13355. &truncated,
  13356. ebuf + cur_len,
  13357. ebuf_len - cur_len - 3,
  13358. ", %s",
  13359. fp->name);
  13360. if (truncated) {
  13361. /* If truncated, add "..." */
  13362. strcat(ebuf, "...");
  13363. }
  13364. }
  13365. }
  13366. /* Debug:
  13367. * printf("Missing function: %s\n", fp->name); */
  13368. } else {
  13369. fp->ptr = u.fp;
  13370. }
  13371. }
  13372. if (!ok) {
  13373. (void)dlclose(dll_handle);
  13374. return NULL;
  13375. }
  13376. return dll_handle;
  13377. }
  13378. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13379. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13380. #endif /* NO_SSL_DL */
  13381. #if defined(SSL_ALREADY_INITIALIZED)
  13382. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13383. #else
  13384. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13385. #endif
  13386. static int
  13387. initialize_ssl(char *ebuf, size_t ebuf_len)
  13388. {
  13389. #if defined(OPENSSL_API_1_1)
  13390. if (ebuf_len > 0) {
  13391. ebuf[0] = 0;
  13392. }
  13393. #if !defined(NO_SSL_DL)
  13394. if (!cryptolib_dll_handle) {
  13395. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13396. if (!cryptolib_dll_handle) {
  13397. mg_snprintf(NULL,
  13398. NULL, /* No truncation check for ebuf */
  13399. ebuf,
  13400. ebuf_len,
  13401. "%s: error loading library %s",
  13402. __func__,
  13403. CRYPTO_LIB);
  13404. DEBUG_TRACE("%s", ebuf);
  13405. return 0;
  13406. }
  13407. }
  13408. #endif /* NO_SSL_DL */
  13409. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13410. return 1;
  13411. }
  13412. #else /* not OPENSSL_API_1_1 */
  13413. int i, num_locks;
  13414. size_t size;
  13415. if (ebuf_len > 0) {
  13416. ebuf[0] = 0;
  13417. }
  13418. #if !defined(NO_SSL_DL)
  13419. if (!cryptolib_dll_handle) {
  13420. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13421. if (!cryptolib_dll_handle) {
  13422. mg_snprintf(NULL,
  13423. NULL, /* No truncation check for ebuf */
  13424. ebuf,
  13425. ebuf_len,
  13426. "%s: error loading library %s",
  13427. __func__,
  13428. CRYPTO_LIB);
  13429. DEBUG_TRACE("%s", ebuf);
  13430. return 0;
  13431. }
  13432. }
  13433. #endif /* NO_SSL_DL */
  13434. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13435. return 1;
  13436. }
  13437. /* Initialize locking callbacks, needed for thread safety.
  13438. * http://www.openssl.org/support/faq.html#PROG1
  13439. */
  13440. num_locks = CRYPTO_num_locks();
  13441. if (num_locks < 0) {
  13442. num_locks = 0;
  13443. }
  13444. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13445. /* allocate mutex array, if required */
  13446. if (num_locks == 0) {
  13447. /* No mutex array required */
  13448. ssl_mutexes = NULL;
  13449. } else {
  13450. /* Mutex array required - allocate it */
  13451. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13452. /* Check OOM */
  13453. if (ssl_mutexes == NULL) {
  13454. mg_snprintf(NULL,
  13455. NULL, /* No truncation check for ebuf */
  13456. ebuf,
  13457. ebuf_len,
  13458. "%s: cannot allocate mutexes: %s",
  13459. __func__,
  13460. ssl_error());
  13461. DEBUG_TRACE("%s", ebuf);
  13462. return 0;
  13463. }
  13464. /* initialize mutex array */
  13465. for (i = 0; i < num_locks; i++) {
  13466. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13467. mg_snprintf(NULL,
  13468. NULL, /* No truncation check for ebuf */
  13469. ebuf,
  13470. ebuf_len,
  13471. "%s: error initializing mutex %i of %i",
  13472. __func__,
  13473. i,
  13474. num_locks);
  13475. DEBUG_TRACE("%s", ebuf);
  13476. mg_free(ssl_mutexes);
  13477. return 0;
  13478. }
  13479. }
  13480. }
  13481. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13482. CRYPTO_set_id_callback(&mg_current_thread_id);
  13483. #endif /* OPENSSL_API_1_1 */
  13484. #if !defined(NO_SSL_DL)
  13485. if (!ssllib_dll_handle) {
  13486. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13487. if (!ssllib_dll_handle) {
  13488. #if !defined(OPENSSL_API_1_1)
  13489. mg_free(ssl_mutexes);
  13490. #endif
  13491. DEBUG_TRACE("%s", ebuf);
  13492. return 0;
  13493. }
  13494. }
  13495. #endif /* NO_SSL_DL */
  13496. #if defined(OPENSSL_API_1_1)
  13497. /* Initialize SSL library */
  13498. OPENSSL_init_ssl(0, NULL);
  13499. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13500. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13501. NULL);
  13502. #else
  13503. /* Initialize SSL library */
  13504. SSL_library_init();
  13505. SSL_load_error_strings();
  13506. #endif
  13507. return 1;
  13508. }
  13509. static int
  13510. ssl_use_pem_file(struct mg_context *phys_ctx,
  13511. struct mg_domain_context *dom_ctx,
  13512. const char *pem,
  13513. const char *chain)
  13514. {
  13515. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13516. mg_cry_ctx_internal(phys_ctx,
  13517. "%s: cannot open certificate file %s: %s",
  13518. __func__,
  13519. pem,
  13520. ssl_error());
  13521. return 0;
  13522. }
  13523. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13524. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13525. mg_cry_ctx_internal(phys_ctx,
  13526. "%s: cannot open private key file %s: %s",
  13527. __func__,
  13528. pem,
  13529. ssl_error());
  13530. return 0;
  13531. }
  13532. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13533. mg_cry_ctx_internal(phys_ctx,
  13534. "%s: certificate and private key do not match: %s",
  13535. __func__,
  13536. pem);
  13537. return 0;
  13538. }
  13539. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13540. * chain files that contain private keys and certificates in
  13541. * SSL_CTX_use_certificate_chain_file.
  13542. * The CivetWeb-Server used pem-Files that contained both information.
  13543. * In order to make wolfSSL work, it is split in two files.
  13544. * One file that contains key and certificate used by the server and
  13545. * an optional chain file for the ssl stack.
  13546. */
  13547. if (chain) {
  13548. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13549. mg_cry_ctx_internal(phys_ctx,
  13550. "%s: cannot use certificate chain file %s: %s",
  13551. __func__,
  13552. chain,
  13553. ssl_error());
  13554. return 0;
  13555. }
  13556. }
  13557. return 1;
  13558. }
  13559. #if defined(OPENSSL_API_1_1)
  13560. static unsigned long
  13561. ssl_get_protocol(int version_id)
  13562. {
  13563. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13564. if (version_id > 0)
  13565. ret |= SSL_OP_NO_SSLv2;
  13566. if (version_id > 1)
  13567. ret |= SSL_OP_NO_SSLv3;
  13568. if (version_id > 2)
  13569. ret |= SSL_OP_NO_TLSv1;
  13570. if (version_id > 3)
  13571. ret |= SSL_OP_NO_TLSv1_1;
  13572. if (version_id > 4)
  13573. ret |= SSL_OP_NO_TLSv1_2;
  13574. #if defined(SSL_OP_NO_TLSv1_3)
  13575. if (version_id > 5)
  13576. ret |= SSL_OP_NO_TLSv1_3;
  13577. #endif
  13578. return ret;
  13579. }
  13580. #else
  13581. static long
  13582. ssl_get_protocol(int version_id)
  13583. {
  13584. long ret = (long)SSL_OP_ALL;
  13585. if (version_id > 0)
  13586. ret |= SSL_OP_NO_SSLv2;
  13587. if (version_id > 1)
  13588. ret |= SSL_OP_NO_SSLv3;
  13589. if (version_id > 2)
  13590. ret |= SSL_OP_NO_TLSv1;
  13591. if (version_id > 3)
  13592. ret |= SSL_OP_NO_TLSv1_1;
  13593. if (version_id > 4)
  13594. ret |= SSL_OP_NO_TLSv1_2;
  13595. #if defined(SSL_OP_NO_TLSv1_3)
  13596. if (version_id > 5)
  13597. ret |= SSL_OP_NO_TLSv1_3;
  13598. #endif
  13599. return ret;
  13600. }
  13601. #endif /* OPENSSL_API_1_1 */
  13602. /* SSL callback documentation:
  13603. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13604. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13605. * https://linux.die.net/man/3/ssl_set_info_callback */
  13606. /* Note: There is no "const" for the first argument in the documentation
  13607. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13608. * / OpenSSL compatibility layers have it. Having a different definition will
  13609. * cause a warning in C and an error in C++. Use "const SSL *", while
  13610. * automatical conversion from "SSL *" works for all compilers, but not other
  13611. * way around */
  13612. static void
  13613. ssl_info_callback(const SSL *ssl, int what, int ret)
  13614. {
  13615. (void)ret;
  13616. if (what & SSL_CB_HANDSHAKE_START) {
  13617. SSL_get_app_data(ssl);
  13618. }
  13619. if (what & SSL_CB_HANDSHAKE_DONE) {
  13620. /* TODO: check for openSSL 1.1 */
  13621. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13622. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13623. }
  13624. }
  13625. static int
  13626. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13627. {
  13628. struct mg_context *ctx = (struct mg_context *)arg;
  13629. struct mg_domain_context *dom =
  13630. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13631. #if defined(GCC_DIAGNOSTIC)
  13632. #pragma GCC diagnostic push
  13633. #pragma GCC diagnostic ignored "-Wcast-align"
  13634. #endif /* defined(GCC_DIAGNOSTIC) */
  13635. /* We used an aligned pointer in SSL_set_app_data */
  13636. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13637. #if defined(GCC_DIAGNOSTIC)
  13638. #pragma GCC diagnostic pop
  13639. #endif /* defined(GCC_DIAGNOSTIC) */
  13640. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13641. (void)ad;
  13642. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13643. DEBUG_TRACE("%s", "internal error - assertion failed");
  13644. return SSL_TLSEXT_ERR_NOACK;
  13645. }
  13646. /* Old clients (Win XP) will not support SNI. Then, there
  13647. * is no server name available in the request - we can
  13648. * only work with the default certificate.
  13649. * Multiple HTTPS hosts on one IP+port are only possible
  13650. * with a certificate containing all alternative names.
  13651. */
  13652. if ((servername == NULL) || (*servername == 0)) {
  13653. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13654. conn->dom_ctx = &(ctx->dd);
  13655. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13656. return SSL_TLSEXT_ERR_NOACK;
  13657. }
  13658. DEBUG_TRACE("TLS connection to host %s", servername);
  13659. while (dom) {
  13660. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13661. /* Found matching domain */
  13662. DEBUG_TRACE("TLS domain %s found",
  13663. dom->config[AUTHENTICATION_DOMAIN]);
  13664. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13665. conn->dom_ctx = dom;
  13666. return SSL_TLSEXT_ERR_OK;
  13667. }
  13668. dom = dom->next;
  13669. }
  13670. /* Default domain */
  13671. DEBUG_TRACE("TLS default domain %s used",
  13672. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13673. conn->dom_ctx = &(ctx->dd);
  13674. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13675. return SSL_TLSEXT_ERR_OK;
  13676. }
  13677. /* Setup SSL CTX as required by CivetWeb */
  13678. static int
  13679. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13680. struct mg_domain_context *dom_ctx,
  13681. const char *pem,
  13682. const char *chain)
  13683. {
  13684. int callback_ret;
  13685. int should_verify_peer;
  13686. int peer_certificate_optional;
  13687. const char *ca_path;
  13688. const char *ca_file;
  13689. int use_default_verify_paths;
  13690. int verify_depth;
  13691. struct timespec now_mt;
  13692. md5_byte_t ssl_context_id[16];
  13693. md5_state_t md5state;
  13694. int protocol_ver;
  13695. #if defined(OPENSSL_API_1_1)
  13696. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13697. mg_cry_ctx_internal(phys_ctx,
  13698. "SSL_CTX_new (server) error: %s",
  13699. ssl_error());
  13700. return 0;
  13701. }
  13702. #else
  13703. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13704. mg_cry_ctx_internal(phys_ctx,
  13705. "SSL_CTX_new (server) error: %s",
  13706. ssl_error());
  13707. return 0;
  13708. }
  13709. #endif /* OPENSSL_API_1_1 */
  13710. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13711. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13712. | SSL_OP_NO_TLSv1_1);
  13713. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13714. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13715. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13716. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13717. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13718. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13719. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13720. #if defined(SSL_OP_NO_RENEGOTIATION)
  13721. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  13722. #endif
  13723. #if !defined(NO_SSL_DL)
  13724. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13725. #endif /* NO_SSL_DL */
  13726. /* In SSL documentation examples callback defined without const specifier
  13727. * 'void (*)(SSL *, int, int)' See:
  13728. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13729. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13730. * But in the source code const SSL is used:
  13731. * 'void (*)(const SSL *, int, int)' See:
  13732. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13733. * Problem about wrong documentation described, but not resolved:
  13734. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13735. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13736. * But when compiled with modern C++ compiler, correct const should be
  13737. * provided
  13738. */
  13739. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13740. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13741. ssl_servername_callback);
  13742. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13743. /* If a callback has been specified, call it. */
  13744. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13745. ? 0
  13746. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13747. phys_ctx->user_data));
  13748. /* If callback returns 0, civetweb sets up the SSL certificate.
  13749. * If it returns 1, civetweb assumes the calback already did this.
  13750. * If it returns -1, initializing ssl fails. */
  13751. if (callback_ret < 0) {
  13752. mg_cry_ctx_internal(phys_ctx,
  13753. "SSL callback returned error: %i",
  13754. callback_ret);
  13755. return 0;
  13756. }
  13757. if (callback_ret > 0) {
  13758. /* Callback did everything. */
  13759. return 1;
  13760. }
  13761. /* Use some combination of start time, domain and port as a SSL
  13762. * context ID. This should be unique on the current machine. */
  13763. md5_init(&md5state);
  13764. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13765. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13766. md5_append(&md5state,
  13767. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13768. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13769. md5_append(&md5state,
  13770. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13771. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13772. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13773. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13774. md5_finish(&md5state, ssl_context_id);
  13775. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13776. (unsigned char *)ssl_context_id,
  13777. sizeof(ssl_context_id));
  13778. if (pem != NULL) {
  13779. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13780. return 0;
  13781. }
  13782. }
  13783. /* Should we support client certificates? */
  13784. /* Default is "no". */
  13785. should_verify_peer = 0;
  13786. peer_certificate_optional = 0;
  13787. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13788. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13789. /* Yes, they are mandatory */
  13790. should_verify_peer = 1;
  13791. peer_certificate_optional = 0;
  13792. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13793. "optional")
  13794. == 0) {
  13795. /* Yes, they are optional */
  13796. should_verify_peer = 1;
  13797. peer_certificate_optional = 1;
  13798. }
  13799. }
  13800. use_default_verify_paths =
  13801. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13802. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13803. == 0);
  13804. if (should_verify_peer) {
  13805. ca_path = dom_ctx->config[SSL_CA_PATH];
  13806. ca_file = dom_ctx->config[SSL_CA_FILE];
  13807. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13808. != 1) {
  13809. mg_cry_ctx_internal(phys_ctx,
  13810. "SSL_CTX_load_verify_locations error: %s "
  13811. "ssl_verify_peer requires setting "
  13812. "either ssl_ca_path or ssl_ca_file. "
  13813. "Is any of them present in the "
  13814. ".conf file?",
  13815. ssl_error());
  13816. return 0;
  13817. }
  13818. if (peer_certificate_optional) {
  13819. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13820. } else {
  13821. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13822. SSL_VERIFY_PEER
  13823. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13824. NULL);
  13825. }
  13826. if (use_default_verify_paths
  13827. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13828. mg_cry_ctx_internal(phys_ctx,
  13829. "SSL_CTX_set_default_verify_paths error: %s",
  13830. ssl_error());
  13831. return 0;
  13832. }
  13833. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13834. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13835. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13836. }
  13837. }
  13838. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13839. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13840. dom_ctx->config[SSL_CIPHER_LIST])
  13841. != 1) {
  13842. mg_cry_ctx_internal(phys_ctx,
  13843. "SSL_CTX_set_cipher_list error: %s",
  13844. ssl_error());
  13845. }
  13846. }
  13847. return 1;
  13848. }
  13849. /* Check if SSL is required.
  13850. * If so, dynamically load SSL library
  13851. * and set up ctx->ssl_ctx pointer. */
  13852. static int
  13853. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13854. {
  13855. void *ssl_ctx = 0;
  13856. int callback_ret;
  13857. const char *pem;
  13858. const char *chain;
  13859. char ebuf[128];
  13860. if (!phys_ctx) {
  13861. return 0;
  13862. }
  13863. if (!dom_ctx) {
  13864. dom_ctx = &(phys_ctx->dd);
  13865. }
  13866. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13867. /* No SSL port is set. No need to setup SSL. */
  13868. return 1;
  13869. }
  13870. /* Check for external SSL_CTX */
  13871. callback_ret =
  13872. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13873. ? 0
  13874. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13875. phys_ctx->user_data));
  13876. if (callback_ret < 0) {
  13877. mg_cry_ctx_internal(phys_ctx,
  13878. "external_ssl_ctx callback returned error: %i",
  13879. callback_ret);
  13880. return 0;
  13881. } else if (callback_ret > 0) {
  13882. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13883. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13884. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  13885. return 0;
  13886. }
  13887. return 1;
  13888. }
  13889. /* else: external_ssl_ctx does not exist or returns 0,
  13890. * CivetWeb should continue initializing SSL */
  13891. /* If PEM file is not specified and the init_ssl callback
  13892. * is not specified, setup will fail. */
  13893. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13894. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13895. /* No certificate and no callback:
  13896. * Essential data to set up TLS is missing.
  13897. */
  13898. mg_cry_ctx_internal(phys_ctx,
  13899. "Initializing SSL failed: -%s is not set",
  13900. config_options[SSL_CERTIFICATE].name);
  13901. return 0;
  13902. }
  13903. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13904. if (chain == NULL) {
  13905. chain = pem;
  13906. }
  13907. if ((chain != NULL) && (*chain == 0)) {
  13908. chain = NULL;
  13909. }
  13910. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13911. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  13912. return 0;
  13913. }
  13914. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13915. }
  13916. static void
  13917. uninitialize_ssl(void)
  13918. {
  13919. #if defined(OPENSSL_API_1_1)
  13920. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13921. /* Shutdown according to
  13922. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13923. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13924. */
  13925. CONF_modules_unload(1);
  13926. #else
  13927. int i;
  13928. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13929. /* Shutdown according to
  13930. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13931. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13932. */
  13933. CRYPTO_set_locking_callback(NULL);
  13934. CRYPTO_set_id_callback(NULL);
  13935. ENGINE_cleanup();
  13936. CONF_modules_unload(1);
  13937. ERR_free_strings();
  13938. EVP_cleanup();
  13939. CRYPTO_cleanup_all_ex_data();
  13940. OPENSSL_REMOVE_THREAD_STATE();
  13941. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13942. pthread_mutex_destroy(&ssl_mutexes[i]);
  13943. }
  13944. mg_free(ssl_mutexes);
  13945. ssl_mutexes = NULL;
  13946. #endif /* OPENSSL_API_1_1 */
  13947. }
  13948. }
  13949. #endif /* !NO_SSL */
  13950. #if !defined(NO_FILESYSTEMS)
  13951. static int
  13952. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13953. {
  13954. if (phys_ctx) {
  13955. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13956. const char *path;
  13957. struct mg_connection fc;
  13958. if (!dom_ctx) {
  13959. dom_ctx = &(phys_ctx->dd);
  13960. }
  13961. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13962. if ((path != NULL)
  13963. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  13964. mg_cry_ctx_internal(phys_ctx,
  13965. "Cannot open %s: %s",
  13966. path,
  13967. strerror(ERRNO));
  13968. return 0;
  13969. }
  13970. return 1;
  13971. }
  13972. return 0;
  13973. }
  13974. #endif /* NO_FILESYSTEMS */
  13975. static int
  13976. set_acl_option(struct mg_context *phys_ctx)
  13977. {
  13978. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13979. }
  13980. static void
  13981. reset_per_request_attributes(struct mg_connection *conn)
  13982. {
  13983. if (!conn) {
  13984. return;
  13985. }
  13986. conn->connection_type =
  13987. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13988. conn->num_bytes_sent = conn->consumed_content = 0;
  13989. conn->path_info = NULL;
  13990. conn->status_code = -1;
  13991. conn->content_len = -1;
  13992. conn->is_chunked = 0;
  13993. conn->must_close = 0;
  13994. conn->request_len = 0;
  13995. conn->throttle = 0;
  13996. conn->accept_gzip = 0;
  13997. conn->response_info.content_length = conn->request_info.content_length = -1;
  13998. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13999. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  14000. conn->response_info.status_text = NULL;
  14001. conn->response_info.status_code = 0;
  14002. conn->request_info.remote_user = NULL;
  14003. conn->request_info.request_method = NULL;
  14004. conn->request_info.request_uri = NULL;
  14005. conn->request_info.local_uri = NULL;
  14006. #if defined(MG_LEGACY_INTERFACE)
  14007. /* Legacy before split into local_uri and request_uri */
  14008. conn->request_info.uri = NULL;
  14009. #endif
  14010. }
  14011. static int
  14012. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14013. {
  14014. if (setsockopt(sock,
  14015. IPPROTO_TCP,
  14016. TCP_NODELAY,
  14017. (SOCK_OPT_TYPE)&nodelay_on,
  14018. sizeof(nodelay_on))
  14019. != 0) {
  14020. /* Error */
  14021. return 1;
  14022. }
  14023. /* OK */
  14024. return 0;
  14025. }
  14026. #if !defined(__ZEPHYR__)
  14027. static void
  14028. close_socket_gracefully(struct mg_connection *conn)
  14029. {
  14030. #if defined(_WIN32)
  14031. char buf[MG_BUF_LEN];
  14032. int n;
  14033. #endif
  14034. struct linger linger;
  14035. int error_code = 0;
  14036. int linger_timeout = -2;
  14037. socklen_t opt_len = sizeof(error_code);
  14038. if (!conn) {
  14039. return;
  14040. }
  14041. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14042. * "Note that enabling a nonzero timeout on a nonblocking socket
  14043. * is not recommended.", so set it to blocking now */
  14044. set_blocking_mode(conn->client.sock);
  14045. /* Send FIN to the client */
  14046. shutdown(conn->client.sock, SHUTDOWN_WR);
  14047. #if defined(_WIN32)
  14048. /* Read and discard pending incoming data. If we do not do that and
  14049. * close
  14050. * the socket, the data in the send buffer may be discarded. This
  14051. * behaviour is seen on Windows, when client keeps sending data
  14052. * when server decides to close the connection; then when client
  14053. * does recv() it gets no data back. */
  14054. do {
  14055. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14056. } while (n > 0);
  14057. #endif
  14058. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14059. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14060. }
  14061. /* Set linger option according to configuration */
  14062. if (linger_timeout >= 0) {
  14063. /* Set linger option to avoid socket hanging out after close. This
  14064. * prevent ephemeral port exhaust problem under high QPS. */
  14065. linger.l_onoff = 1;
  14066. #if defined(_MSC_VER)
  14067. #pragma warning(push)
  14068. #pragma warning(disable : 4244)
  14069. #endif
  14070. #if defined(GCC_DIAGNOSTIC)
  14071. #pragma GCC diagnostic push
  14072. #pragma GCC diagnostic ignored "-Wconversion"
  14073. #endif
  14074. /* Data type of linger structure elements may differ,
  14075. * so we don't know what cast we need here.
  14076. * Disable type conversion warnings. */
  14077. linger.l_linger = (linger_timeout + 999) / 1000;
  14078. #if defined(GCC_DIAGNOSTIC)
  14079. #pragma GCC diagnostic pop
  14080. #endif
  14081. #if defined(_MSC_VER)
  14082. #pragma warning(pop)
  14083. #endif
  14084. } else {
  14085. linger.l_onoff = 0;
  14086. linger.l_linger = 0;
  14087. }
  14088. if (linger_timeout < -1) {
  14089. /* Default: don't configure any linger */
  14090. } else if (getsockopt(conn->client.sock,
  14091. SOL_SOCKET,
  14092. SO_ERROR,
  14093. #if defined(_WIN32) /* WinSock uses different data type here */
  14094. (char *)&error_code,
  14095. #else
  14096. &error_code,
  14097. #endif
  14098. &opt_len)
  14099. != 0) {
  14100. /* Cannot determine if socket is already closed. This should
  14101. * not occur and never did in a test. Log an error message
  14102. * and continue. */
  14103. mg_cry_internal(conn,
  14104. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14105. __func__,
  14106. strerror(ERRNO));
  14107. #if defined(_WIN32)
  14108. } else if (error_code == WSAECONNRESET) {
  14109. #else
  14110. } else if (error_code == ECONNRESET) {
  14111. #endif
  14112. /* Socket already closed by client/peer, close socket without linger
  14113. */
  14114. } else {
  14115. /* Set linger timeout */
  14116. if (setsockopt(conn->client.sock,
  14117. SOL_SOCKET,
  14118. SO_LINGER,
  14119. (char *)&linger,
  14120. sizeof(linger))
  14121. != 0) {
  14122. mg_cry_internal(
  14123. conn,
  14124. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14125. __func__,
  14126. linger.l_onoff,
  14127. linger.l_linger,
  14128. strerror(ERRNO));
  14129. }
  14130. }
  14131. /* Now we know that our FIN is ACK-ed, safe to close */
  14132. closesocket(conn->client.sock);
  14133. conn->client.sock = INVALID_SOCKET;
  14134. }
  14135. #endif
  14136. static void
  14137. close_connection(struct mg_connection *conn)
  14138. {
  14139. #if defined(USE_SERVER_STATS)
  14140. conn->conn_state = 6; /* to close */
  14141. #endif
  14142. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14143. if (conn->lua_websocket_state) {
  14144. lua_websocket_close(conn, conn->lua_websocket_state);
  14145. conn->lua_websocket_state = NULL;
  14146. }
  14147. #endif
  14148. mg_lock_connection(conn);
  14149. /* Set close flag, so keep-alive loops will stop */
  14150. conn->must_close = 1;
  14151. /* call the connection_close callback if assigned */
  14152. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14153. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14154. conn->phys_ctx->callbacks.connection_close(conn);
  14155. }
  14156. }
  14157. /* Reset user data, after close callback is called.
  14158. * Do not reuse it. If the user needs a destructor,
  14159. * it must be done in the connection_close callback. */
  14160. mg_set_user_connection_data(conn, NULL);
  14161. #if defined(USE_SERVER_STATS)
  14162. conn->conn_state = 7; /* closing */
  14163. #endif
  14164. #if !defined(NO_SSL)
  14165. if (conn->ssl != NULL) {
  14166. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14167. */
  14168. SSL_shutdown(conn->ssl);
  14169. SSL_free(conn->ssl);
  14170. OPENSSL_REMOVE_THREAD_STATE();
  14171. conn->ssl = NULL;
  14172. }
  14173. #endif
  14174. if (conn->client.sock != INVALID_SOCKET) {
  14175. #if defined(__ZEPHYR__)
  14176. closesocket(conn->client.sock);
  14177. #else
  14178. close_socket_gracefully(conn);
  14179. #endif
  14180. conn->client.sock = INVALID_SOCKET;
  14181. }
  14182. if (conn->host) {
  14183. mg_free((void *)conn->host);
  14184. conn->host = NULL;
  14185. }
  14186. mg_unlock_connection(conn);
  14187. #if defined(USE_SERVER_STATS)
  14188. conn->conn_state = 8; /* closed */
  14189. #endif
  14190. }
  14191. void
  14192. mg_close_connection(struct mg_connection *conn)
  14193. {
  14194. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14195. return;
  14196. }
  14197. #if defined(USE_WEBSOCKET)
  14198. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14199. if (conn->in_websocket_handling) {
  14200. /* Set close flag, so the server thread can exit. */
  14201. conn->must_close = 1;
  14202. return;
  14203. }
  14204. }
  14205. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14206. unsigned int i;
  14207. /* client context: loops must end */
  14208. conn->phys_ctx->stop_flag = 1;
  14209. conn->must_close = 1;
  14210. /* We need to get the client thread out of the select/recv call
  14211. * here. */
  14212. /* Since we use a sleep quantum of some seconds to check for recv
  14213. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14214. /* join worker thread */
  14215. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14216. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14217. }
  14218. }
  14219. #endif /* defined(USE_WEBSOCKET) */
  14220. close_connection(conn);
  14221. #if !defined(NO_SSL)
  14222. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14223. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14224. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14225. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14226. }
  14227. #endif
  14228. #if defined(USE_WEBSOCKET)
  14229. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14230. mg_free(conn->phys_ctx->worker_threadids);
  14231. (void)pthread_mutex_destroy(&conn->mutex);
  14232. mg_free(conn);
  14233. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14234. mg_free(conn);
  14235. }
  14236. #else
  14237. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14238. mg_free(conn);
  14239. }
  14240. #endif /* defined(USE_WEBSOCKET) */
  14241. }
  14242. static struct mg_connection *
  14243. mg_connect_client_impl(const struct mg_client_options *client_options,
  14244. int use_ssl,
  14245. char *ebuf,
  14246. size_t ebuf_len)
  14247. {
  14248. struct mg_connection *conn = NULL;
  14249. SOCKET sock;
  14250. union usa sa;
  14251. struct sockaddr *psa;
  14252. socklen_t len;
  14253. unsigned max_req_size =
  14254. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14255. /* Size of structures, aligned to 8 bytes */
  14256. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14257. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14258. conn =
  14259. (struct mg_connection *)mg_calloc(1,
  14260. conn_size + ctx_size + max_req_size);
  14261. if (conn == NULL) {
  14262. mg_snprintf(NULL,
  14263. NULL, /* No truncation check for ebuf */
  14264. ebuf,
  14265. ebuf_len,
  14266. "calloc(): %s",
  14267. strerror(ERRNO));
  14268. return NULL;
  14269. }
  14270. #if defined(GCC_DIAGNOSTIC)
  14271. #pragma GCC diagnostic push
  14272. #pragma GCC diagnostic ignored "-Wcast-align"
  14273. #endif /* defined(GCC_DIAGNOSTIC) */
  14274. /* conn_size is aligned to 8 bytes */
  14275. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14276. #if defined(GCC_DIAGNOSTIC)
  14277. #pragma GCC diagnostic pop
  14278. #endif /* defined(GCC_DIAGNOSTIC) */
  14279. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14280. conn->buf_size = (int)max_req_size;
  14281. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14282. conn->dom_ctx = &(conn->phys_ctx->dd);
  14283. if (!connect_socket(conn->phys_ctx,
  14284. client_options->host,
  14285. client_options->port,
  14286. use_ssl,
  14287. ebuf,
  14288. ebuf_len,
  14289. &sock,
  14290. &sa)) {
  14291. /* ebuf is set by connect_socket,
  14292. * free all memory and return NULL; */
  14293. mg_free(conn);
  14294. return NULL;
  14295. }
  14296. #if !defined(NO_SSL)
  14297. #if defined(OPENSSL_API_1_1)
  14298. if (use_ssl
  14299. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14300. == NULL) {
  14301. mg_snprintf(NULL,
  14302. NULL, /* No truncation check for ebuf */
  14303. ebuf,
  14304. ebuf_len,
  14305. "SSL_CTX_new error: %s",
  14306. ssl_error());
  14307. closesocket(sock);
  14308. mg_free(conn);
  14309. return NULL;
  14310. }
  14311. #else
  14312. if (use_ssl
  14313. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14314. == NULL) {
  14315. mg_snprintf(NULL,
  14316. NULL, /* No truncation check for ebuf */
  14317. ebuf,
  14318. ebuf_len,
  14319. "SSL_CTX_new error: %s",
  14320. ssl_error());
  14321. closesocket(sock);
  14322. mg_free(conn);
  14323. return NULL;
  14324. }
  14325. #endif /* OPENSSL_API_1_1 */
  14326. #endif /* NO_SSL */
  14327. #if defined(USE_IPV6)
  14328. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14329. : sizeof(conn->client.rsa.sin6);
  14330. psa = (sa.sa.sa_family == AF_INET)
  14331. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14332. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14333. #else
  14334. len = sizeof(conn->client.rsa.sin);
  14335. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14336. #endif
  14337. conn->client.sock = sock;
  14338. conn->client.lsa = sa;
  14339. if (getsockname(sock, psa, &len) != 0) {
  14340. mg_cry_internal(conn,
  14341. "%s: getsockname() failed: %s",
  14342. __func__,
  14343. strerror(ERRNO));
  14344. }
  14345. conn->client.is_ssl = use_ssl ? 1 : 0;
  14346. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14347. mg_snprintf(NULL,
  14348. NULL, /* No truncation check for ebuf */
  14349. ebuf,
  14350. ebuf_len,
  14351. "Can not create mutex");
  14352. #if !defined(NO_SSL)
  14353. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14354. #endif
  14355. closesocket(sock);
  14356. mg_free(conn);
  14357. return NULL;
  14358. }
  14359. #if !defined(NO_SSL)
  14360. if (use_ssl) {
  14361. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14362. * SSL_CTX_set_verify call is needed to switch off server
  14363. * certificate checking, which is off by default in OpenSSL and
  14364. * on in yaSSL. */
  14365. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14366. * SSL_VERIFY_PEER, verify_ssl_server); */
  14367. if (client_options->client_cert) {
  14368. if (!ssl_use_pem_file(conn->phys_ctx,
  14369. conn->dom_ctx,
  14370. client_options->client_cert,
  14371. NULL)) {
  14372. mg_snprintf(NULL,
  14373. NULL, /* No truncation check for ebuf */
  14374. ebuf,
  14375. ebuf_len,
  14376. "Can not use SSL client certificate");
  14377. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14378. closesocket(sock);
  14379. mg_free(conn);
  14380. return NULL;
  14381. }
  14382. }
  14383. if (client_options->server_cert) {
  14384. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14385. client_options->server_cert,
  14386. NULL)
  14387. != 1) {
  14388. mg_cry_internal(conn,
  14389. "SSL_CTX_load_verify_locations error: %s ",
  14390. ssl_error());
  14391. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14392. closesocket(sock);
  14393. mg_free(conn);
  14394. return NULL;
  14395. }
  14396. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14397. } else {
  14398. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14399. }
  14400. if (!sslize(conn,
  14401. conn->dom_ctx->ssl_ctx,
  14402. SSL_connect,
  14403. &(conn->phys_ctx->stop_flag),
  14404. client_options)) {
  14405. mg_snprintf(NULL,
  14406. NULL, /* No truncation check for ebuf */
  14407. ebuf,
  14408. ebuf_len,
  14409. "SSL connection error");
  14410. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14411. closesocket(sock);
  14412. mg_free(conn);
  14413. return NULL;
  14414. }
  14415. }
  14416. #endif
  14417. return conn;
  14418. }
  14419. CIVETWEB_API struct mg_connection *
  14420. mg_connect_client_secure(const struct mg_client_options *client_options,
  14421. char *error_buffer,
  14422. size_t error_buffer_size)
  14423. {
  14424. return mg_connect_client_impl(client_options,
  14425. 1,
  14426. error_buffer,
  14427. error_buffer_size);
  14428. }
  14429. struct mg_connection *
  14430. mg_connect_client(const char *host,
  14431. int port,
  14432. int use_ssl,
  14433. char *error_buffer,
  14434. size_t error_buffer_size)
  14435. {
  14436. struct mg_client_options opts;
  14437. memset(&opts, 0, sizeof(opts));
  14438. opts.host = host;
  14439. opts.port = port;
  14440. return mg_connect_client_impl(&opts,
  14441. use_ssl,
  14442. error_buffer,
  14443. error_buffer_size);
  14444. }
  14445. static const struct {
  14446. const char *proto;
  14447. size_t proto_len;
  14448. unsigned default_port;
  14449. } abs_uri_protocols[] = {{"http://", 7, 80},
  14450. {"https://", 8, 443},
  14451. {"ws://", 5, 80},
  14452. {"wss://", 6, 443},
  14453. {NULL, 0, 0}};
  14454. /* Check if the uri is valid.
  14455. * return 0 for invalid uri,
  14456. * return 1 for *,
  14457. * return 2 for relative uri,
  14458. * return 3 for absolute uri without port,
  14459. * return 4 for absolute uri with port */
  14460. static int
  14461. get_uri_type(const char *uri)
  14462. {
  14463. int i;
  14464. const char *hostend, *portbegin;
  14465. char *portend;
  14466. unsigned long port;
  14467. /* According to the HTTP standard
  14468. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14469. * URI can be an asterisk (*) or should start with slash (relative uri),
  14470. * or it should start with the protocol (absolute uri). */
  14471. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14472. /* asterisk */
  14473. return 1;
  14474. }
  14475. /* Valid URIs according to RFC 3986
  14476. * (https://www.ietf.org/rfc/rfc3986.txt)
  14477. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14478. * and unreserved characters A-Z a-z 0-9 and -._~
  14479. * and % encoded symbols.
  14480. */
  14481. for (i = 0; uri[i] != 0; i++) {
  14482. if (uri[i] < 33) {
  14483. /* control characters and spaces are invalid */
  14484. return 0;
  14485. }
  14486. if (uri[i] > 126) {
  14487. /* non-ascii characters must be % encoded */
  14488. return 0;
  14489. } else {
  14490. switch (uri[i]) {
  14491. case '"': /* 34 */
  14492. case '<': /* 60 */
  14493. case '>': /* 62 */
  14494. case '\\': /* 92 */
  14495. case '^': /* 94 */
  14496. case '`': /* 96 */
  14497. case '{': /* 123 */
  14498. case '|': /* 124 */
  14499. case '}': /* 125 */
  14500. return 0;
  14501. default:
  14502. /* character is ok */
  14503. break;
  14504. }
  14505. }
  14506. }
  14507. /* A relative uri starts with a / character */
  14508. if (uri[0] == '/') {
  14509. /* relative uri */
  14510. return 2;
  14511. }
  14512. /* It could be an absolute uri: */
  14513. /* This function only checks if the uri is valid, not if it is
  14514. * addressing the current server. So civetweb can also be used
  14515. * as a proxy server. */
  14516. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14517. if (mg_strncasecmp(uri,
  14518. abs_uri_protocols[i].proto,
  14519. abs_uri_protocols[i].proto_len)
  14520. == 0) {
  14521. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14522. if (!hostend) {
  14523. return 0;
  14524. }
  14525. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14526. if (!portbegin) {
  14527. return 3;
  14528. }
  14529. port = strtoul(portbegin + 1, &portend, 10);
  14530. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14531. return 0;
  14532. }
  14533. return 4;
  14534. }
  14535. }
  14536. return 0;
  14537. }
  14538. /* Return NULL or the relative uri at the current server */
  14539. static const char *
  14540. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14541. {
  14542. const char *server_domain;
  14543. size_t server_domain_len;
  14544. size_t request_domain_len = 0;
  14545. unsigned long port = 0;
  14546. int i, auth_domain_check_enabled;
  14547. const char *hostbegin = NULL;
  14548. const char *hostend = NULL;
  14549. const char *portbegin;
  14550. char *portend;
  14551. auth_domain_check_enabled =
  14552. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14553. /* DNS is case insensitive, so use case insensitive string compare here
  14554. */
  14555. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14556. if (mg_strncasecmp(uri,
  14557. abs_uri_protocols[i].proto,
  14558. abs_uri_protocols[i].proto_len)
  14559. == 0) {
  14560. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14561. hostend = strchr(hostbegin, '/');
  14562. if (!hostend) {
  14563. return 0;
  14564. }
  14565. portbegin = strchr(hostbegin, ':');
  14566. if ((!portbegin) || (portbegin > hostend)) {
  14567. port = abs_uri_protocols[i].default_port;
  14568. request_domain_len = (size_t)(hostend - hostbegin);
  14569. } else {
  14570. port = strtoul(portbegin + 1, &portend, 10);
  14571. if ((portend != hostend) || (port <= 0)
  14572. || !is_valid_port(port)) {
  14573. return 0;
  14574. }
  14575. request_domain_len = (size_t)(portbegin - hostbegin);
  14576. }
  14577. /* protocol found, port set */
  14578. break;
  14579. }
  14580. }
  14581. if (!port) {
  14582. /* port remains 0 if the protocol is not found */
  14583. return 0;
  14584. }
  14585. /* Check if the request is directed to a different server. */
  14586. /* First check if the port is the same (IPv4 and IPv6). */
  14587. #if defined(USE_IPV6)
  14588. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14589. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14590. /* Request is directed to a different port */
  14591. return 0;
  14592. }
  14593. } else
  14594. #endif
  14595. {
  14596. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14597. /* Request is directed to a different port */
  14598. return 0;
  14599. }
  14600. }
  14601. /* Finally check if the server corresponds to the authentication
  14602. * domain of the server (the server domain).
  14603. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14604. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14605. * but do not allow substrings (like
  14606. * http://notmydomain.com/path/file.ext
  14607. * or http://mydomain.com.fake/path/file.ext).
  14608. */
  14609. if (auth_domain_check_enabled) {
  14610. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14611. server_domain_len = strlen(server_domain);
  14612. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14613. return 0;
  14614. }
  14615. if ((request_domain_len == server_domain_len)
  14616. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14617. /* Request is directed to this server - full name match. */
  14618. } else {
  14619. if (request_domain_len < (server_domain_len + 2)) {
  14620. /* Request is directed to another server: The server name
  14621. * is longer than the request name.
  14622. * Drop this case here to avoid overflows in the
  14623. * following checks. */
  14624. return 0;
  14625. }
  14626. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14627. /* Request is directed to another server: It could be a
  14628. * substring
  14629. * like notmyserver.com */
  14630. return 0;
  14631. }
  14632. if (0
  14633. != memcmp(server_domain,
  14634. hostbegin + request_domain_len - server_domain_len,
  14635. server_domain_len)) {
  14636. /* Request is directed to another server:
  14637. * The server name is different. */
  14638. return 0;
  14639. }
  14640. }
  14641. }
  14642. return hostend;
  14643. }
  14644. static int
  14645. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14646. {
  14647. if (ebuf_len > 0) {
  14648. ebuf[0] = '\0';
  14649. }
  14650. *err = 0;
  14651. reset_per_request_attributes(conn);
  14652. if (!conn) {
  14653. mg_snprintf(conn,
  14654. NULL, /* No truncation check for ebuf */
  14655. ebuf,
  14656. ebuf_len,
  14657. "%s",
  14658. "Internal error");
  14659. *err = 500;
  14660. return 0;
  14661. }
  14662. /* Set the time the request was received. This value should be used for
  14663. * timeouts. */
  14664. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14665. conn->request_len =
  14666. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14667. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14668. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14669. mg_snprintf(conn,
  14670. NULL, /* No truncation check for ebuf */
  14671. ebuf,
  14672. ebuf_len,
  14673. "%s",
  14674. "Invalid message size");
  14675. *err = 500;
  14676. return 0;
  14677. }
  14678. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14679. mg_snprintf(conn,
  14680. NULL, /* No truncation check for ebuf */
  14681. ebuf,
  14682. ebuf_len,
  14683. "%s",
  14684. "Message too large");
  14685. *err = 413;
  14686. return 0;
  14687. }
  14688. if (conn->request_len <= 0) {
  14689. if (conn->data_len > 0) {
  14690. mg_snprintf(conn,
  14691. NULL, /* No truncation check for ebuf */
  14692. ebuf,
  14693. ebuf_len,
  14694. "%s",
  14695. "Malformed message");
  14696. *err = 400;
  14697. } else {
  14698. /* Server did not recv anything -> just close the connection */
  14699. conn->must_close = 1;
  14700. mg_snprintf(conn,
  14701. NULL, /* No truncation check for ebuf */
  14702. ebuf,
  14703. ebuf_len,
  14704. "%s",
  14705. "No data received");
  14706. *err = 0;
  14707. }
  14708. return 0;
  14709. }
  14710. return 1;
  14711. }
  14712. static int
  14713. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14714. {
  14715. const char *cl;
  14716. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14717. return 0;
  14718. }
  14719. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14720. <= 0) {
  14721. mg_snprintf(conn,
  14722. NULL, /* No truncation check for ebuf */
  14723. ebuf,
  14724. ebuf_len,
  14725. "%s",
  14726. "Bad request");
  14727. *err = 400;
  14728. return 0;
  14729. }
  14730. /* Message is a valid request */
  14731. /* Is there a "host" ? */
  14732. if (conn->host != NULL) {
  14733. mg_free((void *)conn->host);
  14734. }
  14735. conn->host = alloc_get_host(conn);
  14736. if (!conn->host) {
  14737. mg_snprintf(conn,
  14738. NULL, /* No truncation check for ebuf */
  14739. ebuf,
  14740. ebuf_len,
  14741. "%s",
  14742. "Bad request: Host mismatch");
  14743. *err = 400;
  14744. return 0;
  14745. }
  14746. if (((cl = get_header(conn->request_info.http_headers,
  14747. conn->request_info.num_headers,
  14748. "Transfer-Encoding"))
  14749. != NULL)
  14750. && mg_strcasecmp(cl, "identity")) {
  14751. if (mg_strcasecmp(cl, "chunked")) {
  14752. mg_snprintf(conn,
  14753. NULL, /* No truncation check for ebuf */
  14754. ebuf,
  14755. ebuf_len,
  14756. "%s",
  14757. "Bad request");
  14758. *err = 400;
  14759. return 0;
  14760. }
  14761. conn->is_chunked = 1;
  14762. conn->content_len = 0; /* not yet read */
  14763. } else if ((cl = get_header(conn->request_info.http_headers,
  14764. conn->request_info.num_headers,
  14765. "Content-Length"))
  14766. != NULL) {
  14767. /* Request has content length set */
  14768. char *endptr = NULL;
  14769. conn->content_len = strtoll(cl, &endptr, 10);
  14770. if ((endptr == cl) || (conn->content_len < 0)) {
  14771. mg_snprintf(conn,
  14772. NULL, /* No truncation check for ebuf */
  14773. ebuf,
  14774. ebuf_len,
  14775. "%s",
  14776. "Bad request");
  14777. *err = 411;
  14778. return 0;
  14779. }
  14780. /* Publish the content length back to the request info. */
  14781. conn->request_info.content_length = conn->content_len;
  14782. } else {
  14783. /* There is no exception, see RFC7230. */
  14784. conn->content_len = 0;
  14785. }
  14786. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14787. return 1;
  14788. }
  14789. /* conn is assumed to be valid in this internal function */
  14790. static int
  14791. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14792. {
  14793. const char *cl;
  14794. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14795. return 0;
  14796. }
  14797. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14798. <= 0) {
  14799. mg_snprintf(conn,
  14800. NULL, /* No truncation check for ebuf */
  14801. ebuf,
  14802. ebuf_len,
  14803. "%s",
  14804. "Bad response");
  14805. *err = 400;
  14806. return 0;
  14807. }
  14808. /* Message is a valid response */
  14809. if (((cl = get_header(conn->response_info.http_headers,
  14810. conn->response_info.num_headers,
  14811. "Transfer-Encoding"))
  14812. != NULL)
  14813. && mg_strcasecmp(cl, "identity")) {
  14814. if (mg_strcasecmp(cl, "chunked")) {
  14815. mg_snprintf(conn,
  14816. NULL, /* No truncation check for ebuf */
  14817. ebuf,
  14818. ebuf_len,
  14819. "%s",
  14820. "Bad request");
  14821. *err = 400;
  14822. return 0;
  14823. }
  14824. conn->is_chunked = 1;
  14825. conn->content_len = 0; /* not yet read */
  14826. } else if ((cl = get_header(conn->response_info.http_headers,
  14827. conn->response_info.num_headers,
  14828. "Content-Length"))
  14829. != NULL) {
  14830. char *endptr = NULL;
  14831. conn->content_len = strtoll(cl, &endptr, 10);
  14832. if ((endptr == cl) || (conn->content_len < 0)) {
  14833. mg_snprintf(conn,
  14834. NULL, /* No truncation check for ebuf */
  14835. ebuf,
  14836. ebuf_len,
  14837. "%s",
  14838. "Bad request");
  14839. *err = 411;
  14840. return 0;
  14841. }
  14842. /* Publish the content length back to the response info. */
  14843. conn->response_info.content_length = conn->content_len;
  14844. /* TODO: check if it is still used in response_info */
  14845. conn->request_info.content_length = conn->content_len;
  14846. /* TODO: we should also consider HEAD method */
  14847. if (conn->response_info.status_code == 304) {
  14848. conn->content_len = 0;
  14849. }
  14850. } else {
  14851. /* TODO: we should also consider HEAD method */
  14852. if (((conn->response_info.status_code >= 100)
  14853. && (conn->response_info.status_code <= 199))
  14854. || (conn->response_info.status_code == 204)
  14855. || (conn->response_info.status_code == 304)) {
  14856. conn->content_len = 0;
  14857. } else {
  14858. conn->content_len = -1; /* unknown content length */
  14859. }
  14860. }
  14861. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14862. return 1;
  14863. }
  14864. int
  14865. mg_get_response(struct mg_connection *conn,
  14866. char *ebuf,
  14867. size_t ebuf_len,
  14868. int timeout)
  14869. {
  14870. int err, ret;
  14871. char txt[32]; /* will not overflow */
  14872. char *save_timeout;
  14873. char *new_timeout;
  14874. if (ebuf_len > 0) {
  14875. ebuf[0] = '\0';
  14876. }
  14877. if (!conn) {
  14878. mg_snprintf(conn,
  14879. NULL, /* No truncation check for ebuf */
  14880. ebuf,
  14881. ebuf_len,
  14882. "%s",
  14883. "Parameter error");
  14884. return -1;
  14885. }
  14886. /* Reset the previous responses */
  14887. conn->data_len = 0;
  14888. /* Implementation of API function for HTTP clients */
  14889. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14890. if (timeout >= 0) {
  14891. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14892. new_timeout = txt;
  14893. } else {
  14894. new_timeout = NULL;
  14895. }
  14896. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14897. ret = get_response(conn, ebuf, ebuf_len, &err);
  14898. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14899. #if defined(MG_LEGACY_INTERFACE)
  14900. /* TODO: 1) uri is deprecated;
  14901. * 2) here, ri.uri is the http response code */
  14902. conn->request_info.uri = conn->request_info.request_uri;
  14903. #endif
  14904. conn->request_info.local_uri = conn->request_info.request_uri;
  14905. /* TODO (mid): Define proper return values - maybe return length?
  14906. * For the first test use <0 for error and >0 for OK */
  14907. return (ret == 0) ? -1 : +1;
  14908. }
  14909. struct mg_connection *
  14910. mg_download(const char *host,
  14911. int port,
  14912. int use_ssl,
  14913. char *ebuf,
  14914. size_t ebuf_len,
  14915. const char *fmt,
  14916. ...)
  14917. {
  14918. struct mg_connection *conn;
  14919. va_list ap;
  14920. int i;
  14921. int reqerr;
  14922. if (ebuf_len > 0) {
  14923. ebuf[0] = '\0';
  14924. }
  14925. va_start(ap, fmt);
  14926. /* open a connection */
  14927. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14928. if (conn != NULL) {
  14929. i = mg_vprintf(conn, fmt, ap);
  14930. if (i <= 0) {
  14931. mg_snprintf(conn,
  14932. NULL, /* No truncation check for ebuf */
  14933. ebuf,
  14934. ebuf_len,
  14935. "%s",
  14936. "Error sending request");
  14937. } else {
  14938. /* make sure the buffer is clear */
  14939. conn->data_len = 0;
  14940. get_response(conn, ebuf, ebuf_len, &reqerr);
  14941. #if defined(MG_LEGACY_INTERFACE)
  14942. /* TODO: 1) uri is deprecated;
  14943. * 2) here, ri.uri is the http response code */
  14944. conn->request_info.uri = conn->request_info.request_uri;
  14945. #endif
  14946. conn->request_info.local_uri = conn->request_info.request_uri;
  14947. }
  14948. }
  14949. /* if an error occurred, close the connection */
  14950. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14951. mg_close_connection(conn);
  14952. conn = NULL;
  14953. }
  14954. va_end(ap);
  14955. return conn;
  14956. }
  14957. struct websocket_client_thread_data {
  14958. struct mg_connection *conn;
  14959. mg_websocket_data_handler data_handler;
  14960. mg_websocket_close_handler close_handler;
  14961. void *callback_data;
  14962. };
  14963. #if defined(USE_WEBSOCKET)
  14964. #if defined(_WIN32)
  14965. static unsigned __stdcall websocket_client_thread(void *data)
  14966. #else
  14967. static void *
  14968. websocket_client_thread(void *data)
  14969. #endif
  14970. {
  14971. struct websocket_client_thread_data *cdata =
  14972. (struct websocket_client_thread_data *)data;
  14973. void *user_thread_ptr = NULL;
  14974. #if !defined(_WIN32)
  14975. struct sigaction sa;
  14976. /* Ignore SIGPIPE */
  14977. memset(&sa, 0, sizeof(sa));
  14978. sa.sa_handler = SIG_IGN;
  14979. sigaction(SIGPIPE, &sa, NULL);
  14980. #endif
  14981. mg_set_thread_name("ws-clnt");
  14982. if (cdata->conn->phys_ctx) {
  14983. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14984. /* 3 indicates a websocket client thread */
  14985. /* TODO: check if conn->phys_ctx can be set */
  14986. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  14987. cdata->conn->phys_ctx, 3);
  14988. }
  14989. }
  14990. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14991. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14992. if (cdata->close_handler != NULL) {
  14993. cdata->close_handler(cdata->conn, cdata->callback_data);
  14994. }
  14995. /* The websocket_client context has only this thread. If it runs out,
  14996. set the stop_flag to 2 (= "stopped"). */
  14997. cdata->conn->phys_ctx->stop_flag = 2;
  14998. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  14999. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  15000. 3,
  15001. user_thread_ptr);
  15002. }
  15003. mg_free((void *)cdata);
  15004. #if defined(_WIN32)
  15005. return 0;
  15006. #else
  15007. return NULL;
  15008. #endif
  15009. }
  15010. #endif
  15011. struct mg_connection *
  15012. mg_connect_websocket_client(const char *host,
  15013. int port,
  15014. int use_ssl,
  15015. char *error_buffer,
  15016. size_t error_buffer_size,
  15017. const char *path,
  15018. const char *origin,
  15019. mg_websocket_data_handler data_func,
  15020. mg_websocket_close_handler close_func,
  15021. void *user_data)
  15022. {
  15023. struct mg_connection *conn = NULL;
  15024. #if defined(USE_WEBSOCKET)
  15025. struct websocket_client_thread_data *thread_data;
  15026. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15027. static const char *handshake_req;
  15028. if (origin != NULL) {
  15029. handshake_req = "GET %s HTTP/1.1\r\n"
  15030. "Host: %s\r\n"
  15031. "Upgrade: websocket\r\n"
  15032. "Connection: Upgrade\r\n"
  15033. "Sec-WebSocket-Key: %s\r\n"
  15034. "Sec-WebSocket-Version: 13\r\n"
  15035. "Origin: %s\r\n"
  15036. "\r\n";
  15037. } else {
  15038. handshake_req = "GET %s HTTP/1.1\r\n"
  15039. "Host: %s\r\n"
  15040. "Upgrade: websocket\r\n"
  15041. "Connection: Upgrade\r\n"
  15042. "Sec-WebSocket-Key: %s\r\n"
  15043. "Sec-WebSocket-Version: 13\r\n"
  15044. "\r\n";
  15045. }
  15046. #if defined(__clang__)
  15047. #pragma clang diagnostic push
  15048. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15049. #endif
  15050. /* Establish the client connection and request upgrade */
  15051. conn = mg_download(host,
  15052. port,
  15053. use_ssl,
  15054. error_buffer,
  15055. error_buffer_size,
  15056. handshake_req,
  15057. path,
  15058. host,
  15059. magic,
  15060. origin);
  15061. #if defined(__clang__)
  15062. #pragma clang diagnostic pop
  15063. #endif
  15064. /* Connection object will be null if something goes wrong */
  15065. if (conn == NULL) {
  15066. if (!*error_buffer) {
  15067. /* There should be already an error message */
  15068. mg_snprintf(conn,
  15069. NULL, /* No truncation check for ebuf */
  15070. error_buffer,
  15071. error_buffer_size,
  15072. "Unexpected error");
  15073. }
  15074. return NULL;
  15075. }
  15076. if (conn->response_info.status_code != 101) {
  15077. /* We sent an "upgrade" request. For a correct websocket
  15078. * protocol handshake, we expect a "101 Continue" response.
  15079. * Otherwise it is a protocol violation. Maybe the HTTP
  15080. * Server does not know websockets. */
  15081. if (!*error_buffer) {
  15082. /* set an error, if not yet set */
  15083. mg_snprintf(conn,
  15084. NULL, /* No truncation check for ebuf */
  15085. error_buffer,
  15086. error_buffer_size,
  15087. "Unexpected server reply");
  15088. }
  15089. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15090. mg_close_connection(conn);
  15091. return NULL;
  15092. }
  15093. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15094. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15095. if (!thread_data) {
  15096. DEBUG_TRACE("%s\r\n", "Out of memory");
  15097. mg_close_connection(conn);
  15098. return NULL;
  15099. }
  15100. thread_data->conn = conn;
  15101. thread_data->data_handler = data_func;
  15102. thread_data->close_handler = close_func;
  15103. thread_data->callback_data = user_data;
  15104. conn->phys_ctx->worker_threadids =
  15105. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15106. if (!conn->phys_ctx->worker_threadids) {
  15107. DEBUG_TRACE("%s\r\n", "Out of memory");
  15108. mg_free(thread_data);
  15109. mg_close_connection(conn);
  15110. return NULL;
  15111. }
  15112. /* Now upgrade to ws/wss client context */
  15113. conn->phys_ctx->user_data = user_data;
  15114. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15115. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15116. /* Start a thread to read the websocket client connection
  15117. * This thread will automatically stop when mg_disconnect is
  15118. * called on the client connection */
  15119. if (mg_start_thread_with_id(websocket_client_thread,
  15120. thread_data,
  15121. conn->phys_ctx->worker_threadids)
  15122. != 0) {
  15123. conn->phys_ctx->cfg_worker_threads = 0;
  15124. mg_free(thread_data);
  15125. mg_close_connection(conn);
  15126. conn = NULL;
  15127. DEBUG_TRACE("%s",
  15128. "Websocket client connect thread could not be started\r\n");
  15129. }
  15130. #else
  15131. /* Appease "unused parameter" warnings */
  15132. (void)host;
  15133. (void)port;
  15134. (void)use_ssl;
  15135. (void)error_buffer;
  15136. (void)error_buffer_size;
  15137. (void)path;
  15138. (void)origin;
  15139. (void)user_data;
  15140. (void)data_func;
  15141. (void)close_func;
  15142. #endif
  15143. return conn;
  15144. }
  15145. /* Prepare connection data structure */
  15146. static void
  15147. init_connection(struct mg_connection *conn)
  15148. {
  15149. /* Is keep alive allowed by the server */
  15150. int keep_alive_enabled =
  15151. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15152. if (!keep_alive_enabled) {
  15153. conn->must_close = 1;
  15154. }
  15155. /* Important: on new connection, reset the receiving buffer. Credit
  15156. * goes to crule42. */
  15157. conn->data_len = 0;
  15158. conn->handled_requests = 0;
  15159. mg_set_user_connection_data(conn, NULL);
  15160. #if defined(USE_SERVER_STATS)
  15161. conn->conn_state = 2; /* init */
  15162. #endif
  15163. /* call the init_connection callback if assigned */
  15164. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15165. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15166. void *conn_data = NULL;
  15167. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15168. mg_set_user_connection_data(conn, conn_data);
  15169. }
  15170. }
  15171. }
  15172. /* Process a connection - may handle multiple requests
  15173. * using the same connection.
  15174. * Must be called with a valid connection (conn and
  15175. * conn->phys_ctx must be valid).
  15176. */
  15177. static void
  15178. process_new_connection(struct mg_connection *conn)
  15179. {
  15180. struct mg_request_info *ri = &conn->request_info;
  15181. int keep_alive, discard_len;
  15182. char ebuf[100];
  15183. const char *hostend;
  15184. int reqerr, uri_type;
  15185. #if defined(USE_SERVER_STATS)
  15186. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15187. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15188. if (mcon > (conn->phys_ctx->max_connections)) {
  15189. /* could use atomic compare exchange, but this
  15190. * seems overkill for statistics data */
  15191. conn->phys_ctx->max_connections = mcon;
  15192. }
  15193. #endif
  15194. init_connection(conn);
  15195. DEBUG_TRACE("Start processing connection from %s",
  15196. conn->request_info.remote_addr);
  15197. /* Loop over multiple requests sent using the same connection
  15198. * (while "keep alive"). */
  15199. do {
  15200. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15201. conn->handled_requests + 1);
  15202. #if defined(USE_SERVER_STATS)
  15203. conn->conn_state = 3; /* ready */
  15204. #endif
  15205. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15206. /* The request sent by the client could not be understood by
  15207. * the server, or it was incomplete or a timeout. Send an
  15208. * error message and close the connection. */
  15209. if (reqerr > 0) {
  15210. DEBUG_ASSERT(ebuf[0] != '\0');
  15211. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15212. }
  15213. } else if (strcmp(ri->http_version, "1.0")
  15214. && strcmp(ri->http_version, "1.1")) {
  15215. mg_snprintf(conn,
  15216. NULL, /* No truncation check for ebuf */
  15217. ebuf,
  15218. sizeof(ebuf),
  15219. "Bad HTTP version: [%s]",
  15220. ri->http_version);
  15221. mg_send_http_error(conn, 505, "%s", ebuf);
  15222. }
  15223. if (ebuf[0] == '\0') {
  15224. uri_type = get_uri_type(conn->request_info.request_uri);
  15225. switch (uri_type) {
  15226. case 1:
  15227. /* Asterisk */
  15228. conn->request_info.local_uri = NULL;
  15229. break;
  15230. case 2:
  15231. /* relative uri */
  15232. conn->request_info.local_uri = conn->request_info.request_uri;
  15233. break;
  15234. case 3:
  15235. case 4:
  15236. /* absolute uri (with/without port) */
  15237. hostend = get_rel_url_at_current_server(
  15238. conn->request_info.request_uri, conn);
  15239. if (hostend) {
  15240. conn->request_info.local_uri = hostend;
  15241. } else {
  15242. conn->request_info.local_uri = NULL;
  15243. }
  15244. break;
  15245. default:
  15246. mg_snprintf(conn,
  15247. NULL, /* No truncation check for ebuf */
  15248. ebuf,
  15249. sizeof(ebuf),
  15250. "Invalid URI");
  15251. mg_send_http_error(conn, 400, "%s", ebuf);
  15252. conn->request_info.local_uri = NULL;
  15253. break;
  15254. }
  15255. #if defined(MG_LEGACY_INTERFACE)
  15256. /* Legacy before split into local_uri and request_uri */
  15257. conn->request_info.uri = conn->request_info.local_uri;
  15258. #endif
  15259. }
  15260. DEBUG_TRACE("http: %s, error: %s",
  15261. (ri->http_version ? ri->http_version : "none"),
  15262. (ebuf[0] ? ebuf : "none"));
  15263. if (ebuf[0] == '\0') {
  15264. if (conn->request_info.local_uri) {
  15265. /* handle request to local server */
  15266. #if defined(USE_SERVER_STATS)
  15267. conn->conn_state = 4; /* processing */
  15268. #endif
  15269. handle_request(conn);
  15270. #if defined(USE_SERVER_STATS)
  15271. conn->conn_state = 5; /* processed */
  15272. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15273. conn->consumed_content);
  15274. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15275. conn->num_bytes_sent);
  15276. #endif
  15277. DEBUG_TRACE("%s", "handle_request done");
  15278. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15279. conn->phys_ctx->callbacks.end_request(conn,
  15280. conn->status_code);
  15281. DEBUG_TRACE("%s", "end_request callback done");
  15282. }
  15283. log_access(conn);
  15284. } else {
  15285. /* TODO: handle non-local request (PROXY) */
  15286. conn->must_close = 1;
  15287. }
  15288. } else {
  15289. conn->must_close = 1;
  15290. }
  15291. if (ri->remote_user != NULL) {
  15292. mg_free((void *)ri->remote_user);
  15293. /* Important! When having connections with and without auth
  15294. * would cause double free and then crash */
  15295. ri->remote_user = NULL;
  15296. }
  15297. /* NOTE(lsm): order is important here. should_keep_alive() call
  15298. * is using parsed request, which will be invalid after
  15299. * memmove's below.
  15300. * Therefore, memorize should_keep_alive() result now for later
  15301. * use in loop exit condition. */
  15302. /* Enable it only if this request is completely discardable. */
  15303. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15304. && (conn->content_len >= 0) && (conn->request_len > 0)
  15305. && ((conn->is_chunked == 4)
  15306. || (!conn->is_chunked
  15307. && ((conn->consumed_content == conn->content_len)
  15308. || ((conn->request_len + conn->content_len)
  15309. <= conn->data_len))));
  15310. if (keep_alive) {
  15311. /* Discard all buffered data for this request */
  15312. discard_len =
  15313. ((conn->request_len + conn->content_len) < conn->data_len)
  15314. ? (int)(conn->request_len + conn->content_len)
  15315. : conn->data_len;
  15316. conn->data_len -= discard_len;
  15317. if (conn->data_len > 0) {
  15318. DEBUG_TRACE("discard_len = %d", discard_len);
  15319. memmove(conn->buf,
  15320. conn->buf + discard_len,
  15321. (size_t)conn->data_len);
  15322. }
  15323. }
  15324. DEBUG_ASSERT(conn->data_len >= 0);
  15325. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15326. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15327. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15328. (long int)conn->data_len,
  15329. (long int)conn->buf_size);
  15330. break;
  15331. }
  15332. conn->handled_requests++;
  15333. } while (keep_alive);
  15334. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15335. conn->request_info.remote_addr,
  15336. difftime(time(NULL), conn->conn_birth_time));
  15337. close_connection(conn);
  15338. #if defined(USE_SERVER_STATS)
  15339. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15340. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15341. #endif
  15342. }
  15343. #if defined(ALTERNATIVE_QUEUE)
  15344. static void
  15345. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15346. {
  15347. unsigned int i;
  15348. while (!ctx->stop_flag) {
  15349. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15350. /* find a free worker slot and signal it */
  15351. if (ctx->client_socks[i].in_use == 2) {
  15352. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15353. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15354. ctx->client_socks[i] = *sp;
  15355. ctx->client_socks[i].in_use = 1;
  15356. /* socket has been moved to the consumer */
  15357. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15358. (void)event_signal(ctx->client_wait_events[i]);
  15359. return;
  15360. }
  15361. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15362. }
  15363. }
  15364. /* queue is full */
  15365. mg_sleep(1);
  15366. }
  15367. /* must consume */
  15368. set_blocking_mode(sp->sock);
  15369. closesocket(sp->sock);
  15370. }
  15371. static int
  15372. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15373. {
  15374. DEBUG_TRACE("%s", "going idle");
  15375. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15376. ctx->client_socks[thread_index].in_use = 2;
  15377. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15378. event_wait(ctx->client_wait_events[thread_index]);
  15379. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15380. *sp = ctx->client_socks[thread_index];
  15381. if (ctx->stop_flag) {
  15382. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15383. if (sp->in_use == 1) {
  15384. /* must consume */
  15385. set_blocking_mode(sp->sock);
  15386. closesocket(sp->sock);
  15387. }
  15388. return 0;
  15389. }
  15390. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15391. if (sp->in_use == 1) {
  15392. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15393. return 1;
  15394. }
  15395. /* must not reach here */
  15396. DEBUG_ASSERT(0);
  15397. return 0;
  15398. }
  15399. #else /* ALTERNATIVE_QUEUE */
  15400. /* Worker threads take accepted socket from the queue */
  15401. static int
  15402. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15403. {
  15404. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15405. (void)thread_index;
  15406. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15407. DEBUG_TRACE("%s", "going idle");
  15408. /* If the queue is empty, wait. We're idle at this point. */
  15409. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15410. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15411. }
  15412. /* If we're stopping, sq_head may be equal to sq_tail. */
  15413. if (ctx->sq_head > ctx->sq_tail) {
  15414. /* Copy socket from the queue and increment tail */
  15415. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15416. ctx->sq_tail++;
  15417. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15418. /* Wrap pointers if needed */
  15419. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15420. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15421. ctx->sq_head -= QUEUE_SIZE(ctx);
  15422. }
  15423. }
  15424. (void)pthread_cond_signal(&ctx->sq_empty);
  15425. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15426. return !ctx->stop_flag;
  15427. #undef QUEUE_SIZE
  15428. }
  15429. /* Master thread adds accepted socket to a queue */
  15430. static void
  15431. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15432. {
  15433. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15434. if (!ctx) {
  15435. return;
  15436. }
  15437. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15438. /* If the queue is full, wait */
  15439. while ((ctx->stop_flag == 0)
  15440. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15441. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15442. }
  15443. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15444. /* Copy socket to the queue and increment head */
  15445. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15446. ctx->sq_head++;
  15447. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15448. }
  15449. (void)pthread_cond_signal(&ctx->sq_full);
  15450. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15451. #undef QUEUE_SIZE
  15452. }
  15453. #endif /* ALTERNATIVE_QUEUE */
  15454. static void
  15455. worker_thread_run(struct mg_connection *conn)
  15456. {
  15457. struct mg_context *ctx = conn->phys_ctx;
  15458. int thread_index;
  15459. struct mg_workerTLS tls;
  15460. #if defined(MG_LEGACY_INTERFACE)
  15461. uint32_t addr;
  15462. #endif
  15463. mg_set_thread_name("worker");
  15464. tls.is_master = 0;
  15465. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15466. #if defined(_WIN32)
  15467. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15468. #endif
  15469. /* Initialize thread local storage before calling any callback */
  15470. pthread_setspecific(sTlsKey, &tls);
  15471. /* Check if there is a user callback */
  15472. if (ctx->callbacks.init_thread) {
  15473. /* call init_thread for a worker thread (type 1), and store the return
  15474. * value */
  15475. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  15476. } else {
  15477. /* No callback: set user pointer to NULL */
  15478. tls.user_ptr = NULL;
  15479. }
  15480. /* Connection structure has been pre-allocated */
  15481. thread_index = (int)(conn - ctx->worker_connections);
  15482. if ((thread_index < 0)
  15483. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  15484. mg_cry_ctx_internal(ctx,
  15485. "Internal error: Invalid worker index %i",
  15486. thread_index);
  15487. return;
  15488. }
  15489. /* Request buffers are not pre-allocated. They are private to the
  15490. * request and do not contain any state information that might be
  15491. * of interest to anyone observing a server status. */
  15492. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15493. if (conn->buf == NULL) {
  15494. mg_cry_ctx_internal(
  15495. ctx,
  15496. "Out of memory: Cannot allocate buffer for worker %i",
  15497. thread_index);
  15498. return;
  15499. }
  15500. conn->buf_size = (int)ctx->max_request_size;
  15501. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15502. conn->host = NULL; /* until we have more information. */
  15503. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  15504. conn->request_info.user_data = ctx->user_data;
  15505. /* Allocate a mutex for this connection to allow communication both
  15506. * within the request handler and from elsewhere in the application
  15507. */
  15508. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15509. mg_free(conn->buf);
  15510. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  15511. return;
  15512. }
  15513. #if defined(USE_SERVER_STATS)
  15514. conn->conn_state = 1; /* not consumed */
  15515. #endif
  15516. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15517. * signal sq_empty condvar to wake up the master waiting in
  15518. * produce_socket() */
  15519. while (consume_socket(ctx, &conn->client, thread_index)) {
  15520. conn->conn_birth_time = time(NULL);
  15521. /* Fill in IP, port info early so even if SSL setup below fails,
  15522. * error handler would have the corresponding info.
  15523. * Thanks to Johannes Winkelmann for the patch.
  15524. */
  15525. #if defined(USE_IPV6)
  15526. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15527. conn->request_info.remote_port =
  15528. ntohs(conn->client.rsa.sin6.sin6_port);
  15529. } else
  15530. #endif
  15531. {
  15532. conn->request_info.remote_port =
  15533. ntohs(conn->client.rsa.sin.sin_port);
  15534. }
  15535. sockaddr_to_string(conn->request_info.remote_addr,
  15536. sizeof(conn->request_info.remote_addr),
  15537. &conn->client.rsa);
  15538. DEBUG_TRACE("Start processing connection from %s",
  15539. conn->request_info.remote_addr);
  15540. conn->request_info.is_ssl = conn->client.is_ssl;
  15541. if (conn->client.is_ssl) {
  15542. #if !defined(NO_SSL)
  15543. /* HTTPS connection */
  15544. if (sslize(conn,
  15545. conn->dom_ctx->ssl_ctx,
  15546. SSL_accept,
  15547. &(conn->phys_ctx->stop_flag),
  15548. NULL)) {
  15549. /* conn->dom_ctx is set in get_request */
  15550. /* Get SSL client certificate information (if set) */
  15551. ssl_get_client_cert_info(conn);
  15552. /* process HTTPS connection */
  15553. process_new_connection(conn);
  15554. /* Free client certificate info */
  15555. if (conn->request_info.client_cert) {
  15556. mg_free((void *)(conn->request_info.client_cert->subject));
  15557. mg_free((void *)(conn->request_info.client_cert->issuer));
  15558. mg_free((void *)(conn->request_info.client_cert->serial));
  15559. mg_free((void *)(conn->request_info.client_cert->finger));
  15560. /* Free certificate memory */
  15561. X509_free(
  15562. (X509 *)conn->request_info.client_cert->peer_cert);
  15563. conn->request_info.client_cert->peer_cert = 0;
  15564. conn->request_info.client_cert->subject = 0;
  15565. conn->request_info.client_cert->issuer = 0;
  15566. conn->request_info.client_cert->serial = 0;
  15567. conn->request_info.client_cert->finger = 0;
  15568. mg_free(conn->request_info.client_cert);
  15569. conn->request_info.client_cert = 0;
  15570. }
  15571. } else {
  15572. /* make sure the connection is cleaned up on SSL failure */
  15573. close_connection(conn);
  15574. }
  15575. #endif
  15576. } else {
  15577. /* process HTTP connection */
  15578. process_new_connection(conn);
  15579. }
  15580. DEBUG_TRACE("%s", "Connection closed");
  15581. }
  15582. /* Call exit thread user callback */
  15583. if (ctx->callbacks.exit_thread) {
  15584. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  15585. }
  15586. /* delete thread local storage objects */
  15587. pthread_setspecific(sTlsKey, NULL);
  15588. #if defined(_WIN32)
  15589. CloseHandle(tls.pthread_cond_helper_mutex);
  15590. #endif
  15591. pthread_mutex_destroy(&conn->mutex);
  15592. /* Free the request buffer. */
  15593. conn->buf_size = 0;
  15594. mg_free(conn->buf);
  15595. conn->buf = NULL;
  15596. #if defined(USE_SERVER_STATS)
  15597. conn->conn_state = 9; /* done */
  15598. #endif
  15599. DEBUG_TRACE("%s", "exiting");
  15600. }
  15601. /* Threads have different return types on Windows and Unix. */
  15602. #if defined(_WIN32)
  15603. static unsigned __stdcall worker_thread(void *thread_func_param)
  15604. {
  15605. worker_thread_run((struct mg_connection *)thread_func_param);
  15606. return 0;
  15607. }
  15608. #else
  15609. static void *
  15610. worker_thread(void *thread_func_param)
  15611. {
  15612. #if !defined(__ZEPHYR__)
  15613. struct sigaction sa;
  15614. /* Ignore SIGPIPE */
  15615. memset(&sa, 0, sizeof(sa));
  15616. sa.sa_handler = SIG_IGN;
  15617. sigaction(SIGPIPE, &sa, NULL);
  15618. #endif
  15619. worker_thread_run((struct mg_connection *)thread_func_param);
  15620. return NULL;
  15621. }
  15622. #endif /* _WIN32 */
  15623. /* This is an internal function, thus all arguments are expected to be
  15624. * valid - a NULL check is not required. */
  15625. static void
  15626. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15627. {
  15628. struct socket so;
  15629. char src_addr[IP_ADDR_STR_LEN];
  15630. socklen_t len = sizeof(so.rsa);
  15631. #if !defined(__ZEPHYR__)
  15632. int on = 1;
  15633. #endif
  15634. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15635. == INVALID_SOCKET) {
  15636. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15637. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15638. mg_cry_ctx_internal(ctx,
  15639. "%s: %s is not allowed to connect",
  15640. __func__,
  15641. src_addr);
  15642. closesocket(so.sock);
  15643. } else {
  15644. /* Put so socket structure into the queue */
  15645. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15646. set_close_on_exec(so.sock, NULL, ctx);
  15647. so.is_ssl = listener->is_ssl;
  15648. so.ssl_redir = listener->ssl_redir;
  15649. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15650. mg_cry_ctx_internal(ctx,
  15651. "%s: getsockname() failed: %s",
  15652. __func__,
  15653. strerror(ERRNO));
  15654. }
  15655. #if !defined(__ZEPHYR__)
  15656. /* Set TCP keep-alive. This is needed because if HTTP-level
  15657. * keep-alive
  15658. * is enabled, and client resets the connection, server won't get
  15659. * TCP FIN or RST and will keep the connection open forever. With
  15660. * TCP keep-alive, next keep-alive handshake will figure out that
  15661. * the client is down and will close the server end.
  15662. * Thanks to Igor Klopov who suggested the patch. */
  15663. if (setsockopt(so.sock,
  15664. SOL_SOCKET,
  15665. SO_KEEPALIVE,
  15666. (SOCK_OPT_TYPE)&on,
  15667. sizeof(on))
  15668. != 0) {
  15669. mg_cry_ctx_internal(
  15670. ctx,
  15671. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15672. __func__,
  15673. strerror(ERRNO));
  15674. }
  15675. #endif
  15676. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15677. * to effectively fill up the underlying IP packet payload and
  15678. * reduce the overhead of sending lots of small buffers. However
  15679. * this hurts the server's throughput (ie. operations per second)
  15680. * when HTTP 1.1 persistent connections are used and the responses
  15681. * are relatively small (eg. less than 1400 bytes).
  15682. */
  15683. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15684. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15685. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15686. mg_cry_ctx_internal(
  15687. ctx,
  15688. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15689. __func__,
  15690. strerror(ERRNO));
  15691. }
  15692. }
  15693. /* The "non blocking" property should already be
  15694. * inherited from the parent socket. Set it for
  15695. * non-compliant socket implementations. */
  15696. set_non_blocking_mode(so.sock);
  15697. so.in_use = 0;
  15698. produce_socket(ctx, &so);
  15699. }
  15700. }
  15701. static void
  15702. master_thread_run(struct mg_context *ctx)
  15703. {
  15704. struct mg_workerTLS tls;
  15705. struct mg_pollfd *pfd;
  15706. unsigned int i;
  15707. unsigned int workerthreadcount;
  15708. if (!ctx) {
  15709. return;
  15710. }
  15711. mg_set_thread_name("master");
  15712. /* Increase priority of the master thread */
  15713. #if defined(_WIN32)
  15714. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15715. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15716. int min_prio = sched_get_priority_min(SCHED_RR);
  15717. int max_prio = sched_get_priority_max(SCHED_RR);
  15718. if ((min_prio >= 0) && (max_prio >= 0)
  15719. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15720. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15721. struct sched_param sched_param = {0};
  15722. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15723. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15724. }
  15725. #endif
  15726. /* Initialize thread local storage */
  15727. #if defined(_WIN32)
  15728. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15729. #endif
  15730. tls.is_master = 1;
  15731. pthread_setspecific(sTlsKey, &tls);
  15732. if (ctx->callbacks.init_thread) {
  15733. /* Callback for the master thread (type 0) */
  15734. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  15735. } else {
  15736. tls.user_ptr = NULL;
  15737. }
  15738. /* Server starts *now* */
  15739. ctx->start_time = time(NULL);
  15740. /* Start the server */
  15741. pfd = ctx->listening_socket_fds;
  15742. while (ctx->stop_flag == 0) {
  15743. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15744. pfd[i].fd = ctx->listening_sockets[i].sock;
  15745. pfd[i].events = POLLIN;
  15746. }
  15747. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15748. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15749. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15750. * successful poll, and POLLIN is defined as
  15751. * (POLLRDNORM | POLLRDBAND)
  15752. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15753. * pfd[i].revents == POLLIN. */
  15754. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15755. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15756. }
  15757. }
  15758. }
  15759. }
  15760. /* Here stop_flag is 1 - Initiate shutdown. */
  15761. DEBUG_TRACE("%s", "stopping workers");
  15762. /* Stop signal received: somebody called mg_stop. Quit. */
  15763. close_all_listening_sockets(ctx);
  15764. /* Wakeup workers that are waiting for connections to handle. */
  15765. #if defined(ALTERNATIVE_QUEUE)
  15766. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15767. event_signal(ctx->client_wait_events[i]);
  15768. }
  15769. #else
  15770. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15771. pthread_cond_broadcast(&ctx->sq_full);
  15772. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15773. #endif
  15774. /* Join all worker threads to avoid leaking threads. */
  15775. workerthreadcount = ctx->cfg_worker_threads;
  15776. for (i = 0; i < workerthreadcount; i++) {
  15777. if (ctx->worker_threadids[i] != 0) {
  15778. mg_join_thread(ctx->worker_threadids[i]);
  15779. }
  15780. }
  15781. #if defined(USE_LUA)
  15782. /* Free Lua state of lua background task */
  15783. if (ctx->lua_background_state) {
  15784. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15785. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15786. if (lua_istable(lstate, -1)) {
  15787. reg_boolean(lstate, "shutdown", 1);
  15788. lua_pop(lstate, 1);
  15789. mg_sleep(2);
  15790. }
  15791. lua_close(lstate);
  15792. ctx->lua_background_state = 0;
  15793. }
  15794. #endif
  15795. DEBUG_TRACE("%s", "exiting");
  15796. /* call exit thread callback */
  15797. if (ctx->callbacks.exit_thread) {
  15798. /* Callback for the master thread (type 0) */
  15799. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  15800. }
  15801. #if defined(_WIN32)
  15802. CloseHandle(tls.pthread_cond_helper_mutex);
  15803. #endif
  15804. pthread_setspecific(sTlsKey, NULL);
  15805. /* Signal mg_stop() that we're done.
  15806. * WARNING: This must be the very last thing this
  15807. * thread does, as ctx becomes invalid after this line. */
  15808. ctx->stop_flag = 2;
  15809. }
  15810. /* Threads have different return types on Windows and Unix. */
  15811. #if defined(_WIN32)
  15812. static unsigned __stdcall master_thread(void *thread_func_param)
  15813. {
  15814. master_thread_run((struct mg_context *)thread_func_param);
  15815. return 0;
  15816. }
  15817. #else
  15818. static void *
  15819. master_thread(void *thread_func_param)
  15820. {
  15821. #if !defined(__ZEPHYR__)
  15822. struct sigaction sa;
  15823. /* Ignore SIGPIPE */
  15824. memset(&sa, 0, sizeof(sa));
  15825. sa.sa_handler = SIG_IGN;
  15826. sigaction(SIGPIPE, &sa, NULL);
  15827. #endif
  15828. master_thread_run((struct mg_context *)thread_func_param);
  15829. return NULL;
  15830. }
  15831. #endif /* _WIN32 */
  15832. static void
  15833. free_context(struct mg_context *ctx)
  15834. {
  15835. int i;
  15836. struct mg_handler_info *tmp_rh;
  15837. if (ctx == NULL) {
  15838. return;
  15839. }
  15840. if (ctx->callbacks.exit_context) {
  15841. ctx->callbacks.exit_context(ctx);
  15842. }
  15843. /* All threads exited, no sync is needed. Destroy thread mutex and
  15844. * condvars
  15845. */
  15846. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15847. #if defined(ALTERNATIVE_QUEUE)
  15848. mg_free(ctx->client_socks);
  15849. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15850. event_destroy(ctx->client_wait_events[i]);
  15851. }
  15852. mg_free(ctx->client_wait_events);
  15853. #else
  15854. (void)pthread_cond_destroy(&ctx->sq_empty);
  15855. (void)pthread_cond_destroy(&ctx->sq_full);
  15856. #endif
  15857. /* Destroy other context global data structures mutex */
  15858. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15859. #if defined(USE_TIMERS)
  15860. timers_exit(ctx);
  15861. #endif
  15862. /* Deallocate config parameters */
  15863. for (i = 0; i < NUM_OPTIONS; i++) {
  15864. if (ctx->dd.config[i] != NULL) {
  15865. #if defined(_MSC_VER)
  15866. #pragma warning(suppress : 6001)
  15867. #endif
  15868. mg_free(ctx->dd.config[i]);
  15869. }
  15870. }
  15871. /* Deallocate request handlers */
  15872. while (ctx->dd.handlers) {
  15873. tmp_rh = ctx->dd.handlers;
  15874. ctx->dd.handlers = tmp_rh->next;
  15875. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15876. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15877. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15878. }
  15879. mg_free(tmp_rh->uri);
  15880. mg_free(tmp_rh);
  15881. }
  15882. #if !defined(NO_SSL)
  15883. /* Deallocate SSL context */
  15884. if (ctx->dd.ssl_ctx != NULL) {
  15885. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15886. int callback_ret =
  15887. (ctx->callbacks.external_ssl_ctx == NULL)
  15888. ? 0
  15889. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15890. if (callback_ret == 0) {
  15891. SSL_CTX_free(ctx->dd.ssl_ctx);
  15892. }
  15893. /* else: ignore error and ommit SSL_CTX_free in case
  15894. * callback_ret is 1 */
  15895. }
  15896. #endif /* !NO_SSL */
  15897. /* Deallocate worker thread ID array */
  15898. mg_free(ctx->worker_threadids);
  15899. /* Deallocate worker thread ID array */
  15900. mg_free(ctx->worker_connections);
  15901. /* deallocate system name string */
  15902. mg_free(ctx->systemName);
  15903. /* Deallocate context itself */
  15904. mg_free(ctx);
  15905. }
  15906. void
  15907. mg_stop(struct mg_context *ctx)
  15908. {
  15909. pthread_t mt;
  15910. if (!ctx) {
  15911. return;
  15912. }
  15913. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15914. * two threads is not allowed. */
  15915. mt = ctx->masterthreadid;
  15916. if (mt == 0) {
  15917. return;
  15918. }
  15919. ctx->masterthreadid = 0;
  15920. /* Set stop flag, so all threads know they have to exit. */
  15921. ctx->stop_flag = 1;
  15922. /* Wait until everything has stopped. */
  15923. while (ctx->stop_flag != 2) {
  15924. (void)mg_sleep(10);
  15925. }
  15926. mg_join_thread(mt);
  15927. free_context(ctx);
  15928. #if defined(_WIN32)
  15929. (void)WSACleanup();
  15930. #endif /* _WIN32 */
  15931. }
  15932. static void
  15933. get_system_name(char **sysName)
  15934. {
  15935. #if defined(_WIN32)
  15936. #if !defined(__SYMBIAN32__)
  15937. #if defined(_WIN32_WCE)
  15938. *sysName = mg_strdup("WinCE");
  15939. #else
  15940. char name[128];
  15941. DWORD dwVersion = 0;
  15942. DWORD dwMajorVersion = 0;
  15943. DWORD dwMinorVersion = 0;
  15944. DWORD dwBuild = 0;
  15945. BOOL wowRet, isWoW = FALSE;
  15946. #if defined(_MSC_VER)
  15947. #pragma warning(push)
  15948. /* GetVersion was declared deprecated */
  15949. #pragma warning(disable : 4996)
  15950. #endif
  15951. dwVersion = GetVersion();
  15952. #if defined(_MSC_VER)
  15953. #pragma warning(pop)
  15954. #endif
  15955. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15956. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15957. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15958. (void)dwBuild;
  15959. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15960. sprintf(name,
  15961. "Windows %u.%u%s",
  15962. (unsigned)dwMajorVersion,
  15963. (unsigned)dwMinorVersion,
  15964. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15965. *sysName = mg_strdup(name);
  15966. #endif
  15967. #else
  15968. *sysName = mg_strdup("Symbian");
  15969. #endif
  15970. #elif defined(__ZEPHYR__)
  15971. *sysName = mg_strdup("Zephyr OS");
  15972. #else
  15973. struct utsname name;
  15974. memset(&name, 0, sizeof(name));
  15975. uname(&name);
  15976. *sysName = mg_strdup(name.sysname);
  15977. #endif
  15978. }
  15979. static void
  15980. legacy_init(const char **options)
  15981. {
  15982. const char *ports_option = config_options[LISTENING_PORTS].default_value;
  15983. if (options) {
  15984. const char **run_options = options;
  15985. const char *optname = config_options[LISTENING_PORTS].name;
  15986. /* Try to find the "listening_ports" option */
  15987. while (*run_options) {
  15988. if (!strcmp(*run_options, optname)) {
  15989. ports_option = run_options[1];
  15990. }
  15991. run_options += 2;
  15992. }
  15993. }
  15994. if (is_ssl_port_used(ports_option)) {
  15995. /* Initialize with SSL support */
  15996. mg_init_library(MG_FEATURES_TLS);
  15997. } else {
  15998. /* Initialize without SSL support */
  15999. mg_init_library(MG_FEATURES_DEFAULT);
  16000. }
  16001. }
  16002. struct mg_context *
  16003. mg_start(const struct mg_callbacks *callbacks,
  16004. void *user_data,
  16005. const char **options)
  16006. {
  16007. struct mg_context *ctx;
  16008. const char *name, *value, *default_value;
  16009. int idx, ok, workerthreadcount;
  16010. unsigned int i;
  16011. int itmp;
  16012. void (*exit_callback)(const struct mg_context *ctx) = 0;
  16013. struct mg_workerTLS tls;
  16014. #if defined(_WIN32)
  16015. WSADATA data;
  16016. WSAStartup(MAKEWORD(2, 2), &data);
  16017. #endif /* _WIN32 */
  16018. if (mg_init_library_called == 0) {
  16019. /* Legacy INIT, if mg_start is called without mg_init_library.
  16020. * Note: This will cause a memory leak when unloading the library. */
  16021. legacy_init(options);
  16022. }
  16023. /* Allocate context and initialize reasonable general case defaults. */
  16024. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  16025. return NULL;
  16026. }
  16027. /* Random number generator will initialize at the first call */
  16028. ctx->dd.auth_nonce_mask =
  16029. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  16030. tls.is_master = -1;
  16031. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16032. #if defined(_WIN32)
  16033. tls.pthread_cond_helper_mutex = NULL;
  16034. #endif
  16035. pthread_setspecific(sTlsKey, &tls);
  16036. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16037. #if !defined(ALTERNATIVE_QUEUE)
  16038. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16039. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16040. #endif
  16041. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16042. if (!ok) {
  16043. /* Fatal error - abort start. However, this situation should never
  16044. * occur in practice. */
  16045. mg_cry_ctx_internal(ctx,
  16046. "%s",
  16047. "Cannot initialize thread synchronization objects");
  16048. mg_free(ctx);
  16049. pthread_setspecific(sTlsKey, NULL);
  16050. return NULL;
  16051. }
  16052. if (callbacks) {
  16053. ctx->callbacks = *callbacks;
  16054. exit_callback = callbacks->exit_context;
  16055. ctx->callbacks.exit_context = 0;
  16056. }
  16057. ctx->user_data = user_data;
  16058. ctx->dd.handlers = NULL;
  16059. ctx->dd.next = NULL;
  16060. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16061. ctx->dd.shared_lua_websockets = NULL;
  16062. #endif
  16063. /* Store options */
  16064. while (options && (name = *options++) != NULL) {
  16065. if ((idx = get_option_index(name)) == -1) {
  16066. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16067. free_context(ctx);
  16068. pthread_setspecific(sTlsKey, NULL);
  16069. return NULL;
  16070. } else if ((value = *options++) == NULL) {
  16071. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16072. free_context(ctx);
  16073. pthread_setspecific(sTlsKey, NULL);
  16074. return NULL;
  16075. }
  16076. if (ctx->dd.config[idx] != NULL) {
  16077. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16078. mg_free(ctx->dd.config[idx]);
  16079. }
  16080. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16081. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16082. }
  16083. /* Set default value if needed */
  16084. for (i = 0; config_options[i].name != NULL; i++) {
  16085. default_value = config_options[i].default_value;
  16086. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16087. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16088. }
  16089. }
  16090. /* Request size option */
  16091. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16092. if (itmp < 1024) {
  16093. mg_cry_ctx_internal(ctx, "%s", "max_request_size too small");
  16094. free_context(ctx);
  16095. pthread_setspecific(sTlsKey, NULL);
  16096. return NULL;
  16097. }
  16098. ctx->max_request_size = (unsigned)itmp;
  16099. /* Worker thread count option */
  16100. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16101. if (workerthreadcount > MAX_WORKER_THREADS) {
  16102. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16103. free_context(ctx);
  16104. pthread_setspecific(sTlsKey, NULL);
  16105. return NULL;
  16106. }
  16107. if (workerthreadcount <= 0) {
  16108. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16109. free_context(ctx);
  16110. pthread_setspecific(sTlsKey, NULL);
  16111. return NULL;
  16112. }
  16113. /* Document root */
  16114. #if defined(NO_FILES)
  16115. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16116. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16117. free_context(ctx);
  16118. pthread_setspecific(sTlsKey, NULL);
  16119. return NULL;
  16120. }
  16121. #endif
  16122. get_system_name(&ctx->systemName);
  16123. #if defined(USE_LUA)
  16124. /* If a Lua background script has been configured, start it. */
  16125. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16126. char ebuf[256];
  16127. struct vec opt_vec;
  16128. struct vec eq_vec;
  16129. const char *sparams;
  16130. lua_State *state = mg_prepare_lua_context_script(
  16131. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16132. if (!state) {
  16133. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16134. free_context(ctx);
  16135. pthread_setspecific(sTlsKey, NULL);
  16136. return NULL;
  16137. }
  16138. ctx->lua_background_state = (void *)state;
  16139. lua_newtable(state);
  16140. reg_boolean(state, "shutdown", 0);
  16141. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16142. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16143. reg_llstring(
  16144. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16145. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16146. break;
  16147. }
  16148. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16149. } else {
  16150. ctx->lua_background_state = 0;
  16151. }
  16152. #endif
  16153. /* NOTE(lsm): order is important here. SSL certificates must
  16154. * be initialized before listening ports. UID must be set last. */
  16155. if (
  16156. #if !defined(NO_FILESYSTEMS)
  16157. !set_gpass_option(ctx, NULL) ||
  16158. #endif
  16159. #if !defined(NO_SSL)
  16160. !init_ssl_ctx(ctx, NULL) ||
  16161. #endif
  16162. !set_ports_option(ctx) ||
  16163. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16164. !set_uid_option(ctx) ||
  16165. #endif
  16166. !set_acl_option(ctx)) {
  16167. free_context(ctx);
  16168. pthread_setspecific(sTlsKey, NULL);
  16169. return NULL;
  16170. }
  16171. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16172. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16173. sizeof(pthread_t),
  16174. ctx);
  16175. if (ctx->worker_threadids == NULL) {
  16176. mg_cry_ctx_internal(ctx,
  16177. "%s",
  16178. "Not enough memory for worker thread ID array");
  16179. free_context(ctx);
  16180. pthread_setspecific(sTlsKey, NULL);
  16181. return NULL;
  16182. }
  16183. ctx->worker_connections =
  16184. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16185. sizeof(struct mg_connection),
  16186. ctx);
  16187. if (ctx->worker_connections == NULL) {
  16188. mg_cry_ctx_internal(
  16189. ctx, "%s", "Not enough memory for worker thread connection array");
  16190. free_context(ctx);
  16191. pthread_setspecific(sTlsKey, NULL);
  16192. return NULL;
  16193. }
  16194. #if defined(ALTERNATIVE_QUEUE)
  16195. ctx->client_wait_events =
  16196. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  16197. sizeof(ctx->client_wait_events[0]),
  16198. ctx);
  16199. if (ctx->client_wait_events == NULL) {
  16200. mg_cry_ctx_internal(ctx,
  16201. "%s",
  16202. "Not enough memory for worker event array");
  16203. mg_free(ctx->worker_threadids);
  16204. free_context(ctx);
  16205. pthread_setspecific(sTlsKey, NULL);
  16206. return NULL;
  16207. }
  16208. ctx->client_socks =
  16209. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16210. sizeof(ctx->client_socks[0]),
  16211. ctx);
  16212. if (ctx->client_socks == NULL) {
  16213. mg_cry_ctx_internal(ctx,
  16214. "%s",
  16215. "Not enough memory for worker socket array");
  16216. mg_free(ctx->client_wait_events);
  16217. mg_free(ctx->worker_threadids);
  16218. free_context(ctx);
  16219. pthread_setspecific(sTlsKey, NULL);
  16220. return NULL;
  16221. }
  16222. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16223. ctx->client_wait_events[i] = event_create();
  16224. if (ctx->client_wait_events[i] == 0) {
  16225. mg_cry_ctx_internal(ctx, "Error creating worker event %i", i);
  16226. while (i > 0) {
  16227. i--;
  16228. event_destroy(ctx->client_wait_events[i]);
  16229. }
  16230. mg_free(ctx->client_socks);
  16231. mg_free(ctx->client_wait_events);
  16232. mg_free(ctx->worker_threadids);
  16233. free_context(ctx);
  16234. pthread_setspecific(sTlsKey, NULL);
  16235. return NULL;
  16236. }
  16237. }
  16238. #endif
  16239. #if defined(USE_TIMERS)
  16240. if (timers_init(ctx) != 0) {
  16241. mg_cry_ctx_internal(ctx, "%s", "Error creating timers");
  16242. free_context(ctx);
  16243. pthread_setspecific(sTlsKey, NULL);
  16244. return NULL;
  16245. }
  16246. #endif
  16247. /* Context has been created - init user libraries */
  16248. if (ctx->callbacks.init_context) {
  16249. ctx->callbacks.init_context(ctx);
  16250. }
  16251. ctx->callbacks.exit_context = exit_callback;
  16252. ctx->context_type = CONTEXT_SERVER; /* server context */
  16253. /* Start master (listening) thread */
  16254. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16255. /* Start worker threads */
  16256. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16257. /* worker_thread sets up the other fields */
  16258. ctx->worker_connections[i].phys_ctx = ctx;
  16259. if (mg_start_thread_with_id(worker_thread,
  16260. &ctx->worker_connections[i],
  16261. &ctx->worker_threadids[i])
  16262. != 0) {
  16263. /* thread was not created */
  16264. if (i > 0) {
  16265. mg_cry_ctx_internal(ctx,
  16266. "Cannot start worker thread %i: error %ld",
  16267. i + 1,
  16268. (long)ERRNO);
  16269. } else {
  16270. mg_cry_ctx_internal(ctx,
  16271. "Cannot create threads: error %ld",
  16272. (long)ERRNO);
  16273. free_context(ctx);
  16274. pthread_setspecific(sTlsKey, NULL);
  16275. return NULL;
  16276. }
  16277. break;
  16278. }
  16279. }
  16280. pthread_setspecific(sTlsKey, NULL);
  16281. return ctx;
  16282. }
  16283. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16284. /* Add an additional domain to an already running web server. */
  16285. int
  16286. mg_start_domain(struct mg_context *ctx, const char **options)
  16287. {
  16288. const char *name;
  16289. const char *value;
  16290. const char *default_value;
  16291. struct mg_domain_context *new_dom;
  16292. struct mg_domain_context *dom;
  16293. int idx, i;
  16294. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  16295. return -1;
  16296. }
  16297. new_dom = (struct mg_domain_context *)
  16298. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16299. if (!new_dom) {
  16300. /* Out of memory */
  16301. return -6;
  16302. }
  16303. /* Store options - TODO: unite duplicate code */
  16304. while (options && (name = *options++) != NULL) {
  16305. if ((idx = get_option_index(name)) == -1) {
  16306. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16307. mg_free(new_dom);
  16308. return -2;
  16309. } else if ((value = *options++) == NULL) {
  16310. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16311. mg_free(new_dom);
  16312. return -2;
  16313. }
  16314. if (new_dom->config[idx] != NULL) {
  16315. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16316. mg_free(new_dom->config[idx]);
  16317. }
  16318. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16319. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16320. }
  16321. /* Authentication domain is mandatory */
  16322. /* TODO: Maybe use a new option hostname? */
  16323. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16324. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  16325. mg_free(new_dom);
  16326. return -4;
  16327. }
  16328. /* Set default value if needed. Take the config value from
  16329. * ctx as a default value. */
  16330. for (i = 0; config_options[i].name != NULL; i++) {
  16331. default_value = ctx->dd.config[i];
  16332. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16333. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16334. }
  16335. }
  16336. new_dom->handlers = NULL;
  16337. new_dom->next = NULL;
  16338. new_dom->nonce_count = 0;
  16339. new_dom->auth_nonce_mask =
  16340. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16341. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16342. new_dom->shared_lua_websockets = NULL;
  16343. #endif
  16344. if (!init_ssl_ctx(ctx, new_dom)) {
  16345. /* Init SSL failed */
  16346. mg_free(new_dom);
  16347. return -3;
  16348. }
  16349. /* Add element to linked list. */
  16350. mg_lock_context(ctx);
  16351. idx = 0;
  16352. dom = &(ctx->dd);
  16353. for (;;) {
  16354. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16355. dom->config[AUTHENTICATION_DOMAIN])) {
  16356. /* Domain collision */
  16357. mg_cry_ctx_internal(ctx,
  16358. "domain %s already in use",
  16359. new_dom->config[AUTHENTICATION_DOMAIN]);
  16360. mg_free(new_dom);
  16361. return -5;
  16362. }
  16363. /* Count number of domains */
  16364. idx++;
  16365. if (dom->next == NULL) {
  16366. dom->next = new_dom;
  16367. break;
  16368. }
  16369. dom = dom->next;
  16370. }
  16371. mg_unlock_context(ctx);
  16372. /* Return domain number */
  16373. return idx;
  16374. }
  16375. #endif
  16376. /* Feature check API function */
  16377. unsigned
  16378. mg_check_feature(unsigned feature)
  16379. {
  16380. static const unsigned feature_set = 0
  16381. /* Set bits for available features according to API documentation.
  16382. * This bit mask is created at compile time, according to the active
  16383. * preprocessor defines. It is a single const value at runtime. */
  16384. #if !defined(NO_FILES)
  16385. | MG_FEATURES_FILES
  16386. #endif
  16387. #if !defined(NO_SSL)
  16388. | MG_FEATURES_SSL
  16389. #endif
  16390. #if !defined(NO_CGI)
  16391. | MG_FEATURES_CGI
  16392. #endif
  16393. #if defined(USE_IPV6)
  16394. | MG_FEATURES_IPV6
  16395. #endif
  16396. #if defined(USE_WEBSOCKET)
  16397. | MG_FEATURES_WEBSOCKET
  16398. #endif
  16399. #if defined(USE_LUA)
  16400. | MG_FEATURES_LUA
  16401. #endif
  16402. #if defined(USE_DUKTAPE)
  16403. | MG_FEATURES_SSJS
  16404. #endif
  16405. #if !defined(NO_CACHING)
  16406. | MG_FEATURES_CACHE
  16407. #endif
  16408. #if defined(USE_SERVER_STATS)
  16409. | MG_FEATURES_STATS
  16410. #endif
  16411. #if defined(USE_ZLIB)
  16412. | MG_FEATURES_COMPRESSION
  16413. #endif
  16414. /* Set some extra bits not defined in the API documentation.
  16415. * These bits may change without further notice. */
  16416. #if defined(MG_LEGACY_INTERFACE)
  16417. | 0x00008000u
  16418. #endif
  16419. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16420. | 0x00004000u
  16421. #endif
  16422. #if defined(MEMORY_DEBUGGING)
  16423. | 0x00001000u
  16424. #endif
  16425. #if defined(USE_TIMERS)
  16426. | 0x00020000u
  16427. #endif
  16428. #if !defined(NO_NONCE_CHECK)
  16429. | 0x00040000u
  16430. #endif
  16431. #if !defined(NO_POPEN)
  16432. | 0x00080000u
  16433. #endif
  16434. ;
  16435. return (feature & feature_set);
  16436. }
  16437. static size_t
  16438. mg_str_append(char **dst, char *end, const char *src)
  16439. {
  16440. size_t len = strlen(src);
  16441. if (*dst != end) {
  16442. /* Append src if enough space, or close dst. */
  16443. if ((size_t)(end - *dst) > len) {
  16444. strcpy(*dst, src);
  16445. *dst += len;
  16446. } else {
  16447. *dst = end;
  16448. }
  16449. }
  16450. return len;
  16451. }
  16452. /* Get system information. It can be printed or stored by the caller.
  16453. * Return the size of available information. */
  16454. int
  16455. mg_get_system_info(char *buffer, int buflen)
  16456. {
  16457. char *end, *append_eoobj = NULL, block[256];
  16458. size_t system_info_length = 0;
  16459. #if defined(_WIN32)
  16460. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16461. #else
  16462. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16463. #endif
  16464. if ((buffer == NULL) || (buflen < 1)) {
  16465. buflen = 0;
  16466. end = buffer;
  16467. } else {
  16468. *buffer = 0;
  16469. end = buffer + buflen;
  16470. }
  16471. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16472. /* has enough space to append eoobj */
  16473. append_eoobj = buffer;
  16474. end -= sizeof(eoobj) - 1;
  16475. }
  16476. system_info_length += mg_str_append(&buffer, end, "{");
  16477. /* Server version */
  16478. {
  16479. const char *version = mg_version();
  16480. mg_snprintf(NULL,
  16481. NULL,
  16482. block,
  16483. sizeof(block),
  16484. "%s\"version\" : \"%s\"",
  16485. eol,
  16486. version);
  16487. system_info_length += mg_str_append(&buffer, end, block);
  16488. }
  16489. /* System info */
  16490. {
  16491. #if defined(_WIN32)
  16492. DWORD dwVersion = 0;
  16493. DWORD dwMajorVersion = 0;
  16494. DWORD dwMinorVersion = 0;
  16495. SYSTEM_INFO si;
  16496. GetSystemInfo(&si);
  16497. #if defined(_MSC_VER)
  16498. #pragma warning(push)
  16499. /* GetVersion was declared deprecated */
  16500. #pragma warning(disable : 4996)
  16501. #endif
  16502. dwVersion = GetVersion();
  16503. #if defined(_MSC_VER)
  16504. #pragma warning(pop)
  16505. #endif
  16506. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16507. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16508. mg_snprintf(NULL,
  16509. NULL,
  16510. block,
  16511. sizeof(block),
  16512. ",%s\"os\" : \"Windows %u.%u\"",
  16513. eol,
  16514. (unsigned)dwMajorVersion,
  16515. (unsigned)dwMinorVersion);
  16516. system_info_length += mg_str_append(&buffer, end, block);
  16517. mg_snprintf(NULL,
  16518. NULL,
  16519. block,
  16520. sizeof(block),
  16521. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  16522. eol,
  16523. (unsigned)si.wProcessorArchitecture,
  16524. (unsigned)si.dwNumberOfProcessors,
  16525. (unsigned)si.dwActiveProcessorMask);
  16526. system_info_length += mg_str_append(&buffer, end, block);
  16527. #elif defined(__ZEPHYR__)
  16528. mg_snprintf(NULL,
  16529. NULL,
  16530. block,
  16531. sizeof(block),
  16532. ",%s\"os\" : \"%s %s\"",
  16533. eol,
  16534. "Zephyr OS",
  16535. ZEPHYR_VERSION);
  16536. system_info_length += mg_str_append(&buffer, end, block);
  16537. #else
  16538. struct utsname name;
  16539. memset(&name, 0, sizeof(name));
  16540. uname(&name);
  16541. mg_snprintf(NULL,
  16542. NULL,
  16543. block,
  16544. sizeof(block),
  16545. ",%s\"os\" : \"%s %s (%s) - %s\"",
  16546. eol,
  16547. name.sysname,
  16548. name.version,
  16549. name.release,
  16550. name.machine);
  16551. system_info_length += mg_str_append(&buffer, end, block);
  16552. #endif
  16553. }
  16554. /* Features */
  16555. {
  16556. mg_snprintf(NULL,
  16557. NULL,
  16558. block,
  16559. sizeof(block),
  16560. ",%s\"features\" : %lu"
  16561. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  16562. eol,
  16563. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16564. eol,
  16565. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16566. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16567. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16568. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16569. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16570. : "",
  16571. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16572. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16573. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16574. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  16575. system_info_length += mg_str_append(&buffer, end, block);
  16576. #if defined(USE_LUA)
  16577. mg_snprintf(NULL,
  16578. NULL,
  16579. block,
  16580. sizeof(block),
  16581. ",%s\"lua_version\" : \"%u (%s)\"",
  16582. eol,
  16583. (unsigned)LUA_VERSION_NUM,
  16584. LUA_RELEASE);
  16585. system_info_length += mg_str_append(&buffer, end, block);
  16586. #endif
  16587. #if defined(USE_DUKTAPE)
  16588. mg_snprintf(NULL,
  16589. NULL,
  16590. block,
  16591. sizeof(block),
  16592. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  16593. eol,
  16594. (unsigned)DUK_VERSION / 10000,
  16595. ((unsigned)DUK_VERSION / 100) % 100,
  16596. (unsigned)DUK_VERSION % 100);
  16597. system_info_length += mg_str_append(&buffer, end, block);
  16598. #endif
  16599. }
  16600. /* Build date */
  16601. {
  16602. #if defined(GCC_DIAGNOSTIC)
  16603. #if GCC_VERSION >= 40900
  16604. #pragma GCC diagnostic push
  16605. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  16606. #pragma GCC diagnostic ignored "-Wdate-time"
  16607. #endif
  16608. #endif
  16609. mg_snprintf(NULL,
  16610. NULL,
  16611. block,
  16612. sizeof(block),
  16613. ",%s\"build\" : \"%s\"",
  16614. eol,
  16615. __DATE__);
  16616. #if defined(GCC_DIAGNOSTIC)
  16617. #if GCC_VERSION >= 40900
  16618. #pragma GCC diagnostic pop
  16619. #endif
  16620. #endif
  16621. system_info_length += mg_str_append(&buffer, end, block);
  16622. }
  16623. /* Compiler information */
  16624. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16625. {
  16626. #if defined(_MSC_VER)
  16627. mg_snprintf(NULL,
  16628. NULL,
  16629. block,
  16630. sizeof(block),
  16631. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  16632. eol,
  16633. (unsigned)_MSC_VER,
  16634. (unsigned)_MSC_FULL_VER);
  16635. system_info_length += mg_str_append(&buffer, end, block);
  16636. #elif defined(__MINGW64__)
  16637. mg_snprintf(NULL,
  16638. NULL,
  16639. block,
  16640. sizeof(block),
  16641. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  16642. eol,
  16643. (unsigned)__MINGW64_VERSION_MAJOR,
  16644. (unsigned)__MINGW64_VERSION_MINOR);
  16645. system_info_length += mg_str_append(&buffer, end, block);
  16646. mg_snprintf(NULL,
  16647. NULL,
  16648. block,
  16649. sizeof(block),
  16650. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16651. eol,
  16652. (unsigned)__MINGW32_MAJOR_VERSION,
  16653. (unsigned)__MINGW32_MINOR_VERSION);
  16654. system_info_length += mg_str_append(&buffer, end, block);
  16655. #elif defined(__MINGW32__)
  16656. mg_snprintf(NULL,
  16657. NULL,
  16658. block,
  16659. sizeof(block),
  16660. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16661. eol,
  16662. (unsigned)__MINGW32_MAJOR_VERSION,
  16663. (unsigned)__MINGW32_MINOR_VERSION);
  16664. system_info_length += mg_str_append(&buffer, end, block);
  16665. #elif defined(__clang__)
  16666. mg_snprintf(NULL,
  16667. NULL,
  16668. block,
  16669. sizeof(block),
  16670. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  16671. eol,
  16672. __clang_major__,
  16673. __clang_minor__,
  16674. __clang_patchlevel__,
  16675. __clang_version__);
  16676. system_info_length += mg_str_append(&buffer, end, block);
  16677. #elif defined(__GNUC__)
  16678. mg_snprintf(NULL,
  16679. NULL,
  16680. block,
  16681. sizeof(block),
  16682. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  16683. eol,
  16684. (unsigned)__GNUC__,
  16685. (unsigned)__GNUC_MINOR__,
  16686. (unsigned)__GNUC_PATCHLEVEL__);
  16687. system_info_length += mg_str_append(&buffer, end, block);
  16688. #elif defined(__INTEL_COMPILER)
  16689. mg_snprintf(NULL,
  16690. NULL,
  16691. block,
  16692. sizeof(block),
  16693. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  16694. eol,
  16695. (unsigned)__INTEL_COMPILER);
  16696. system_info_length += mg_str_append(&buffer, end, block);
  16697. #elif defined(__BORLANDC__)
  16698. mg_snprintf(NULL,
  16699. NULL,
  16700. block,
  16701. sizeof(block),
  16702. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  16703. eol,
  16704. (unsigned)__BORLANDC__);
  16705. system_info_length += mg_str_append(&buffer, end, block);
  16706. #elif defined(__SUNPRO_C)
  16707. mg_snprintf(NULL,
  16708. NULL,
  16709. block,
  16710. sizeof(block),
  16711. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  16712. eol,
  16713. (unsigned)__SUNPRO_C);
  16714. system_info_length += mg_str_append(&buffer, end, block);
  16715. #else
  16716. mg_snprintf(NULL,
  16717. NULL,
  16718. block,
  16719. sizeof(block),
  16720. ",%s\"compiler\" : \"other\"",
  16721. eol);
  16722. system_info_length += mg_str_append(&buffer, end, block);
  16723. #endif
  16724. }
  16725. /* Determine 32/64 bit data mode.
  16726. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16727. {
  16728. mg_snprintf(NULL,
  16729. NULL,
  16730. block,
  16731. sizeof(block),
  16732. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16733. "char:%u/%u, "
  16734. "ptr:%u, size:%u, time:%u\"",
  16735. eol,
  16736. (unsigned)sizeof(short),
  16737. (unsigned)sizeof(int),
  16738. (unsigned)sizeof(long),
  16739. (unsigned)sizeof(long long),
  16740. (unsigned)sizeof(float),
  16741. (unsigned)sizeof(double),
  16742. (unsigned)sizeof(long double),
  16743. (unsigned)sizeof(char),
  16744. (unsigned)sizeof(wchar_t),
  16745. (unsigned)sizeof(void *),
  16746. (unsigned)sizeof(size_t),
  16747. (unsigned)sizeof(time_t));
  16748. system_info_length += mg_str_append(&buffer, end, block);
  16749. }
  16750. /* Terminate string */
  16751. if (append_eoobj) {
  16752. strcat(append_eoobj, eoobj);
  16753. }
  16754. system_info_length += sizeof(eoobj) - 1;
  16755. return (int)system_info_length;
  16756. }
  16757. /* Get context information. It can be printed or stored by the caller.
  16758. * Return the size of available information. */
  16759. int
  16760. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16761. {
  16762. #if defined(USE_SERVER_STATS)
  16763. char *end, *append_eoobj = NULL, block[256];
  16764. size_t context_info_length = 0;
  16765. #if defined(_WIN32)
  16766. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16767. #else
  16768. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16769. #endif
  16770. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16771. if ((buffer == NULL) || (buflen < 1)) {
  16772. buflen = 0;
  16773. end = buffer;
  16774. } else {
  16775. *buffer = 0;
  16776. end = buffer + buflen;
  16777. }
  16778. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16779. /* has enough space to append eoobj */
  16780. append_eoobj = buffer;
  16781. end -= sizeof(eoobj) - 1;
  16782. }
  16783. context_info_length += mg_str_append(&buffer, end, "{");
  16784. if (ms) { /* <-- should be always true */
  16785. /* Memory information */
  16786. mg_snprintf(NULL,
  16787. NULL,
  16788. block,
  16789. sizeof(block),
  16790. "%s\"memory\" : {%s"
  16791. "\"blocks\" : %i,%s"
  16792. "\"used\" : %" INT64_FMT ",%s"
  16793. "\"maxUsed\" : %" INT64_FMT "%s"
  16794. "}",
  16795. eol,
  16796. eol,
  16797. ms->blockCount,
  16798. eol,
  16799. ms->totalMemUsed,
  16800. eol,
  16801. ms->maxMemUsed,
  16802. eol);
  16803. context_info_length += mg_str_append(&buffer, end, block);
  16804. }
  16805. if (ctx) {
  16806. /* Declare all variables at begin of the block, to comply
  16807. * with old C standards. */
  16808. char start_time_str[64] = {0};
  16809. char now_str[64] = {0};
  16810. time_t start_time = ctx->start_time;
  16811. time_t now = time(NULL);
  16812. /* Connections information */
  16813. mg_snprintf(NULL,
  16814. NULL,
  16815. block,
  16816. sizeof(block),
  16817. ",%s\"connections\" : {%s"
  16818. "\"active\" : %i,%s"
  16819. "\"maxActive\" : %i,%s"
  16820. "\"total\" : %" INT64_FMT "%s"
  16821. "}",
  16822. eol,
  16823. eol,
  16824. ctx->active_connections,
  16825. eol,
  16826. ctx->max_connections,
  16827. eol,
  16828. ctx->total_connections,
  16829. eol);
  16830. context_info_length += mg_str_append(&buffer, end, block);
  16831. /* Requests information */
  16832. mg_snprintf(NULL,
  16833. NULL,
  16834. block,
  16835. sizeof(block),
  16836. ",%s\"requests\" : {%s"
  16837. "\"total\" : %" INT64_FMT "%s"
  16838. "}",
  16839. eol,
  16840. eol,
  16841. ctx->total_requests,
  16842. eol);
  16843. context_info_length += mg_str_append(&buffer, end, block);
  16844. /* Data information */
  16845. mg_snprintf(NULL,
  16846. NULL,
  16847. block,
  16848. sizeof(block),
  16849. ",%s\"data\" : {%s"
  16850. "\"read\" : %" INT64_FMT ",%s"
  16851. "\"written\" : %" INT64_FMT "%s"
  16852. "}",
  16853. eol,
  16854. eol,
  16855. ctx->total_data_read,
  16856. eol,
  16857. ctx->total_data_written,
  16858. eol);
  16859. context_info_length += mg_str_append(&buffer, end, block);
  16860. /* Execution time information */
  16861. gmt_time_string(start_time_str,
  16862. sizeof(start_time_str) - 1,
  16863. &start_time);
  16864. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16865. mg_snprintf(NULL,
  16866. NULL,
  16867. block,
  16868. sizeof(block),
  16869. ",%s\"time\" : {%s"
  16870. "\"uptime\" : %.0f,%s"
  16871. "\"start\" : \"%s\",%s"
  16872. "\"now\" : \"%s\"%s"
  16873. "}",
  16874. eol,
  16875. eol,
  16876. difftime(now, start_time),
  16877. eol,
  16878. start_time_str,
  16879. eol,
  16880. now_str,
  16881. eol);
  16882. context_info_length += mg_str_append(&buffer, end, block);
  16883. }
  16884. /* Terminate string */
  16885. if (append_eoobj) {
  16886. strcat(append_eoobj, eoobj);
  16887. }
  16888. context_info_length += sizeof(eoobj) - 1;
  16889. return (int)context_info_length;
  16890. #else
  16891. (void)ctx;
  16892. if ((buffer != NULL) && (buflen > 0)) {
  16893. *buffer = 0;
  16894. }
  16895. return 0;
  16896. #endif
  16897. }
  16898. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16899. /* Get connection information. It can be printed or stored by the caller.
  16900. * Return the size of available information. */
  16901. int
  16902. mg_get_connection_info(const struct mg_context *ctx,
  16903. int idx,
  16904. char *buffer,
  16905. int buflen)
  16906. {
  16907. const struct mg_connection *conn;
  16908. const struct mg_request_info *ri;
  16909. char *end, *append_eoobj = NULL, block[256];
  16910. size_t connection_info_length = 0;
  16911. int state = 0;
  16912. const char *state_str = "unknown";
  16913. #if defined(_WIN32)
  16914. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16915. #else
  16916. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16917. #endif
  16918. if ((buffer == NULL) || (buflen < 1)) {
  16919. buflen = 0;
  16920. end = buffer;
  16921. } else {
  16922. *buffer = 0;
  16923. end = buffer + buflen;
  16924. }
  16925. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16926. /* has enough space to append eoobj */
  16927. append_eoobj = buffer;
  16928. end -= sizeof(eoobj) - 1;
  16929. }
  16930. if ((ctx == NULL) || (idx < 0)) {
  16931. /* Parameter error */
  16932. return 0;
  16933. }
  16934. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16935. /* Out of range */
  16936. return 0;
  16937. }
  16938. /* Take connection [idx]. This connection is not locked in
  16939. * any way, so some other thread might use it. */
  16940. conn = (ctx->worker_connections) + idx;
  16941. /* Initialize output string */
  16942. connection_info_length += mg_str_append(&buffer, end, "{");
  16943. /* Init variables */
  16944. ri = &(conn->request_info);
  16945. #if defined(USE_SERVER_STATS)
  16946. state = conn->conn_state;
  16947. /* State as string */
  16948. switch (state) {
  16949. case 0:
  16950. state_str = "undefined";
  16951. break;
  16952. case 1:
  16953. state_str = "not used";
  16954. break;
  16955. case 2:
  16956. state_str = "init";
  16957. break;
  16958. case 3:
  16959. state_str = "ready";
  16960. break;
  16961. case 4:
  16962. state_str = "processing";
  16963. break;
  16964. case 5:
  16965. state_str = "processed";
  16966. break;
  16967. case 6:
  16968. state_str = "to close";
  16969. break;
  16970. case 7:
  16971. state_str = "closing";
  16972. break;
  16973. case 8:
  16974. state_str = "closed";
  16975. break;
  16976. case 9:
  16977. state_str = "done";
  16978. break;
  16979. }
  16980. #endif
  16981. /* Connection info */
  16982. if ((state >= 3) && (state < 9)) {
  16983. mg_snprintf(NULL,
  16984. NULL,
  16985. block,
  16986. sizeof(block),
  16987. "%s\"connection\" : {%s"
  16988. "\"remote\" : {%s"
  16989. "\"protocol\" : \"%s\",%s"
  16990. "\"addr\" : \"%s\",%s"
  16991. "\"port\" : %u%s"
  16992. "},%s"
  16993. "\"handled_requests\" : %u%s"
  16994. "}",
  16995. eol,
  16996. eol,
  16997. eol,
  16998. get_proto_name(conn),
  16999. eol,
  17000. ri->remote_addr,
  17001. eol,
  17002. ri->remote_port,
  17003. eol,
  17004. eol,
  17005. conn->handled_requests,
  17006. eol);
  17007. connection_info_length += mg_str_append(&buffer, end, block);
  17008. }
  17009. /* Request info */
  17010. if ((state >= 4) && (state < 6)) {
  17011. mg_snprintf(NULL,
  17012. NULL,
  17013. block,
  17014. sizeof(block),
  17015. "%s%s\"request_info\" : {%s"
  17016. "\"method\" : \"%s\",%s"
  17017. "\"uri\" : \"%s\",%s"
  17018. "\"query\" : %s%s%s%s"
  17019. "}",
  17020. (connection_info_length > 1 ? "," : ""),
  17021. eol,
  17022. eol,
  17023. ri->request_method,
  17024. eol,
  17025. ri->request_uri,
  17026. eol,
  17027. ri->query_string ? "\"" : "",
  17028. ri->query_string ? ri->query_string : "null",
  17029. ri->query_string ? "\"" : "",
  17030. eol);
  17031. connection_info_length += mg_str_append(&buffer, end, block);
  17032. }
  17033. /* Execution time information */
  17034. if ((state >= 2) && (state < 9)) {
  17035. char start_time_str[64] = {0};
  17036. char now_str[64] = {0};
  17037. time_t start_time = conn->conn_birth_time;
  17038. time_t now = time(NULL);
  17039. gmt_time_string(start_time_str,
  17040. sizeof(start_time_str) - 1,
  17041. &start_time);
  17042. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17043. mg_snprintf(NULL,
  17044. NULL,
  17045. block,
  17046. sizeof(block),
  17047. "%s%s\"time\" : {%s"
  17048. "\"uptime\" : %.0f,%s"
  17049. "\"start\" : \"%s\",%s"
  17050. "\"now\" : \"%s\"%s"
  17051. "}",
  17052. (connection_info_length > 1 ? "," : ""),
  17053. eol,
  17054. eol,
  17055. difftime(now, start_time),
  17056. eol,
  17057. start_time_str,
  17058. eol,
  17059. now_str,
  17060. eol);
  17061. connection_info_length += mg_str_append(&buffer, end, block);
  17062. }
  17063. /* Remote user name */
  17064. if ((ri->remote_user) && (state < 9)) {
  17065. mg_snprintf(NULL,
  17066. NULL,
  17067. block,
  17068. sizeof(block),
  17069. "%s%s\"user\" : {%s"
  17070. "\"name\" : \"%s\",%s"
  17071. "}",
  17072. (connection_info_length > 1 ? "," : ""),
  17073. eol,
  17074. eol,
  17075. ri->remote_user,
  17076. eol);
  17077. connection_info_length += mg_str_append(&buffer, end, block);
  17078. }
  17079. /* Data block */
  17080. if (state >= 3) {
  17081. mg_snprintf(NULL,
  17082. NULL,
  17083. block,
  17084. sizeof(block),
  17085. "%s%s\"data\" : {%s"
  17086. "\"read\" : %" INT64_FMT ",%s"
  17087. "\"written\" : %" INT64_FMT "%s"
  17088. "}",
  17089. (connection_info_length > 1 ? "," : ""),
  17090. eol,
  17091. eol,
  17092. conn->consumed_content,
  17093. eol,
  17094. conn->num_bytes_sent,
  17095. eol);
  17096. connection_info_length += mg_str_append(&buffer, end, block);
  17097. }
  17098. /* State */
  17099. mg_snprintf(NULL,
  17100. NULL,
  17101. block,
  17102. sizeof(block),
  17103. "%s%s\"state\" : \"%s\"",
  17104. (connection_info_length > 1 ? "," : ""),
  17105. eol,
  17106. state_str);
  17107. connection_info_length += mg_str_append(&buffer, end, block);
  17108. /* Terminate string */
  17109. if (append_eoobj) {
  17110. strcat(append_eoobj, eoobj);
  17111. }
  17112. connection_info_length += sizeof(eoobj) - 1;
  17113. return (int)connection_info_length;
  17114. }
  17115. #endif
  17116. /* Initialize this library. This function does not need to be thread safe.
  17117. */
  17118. unsigned
  17119. mg_init_library(unsigned features)
  17120. {
  17121. #if !defined(NO_SSL)
  17122. char ebuf[128];
  17123. #endif
  17124. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17125. unsigned features_inited = features_to_init;
  17126. if (mg_init_library_called <= 0) {
  17127. /* Not initialized yet */
  17128. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17129. return 0;
  17130. }
  17131. }
  17132. mg_global_lock();
  17133. if (mg_init_library_called <= 0) {
  17134. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17135. /* Fatal error - abort start. However, this situation should
  17136. * never occur in practice. */
  17137. mg_global_unlock();
  17138. return 0;
  17139. }
  17140. #if defined(_WIN32)
  17141. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  17142. #else
  17143. pthread_mutexattr_init(&pthread_mutex_attr);
  17144. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17145. #endif
  17146. #if defined(USE_LUA)
  17147. lua_init_optional_libraries();
  17148. #endif
  17149. }
  17150. mg_global_unlock();
  17151. #if !defined(NO_SSL)
  17152. if (features_to_init & MG_FEATURES_SSL) {
  17153. if (!mg_ssl_initialized) {
  17154. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17155. mg_ssl_initialized = 1;
  17156. } else {
  17157. (void)ebuf;
  17158. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17159. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17160. }
  17161. } else {
  17162. /* ssl already initialized */
  17163. }
  17164. }
  17165. #endif
  17166. /* Start WinSock for Windows */
  17167. mg_global_lock();
  17168. if (mg_init_library_called <= 0) {
  17169. #if defined(_WIN32)
  17170. WSADATA data;
  17171. WSAStartup(MAKEWORD(2, 2), &data);
  17172. #endif /* _WIN32 */
  17173. mg_init_library_called = 1;
  17174. } else {
  17175. mg_init_library_called++;
  17176. }
  17177. mg_global_unlock();
  17178. return features_inited;
  17179. }
  17180. /* Un-initialize this library. */
  17181. unsigned
  17182. mg_exit_library(void)
  17183. {
  17184. if (mg_init_library_called <= 0) {
  17185. return 0;
  17186. }
  17187. mg_global_lock();
  17188. mg_init_library_called--;
  17189. if (mg_init_library_called == 0) {
  17190. #if defined(_WIN32)
  17191. (void)WSACleanup();
  17192. #endif /* _WIN32 */
  17193. #if !defined(NO_SSL)
  17194. if (mg_ssl_initialized) {
  17195. uninitialize_ssl();
  17196. mg_ssl_initialized = 0;
  17197. }
  17198. #endif
  17199. #if defined(_WIN32)
  17200. (void)pthread_mutex_destroy(&global_log_file_lock);
  17201. #else
  17202. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17203. #endif
  17204. (void)pthread_key_delete(sTlsKey);
  17205. #if defined(USE_LUA)
  17206. lua_exit_optional_libraries();
  17207. #endif
  17208. mg_global_unlock();
  17209. (void)pthread_mutex_destroy(&global_lock_mutex);
  17210. return 1;
  17211. }
  17212. mg_global_unlock();
  17213. return 1;
  17214. }
  17215. /* End of civetweb.c */