civetweb.c 530 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876
  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. #endif
  2090. #if !defined(NO_SSL)
  2091. STRICT_HTTPS_MAX_AGE,
  2092. #endif
  2093. ADDITIONAL_HEADER,
  2094. ALLOW_INDEX_SCRIPT_SUB_RES,
  2095. #if defined(DAEMONIZE)
  2096. ENABLE_DAEMONIZE,
  2097. #endif
  2098. NUM_OPTIONS
  2099. };
  2100. /* Config option name, config types, default value.
  2101. * Must be in the same order as the enum const above.
  2102. */
  2103. static const struct mg_option config_options[] = {
  2104. /* Once for each server */
  2105. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2106. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2107. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2108. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2109. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2110. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2111. {"max_connections", MG_CONFIG_TYPE_NUMBER, "100"},
  2112. #if defined(__linux__)
  2113. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2114. #endif
  2115. #if defined(_WIN32)
  2116. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2117. #endif
  2118. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2119. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2120. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2121. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2122. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2123. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2124. #if defined(USE_WEBSOCKET)
  2125. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2126. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2127. #endif
  2128. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2129. #if defined(USE_LUA)
  2130. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2131. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2132. #endif
  2133. #if defined(USE_TIMERS)
  2134. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2135. #endif
  2136. /* Once for each domain */
  2137. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2138. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2139. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2140. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2141. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2142. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2143. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2144. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2145. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2146. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2147. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2148. {"index_files",
  2149. MG_CONFIG_TYPE_STRING_LIST,
  2150. #if defined(USE_LUA)
  2151. "index.xhtml,index.html,index.htm,"
  2152. "index.lp,index.lsp,index.lua,index.cgi,"
  2153. "index.shtml,index.php"},
  2154. #else
  2155. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2156. #endif
  2157. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2158. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2159. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2160. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2161. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2162. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2163. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2164. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2165. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2166. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2167. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2168. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2169. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2170. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2171. #if defined(USE_LUA)
  2172. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2173. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2174. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2175. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2176. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2177. #endif
  2178. #endif
  2179. #if defined(USE_DUKTAPE)
  2180. /* The support for duktape is still in alpha version state.
  2181. * The name of this config option might change. */
  2182. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2183. #endif
  2184. #if defined(USE_WEBSOCKET)
  2185. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2186. #endif
  2187. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2188. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2189. #endif
  2190. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2191. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2192. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2193. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2194. #if !defined(NO_CACHING)
  2195. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2196. #endif
  2197. #if !defined(NO_SSL)
  2198. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2199. #endif
  2200. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2201. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2202. #if defined(DAEMONIZE)
  2203. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2204. #endif
  2205. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2206. /* Check if the config_options and the corresponding enum have compatible
  2207. * sizes. */
  2208. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2209. == (NUM_OPTIONS + 1),
  2210. "config_options and enum not sync");
  2211. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2212. struct mg_handler_info {
  2213. /* Name/Pattern of the URI. */
  2214. char *uri;
  2215. size_t uri_len;
  2216. /* handler type */
  2217. int handler_type;
  2218. /* Handler for http/https or authorization requests. */
  2219. mg_request_handler handler;
  2220. unsigned int refcount;
  2221. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2222. pthread_cond_t
  2223. refcount_cond; /* Signaled when handler refcount is decremented */
  2224. /* Handler for ws/wss (websocket) requests. */
  2225. mg_websocket_connect_handler connect_handler;
  2226. mg_websocket_ready_handler ready_handler;
  2227. mg_websocket_data_handler data_handler;
  2228. mg_websocket_close_handler close_handler;
  2229. /* accepted subprotocols for ws/wss requests. */
  2230. struct mg_websocket_subprotocols *subprotocols;
  2231. /* Handler for authorization requests */
  2232. mg_authorization_handler auth_handler;
  2233. /* User supplied argument for the handler function. */
  2234. void *cbdata;
  2235. /* next handler in a linked list */
  2236. struct mg_handler_info *next;
  2237. };
  2238. enum {
  2239. CONTEXT_INVALID,
  2240. CONTEXT_SERVER,
  2241. CONTEXT_HTTP_CLIENT,
  2242. CONTEXT_WS_CLIENT
  2243. };
  2244. struct mg_domain_context {
  2245. SSL_CTX *ssl_ctx; /* SSL context */
  2246. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2247. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2248. /* Server nonce */
  2249. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2250. unsigned long nonce_count; /* Used nonces, used for authentication */
  2251. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2252. /* linked list of shared lua websockets */
  2253. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2254. #endif
  2255. /* Linked list of domains */
  2256. struct mg_domain_context *next;
  2257. };
  2258. struct mg_context {
  2259. /* Part 1 - Physical context:
  2260. * This holds threads, ports, timeouts, ...
  2261. * set for the entire server, independent from the
  2262. * addressed hostname.
  2263. */
  2264. /* Connection related */
  2265. int context_type; /* See CONTEXT_* above */
  2266. struct socket *listening_sockets;
  2267. struct mg_pollfd *listening_socket_fds;
  2268. unsigned int num_listening_sockets;
  2269. struct mg_connection *worker_connections; /* The connection struct, pre-
  2270. * allocated for each worker */
  2271. #if defined(USE_SERVER_STATS)
  2272. int active_connections;
  2273. int max_connections;
  2274. int64_t total_connections;
  2275. int64_t total_requests;
  2276. int64_t total_data_read;
  2277. int64_t total_data_written;
  2278. #endif
  2279. /* Thread related */
  2280. volatile int stop_flag; /* Should we stop event loop */
  2281. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2282. pthread_t masterthreadid; /* The master thread ID */
  2283. unsigned int
  2284. cfg_worker_threads; /* The number of configured worker threads. */
  2285. pthread_t *worker_threadids; /* The worker thread IDs */
  2286. /* Connection to thread dispatching */
  2287. #if defined(ALTERNATIVE_QUEUE)
  2288. struct socket *client_socks;
  2289. void **client_wait_events;
  2290. #else
  2291. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2292. volatile int sq_head; /* Head of the socket queue */
  2293. volatile int sq_tail; /* Tail of the socket queue */
  2294. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2295. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2296. #endif
  2297. /* Memory related */
  2298. unsigned int max_request_size; /* The max request size */
  2299. #if defined(USE_SERVER_STATS)
  2300. struct mg_memory_stat ctx_memory;
  2301. #endif
  2302. /* Operating system related */
  2303. char *systemName; /* What operating system is running */
  2304. time_t start_time; /* Server start time, used for authentication
  2305. * and for diagnstics. */
  2306. #if defined(USE_TIMERS)
  2307. struct ttimers *timers;
  2308. #endif
  2309. /* Lua specific: Background operations and shared websockets */
  2310. #if defined(USE_LUA)
  2311. void *lua_background_state;
  2312. #endif
  2313. /* Server nonce */
  2314. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2315. /* Server callbacks */
  2316. struct mg_callbacks callbacks; /* User-defined callback function */
  2317. void *user_data; /* User-defined data */
  2318. /* Part 2 - Logical domain:
  2319. * This holds hostname, TLS certificate, document root, ...
  2320. * set for a domain hosted at the server.
  2321. * There may be multiple domains hosted at one physical server.
  2322. * The default domain "dd" is the first element of a list of
  2323. * domains.
  2324. */
  2325. struct mg_domain_context dd; /* default domain */
  2326. };
  2327. #if defined(USE_SERVER_STATS)
  2328. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2329. static struct mg_memory_stat *
  2330. get_memory_stat(struct mg_context *ctx)
  2331. {
  2332. if (ctx) {
  2333. return &(ctx->ctx_memory);
  2334. }
  2335. return &mg_common_memory;
  2336. }
  2337. #endif
  2338. enum {
  2339. CONNECTION_TYPE_INVALID,
  2340. CONNECTION_TYPE_REQUEST,
  2341. CONNECTION_TYPE_RESPONSE
  2342. };
  2343. struct mg_connection {
  2344. int connection_type; /* see CONNECTION_TYPE_* above */
  2345. struct mg_request_info request_info;
  2346. struct mg_response_info response_info;
  2347. struct mg_context *phys_ctx;
  2348. struct mg_domain_context *dom_ctx;
  2349. #if defined(USE_SERVER_STATS)
  2350. int conn_state; /* 0 = undef, numerical value may change in different
  2351. * versions. For the current definition, see
  2352. * mg_get_connection_info_impl */
  2353. #endif
  2354. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2355. SSL *ssl; /* SSL descriptor */
  2356. struct socket client; /* Connected client */
  2357. time_t conn_birth_time; /* Time (wall clock) when connection was
  2358. * established */
  2359. struct timespec req_time; /* Time (since system start) when the request
  2360. * was received */
  2361. int64_t num_bytes_sent; /* Total bytes sent to client */
  2362. int64_t content_len; /* How many bytes of content can be read
  2363. * !is_chunked: Content-Length header value
  2364. * or -1 (until connection closed,
  2365. * not allowed for a request)
  2366. * is_chunked: >= 0, appended gradually
  2367. */
  2368. int64_t consumed_content; /* How many bytes of content have been read */
  2369. int is_chunked; /* Transfer-Encoding is chunked:
  2370. * 0 = not chunked,
  2371. * 1 = chunked, not yet, or some data read,
  2372. * 2 = chunked, has error,
  2373. * 3 = chunked, all data read except trailer,
  2374. * 4 = chunked, all data read
  2375. */
  2376. char *buf; /* Buffer for received data */
  2377. char *path_info; /* PATH_INFO part of the URL */
  2378. int must_close; /* 1 if connection must be closed */
  2379. int accept_gzip; /* 1 if gzip encoding is accepted */
  2380. int in_error_handler; /* 1 if in handler for user defined error
  2381. * pages */
  2382. #if defined(USE_WEBSOCKET)
  2383. int in_websocket_handling; /* 1 if in read_websocket */
  2384. #endif
  2385. int handled_requests; /* Number of requests handled by this connection
  2386. */
  2387. int buf_size; /* Buffer size */
  2388. int request_len; /* Size of the request + headers in a buffer */
  2389. int data_len; /* Total size of data in a buffer */
  2390. int status_code; /* HTTP reply status code, e.g. 200 */
  2391. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2392. * throttle */
  2393. time_t last_throttle_time; /* Last time throttled data was sent */
  2394. int last_throttle_bytes; /* Bytes sent this second */
  2395. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2396. * atomic transmissions for websockets */
  2397. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2398. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2399. #endif
  2400. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2401. * for quick access */
  2402. };
  2403. /* Directory entry */
  2404. struct de {
  2405. struct mg_connection *conn;
  2406. char *file_name;
  2407. struct mg_file_stat file;
  2408. };
  2409. #if defined(USE_WEBSOCKET)
  2410. static int is_websocket_protocol(const struct mg_connection *conn);
  2411. #else
  2412. #define is_websocket_protocol(conn) (0)
  2413. #endif
  2414. #define mg_cry_internal(conn, fmt, ...) \
  2415. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2416. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2417. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2418. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2419. struct mg_context *ctx,
  2420. const char *func,
  2421. unsigned line,
  2422. const char *fmt,
  2423. ...) PRINTF_ARGS(5, 6);
  2424. #if !defined(NO_THREAD_NAME)
  2425. #if defined(_WIN32) && defined(_MSC_VER)
  2426. /* Set the thread name for debugging purposes in Visual Studio
  2427. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2428. */
  2429. #pragma pack(push, 8)
  2430. typedef struct tagTHREADNAME_INFO {
  2431. DWORD dwType; /* Must be 0x1000. */
  2432. LPCSTR szName; /* Pointer to name (in user addr space). */
  2433. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2434. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2435. } THREADNAME_INFO;
  2436. #pragma pack(pop)
  2437. #elif defined(__linux__)
  2438. #include <sys/prctl.h>
  2439. #include <sys/sendfile.h>
  2440. #if defined(ALTERNATIVE_QUEUE)
  2441. #include <sys/eventfd.h>
  2442. #endif /* ALTERNATIVE_QUEUE */
  2443. #if defined(ALTERNATIVE_QUEUE)
  2444. static void *
  2445. event_create(void)
  2446. {
  2447. int evhdl = eventfd(0, EFD_CLOEXEC);
  2448. int *ret;
  2449. if (evhdl == -1) {
  2450. /* Linux uses -1 on error, Windows NULL. */
  2451. /* However, Linux does not return 0 on success either. */
  2452. return 0;
  2453. }
  2454. ret = (int *)mg_malloc(sizeof(int));
  2455. if (ret) {
  2456. *ret = evhdl;
  2457. } else {
  2458. (void)close(evhdl);
  2459. }
  2460. return (void *)ret;
  2461. }
  2462. static int
  2463. event_wait(void *eventhdl)
  2464. {
  2465. uint64_t u;
  2466. int evhdl, s;
  2467. if (!eventhdl) {
  2468. /* error */
  2469. return 0;
  2470. }
  2471. evhdl = *(int *)eventhdl;
  2472. s = (int)read(evhdl, &u, sizeof(u));
  2473. if (s != sizeof(u)) {
  2474. /* error */
  2475. return 0;
  2476. }
  2477. (void)u; /* the value is not required */
  2478. return 1;
  2479. }
  2480. static int
  2481. event_signal(void *eventhdl)
  2482. {
  2483. uint64_t u = 1;
  2484. int evhdl, s;
  2485. if (!eventhdl) {
  2486. /* error */
  2487. return 0;
  2488. }
  2489. evhdl = *(int *)eventhdl;
  2490. s = (int)write(evhdl, &u, sizeof(u));
  2491. if (s != sizeof(u)) {
  2492. /* error */
  2493. return 0;
  2494. }
  2495. return 1;
  2496. }
  2497. static void
  2498. event_destroy(void *eventhdl)
  2499. {
  2500. int evhdl;
  2501. if (!eventhdl) {
  2502. /* error */
  2503. return;
  2504. }
  2505. evhdl = *(int *)eventhdl;
  2506. close(evhdl);
  2507. mg_free(eventhdl);
  2508. }
  2509. #endif
  2510. #endif
  2511. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2512. struct posix_event {
  2513. pthread_mutex_t mutex;
  2514. pthread_cond_t cond;
  2515. int signaled;
  2516. };
  2517. static void *
  2518. event_create(void)
  2519. {
  2520. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2521. if (ret == 0) {
  2522. /* out of memory */
  2523. return 0;
  2524. }
  2525. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2526. /* pthread mutex not available */
  2527. mg_free(ret);
  2528. return 0;
  2529. }
  2530. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2531. /* pthread cond not available */
  2532. pthread_mutex_destroy(&(ret->mutex));
  2533. mg_free(ret);
  2534. return 0;
  2535. }
  2536. ret->signaled = 0;
  2537. return (void *)ret;
  2538. }
  2539. static int
  2540. event_wait(void *eventhdl)
  2541. {
  2542. struct posix_event *ev = (struct posix_event *)eventhdl;
  2543. pthread_mutex_lock(&(ev->mutex));
  2544. while (!ev->signaled) {
  2545. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2546. }
  2547. ev->signaled = 0;
  2548. pthread_mutex_unlock(&(ev->mutex));
  2549. return 1;
  2550. }
  2551. static int
  2552. event_signal(void *eventhdl)
  2553. {
  2554. struct posix_event *ev = (struct posix_event *)eventhdl;
  2555. pthread_mutex_lock(&(ev->mutex));
  2556. pthread_cond_signal(&(ev->cond));
  2557. ev->signaled = 1;
  2558. pthread_mutex_unlock(&(ev->mutex));
  2559. return 1;
  2560. }
  2561. static void
  2562. event_destroy(void *eventhdl)
  2563. {
  2564. struct posix_event *ev = (struct posix_event *)eventhdl;
  2565. pthread_cond_destroy(&(ev->cond));
  2566. pthread_mutex_destroy(&(ev->mutex));
  2567. mg_free(ev);
  2568. }
  2569. #endif
  2570. static void
  2571. mg_set_thread_name(const char *name)
  2572. {
  2573. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2574. mg_snprintf(
  2575. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2576. #if defined(_WIN32)
  2577. #if defined(_MSC_VER)
  2578. /* Windows and Visual Studio Compiler */
  2579. __try {
  2580. THREADNAME_INFO info;
  2581. info.dwType = 0x1000;
  2582. info.szName = threadName;
  2583. info.dwThreadID = ~0U;
  2584. info.dwFlags = 0;
  2585. RaiseException(0x406D1388,
  2586. 0,
  2587. sizeof(info) / sizeof(ULONG_PTR),
  2588. (ULONG_PTR *)&info);
  2589. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2590. }
  2591. #elif defined(__MINGW32__)
  2592. /* No option known to set thread name for MinGW */
  2593. #endif
  2594. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2595. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2596. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2597. #if defined(__MACH__)
  2598. /* OS X only current thread name can be changed */
  2599. (void)pthread_setname_np(threadName);
  2600. #else
  2601. (void)pthread_setname_np(pthread_self(), threadName);
  2602. #endif
  2603. #elif defined(__linux__)
  2604. /* on linux we can use the old prctl function */
  2605. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2606. #endif
  2607. }
  2608. #else /* !defined(NO_THREAD_NAME) */
  2609. void
  2610. mg_set_thread_name(const char *threadName)
  2611. {
  2612. }
  2613. #endif
  2614. #if defined(MG_LEGACY_INTERFACE)
  2615. const char **
  2616. mg_get_valid_option_names(void)
  2617. {
  2618. /* This function is deprecated. Use mg_get_valid_options instead. */
  2619. static const char
  2620. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2621. int i;
  2622. for (i = 0; config_options[i].name != NULL; i++) {
  2623. data[i * 2] = config_options[i].name;
  2624. data[i * 2 + 1] = config_options[i].default_value;
  2625. }
  2626. return data;
  2627. }
  2628. #endif
  2629. const struct mg_option *
  2630. mg_get_valid_options(void)
  2631. {
  2632. return config_options;
  2633. }
  2634. /* Do not open file (used in is_file_in_memory) */
  2635. #define MG_FOPEN_MODE_NONE (0)
  2636. /* Open file for read only access */
  2637. #define MG_FOPEN_MODE_READ (1)
  2638. /* Open file for writing, create and overwrite */
  2639. #define MG_FOPEN_MODE_WRITE (2)
  2640. /* Open file for writing, create and append */
  2641. #define MG_FOPEN_MODE_APPEND (4)
  2642. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2643. * output filep and return 1, otherwise return 0 and don't modify anything.
  2644. */
  2645. static int
  2646. open_file_in_memory(const struct mg_connection *conn,
  2647. const char *path,
  2648. struct mg_file *filep,
  2649. int mode)
  2650. {
  2651. #if defined(MG_USE_OPEN_FILE)
  2652. size_t size = 0;
  2653. const char *buf = NULL;
  2654. if (!conn) {
  2655. return 0;
  2656. }
  2657. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2658. return 0;
  2659. }
  2660. if (conn->phys_ctx->callbacks.open_file) {
  2661. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2662. if (buf != NULL) {
  2663. if (filep == NULL) {
  2664. /* This is a file in memory, but we cannot store the
  2665. * properties
  2666. * now.
  2667. * Called from "is_file_in_memory" function. */
  2668. return 1;
  2669. }
  2670. /* NOTE: override filep->size only on success. Otherwise, it
  2671. * might
  2672. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2673. filep->access.membuf = buf;
  2674. filep->access.fp = NULL;
  2675. /* Size was set by the callback */
  2676. filep->stat.size = size;
  2677. /* Assume the data may change during runtime by setting
  2678. * last_modified = now */
  2679. filep->stat.last_modified = time(NULL);
  2680. filep->stat.is_directory = 0;
  2681. filep->stat.is_gzipped = 0;
  2682. }
  2683. }
  2684. return (buf != NULL);
  2685. #else
  2686. (void)conn;
  2687. (void)path;
  2688. (void)filep;
  2689. (void)mode;
  2690. return 0;
  2691. #endif
  2692. }
  2693. static int
  2694. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2695. {
  2696. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2697. }
  2698. static int
  2699. is_file_opened(const struct mg_file_access *fileacc)
  2700. {
  2701. if (!fileacc) {
  2702. return 0;
  2703. }
  2704. #if defined(MG_USE_OPEN_FILE)
  2705. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2706. #else
  2707. return (fileacc->fp != NULL);
  2708. #endif
  2709. }
  2710. #if !defined(NO_FILESYSTEMS)
  2711. static int mg_stat(const struct mg_connection *conn,
  2712. const char *path,
  2713. struct mg_file_stat *filep);
  2714. /* mg_fopen will open a file either in memory or on the disk.
  2715. * The input parameter path is a string in UTF-8 encoding.
  2716. * The input parameter mode is MG_FOPEN_MODE_*
  2717. * On success, either fp or membuf will be set in the output
  2718. * struct file. All status members will also be set.
  2719. * The function returns 1 on success, 0 on error. */
  2720. static int
  2721. mg_fopen(const struct mg_connection *conn,
  2722. const char *path,
  2723. int mode,
  2724. struct mg_file *filep)
  2725. {
  2726. int found;
  2727. if (!filep) {
  2728. return 0;
  2729. }
  2730. filep->access.fp = NULL;
  2731. #if defined(MG_USE_OPEN_FILE)
  2732. filep->access.membuf = NULL;
  2733. #endif
  2734. if (!is_file_in_memory(conn, path)) {
  2735. /* filep is initialized in mg_stat: all fields with memset to,
  2736. * some fields like size and modification date with values */
  2737. found = mg_stat(conn, path, &(filep->stat));
  2738. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2739. /* file does not exist and will not be created */
  2740. return 0;
  2741. }
  2742. #if defined(_WIN32)
  2743. {
  2744. wchar_t wbuf[W_PATH_MAX];
  2745. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2746. switch (mode) {
  2747. case MG_FOPEN_MODE_READ:
  2748. filep->access.fp = _wfopen(wbuf, L"rb");
  2749. break;
  2750. case MG_FOPEN_MODE_WRITE:
  2751. filep->access.fp = _wfopen(wbuf, L"wb");
  2752. break;
  2753. case MG_FOPEN_MODE_APPEND:
  2754. filep->access.fp = _wfopen(wbuf, L"ab");
  2755. break;
  2756. }
  2757. }
  2758. #else
  2759. /* Linux et al already use unicode. No need to convert. */
  2760. switch (mode) {
  2761. case MG_FOPEN_MODE_READ:
  2762. filep->access.fp = fopen(path, "r");
  2763. break;
  2764. case MG_FOPEN_MODE_WRITE:
  2765. filep->access.fp = fopen(path, "w");
  2766. break;
  2767. case MG_FOPEN_MODE_APPEND:
  2768. filep->access.fp = fopen(path, "a");
  2769. break;
  2770. }
  2771. #endif
  2772. if (!found) {
  2773. /* File did not exist before fopen was called.
  2774. * Maybe it has been created now. Get stat info
  2775. * like creation time now. */
  2776. found = mg_stat(conn, path, &(filep->stat));
  2777. (void)found;
  2778. }
  2779. /* file is on disk */
  2780. return (filep->access.fp != NULL);
  2781. } else {
  2782. #if defined(MG_USE_OPEN_FILE)
  2783. /* is_file_in_memory returned true */
  2784. if (open_file_in_memory(conn, path, filep, mode)) {
  2785. /* file is in memory */
  2786. return (filep->access.membuf != NULL);
  2787. }
  2788. #endif
  2789. }
  2790. /* Open failed */
  2791. return 0;
  2792. }
  2793. /* return 0 on success, just like fclose */
  2794. static int
  2795. mg_fclose(struct mg_file_access *fileacc)
  2796. {
  2797. int ret = -1;
  2798. if (fileacc != NULL) {
  2799. if (fileacc->fp != NULL) {
  2800. ret = fclose(fileacc->fp);
  2801. #if defined(MG_USE_OPEN_FILE)
  2802. } else if (fileacc->membuf != NULL) {
  2803. ret = 0;
  2804. #endif
  2805. }
  2806. /* reset all members of fileacc */
  2807. memset(fileacc, 0, sizeof(*fileacc));
  2808. }
  2809. return ret;
  2810. }
  2811. #endif /* NO_FILESYSTEMS */
  2812. static void
  2813. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2814. {
  2815. for (; *src != '\0' && n > 1; n--) {
  2816. *dst++ = *src++;
  2817. }
  2818. *dst = '\0';
  2819. }
  2820. static int
  2821. lowercase(const char *s)
  2822. {
  2823. return tolower((unsigned char)*s);
  2824. }
  2825. int
  2826. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2827. {
  2828. int diff = 0;
  2829. if (len > 0) {
  2830. do {
  2831. diff = lowercase(s1++) - lowercase(s2++);
  2832. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2833. }
  2834. return diff;
  2835. }
  2836. int
  2837. mg_strcasecmp(const char *s1, const char *s2)
  2838. {
  2839. int diff;
  2840. do {
  2841. diff = lowercase(s1++) - lowercase(s2++);
  2842. } while (diff == 0 && s1[-1] != '\0');
  2843. return diff;
  2844. }
  2845. static char *
  2846. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2847. {
  2848. char *p;
  2849. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2850. * defined */
  2851. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2852. mg_strlcpy(p, ptr, len + 1);
  2853. }
  2854. return p;
  2855. }
  2856. static char *
  2857. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2858. {
  2859. return mg_strndup_ctx(str, strlen(str), ctx);
  2860. }
  2861. static char *
  2862. mg_strdup(const char *str)
  2863. {
  2864. return mg_strndup_ctx(str, strlen(str), NULL);
  2865. }
  2866. static const char *
  2867. mg_strcasestr(const char *big_str, const char *small_str)
  2868. {
  2869. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2870. if (big_len >= small_len) {
  2871. for (i = 0; i <= (big_len - small_len); i++) {
  2872. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2873. return big_str + i;
  2874. }
  2875. }
  2876. }
  2877. return NULL;
  2878. }
  2879. /* Return null terminated string of given maximum length.
  2880. * Report errors if length is exceeded. */
  2881. static void
  2882. mg_vsnprintf(const struct mg_connection *conn,
  2883. int *truncated,
  2884. char *buf,
  2885. size_t buflen,
  2886. const char *fmt,
  2887. va_list ap)
  2888. {
  2889. int n, ok;
  2890. if (buflen == 0) {
  2891. if (truncated) {
  2892. *truncated = 1;
  2893. }
  2894. return;
  2895. }
  2896. #if defined(__clang__)
  2897. #pragma clang diagnostic push
  2898. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2899. /* Using fmt as a non-literal is intended here, since it is mostly called
  2900. * indirectly by mg_snprintf */
  2901. #endif
  2902. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2903. ok = (n >= 0) && ((size_t)n < buflen);
  2904. #if defined(__clang__)
  2905. #pragma clang diagnostic pop
  2906. #endif
  2907. if (ok) {
  2908. if (truncated) {
  2909. *truncated = 0;
  2910. }
  2911. } else {
  2912. if (truncated) {
  2913. *truncated = 1;
  2914. }
  2915. mg_cry_internal(conn,
  2916. "truncating vsnprintf buffer: [%.*s]",
  2917. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2918. buf);
  2919. n = (int)buflen - 1;
  2920. }
  2921. buf[n] = '\0';
  2922. }
  2923. static void
  2924. mg_snprintf(const struct mg_connection *conn,
  2925. int *truncated,
  2926. char *buf,
  2927. size_t buflen,
  2928. const char *fmt,
  2929. ...)
  2930. {
  2931. va_list ap;
  2932. va_start(ap, fmt);
  2933. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2934. va_end(ap);
  2935. }
  2936. static int
  2937. get_option_index(const char *name)
  2938. {
  2939. int i;
  2940. for (i = 0; config_options[i].name != NULL; i++) {
  2941. if (strcmp(config_options[i].name, name) == 0) {
  2942. return i;
  2943. }
  2944. }
  2945. return -1;
  2946. }
  2947. const char *
  2948. mg_get_option(const struct mg_context *ctx, const char *name)
  2949. {
  2950. int i;
  2951. if ((i = get_option_index(name)) == -1) {
  2952. return NULL;
  2953. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2954. return "";
  2955. } else {
  2956. return ctx->dd.config[i];
  2957. }
  2958. }
  2959. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2960. struct mg_context *
  2961. mg_get_context(const struct mg_connection *conn)
  2962. {
  2963. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2964. }
  2965. void *
  2966. mg_get_user_data(const struct mg_context *ctx)
  2967. {
  2968. return (ctx == NULL) ? NULL : ctx->user_data;
  2969. }
  2970. void *
  2971. mg_get_thread_pointer(const struct mg_connection *conn)
  2972. {
  2973. /* both methods should return the same pointer */
  2974. if (conn) {
  2975. /* quick access, in case conn is known */
  2976. return conn->tls_user_ptr;
  2977. } else {
  2978. /* otherwise get pointer from thread local storage (TLS) */
  2979. struct mg_workerTLS *tls =
  2980. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2981. return tls->user_ptr;
  2982. }
  2983. }
  2984. void
  2985. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2986. {
  2987. if (conn != NULL) {
  2988. conn->request_info.conn_data = data;
  2989. }
  2990. }
  2991. void *
  2992. mg_get_user_connection_data(const struct mg_connection *conn)
  2993. {
  2994. if (conn != NULL) {
  2995. return conn->request_info.conn_data;
  2996. }
  2997. return NULL;
  2998. }
  2999. #if defined(MG_LEGACY_INTERFACE)
  3000. /* Deprecated: Use mg_get_server_ports instead. */
  3001. size_t
  3002. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3003. {
  3004. size_t i;
  3005. if (!ctx) {
  3006. return 0;
  3007. }
  3008. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3009. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3010. ports[i] =
  3011. #if defined(USE_IPV6)
  3012. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3013. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3014. :
  3015. #endif
  3016. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3017. }
  3018. return i;
  3019. }
  3020. #endif
  3021. int
  3022. mg_get_server_ports(const struct mg_context *ctx,
  3023. int size,
  3024. struct mg_server_port *ports)
  3025. {
  3026. int i, cnt = 0;
  3027. if (size <= 0) {
  3028. return -1;
  3029. }
  3030. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3031. if (!ctx) {
  3032. return -1;
  3033. }
  3034. if (!ctx->listening_sockets) {
  3035. return -1;
  3036. }
  3037. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3038. ports[cnt].port =
  3039. #if defined(USE_IPV6)
  3040. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3041. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3042. :
  3043. #endif
  3044. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3045. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3046. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3047. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3048. /* IPv4 */
  3049. ports[cnt].protocol = 1;
  3050. cnt++;
  3051. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3052. /* IPv6 */
  3053. ports[cnt].protocol = 3;
  3054. cnt++;
  3055. }
  3056. }
  3057. return cnt;
  3058. }
  3059. static void
  3060. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3061. {
  3062. buf[0] = '\0';
  3063. if (!usa) {
  3064. return;
  3065. }
  3066. if (usa->sa.sa_family == AF_INET) {
  3067. getnameinfo(&usa->sa,
  3068. sizeof(usa->sin),
  3069. buf,
  3070. (unsigned)len,
  3071. NULL,
  3072. 0,
  3073. NI_NUMERICHOST);
  3074. }
  3075. #if defined(USE_IPV6)
  3076. else if (usa->sa.sa_family == AF_INET6) {
  3077. getnameinfo(&usa->sa,
  3078. sizeof(usa->sin6),
  3079. buf,
  3080. (unsigned)len,
  3081. NULL,
  3082. 0,
  3083. NI_NUMERICHOST);
  3084. }
  3085. #endif
  3086. }
  3087. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3088. * included in all responses other than 100, 101, 5xx. */
  3089. static void
  3090. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3091. {
  3092. #if !defined(REENTRANT_TIME)
  3093. struct tm *tm;
  3094. tm = ((t != NULL) ? gmtime(t) : NULL);
  3095. if (tm != NULL) {
  3096. #else
  3097. struct tm _tm;
  3098. struct tm *tm = &_tm;
  3099. if (t != NULL) {
  3100. gmtime_r(t, tm);
  3101. #endif
  3102. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3103. } else {
  3104. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3105. buf[buf_len - 1] = '\0';
  3106. }
  3107. }
  3108. /* difftime for struct timespec. Return value is in seconds. */
  3109. static double
  3110. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3111. {
  3112. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3113. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3114. }
  3115. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3116. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3117. const char *func,
  3118. unsigned line,
  3119. const char *fmt,
  3120. va_list ap);
  3121. #include "external_mg_cry_internal_impl.inl"
  3122. #elif !defined(NO_FILESYSTEMS)
  3123. /* Print error message to the opened error log stream. */
  3124. static void
  3125. mg_cry_internal_impl(const struct mg_connection *conn,
  3126. const char *func,
  3127. unsigned line,
  3128. const char *fmt,
  3129. va_list ap)
  3130. {
  3131. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3132. struct mg_file fi;
  3133. time_t timestamp;
  3134. /* Unused, in the RELEASE build */
  3135. (void)func;
  3136. (void)line;
  3137. #if defined(GCC_DIAGNOSTIC)
  3138. #pragma GCC diagnostic push
  3139. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3140. #endif
  3141. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3142. #if defined(GCC_DIAGNOSTIC)
  3143. #pragma GCC diagnostic pop
  3144. #endif
  3145. buf[sizeof(buf) - 1] = 0;
  3146. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3147. if (!conn) {
  3148. puts(buf);
  3149. return;
  3150. }
  3151. /* Do not lock when getting the callback value, here and below.
  3152. * I suppose this is fine, since function cannot disappear in the
  3153. * same way string option can. */
  3154. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3155. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3156. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3157. if (mg_fopen(conn,
  3158. conn->dom_ctx->config[ERROR_LOG_FILE],
  3159. MG_FOPEN_MODE_APPEND,
  3160. &fi)
  3161. == 0) {
  3162. fi.access.fp = NULL;
  3163. }
  3164. } else {
  3165. fi.access.fp = NULL;
  3166. }
  3167. if (fi.access.fp != NULL) {
  3168. flockfile(fi.access.fp);
  3169. timestamp = time(NULL);
  3170. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3171. fprintf(fi.access.fp,
  3172. "[%010lu] [error] [client %s] ",
  3173. (unsigned long)timestamp,
  3174. src_addr);
  3175. if (conn->request_info.request_method != NULL) {
  3176. fprintf(fi.access.fp,
  3177. "%s %s: ",
  3178. conn->request_info.request_method,
  3179. conn->request_info.request_uri
  3180. ? conn->request_info.request_uri
  3181. : "");
  3182. }
  3183. fprintf(fi.access.fp, "%s", buf);
  3184. fputc('\n', fi.access.fp);
  3185. fflush(fi.access.fp);
  3186. funlockfile(fi.access.fp);
  3187. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3188. * mg_cry here anyway ;-) */
  3189. }
  3190. }
  3191. }
  3192. #else
  3193. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3194. #endif /* Externally provided function */
  3195. /* Construct fake connection structure. Used for logging, if connection
  3196. * is not applicable at the moment of logging. */
  3197. static struct mg_connection *
  3198. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3199. {
  3200. static const struct mg_connection conn_zero = {0};
  3201. *fc = conn_zero;
  3202. fc->phys_ctx = ctx;
  3203. fc->dom_ctx = &(ctx->dd);
  3204. return fc;
  3205. }
  3206. static void
  3207. mg_cry_internal_wrap(const struct mg_connection *conn,
  3208. struct mg_context *ctx,
  3209. const char *func,
  3210. unsigned line,
  3211. const char *fmt,
  3212. ...)
  3213. {
  3214. va_list ap;
  3215. va_start(ap, fmt);
  3216. if (!conn && ctx) {
  3217. struct mg_connection fc;
  3218. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3219. } else {
  3220. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3221. }
  3222. va_end(ap);
  3223. }
  3224. void
  3225. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3226. {
  3227. va_list ap;
  3228. va_start(ap, fmt);
  3229. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3230. va_end(ap);
  3231. }
  3232. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3233. const char *
  3234. mg_version(void)
  3235. {
  3236. return CIVETWEB_VERSION;
  3237. }
  3238. const struct mg_request_info *
  3239. mg_get_request_info(const struct mg_connection *conn)
  3240. {
  3241. if (!conn) {
  3242. return NULL;
  3243. }
  3244. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3245. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3246. char txt[16];
  3247. struct mg_workerTLS *tls =
  3248. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3249. sprintf(txt, "%03i", conn->response_info.status_code);
  3250. if (strlen(txt) == 3) {
  3251. memcpy(tls->txtbuf, txt, 4);
  3252. } else {
  3253. strcpy(tls->txtbuf, "ERR");
  3254. }
  3255. ((struct mg_connection *)conn)->request_info.local_uri =
  3256. ((struct mg_connection *)conn)->request_info.request_uri =
  3257. tls->txtbuf; /* use thread safe buffer */
  3258. ((struct mg_connection *)conn)->request_info.num_headers =
  3259. conn->response_info.num_headers;
  3260. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3261. conn->response_info.http_headers,
  3262. sizeof(conn->response_info.http_headers));
  3263. } else
  3264. #endif
  3265. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3266. return NULL;
  3267. }
  3268. return &conn->request_info;
  3269. }
  3270. const struct mg_response_info *
  3271. mg_get_response_info(const struct mg_connection *conn)
  3272. {
  3273. if (!conn) {
  3274. return NULL;
  3275. }
  3276. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3277. return NULL;
  3278. }
  3279. return &conn->response_info;
  3280. }
  3281. static const char *
  3282. get_proto_name(const struct mg_connection *conn)
  3283. {
  3284. #if defined(__clang__)
  3285. #pragma clang diagnostic push
  3286. #pragma clang diagnostic ignored "-Wunreachable-code"
  3287. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3288. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3289. * unreachable, but splitting into four different #ifdef clauses here is more
  3290. * complicated.
  3291. */
  3292. #endif
  3293. const struct mg_request_info *ri = &conn->request_info;
  3294. const char *proto =
  3295. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3296. : (ri->is_ssl ? "https" : "http"));
  3297. return proto;
  3298. #if defined(__clang__)
  3299. #pragma clang diagnostic pop
  3300. #endif
  3301. }
  3302. int
  3303. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3304. {
  3305. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3306. return -1;
  3307. } else {
  3308. int truncated = 0;
  3309. const struct mg_request_info *ri = &conn->request_info;
  3310. const char *proto = get_proto_name(conn);
  3311. if (ri->local_uri == NULL) {
  3312. return -1;
  3313. }
  3314. if ((ri->request_uri != NULL)
  3315. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3316. /* The request uri is different from the local uri.
  3317. * This is usually if an absolute URI, including server
  3318. * name has been provided. */
  3319. mg_snprintf(conn,
  3320. &truncated,
  3321. buf,
  3322. buflen,
  3323. "%s://%s",
  3324. proto,
  3325. ri->request_uri);
  3326. if (truncated) {
  3327. return -1;
  3328. }
  3329. return 0;
  3330. } else {
  3331. /* The common case is a relative URI, so we have to
  3332. * construct an absolute URI from server name and port */
  3333. #if defined(USE_IPV6)
  3334. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3335. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3336. : htons(conn->client.lsa.sin.sin_port);
  3337. #else
  3338. int port = htons(conn->client.lsa.sin.sin_port);
  3339. #endif
  3340. int def_port = ri->is_ssl ? 443 : 80;
  3341. int auth_domain_check_enabled =
  3342. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3343. && (!mg_strcasecmp(
  3344. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3345. const char *server_domain =
  3346. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3347. char portstr[16];
  3348. char server_ip[48];
  3349. if (port != def_port) {
  3350. sprintf(portstr, ":%u", (unsigned)port);
  3351. } else {
  3352. portstr[0] = 0;
  3353. }
  3354. if (!auth_domain_check_enabled || !server_domain) {
  3355. sockaddr_to_string(server_ip,
  3356. sizeof(server_ip),
  3357. &conn->client.lsa);
  3358. server_domain = server_ip;
  3359. }
  3360. mg_snprintf(conn,
  3361. &truncated,
  3362. buf,
  3363. buflen,
  3364. "%s://%s%s%s",
  3365. proto,
  3366. server_domain,
  3367. portstr,
  3368. ri->local_uri);
  3369. if (truncated) {
  3370. return -1;
  3371. }
  3372. return 0;
  3373. }
  3374. }
  3375. }
  3376. /* Skip the characters until one of the delimiters characters found.
  3377. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3378. * Advance pointer to buffer to the next word. Return found 0-terminated
  3379. * word.
  3380. * Delimiters can be quoted with quotechar. */
  3381. static char *
  3382. skip_quoted(char **buf,
  3383. const char *delimiters,
  3384. const char *whitespace,
  3385. char quotechar)
  3386. {
  3387. char *p, *begin_word, *end_word, *end_whitespace;
  3388. begin_word = *buf;
  3389. end_word = begin_word + strcspn(begin_word, delimiters);
  3390. /* Check for quotechar */
  3391. if (end_word > begin_word) {
  3392. p = end_word - 1;
  3393. while (*p == quotechar) {
  3394. /* While the delimiter is quoted, look for the next delimiter.
  3395. */
  3396. /* This happens, e.g., in calls from parse_auth_header,
  3397. * if the user name contains a " character. */
  3398. /* If there is anything beyond end_word, copy it. */
  3399. if (*end_word != '\0') {
  3400. size_t end_off = strcspn(end_word + 1, delimiters);
  3401. memmove(p, end_word, end_off + 1);
  3402. p += end_off; /* p must correspond to end_word - 1 */
  3403. end_word += end_off + 1;
  3404. } else {
  3405. *p = '\0';
  3406. break;
  3407. }
  3408. }
  3409. for (p++; p < end_word; p++) {
  3410. *p = '\0';
  3411. }
  3412. }
  3413. if (*end_word == '\0') {
  3414. *buf = end_word;
  3415. } else {
  3416. #if defined(GCC_DIAGNOSTIC)
  3417. /* Disable spurious conversion warning for GCC */
  3418. #pragma GCC diagnostic push
  3419. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3420. #endif /* defined(GCC_DIAGNOSTIC) */
  3421. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3422. #if defined(GCC_DIAGNOSTIC)
  3423. #pragma GCC diagnostic pop
  3424. #endif /* defined(GCC_DIAGNOSTIC) */
  3425. for (p = end_word; p < end_whitespace; p++) {
  3426. *p = '\0';
  3427. }
  3428. *buf = end_whitespace;
  3429. }
  3430. return begin_word;
  3431. }
  3432. /* Return HTTP header value, or NULL if not found. */
  3433. static const char *
  3434. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3435. {
  3436. int i;
  3437. for (i = 0; i < num_hdr; i++) {
  3438. if (!mg_strcasecmp(name, hdr[i].name)) {
  3439. return hdr[i].value;
  3440. }
  3441. }
  3442. return NULL;
  3443. }
  3444. #if defined(USE_WEBSOCKET)
  3445. /* Retrieve requested HTTP header multiple values, and return the number of
  3446. * found occurrences */
  3447. static int
  3448. get_req_headers(const struct mg_request_info *ri,
  3449. const char *name,
  3450. const char **output,
  3451. int output_max_size)
  3452. {
  3453. int i;
  3454. int cnt = 0;
  3455. if (ri) {
  3456. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3457. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3458. output[cnt++] = ri->http_headers[i].value;
  3459. }
  3460. }
  3461. }
  3462. return cnt;
  3463. }
  3464. #endif
  3465. const char *
  3466. mg_get_header(const struct mg_connection *conn, const char *name)
  3467. {
  3468. if (!conn) {
  3469. return NULL;
  3470. }
  3471. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3472. return get_header(conn->request_info.http_headers,
  3473. conn->request_info.num_headers,
  3474. name);
  3475. }
  3476. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3477. return get_header(conn->response_info.http_headers,
  3478. conn->response_info.num_headers,
  3479. name);
  3480. }
  3481. return NULL;
  3482. }
  3483. static const char *
  3484. get_http_version(const struct mg_connection *conn)
  3485. {
  3486. if (!conn) {
  3487. return NULL;
  3488. }
  3489. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3490. return conn->request_info.http_version;
  3491. }
  3492. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3493. return conn->response_info.http_version;
  3494. }
  3495. return NULL;
  3496. }
  3497. /* A helper function for traversing a comma separated list of values.
  3498. * It returns a list pointer shifted to the next value, or NULL if the end
  3499. * of the list found.
  3500. * Value is stored in val vector. If value has form "x=y", then eq_val
  3501. * vector is initialized to point to the "y" part, and val vector length
  3502. * is adjusted to point only to "x". */
  3503. static const char *
  3504. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3505. {
  3506. int end;
  3507. reparse:
  3508. if (val == NULL || list == NULL || *list == '\0') {
  3509. /* End of the list */
  3510. return NULL;
  3511. }
  3512. /* Skip over leading LWS */
  3513. while (*list == ' ' || *list == '\t')
  3514. list++;
  3515. val->ptr = list;
  3516. if ((list = strchr(val->ptr, ',')) != NULL) {
  3517. /* Comma found. Store length and shift the list ptr */
  3518. val->len = ((size_t)(list - val->ptr));
  3519. list++;
  3520. } else {
  3521. /* This value is the last one */
  3522. list = val->ptr + strlen(val->ptr);
  3523. val->len = ((size_t)(list - val->ptr));
  3524. }
  3525. /* Adjust length for trailing LWS */
  3526. end = (int)val->len - 1;
  3527. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3528. end--;
  3529. val->len = (size_t)(end) + (size_t)(1);
  3530. if (val->len == 0) {
  3531. /* Ignore any empty entries. */
  3532. goto reparse;
  3533. }
  3534. if (eq_val != NULL) {
  3535. /* Value has form "x=y", adjust pointers and lengths
  3536. * so that val points to "x", and eq_val points to "y". */
  3537. eq_val->len = 0;
  3538. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3539. if (eq_val->ptr != NULL) {
  3540. eq_val->ptr++; /* Skip over '=' character */
  3541. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3542. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3543. }
  3544. }
  3545. return list;
  3546. }
  3547. /* A helper function for checking if a comma separated list of values
  3548. * contains
  3549. * the given option (case insensitvely).
  3550. * 'header' can be NULL, in which case false is returned. */
  3551. static int
  3552. header_has_option(const char *header, const char *option)
  3553. {
  3554. struct vec opt_vec;
  3555. struct vec eq_vec;
  3556. DEBUG_ASSERT(option != NULL);
  3557. DEBUG_ASSERT(option[0] != '\0');
  3558. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3559. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3560. return 1;
  3561. }
  3562. return 0;
  3563. }
  3564. /* Perform case-insensitive match of string against pattern */
  3565. static ptrdiff_t
  3566. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3567. {
  3568. const char *or_str;
  3569. ptrdiff_t i, j, len, res;
  3570. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3571. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3572. return (res > 0) ? res
  3573. : match_prefix(or_str + 1,
  3574. (size_t)((pattern + pattern_len)
  3575. - (or_str + 1)),
  3576. str);
  3577. }
  3578. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3579. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3580. continue;
  3581. } else if (pattern[i] == '$') {
  3582. return (str[j] == '\0') ? j : -1;
  3583. } else if (pattern[i] == '*') {
  3584. i++;
  3585. if (pattern[i] == '*') {
  3586. i++;
  3587. len = strlen(str + j);
  3588. } else {
  3589. len = strcspn(str + j, "/");
  3590. }
  3591. if (i == (ptrdiff_t)pattern_len) {
  3592. return j + len;
  3593. }
  3594. do {
  3595. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3596. } while (res == -1 && len-- > 0);
  3597. return (res == -1) ? -1 : j + res + len;
  3598. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3599. return -1;
  3600. }
  3601. }
  3602. return (ptrdiff_t)j;
  3603. }
  3604. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3605. * This function must tolerate situations when connection info is not
  3606. * set up, for example if request parsing failed. */
  3607. static int
  3608. should_keep_alive(const struct mg_connection *conn)
  3609. {
  3610. const char *http_version;
  3611. const char *header;
  3612. /* First satisfy needs of the server */
  3613. if ((conn == NULL) || conn->must_close) {
  3614. /* Close, if civetweb framework needs to close */
  3615. return 0;
  3616. }
  3617. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3618. /* Close, if keep alive is not enabled */
  3619. return 0;
  3620. }
  3621. /* Check explicit wish of the client */
  3622. header = mg_get_header(conn, "Connection");
  3623. if (header) {
  3624. /* If there is a connection header from the client, obey */
  3625. if (header_has_option(header, "keep-alive")) {
  3626. return 1;
  3627. }
  3628. return 0;
  3629. }
  3630. /* Use default of the standard */
  3631. http_version = get_http_version(conn);
  3632. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3633. /* HTTP 1.1 default is keep alive */
  3634. return 1;
  3635. }
  3636. /* HTTP 1.0 (and earlier) default is to close the connection */
  3637. return 0;
  3638. }
  3639. static int
  3640. should_decode_url(const struct mg_connection *conn)
  3641. {
  3642. if (!conn || !conn->dom_ctx) {
  3643. return 0;
  3644. }
  3645. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3646. }
  3647. static const char *
  3648. suggest_connection_header(const struct mg_connection *conn)
  3649. {
  3650. return should_keep_alive(conn) ? "keep-alive" : "close";
  3651. }
  3652. static int
  3653. send_no_cache_header(struct mg_connection *conn)
  3654. {
  3655. /* Send all current and obsolete cache opt-out directives. */
  3656. return mg_printf(conn,
  3657. "Cache-Control: no-cache, no-store, "
  3658. "must-revalidate, private, max-age=0\r\n"
  3659. "Pragma: no-cache\r\n"
  3660. "Expires: 0\r\n");
  3661. }
  3662. static int
  3663. send_static_cache_header(struct mg_connection *conn)
  3664. {
  3665. #if !defined(NO_CACHING)
  3666. /* Read the server config to check how long a file may be cached.
  3667. * The configuration is in seconds. */
  3668. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3669. if (max_age <= 0) {
  3670. /* 0 means "do not cache". All values <0 are reserved
  3671. * and may be used differently in the future. */
  3672. /* If a file should not be cached, do not only send
  3673. * max-age=0, but also pragmas and Expires headers. */
  3674. return send_no_cache_header(conn);
  3675. }
  3676. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3677. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3678. /* See also https://www.mnot.net/cache_docs/ */
  3679. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3680. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3681. * leap
  3682. * year to 31622400 seconds. For the moment, we just send whatever has
  3683. * been configured, still the behavior for >1 year should be considered
  3684. * as undefined. */
  3685. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3686. #else /* NO_CACHING */
  3687. return send_no_cache_header(conn);
  3688. #endif /* !NO_CACHING */
  3689. }
  3690. static int
  3691. send_additional_header(struct mg_connection *conn)
  3692. {
  3693. int i = 0;
  3694. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3695. #if !defined(NO_SSL)
  3696. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3697. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3698. if (max_age >= 0) {
  3699. i += mg_printf(conn,
  3700. "Strict-Transport-Security: max-age=%u\r\n",
  3701. (unsigned)max_age);
  3702. }
  3703. }
  3704. #endif
  3705. if (header && header[0]) {
  3706. i += mg_printf(conn, "%s\r\n", header);
  3707. }
  3708. return i;
  3709. }
  3710. #if !defined(NO_FILESYSTEMS)
  3711. static void handle_file_based_request(struct mg_connection *conn,
  3712. const char *path,
  3713. struct mg_file *filep);
  3714. #endif /* NO_FILESYSTEMS */
  3715. const char *
  3716. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3717. {
  3718. /* See IANA HTTP status code assignment:
  3719. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3720. */
  3721. switch (response_code) {
  3722. /* RFC2616 Section 10.1 - Informational 1xx */
  3723. case 100:
  3724. return "Continue"; /* RFC2616 Section 10.1.1 */
  3725. case 101:
  3726. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3727. case 102:
  3728. return "Processing"; /* RFC2518 Section 10.1 */
  3729. /* RFC2616 Section 10.2 - Successful 2xx */
  3730. case 200:
  3731. return "OK"; /* RFC2616 Section 10.2.1 */
  3732. case 201:
  3733. return "Created"; /* RFC2616 Section 10.2.2 */
  3734. case 202:
  3735. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3736. case 203:
  3737. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3738. case 204:
  3739. return "No Content"; /* RFC2616 Section 10.2.5 */
  3740. case 205:
  3741. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3742. case 206:
  3743. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3744. case 207:
  3745. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3746. */
  3747. case 208:
  3748. return "Already Reported"; /* RFC5842 Section 7.1 */
  3749. case 226:
  3750. return "IM used"; /* RFC3229 Section 10.4.1 */
  3751. /* RFC2616 Section 10.3 - Redirection 3xx */
  3752. case 300:
  3753. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3754. case 301:
  3755. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3756. case 302:
  3757. return "Found"; /* RFC2616 Section 10.3.3 */
  3758. case 303:
  3759. return "See Other"; /* RFC2616 Section 10.3.4 */
  3760. case 304:
  3761. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3762. case 305:
  3763. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3764. case 307:
  3765. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3766. case 308:
  3767. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3768. /* RFC2616 Section 10.4 - Client Error 4xx */
  3769. case 400:
  3770. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3771. case 401:
  3772. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3773. case 402:
  3774. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3775. case 403:
  3776. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3777. case 404:
  3778. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3779. case 405:
  3780. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3781. case 406:
  3782. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3783. case 407:
  3784. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3785. case 408:
  3786. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3787. case 409:
  3788. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3789. case 410:
  3790. return "Gone"; /* RFC2616 Section 10.4.11 */
  3791. case 411:
  3792. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3793. case 412:
  3794. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3795. case 413:
  3796. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3797. case 414:
  3798. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3799. case 415:
  3800. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3801. case 416:
  3802. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3803. */
  3804. case 417:
  3805. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3806. case 421:
  3807. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3808. case 422:
  3809. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3810. * Section 11.2 */
  3811. case 423:
  3812. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3813. case 424:
  3814. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3815. * Section 11.4 */
  3816. case 426:
  3817. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3818. case 428:
  3819. return "Precondition Required"; /* RFC 6585, Section 3 */
  3820. case 429:
  3821. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3822. case 431:
  3823. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3824. case 451:
  3825. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3826. * Section 3 */
  3827. /* RFC2616 Section 10.5 - Server Error 5xx */
  3828. case 500:
  3829. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3830. case 501:
  3831. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3832. case 502:
  3833. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3834. case 503:
  3835. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3836. case 504:
  3837. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3838. case 505:
  3839. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3840. case 506:
  3841. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3842. case 507:
  3843. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3844. * Section 11.5 */
  3845. case 508:
  3846. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3847. case 510:
  3848. return "Not Extended"; /* RFC 2774, Section 7 */
  3849. case 511:
  3850. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3851. /* Other status codes, not shown in the IANA HTTP status code
  3852. * assignment.
  3853. * E.g., "de facto" standards due to common use, ... */
  3854. case 418:
  3855. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3856. case 419:
  3857. return "Authentication Timeout"; /* common use */
  3858. case 420:
  3859. return "Enhance Your Calm"; /* common use */
  3860. case 440:
  3861. return "Login Timeout"; /* common use */
  3862. case 509:
  3863. return "Bandwidth Limit Exceeded"; /* common use */
  3864. default:
  3865. /* This error code is unknown. This should not happen. */
  3866. if (conn) {
  3867. mg_cry_internal(conn,
  3868. "Unknown HTTP response code: %u",
  3869. response_code);
  3870. }
  3871. /* Return at least a category according to RFC 2616 Section 10. */
  3872. if (response_code >= 100 && response_code < 200) {
  3873. /* Unknown informational status code */
  3874. return "Information";
  3875. }
  3876. if (response_code >= 200 && response_code < 300) {
  3877. /* Unknown success code */
  3878. return "Success";
  3879. }
  3880. if (response_code >= 300 && response_code < 400) {
  3881. /* Unknown redirection code */
  3882. return "Redirection";
  3883. }
  3884. if (response_code >= 400 && response_code < 500) {
  3885. /* Unknown request error code */
  3886. return "Client Error";
  3887. }
  3888. if (response_code >= 500 && response_code < 600) {
  3889. /* Unknown server error code */
  3890. return "Server Error";
  3891. }
  3892. /* Response code not even within reasonable range */
  3893. return "";
  3894. }
  3895. }
  3896. static int
  3897. mg_send_http_error_impl(struct mg_connection *conn,
  3898. int status,
  3899. const char *fmt,
  3900. va_list args)
  3901. {
  3902. char errmsg_buf[MG_BUF_LEN];
  3903. va_list ap;
  3904. int has_body;
  3905. char date[64];
  3906. time_t curtime = time(NULL);
  3907. #if !defined(NO_FILESYSTEMS)
  3908. char path_buf[PATH_MAX];
  3909. int len, i, page_handler_found, scope, truncated;
  3910. const char *error_handler = NULL;
  3911. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3912. const char *error_page_file_ext, *tstr;
  3913. #endif /* NO_FILESYSTEMS */
  3914. int handled_by_callback = 0;
  3915. const char *status_text = mg_get_response_code_text(conn, status);
  3916. if ((conn == NULL) || (fmt == NULL)) {
  3917. return -2;
  3918. }
  3919. /* Set status (for log) */
  3920. conn->status_code = status;
  3921. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3922. has_body = ((status > 199) && (status != 204) && (status != 304));
  3923. /* Prepare message in buf, if required */
  3924. if (has_body
  3925. || (!conn->in_error_handler
  3926. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3927. /* Store error message in errmsg_buf */
  3928. va_copy(ap, args);
  3929. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3930. va_end(ap);
  3931. /* In a debug build, print all html errors */
  3932. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3933. }
  3934. /* If there is a http_error callback, call it.
  3935. * But don't do it recursively, if callback calls mg_send_http_error again.
  3936. */
  3937. if (!conn->in_error_handler
  3938. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3939. /* Mark in_error_handler to avoid recursion and call user callback. */
  3940. conn->in_error_handler = 1;
  3941. handled_by_callback =
  3942. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3943. == 0);
  3944. conn->in_error_handler = 0;
  3945. }
  3946. if (!handled_by_callback) {
  3947. /* Check for recursion */
  3948. if (conn->in_error_handler) {
  3949. DEBUG_TRACE(
  3950. "Recursion when handling error %u - fall back to default",
  3951. status);
  3952. #if !defined(NO_FILESYSTEMS)
  3953. } else {
  3954. /* Send user defined error pages, if defined */
  3955. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3956. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3957. page_handler_found = 0;
  3958. if (error_handler != NULL) {
  3959. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3960. switch (scope) {
  3961. case 1: /* Handler for specific error, e.g. 404 error */
  3962. mg_snprintf(conn,
  3963. &truncated,
  3964. path_buf,
  3965. sizeof(path_buf) - 32,
  3966. "%serror%03u.",
  3967. error_handler,
  3968. status);
  3969. break;
  3970. case 2: /* Handler for error group, e.g., 5xx error
  3971. * handler
  3972. * for all server errors (500-599) */
  3973. mg_snprintf(conn,
  3974. &truncated,
  3975. path_buf,
  3976. sizeof(path_buf) - 32,
  3977. "%serror%01uxx.",
  3978. error_handler,
  3979. status / 100);
  3980. break;
  3981. default: /* Handler for all errors */
  3982. mg_snprintf(conn,
  3983. &truncated,
  3984. path_buf,
  3985. sizeof(path_buf) - 32,
  3986. "%serror.",
  3987. error_handler);
  3988. break;
  3989. }
  3990. /* String truncation in buf may only occur if
  3991. * error_handler is too long. This string is
  3992. * from the config, not from a client. */
  3993. (void)truncated;
  3994. len = (int)strlen(path_buf);
  3995. tstr = strchr(error_page_file_ext, '.');
  3996. while (tstr) {
  3997. for (i = 1;
  3998. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3999. i++) {
  4000. /* buffer overrun is not possible here, since
  4001. * (i < 32) && (len < sizeof(path_buf) - 32)
  4002. * ==> (i + len) < sizeof(path_buf) */
  4003. path_buf[len + i - 1] = tstr[i];
  4004. }
  4005. /* buffer overrun is not possible here, since
  4006. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4007. * ==> (i + len) <= sizeof(path_buf) */
  4008. path_buf[len + i - 1] = 0;
  4009. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4010. DEBUG_TRACE("Check error page %s - found",
  4011. path_buf);
  4012. page_handler_found = 1;
  4013. break;
  4014. }
  4015. DEBUG_TRACE("Check error page %s - not found",
  4016. path_buf);
  4017. tstr = strchr(tstr + i, '.');
  4018. }
  4019. }
  4020. }
  4021. if (page_handler_found) {
  4022. conn->in_error_handler = 1;
  4023. handle_file_based_request(conn, path_buf, &error_page_file);
  4024. conn->in_error_handler = 0;
  4025. return 0;
  4026. }
  4027. #endif /* NO_FILESYSTEMS */
  4028. }
  4029. /* No custom error page. Send default error page. */
  4030. gmt_time_string(date, sizeof(date), &curtime);
  4031. conn->must_close = 1;
  4032. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4033. send_no_cache_header(conn);
  4034. send_additional_header(conn);
  4035. if (has_body) {
  4036. mg_printf(conn,
  4037. "%s",
  4038. "Content-Type: text/plain; charset=utf-8\r\n");
  4039. }
  4040. mg_printf(conn,
  4041. "Date: %s\r\n"
  4042. "Connection: close\r\n\r\n",
  4043. date);
  4044. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4045. if (has_body) {
  4046. /* For other errors, send a generic error message. */
  4047. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4048. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4049. } else {
  4050. /* No body allowed. Close the connection. */
  4051. DEBUG_TRACE("Error %i", status);
  4052. }
  4053. }
  4054. return 0;
  4055. }
  4056. int
  4057. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4058. {
  4059. va_list ap;
  4060. int ret;
  4061. va_start(ap, fmt);
  4062. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4063. va_end(ap);
  4064. return ret;
  4065. }
  4066. int
  4067. mg_send_http_ok(struct mg_connection *conn,
  4068. const char *mime_type,
  4069. long long content_length)
  4070. {
  4071. char date[64];
  4072. time_t curtime = time(NULL);
  4073. if ((mime_type == NULL) || (*mime_type == 0)) {
  4074. /* Parameter error */
  4075. return -2;
  4076. }
  4077. gmt_time_string(date, sizeof(date), &curtime);
  4078. mg_printf(conn,
  4079. "HTTP/1.1 200 OK\r\n"
  4080. "Content-Type: %s\r\n"
  4081. "Date: %s\r\n"
  4082. "Connection: %s\r\n",
  4083. mime_type,
  4084. date,
  4085. suggest_connection_header(conn));
  4086. send_no_cache_header(conn);
  4087. send_additional_header(conn);
  4088. if (content_length < 0) {
  4089. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4090. } else {
  4091. mg_printf(conn,
  4092. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4093. (uint64_t)content_length);
  4094. }
  4095. return 0;
  4096. }
  4097. int
  4098. mg_send_http_redirect(struct mg_connection *conn,
  4099. const char *target_url,
  4100. int redirect_code)
  4101. {
  4102. /* Send a 30x redirect response.
  4103. *
  4104. * Redirect types (status codes):
  4105. *
  4106. * Status | Perm/Temp | Method | Version
  4107. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4108. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4109. * 303 | temporary | always use GET | HTTP/1.1
  4110. * 307 | temporary | always keep method | HTTP/1.1
  4111. * 308 | permanent | always keep method | HTTP/1.1
  4112. */
  4113. const char *redirect_text;
  4114. int ret;
  4115. size_t content_len = 0;
  4116. char reply[MG_BUF_LEN];
  4117. /* In case redirect_code=0, use 307. */
  4118. if (redirect_code == 0) {
  4119. redirect_code = 307;
  4120. }
  4121. /* In case redirect_code is none of the above, return error. */
  4122. if ((redirect_code != 301) && (redirect_code != 302)
  4123. && (redirect_code != 303) && (redirect_code != 307)
  4124. && (redirect_code != 308)) {
  4125. /* Parameter error */
  4126. return -2;
  4127. }
  4128. /* Get proper text for response code */
  4129. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4130. /* If target_url is not defined, redirect to "/". */
  4131. if ((target_url == NULL) || (*target_url == 0)) {
  4132. target_url = "/";
  4133. }
  4134. #if defined(MG_SEND_REDIRECT_BODY)
  4135. /* TODO: condition name? */
  4136. /* Prepare a response body with a hyperlink.
  4137. *
  4138. * According to RFC2616 (and RFC1945 before):
  4139. * Unless the request method was HEAD, the entity of the
  4140. * response SHOULD contain a short hypertext note with a hyperlink to
  4141. * the new URI(s).
  4142. *
  4143. * However, this response body is not useful in M2M communication.
  4144. * Probably the original reason in the RFC was, clients not supporting
  4145. * a 30x HTTP redirect could still show the HTML page and let the user
  4146. * press the link. Since current browsers support 30x HTTP, the additional
  4147. * HTML body does not seem to make sense anymore.
  4148. *
  4149. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4150. * but it only notes:
  4151. * The server's response payload usually contains a short
  4152. * hypertext note with a hyperlink to the new URI(s).
  4153. *
  4154. * Deactivated by default. If you need the 30x body, set the define.
  4155. */
  4156. mg_snprintf(
  4157. conn,
  4158. NULL /* ignore truncation */,
  4159. reply,
  4160. sizeof(reply),
  4161. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4162. redirect_text,
  4163. target_url,
  4164. target_url);
  4165. content_len = strlen(reply);
  4166. #else
  4167. reply[0] = 0;
  4168. #endif
  4169. /* Do not send any additional header. For all other options,
  4170. * including caching, there are suitable defaults. */
  4171. ret = mg_printf(conn,
  4172. "HTTP/1.1 %i %s\r\n"
  4173. "Location: %s\r\n"
  4174. "Content-Length: %u\r\n"
  4175. "Connection: %s\r\n\r\n",
  4176. redirect_code,
  4177. redirect_text,
  4178. target_url,
  4179. (unsigned int)content_len,
  4180. suggest_connection_header(conn));
  4181. /* Send response body */
  4182. if (ret > 0) {
  4183. /* ... unless it is a HEAD request */
  4184. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4185. ret = mg_write(conn, reply, content_len);
  4186. }
  4187. }
  4188. return (ret > 0) ? ret : -1;
  4189. }
  4190. #if defined(_WIN32)
  4191. /* Create substitutes for POSIX functions in Win32. */
  4192. #if defined(GCC_DIAGNOSTIC)
  4193. /* Show no warning in case system functions are not used. */
  4194. #pragma GCC diagnostic push
  4195. #pragma GCC diagnostic ignored "-Wunused-function"
  4196. #endif
  4197. static int
  4198. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4199. {
  4200. (void)unused;
  4201. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4202. InitializeCriticalSection(&mutex->sec);
  4203. return 0;
  4204. }
  4205. static int
  4206. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4207. {
  4208. DeleteCriticalSection(&mutex->sec);
  4209. return 0;
  4210. }
  4211. static int
  4212. pthread_mutex_lock(pthread_mutex_t *mutex)
  4213. {
  4214. EnterCriticalSection(&mutex->sec);
  4215. return 0;
  4216. }
  4217. static int
  4218. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4219. {
  4220. LeaveCriticalSection(&mutex->sec);
  4221. return 0;
  4222. }
  4223. FUNCTION_MAY_BE_UNUSED
  4224. static int
  4225. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4226. {
  4227. (void)unused;
  4228. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4229. cv->waiting_thread = NULL;
  4230. return 0;
  4231. }
  4232. FUNCTION_MAY_BE_UNUSED
  4233. static int
  4234. pthread_cond_timedwait(pthread_cond_t *cv,
  4235. pthread_mutex_t *mutex,
  4236. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4237. {
  4238. struct mg_workerTLS **ptls,
  4239. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4240. int ok;
  4241. int64_t nsnow, nswaitabs, nswaitrel;
  4242. DWORD mswaitrel;
  4243. pthread_mutex_lock(&cv->threadIdSec);
  4244. /* Add this thread to cv's waiting list */
  4245. ptls = &cv->waiting_thread;
  4246. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4247. ;
  4248. tls->next_waiting_thread = NULL;
  4249. *ptls = tls;
  4250. pthread_mutex_unlock(&cv->threadIdSec);
  4251. if (abstime) {
  4252. nsnow = mg_get_current_time_ns();
  4253. nswaitabs =
  4254. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4255. nswaitrel = nswaitabs - nsnow;
  4256. if (nswaitrel < 0) {
  4257. nswaitrel = 0;
  4258. }
  4259. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4260. } else {
  4261. mswaitrel = (DWORD)INFINITE;
  4262. }
  4263. pthread_mutex_unlock(mutex);
  4264. ok = (WAIT_OBJECT_0
  4265. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4266. if (!ok) {
  4267. ok = 1;
  4268. pthread_mutex_lock(&cv->threadIdSec);
  4269. ptls = &cv->waiting_thread;
  4270. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4271. if (*ptls == tls) {
  4272. *ptls = tls->next_waiting_thread;
  4273. ok = 0;
  4274. break;
  4275. }
  4276. }
  4277. pthread_mutex_unlock(&cv->threadIdSec);
  4278. if (ok) {
  4279. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4280. (DWORD)INFINITE);
  4281. }
  4282. }
  4283. /* This thread has been removed from cv's waiting list */
  4284. pthread_mutex_lock(mutex);
  4285. return ok ? 0 : -1;
  4286. }
  4287. FUNCTION_MAY_BE_UNUSED
  4288. static int
  4289. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4290. {
  4291. return pthread_cond_timedwait(cv, mutex, NULL);
  4292. }
  4293. FUNCTION_MAY_BE_UNUSED
  4294. static int
  4295. pthread_cond_signal(pthread_cond_t *cv)
  4296. {
  4297. HANDLE wkup = NULL;
  4298. BOOL ok = FALSE;
  4299. pthread_mutex_lock(&cv->threadIdSec);
  4300. if (cv->waiting_thread) {
  4301. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4302. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4303. ok = SetEvent(wkup);
  4304. DEBUG_ASSERT(ok);
  4305. }
  4306. pthread_mutex_unlock(&cv->threadIdSec);
  4307. return ok ? 0 : 1;
  4308. }
  4309. FUNCTION_MAY_BE_UNUSED
  4310. static int
  4311. pthread_cond_broadcast(pthread_cond_t *cv)
  4312. {
  4313. pthread_mutex_lock(&cv->threadIdSec);
  4314. while (cv->waiting_thread) {
  4315. pthread_cond_signal(cv);
  4316. }
  4317. pthread_mutex_unlock(&cv->threadIdSec);
  4318. return 0;
  4319. }
  4320. FUNCTION_MAY_BE_UNUSED
  4321. static int
  4322. pthread_cond_destroy(pthread_cond_t *cv)
  4323. {
  4324. pthread_mutex_lock(&cv->threadIdSec);
  4325. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4326. pthread_mutex_unlock(&cv->threadIdSec);
  4327. pthread_mutex_destroy(&cv->threadIdSec);
  4328. return 0;
  4329. }
  4330. #if defined(ALTERNATIVE_QUEUE)
  4331. FUNCTION_MAY_BE_UNUSED
  4332. static void *
  4333. event_create(void)
  4334. {
  4335. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4336. }
  4337. FUNCTION_MAY_BE_UNUSED
  4338. static int
  4339. event_wait(void *eventhdl)
  4340. {
  4341. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4342. return (res == WAIT_OBJECT_0);
  4343. }
  4344. FUNCTION_MAY_BE_UNUSED
  4345. static int
  4346. event_signal(void *eventhdl)
  4347. {
  4348. return (int)SetEvent((HANDLE)eventhdl);
  4349. }
  4350. FUNCTION_MAY_BE_UNUSED
  4351. static void
  4352. event_destroy(void *eventhdl)
  4353. {
  4354. CloseHandle((HANDLE)eventhdl);
  4355. }
  4356. #endif
  4357. #if defined(GCC_DIAGNOSTIC)
  4358. /* Enable unused function warning again */
  4359. #pragma GCC diagnostic pop
  4360. #endif
  4361. /* For Windows, change all slashes to backslashes in path names. */
  4362. static void
  4363. change_slashes_to_backslashes(char *path)
  4364. {
  4365. int i;
  4366. for (i = 0; path[i] != '\0'; i++) {
  4367. if (path[i] == '/') {
  4368. path[i] = '\\';
  4369. }
  4370. /* remove double backslash (check i > 0 to preserve UNC paths,
  4371. * like \\server\file.txt) */
  4372. if ((path[i] == '\\') && (i > 0)) {
  4373. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4374. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4375. }
  4376. }
  4377. }
  4378. }
  4379. static int
  4380. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4381. {
  4382. int diff;
  4383. do {
  4384. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4385. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4386. s1++;
  4387. s2++;
  4388. } while ((diff == 0) && (s1[-1] != L'\0'));
  4389. return diff;
  4390. }
  4391. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4392. * wbuf and wbuf_len is a target buffer and its length. */
  4393. static void
  4394. path_to_unicode(const struct mg_connection *conn,
  4395. const char *path,
  4396. wchar_t *wbuf,
  4397. size_t wbuf_len)
  4398. {
  4399. char buf[PATH_MAX], buf2[PATH_MAX];
  4400. wchar_t wbuf2[W_PATH_MAX + 1];
  4401. DWORD long_len, err;
  4402. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4403. mg_strlcpy(buf, path, sizeof(buf));
  4404. change_slashes_to_backslashes(buf);
  4405. /* Convert to Unicode and back. If doubly-converted string does not
  4406. * match the original, something is fishy, reject. */
  4407. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4408. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4409. WideCharToMultiByte(
  4410. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4411. if (strcmp(buf, buf2) != 0) {
  4412. wbuf[0] = L'\0';
  4413. }
  4414. /* Windows file systems are not case sensitive, but you can still use
  4415. * uppercase and lowercase letters (on all modern file systems).
  4416. * The server can check if the URI uses the same upper/lowercase
  4417. * letters an the file system, effectively making Windows servers
  4418. * case sensitive (like Linux servers are). It is still not possible
  4419. * to use two files with the same name in different cases on Windows
  4420. * (like /a and /A) - this would be possible in Linux.
  4421. * As a default, Windows is not case sensitive, but the case sensitive
  4422. * file name check can be activated by an additional configuration. */
  4423. if (conn) {
  4424. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4425. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4426. "yes")) {
  4427. /* Use case sensitive compare function */
  4428. fcompare = wcscmp;
  4429. }
  4430. }
  4431. (void)conn; /* conn is currently unused */
  4432. #if !defined(_WIN32_WCE)
  4433. /* Only accept a full file path, not a Windows short (8.3) path. */
  4434. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4435. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4436. if (long_len == 0) {
  4437. err = GetLastError();
  4438. if (err == ERROR_FILE_NOT_FOUND) {
  4439. /* File does not exist. This is not always a problem here. */
  4440. return;
  4441. }
  4442. }
  4443. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4444. /* Short name is used. */
  4445. wbuf[0] = L'\0';
  4446. }
  4447. #else
  4448. (void)long_len;
  4449. (void)wbuf2;
  4450. (void)err;
  4451. if (strchr(path, '~')) {
  4452. wbuf[0] = L'\0';
  4453. }
  4454. #endif
  4455. }
  4456. #if !defined(NO_FILESYSTEMS)
  4457. static int
  4458. mg_stat(const struct mg_connection *conn,
  4459. const char *path,
  4460. struct mg_file_stat *filep)
  4461. {
  4462. wchar_t wbuf[W_PATH_MAX];
  4463. WIN32_FILE_ATTRIBUTE_DATA info;
  4464. time_t creation_time;
  4465. size_t len;
  4466. if (!filep) {
  4467. return 0;
  4468. }
  4469. memset(filep, 0, sizeof(*filep));
  4470. if (conn && is_file_in_memory(conn, path)) {
  4471. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4472. * memset */
  4473. /* Quick fix (for 1.9.x): */
  4474. /* mg_stat must fill all fields, also for files in memory */
  4475. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4476. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4477. filep->size = tmp_file.stat.size;
  4478. filep->location = 2;
  4479. /* TODO: for 1.10: restructure how files in memory are handled */
  4480. /* The "file in memory" feature is a candidate for deletion.
  4481. * Please join the discussion at
  4482. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4483. */
  4484. filep->last_modified = time(NULL); /* TODO */
  4485. /* last_modified = now ... assumes the file may change during
  4486. * runtime,
  4487. * so every mg_fopen call may return different data */
  4488. /* last_modified = conn->phys_ctx.start_time;
  4489. * May be used it the data does not change during runtime. This
  4490. * allows
  4491. * browser caching. Since we do not know, we have to assume the file
  4492. * in memory may change. */
  4493. return 1;
  4494. }
  4495. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4496. /* Windows happily opens files with some garbage at the end of file name.
  4497. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4498. * "a.cgi", despite one would expect an error back. */
  4499. len = strlen(path);
  4500. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4501. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4502. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4503. filep->last_modified =
  4504. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4505. info.ftLastWriteTime.dwHighDateTime);
  4506. /* On Windows, the file creation time can be higher than the
  4507. * modification time, e.g. when a file is copied.
  4508. * Since the Last-Modified timestamp is used for caching
  4509. * it should be based on the most recent timestamp. */
  4510. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4511. info.ftCreationTime.dwHighDateTime);
  4512. if (creation_time > filep->last_modified) {
  4513. filep->last_modified = creation_time;
  4514. }
  4515. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4516. return 1;
  4517. }
  4518. return 0;
  4519. }
  4520. #endif
  4521. static int
  4522. mg_remove(const struct mg_connection *conn, const char *path)
  4523. {
  4524. wchar_t wbuf[W_PATH_MAX];
  4525. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4526. return DeleteFileW(wbuf) ? 0 : -1;
  4527. }
  4528. static int
  4529. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4530. {
  4531. wchar_t wbuf[W_PATH_MAX];
  4532. (void)mode;
  4533. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4534. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4535. }
  4536. /* Create substitutes for POSIX functions in Win32. */
  4537. #if defined(GCC_DIAGNOSTIC)
  4538. /* Show no warning in case system functions are not used. */
  4539. #pragma GCC diagnostic push
  4540. #pragma GCC diagnostic ignored "-Wunused-function"
  4541. #endif
  4542. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4543. FUNCTION_MAY_BE_UNUSED
  4544. static DIR *
  4545. mg_opendir(const struct mg_connection *conn, const char *name)
  4546. {
  4547. DIR *dir = NULL;
  4548. wchar_t wpath[W_PATH_MAX];
  4549. DWORD attrs;
  4550. if (name == NULL) {
  4551. SetLastError(ERROR_BAD_ARGUMENTS);
  4552. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4553. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4554. } else {
  4555. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4556. attrs = GetFileAttributesW(wpath);
  4557. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4558. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4559. (void)wcscat(wpath, L"\\*");
  4560. dir->handle = FindFirstFileW(wpath, &dir->info);
  4561. dir->result.d_name[0] = '\0';
  4562. } else {
  4563. mg_free(dir);
  4564. dir = NULL;
  4565. }
  4566. }
  4567. return dir;
  4568. }
  4569. FUNCTION_MAY_BE_UNUSED
  4570. static int
  4571. mg_closedir(DIR *dir)
  4572. {
  4573. int result = 0;
  4574. if (dir != NULL) {
  4575. if (dir->handle != INVALID_HANDLE_VALUE)
  4576. result = FindClose(dir->handle) ? 0 : -1;
  4577. mg_free(dir);
  4578. } else {
  4579. result = -1;
  4580. SetLastError(ERROR_BAD_ARGUMENTS);
  4581. }
  4582. return result;
  4583. }
  4584. FUNCTION_MAY_BE_UNUSED
  4585. static struct dirent *
  4586. mg_readdir(DIR *dir)
  4587. {
  4588. struct dirent *result = 0;
  4589. if (dir) {
  4590. if (dir->handle != INVALID_HANDLE_VALUE) {
  4591. result = &dir->result;
  4592. (void)WideCharToMultiByte(CP_UTF8,
  4593. 0,
  4594. dir->info.cFileName,
  4595. -1,
  4596. result->d_name,
  4597. sizeof(result->d_name),
  4598. NULL,
  4599. NULL);
  4600. if (!FindNextFileW(dir->handle, &dir->info)) {
  4601. (void)FindClose(dir->handle);
  4602. dir->handle = INVALID_HANDLE_VALUE;
  4603. }
  4604. } else {
  4605. SetLastError(ERROR_FILE_NOT_FOUND);
  4606. }
  4607. } else {
  4608. SetLastError(ERROR_BAD_ARGUMENTS);
  4609. }
  4610. return result;
  4611. }
  4612. #if !defined(HAVE_POLL)
  4613. #undef POLLIN
  4614. #undef POLLPRI
  4615. #undef POLLOUT
  4616. #define POLLIN (1) /* Data ready - read will not block. */
  4617. #define POLLPRI (2) /* Priority data ready. */
  4618. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4619. FUNCTION_MAY_BE_UNUSED
  4620. static int
  4621. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4622. {
  4623. struct timeval tv;
  4624. fd_set rset;
  4625. fd_set wset;
  4626. unsigned int i;
  4627. int result;
  4628. SOCKET maxfd = 0;
  4629. memset(&tv, 0, sizeof(tv));
  4630. tv.tv_sec = milliseconds / 1000;
  4631. tv.tv_usec = (milliseconds % 1000) * 1000;
  4632. FD_ZERO(&rset);
  4633. FD_ZERO(&wset);
  4634. for (i = 0; i < n; i++) {
  4635. if (pfd[i].events & POLLIN) {
  4636. FD_SET(pfd[i].fd, &rset);
  4637. }
  4638. if (pfd[i].events & POLLOUT) {
  4639. FD_SET(pfd[i].fd, &wset);
  4640. }
  4641. pfd[i].revents = 0;
  4642. if (pfd[i].fd > maxfd) {
  4643. maxfd = pfd[i].fd;
  4644. }
  4645. }
  4646. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4647. for (i = 0; i < n; i++) {
  4648. if (FD_ISSET(pfd[i].fd, &rset)) {
  4649. pfd[i].revents |= POLLIN;
  4650. }
  4651. if (FD_ISSET(pfd[i].fd, &wset)) {
  4652. pfd[i].revents |= POLLOUT;
  4653. }
  4654. }
  4655. }
  4656. /* We should subtract the time used in select from remaining
  4657. * "milliseconds", in particular if called from mg_poll with a
  4658. * timeout quantum.
  4659. * Unfortunately, the remaining time is not stored in "tv" in all
  4660. * implementations, so the result in "tv" must be considered undefined.
  4661. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4662. return result;
  4663. }
  4664. #endif /* HAVE_POLL */
  4665. #if defined(GCC_DIAGNOSTIC)
  4666. /* Enable unused function warning again */
  4667. #pragma GCC diagnostic pop
  4668. #endif
  4669. static void
  4670. set_close_on_exec(SOCKET sock,
  4671. const struct mg_connection *conn /* may be null */,
  4672. struct mg_context *ctx /* may be null */)
  4673. {
  4674. (void)conn; /* Unused. */
  4675. (void)ctx;
  4676. #if defined(_WIN32_WCE)
  4677. (void)sock;
  4678. #else
  4679. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4680. #endif
  4681. }
  4682. int
  4683. mg_start_thread(mg_thread_func_t f, void *p)
  4684. {
  4685. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4686. /* Compile-time option to control stack size, e.g.
  4687. * -DUSE_STACK_SIZE=16384
  4688. */
  4689. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4690. == ((uintptr_t)(-1L)))
  4691. ? -1
  4692. : 0);
  4693. #else
  4694. return (
  4695. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4696. ? -1
  4697. : 0);
  4698. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4699. }
  4700. /* Start a thread storing the thread context. */
  4701. static int
  4702. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4703. void *p,
  4704. pthread_t *threadidptr)
  4705. {
  4706. uintptr_t uip;
  4707. HANDLE threadhandle;
  4708. int result = -1;
  4709. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4710. threadhandle = (HANDLE)uip;
  4711. if ((uip != 0) && (threadidptr != NULL)) {
  4712. *threadidptr = threadhandle;
  4713. result = 0;
  4714. }
  4715. return result;
  4716. }
  4717. /* Wait for a thread to finish. */
  4718. static int
  4719. mg_join_thread(pthread_t threadid)
  4720. {
  4721. int result;
  4722. DWORD dwevent;
  4723. result = -1;
  4724. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4725. if (dwevent == WAIT_FAILED) {
  4726. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4727. } else {
  4728. if (dwevent == WAIT_OBJECT_0) {
  4729. CloseHandle(threadid);
  4730. result = 0;
  4731. }
  4732. }
  4733. return result;
  4734. }
  4735. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4736. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4737. /* Create substitutes for POSIX functions in Win32. */
  4738. #if defined(GCC_DIAGNOSTIC)
  4739. /* Show no warning in case system functions are not used. */
  4740. #pragma GCC diagnostic push
  4741. #pragma GCC diagnostic ignored "-Wunused-function"
  4742. #endif
  4743. FUNCTION_MAY_BE_UNUSED
  4744. static HANDLE
  4745. dlopen(const char *dll_name, int flags)
  4746. {
  4747. wchar_t wbuf[W_PATH_MAX];
  4748. (void)flags;
  4749. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4750. return LoadLibraryW(wbuf);
  4751. }
  4752. FUNCTION_MAY_BE_UNUSED
  4753. static int
  4754. dlclose(void *handle)
  4755. {
  4756. int result;
  4757. if (FreeLibrary((HMODULE)handle) != 0) {
  4758. result = 0;
  4759. } else {
  4760. result = -1;
  4761. }
  4762. return result;
  4763. }
  4764. #if defined(GCC_DIAGNOSTIC)
  4765. /* Enable unused function warning again */
  4766. #pragma GCC diagnostic pop
  4767. #endif
  4768. #endif
  4769. #if !defined(NO_CGI)
  4770. #define SIGKILL (0)
  4771. static int
  4772. kill(pid_t pid, int sig_num)
  4773. {
  4774. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4775. (void)CloseHandle((HANDLE)pid);
  4776. return 0;
  4777. }
  4778. #if !defined(WNOHANG)
  4779. #define WNOHANG (1)
  4780. #endif
  4781. static pid_t
  4782. waitpid(pid_t pid, int *status, int flags)
  4783. {
  4784. DWORD timeout = INFINITE;
  4785. DWORD waitres;
  4786. (void)status; /* Currently not used by any client here */
  4787. if ((flags | WNOHANG) == WNOHANG) {
  4788. timeout = 0;
  4789. }
  4790. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4791. if (waitres == WAIT_OBJECT_0) {
  4792. return pid;
  4793. }
  4794. if (waitres == WAIT_TIMEOUT) {
  4795. return 0;
  4796. }
  4797. return (pid_t)-1;
  4798. }
  4799. static void
  4800. trim_trailing_whitespaces(char *s)
  4801. {
  4802. char *e = s + strlen(s);
  4803. while ((e > s) && isspace((unsigned char)e[-1])) {
  4804. *(--e) = '\0';
  4805. }
  4806. }
  4807. static pid_t
  4808. spawn_process(struct mg_connection *conn,
  4809. const char *prog,
  4810. char *envblk,
  4811. char *envp[],
  4812. int fdin[2],
  4813. int fdout[2],
  4814. int fderr[2],
  4815. const char *dir)
  4816. {
  4817. HANDLE me;
  4818. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4819. cmdline[PATH_MAX], buf[PATH_MAX];
  4820. int truncated;
  4821. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4822. STARTUPINFOA si;
  4823. PROCESS_INFORMATION pi = {0};
  4824. (void)envp;
  4825. memset(&si, 0, sizeof(si));
  4826. si.cb = sizeof(si);
  4827. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4828. si.wShowWindow = SW_HIDE;
  4829. me = GetCurrentProcess();
  4830. DuplicateHandle(me,
  4831. (HANDLE)_get_osfhandle(fdin[0]),
  4832. me,
  4833. &si.hStdInput,
  4834. 0,
  4835. TRUE,
  4836. DUPLICATE_SAME_ACCESS);
  4837. DuplicateHandle(me,
  4838. (HANDLE)_get_osfhandle(fdout[1]),
  4839. me,
  4840. &si.hStdOutput,
  4841. 0,
  4842. TRUE,
  4843. DUPLICATE_SAME_ACCESS);
  4844. DuplicateHandle(me,
  4845. (HANDLE)_get_osfhandle(fderr[1]),
  4846. me,
  4847. &si.hStdError,
  4848. 0,
  4849. TRUE,
  4850. DUPLICATE_SAME_ACCESS);
  4851. /* Mark handles that should not be inherited. See
  4852. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4853. */
  4854. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4855. HANDLE_FLAG_INHERIT,
  4856. 0);
  4857. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4858. HANDLE_FLAG_INHERIT,
  4859. 0);
  4860. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4861. HANDLE_FLAG_INHERIT,
  4862. 0);
  4863. /* If CGI file is a script, try to read the interpreter line */
  4864. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4865. if (interp == NULL) {
  4866. buf[0] = buf[1] = '\0';
  4867. /* Read the first line of the script into the buffer */
  4868. mg_snprintf(
  4869. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4870. if (truncated) {
  4871. pi.hProcess = (pid_t)-1;
  4872. goto spawn_cleanup;
  4873. }
  4874. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4875. #if defined(MG_USE_OPEN_FILE)
  4876. p = (char *)file.access.membuf;
  4877. #else
  4878. p = (char *)NULL;
  4879. #endif
  4880. mg_fgets(buf, sizeof(buf), &file, &p);
  4881. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4882. buf[sizeof(buf) - 1] = '\0';
  4883. }
  4884. if ((buf[0] == '#') && (buf[1] == '!')) {
  4885. trim_trailing_whitespaces(buf + 2);
  4886. } else {
  4887. buf[2] = '\0';
  4888. }
  4889. interp = buf + 2;
  4890. }
  4891. if (interp[0] != '\0') {
  4892. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4893. interp = full_interp;
  4894. }
  4895. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4896. if (interp[0] != '\0') {
  4897. mg_snprintf(conn,
  4898. &truncated,
  4899. cmdline,
  4900. sizeof(cmdline),
  4901. "\"%s\" \"%s\\%s\"",
  4902. interp,
  4903. full_dir,
  4904. prog);
  4905. } else {
  4906. mg_snprintf(conn,
  4907. &truncated,
  4908. cmdline,
  4909. sizeof(cmdline),
  4910. "\"%s\\%s\"",
  4911. full_dir,
  4912. prog);
  4913. }
  4914. if (truncated) {
  4915. pi.hProcess = (pid_t)-1;
  4916. goto spawn_cleanup;
  4917. }
  4918. DEBUG_TRACE("Running [%s]", cmdline);
  4919. if (CreateProcessA(NULL,
  4920. cmdline,
  4921. NULL,
  4922. NULL,
  4923. TRUE,
  4924. CREATE_NEW_PROCESS_GROUP,
  4925. envblk,
  4926. NULL,
  4927. &si,
  4928. &pi)
  4929. == 0) {
  4930. mg_cry_internal(
  4931. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4932. pi.hProcess = (pid_t)-1;
  4933. /* goto spawn_cleanup; */
  4934. }
  4935. spawn_cleanup:
  4936. (void)CloseHandle(si.hStdOutput);
  4937. (void)CloseHandle(si.hStdError);
  4938. (void)CloseHandle(si.hStdInput);
  4939. if (pi.hThread != NULL) {
  4940. (void)CloseHandle(pi.hThread);
  4941. }
  4942. return (pid_t)pi.hProcess;
  4943. }
  4944. #endif /* !NO_CGI */
  4945. static int
  4946. set_blocking_mode(SOCKET sock)
  4947. {
  4948. unsigned long non_blocking = 0;
  4949. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4950. }
  4951. static int
  4952. set_non_blocking_mode(SOCKET sock)
  4953. {
  4954. unsigned long non_blocking = 1;
  4955. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4956. }
  4957. #else
  4958. #if !defined(NO_FILESYSTEMS)
  4959. static int
  4960. mg_stat(const struct mg_connection *conn,
  4961. const char *path,
  4962. struct mg_file_stat *filep)
  4963. {
  4964. struct stat st;
  4965. if (!filep) {
  4966. return 0;
  4967. }
  4968. memset(filep, 0, sizeof(*filep));
  4969. if (conn && is_file_in_memory(conn, path)) {
  4970. /* Quick fix (for 1.9.x): */
  4971. /* mg_stat must fill all fields, also for files in memory */
  4972. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4973. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4974. filep->size = tmp_file.stat.size;
  4975. filep->last_modified = time(NULL);
  4976. filep->location = 2;
  4977. /* TODO: remove legacy "files in memory" feature */
  4978. return 1;
  4979. }
  4980. if (0 == stat(path, &st)) {
  4981. filep->size = (uint64_t)(st.st_size);
  4982. filep->last_modified = st.st_mtime;
  4983. filep->is_directory = S_ISDIR(st.st_mode);
  4984. return 1;
  4985. }
  4986. return 0;
  4987. }
  4988. #endif /* NO_FILESYSTEMS */
  4989. static void
  4990. set_close_on_exec(int fd,
  4991. const struct mg_connection *conn /* may be null */,
  4992. struct mg_context *ctx /* may be null */)
  4993. {
  4994. #if defined(__ZEPHYR__)
  4995. (void)fd;
  4996. (void)conn;
  4997. (void)ctx;
  4998. #else
  4999. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  5000. if (conn || ctx) {
  5001. struct mg_connection fc;
  5002. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5003. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5004. __func__,
  5005. strerror(ERRNO));
  5006. }
  5007. }
  5008. #endif
  5009. }
  5010. int
  5011. mg_start_thread(mg_thread_func_t func, void *param)
  5012. {
  5013. pthread_t thread_id;
  5014. pthread_attr_t attr;
  5015. int result;
  5016. (void)pthread_attr_init(&attr);
  5017. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5018. #if defined(__ZEPHYR__)
  5019. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5020. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5021. /* Compile-time option to control stack size,
  5022. * e.g. -DUSE_STACK_SIZE=16384 */
  5023. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5024. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5025. result = pthread_create(&thread_id, &attr, func, param);
  5026. pthread_attr_destroy(&attr);
  5027. return result;
  5028. }
  5029. /* Start a thread storing the thread context. */
  5030. static int
  5031. mg_start_thread_with_id(mg_thread_func_t func,
  5032. void *param,
  5033. pthread_t *threadidptr)
  5034. {
  5035. pthread_t thread_id;
  5036. pthread_attr_t attr;
  5037. int result;
  5038. (void)pthread_attr_init(&attr);
  5039. #if defined(__ZEPHYR__)
  5040. pthread_attr_setstack(&attr,
  5041. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5042. ZEPHYR_STACK_SIZE);
  5043. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5044. /* Compile-time option to control stack size,
  5045. * e.g. -DUSE_STACK_SIZE=16384 */
  5046. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5047. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5048. result = pthread_create(&thread_id, &attr, func, param);
  5049. pthread_attr_destroy(&attr);
  5050. if ((result == 0) && (threadidptr != NULL)) {
  5051. *threadidptr = thread_id;
  5052. }
  5053. return result;
  5054. }
  5055. /* Wait for a thread to finish. */
  5056. static int
  5057. mg_join_thread(pthread_t threadid)
  5058. {
  5059. int result;
  5060. result = pthread_join(threadid, NULL);
  5061. return result;
  5062. }
  5063. #if !defined(NO_CGI)
  5064. static pid_t
  5065. spawn_process(struct mg_connection *conn,
  5066. const char *prog,
  5067. char *envblk,
  5068. char *envp[],
  5069. int fdin[2],
  5070. int fdout[2],
  5071. int fderr[2],
  5072. const char *dir)
  5073. {
  5074. pid_t pid;
  5075. const char *interp;
  5076. (void)envblk;
  5077. if ((pid = fork()) == -1) {
  5078. /* Parent */
  5079. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5080. } else if (pid != 0) {
  5081. /* Make sure children close parent-side descriptors.
  5082. * The caller will close the child-side immediately. */
  5083. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5084. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5085. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5086. } else {
  5087. /* Child */
  5088. if (chdir(dir) != 0) {
  5089. mg_cry_internal(
  5090. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5091. } else if (dup2(fdin[0], 0) == -1) {
  5092. mg_cry_internal(conn,
  5093. "%s: dup2(%d, 0): %s",
  5094. __func__,
  5095. fdin[0],
  5096. strerror(ERRNO));
  5097. } else if (dup2(fdout[1], 1) == -1) {
  5098. mg_cry_internal(conn,
  5099. "%s: dup2(%d, 1): %s",
  5100. __func__,
  5101. fdout[1],
  5102. strerror(ERRNO));
  5103. } else if (dup2(fderr[1], 2) == -1) {
  5104. mg_cry_internal(conn,
  5105. "%s: dup2(%d, 2): %s",
  5106. __func__,
  5107. fderr[1],
  5108. strerror(ERRNO));
  5109. } else {
  5110. struct sigaction sa;
  5111. /* Keep stderr and stdout in two different pipes.
  5112. * Stdout will be sent back to the client,
  5113. * stderr should go into a server error log. */
  5114. (void)close(fdin[0]);
  5115. (void)close(fdout[1]);
  5116. (void)close(fderr[1]);
  5117. /* Close write end fdin and read end fdout and fderr */
  5118. (void)close(fdin[1]);
  5119. (void)close(fdout[0]);
  5120. (void)close(fderr[0]);
  5121. /* After exec, all signal handlers are restored to their default
  5122. * values, with one exception of SIGCHLD. According to
  5123. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5124. * will leave unchanged after exec if it was set to be ignored.
  5125. * Restore it to default action. */
  5126. memset(&sa, 0, sizeof(sa));
  5127. sa.sa_handler = SIG_DFL;
  5128. sigaction(SIGCHLD, &sa, NULL);
  5129. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5130. if (interp == NULL) {
  5131. (void)execle(prog, prog, NULL, envp);
  5132. mg_cry_internal(conn,
  5133. "%s: execle(%s): %s",
  5134. __func__,
  5135. prog,
  5136. strerror(ERRNO));
  5137. } else {
  5138. (void)execle(interp, interp, prog, NULL, envp);
  5139. mg_cry_internal(conn,
  5140. "%s: execle(%s %s): %s",
  5141. __func__,
  5142. interp,
  5143. prog,
  5144. strerror(ERRNO));
  5145. }
  5146. }
  5147. exit(EXIT_FAILURE);
  5148. }
  5149. return pid;
  5150. }
  5151. #endif /* !NO_CGI */
  5152. static int
  5153. set_non_blocking_mode(SOCKET sock)
  5154. {
  5155. int flags = fcntl(sock, F_GETFL, 0);
  5156. if (flags < 0) {
  5157. return -1;
  5158. }
  5159. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5160. return -1;
  5161. }
  5162. return 0;
  5163. }
  5164. static int
  5165. set_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 & (~(int)(O_NONBLOCK))) < 0) {
  5172. return -1;
  5173. }
  5174. return 0;
  5175. }
  5176. #endif /* _WIN32 / else */
  5177. /* End of initial operating system specific define block. */
  5178. /* Get a random number (independent of C rand function) */
  5179. static uint64_t
  5180. get_random(void)
  5181. {
  5182. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5183. static uint64_t lcg = 0; /* Linear congruential generator */
  5184. uint64_t now = mg_get_current_time_ns();
  5185. if (lfsr == 0) {
  5186. /* lfsr will be only 0 if has not been initialized,
  5187. * so this code is called only once. */
  5188. lfsr = mg_get_current_time_ns();
  5189. lcg = mg_get_current_time_ns();
  5190. } else {
  5191. /* Get the next step of both random number generators. */
  5192. lfsr = (lfsr >> 1)
  5193. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5194. << 63);
  5195. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5196. }
  5197. /* Combining two pseudo-random number generators and a high resolution
  5198. * part
  5199. * of the current server time will make it hard (impossible?) to guess
  5200. * the
  5201. * next number. */
  5202. return (lfsr ^ lcg ^ now);
  5203. }
  5204. static int
  5205. mg_poll(struct mg_pollfd *pfd,
  5206. unsigned int n,
  5207. int milliseconds,
  5208. volatile int *stop_server)
  5209. {
  5210. /* Call poll, but only for a maximum time of a few seconds.
  5211. * This will allow to stop the server after some seconds, instead
  5212. * of having to wait for a long socket timeout. */
  5213. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5214. do {
  5215. int result;
  5216. if (*stop_server) {
  5217. /* Shut down signal */
  5218. return -2;
  5219. }
  5220. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5221. ms_now = milliseconds;
  5222. }
  5223. result = poll(pfd, n, ms_now);
  5224. if (result != 0) {
  5225. /* Poll returned either success (1) or error (-1).
  5226. * Forward both to the caller. */
  5227. return result;
  5228. }
  5229. /* Poll returned timeout (0). */
  5230. if (milliseconds > 0) {
  5231. milliseconds -= ms_now;
  5232. }
  5233. } while (milliseconds != 0);
  5234. /* timeout: return 0 */
  5235. return 0;
  5236. }
  5237. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5238. * descriptor.
  5239. * Return value:
  5240. * >=0 .. number of bytes successfully written
  5241. * -1 .. timeout
  5242. * -2 .. error
  5243. */
  5244. static int
  5245. push_inner(struct mg_context *ctx,
  5246. FILE *fp,
  5247. SOCKET sock,
  5248. SSL *ssl,
  5249. const char *buf,
  5250. int len,
  5251. double timeout)
  5252. {
  5253. uint64_t start = 0, now = 0, timeout_ns = 0;
  5254. int n, err;
  5255. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5256. #if defined(_WIN32)
  5257. typedef int len_t;
  5258. #else
  5259. typedef size_t len_t;
  5260. #endif
  5261. if (timeout > 0) {
  5262. now = mg_get_current_time_ns();
  5263. start = now;
  5264. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5265. }
  5266. if (ctx == NULL) {
  5267. return -2;
  5268. }
  5269. #if defined(NO_SSL)
  5270. if (ssl) {
  5271. return -2;
  5272. }
  5273. #endif
  5274. /* Try to read until it succeeds, fails, times out, or the server
  5275. * shuts down. */
  5276. for (;;) {
  5277. #if !defined(NO_SSL)
  5278. if (ssl != NULL) {
  5279. n = SSL_write(ssl, buf, len);
  5280. if (n <= 0) {
  5281. err = SSL_get_error(ssl, n);
  5282. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5283. err = ERRNO;
  5284. } else if ((err == SSL_ERROR_WANT_READ)
  5285. || (err == SSL_ERROR_WANT_WRITE)) {
  5286. n = 0;
  5287. } else {
  5288. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5289. return -2;
  5290. }
  5291. } else {
  5292. err = 0;
  5293. }
  5294. } else
  5295. #endif
  5296. if (fp != NULL) {
  5297. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5298. if (ferror(fp)) {
  5299. n = -1;
  5300. err = ERRNO;
  5301. } else {
  5302. err = 0;
  5303. }
  5304. } else {
  5305. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5306. err = (n < 0) ? ERRNO : 0;
  5307. #if defined(_WIN32)
  5308. if (err == WSAEWOULDBLOCK) {
  5309. err = 0;
  5310. n = 0;
  5311. }
  5312. #else
  5313. if (err == EWOULDBLOCK) {
  5314. err = 0;
  5315. n = 0;
  5316. }
  5317. #endif
  5318. if (n < 0) {
  5319. /* shutdown of the socket at client side */
  5320. return -2;
  5321. }
  5322. }
  5323. if (ctx->stop_flag) {
  5324. return -2;
  5325. }
  5326. if ((n > 0) || ((n == 0) && (len == 0))) {
  5327. /* some data has been read, or no data was requested */
  5328. return n;
  5329. }
  5330. if (n < 0) {
  5331. /* socket error - check errno */
  5332. DEBUG_TRACE("send() failed, error %d", err);
  5333. /* TODO (mid): error handling depending on the error code.
  5334. * These codes are different between Windows and Linux.
  5335. * Currently there is no problem with failing send calls,
  5336. * if there is a reproducible situation, it should be
  5337. * investigated in detail.
  5338. */
  5339. return -2;
  5340. }
  5341. /* Only in case n=0 (timeout), repeat calling the write function */
  5342. /* If send failed, wait before retry */
  5343. if (fp != NULL) {
  5344. /* For files, just wait a fixed time.
  5345. * Maybe it helps, maybe not. */
  5346. mg_sleep(5);
  5347. } else {
  5348. /* For sockets, wait for the socket using poll */
  5349. struct mg_pollfd pfd[1];
  5350. int pollres;
  5351. pfd[0].fd = sock;
  5352. pfd[0].events = POLLOUT;
  5353. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5354. if (ctx->stop_flag) {
  5355. return -2;
  5356. }
  5357. if (pollres > 0) {
  5358. continue;
  5359. }
  5360. }
  5361. if (timeout > 0) {
  5362. now = mg_get_current_time_ns();
  5363. if ((now - start) > timeout_ns) {
  5364. /* Timeout */
  5365. break;
  5366. }
  5367. }
  5368. }
  5369. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5370. used */
  5371. return -1;
  5372. }
  5373. static int
  5374. push_all(struct mg_context *ctx,
  5375. FILE *fp,
  5376. SOCKET sock,
  5377. SSL *ssl,
  5378. const char *buf,
  5379. int len)
  5380. {
  5381. double timeout = -1.0;
  5382. int n, nwritten = 0;
  5383. if (ctx == NULL) {
  5384. return -1;
  5385. }
  5386. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5387. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5388. }
  5389. while ((len > 0) && (ctx->stop_flag == 0)) {
  5390. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5391. if (n < 0) {
  5392. if (nwritten == 0) {
  5393. nwritten = -1; /* Propagate the error */
  5394. }
  5395. break;
  5396. } else if (n == 0) {
  5397. break; /* No more data to write */
  5398. } else {
  5399. nwritten += n;
  5400. len -= n;
  5401. }
  5402. }
  5403. return nwritten;
  5404. }
  5405. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5406. * Return value:
  5407. * >=0 .. number of bytes successfully read
  5408. * -1 .. timeout
  5409. * -2 .. error
  5410. */
  5411. static int
  5412. pull_inner(FILE *fp,
  5413. struct mg_connection *conn,
  5414. char *buf,
  5415. int len,
  5416. double timeout)
  5417. {
  5418. int nread, err = 0;
  5419. #if defined(_WIN32)
  5420. typedef int len_t;
  5421. #else
  5422. typedef size_t len_t;
  5423. #endif
  5424. #if !defined(NO_SSL)
  5425. int ssl_pending;
  5426. #endif
  5427. /* We need an additional wait loop around this, because in some cases
  5428. * with TLSwe may get data from the socket but not from SSL_read.
  5429. * In this case we need to repeat at least once.
  5430. */
  5431. if (fp != NULL) {
  5432. #if !defined(_WIN32_WCE)
  5433. /* Use read() instead of fread(), because if we're reading from the
  5434. * CGI pipe, fread() may block until IO buffer is filled up. We
  5435. * cannot afford to block and must pass all read bytes immediately
  5436. * to the client. */
  5437. nread = (int)read(fileno(fp), buf, (size_t)len);
  5438. #else
  5439. /* WinCE does not support CGI pipes */
  5440. nread = (int)fread(buf, 1, (size_t)len, fp);
  5441. #endif
  5442. err = (nread < 0) ? ERRNO : 0;
  5443. if ((nread == 0) && (len > 0)) {
  5444. /* Should get data, but got EOL */
  5445. return -2;
  5446. }
  5447. #if !defined(NO_SSL)
  5448. } else if ((conn->ssl != NULL)
  5449. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5450. /* We already know there is no more data buffered in conn->buf
  5451. * but there is more available in the SSL layer. So don't poll
  5452. * conn->client.sock yet. */
  5453. if (ssl_pending > len) {
  5454. ssl_pending = len;
  5455. }
  5456. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5457. if (nread <= 0) {
  5458. err = SSL_get_error(conn->ssl, nread);
  5459. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5460. err = ERRNO;
  5461. } else if ((err == SSL_ERROR_WANT_READ)
  5462. || (err == SSL_ERROR_WANT_WRITE)) {
  5463. nread = 0;
  5464. } else {
  5465. /* All errors should return -2 */
  5466. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5467. return -2;
  5468. }
  5469. ERR_clear_error();
  5470. } else {
  5471. err = 0;
  5472. }
  5473. } else if (conn->ssl != NULL) {
  5474. struct mg_pollfd pfd[1];
  5475. int pollres;
  5476. pfd[0].fd = conn->client.sock;
  5477. pfd[0].events = POLLIN;
  5478. pollres = mg_poll(pfd,
  5479. 1,
  5480. (int)(timeout * 1000.0),
  5481. &(conn->phys_ctx->stop_flag));
  5482. if (conn->phys_ctx->stop_flag) {
  5483. return -2;
  5484. }
  5485. if (pollres > 0) {
  5486. nread = SSL_read(conn->ssl, buf, len);
  5487. if (nread <= 0) {
  5488. err = SSL_get_error(conn->ssl, nread);
  5489. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5490. err = ERRNO;
  5491. } else if ((err == SSL_ERROR_WANT_READ)
  5492. || (err == SSL_ERROR_WANT_WRITE)) {
  5493. nread = 0;
  5494. } else {
  5495. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5496. return -2;
  5497. }
  5498. } else {
  5499. err = 0;
  5500. }
  5501. ERR_clear_error();
  5502. } else if (pollres < 0) {
  5503. /* Error */
  5504. return -2;
  5505. } else {
  5506. /* pollres = 0 means timeout */
  5507. nread = 0;
  5508. }
  5509. #endif
  5510. } else {
  5511. struct mg_pollfd pfd[1];
  5512. int pollres;
  5513. pfd[0].fd = conn->client.sock;
  5514. pfd[0].events = POLLIN;
  5515. pollres = mg_poll(pfd,
  5516. 1,
  5517. (int)(timeout * 1000.0),
  5518. &(conn->phys_ctx->stop_flag));
  5519. if (conn->phys_ctx->stop_flag) {
  5520. return -2;
  5521. }
  5522. if (pollres > 0) {
  5523. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5524. err = (nread < 0) ? ERRNO : 0;
  5525. if (nread <= 0) {
  5526. /* shutdown of the socket at client side */
  5527. return -2;
  5528. }
  5529. } else if (pollres < 0) {
  5530. /* error callint poll */
  5531. return -2;
  5532. } else {
  5533. /* pollres = 0 means timeout */
  5534. nread = 0;
  5535. }
  5536. }
  5537. if (conn->phys_ctx->stop_flag) {
  5538. return -2;
  5539. }
  5540. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5541. /* some data has been read, or no data was requested */
  5542. return nread;
  5543. }
  5544. if (nread < 0) {
  5545. /* socket error - check errno */
  5546. #if defined(_WIN32)
  5547. if (err == WSAEWOULDBLOCK) {
  5548. /* TODO (low): check if this is still required */
  5549. /* standard case if called from close_socket_gracefully */
  5550. return -2;
  5551. } else if (err == WSAETIMEDOUT) {
  5552. /* TODO (low): check if this is still required */
  5553. /* timeout is handled by the while loop */
  5554. return 0;
  5555. } else if (err == WSAECONNABORTED) {
  5556. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5557. return -2;
  5558. } else {
  5559. DEBUG_TRACE("recv() failed, error %d", err);
  5560. return -2;
  5561. }
  5562. #else
  5563. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5564. * if the timeout is reached and if the socket was set to non-
  5565. * blocking in close_socket_gracefully, so we can not distinguish
  5566. * here. We have to wait for the timeout in both cases for now.
  5567. */
  5568. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5569. /* TODO (low): check if this is still required */
  5570. /* EAGAIN/EWOULDBLOCK:
  5571. * standard case if called from close_socket_gracefully
  5572. * => should return -1 */
  5573. /* or timeout occurred
  5574. * => the code must stay in the while loop */
  5575. /* EINTR can be generated on a socket with a timeout set even
  5576. * when SA_RESTART is effective for all relevant signals
  5577. * (see signal(7)).
  5578. * => stay in the while loop */
  5579. } else {
  5580. DEBUG_TRACE("recv() failed, error %d", err);
  5581. return -2;
  5582. }
  5583. #endif
  5584. }
  5585. /* Timeout occurred, but no data available. */
  5586. return -1;
  5587. }
  5588. static int
  5589. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5590. {
  5591. int n, nread = 0;
  5592. double timeout = -1.0;
  5593. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5594. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5595. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5596. }
  5597. if (timeout >= 0.0) {
  5598. start_time = mg_get_current_time_ns();
  5599. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5600. }
  5601. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5602. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5603. if (n == -2) {
  5604. if (nread == 0) {
  5605. nread = -1; /* Propagate the error */
  5606. }
  5607. break;
  5608. } else if (n == -1) {
  5609. /* timeout */
  5610. if (timeout >= 0.0) {
  5611. now = mg_get_current_time_ns();
  5612. if ((now - start_time) <= timeout_ns) {
  5613. continue;
  5614. }
  5615. }
  5616. break;
  5617. } else if (n == 0) {
  5618. break; /* No more data to read */
  5619. } else {
  5620. nread += n;
  5621. len -= n;
  5622. }
  5623. }
  5624. return nread;
  5625. }
  5626. static void
  5627. discard_unread_request_data(struct mg_connection *conn)
  5628. {
  5629. char buf[MG_BUF_LEN];
  5630. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5631. ;
  5632. }
  5633. static int
  5634. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5635. {
  5636. int64_t content_len, n, buffered_len, nread;
  5637. int64_t len64 =
  5638. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5639. * int, we may not read more
  5640. * bytes */
  5641. const char *body;
  5642. if (conn == NULL) {
  5643. return 0;
  5644. }
  5645. /* If Content-Length is not set for a response with body data,
  5646. * we do not know in advance how much data should be read. */
  5647. content_len = conn->content_len;
  5648. if (content_len < 0) {
  5649. /* The body data is completed when the connection is closed. */
  5650. content_len = INT64_MAX;
  5651. }
  5652. nread = 0;
  5653. if (conn->consumed_content < content_len) {
  5654. /* Adjust number of bytes to read. */
  5655. int64_t left_to_read = content_len - conn->consumed_content;
  5656. if (left_to_read < len64) {
  5657. /* Do not read more than the total content length of the
  5658. * request.
  5659. */
  5660. len64 = left_to_read;
  5661. }
  5662. /* Return buffered data */
  5663. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5664. - conn->consumed_content;
  5665. if (buffered_len > 0) {
  5666. if (len64 < buffered_len) {
  5667. buffered_len = len64;
  5668. }
  5669. body = conn->buf + conn->request_len + conn->consumed_content;
  5670. memcpy(buf, body, (size_t)buffered_len);
  5671. len64 -= buffered_len;
  5672. conn->consumed_content += buffered_len;
  5673. nread += buffered_len;
  5674. buf = (char *)buf + buffered_len;
  5675. }
  5676. /* We have returned all buffered data. Read new data from the remote
  5677. * socket.
  5678. */
  5679. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5680. conn->consumed_content += n;
  5681. nread += n;
  5682. } else {
  5683. nread = ((nread > 0) ? nread : n);
  5684. }
  5685. }
  5686. return (int)nread;
  5687. }
  5688. int
  5689. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5690. {
  5691. if (len > INT_MAX) {
  5692. len = INT_MAX;
  5693. }
  5694. if (conn == NULL) {
  5695. return 0;
  5696. }
  5697. if (conn->is_chunked) {
  5698. size_t all_read = 0;
  5699. while (len > 0) {
  5700. if (conn->is_chunked >= 3) {
  5701. /* No more data left to read */
  5702. return 0;
  5703. }
  5704. if (conn->is_chunked != 1) {
  5705. /* Has error */
  5706. return -1;
  5707. }
  5708. if (conn->consumed_content != conn->content_len) {
  5709. /* copy from the current chunk */
  5710. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5711. if (read_ret < 1) {
  5712. /* read error */
  5713. conn->is_chunked = 2;
  5714. return -1;
  5715. }
  5716. all_read += (size_t)read_ret;
  5717. len -= (size_t)read_ret;
  5718. if (conn->consumed_content == conn->content_len) {
  5719. /* Add data bytes in the current chunk have been read,
  5720. * so we are expecting \r\n now. */
  5721. char x[2];
  5722. conn->content_len += 2;
  5723. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5724. || (x[1] != '\n')) {
  5725. /* Protocol violation */
  5726. conn->is_chunked = 2;
  5727. return -1;
  5728. }
  5729. }
  5730. } else {
  5731. /* fetch a new chunk */
  5732. size_t i;
  5733. char lenbuf[64];
  5734. char *end = NULL;
  5735. unsigned long chunkSize = 0;
  5736. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5737. conn->content_len++;
  5738. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5739. lenbuf[i] = 0;
  5740. }
  5741. if ((i > 0) && (lenbuf[i] == '\r')
  5742. && (lenbuf[i - 1] != '\r')) {
  5743. continue;
  5744. }
  5745. if ((i > 1) && (lenbuf[i] == '\n')
  5746. && (lenbuf[i - 1] == '\r')) {
  5747. lenbuf[i + 1] = 0;
  5748. chunkSize = strtoul(lenbuf, &end, 16);
  5749. if (chunkSize == 0) {
  5750. /* regular end of content */
  5751. conn->is_chunked = 3;
  5752. }
  5753. break;
  5754. }
  5755. if (!isxdigit((unsigned char)lenbuf[i])) {
  5756. /* illegal character for chunk length */
  5757. conn->is_chunked = 2;
  5758. return -1;
  5759. }
  5760. }
  5761. if ((end == NULL) || (*end != '\r')) {
  5762. /* chunksize not set correctly */
  5763. conn->is_chunked = 2;
  5764. return -1;
  5765. }
  5766. if (chunkSize == 0) {
  5767. /* try discarding trailer for keep-alive */
  5768. conn->content_len += 2;
  5769. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5770. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5771. conn->is_chunked = 4;
  5772. }
  5773. break;
  5774. }
  5775. /* append a new chunk */
  5776. conn->content_len += chunkSize;
  5777. }
  5778. }
  5779. return (int)all_read;
  5780. }
  5781. return mg_read_inner(conn, buf, len);
  5782. }
  5783. int
  5784. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5785. {
  5786. time_t now;
  5787. int n, total, allowed;
  5788. if (conn == NULL) {
  5789. return 0;
  5790. }
  5791. if (len > INT_MAX) {
  5792. return -1;
  5793. }
  5794. if (conn->throttle > 0) {
  5795. if ((now = time(NULL)) != conn->last_throttle_time) {
  5796. conn->last_throttle_time = now;
  5797. conn->last_throttle_bytes = 0;
  5798. }
  5799. allowed = conn->throttle - conn->last_throttle_bytes;
  5800. if (allowed > (int)len) {
  5801. allowed = (int)len;
  5802. }
  5803. if ((total = push_all(conn->phys_ctx,
  5804. NULL,
  5805. conn->client.sock,
  5806. conn->ssl,
  5807. (const char *)buf,
  5808. allowed))
  5809. == allowed) {
  5810. buf = (const char *)buf + total;
  5811. conn->last_throttle_bytes += total;
  5812. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5813. allowed = (conn->throttle > ((int)len - total))
  5814. ? (int)len - total
  5815. : conn->throttle;
  5816. if ((n = push_all(conn->phys_ctx,
  5817. NULL,
  5818. conn->client.sock,
  5819. conn->ssl,
  5820. (const char *)buf,
  5821. allowed))
  5822. != allowed) {
  5823. break;
  5824. }
  5825. sleep(1);
  5826. conn->last_throttle_bytes = allowed;
  5827. conn->last_throttle_time = time(NULL);
  5828. buf = (const char *)buf + n;
  5829. total += n;
  5830. }
  5831. }
  5832. } else {
  5833. total = push_all(conn->phys_ctx,
  5834. NULL,
  5835. conn->client.sock,
  5836. conn->ssl,
  5837. (const char *)buf,
  5838. (int)len);
  5839. }
  5840. if (total > 0) {
  5841. conn->num_bytes_sent += total;
  5842. }
  5843. return total;
  5844. }
  5845. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5846. int
  5847. mg_send_chunk(struct mg_connection *conn,
  5848. const char *chunk,
  5849. unsigned int chunk_len)
  5850. {
  5851. char lenbuf[16];
  5852. size_t lenbuf_len;
  5853. int ret;
  5854. int t;
  5855. /* First store the length information in a text buffer. */
  5856. sprintf(lenbuf, "%x\r\n", chunk_len);
  5857. lenbuf_len = strlen(lenbuf);
  5858. /* Then send length information, chunk and terminating \r\n. */
  5859. ret = mg_write(conn, lenbuf, lenbuf_len);
  5860. if (ret != (int)lenbuf_len) {
  5861. return -1;
  5862. }
  5863. t = ret;
  5864. ret = mg_write(conn, chunk, chunk_len);
  5865. if (ret != (int)chunk_len) {
  5866. return -1;
  5867. }
  5868. t += ret;
  5869. ret = mg_write(conn, "\r\n", 2);
  5870. if (ret != 2) {
  5871. return -1;
  5872. }
  5873. t += ret;
  5874. return t;
  5875. }
  5876. #if defined(GCC_DIAGNOSTIC)
  5877. /* This block forwards format strings to printf implementations,
  5878. * so we need to disable the format-nonliteral warning. */
  5879. #pragma GCC diagnostic push
  5880. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5881. #endif
  5882. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5883. static int
  5884. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5885. {
  5886. va_list ap_copy;
  5887. size_t size = MG_BUF_LEN / 4;
  5888. int len = -1;
  5889. *buf = NULL;
  5890. while (len < 0) {
  5891. if (*buf) {
  5892. mg_free(*buf);
  5893. }
  5894. size *= 4;
  5895. *buf = (char *)mg_malloc(size);
  5896. if (!*buf) {
  5897. break;
  5898. }
  5899. va_copy(ap_copy, ap);
  5900. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5901. va_end(ap_copy);
  5902. (*buf)[size - 1] = 0;
  5903. }
  5904. return len;
  5905. }
  5906. /* Print message to buffer. If buffer is large enough to hold the message,
  5907. * return buffer. If buffer is to small, allocate large enough buffer on
  5908. * heap,
  5909. * and return allocated buffer. */
  5910. static int
  5911. alloc_vprintf(char **out_buf,
  5912. char *prealloc_buf,
  5913. size_t prealloc_size,
  5914. const char *fmt,
  5915. va_list ap)
  5916. {
  5917. va_list ap_copy;
  5918. int len;
  5919. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5920. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5921. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5922. * Therefore, we make two passes: on first pass, get required message
  5923. * length.
  5924. * On second pass, actually print the message. */
  5925. va_copy(ap_copy, ap);
  5926. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5927. va_end(ap_copy);
  5928. if (len < 0) {
  5929. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5930. * Switch to alternative code path that uses incremental
  5931. * allocations.
  5932. */
  5933. va_copy(ap_copy, ap);
  5934. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5935. va_end(ap_copy);
  5936. } else if ((size_t)(len) >= prealloc_size) {
  5937. /* The pre-allocated buffer not large enough. */
  5938. /* Allocate a new buffer. */
  5939. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5940. if (!*out_buf) {
  5941. /* Allocation failed. Return -1 as "out of memory" error. */
  5942. return -1;
  5943. }
  5944. /* Buffer allocation successful. Store the string there. */
  5945. va_copy(ap_copy, ap);
  5946. IGNORE_UNUSED_RESULT(
  5947. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5948. va_end(ap_copy);
  5949. } else {
  5950. /* The pre-allocated buffer is large enough.
  5951. * Use it to store the string and return the address. */
  5952. va_copy(ap_copy, ap);
  5953. IGNORE_UNUSED_RESULT(
  5954. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5955. va_end(ap_copy);
  5956. *out_buf = prealloc_buf;
  5957. }
  5958. return len;
  5959. }
  5960. #if defined(GCC_DIAGNOSTIC)
  5961. /* Enable format-nonliteral warning again. */
  5962. #pragma GCC diagnostic pop
  5963. #endif
  5964. static int
  5965. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5966. {
  5967. char mem[MG_BUF_LEN];
  5968. char *buf = NULL;
  5969. int len;
  5970. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5971. len = mg_write(conn, buf, (size_t)len);
  5972. }
  5973. if (buf != mem) {
  5974. mg_free(buf);
  5975. }
  5976. return len;
  5977. }
  5978. int
  5979. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5980. {
  5981. va_list ap;
  5982. int result;
  5983. va_start(ap, fmt);
  5984. result = mg_vprintf(conn, fmt, ap);
  5985. va_end(ap);
  5986. return result;
  5987. }
  5988. int
  5989. mg_url_decode(const char *src,
  5990. int src_len,
  5991. char *dst,
  5992. int dst_len,
  5993. int is_form_url_encoded)
  5994. {
  5995. int i, j, a, b;
  5996. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5997. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5998. if ((i < src_len - 2) && (src[i] == '%')
  5999. && isxdigit((unsigned char)src[i + 1])
  6000. && isxdigit((unsigned char)src[i + 2])) {
  6001. a = tolower((unsigned char)src[i + 1]);
  6002. b = tolower((unsigned char)src[i + 2]);
  6003. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6004. i += 2;
  6005. } else if (is_form_url_encoded && (src[i] == '+')) {
  6006. dst[j] = ' ';
  6007. } else {
  6008. dst[j] = src[i];
  6009. }
  6010. }
  6011. dst[j] = '\0'; /* Null-terminate the destination */
  6012. return (i >= src_len) ? j : -1;
  6013. }
  6014. int
  6015. mg_get_var(const char *data,
  6016. size_t data_len,
  6017. const char *name,
  6018. char *dst,
  6019. size_t dst_len)
  6020. {
  6021. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6022. }
  6023. int
  6024. mg_get_var2(const char *data,
  6025. size_t data_len,
  6026. const char *name,
  6027. char *dst,
  6028. size_t dst_len,
  6029. size_t occurrence)
  6030. {
  6031. const char *p, *e, *s;
  6032. size_t name_len;
  6033. int len;
  6034. if ((dst == NULL) || (dst_len == 0)) {
  6035. len = -2;
  6036. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6037. len = -1;
  6038. dst[0] = '\0';
  6039. } else {
  6040. name_len = strlen(name);
  6041. e = data + data_len;
  6042. len = -1;
  6043. dst[0] = '\0';
  6044. /* data is "var1=val1&var2=val2...". Find variable first */
  6045. for (p = data; p + name_len < e; p++) {
  6046. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6047. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6048. /* Point p to variable value */
  6049. p += name_len + 1;
  6050. /* Point s to the end of the value */
  6051. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6052. if (s == NULL) {
  6053. s = e;
  6054. }
  6055. DEBUG_ASSERT(s >= p);
  6056. if (s < p) {
  6057. return -3;
  6058. }
  6059. /* Decode variable into destination buffer */
  6060. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6061. /* Redirect error code from -1 to -2 (destination buffer too
  6062. * small). */
  6063. if (len == -1) {
  6064. len = -2;
  6065. }
  6066. break;
  6067. }
  6068. }
  6069. }
  6070. return len;
  6071. }
  6072. /* HCP24: some changes to compare hole var_name */
  6073. int
  6074. mg_get_cookie(const char *cookie_header,
  6075. const char *var_name,
  6076. char *dst,
  6077. size_t dst_size)
  6078. {
  6079. const char *s, *p, *end;
  6080. int name_len, len = -1;
  6081. if ((dst == NULL) || (dst_size == 0)) {
  6082. return -2;
  6083. }
  6084. dst[0] = '\0';
  6085. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6086. return -1;
  6087. }
  6088. name_len = (int)strlen(var_name);
  6089. end = s + strlen(s);
  6090. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6091. if (s[name_len] == '=') {
  6092. /* HCP24: now check is it a substring or a full cookie name */
  6093. if ((s == cookie_header) || (s[-1] == ' ')) {
  6094. s += name_len + 1;
  6095. if ((p = strchr(s, ' ')) == NULL) {
  6096. p = end;
  6097. }
  6098. if (p[-1] == ';') {
  6099. p--;
  6100. }
  6101. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6102. s++;
  6103. p--;
  6104. }
  6105. if ((size_t)(p - s) < dst_size) {
  6106. len = (int)(p - s);
  6107. mg_strlcpy(dst, s, (size_t)len + 1);
  6108. } else {
  6109. len = -3;
  6110. }
  6111. break;
  6112. }
  6113. }
  6114. }
  6115. return len;
  6116. }
  6117. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6118. static void
  6119. base64_encode(const unsigned char *src, int src_len, char *dst)
  6120. {
  6121. static const char *b64 =
  6122. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6123. int i, j, a, b, c;
  6124. for (i = j = 0; i < src_len; i += 3) {
  6125. a = src[i];
  6126. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6127. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6128. dst[j++] = b64[a >> 2];
  6129. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6130. if (i + 1 < src_len) {
  6131. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6132. }
  6133. if (i + 2 < src_len) {
  6134. dst[j++] = b64[c & 63];
  6135. }
  6136. }
  6137. while (j % 4 != 0) {
  6138. dst[j++] = '=';
  6139. }
  6140. dst[j++] = '\0';
  6141. }
  6142. #endif
  6143. #if defined(USE_LUA)
  6144. static unsigned char
  6145. b64reverse(char letter)
  6146. {
  6147. if ((letter >= 'A') && (letter <= 'Z')) {
  6148. return letter - 'A';
  6149. }
  6150. if ((letter >= 'a') && (letter <= 'z')) {
  6151. return letter - 'a' + 26;
  6152. }
  6153. if ((letter >= '0') && (letter <= '9')) {
  6154. return letter - '0' + 52;
  6155. }
  6156. if (letter == '+') {
  6157. return 62;
  6158. }
  6159. if (letter == '/') {
  6160. return 63;
  6161. }
  6162. if (letter == '=') {
  6163. return 255; /* normal end */
  6164. }
  6165. return 254; /* error */
  6166. }
  6167. static int
  6168. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6169. {
  6170. int i;
  6171. unsigned char a, b, c, d;
  6172. *dst_len = 0;
  6173. for (i = 0; i < src_len; i += 4) {
  6174. a = b64reverse(src[i]);
  6175. if (a >= 254) {
  6176. return i;
  6177. }
  6178. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6179. if (b >= 254) {
  6180. return i + 1;
  6181. }
  6182. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6183. if (c == 254) {
  6184. return i + 2;
  6185. }
  6186. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6187. if (d == 254) {
  6188. return i + 3;
  6189. }
  6190. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6191. if (c != 255) {
  6192. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6193. if (d != 255) {
  6194. dst[(*dst_len)++] = (c << 6) + d;
  6195. }
  6196. }
  6197. }
  6198. return -1;
  6199. }
  6200. #endif
  6201. static int
  6202. is_put_or_delete_method(const struct mg_connection *conn)
  6203. {
  6204. if (conn) {
  6205. const char *s = conn->request_info.request_method;
  6206. return (s != NULL)
  6207. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6208. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6209. }
  6210. return 0;
  6211. }
  6212. #if !defined(NO_FILES)
  6213. static int
  6214. extention_matches_script(
  6215. struct mg_connection *conn, /* in: request (must be valid) */
  6216. const char *filename /* in: filename (must be valid) */
  6217. )
  6218. {
  6219. #if !defined(NO_CGI)
  6220. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6221. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6222. filename)
  6223. > 0) {
  6224. return 1;
  6225. }
  6226. #endif
  6227. #if defined(USE_LUA)
  6228. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6229. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6230. filename)
  6231. > 0) {
  6232. return 1;
  6233. }
  6234. #endif
  6235. #if defined(USE_DUKTAPE)
  6236. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6237. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6238. filename)
  6239. > 0) {
  6240. return 1;
  6241. }
  6242. #endif
  6243. /* filename and conn could be unused, if all preocessor conditions
  6244. * are false (no script language supported). */
  6245. (void)filename;
  6246. (void)conn;
  6247. return 0;
  6248. }
  6249. /* For given directory path, substitute it to valid index file.
  6250. * Return 1 if index file has been found, 0 if not found.
  6251. * If the file is found, it's stats is returned in stp. */
  6252. static int
  6253. substitute_index_file(struct mg_connection *conn,
  6254. char *path,
  6255. size_t path_len,
  6256. struct mg_file_stat *filestat)
  6257. {
  6258. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6259. struct vec filename_vec;
  6260. size_t n = strlen(path);
  6261. int found = 0;
  6262. /* The 'path' given to us points to the directory. Remove all trailing
  6263. * directory separator characters from the end of the path, and
  6264. * then append single directory separator character. */
  6265. while ((n > 0) && (path[n - 1] == '/')) {
  6266. n--;
  6267. }
  6268. path[n] = '/';
  6269. /* Traverse index files list. For each entry, append it to the given
  6270. * path and see if the file exists. If it exists, break the loop */
  6271. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6272. /* Ignore too long entries that may overflow path buffer */
  6273. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6274. continue;
  6275. }
  6276. /* Prepare full path to the index file */
  6277. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6278. /* Does it exist? */
  6279. if (mg_stat(conn, path, filestat)) {
  6280. /* Yes it does, break the loop */
  6281. found = 1;
  6282. break;
  6283. }
  6284. }
  6285. /* If no index file exists, restore directory path */
  6286. if (!found) {
  6287. path[n] = '\0';
  6288. }
  6289. return found;
  6290. }
  6291. #endif
  6292. static void
  6293. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6294. char *filename, /* out: filename */
  6295. size_t filename_buf_len, /* in: size of filename buffer */
  6296. struct mg_file_stat *filestat, /* out: file status structure */
  6297. int *is_found, /* out: file found (directly) */
  6298. int *is_script_resource, /* out: handled by a script? */
  6299. int *is_websocket_request, /* out: websocket connetion? */
  6300. int *is_put_or_delete_request /* out: put/delete a file? */
  6301. )
  6302. {
  6303. char const *accept_encoding;
  6304. #if !defined(NO_FILES)
  6305. const char *uri = conn->request_info.local_uri;
  6306. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6307. const char *rewrite;
  6308. struct vec a, b;
  6309. ptrdiff_t match_len;
  6310. char gz_path[PATH_MAX];
  6311. int truncated;
  6312. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6313. char *tmp_str;
  6314. size_t tmp_str_len, sep_pos;
  6315. int allow_substitute_script_subresources;
  6316. #endif
  6317. #else
  6318. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6319. #endif
  6320. /* Step 1: Set all initially unknown outputs to zero */
  6321. memset(filestat, 0, sizeof(*filestat));
  6322. *filename = 0;
  6323. *is_found = 0;
  6324. *is_script_resource = 0;
  6325. /* Step 2: Check if the request attempts to modify the file system */
  6326. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6327. /* Step 3: Check if it is a websocket request, and modify the document
  6328. * root if required */
  6329. #if defined(USE_WEBSOCKET)
  6330. *is_websocket_request = is_websocket_protocol(conn);
  6331. #if !defined(NO_FILES)
  6332. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6333. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6334. }
  6335. #endif /* !NO_FILES */
  6336. #else /* USE_WEBSOCKET */
  6337. *is_websocket_request = 0;
  6338. #endif /* USE_WEBSOCKET */
  6339. /* Step 4: Check if gzip encoded response is allowed */
  6340. conn->accept_gzip = 0;
  6341. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6342. if (strstr(accept_encoding, "gzip") != NULL) {
  6343. conn->accept_gzip = 1;
  6344. }
  6345. }
  6346. #if !defined(NO_FILES)
  6347. /* Step 5: If there is no root directory, don't look for files. */
  6348. /* Note that root == NULL is a regular use case here. This occurs,
  6349. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6350. * config is not required. */
  6351. if (root == NULL) {
  6352. /* all file related outputs have already been set to 0, just return
  6353. */
  6354. return;
  6355. }
  6356. /* Step 6: Determine the local file path from the root path and the
  6357. * request uri. */
  6358. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6359. * part of the path one byte on the right. */
  6360. mg_snprintf(
  6361. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6362. if (truncated) {
  6363. goto interpret_cleanup;
  6364. }
  6365. /* Step 7: URI rewriting */
  6366. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6367. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6368. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6369. mg_snprintf(conn,
  6370. &truncated,
  6371. filename,
  6372. filename_buf_len - 1,
  6373. "%.*s%s",
  6374. (int)b.len,
  6375. b.ptr,
  6376. uri + match_len);
  6377. break;
  6378. }
  6379. }
  6380. if (truncated) {
  6381. goto interpret_cleanup;
  6382. }
  6383. /* Step 8: Check if the file exists at the server */
  6384. /* Local file path and name, corresponding to requested URI
  6385. * is now stored in "filename" variable. */
  6386. if (mg_stat(conn, filename, filestat)) {
  6387. int uri_len = (int)strlen(uri);
  6388. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6389. /* 8.1: File exists. */
  6390. *is_found = 1;
  6391. /* 8.2: Check if it is a script type. */
  6392. if (extention_matches_script(conn, filename)) {
  6393. /* The request addresses a CGI resource, Lua script or
  6394. * server-side javascript.
  6395. * The URI corresponds to the script itself (like
  6396. * /path/script.cgi), and there is no additional resource
  6397. * path (like /path/script.cgi/something).
  6398. * Requests that modify (replace or delete) a resource, like
  6399. * PUT and DELETE requests, should replace/delete the script
  6400. * file.
  6401. * Requests that read or write from/to a resource, like GET and
  6402. * POST requests, should call the script and return the
  6403. * generated response. */
  6404. *is_script_resource = (!*is_put_or_delete_request);
  6405. }
  6406. /* 8.3: If the request target is a directory, there could be
  6407. * a substitute file (index.html, index.cgi, ...). */
  6408. if (filestat->is_directory && is_uri_end_slash) {
  6409. /* Use a local copy here, since substitute_index_file will
  6410. * change the content of the file status */
  6411. struct mg_file_stat tmp_filestat;
  6412. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6413. if (substitute_index_file(
  6414. conn, filename, filename_buf_len, &tmp_filestat)) {
  6415. /* Substitute file found. Copy stat to the output, then
  6416. * check if the file is a script file */
  6417. *filestat = tmp_filestat;
  6418. if (extention_matches_script(conn, filename)) {
  6419. /* Substitute file is a script file */
  6420. *is_script_resource = 1;
  6421. } else {
  6422. /* Substitute file is a regular file */
  6423. *is_script_resource = 0;
  6424. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6425. }
  6426. }
  6427. /* If there is no substitute file, the server could return
  6428. * a directory listing in a later step */
  6429. }
  6430. return;
  6431. }
  6432. /* Step 9: Check for zipped files: */
  6433. /* If we can't find the actual file, look for the file
  6434. * with the same name but a .gz extension. If we find it,
  6435. * use that and set the gzipped flag in the file struct
  6436. * to indicate that the response need to have the content-
  6437. * encoding: gzip header.
  6438. * We can only do this if the browser declares support. */
  6439. if (conn->accept_gzip) {
  6440. mg_snprintf(
  6441. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6442. if (truncated) {
  6443. goto interpret_cleanup;
  6444. }
  6445. if (mg_stat(conn, gz_path, filestat)) {
  6446. if (filestat) {
  6447. filestat->is_gzipped = 1;
  6448. *is_found = 1;
  6449. }
  6450. /* Currently gz files can not be scripts. */
  6451. return;
  6452. }
  6453. }
  6454. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6455. /* Step 10: Script resources may handle sub-resources */
  6456. /* Support PATH_INFO for CGI scripts. */
  6457. tmp_str_len = strlen(filename);
  6458. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6459. if (!tmp_str) {
  6460. /* Out of memory */
  6461. goto interpret_cleanup;
  6462. }
  6463. memcpy(tmp_str, filename, tmp_str_len + 1);
  6464. /* Check config, if index scripts may have sub-resources */
  6465. allow_substitute_script_subresources =
  6466. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6467. "yes");
  6468. sep_pos = tmp_str_len;
  6469. while (sep_pos > 0) {
  6470. sep_pos--;
  6471. if (tmp_str[sep_pos] == '/') {
  6472. int is_script = 0, does_exist = 0;
  6473. tmp_str[sep_pos] = 0;
  6474. if (tmp_str[0]) {
  6475. is_script = extention_matches_script(conn, tmp_str);
  6476. does_exist = mg_stat(conn, tmp_str, filestat);
  6477. }
  6478. if (does_exist && is_script) {
  6479. filename[sep_pos] = 0;
  6480. memmove(filename + sep_pos + 2,
  6481. filename + sep_pos + 1,
  6482. strlen(filename + sep_pos + 1) + 1);
  6483. conn->path_info = filename + sep_pos + 1;
  6484. filename[sep_pos + 1] = '/';
  6485. *is_script_resource = 1;
  6486. *is_found = 1;
  6487. break;
  6488. }
  6489. if (allow_substitute_script_subresources) {
  6490. if (substitute_index_file(
  6491. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6492. /* some intermediate directory has an index file */
  6493. if (extention_matches_script(conn, tmp_str)) {
  6494. char *tmp_str2;
  6495. DEBUG_TRACE("Substitute script %s serving path %s",
  6496. tmp_str,
  6497. filename);
  6498. /* this index file is a script */
  6499. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6500. conn->phys_ctx);
  6501. mg_snprintf(conn,
  6502. &truncated,
  6503. filename,
  6504. filename_buf_len,
  6505. "%s//%s",
  6506. tmp_str,
  6507. tmp_str2);
  6508. mg_free(tmp_str2);
  6509. if (truncated) {
  6510. mg_free(tmp_str);
  6511. goto interpret_cleanup;
  6512. }
  6513. sep_pos = strlen(tmp_str);
  6514. filename[sep_pos] = 0;
  6515. conn->path_info = filename + sep_pos + 1;
  6516. *is_script_resource = 1;
  6517. *is_found = 1;
  6518. break;
  6519. } else {
  6520. DEBUG_TRACE("Substitute file %s serving path %s",
  6521. tmp_str,
  6522. filename);
  6523. /* non-script files will not have sub-resources */
  6524. filename[sep_pos] = 0;
  6525. conn->path_info = 0;
  6526. *is_script_resource = 0;
  6527. *is_found = 0;
  6528. break;
  6529. }
  6530. }
  6531. }
  6532. tmp_str[sep_pos] = '/';
  6533. }
  6534. }
  6535. mg_free(tmp_str);
  6536. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6537. #endif /* !defined(NO_FILES) */
  6538. return;
  6539. #if !defined(NO_FILES)
  6540. /* Reset all outputs */
  6541. interpret_cleanup:
  6542. memset(filestat, 0, sizeof(*filestat));
  6543. *filename = 0;
  6544. *is_found = 0;
  6545. *is_script_resource = 0;
  6546. *is_websocket_request = 0;
  6547. *is_put_or_delete_request = 0;
  6548. #endif /* !defined(NO_FILES) */
  6549. }
  6550. /* Check whether full request is buffered. Return:
  6551. * -1 if request or response is malformed
  6552. * 0 if request or response is not yet fully buffered
  6553. * >0 actual request length, including last \r\n\r\n */
  6554. static int
  6555. get_http_header_len(const char *buf, int buflen)
  6556. {
  6557. int i;
  6558. for (i = 0; i < buflen; i++) {
  6559. /* Do an unsigned comparison in some conditions below */
  6560. const unsigned char c = (unsigned char)buf[i];
  6561. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6562. && !isprint(c)) {
  6563. /* abort scan as soon as one malformed character is found */
  6564. return -1;
  6565. }
  6566. if (i < buflen - 1) {
  6567. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6568. /* Two newline, no carriage return - not standard compliant,
  6569. * but
  6570. * it
  6571. * should be accepted */
  6572. return i + 2;
  6573. }
  6574. }
  6575. if (i < buflen - 3) {
  6576. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6577. && (buf[i + 3] == '\n')) {
  6578. /* Two \r\n - standard compliant */
  6579. return i + 4;
  6580. }
  6581. }
  6582. }
  6583. return 0;
  6584. }
  6585. #if !defined(NO_CACHING)
  6586. /* Convert month to the month number. Return -1 on error, or month number */
  6587. static int
  6588. get_month_index(const char *s)
  6589. {
  6590. size_t i;
  6591. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6592. if (!strcmp(s, month_names[i])) {
  6593. return (int)i;
  6594. }
  6595. }
  6596. return -1;
  6597. }
  6598. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6599. static time_t
  6600. parse_date_string(const char *datetime)
  6601. {
  6602. char month_str[32] = {0};
  6603. int second, minute, hour, day, month, year;
  6604. time_t result = (time_t)0;
  6605. struct tm tm;
  6606. if ((sscanf(datetime,
  6607. "%d/%3s/%d %d:%d:%d",
  6608. &day,
  6609. month_str,
  6610. &year,
  6611. &hour,
  6612. &minute,
  6613. &second)
  6614. == 6)
  6615. || (sscanf(datetime,
  6616. "%d %3s %d %d:%d:%d",
  6617. &day,
  6618. month_str,
  6619. &year,
  6620. &hour,
  6621. &minute,
  6622. &second)
  6623. == 6)
  6624. || (sscanf(datetime,
  6625. "%*3s, %d %3s %d %d:%d:%d",
  6626. &day,
  6627. month_str,
  6628. &year,
  6629. &hour,
  6630. &minute,
  6631. &second)
  6632. == 6)
  6633. || (sscanf(datetime,
  6634. "%d-%3s-%d %d:%d:%d",
  6635. &day,
  6636. month_str,
  6637. &year,
  6638. &hour,
  6639. &minute,
  6640. &second)
  6641. == 6)) {
  6642. month = get_month_index(month_str);
  6643. if ((month >= 0) && (year >= 1970)) {
  6644. memset(&tm, 0, sizeof(tm));
  6645. tm.tm_year = year - 1900;
  6646. tm.tm_mon = month;
  6647. tm.tm_mday = day;
  6648. tm.tm_hour = hour;
  6649. tm.tm_min = minute;
  6650. tm.tm_sec = second;
  6651. result = timegm(&tm);
  6652. }
  6653. }
  6654. return result;
  6655. }
  6656. #endif /* !NO_CACHING */
  6657. /* Protect against directory disclosure attack by removing '..',
  6658. * excessive '/' and '\' characters */
  6659. static void
  6660. remove_double_dots_and_double_slashes(char *s)
  6661. {
  6662. char *p = s;
  6663. while ((s[0] == '.') && (s[1] == '.')) {
  6664. s++;
  6665. }
  6666. while (*s != '\0') {
  6667. *p++ = *s++;
  6668. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6669. /* Skip all following slashes, backslashes and double-dots */
  6670. while (s[0] != '\0') {
  6671. if ((s[0] == '/') || (s[0] == '\\')) {
  6672. s++;
  6673. } else if ((s[0] == '.') && (s[1] == '.')) {
  6674. s += 2;
  6675. } else {
  6676. break;
  6677. }
  6678. }
  6679. }
  6680. }
  6681. *p = '\0';
  6682. }
  6683. static const struct {
  6684. const char *extension;
  6685. size_t ext_len;
  6686. const char *mime_type;
  6687. } builtin_mime_types[] = {
  6688. /* IANA registered MIME types
  6689. * (http://www.iana.org/assignments/media-types)
  6690. * application types */
  6691. {".doc", 4, "application/msword"},
  6692. {".eps", 4, "application/postscript"},
  6693. {".exe", 4, "application/octet-stream"},
  6694. {".js", 3, "application/javascript"},
  6695. {".json", 5, "application/json"},
  6696. {".pdf", 4, "application/pdf"},
  6697. {".ps", 3, "application/postscript"},
  6698. {".rtf", 4, "application/rtf"},
  6699. {".xhtml", 6, "application/xhtml+xml"},
  6700. {".xsl", 4, "application/xml"},
  6701. {".xslt", 5, "application/xml"},
  6702. /* fonts */
  6703. {".ttf", 4, "application/font-sfnt"},
  6704. {".cff", 4, "application/font-sfnt"},
  6705. {".otf", 4, "application/font-sfnt"},
  6706. {".aat", 4, "application/font-sfnt"},
  6707. {".sil", 4, "application/font-sfnt"},
  6708. {".pfr", 4, "application/font-tdpfr"},
  6709. {".woff", 5, "application/font-woff"},
  6710. /* audio */
  6711. {".mp3", 4, "audio/mpeg"},
  6712. {".oga", 4, "audio/ogg"},
  6713. {".ogg", 4, "audio/ogg"},
  6714. /* image */
  6715. {".gif", 4, "image/gif"},
  6716. {".ief", 4, "image/ief"},
  6717. {".jpeg", 5, "image/jpeg"},
  6718. {".jpg", 4, "image/jpeg"},
  6719. {".jpm", 4, "image/jpm"},
  6720. {".jpx", 4, "image/jpx"},
  6721. {".png", 4, "image/png"},
  6722. {".svg", 4, "image/svg+xml"},
  6723. {".tif", 4, "image/tiff"},
  6724. {".tiff", 5, "image/tiff"},
  6725. /* model */
  6726. {".wrl", 4, "model/vrml"},
  6727. /* text */
  6728. {".css", 4, "text/css"},
  6729. {".csv", 4, "text/csv"},
  6730. {".htm", 4, "text/html"},
  6731. {".html", 5, "text/html"},
  6732. {".sgm", 4, "text/sgml"},
  6733. {".shtm", 5, "text/html"},
  6734. {".shtml", 6, "text/html"},
  6735. {".txt", 4, "text/plain"},
  6736. {".xml", 4, "text/xml"},
  6737. /* video */
  6738. {".mov", 4, "video/quicktime"},
  6739. {".mp4", 4, "video/mp4"},
  6740. {".mpeg", 5, "video/mpeg"},
  6741. {".mpg", 4, "video/mpeg"},
  6742. {".ogv", 4, "video/ogg"},
  6743. {".qt", 3, "video/quicktime"},
  6744. /* not registered types
  6745. * (http://reference.sitepoint.com/html/mime-types-full,
  6746. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6747. {".arj", 4, "application/x-arj-compressed"},
  6748. {".gz", 3, "application/x-gunzip"},
  6749. {".rar", 4, "application/x-arj-compressed"},
  6750. {".swf", 4, "application/x-shockwave-flash"},
  6751. {".tar", 4, "application/x-tar"},
  6752. {".tgz", 4, "application/x-tar-gz"},
  6753. {".torrent", 8, "application/x-bittorrent"},
  6754. {".ppt", 4, "application/x-mspowerpoint"},
  6755. {".xls", 4, "application/x-msexcel"},
  6756. {".zip", 4, "application/x-zip-compressed"},
  6757. {".aac",
  6758. 4,
  6759. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6760. {".aif", 4, "audio/x-aif"},
  6761. {".m3u", 4, "audio/x-mpegurl"},
  6762. {".mid", 4, "audio/x-midi"},
  6763. {".ra", 3, "audio/x-pn-realaudio"},
  6764. {".ram", 4, "audio/x-pn-realaudio"},
  6765. {".wav", 4, "audio/x-wav"},
  6766. {".bmp", 4, "image/bmp"},
  6767. {".ico", 4, "image/x-icon"},
  6768. {".pct", 4, "image/x-pct"},
  6769. {".pict", 5, "image/pict"},
  6770. {".rgb", 4, "image/x-rgb"},
  6771. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6772. {".asf", 4, "video/x-ms-asf"},
  6773. {".avi", 4, "video/x-msvideo"},
  6774. {".m4v", 4, "video/x-m4v"},
  6775. {NULL, 0, NULL}};
  6776. const char *
  6777. mg_get_builtin_mime_type(const char *path)
  6778. {
  6779. const char *ext;
  6780. size_t i, path_len;
  6781. path_len = strlen(path);
  6782. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6783. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6784. if ((path_len > builtin_mime_types[i].ext_len)
  6785. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6786. return builtin_mime_types[i].mime_type;
  6787. }
  6788. }
  6789. return "text/plain";
  6790. }
  6791. /* Look at the "path" extension and figure what mime type it has.
  6792. * Store mime type in the vector. */
  6793. static void
  6794. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6795. {
  6796. struct vec ext_vec, mime_vec;
  6797. const char *list, *ext;
  6798. size_t path_len;
  6799. path_len = strlen(path);
  6800. if ((conn == NULL) || (vec == NULL)) {
  6801. if (vec != NULL) {
  6802. memset(vec, '\0', sizeof(struct vec));
  6803. }
  6804. return;
  6805. }
  6806. /* Scan user-defined mime types first, in case user wants to
  6807. * override default mime types. */
  6808. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6809. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6810. /* ext now points to the path suffix */
  6811. ext = path + path_len - ext_vec.len;
  6812. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6813. *vec = mime_vec;
  6814. return;
  6815. }
  6816. }
  6817. vec->ptr = mg_get_builtin_mime_type(path);
  6818. vec->len = strlen(vec->ptr);
  6819. }
  6820. /* Stringify binary data. Output buffer must be twice as big as input,
  6821. * because each byte takes 2 bytes in string representation */
  6822. static void
  6823. bin2str(char *to, const unsigned char *p, size_t len)
  6824. {
  6825. static const char *hex = "0123456789abcdef";
  6826. for (; len--; p++) {
  6827. *to++ = hex[p[0] >> 4];
  6828. *to++ = hex[p[0] & 0x0f];
  6829. }
  6830. *to = '\0';
  6831. }
  6832. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6833. */
  6834. char *
  6835. mg_md5(char buf[33], ...)
  6836. {
  6837. md5_byte_t hash[16];
  6838. const char *p;
  6839. va_list ap;
  6840. md5_state_t ctx;
  6841. md5_init(&ctx);
  6842. va_start(ap, buf);
  6843. while ((p = va_arg(ap, const char *)) != NULL) {
  6844. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6845. }
  6846. va_end(ap);
  6847. md5_finish(&ctx, hash);
  6848. bin2str(buf, hash, sizeof(hash));
  6849. return buf;
  6850. }
  6851. /* Check the user's password, return 1 if OK */
  6852. static int
  6853. check_password(const char *method,
  6854. const char *ha1,
  6855. const char *uri,
  6856. const char *nonce,
  6857. const char *nc,
  6858. const char *cnonce,
  6859. const char *qop,
  6860. const char *response)
  6861. {
  6862. char ha2[32 + 1], expected_response[32 + 1];
  6863. /* Some of the parameters may be NULL */
  6864. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6865. || (qop == NULL) || (response == NULL)) {
  6866. return 0;
  6867. }
  6868. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6869. if (strlen(response) != 32) {
  6870. return 0;
  6871. }
  6872. mg_md5(ha2, method, ":", uri, NULL);
  6873. mg_md5(expected_response,
  6874. ha1,
  6875. ":",
  6876. nonce,
  6877. ":",
  6878. nc,
  6879. ":",
  6880. cnonce,
  6881. ":",
  6882. qop,
  6883. ":",
  6884. ha2,
  6885. NULL);
  6886. return mg_strcasecmp(response, expected_response) == 0;
  6887. }
  6888. #if !defined(NO_FILESYSTEMS)
  6889. /* Use the global passwords file, if specified by auth_gpass option,
  6890. * or search for .htpasswd in the requested directory. */
  6891. static void
  6892. open_auth_file(struct mg_connection *conn,
  6893. const char *path,
  6894. struct mg_file *filep)
  6895. {
  6896. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6897. char name[PATH_MAX];
  6898. const char *p, *e,
  6899. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6900. int truncated;
  6901. if (gpass != NULL) {
  6902. /* Use global passwords file */
  6903. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6904. #if defined(DEBUG)
  6905. /* Use mg_cry_internal here, since gpass has been configured. */
  6906. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6907. #endif
  6908. }
  6909. /* Important: using local struct mg_file to test path for
  6910. * is_directory flag. If filep is used, mg_stat() makes it
  6911. * appear as if auth file was opened.
  6912. * TODO(mid): Check if this is still required after rewriting
  6913. * mg_stat */
  6914. } else if (mg_stat(conn, path, &filep->stat)
  6915. && filep->stat.is_directory) {
  6916. mg_snprintf(conn,
  6917. &truncated,
  6918. name,
  6919. sizeof(name),
  6920. "%s/%s",
  6921. path,
  6922. PASSWORDS_FILE_NAME);
  6923. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6924. #if defined(DEBUG)
  6925. /* Don't use mg_cry_internal here, but only a trace, since this
  6926. * is
  6927. * a typical case. It will occur for every directory
  6928. * without a password file. */
  6929. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6930. #endif
  6931. }
  6932. } else {
  6933. /* Try to find .htpasswd in requested directory. */
  6934. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6935. if (e[0] == '/') {
  6936. break;
  6937. }
  6938. }
  6939. mg_snprintf(conn,
  6940. &truncated,
  6941. name,
  6942. sizeof(name),
  6943. "%.*s/%s",
  6944. (int)(e - p),
  6945. p,
  6946. PASSWORDS_FILE_NAME);
  6947. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6948. #if defined(DEBUG)
  6949. /* Don't use mg_cry_internal here, but only a trace, since this
  6950. * is
  6951. * a typical case. It will occur for every directory
  6952. * without a password file. */
  6953. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6954. #endif
  6955. }
  6956. }
  6957. }
  6958. }
  6959. #endif /* NO_FILESYSTEMS */
  6960. /* Parsed Authorization header */
  6961. struct ah {
  6962. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6963. };
  6964. /* Return 1 on success. Always initializes the ah structure. */
  6965. static int
  6966. parse_auth_header(struct mg_connection *conn,
  6967. char *buf,
  6968. size_t buf_size,
  6969. struct ah *ah)
  6970. {
  6971. char *name, *value, *s;
  6972. const char *auth_header;
  6973. uint64_t nonce;
  6974. if (!ah || !conn) {
  6975. return 0;
  6976. }
  6977. (void)memset(ah, 0, sizeof(*ah));
  6978. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6979. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6980. return 0;
  6981. }
  6982. /* Make modifiable copy of the auth header */
  6983. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6984. s = buf;
  6985. /* Parse authorization header */
  6986. for (;;) {
  6987. /* Gobble initial spaces */
  6988. while (isspace((unsigned char)*s)) {
  6989. s++;
  6990. }
  6991. name = skip_quoted(&s, "=", " ", 0);
  6992. /* Value is either quote-delimited, or ends at first comma or space.
  6993. */
  6994. if (s[0] == '\"') {
  6995. s++;
  6996. value = skip_quoted(&s, "\"", " ", '\\');
  6997. if (s[0] == ',') {
  6998. s++;
  6999. }
  7000. } else {
  7001. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  7002. * spaces */
  7003. }
  7004. if (*name == '\0') {
  7005. break;
  7006. }
  7007. if (!strcmp(name, "username")) {
  7008. ah->user = value;
  7009. } else if (!strcmp(name, "cnonce")) {
  7010. ah->cnonce = value;
  7011. } else if (!strcmp(name, "response")) {
  7012. ah->response = value;
  7013. } else if (!strcmp(name, "uri")) {
  7014. ah->uri = value;
  7015. } else if (!strcmp(name, "qop")) {
  7016. ah->qop = value;
  7017. } else if (!strcmp(name, "nc")) {
  7018. ah->nc = value;
  7019. } else if (!strcmp(name, "nonce")) {
  7020. ah->nonce = value;
  7021. }
  7022. }
  7023. #if !defined(NO_NONCE_CHECK)
  7024. /* Read the nonce from the response. */
  7025. if (ah->nonce == NULL) {
  7026. return 0;
  7027. }
  7028. s = NULL;
  7029. nonce = strtoull(ah->nonce, &s, 10);
  7030. if ((s == NULL) || (*s != 0)) {
  7031. return 0;
  7032. }
  7033. /* Convert the nonce from the client to a number. */
  7034. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7035. /* The converted number corresponds to the time the nounce has been
  7036. * created. This should not be earlier than the server start. */
  7037. /* Server side nonce check is valuable in all situations but one:
  7038. * if the server restarts frequently, but the client should not see
  7039. * that, so the server should accept nonces from previous starts. */
  7040. /* However, the reasonable default is to not accept a nonce from a
  7041. * previous start, so if anyone changed the access rights between
  7042. * two restarts, a new login is required. */
  7043. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7044. /* nonce is from a previous start of the server and no longer valid
  7045. * (replay attack?) */
  7046. return 0;
  7047. }
  7048. /* Check if the nonce is too high, so it has not (yet) been used by the
  7049. * server. */
  7050. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7051. + conn->dom_ctx->nonce_count)) {
  7052. return 0;
  7053. }
  7054. #else
  7055. (void)nonce;
  7056. #endif
  7057. /* CGI needs it as REMOTE_USER */
  7058. if (ah->user != NULL) {
  7059. conn->request_info.remote_user =
  7060. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7061. } else {
  7062. return 0;
  7063. }
  7064. return 1;
  7065. }
  7066. static const char *
  7067. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7068. {
  7069. #if defined(MG_USE_OPEN_FILE)
  7070. const char *eof;
  7071. size_t len;
  7072. const char *memend;
  7073. #else
  7074. (void)p; /* parameter is unused */
  7075. #endif
  7076. if (!filep) {
  7077. return NULL;
  7078. }
  7079. #if defined(MG_USE_OPEN_FILE)
  7080. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7081. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7082. /* Search for \n from p till the end of stream */
  7083. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7084. if (eof != NULL) {
  7085. eof += 1; /* Include \n */
  7086. } else {
  7087. eof = memend; /* Copy remaining data */
  7088. }
  7089. len =
  7090. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7091. memcpy(buf, *p, len);
  7092. buf[len] = '\0';
  7093. *p += len;
  7094. return len ? eof : NULL;
  7095. } else /* filep->access.fp block below */
  7096. #endif
  7097. if (filep->access.fp != NULL) {
  7098. return fgets(buf, (int)size, filep->access.fp);
  7099. } else {
  7100. return NULL;
  7101. }
  7102. }
  7103. /* Define the initial recursion depth for procesesing htpasswd files that
  7104. * include other htpasswd
  7105. * (or even the same) files. It is not difficult to provide a file or files
  7106. * s.t. they force civetweb
  7107. * to infinitely recurse and then crash.
  7108. */
  7109. #define INITIAL_DEPTH 9
  7110. #if INITIAL_DEPTH <= 0
  7111. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7112. #endif
  7113. #if !defined(NO_FILESYSTEMS)
  7114. struct read_auth_file_struct {
  7115. struct mg_connection *conn;
  7116. struct ah ah;
  7117. const char *domain;
  7118. char buf[256 + 256 + 40];
  7119. const char *f_user;
  7120. const char *f_domain;
  7121. const char *f_ha1;
  7122. };
  7123. static int
  7124. read_auth_file(struct mg_file *filep,
  7125. struct read_auth_file_struct *workdata,
  7126. int depth)
  7127. {
  7128. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7129. int is_authorized = 0;
  7130. struct mg_file fp;
  7131. size_t l;
  7132. if (!filep || !workdata || (0 == depth)) {
  7133. return 0;
  7134. }
  7135. /* Loop over passwords file */
  7136. #if defined(MG_USE_OPEN_FILE)
  7137. p = (char *)filep->access.membuf;
  7138. #endif
  7139. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7140. l = strlen(workdata->buf);
  7141. while (l > 0) {
  7142. if (isspace((unsigned char)workdata->buf[l - 1])
  7143. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7144. l--;
  7145. workdata->buf[l] = 0;
  7146. } else
  7147. break;
  7148. }
  7149. if (l < 1) {
  7150. continue;
  7151. }
  7152. workdata->f_user = workdata->buf;
  7153. if (workdata->f_user[0] == ':') {
  7154. /* user names may not contain a ':' and may not be empty,
  7155. * so lines starting with ':' may be used for a special purpose
  7156. */
  7157. if (workdata->f_user[1] == '#') {
  7158. /* :# is a comment */
  7159. continue;
  7160. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7161. if (mg_fopen(workdata->conn,
  7162. workdata->f_user + 9,
  7163. MG_FOPEN_MODE_READ,
  7164. &fp)) {
  7165. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7166. (void)mg_fclose(
  7167. &fp.access); /* ignore error on read only file */
  7168. /* No need to continue processing files once we have a
  7169. * match, since nothing will reset it back
  7170. * to 0.
  7171. */
  7172. if (is_authorized) {
  7173. return is_authorized;
  7174. }
  7175. } else {
  7176. mg_cry_internal(workdata->conn,
  7177. "%s: cannot open authorization file: %s",
  7178. __func__,
  7179. workdata->buf);
  7180. }
  7181. continue;
  7182. }
  7183. /* everything is invalid for the moment (might change in the
  7184. * future) */
  7185. mg_cry_internal(workdata->conn,
  7186. "%s: syntax error in authorization file: %s",
  7187. __func__,
  7188. workdata->buf);
  7189. continue;
  7190. }
  7191. workdata->f_domain = strchr(workdata->f_user, ':');
  7192. if (workdata->f_domain == NULL) {
  7193. mg_cry_internal(workdata->conn,
  7194. "%s: syntax error in authorization file: %s",
  7195. __func__,
  7196. workdata->buf);
  7197. continue;
  7198. }
  7199. *(char *)(workdata->f_domain) = 0;
  7200. (workdata->f_domain)++;
  7201. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7202. if (workdata->f_ha1 == NULL) {
  7203. mg_cry_internal(workdata->conn,
  7204. "%s: syntax error in authorization file: %s",
  7205. __func__,
  7206. workdata->buf);
  7207. continue;
  7208. }
  7209. *(char *)(workdata->f_ha1) = 0;
  7210. (workdata->f_ha1)++;
  7211. if (!strcmp(workdata->ah.user, workdata->f_user)
  7212. && !strcmp(workdata->domain, workdata->f_domain)) {
  7213. return check_password(workdata->conn->request_info.request_method,
  7214. workdata->f_ha1,
  7215. workdata->ah.uri,
  7216. workdata->ah.nonce,
  7217. workdata->ah.nc,
  7218. workdata->ah.cnonce,
  7219. workdata->ah.qop,
  7220. workdata->ah.response);
  7221. }
  7222. }
  7223. return is_authorized;
  7224. }
  7225. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7226. static int
  7227. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7228. {
  7229. struct read_auth_file_struct workdata;
  7230. char buf[MG_BUF_LEN];
  7231. if (!conn || !conn->dom_ctx) {
  7232. return 0;
  7233. }
  7234. memset(&workdata, 0, sizeof(workdata));
  7235. workdata.conn = conn;
  7236. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7237. return 0;
  7238. }
  7239. if (realm) {
  7240. workdata.domain = realm;
  7241. } else {
  7242. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7243. }
  7244. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7245. }
  7246. /* Public function to check http digest authentication header */
  7247. int
  7248. mg_check_digest_access_authentication(struct mg_connection *conn,
  7249. const char *realm,
  7250. const char *filename)
  7251. {
  7252. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7253. int auth;
  7254. if (!conn || !filename) {
  7255. return -1;
  7256. }
  7257. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7258. return -2;
  7259. }
  7260. auth = authorize(conn, &file, realm);
  7261. mg_fclose(&file.access);
  7262. return auth;
  7263. }
  7264. #endif /* NO_FILESYSTEMS */
  7265. /* Return 1 if request is authorised, 0 otherwise. */
  7266. static int
  7267. check_authorization(struct mg_connection *conn, const char *path)
  7268. {
  7269. #if !defined(NO_FILESYSTEMS)
  7270. char fname[PATH_MAX];
  7271. struct vec uri_vec, filename_vec;
  7272. const char *list;
  7273. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7274. int authorized = 1, truncated;
  7275. if (!conn || !conn->dom_ctx) {
  7276. return 0;
  7277. }
  7278. list = conn->dom_ctx->config[PROTECT_URI];
  7279. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7280. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7281. mg_snprintf(conn,
  7282. &truncated,
  7283. fname,
  7284. sizeof(fname),
  7285. "%.*s",
  7286. (int)filename_vec.len,
  7287. filename_vec.ptr);
  7288. if (truncated
  7289. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7290. mg_cry_internal(conn,
  7291. "%s: cannot open %s: %s",
  7292. __func__,
  7293. fname,
  7294. strerror(errno));
  7295. }
  7296. break;
  7297. }
  7298. }
  7299. if (!is_file_opened(&file.access)) {
  7300. open_auth_file(conn, path, &file);
  7301. }
  7302. if (is_file_opened(&file.access)) {
  7303. authorized = authorize(conn, &file, NULL);
  7304. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7305. }
  7306. return authorized;
  7307. #else
  7308. (void)conn;
  7309. (void)path;
  7310. return 1;
  7311. #endif /* NO_FILESYSTEMS */
  7312. }
  7313. /* Internal function. Assumes conn is valid */
  7314. static void
  7315. send_authorization_request(struct mg_connection *conn, const char *realm)
  7316. {
  7317. char date[64];
  7318. time_t curtime = time(NULL);
  7319. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7320. if (!realm) {
  7321. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7322. }
  7323. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7324. nonce += conn->dom_ctx->nonce_count;
  7325. ++conn->dom_ctx->nonce_count;
  7326. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7327. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7328. conn->status_code = 401;
  7329. conn->must_close = 1;
  7330. gmt_time_string(date, sizeof(date), &curtime);
  7331. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7332. send_no_cache_header(conn);
  7333. send_additional_header(conn);
  7334. mg_printf(conn,
  7335. "Date: %s\r\n"
  7336. "Connection: %s\r\n"
  7337. "Content-Length: 0\r\n"
  7338. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7339. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7340. date,
  7341. suggest_connection_header(conn),
  7342. realm,
  7343. nonce);
  7344. }
  7345. /* Interface function. Parameters are provided by the user, so do
  7346. * at least some basic checks.
  7347. */
  7348. int
  7349. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7350. const char *realm)
  7351. {
  7352. if (conn && conn->dom_ctx) {
  7353. send_authorization_request(conn, realm);
  7354. return 0;
  7355. }
  7356. return -1;
  7357. }
  7358. #if !defined(NO_FILES)
  7359. static int
  7360. is_authorized_for_put(struct mg_connection *conn)
  7361. {
  7362. if (conn) {
  7363. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7364. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7365. int ret = 0;
  7366. if (passfile != NULL
  7367. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7368. ret = authorize(conn, &file, NULL);
  7369. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7370. }
  7371. return ret;
  7372. }
  7373. return 0;
  7374. }
  7375. #endif
  7376. int
  7377. mg_modify_passwords_file(const char *fname,
  7378. const char *domain,
  7379. const char *user,
  7380. const char *pass)
  7381. {
  7382. int found, i;
  7383. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7384. FILE *fp, *fp2;
  7385. found = 0;
  7386. fp = fp2 = NULL;
  7387. /* Regard empty password as no password - remove user record. */
  7388. if ((pass != NULL) && (pass[0] == '\0')) {
  7389. pass = NULL;
  7390. }
  7391. /* Other arguments must not be empty */
  7392. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7393. return 0;
  7394. }
  7395. /* Using the given file format, user name and domain must not contain
  7396. * ':'
  7397. */
  7398. if (strchr(user, ':') != NULL) {
  7399. return 0;
  7400. }
  7401. if (strchr(domain, ':') != NULL) {
  7402. return 0;
  7403. }
  7404. /* Do not allow control characters like newline in user name and domain.
  7405. * Do not allow excessively long names either. */
  7406. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7407. if (iscntrl((unsigned char)user[i])) {
  7408. return 0;
  7409. }
  7410. }
  7411. if (user[i]) {
  7412. return 0;
  7413. }
  7414. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7415. if (iscntrl((unsigned char)domain[i])) {
  7416. return 0;
  7417. }
  7418. }
  7419. if (domain[i]) {
  7420. return 0;
  7421. }
  7422. /* The maximum length of the path to the password file is limited */
  7423. if ((strlen(fname) + 4) >= PATH_MAX) {
  7424. return 0;
  7425. }
  7426. /* Create a temporary file name. Length has been checked before. */
  7427. strcpy(tmp, fname);
  7428. strcat(tmp, ".tmp");
  7429. /* Create the file if does not exist */
  7430. /* Use of fopen here is OK, since fname is only ASCII */
  7431. if ((fp = fopen(fname, "a+")) != NULL) {
  7432. (void)fclose(fp);
  7433. }
  7434. /* Open the given file and temporary file */
  7435. if ((fp = fopen(fname, "r")) == NULL) {
  7436. return 0;
  7437. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7438. fclose(fp);
  7439. return 0;
  7440. }
  7441. /* Copy the stuff to temporary file */
  7442. while (fgets(line, sizeof(line), fp) != NULL) {
  7443. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7444. continue;
  7445. }
  7446. u[255] = 0;
  7447. d[255] = 0;
  7448. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7449. found++;
  7450. if (pass != NULL) {
  7451. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7452. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7453. }
  7454. } else {
  7455. fprintf(fp2, "%s", line);
  7456. }
  7457. }
  7458. /* If new user, just add it */
  7459. if (!found && (pass != NULL)) {
  7460. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7461. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7462. }
  7463. /* Close files */
  7464. fclose(fp);
  7465. fclose(fp2);
  7466. /* Put the temp file in place of real file */
  7467. IGNORE_UNUSED_RESULT(remove(fname));
  7468. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7469. return 1;
  7470. }
  7471. static int
  7472. is_valid_port(unsigned long port)
  7473. {
  7474. return (port <= 0xffff);
  7475. }
  7476. static int
  7477. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7478. {
  7479. struct addrinfo hints, *res, *ressave;
  7480. int func_ret = 0;
  7481. int gai_ret;
  7482. memset(&hints, 0, sizeof(struct addrinfo));
  7483. hints.ai_family = af;
  7484. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7485. if (gai_ret != 0) {
  7486. /* gai_strerror could be used to convert gai_ret to a string */
  7487. /* POSIX return values: see
  7488. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7489. */
  7490. /* Windows return values: see
  7491. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7492. */
  7493. return 0;
  7494. }
  7495. ressave = res;
  7496. while (res) {
  7497. if (dstlen >= (size_t)res->ai_addrlen) {
  7498. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7499. func_ret = 1;
  7500. }
  7501. res = res->ai_next;
  7502. }
  7503. freeaddrinfo(ressave);
  7504. return func_ret;
  7505. }
  7506. static int
  7507. connect_socket(struct mg_context *ctx /* may be NULL */,
  7508. const char *host,
  7509. int port,
  7510. int use_ssl,
  7511. char *ebuf,
  7512. size_t ebuf_len,
  7513. SOCKET *sock /* output: socket, must not be NULL */,
  7514. union usa *sa /* output: socket address, must not be NULL */
  7515. )
  7516. {
  7517. int ip_ver = 0;
  7518. int conn_ret = -1;
  7519. int sockerr = 0;
  7520. *sock = INVALID_SOCKET;
  7521. memset(sa, 0, sizeof(*sa));
  7522. if (ebuf_len > 0) {
  7523. *ebuf = 0;
  7524. }
  7525. if (host == NULL) {
  7526. mg_snprintf(NULL,
  7527. NULL, /* No truncation check for ebuf */
  7528. ebuf,
  7529. ebuf_len,
  7530. "%s",
  7531. "NULL host");
  7532. return 0;
  7533. }
  7534. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7535. mg_snprintf(NULL,
  7536. NULL, /* No truncation check for ebuf */
  7537. ebuf,
  7538. ebuf_len,
  7539. "%s",
  7540. "invalid port");
  7541. return 0;
  7542. }
  7543. #if !defined(NO_SSL)
  7544. #if !defined(NO_SSL_DL)
  7545. #if defined(OPENSSL_API_1_1)
  7546. if (use_ssl && (TLS_client_method == NULL)) {
  7547. mg_snprintf(NULL,
  7548. NULL, /* No truncation check for ebuf */
  7549. ebuf,
  7550. ebuf_len,
  7551. "%s",
  7552. "SSL is not initialized");
  7553. return 0;
  7554. }
  7555. #else
  7556. if (use_ssl && (SSLv23_client_method == NULL)) {
  7557. mg_snprintf(NULL,
  7558. NULL, /* No truncation check for ebuf */
  7559. ebuf,
  7560. ebuf_len,
  7561. "%s",
  7562. "SSL is not initialized");
  7563. return 0;
  7564. }
  7565. #endif /* OPENSSL_API_1_1 */
  7566. #else
  7567. (void)use_ssl;
  7568. #endif /* NO_SSL_DL */
  7569. #else
  7570. (void)use_ssl;
  7571. #endif /* !defined(NO_SSL) */
  7572. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7573. sa->sin.sin_family = AF_INET;
  7574. sa->sin.sin_port = htons((uint16_t)port);
  7575. ip_ver = 4;
  7576. #if defined(USE_IPV6)
  7577. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7578. sa->sin6.sin6_family = AF_INET6;
  7579. sa->sin6.sin6_port = htons((uint16_t)port);
  7580. ip_ver = 6;
  7581. } else if (host[0] == '[') {
  7582. /* While getaddrinfo on Windows will work with [::1],
  7583. * getaddrinfo on Linux only works with ::1 (without []). */
  7584. size_t l = strlen(host + 1);
  7585. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7586. if (h) {
  7587. h[l - 1] = 0;
  7588. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7589. sa->sin6.sin6_family = AF_INET6;
  7590. sa->sin6.sin6_port = htons((uint16_t)port);
  7591. ip_ver = 6;
  7592. }
  7593. mg_free(h);
  7594. }
  7595. #endif
  7596. }
  7597. if (ip_ver == 0) {
  7598. mg_snprintf(NULL,
  7599. NULL, /* No truncation check for ebuf */
  7600. ebuf,
  7601. ebuf_len,
  7602. "%s",
  7603. "host not found");
  7604. return 0;
  7605. }
  7606. if (ip_ver == 4) {
  7607. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7608. }
  7609. #if defined(USE_IPV6)
  7610. else if (ip_ver == 6) {
  7611. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7612. }
  7613. #endif
  7614. if (*sock == INVALID_SOCKET) {
  7615. mg_snprintf(NULL,
  7616. NULL, /* No truncation check for ebuf */
  7617. ebuf,
  7618. ebuf_len,
  7619. "socket(): %s",
  7620. strerror(ERRNO));
  7621. return 0;
  7622. }
  7623. if (0 != set_non_blocking_mode(*sock)) {
  7624. mg_snprintf(NULL,
  7625. NULL, /* No truncation check for ebuf */
  7626. ebuf,
  7627. ebuf_len,
  7628. "Cannot set socket to non-blocking: %s",
  7629. strerror(ERRNO));
  7630. closesocket(*sock);
  7631. *sock = INVALID_SOCKET;
  7632. return 0;
  7633. }
  7634. set_close_on_exec(*sock, NULL, ctx);
  7635. if (ip_ver == 4) {
  7636. /* connected with IPv4 */
  7637. conn_ret = connect(*sock,
  7638. (struct sockaddr *)((void *)&sa->sin),
  7639. sizeof(sa->sin));
  7640. }
  7641. #if defined(USE_IPV6)
  7642. else if (ip_ver == 6) {
  7643. /* connected with IPv6 */
  7644. conn_ret = connect(*sock,
  7645. (struct sockaddr *)((void *)&sa->sin6),
  7646. sizeof(sa->sin6));
  7647. }
  7648. #endif
  7649. if (conn_ret != 0) {
  7650. sockerr = ERRNO;
  7651. }
  7652. #if defined(_WIN32)
  7653. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7654. #else
  7655. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7656. #endif
  7657. /* Data for getsockopt */
  7658. void *psockerr = &sockerr;
  7659. int ret;
  7660. #if defined(_WIN32)
  7661. int len = (int)sizeof(sockerr);
  7662. #else
  7663. socklen_t len = (socklen_t)sizeof(sockerr);
  7664. #endif
  7665. /* Data for poll */
  7666. struct mg_pollfd pfd[1];
  7667. int pollres;
  7668. int ms_wait = 10000; /* 10 second timeout */
  7669. int nonstop = 0;
  7670. /* For a non-blocking socket, the connect sequence is:
  7671. * 1) call connect (will not block)
  7672. * 2) wait until the socket is ready for writing (select or poll)
  7673. * 3) check connection state with getsockopt
  7674. */
  7675. pfd[0].fd = *sock;
  7676. pfd[0].events = POLLOUT;
  7677. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7678. if (pollres != 1) {
  7679. /* Not connected */
  7680. mg_snprintf(NULL,
  7681. NULL, /* No truncation check for ebuf */
  7682. ebuf,
  7683. ebuf_len,
  7684. "connect(%s:%d): timeout",
  7685. host,
  7686. port);
  7687. closesocket(*sock);
  7688. *sock = INVALID_SOCKET;
  7689. return 0;
  7690. }
  7691. #if defined(_WIN32)
  7692. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7693. #else
  7694. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7695. #endif
  7696. if ((ret == 0) && (sockerr == 0)) {
  7697. conn_ret = 0;
  7698. }
  7699. }
  7700. if (conn_ret != 0) {
  7701. /* Not connected */
  7702. mg_snprintf(NULL,
  7703. NULL, /* No truncation check for ebuf */
  7704. ebuf,
  7705. ebuf_len,
  7706. "connect(%s:%d): error %s",
  7707. host,
  7708. port,
  7709. strerror(sockerr));
  7710. closesocket(*sock);
  7711. *sock = INVALID_SOCKET;
  7712. return 0;
  7713. }
  7714. return 1;
  7715. }
  7716. int
  7717. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7718. {
  7719. static const char *dont_escape = "._-$,;~()";
  7720. static const char *hex = "0123456789abcdef";
  7721. char *pos = dst;
  7722. const char *end = dst + dst_len - 1;
  7723. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7724. if (isalnum((unsigned char)*src)
  7725. || (strchr(dont_escape, *src) != NULL)) {
  7726. *pos = *src;
  7727. } else if (pos + 2 < end) {
  7728. pos[0] = '%';
  7729. pos[1] = hex[(unsigned char)*src >> 4];
  7730. pos[2] = hex[(unsigned char)*src & 0xf];
  7731. pos += 2;
  7732. } else {
  7733. break;
  7734. }
  7735. }
  7736. *pos = '\0';
  7737. return (*src == '\0') ? (int)(pos - dst) : -1;
  7738. }
  7739. /* Return 0 on success, non-zero if an error occurs. */
  7740. static int
  7741. print_dir_entry(struct de *de)
  7742. {
  7743. size_t namesize, escsize, i;
  7744. char *href, *esc, *p;
  7745. char size[64], mod[64];
  7746. #if defined(REENTRANT_TIME)
  7747. struct tm _tm;
  7748. struct tm *tm = &_tm;
  7749. #else
  7750. struct tm *tm;
  7751. #endif
  7752. /* Estimate worst case size for encoding and escaping */
  7753. namesize = strlen(de->file_name) + 1;
  7754. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7755. href = (char *)mg_malloc(namesize * 3 + escsize);
  7756. if (href == NULL) {
  7757. return -1;
  7758. }
  7759. mg_url_encode(de->file_name, href, namesize * 3);
  7760. esc = NULL;
  7761. if (escsize > 0) {
  7762. /* HTML escaping needed */
  7763. esc = href + namesize * 3;
  7764. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7765. mg_strlcpy(p, de->file_name + i, 2);
  7766. if (*p == '&') {
  7767. strcpy(p, "&amp;");
  7768. } else if (*p == '<') {
  7769. strcpy(p, "&lt;");
  7770. } else if (*p == '>') {
  7771. strcpy(p, "&gt;");
  7772. }
  7773. }
  7774. }
  7775. if (de->file.is_directory) {
  7776. mg_snprintf(de->conn,
  7777. NULL, /* Buffer is big enough */
  7778. size,
  7779. sizeof(size),
  7780. "%s",
  7781. "[DIRECTORY]");
  7782. } else {
  7783. /* We use (signed) cast below because MSVC 6 compiler cannot
  7784. * convert unsigned __int64 to double. Sigh. */
  7785. if (de->file.size < 1024) {
  7786. mg_snprintf(de->conn,
  7787. NULL, /* Buffer is big enough */
  7788. size,
  7789. sizeof(size),
  7790. "%d",
  7791. (int)de->file.size);
  7792. } else if (de->file.size < 0x100000) {
  7793. mg_snprintf(de->conn,
  7794. NULL, /* Buffer is big enough */
  7795. size,
  7796. sizeof(size),
  7797. "%.1fk",
  7798. (double)de->file.size / 1024.0);
  7799. } else if (de->file.size < 0x40000000) {
  7800. mg_snprintf(de->conn,
  7801. NULL, /* Buffer is big enough */
  7802. size,
  7803. sizeof(size),
  7804. "%.1fM",
  7805. (double)de->file.size / 1048576);
  7806. } else {
  7807. mg_snprintf(de->conn,
  7808. NULL, /* Buffer is big enough */
  7809. size,
  7810. sizeof(size),
  7811. "%.1fG",
  7812. (double)de->file.size / 1073741824);
  7813. }
  7814. }
  7815. /* Note: mg_snprintf will not cause a buffer overflow above.
  7816. * So, string truncation checks are not required here. */
  7817. #if defined(REENTRANT_TIME)
  7818. localtime_r(&de->file.last_modified, tm);
  7819. #else
  7820. tm = localtime(&de->file.last_modified);
  7821. #endif
  7822. if (tm != NULL) {
  7823. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7824. } else {
  7825. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7826. mod[sizeof(mod) - 1] = '\0';
  7827. }
  7828. mg_printf(de->conn,
  7829. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7830. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7831. href,
  7832. de->file.is_directory ? "/" : "",
  7833. esc ? esc : de->file_name,
  7834. de->file.is_directory ? "/" : "",
  7835. mod,
  7836. size);
  7837. mg_free(href);
  7838. return 0;
  7839. }
  7840. /* This function is called from send_directory() and used for
  7841. * sorting directory entries by size, or name, or modification time.
  7842. * On windows, __cdecl specification is needed in case if project is built
  7843. * with __stdcall convention. qsort always requires __cdels callback. */
  7844. static int WINCDECL
  7845. compare_dir_entries(const void *p1, const void *p2)
  7846. {
  7847. if (p1 && p2) {
  7848. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7849. const char *query_string = a->conn->request_info.query_string;
  7850. int cmp_result = 0;
  7851. if ((query_string == NULL) || (query_string[0] == '\0')) {
  7852. query_string = "n";
  7853. }
  7854. if (a->file.is_directory && !b->file.is_directory) {
  7855. return -1; /* Always put directories on top */
  7856. } else if (!a->file.is_directory && b->file.is_directory) {
  7857. return 1; /* Always put directories on top */
  7858. } else if (*query_string == 'n') {
  7859. cmp_result = strcmp(a->file_name, b->file_name);
  7860. } else if (*query_string == 's') {
  7861. cmp_result = (a->file.size == b->file.size)
  7862. ? 0
  7863. : ((a->file.size > b->file.size) ? 1 : -1);
  7864. } else if (*query_string == 'd') {
  7865. cmp_result =
  7866. (a->file.last_modified == b->file.last_modified)
  7867. ? 0
  7868. : ((a->file.last_modified > b->file.last_modified) ? 1
  7869. : -1);
  7870. }
  7871. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7872. }
  7873. return 0;
  7874. }
  7875. static int
  7876. must_hide_file(struct mg_connection *conn, const char *path)
  7877. {
  7878. if (conn && conn->dom_ctx) {
  7879. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7880. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7881. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7882. || ((pattern != NULL)
  7883. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7884. }
  7885. return 0;
  7886. }
  7887. #if !defined(NO_FILESYSTEMS)
  7888. static int
  7889. scan_directory(struct mg_connection *conn,
  7890. const char *dir,
  7891. void *data,
  7892. int (*cb)(struct de *, void *))
  7893. {
  7894. char path[PATH_MAX];
  7895. struct dirent *dp;
  7896. DIR *dirp;
  7897. struct de de;
  7898. int truncated;
  7899. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7900. return 0;
  7901. } else {
  7902. de.conn = conn;
  7903. while ((dp = mg_readdir(dirp)) != NULL) {
  7904. /* Do not show current dir and hidden files */
  7905. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7906. || must_hide_file(conn, dp->d_name)) {
  7907. continue;
  7908. }
  7909. mg_snprintf(
  7910. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7911. /* If we don't memset stat structure to zero, mtime will have
  7912. * garbage and strftime() will segfault later on in
  7913. * print_dir_entry(). memset is required only if mg_stat()
  7914. * fails. For more details, see
  7915. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7916. memset(&de.file, 0, sizeof(de.file));
  7917. if (truncated) {
  7918. /* If the path is not complete, skip processing. */
  7919. continue;
  7920. }
  7921. if (!mg_stat(conn, path, &de.file)) {
  7922. mg_cry_internal(conn,
  7923. "%s: mg_stat(%s) failed: %s",
  7924. __func__,
  7925. path,
  7926. strerror(ERRNO));
  7927. }
  7928. de.file_name = dp->d_name;
  7929. cb(&de, data);
  7930. }
  7931. (void)mg_closedir(dirp);
  7932. }
  7933. return 1;
  7934. }
  7935. #endif /* NO_FILESYSTEMS */
  7936. #if !defined(NO_FILES)
  7937. static int
  7938. remove_directory(struct mg_connection *conn, const char *dir)
  7939. {
  7940. char path[PATH_MAX];
  7941. struct dirent *dp;
  7942. DIR *dirp;
  7943. struct de de;
  7944. int truncated;
  7945. int ok = 1;
  7946. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7947. return 0;
  7948. } else {
  7949. de.conn = conn;
  7950. while ((dp = mg_readdir(dirp)) != NULL) {
  7951. /* Do not show current dir (but show hidden files as they will
  7952. * also be removed) */
  7953. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7954. continue;
  7955. }
  7956. mg_snprintf(
  7957. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7958. /* If we don't memset stat structure to zero, mtime will have
  7959. * garbage and strftime() will segfault later on in
  7960. * print_dir_entry(). memset is required only if mg_stat()
  7961. * fails. For more details, see
  7962. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7963. memset(&de.file, 0, sizeof(de.file));
  7964. if (truncated) {
  7965. /* Do not delete anything shorter */
  7966. ok = 0;
  7967. continue;
  7968. }
  7969. if (!mg_stat(conn, path, &de.file)) {
  7970. mg_cry_internal(conn,
  7971. "%s: mg_stat(%s) failed: %s",
  7972. __func__,
  7973. path,
  7974. strerror(ERRNO));
  7975. ok = 0;
  7976. }
  7977. if (de.file.is_directory) {
  7978. if (remove_directory(conn, path) == 0) {
  7979. ok = 0;
  7980. }
  7981. } else {
  7982. /* This will fail file is the file is in memory */
  7983. if (mg_remove(conn, path) == 0) {
  7984. ok = 0;
  7985. }
  7986. }
  7987. }
  7988. (void)mg_closedir(dirp);
  7989. IGNORE_UNUSED_RESULT(rmdir(dir));
  7990. }
  7991. return ok;
  7992. }
  7993. #endif
  7994. struct dir_scan_data {
  7995. struct de *entries;
  7996. unsigned int num_entries;
  7997. unsigned int arr_size;
  7998. };
  7999. /* Behaves like realloc(), but frees original pointer on failure */
  8000. static void *
  8001. realloc2(void *ptr, size_t size)
  8002. {
  8003. void *new_ptr = mg_realloc(ptr, size);
  8004. if (new_ptr == NULL) {
  8005. mg_free(ptr);
  8006. }
  8007. return new_ptr;
  8008. }
  8009. #if !defined(NO_FILESYSTEMS)
  8010. static int
  8011. dir_scan_callback(struct de *de, void *data)
  8012. {
  8013. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8014. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8015. dsd->arr_size *= 2;
  8016. dsd->entries =
  8017. (struct de *)realloc2(dsd->entries,
  8018. dsd->arr_size * sizeof(dsd->entries[0]));
  8019. }
  8020. if (dsd->entries == NULL) {
  8021. /* TODO(lsm, low): propagate an error to the caller */
  8022. dsd->num_entries = 0;
  8023. } else {
  8024. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8025. dsd->entries[dsd->num_entries].file = de->file;
  8026. dsd->entries[dsd->num_entries].conn = de->conn;
  8027. dsd->num_entries++;
  8028. }
  8029. return 0;
  8030. }
  8031. static void
  8032. handle_directory_request(struct mg_connection *conn, const char *dir)
  8033. {
  8034. unsigned int i;
  8035. int sort_direction;
  8036. struct dir_scan_data data = {NULL, 0, 128};
  8037. char date[64], *esc, *p;
  8038. const char *title;
  8039. time_t curtime = time(NULL);
  8040. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8041. mg_send_http_error(conn,
  8042. 500,
  8043. "Error: Cannot open directory\nopendir(%s): %s",
  8044. dir,
  8045. strerror(ERRNO));
  8046. return;
  8047. }
  8048. gmt_time_string(date, sizeof(date), &curtime);
  8049. if (!conn) {
  8050. return;
  8051. }
  8052. esc = NULL;
  8053. title = conn->request_info.local_uri;
  8054. if (title[strcspn(title, "&<>")]) {
  8055. /* HTML escaping needed */
  8056. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8057. if (esc) {
  8058. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8059. mg_strlcpy(p, title + i, 2);
  8060. if (*p == '&') {
  8061. strcpy(p, "&amp;");
  8062. } else if (*p == '<') {
  8063. strcpy(p, "&lt;");
  8064. } else if (*p == '>') {
  8065. strcpy(p, "&gt;");
  8066. }
  8067. }
  8068. } else {
  8069. title = "";
  8070. }
  8071. }
  8072. sort_direction = ((conn->request_info.query_string != NULL)
  8073. && (conn->request_info.query_string[0] != '\0')
  8074. && (conn->request_info.query_string[1] == 'd'))
  8075. ? 'a'
  8076. : 'd';
  8077. conn->must_close = 1;
  8078. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8079. send_static_cache_header(conn);
  8080. send_additional_header(conn);
  8081. mg_printf(conn,
  8082. "Date: %s\r\n"
  8083. "Connection: close\r\n"
  8084. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8085. date);
  8086. mg_printf(conn,
  8087. "<html><head><title>Index of %s</title>"
  8088. "<style>th {text-align: left;}</style></head>"
  8089. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8090. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8091. "<th><a href=\"?d%c\">Modified</a></th>"
  8092. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8093. "<tr><td colspan=\"3\"><hr></td></tr>",
  8094. esc ? esc : title,
  8095. esc ? esc : title,
  8096. sort_direction,
  8097. sort_direction,
  8098. sort_direction);
  8099. mg_free(esc);
  8100. /* Print first entry - link to a parent directory */
  8101. mg_printf(conn,
  8102. "<tr><td><a href=\"%s\">%s</a></td>"
  8103. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8104. "..",
  8105. "Parent directory",
  8106. "-",
  8107. "-");
  8108. /* Sort and print directory entries */
  8109. if (data.entries != NULL) {
  8110. qsort(data.entries,
  8111. (size_t)data.num_entries,
  8112. sizeof(data.entries[0]),
  8113. compare_dir_entries);
  8114. for (i = 0; i < data.num_entries; i++) {
  8115. print_dir_entry(&data.entries[i]);
  8116. mg_free(data.entries[i].file_name);
  8117. }
  8118. mg_free(data.entries);
  8119. }
  8120. mg_printf(conn, "%s", "</table></pre></body></html>");
  8121. conn->status_code = 200;
  8122. }
  8123. #endif /* NO_FILESYSTEMS */
  8124. /* Send len bytes from the opened file to the client. */
  8125. static void
  8126. send_file_data(struct mg_connection *conn,
  8127. struct mg_file *filep,
  8128. int64_t offset,
  8129. int64_t len)
  8130. {
  8131. char buf[MG_BUF_LEN];
  8132. int to_read, num_read, num_written;
  8133. int64_t size;
  8134. if (!filep || !conn) {
  8135. return;
  8136. }
  8137. /* Sanity check the offset */
  8138. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8139. : (int64_t)(filep->stat.size);
  8140. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8141. #if defined(MG_USE_OPEN_FILE)
  8142. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8143. /* file stored in memory */
  8144. if (len > size - offset) {
  8145. len = size - offset;
  8146. }
  8147. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8148. } else /* else block below */
  8149. #endif
  8150. if (len > 0 && filep->access.fp != NULL) {
  8151. /* file stored on disk */
  8152. #if defined(__linux__)
  8153. /* sendfile is only available for Linux */
  8154. if ((conn->ssl == 0) && (conn->throttle == 0)
  8155. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8156. "yes"))) {
  8157. off_t sf_offs = (off_t)offset;
  8158. ssize_t sf_sent;
  8159. int sf_file = fileno(filep->access.fp);
  8160. int loop_cnt = 0;
  8161. do {
  8162. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8163. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8164. size_t sf_tosend =
  8165. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8166. sf_sent =
  8167. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8168. if (sf_sent > 0) {
  8169. len -= sf_sent;
  8170. offset += sf_sent;
  8171. } else if (loop_cnt == 0) {
  8172. /* This file can not be sent using sendfile.
  8173. * This might be the case for pseudo-files in the
  8174. * /sys/ and /proc/ file system.
  8175. * Use the regular user mode copy code instead. */
  8176. break;
  8177. } else if (sf_sent == 0) {
  8178. /* No error, but 0 bytes sent. May be EOF? */
  8179. return;
  8180. }
  8181. loop_cnt++;
  8182. } while ((len > 0) && (sf_sent >= 0));
  8183. if (sf_sent > 0) {
  8184. return; /* OK */
  8185. }
  8186. /* sf_sent<0 means error, thus fall back to the classic way */
  8187. /* This is always the case, if sf_file is not a "normal" file,
  8188. * e.g., for sending data from the output of a CGI process. */
  8189. offset = (int64_t)sf_offs;
  8190. }
  8191. #endif
  8192. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8193. mg_cry_internal(conn,
  8194. "%s: fseeko() failed: %s",
  8195. __func__,
  8196. strerror(ERRNO));
  8197. mg_send_http_error(
  8198. conn,
  8199. 500,
  8200. "%s",
  8201. "Error: Unable to access file at requested position.");
  8202. } else {
  8203. while (len > 0) {
  8204. /* Calculate how much to read from the file in the buffer */
  8205. to_read = sizeof(buf);
  8206. if ((int64_t)to_read > len) {
  8207. to_read = (int)len;
  8208. }
  8209. /* Read from file, exit the loop on error */
  8210. if ((num_read =
  8211. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8212. <= 0) {
  8213. break;
  8214. }
  8215. /* Send read bytes to the client, exit the loop on error */
  8216. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8217. != num_read) {
  8218. break;
  8219. }
  8220. /* Both read and were successful, adjust counters */
  8221. len -= num_written;
  8222. }
  8223. }
  8224. }
  8225. }
  8226. static int
  8227. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8228. {
  8229. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8230. }
  8231. static void
  8232. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8233. {
  8234. if ((filestat != NULL) && (buf != NULL)) {
  8235. mg_snprintf(NULL,
  8236. NULL, /* All calls to construct_etag use 64 byte buffer */
  8237. buf,
  8238. buf_len,
  8239. "\"%lx.%" INT64_FMT "\"",
  8240. (unsigned long)filestat->last_modified,
  8241. filestat->size);
  8242. }
  8243. }
  8244. static void
  8245. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8246. {
  8247. if (filep != NULL && filep->fp != NULL) {
  8248. #if defined(_WIN32)
  8249. (void)conn; /* Unused. */
  8250. #else
  8251. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8252. mg_cry_internal(conn,
  8253. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8254. __func__,
  8255. strerror(ERRNO));
  8256. }
  8257. #endif
  8258. }
  8259. }
  8260. #if defined(USE_ZLIB)
  8261. #include "mod_zlib.inl"
  8262. #endif
  8263. #if !defined(NO_FILESYSTEMS)
  8264. static void
  8265. handle_static_file_request(struct mg_connection *conn,
  8266. const char *path,
  8267. struct mg_file *filep,
  8268. const char *mime_type,
  8269. const char *additional_headers)
  8270. {
  8271. char date[64], lm[64], etag[64];
  8272. char range[128]; /* large enough, so there will be no overflow */
  8273. const char *msg = "OK";
  8274. const char *range_hdr;
  8275. time_t curtime = time(NULL);
  8276. int64_t cl, r1, r2;
  8277. struct vec mime_vec;
  8278. int n, truncated;
  8279. char gz_path[PATH_MAX];
  8280. const char *encoding = "";
  8281. const char *origin_hdr;
  8282. const char *cors_orig_cfg;
  8283. const char *cors1, *cors2, *cors3;
  8284. int is_head_request;
  8285. #if defined(USE_ZLIB)
  8286. /* Compression is allowed, unless there is a reason not to use compression.
  8287. * If the file is already compressed, too small or a "range" request was
  8288. * made, on the fly compression is not possible. */
  8289. int allow_on_the_fly_compression = 1;
  8290. #endif
  8291. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8292. return;
  8293. }
  8294. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8295. if (mime_type == NULL) {
  8296. get_mime_type(conn, path, &mime_vec);
  8297. } else {
  8298. mime_vec.ptr = mime_type;
  8299. mime_vec.len = strlen(mime_type);
  8300. }
  8301. if (filep->stat.size > INT64_MAX) {
  8302. mg_send_http_error(conn,
  8303. 500,
  8304. "Error: File size is too large to send\n%" INT64_FMT,
  8305. filep->stat.size);
  8306. return;
  8307. }
  8308. cl = (int64_t)filep->stat.size;
  8309. conn->status_code = 200;
  8310. range[0] = '\0';
  8311. #if defined(USE_ZLIB)
  8312. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8313. * it's important to rewrite the filename after resolving
  8314. * the mime type from it, to preserve the actual file's type */
  8315. if (!conn->accept_gzip) {
  8316. allow_on_the_fly_compression = 0;
  8317. }
  8318. #endif
  8319. /* Check if there is a range header */
  8320. range_hdr = mg_get_header(conn, "Range");
  8321. /* For gzipped files, add *.gz */
  8322. if (filep->stat.is_gzipped) {
  8323. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8324. if (truncated) {
  8325. mg_send_http_error(conn,
  8326. 500,
  8327. "Error: Path of zipped file too long (%s)",
  8328. path);
  8329. return;
  8330. }
  8331. path = gz_path;
  8332. encoding = "Content-Encoding: gzip\r\n";
  8333. #if defined(USE_ZLIB)
  8334. /* File is already compressed. No "on the fly" compression. */
  8335. allow_on_the_fly_compression = 0;
  8336. #endif
  8337. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8338. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8339. struct mg_file_stat file_stat;
  8340. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8341. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8342. && !file_stat.is_directory) {
  8343. file_stat.is_gzipped = 1;
  8344. filep->stat = file_stat;
  8345. cl = (int64_t)filep->stat.size;
  8346. path = gz_path;
  8347. encoding = "Content-Encoding: gzip\r\n";
  8348. #if defined(USE_ZLIB)
  8349. /* File is already compressed. No "on the fly" compression. */
  8350. allow_on_the_fly_compression = 0;
  8351. #endif
  8352. }
  8353. }
  8354. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8355. mg_send_http_error(conn,
  8356. 500,
  8357. "Error: Cannot open file\nfopen(%s): %s",
  8358. path,
  8359. strerror(ERRNO));
  8360. return;
  8361. }
  8362. fclose_on_exec(&filep->access, conn);
  8363. /* If "Range" request was made: parse header, send only selected part
  8364. * of the file. */
  8365. r1 = r2 = 0;
  8366. if ((range_hdr != NULL)
  8367. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8368. && (r2 >= 0)) {
  8369. /* actually, range requests don't play well with a pre-gzipped
  8370. * file (since the range is specified in the uncompressed space) */
  8371. if (filep->stat.is_gzipped) {
  8372. mg_send_http_error(
  8373. conn,
  8374. 416, /* 416 = Range Not Satisfiable */
  8375. "%s",
  8376. "Error: Range requests in gzipped files are not supported");
  8377. (void)mg_fclose(
  8378. &filep->access); /* ignore error on read only file */
  8379. return;
  8380. }
  8381. conn->status_code = 206;
  8382. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8383. mg_snprintf(conn,
  8384. NULL, /* range buffer is big enough */
  8385. range,
  8386. sizeof(range),
  8387. "Content-Range: bytes "
  8388. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8389. r1,
  8390. r1 + cl - 1,
  8391. filep->stat.size);
  8392. msg = "Partial Content";
  8393. #if defined(USE_ZLIB)
  8394. /* Do not compress ranges. */
  8395. allow_on_the_fly_compression = 0;
  8396. #endif
  8397. }
  8398. /* Do not compress small files. Small files do not benefit from file
  8399. * compression, but there is still some overhead. */
  8400. #if defined(USE_ZLIB)
  8401. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8402. /* File is below the size limit. */
  8403. allow_on_the_fly_compression = 0;
  8404. }
  8405. #endif
  8406. /* Standard CORS header */
  8407. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8408. origin_hdr = mg_get_header(conn, "Origin");
  8409. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8410. /* Cross-origin resource sharing (CORS), see
  8411. * http://www.html5rocks.com/en/tutorials/cors/,
  8412. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8413. * -
  8414. * preflight is not supported for files. */
  8415. cors1 = "Access-Control-Allow-Origin: ";
  8416. cors2 = cors_orig_cfg;
  8417. cors3 = "\r\n";
  8418. } else {
  8419. cors1 = cors2 = cors3 = "";
  8420. }
  8421. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8422. * according to
  8423. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8424. gmt_time_string(date, sizeof(date), &curtime);
  8425. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8426. construct_etag(etag, sizeof(etag), &filep->stat);
  8427. /* Send header */
  8428. (void)mg_printf(conn,
  8429. "HTTP/1.1 %d %s\r\n"
  8430. "%s%s%s" /* CORS */
  8431. "Date: %s\r\n"
  8432. "Last-Modified: %s\r\n"
  8433. "Etag: %s\r\n"
  8434. "Content-Type: %.*s\r\n"
  8435. "Connection: %s\r\n",
  8436. conn->status_code,
  8437. msg,
  8438. cors1,
  8439. cors2,
  8440. cors3,
  8441. date,
  8442. lm,
  8443. etag,
  8444. (int)mime_vec.len,
  8445. mime_vec.ptr,
  8446. suggest_connection_header(conn));
  8447. send_static_cache_header(conn);
  8448. send_additional_header(conn);
  8449. #if defined(USE_ZLIB)
  8450. /* On the fly compression allowed */
  8451. if (allow_on_the_fly_compression) {
  8452. /* For on the fly compression, we don't know the content size in
  8453. * advance, so we have to use chunked encoding */
  8454. (void)mg_printf(conn,
  8455. "Content-Encoding: gzip\r\n"
  8456. "Transfer-Encoding: chunked\r\n");
  8457. } else
  8458. #endif
  8459. {
  8460. /* Without on-the-fly compression, we know the content-length
  8461. * and we can use ranges (with on-the-fly compression we cannot).
  8462. * So we send these response headers only in this case. */
  8463. (void)mg_printf(conn,
  8464. "Content-Length: %" INT64_FMT "\r\n"
  8465. "Accept-Ranges: bytes\r\n"
  8466. "%s" /* range */
  8467. "%s" /* encoding */,
  8468. cl,
  8469. range,
  8470. encoding);
  8471. }
  8472. /* The previous code must not add any header starting with X- to make
  8473. * sure no one of the additional_headers is included twice */
  8474. if (additional_headers != NULL) {
  8475. (void)mg_printf(conn,
  8476. "%.*s\r\n\r\n",
  8477. (int)strlen(additional_headers),
  8478. additional_headers);
  8479. } else {
  8480. (void)mg_printf(conn, "\r\n");
  8481. }
  8482. if (!is_head_request) {
  8483. #if defined(USE_ZLIB)
  8484. if (allow_on_the_fly_compression) {
  8485. /* Compress and send */
  8486. send_compressed_data(conn, filep);
  8487. } else
  8488. #endif
  8489. {
  8490. /* Send file directly */
  8491. send_file_data(conn, filep, r1, cl);
  8492. }
  8493. }
  8494. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8495. }
  8496. int
  8497. mg_send_file_body(struct mg_connection *conn, const char *path)
  8498. {
  8499. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8500. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8501. return -1;
  8502. }
  8503. fclose_on_exec(&file.access, conn);
  8504. send_file_data(conn, &file, 0, INT64_MAX);
  8505. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8506. return 0; /* >= 0 for OK */
  8507. }
  8508. #endif /* NO_FILESYSTEMS */
  8509. #if !defined(NO_CACHING)
  8510. /* Return True if we should reply 304 Not Modified. */
  8511. static int
  8512. is_not_modified(const struct mg_connection *conn,
  8513. const struct mg_file_stat *filestat)
  8514. {
  8515. char etag[64];
  8516. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8517. const char *inm = mg_get_header(conn, "If-None-Match");
  8518. construct_etag(etag, sizeof(etag), filestat);
  8519. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8520. || ((ims != NULL)
  8521. && (filestat->last_modified <= parse_date_string(ims)));
  8522. }
  8523. static void
  8524. handle_not_modified_static_file_request(struct mg_connection *conn,
  8525. struct mg_file *filep)
  8526. {
  8527. char date[64], lm[64], etag[64];
  8528. time_t curtime = time(NULL);
  8529. if ((conn == NULL) || (filep == NULL)) {
  8530. return;
  8531. }
  8532. conn->status_code = 304;
  8533. gmt_time_string(date, sizeof(date), &curtime);
  8534. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8535. construct_etag(etag, sizeof(etag), &filep->stat);
  8536. (void)mg_printf(conn,
  8537. "HTTP/1.1 %d %s\r\n"
  8538. "Date: %s\r\n",
  8539. conn->status_code,
  8540. mg_get_response_code_text(conn, conn->status_code),
  8541. date);
  8542. send_static_cache_header(conn);
  8543. send_additional_header(conn);
  8544. (void)mg_printf(conn,
  8545. "Last-Modified: %s\r\n"
  8546. "Etag: %s\r\n"
  8547. "Connection: %s\r\n"
  8548. "\r\n",
  8549. lm,
  8550. etag,
  8551. suggest_connection_header(conn));
  8552. }
  8553. #endif
  8554. #if !defined(NO_FILESYSTEMS)
  8555. void
  8556. mg_send_file(struct mg_connection *conn, const char *path)
  8557. {
  8558. mg_send_mime_file2(conn, path, NULL, NULL);
  8559. }
  8560. void
  8561. mg_send_mime_file(struct mg_connection *conn,
  8562. const char *path,
  8563. const char *mime_type)
  8564. {
  8565. mg_send_mime_file2(conn, path, mime_type, NULL);
  8566. }
  8567. void
  8568. mg_send_mime_file2(struct mg_connection *conn,
  8569. const char *path,
  8570. const char *mime_type,
  8571. const char *additional_headers)
  8572. {
  8573. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8574. if (!conn) {
  8575. /* No conn */
  8576. return;
  8577. }
  8578. if (mg_stat(conn, path, &file.stat)) {
  8579. #if !defined(NO_CACHING)
  8580. if (is_not_modified(conn, &file.stat)) {
  8581. /* Send 304 "Not Modified" - this must not send any body data */
  8582. handle_not_modified_static_file_request(conn, &file);
  8583. } else
  8584. #endif /* NO_CACHING */
  8585. if (file.stat.is_directory) {
  8586. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8587. "yes")) {
  8588. handle_directory_request(conn, path);
  8589. } else {
  8590. mg_send_http_error(conn,
  8591. 403,
  8592. "%s",
  8593. "Error: Directory listing denied");
  8594. }
  8595. } else {
  8596. handle_static_file_request(
  8597. conn, path, &file, mime_type, additional_headers);
  8598. }
  8599. } else {
  8600. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8601. }
  8602. }
  8603. /* For a given PUT path, create all intermediate subdirectories.
  8604. * Return 0 if the path itself is a directory.
  8605. * Return 1 if the path leads to a file.
  8606. * Return -1 for if the path is too long.
  8607. * Return -2 if path can not be created.
  8608. */
  8609. static int
  8610. put_dir(struct mg_connection *conn, const char *path)
  8611. {
  8612. char buf[PATH_MAX];
  8613. const char *s, *p;
  8614. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8615. size_t len;
  8616. int res = 1;
  8617. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8618. len = (size_t)(p - path);
  8619. if (len >= sizeof(buf)) {
  8620. /* path too long */
  8621. res = -1;
  8622. break;
  8623. }
  8624. memcpy(buf, path, len);
  8625. buf[len] = '\0';
  8626. /* Try to create intermediate directory */
  8627. DEBUG_TRACE("mkdir(%s)", buf);
  8628. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8629. /* path does not exixt and can not be created */
  8630. res = -2;
  8631. break;
  8632. }
  8633. /* Is path itself a directory? */
  8634. if (p[1] == '\0') {
  8635. res = 0;
  8636. }
  8637. }
  8638. return res;
  8639. }
  8640. static void
  8641. remove_bad_file(const struct mg_connection *conn, const char *path)
  8642. {
  8643. int r = mg_remove(conn, path);
  8644. if (r != 0) {
  8645. mg_cry_internal(conn,
  8646. "%s: Cannot remove invalid file %s",
  8647. __func__,
  8648. path);
  8649. }
  8650. }
  8651. long long
  8652. mg_store_body(struct mg_connection *conn, const char *path)
  8653. {
  8654. char buf[MG_BUF_LEN];
  8655. long long len = 0;
  8656. int ret, n;
  8657. struct mg_file fi;
  8658. if (conn->consumed_content != 0) {
  8659. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8660. return -11;
  8661. }
  8662. ret = put_dir(conn, path);
  8663. if (ret < 0) {
  8664. /* -1 for path too long,
  8665. * -2 for path can not be created. */
  8666. return ret;
  8667. }
  8668. if (ret != 1) {
  8669. /* Return 0 means, path itself is a directory. */
  8670. return 0;
  8671. }
  8672. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8673. return -12;
  8674. }
  8675. ret = mg_read(conn, buf, sizeof(buf));
  8676. while (ret > 0) {
  8677. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8678. if (n != ret) {
  8679. (void)mg_fclose(
  8680. &fi.access); /* File is bad and will be removed anyway. */
  8681. remove_bad_file(conn, path);
  8682. return -13;
  8683. }
  8684. len += ret;
  8685. ret = mg_read(conn, buf, sizeof(buf));
  8686. }
  8687. /* File is open for writing. If fclose fails, there was probably an
  8688. * error flushing the buffer to disk, so the file on disk might be
  8689. * broken. Delete it and return an error to the caller. */
  8690. if (mg_fclose(&fi.access) != 0) {
  8691. remove_bad_file(conn, path);
  8692. return -14;
  8693. }
  8694. return len;
  8695. }
  8696. #endif /* NO_FILESYSTEMS */
  8697. /* Parse a buffer:
  8698. * Forward the string pointer till the end of a word, then
  8699. * terminate it and forward till the begin of the next word.
  8700. */
  8701. static int
  8702. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8703. {
  8704. /* Forward until a space is found - use isgraph here */
  8705. /* See http://www.cplusplus.com/reference/cctype/ */
  8706. while (isgraph((unsigned char)**ppw)) {
  8707. (*ppw)++;
  8708. }
  8709. /* Check end of word */
  8710. if (eol) {
  8711. /* must be a end of line */
  8712. if ((**ppw != '\r') && (**ppw != '\n')) {
  8713. return -1;
  8714. }
  8715. } else {
  8716. /* must be a end of a word, but not a line */
  8717. if (**ppw != ' ') {
  8718. return -1;
  8719. }
  8720. }
  8721. /* Terminate and forward to the next word */
  8722. do {
  8723. **ppw = 0;
  8724. (*ppw)++;
  8725. } while (isspace((unsigned char)**ppw));
  8726. /* Check after term */
  8727. if (!eol) {
  8728. /* if it's not the end of line, there must be a next word */
  8729. if (!isgraph((unsigned char)**ppw)) {
  8730. return -1;
  8731. }
  8732. }
  8733. /* ok */
  8734. return 1;
  8735. }
  8736. /* Parse HTTP headers from the given buffer, advance buf pointer
  8737. * to the point where parsing stopped.
  8738. * All parameters must be valid pointers (not NULL).
  8739. * Return <0 on error. */
  8740. static int
  8741. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8742. {
  8743. int i;
  8744. int num_headers = 0;
  8745. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8746. char *dp = *buf;
  8747. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  8748. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8749. dp++;
  8750. }
  8751. if (dp == *buf) {
  8752. /* End of headers reached. */
  8753. break;
  8754. }
  8755. if (*dp != ':') {
  8756. /* This is not a valid field. */
  8757. return -1;
  8758. }
  8759. /* End of header key (*dp == ':') */
  8760. /* Truncate here and set the key name */
  8761. *dp = 0;
  8762. hdr[i].name = *buf;
  8763. /* Skip all spaces */
  8764. do {
  8765. dp++;
  8766. } while ((*dp == ' ') || (*dp == '\t'));
  8767. /* The rest of the line is the value */
  8768. hdr[i].value = dp;
  8769. /* Find end of line */
  8770. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  8771. dp++;
  8772. };
  8773. /* eliminate \r */
  8774. if (*dp == '\r') {
  8775. *dp = 0;
  8776. dp++;
  8777. if (*dp != '\n') {
  8778. /* This is not a valid line. */
  8779. return -1;
  8780. }
  8781. }
  8782. /* here *dp is either 0 or '\n' */
  8783. /* in any case, we have a new header */
  8784. num_headers = i + 1;
  8785. if (*dp) {
  8786. *dp = 0;
  8787. dp++;
  8788. *buf = dp;
  8789. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  8790. /* This is the end of the header */
  8791. break;
  8792. }
  8793. } else {
  8794. *buf = dp;
  8795. break;
  8796. }
  8797. }
  8798. return num_headers;
  8799. }
  8800. struct mg_http_method_info {
  8801. const char *name;
  8802. int request_has_body;
  8803. int response_has_body;
  8804. int is_safe;
  8805. int is_idempotent;
  8806. int is_cacheable;
  8807. };
  8808. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8809. static struct mg_http_method_info http_methods[] = {
  8810. /* HTTP (RFC 2616) */
  8811. {"GET", 0, 1, 1, 1, 1},
  8812. {"POST", 1, 1, 0, 0, 0},
  8813. {"PUT", 1, 0, 0, 1, 0},
  8814. {"DELETE", 0, 0, 0, 1, 0},
  8815. {"HEAD", 0, 0, 1, 1, 1},
  8816. {"OPTIONS", 0, 0, 1, 1, 0},
  8817. {"CONNECT", 1, 1, 0, 0, 0},
  8818. /* TRACE method (RFC 2616) is not supported for security reasons */
  8819. /* PATCH method (RFC 5789) */
  8820. {"PATCH", 1, 0, 0, 0, 0},
  8821. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8822. /* WEBDAV (RFC 2518) */
  8823. {"PROPFIND", 0, 1, 1, 1, 0},
  8824. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8825. * Some PROPFIND results MAY be cached, with care,
  8826. * as there is no cache validation mechanism for
  8827. * most properties. This method is both safe and
  8828. * idempotent (see Section 9.1 of [RFC2616]). */
  8829. {"MKCOL", 0, 0, 0, 1, 0},
  8830. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8831. * When MKCOL is invoked without a request body,
  8832. * the newly created collection SHOULD have no
  8833. * members. A MKCOL request message may contain
  8834. * a message body. The precise behavior of a MKCOL
  8835. * request when the body is present is undefined,
  8836. * ... ==> We do not support MKCOL with body data.
  8837. * This method is idempotent, but not safe (see
  8838. * Section 9.1 of [RFC2616]). Responses to this
  8839. * method MUST NOT be cached. */
  8840. /* Unsupported WEBDAV Methods: */
  8841. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8842. /* + 11 methods from RFC 3253 */
  8843. /* ORDERPATCH (RFC 3648) */
  8844. /* ACL (RFC 3744) */
  8845. /* SEARCH (RFC 5323) */
  8846. /* + MicroSoft extensions
  8847. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8848. /* REPORT method (RFC 3253) */
  8849. {"REPORT", 1, 1, 1, 1, 1},
  8850. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8851. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8852. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8853. * to be useful for REST in case a "GET request with body" is
  8854. * required. */
  8855. {NULL, 0, 0, 0, 0, 0}
  8856. /* end of list */
  8857. };
  8858. static const struct mg_http_method_info *
  8859. get_http_method_info(const char *method)
  8860. {
  8861. /* Check if the method is known to the server. The list of all known
  8862. * HTTP methods can be found here at
  8863. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8864. */
  8865. const struct mg_http_method_info *m = http_methods;
  8866. while (m->name) {
  8867. if (!strcmp(m->name, method)) {
  8868. return m;
  8869. }
  8870. m++;
  8871. }
  8872. return NULL;
  8873. }
  8874. static int
  8875. is_valid_http_method(const char *method)
  8876. {
  8877. return (get_http_method_info(method) != NULL);
  8878. }
  8879. /* Parse HTTP request, fill in mg_request_info structure.
  8880. * This function modifies the buffer by NUL-terminating
  8881. * HTTP request components, header names and header values.
  8882. * Parameters:
  8883. * buf (in/out): pointer to the HTTP header to parse and split
  8884. * len (in): length of HTTP header buffer
  8885. * re (out): parsed header as mg_request_info
  8886. * buf and ri must be valid pointers (not NULL), len>0.
  8887. * Returns <0 on error. */
  8888. static int
  8889. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8890. {
  8891. int request_length;
  8892. int init_skip = 0;
  8893. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8894. * remote_port */
  8895. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8896. NULL;
  8897. ri->num_headers = 0;
  8898. /* RFC says that all initial whitespaces should be ingored */
  8899. /* This included all leading \r and \n (isspace) */
  8900. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8901. while ((len > 0) && isspace((unsigned char)*buf)) {
  8902. buf++;
  8903. len--;
  8904. init_skip++;
  8905. }
  8906. if (len == 0) {
  8907. /* Incomplete request */
  8908. return 0;
  8909. }
  8910. /* Control characters are not allowed, including zero */
  8911. if (iscntrl((unsigned char)*buf)) {
  8912. return -1;
  8913. }
  8914. /* Find end of HTTP header */
  8915. request_length = get_http_header_len(buf, len);
  8916. if (request_length <= 0) {
  8917. return request_length;
  8918. }
  8919. buf[request_length - 1] = '\0';
  8920. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8921. return -1;
  8922. }
  8923. /* The first word has to be the HTTP method */
  8924. ri->request_method = buf;
  8925. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8926. return -1;
  8927. }
  8928. /* Check for a valid http method */
  8929. if (!is_valid_http_method(ri->request_method)) {
  8930. return -1;
  8931. }
  8932. /* The second word is the URI */
  8933. ri->request_uri = buf;
  8934. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8935. return -1;
  8936. }
  8937. /* Next would be the HTTP version */
  8938. ri->http_version = buf;
  8939. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8940. return -1;
  8941. }
  8942. /* Check for a valid HTTP version key */
  8943. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8944. /* Invalid request */
  8945. return -1;
  8946. }
  8947. ri->http_version += 5;
  8948. /* Parse all HTTP headers */
  8949. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8950. if (ri->num_headers < 0) {
  8951. /* Error while parsing headers */
  8952. return -1;
  8953. }
  8954. return request_length + init_skip;
  8955. }
  8956. static int
  8957. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8958. {
  8959. int response_length;
  8960. int init_skip = 0;
  8961. char *tmp, *tmp2;
  8962. long l;
  8963. /* Initialize elements. */
  8964. ri->http_version = ri->status_text = NULL;
  8965. ri->num_headers = ri->status_code = 0;
  8966. /* RFC says that all initial whitespaces should be ingored */
  8967. /* This included all leading \r and \n (isspace) */
  8968. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8969. while ((len > 0) && isspace((unsigned char)*buf)) {
  8970. buf++;
  8971. len--;
  8972. init_skip++;
  8973. }
  8974. if (len == 0) {
  8975. /* Incomplete request */
  8976. return 0;
  8977. }
  8978. /* Control characters are not allowed, including zero */
  8979. if (iscntrl((unsigned char)*buf)) {
  8980. return -1;
  8981. }
  8982. /* Find end of HTTP header */
  8983. response_length = get_http_header_len(buf, len);
  8984. if (response_length <= 0) {
  8985. return response_length;
  8986. }
  8987. buf[response_length - 1] = '\0';
  8988. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8989. return -1;
  8990. }
  8991. /* The first word is the HTTP version */
  8992. /* Check for a valid HTTP version key */
  8993. if (strncmp(buf, "HTTP/", 5) != 0) {
  8994. /* Invalid request */
  8995. return -1;
  8996. }
  8997. buf += 5;
  8998. if (!isgraph((unsigned char)buf[0])) {
  8999. /* Invalid request */
  9000. return -1;
  9001. }
  9002. ri->http_version = buf;
  9003. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9004. return -1;
  9005. }
  9006. /* The second word is the status as a number */
  9007. tmp = buf;
  9008. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9009. return -1;
  9010. }
  9011. l = strtol(tmp, &tmp2, 10);
  9012. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9013. /* Everything else but a 3 digit code is invalid */
  9014. return -1;
  9015. }
  9016. ri->status_code = (int)l;
  9017. /* The rest of the line is the status text */
  9018. ri->status_text = buf;
  9019. /* Find end of status text */
  9020. /* isgraph or isspace = isprint */
  9021. while (isprint((unsigned char)*buf)) {
  9022. buf++;
  9023. }
  9024. if ((*buf != '\r') && (*buf != '\n')) {
  9025. return -1;
  9026. }
  9027. /* Terminate string and forward buf to next line */
  9028. do {
  9029. *buf = 0;
  9030. buf++;
  9031. } while (isspace((unsigned char)*buf));
  9032. /* Parse all HTTP headers */
  9033. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9034. if (ri->num_headers < 0) {
  9035. /* Error while parsing headers */
  9036. return -1;
  9037. }
  9038. return response_length + init_skip;
  9039. }
  9040. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9041. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9042. * buffer (which marks the end of HTTP request). Buffer buf may already
  9043. * have some data. The length of the data is stored in nread.
  9044. * Upon every read operation, increase nread by the number of bytes read. */
  9045. static int
  9046. read_message(FILE *fp,
  9047. struct mg_connection *conn,
  9048. char *buf,
  9049. int bufsiz,
  9050. int *nread)
  9051. {
  9052. int request_len, n = 0;
  9053. struct timespec last_action_time;
  9054. double request_timeout;
  9055. if (!conn) {
  9056. return 0;
  9057. }
  9058. memset(&last_action_time, 0, sizeof(last_action_time));
  9059. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9060. /* value of request_timeout is in seconds, config in milliseconds */
  9061. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9062. } else {
  9063. request_timeout = -1.0;
  9064. }
  9065. if (conn->handled_requests > 0) {
  9066. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9067. request_timeout =
  9068. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9069. }
  9070. }
  9071. request_len = get_http_header_len(buf, *nread);
  9072. while (request_len == 0) {
  9073. /* Full request not yet received */
  9074. if (conn->phys_ctx->stop_flag != 0) {
  9075. /* Server is to be stopped. */
  9076. return -1;
  9077. }
  9078. if (*nread >= bufsiz) {
  9079. /* Request too long */
  9080. return -2;
  9081. }
  9082. n = pull_inner(
  9083. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9084. if (n == -2) {
  9085. /* Receive error */
  9086. return -1;
  9087. }
  9088. /* update clock after every read request */
  9089. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9090. if (n > 0) {
  9091. *nread += n;
  9092. request_len = get_http_header_len(buf, *nread);
  9093. } else {
  9094. request_len = 0;
  9095. }
  9096. if ((request_len == 0) && (request_timeout >= 0)) {
  9097. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9098. > request_timeout) {
  9099. /* Timeout */
  9100. return -1;
  9101. }
  9102. }
  9103. }
  9104. return request_len;
  9105. }
  9106. #if !defined(NO_CGI) || !defined(NO_FILES)
  9107. static int
  9108. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9109. {
  9110. const char *expect;
  9111. char buf[MG_BUF_LEN];
  9112. int success = 0;
  9113. if (!conn) {
  9114. return 0;
  9115. }
  9116. expect = mg_get_header(conn, "Expect");
  9117. DEBUG_ASSERT(fp != NULL);
  9118. if (!fp) {
  9119. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9120. return 0;
  9121. }
  9122. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9123. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9124. */
  9125. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9126. } else {
  9127. if (expect != NULL) {
  9128. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9129. conn->status_code = 100;
  9130. } else {
  9131. conn->status_code = 200;
  9132. }
  9133. DEBUG_ASSERT(conn->consumed_content == 0);
  9134. if (conn->consumed_content != 0) {
  9135. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9136. return 0;
  9137. }
  9138. for (;;) {
  9139. int nread = mg_read(conn, buf, sizeof(buf));
  9140. if (nread <= 0) {
  9141. success = (nread == 0);
  9142. break;
  9143. }
  9144. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9145. break;
  9146. }
  9147. }
  9148. /* Each error code path in this function must send an error */
  9149. if (!success) {
  9150. /* NOTE: Maybe some data has already been sent. */
  9151. /* TODO (low): If some data has been sent, a correct error
  9152. * reply can no longer be sent, so just close the connection */
  9153. mg_send_http_error(conn, 500, "%s", "");
  9154. }
  9155. }
  9156. return success;
  9157. }
  9158. #endif
  9159. #if defined(USE_TIMERS)
  9160. #define TIMER_API static
  9161. #include "timer.inl"
  9162. #endif /* USE_TIMERS */
  9163. #if !defined(NO_CGI)
  9164. /* This structure helps to create an environment for the spawned CGI
  9165. * program.
  9166. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9167. * last element must be NULL.
  9168. * However, on Windows there is a requirement that all these
  9169. * VARIABLE=VALUE\0
  9170. * strings must reside in a contiguous buffer. The end of the buffer is
  9171. * marked by two '\0' characters.
  9172. * We satisfy both worlds: we create an envp array (which is vars), all
  9173. * entries are actually pointers inside buf. */
  9174. struct cgi_environment {
  9175. struct mg_connection *conn;
  9176. /* Data block */
  9177. char *buf; /* Environment buffer */
  9178. size_t buflen; /* Space available in buf */
  9179. size_t bufused; /* Space taken in buf */
  9180. /* Index block */
  9181. char **var; /* char **envp */
  9182. size_t varlen; /* Number of variables available in var */
  9183. size_t varused; /* Number of variables stored in var */
  9184. };
  9185. static void addenv(struct cgi_environment *env,
  9186. PRINTF_FORMAT_STRING(const char *fmt),
  9187. ...) PRINTF_ARGS(2, 3);
  9188. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9189. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9190. static void
  9191. addenv(struct cgi_environment *env, const char *fmt, ...)
  9192. {
  9193. size_t i, n, space;
  9194. int truncated = 0;
  9195. char *added;
  9196. va_list ap;
  9197. if ((env->varlen - env->varused) < 2) {
  9198. mg_cry_internal(env->conn,
  9199. "%s: Cannot register CGI variable [%s]",
  9200. __func__,
  9201. fmt);
  9202. return;
  9203. }
  9204. /* Calculate how much space is left in the buffer */
  9205. space = (env->buflen - env->bufused);
  9206. do {
  9207. /* Space for "\0\0" is always needed. */
  9208. if (space <= 2) {
  9209. /* Allocate new buffer */
  9210. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9211. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9212. if (!added) {
  9213. /* Out of memory */
  9214. mg_cry_internal(
  9215. env->conn,
  9216. "%s: Cannot allocate memory for CGI variable [%s]",
  9217. __func__,
  9218. fmt);
  9219. return;
  9220. }
  9221. /* Retarget pointers */
  9222. env->buf = added;
  9223. env->buflen = n;
  9224. for (i = 0, n = 0; i < env->varused; i++) {
  9225. env->var[i] = added + n;
  9226. n += strlen(added + n) + 1;
  9227. }
  9228. space = (env->buflen - env->bufused);
  9229. }
  9230. /* Make a pointer to the free space int the buffer */
  9231. added = env->buf + env->bufused;
  9232. /* Copy VARIABLE=VALUE\0 string into the free space */
  9233. va_start(ap, fmt);
  9234. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9235. va_end(ap);
  9236. /* Do not add truncated strings to the environment */
  9237. if (truncated) {
  9238. /* Reallocate the buffer */
  9239. space = 0;
  9240. }
  9241. } while (truncated);
  9242. /* Calculate number of bytes added to the environment */
  9243. n = strlen(added) + 1;
  9244. env->bufused += n;
  9245. /* Append a pointer to the added string into the envp array */
  9246. env->var[env->varused] = added;
  9247. env->varused++;
  9248. }
  9249. /* Return 0 on success, non-zero if an error occurs. */
  9250. static int
  9251. prepare_cgi_environment(struct mg_connection *conn,
  9252. const char *prog,
  9253. struct cgi_environment *env)
  9254. {
  9255. const char *s;
  9256. struct vec var_vec;
  9257. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9258. int i, truncated, uri_len;
  9259. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9260. return -1;
  9261. }
  9262. env->conn = conn;
  9263. env->buflen = CGI_ENVIRONMENT_SIZE;
  9264. env->bufused = 0;
  9265. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9266. if (env->buf == NULL) {
  9267. mg_cry_internal(conn,
  9268. "%s: Not enough memory for environmental buffer",
  9269. __func__);
  9270. return -1;
  9271. }
  9272. env->varlen = MAX_CGI_ENVIR_VARS;
  9273. env->varused = 0;
  9274. env->var =
  9275. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9276. if (env->var == NULL) {
  9277. mg_cry_internal(conn,
  9278. "%s: Not enough memory for environmental variables",
  9279. __func__);
  9280. mg_free(env->buf);
  9281. return -1;
  9282. }
  9283. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9284. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9285. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9286. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9287. /* Prepare the environment block */
  9288. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9289. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9290. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9291. #if defined(USE_IPV6)
  9292. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9293. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9294. } else
  9295. #endif
  9296. {
  9297. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9298. }
  9299. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9300. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9301. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9302. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9303. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9304. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9305. /* SCRIPT_NAME */
  9306. uri_len = (int)strlen(conn->request_info.local_uri);
  9307. if (conn->path_info == NULL) {
  9308. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9309. /* URI: /path_to_script/script.cgi */
  9310. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9311. } else {
  9312. /* URI: /path_to_script/ ... using index.cgi */
  9313. const char *index_file = strrchr(prog, '/');
  9314. if (index_file) {
  9315. addenv(env,
  9316. "SCRIPT_NAME=%s%s",
  9317. conn->request_info.local_uri,
  9318. index_file + 1);
  9319. }
  9320. }
  9321. } else {
  9322. /* URI: /path_to_script/script.cgi/path_info */
  9323. addenv(env,
  9324. "SCRIPT_NAME=%.*s",
  9325. uri_len - (int)strlen(conn->path_info),
  9326. conn->request_info.local_uri);
  9327. }
  9328. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9329. if (conn->path_info == NULL) {
  9330. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9331. } else {
  9332. addenv(env,
  9333. "PATH_TRANSLATED=%s%s",
  9334. conn->dom_ctx->config[DOCUMENT_ROOT],
  9335. conn->path_info);
  9336. }
  9337. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9338. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9339. addenv(env, "CONTENT_TYPE=%s", s);
  9340. }
  9341. if (conn->request_info.query_string != NULL) {
  9342. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9343. }
  9344. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9345. addenv(env, "CONTENT_LENGTH=%s", s);
  9346. }
  9347. if ((s = getenv("PATH")) != NULL) {
  9348. addenv(env, "PATH=%s", s);
  9349. }
  9350. if (conn->path_info != NULL) {
  9351. addenv(env, "PATH_INFO=%s", conn->path_info);
  9352. }
  9353. if (conn->status_code > 0) {
  9354. /* CGI error handler should show the status code */
  9355. addenv(env, "STATUS=%d", conn->status_code);
  9356. }
  9357. #if defined(_WIN32)
  9358. if ((s = getenv("COMSPEC")) != NULL) {
  9359. addenv(env, "COMSPEC=%s", s);
  9360. }
  9361. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9362. addenv(env, "SYSTEMROOT=%s", s);
  9363. }
  9364. if ((s = getenv("SystemDrive")) != NULL) {
  9365. addenv(env, "SystemDrive=%s", s);
  9366. }
  9367. if ((s = getenv("ProgramFiles")) != NULL) {
  9368. addenv(env, "ProgramFiles=%s", s);
  9369. }
  9370. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9371. addenv(env, "ProgramFiles(x86)=%s", s);
  9372. }
  9373. #else
  9374. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9375. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9376. }
  9377. #endif /* _WIN32 */
  9378. if ((s = getenv("PERLLIB")) != NULL) {
  9379. addenv(env, "PERLLIB=%s", s);
  9380. }
  9381. if (conn->request_info.remote_user != NULL) {
  9382. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9383. addenv(env, "%s", "AUTH_TYPE=Digest");
  9384. }
  9385. /* Add all headers as HTTP_* variables */
  9386. for (i = 0; i < conn->request_info.num_headers; i++) {
  9387. (void)mg_snprintf(conn,
  9388. &truncated,
  9389. http_var_name,
  9390. sizeof(http_var_name),
  9391. "HTTP_%s",
  9392. conn->request_info.http_headers[i].name);
  9393. if (truncated) {
  9394. mg_cry_internal(conn,
  9395. "%s: HTTP header variable too long [%s]",
  9396. __func__,
  9397. conn->request_info.http_headers[i].name);
  9398. continue;
  9399. }
  9400. /* Convert variable name into uppercase, and change - to _ */
  9401. for (p = http_var_name; *p != '\0'; p++) {
  9402. if (*p == '-') {
  9403. *p = '_';
  9404. }
  9405. *p = (char)toupper((unsigned char)*p);
  9406. }
  9407. addenv(env,
  9408. "%s=%s",
  9409. http_var_name,
  9410. conn->request_info.http_headers[i].value);
  9411. }
  9412. /* Add user-specified variables */
  9413. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9414. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9415. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9416. }
  9417. env->var[env->varused] = NULL;
  9418. env->buf[env->bufused] = '\0';
  9419. return 0;
  9420. }
  9421. /* Data for CGI process control: PID and number of references */
  9422. struct process_control_data {
  9423. pid_t pid;
  9424. int references;
  9425. };
  9426. static int
  9427. abort_process(void *data)
  9428. {
  9429. /* Waitpid checks for child status and won't work for a pid that does not
  9430. * identify a child of the current process. Thus, if the pid is reused,
  9431. * we will not affect a different process. */
  9432. struct process_control_data *proc = (struct process_control_data *)data;
  9433. int status = 0;
  9434. int refs;
  9435. pid_t ret_pid;
  9436. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9437. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9438. /* Stop child process */
  9439. DEBUG_TRACE("CGI timer: Stop child process %d\n", proc->pid);
  9440. kill(proc->pid, SIGABRT);
  9441. /* Wait until process is terminated (don't leave zombies) */
  9442. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9443. ;
  9444. } else {
  9445. DEBUG_TRACE("CGI timer: Child process %d already stopped\n", proc->pid);
  9446. }
  9447. /* Dec reference counter */
  9448. refs = mg_atomic_dec(&proc->references);
  9449. if (refs == 0) {
  9450. /* no more references - free data */
  9451. mg_free(data);
  9452. }
  9453. return 0;
  9454. }
  9455. /* Local (static) function assumes all arguments are valid. */
  9456. static void
  9457. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9458. {
  9459. char *buf;
  9460. size_t buflen;
  9461. int headers_len, data_len, i, truncated;
  9462. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9463. const char *status, *status_text, *connection_state;
  9464. char *pbuf, dir[PATH_MAX], *p;
  9465. struct mg_request_info ri;
  9466. struct cgi_environment blk;
  9467. FILE *in = NULL, *out = NULL, *err = NULL;
  9468. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9469. pid_t pid = (pid_t)-1;
  9470. struct process_control_data *proc = NULL;
  9471. #if defined(USE_TIMERS)
  9472. double cgi_timeout = -1.0;
  9473. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9474. /* Get timeout in seconds */
  9475. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9476. }
  9477. #endif
  9478. buf = NULL;
  9479. buflen = conn->phys_ctx->max_request_size;
  9480. i = prepare_cgi_environment(conn, prog, &blk);
  9481. if (i != 0) {
  9482. blk.buf = NULL;
  9483. blk.var = NULL;
  9484. goto done;
  9485. }
  9486. /* CGI must be executed in its own directory. 'dir' must point to the
  9487. * directory containing executable program, 'p' must point to the
  9488. * executable program name relative to 'dir'. */
  9489. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9490. if (truncated) {
  9491. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9492. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9493. goto done;
  9494. }
  9495. if ((p = strrchr(dir, '/')) != NULL) {
  9496. *p++ = '\0';
  9497. } else {
  9498. dir[0] = '.';
  9499. dir[1] = '\0';
  9500. p = (char *)prog;
  9501. }
  9502. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9503. status = strerror(ERRNO);
  9504. mg_cry_internal(
  9505. conn,
  9506. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9507. prog,
  9508. status);
  9509. mg_send_http_error(conn,
  9510. 500,
  9511. "Error: Cannot create CGI pipe: %s",
  9512. status);
  9513. goto done;
  9514. }
  9515. proc = (struct process_control_data *)
  9516. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9517. if (proc == NULL) {
  9518. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9519. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9520. goto done;
  9521. }
  9522. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9523. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9524. if (pid == (pid_t)-1) {
  9525. status = strerror(ERRNO);
  9526. mg_cry_internal(
  9527. conn,
  9528. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9529. prog,
  9530. status);
  9531. mg_send_http_error(conn,
  9532. 500,
  9533. "Error: Cannot spawn CGI process [%s]: %s",
  9534. prog,
  9535. status);
  9536. mg_free(proc);
  9537. proc = NULL;
  9538. goto done;
  9539. }
  9540. /* Store data in shared process_control_data */
  9541. proc->pid = pid;
  9542. proc->references = 1;
  9543. #if defined(USE_TIMERS)
  9544. if (cgi_timeout > 0.0) {
  9545. proc->references = 2;
  9546. // Start a timer for CGI
  9547. timer_add(conn->phys_ctx,
  9548. cgi_timeout /* in seconds */,
  9549. 0.0,
  9550. 1,
  9551. abort_process,
  9552. (void *)proc);
  9553. }
  9554. #endif
  9555. /* Parent closes only one side of the pipes.
  9556. * If we don't mark them as closed, close() attempt before
  9557. * return from this function throws an exception on Windows.
  9558. * Windows does not like when closed descriptor is closed again. */
  9559. (void)close(fdin[0]);
  9560. (void)close(fdout[1]);
  9561. (void)close(fderr[1]);
  9562. fdin[0] = fdout[1] = fderr[1] = -1;
  9563. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9564. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9565. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9566. status = strerror(ERRNO);
  9567. mg_cry_internal(conn,
  9568. "Error: CGI program \"%s\": Can not open fd: %s",
  9569. prog,
  9570. status);
  9571. mg_send_http_error(conn,
  9572. 500,
  9573. "Error: CGI can not open fd\nfdopen: %s",
  9574. status);
  9575. goto done;
  9576. }
  9577. setbuf(in, NULL);
  9578. setbuf(out, NULL);
  9579. setbuf(err, NULL);
  9580. fout.access.fp = out;
  9581. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9582. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9583. conn->content_len);
  9584. /* This is a POST/PUT request, or another request with body data. */
  9585. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9586. /* Error sending the body data */
  9587. mg_cry_internal(
  9588. conn,
  9589. "Error: CGI program \"%s\": Forward body data failed",
  9590. prog);
  9591. goto done;
  9592. }
  9593. }
  9594. /* Close so child gets an EOF. */
  9595. fclose(in);
  9596. in = NULL;
  9597. fdin[1] = -1;
  9598. /* Now read CGI reply into a buffer. We need to set correct
  9599. * status code, thus we need to see all HTTP headers first.
  9600. * Do not send anything back to client, until we buffer in all
  9601. * HTTP headers. */
  9602. data_len = 0;
  9603. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9604. if (buf == NULL) {
  9605. mg_send_http_error(conn,
  9606. 500,
  9607. "Error: Not enough memory for CGI buffer (%u bytes)",
  9608. (unsigned int)buflen);
  9609. mg_cry_internal(
  9610. conn,
  9611. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9612. "bytes)",
  9613. prog,
  9614. (unsigned int)buflen);
  9615. goto done;
  9616. }
  9617. DEBUG_TRACE("CGI: %s", "wait for response");
  9618. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9619. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9620. if (headers_len <= 0) {
  9621. /* Could not parse the CGI response. Check if some error message on
  9622. * stderr. */
  9623. i = pull_all(err, conn, buf, (int)buflen);
  9624. if (i > 0) {
  9625. /* CGI program explicitly sent an error */
  9626. /* Write the error message to the internal log */
  9627. mg_cry_internal(conn,
  9628. "Error: CGI program \"%s\" sent error "
  9629. "message: [%.*s]",
  9630. prog,
  9631. i,
  9632. buf);
  9633. /* Don't send the error message back to the client */
  9634. mg_send_http_error(conn,
  9635. 500,
  9636. "Error: CGI program \"%s\" failed.",
  9637. prog);
  9638. } else {
  9639. /* CGI program did not explicitly send an error, but a broken
  9640. * respon header */
  9641. mg_cry_internal(conn,
  9642. "Error: CGI program sent malformed or too big "
  9643. "(>%u bytes) HTTP headers: [%.*s]",
  9644. (unsigned)buflen,
  9645. data_len,
  9646. buf);
  9647. mg_send_http_error(conn,
  9648. 500,
  9649. "Error: CGI program sent malformed or too big "
  9650. "(>%u bytes) HTTP headers: [%.*s]",
  9651. (unsigned)buflen,
  9652. data_len,
  9653. buf);
  9654. }
  9655. /* in both cases, abort processing CGI */
  9656. goto done;
  9657. }
  9658. pbuf = buf;
  9659. buf[headers_len - 1] = '\0';
  9660. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9661. /* Make up and send the status line */
  9662. status_text = "OK";
  9663. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9664. != NULL) {
  9665. conn->status_code = atoi(status);
  9666. status_text = status;
  9667. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9668. status_text++;
  9669. }
  9670. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9671. != NULL) {
  9672. conn->status_code = 307;
  9673. } else {
  9674. conn->status_code = 200;
  9675. }
  9676. connection_state =
  9677. get_header(ri.http_headers, ri.num_headers, "Connection");
  9678. if (!header_has_option(connection_state, "keep-alive")) {
  9679. conn->must_close = 1;
  9680. }
  9681. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9682. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9683. /* Send headers */
  9684. for (i = 0; i < ri.num_headers; i++) {
  9685. DEBUG_TRACE("CGI header: %s: %s",
  9686. ri.http_headers[i].name,
  9687. ri.http_headers[i].value);
  9688. mg_printf(conn,
  9689. "%s: %s\r\n",
  9690. ri.http_headers[i].name,
  9691. ri.http_headers[i].value);
  9692. }
  9693. mg_write(conn, "\r\n", 2);
  9694. /* Send chunk of data that may have been read after the headers */
  9695. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9696. /* Read the rest of CGI output and send to the client */
  9697. DEBUG_TRACE("CGI: %s", "forward all data");
  9698. send_file_data(conn, &fout, 0, INT64_MAX);
  9699. DEBUG_TRACE("CGI: %s", "all data sent");
  9700. done:
  9701. mg_free(blk.var);
  9702. mg_free(blk.buf);
  9703. if (pid != (pid_t)-1) {
  9704. abort_process((void *)proc);
  9705. }
  9706. if (fdin[0] != -1) {
  9707. close(fdin[0]);
  9708. }
  9709. if (fdout[1] != -1) {
  9710. close(fdout[1]);
  9711. }
  9712. if (fderr[1] != -1) {
  9713. close(fderr[1]);
  9714. }
  9715. if (in != NULL) {
  9716. fclose(in);
  9717. } else if (fdin[1] != -1) {
  9718. close(fdin[1]);
  9719. }
  9720. if (out != NULL) {
  9721. fclose(out);
  9722. } else if (fdout[0] != -1) {
  9723. close(fdout[0]);
  9724. }
  9725. if (err != NULL) {
  9726. fclose(err);
  9727. } else if (fderr[0] != -1) {
  9728. close(fderr[0]);
  9729. }
  9730. mg_free(buf);
  9731. }
  9732. #endif /* !NO_CGI */
  9733. #if !defined(NO_FILES)
  9734. static void
  9735. mkcol(struct mg_connection *conn, const char *path)
  9736. {
  9737. int rc, body_len;
  9738. struct de de;
  9739. char date[64];
  9740. time_t curtime = time(NULL);
  9741. if (conn == NULL) {
  9742. return;
  9743. }
  9744. /* TODO (mid): Check the mg_send_http_error situations in this function
  9745. */
  9746. memset(&de.file, 0, sizeof(de.file));
  9747. if (!mg_stat(conn, path, &de.file)) {
  9748. mg_cry_internal(conn,
  9749. "%s: mg_stat(%s) failed: %s",
  9750. __func__,
  9751. path,
  9752. strerror(ERRNO));
  9753. }
  9754. if (de.file.last_modified) {
  9755. /* TODO (mid): This check does not seem to make any sense ! */
  9756. /* TODO (mid): Add a webdav unit test first, before changing
  9757. * anything here. */
  9758. mg_send_http_error(
  9759. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9760. return;
  9761. }
  9762. body_len = conn->data_len - conn->request_len;
  9763. if (body_len > 0) {
  9764. mg_send_http_error(
  9765. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9766. return;
  9767. }
  9768. rc = mg_mkdir(conn, path, 0755);
  9769. if (rc == 0) {
  9770. conn->status_code = 201;
  9771. gmt_time_string(date, sizeof(date), &curtime);
  9772. mg_printf(conn,
  9773. "HTTP/1.1 %d Created\r\n"
  9774. "Date: %s\r\n",
  9775. conn->status_code,
  9776. date);
  9777. send_static_cache_header(conn);
  9778. send_additional_header(conn);
  9779. mg_printf(conn,
  9780. "Content-Length: 0\r\n"
  9781. "Connection: %s\r\n\r\n",
  9782. suggest_connection_header(conn));
  9783. } else {
  9784. if (errno == EEXIST) {
  9785. mg_send_http_error(
  9786. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9787. } else if (errno == EACCES) {
  9788. mg_send_http_error(
  9789. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9790. } else if (errno == ENOENT) {
  9791. mg_send_http_error(
  9792. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9793. } else {
  9794. mg_send_http_error(
  9795. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9796. }
  9797. }
  9798. }
  9799. static void
  9800. put_file(struct mg_connection *conn, const char *path)
  9801. {
  9802. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9803. const char *range;
  9804. int64_t r1, r2;
  9805. int rc;
  9806. char date[64];
  9807. time_t curtime = time(NULL);
  9808. if (conn == NULL) {
  9809. return;
  9810. }
  9811. if (mg_stat(conn, path, &file.stat)) {
  9812. /* File already exists */
  9813. conn->status_code = 200;
  9814. if (file.stat.is_directory) {
  9815. /* This is an already existing directory,
  9816. * so there is nothing to do for the server. */
  9817. rc = 0;
  9818. } else {
  9819. /* File exists and is not a directory. */
  9820. /* Can it be replaced? */
  9821. #if defined(MG_USE_OPEN_FILE)
  9822. if (file.access.membuf != NULL) {
  9823. /* This is an "in-memory" file, that can not be replaced */
  9824. mg_send_http_error(conn,
  9825. 405,
  9826. "Error: Put not possible\nReplacing %s "
  9827. "is not supported",
  9828. path);
  9829. return;
  9830. }
  9831. #endif
  9832. /* Check if the server may write this file */
  9833. if (access(path, W_OK) == 0) {
  9834. /* Access granted */
  9835. conn->status_code = 200;
  9836. rc = 1;
  9837. } else {
  9838. mg_send_http_error(
  9839. conn,
  9840. 403,
  9841. "Error: Put not possible\nReplacing %s is not allowed",
  9842. path);
  9843. return;
  9844. }
  9845. }
  9846. } else {
  9847. /* File should be created */
  9848. conn->status_code = 201;
  9849. rc = put_dir(conn, path);
  9850. }
  9851. if (rc == 0) {
  9852. /* put_dir returns 0 if path is a directory */
  9853. gmt_time_string(date, sizeof(date), &curtime);
  9854. mg_printf(conn,
  9855. "HTTP/1.1 %d %s\r\n",
  9856. conn->status_code,
  9857. mg_get_response_code_text(NULL, conn->status_code));
  9858. send_no_cache_header(conn);
  9859. send_additional_header(conn);
  9860. mg_printf(conn,
  9861. "Date: %s\r\n"
  9862. "Content-Length: 0\r\n"
  9863. "Connection: %s\r\n\r\n",
  9864. date,
  9865. suggest_connection_header(conn));
  9866. /* Request to create a directory has been fulfilled successfully.
  9867. * No need to put a file. */
  9868. return;
  9869. }
  9870. if (rc == -1) {
  9871. /* put_dir returns -1 if the path is too long */
  9872. mg_send_http_error(conn,
  9873. 414,
  9874. "Error: Path too long\nput_dir(%s): %s",
  9875. path,
  9876. strerror(ERRNO));
  9877. return;
  9878. }
  9879. if (rc == -2) {
  9880. /* put_dir returns -2 if the directory can not be created */
  9881. mg_send_http_error(conn,
  9882. 500,
  9883. "Error: Can not create directory\nput_dir(%s): %s",
  9884. path,
  9885. strerror(ERRNO));
  9886. return;
  9887. }
  9888. /* A file should be created or overwritten. */
  9889. /* Currently CivetWeb does not nead read+write access. */
  9890. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9891. || file.access.fp == NULL) {
  9892. (void)mg_fclose(&file.access);
  9893. mg_send_http_error(conn,
  9894. 500,
  9895. "Error: Can not create file\nfopen(%s): %s",
  9896. path,
  9897. strerror(ERRNO));
  9898. return;
  9899. }
  9900. fclose_on_exec(&file.access, conn);
  9901. range = mg_get_header(conn, "Content-Range");
  9902. r1 = r2 = 0;
  9903. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9904. conn->status_code = 206; /* Partial content */
  9905. fseeko(file.access.fp, r1, SEEK_SET);
  9906. }
  9907. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9908. /* forward_body_data failed.
  9909. * The error code has already been sent to the client,
  9910. * and conn->status_code is already set. */
  9911. (void)mg_fclose(&file.access);
  9912. return;
  9913. }
  9914. if (mg_fclose(&file.access) != 0) {
  9915. /* fclose failed. This might have different reasons, but a likely
  9916. * one is "no space on disk", http 507. */
  9917. conn->status_code = 507;
  9918. }
  9919. gmt_time_string(date, sizeof(date), &curtime);
  9920. mg_printf(conn,
  9921. "HTTP/1.1 %d %s\r\n",
  9922. conn->status_code,
  9923. mg_get_response_code_text(NULL, conn->status_code));
  9924. send_no_cache_header(conn);
  9925. send_additional_header(conn);
  9926. mg_printf(conn,
  9927. "Date: %s\r\n"
  9928. "Content-Length: 0\r\n"
  9929. "Connection: %s\r\n\r\n",
  9930. date,
  9931. suggest_connection_header(conn));
  9932. }
  9933. static void
  9934. delete_file(struct mg_connection *conn, const char *path)
  9935. {
  9936. struct de de;
  9937. memset(&de.file, 0, sizeof(de.file));
  9938. if (!mg_stat(conn, path, &de.file)) {
  9939. /* mg_stat returns 0 if the file does not exist */
  9940. mg_send_http_error(conn,
  9941. 404,
  9942. "Error: Cannot delete file\nFile %s not found",
  9943. path);
  9944. return;
  9945. }
  9946. #if 0 /* Ignore if a file in memory is inside a folder */
  9947. if (de.access.membuf != NULL) {
  9948. /* the file is cached in memory */
  9949. mg_send_http_error(
  9950. conn,
  9951. 405,
  9952. "Error: Delete not possible\nDeleting %s is not supported",
  9953. path);
  9954. return;
  9955. }
  9956. #endif
  9957. if (de.file.is_directory) {
  9958. if (remove_directory(conn, path)) {
  9959. /* Delete is successful: Return 204 without content. */
  9960. mg_send_http_error(conn, 204, "%s", "");
  9961. } else {
  9962. /* Delete is not successful: Return 500 (Server error). */
  9963. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9964. }
  9965. return;
  9966. }
  9967. /* This is an existing file (not a directory).
  9968. * Check if write permission is granted. */
  9969. if (access(path, W_OK) != 0) {
  9970. /* File is read only */
  9971. mg_send_http_error(
  9972. conn,
  9973. 403,
  9974. "Error: Delete not possible\nDeleting %s is not allowed",
  9975. path);
  9976. return;
  9977. }
  9978. /* Try to delete it. */
  9979. if (mg_remove(conn, path) == 0) {
  9980. /* Delete was successful: Return 204 without content. */
  9981. mg_send_http_error(conn, 204, "%s", "");
  9982. } else {
  9983. /* Delete not successful (file locked). */
  9984. mg_send_http_error(conn,
  9985. 423,
  9986. "Error: Cannot delete file\nremove(%s): %s",
  9987. path,
  9988. strerror(ERRNO));
  9989. }
  9990. }
  9991. #endif /* !NO_FILES */
  9992. #if !defined(NO_FILESYSTEMS)
  9993. static void
  9994. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9995. static void
  9996. do_ssi_include(struct mg_connection *conn,
  9997. const char *ssi,
  9998. char *tag,
  9999. int include_level)
  10000. {
  10001. char file_name[MG_BUF_LEN], path[512], *p;
  10002. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10003. size_t len;
  10004. int truncated = 0;
  10005. if (conn == NULL) {
  10006. return;
  10007. }
  10008. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10009. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10010. * always < MG_BUF_LEN. */
  10011. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10012. /* File name is relative to the webserver root */
  10013. file_name[511] = 0;
  10014. (void)mg_snprintf(conn,
  10015. &truncated,
  10016. path,
  10017. sizeof(path),
  10018. "%s/%s",
  10019. conn->dom_ctx->config[DOCUMENT_ROOT],
  10020. file_name);
  10021. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10022. /* File name is relative to the webserver working directory
  10023. * or it is absolute system path */
  10024. file_name[511] = 0;
  10025. (void)
  10026. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10027. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10028. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10029. /* File name is relative to the currect document */
  10030. file_name[511] = 0;
  10031. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10032. if (!truncated) {
  10033. if ((p = strrchr(path, '/')) != NULL) {
  10034. p[1] = '\0';
  10035. }
  10036. len = strlen(path);
  10037. (void)mg_snprintf(conn,
  10038. &truncated,
  10039. path + len,
  10040. sizeof(path) - len,
  10041. "%s",
  10042. file_name);
  10043. }
  10044. } else {
  10045. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10046. return;
  10047. }
  10048. if (truncated) {
  10049. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10050. return;
  10051. }
  10052. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10053. mg_cry_internal(conn,
  10054. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10055. tag,
  10056. path,
  10057. strerror(ERRNO));
  10058. } else {
  10059. fclose_on_exec(&file.access, conn);
  10060. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10061. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10062. path)
  10063. > 0) {
  10064. send_ssi_file(conn, path, &file, include_level + 1);
  10065. } else {
  10066. send_file_data(conn, &file, 0, INT64_MAX);
  10067. }
  10068. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10069. }
  10070. }
  10071. #if !defined(NO_POPEN)
  10072. static void
  10073. do_ssi_exec(struct mg_connection *conn, char *tag)
  10074. {
  10075. char cmd[1024] = "";
  10076. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10077. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10078. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10079. } else {
  10080. cmd[1023] = 0;
  10081. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10082. mg_cry_internal(conn,
  10083. "Cannot SSI #exec: [%s]: %s",
  10084. cmd,
  10085. strerror(ERRNO));
  10086. } else {
  10087. send_file_data(conn, &file, 0, INT64_MAX);
  10088. pclose(file.access.fp);
  10089. }
  10090. }
  10091. }
  10092. #endif /* !NO_POPEN */
  10093. static int
  10094. mg_fgetc(struct mg_file *filep, int offset)
  10095. {
  10096. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10097. if (filep == NULL) {
  10098. return EOF;
  10099. }
  10100. #if defined(MG_USE_OPEN_FILE)
  10101. if ((filep->access.membuf != NULL) && (offset >= 0)
  10102. && (((unsigned int)(offset)) < filep->stat.size)) {
  10103. return ((const unsigned char *)filep->access.membuf)[offset];
  10104. } else /* else block below */
  10105. #endif
  10106. if (filep->access.fp != NULL) {
  10107. return fgetc(filep->access.fp);
  10108. } else {
  10109. return EOF;
  10110. }
  10111. }
  10112. static void
  10113. send_ssi_file(struct mg_connection *conn,
  10114. const char *path,
  10115. struct mg_file *filep,
  10116. int include_level)
  10117. {
  10118. char buf[MG_BUF_LEN];
  10119. int ch, offset, len, in_tag, in_ssi_tag;
  10120. if (include_level > 10) {
  10121. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10122. return;
  10123. }
  10124. in_tag = in_ssi_tag = len = offset = 0;
  10125. /* Read file, byte by byte, and look for SSI include tags */
  10126. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10127. if (in_tag) {
  10128. /* We are in a tag, either SSI tag or html tag */
  10129. if (ch == '>') {
  10130. /* Tag is closing */
  10131. buf[len++] = '>';
  10132. if (in_ssi_tag) {
  10133. /* Handle SSI tag */
  10134. buf[len] = 0;
  10135. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10136. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10137. #if !defined(NO_POPEN)
  10138. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10139. do_ssi_exec(conn, buf + 9);
  10140. #endif /* !NO_POPEN */
  10141. } else {
  10142. mg_cry_internal(conn,
  10143. "%s: unknown SSI "
  10144. "command: \"%s\"",
  10145. path,
  10146. buf);
  10147. }
  10148. len = 0;
  10149. in_ssi_tag = in_tag = 0;
  10150. } else {
  10151. /* Not an SSI tag */
  10152. /* Flush buffer */
  10153. (void)mg_write(conn, buf, (size_t)len);
  10154. len = 0;
  10155. in_tag = 0;
  10156. }
  10157. } else {
  10158. /* Tag is still open */
  10159. buf[len++] = (char)(ch & 0xff);
  10160. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10161. /* All SSI tags start with <!--# */
  10162. in_ssi_tag = 1;
  10163. }
  10164. if ((len + 2) > (int)sizeof(buf)) {
  10165. /* Tag to long for buffer */
  10166. mg_cry_internal(conn, "%s: tag is too large", path);
  10167. return;
  10168. }
  10169. }
  10170. } else {
  10171. /* We are not in a tag yet. */
  10172. if (ch == '<') {
  10173. /* Tag is opening */
  10174. in_tag = 1;
  10175. if (len > 0) {
  10176. /* Flush current buffer.
  10177. * Buffer is filled with "len" bytes. */
  10178. (void)mg_write(conn, buf, (size_t)len);
  10179. }
  10180. /* Store the < */
  10181. len = 1;
  10182. buf[0] = '<';
  10183. } else {
  10184. /* No Tag */
  10185. /* Add data to buffer */
  10186. buf[len++] = (char)(ch & 0xff);
  10187. /* Flush if buffer is full */
  10188. if (len == (int)sizeof(buf)) {
  10189. mg_write(conn, buf, (size_t)len);
  10190. len = 0;
  10191. }
  10192. }
  10193. }
  10194. }
  10195. /* Send the rest of buffered data */
  10196. if (len > 0) {
  10197. mg_write(conn, buf, (size_t)len);
  10198. }
  10199. }
  10200. static void
  10201. handle_ssi_file_request(struct mg_connection *conn,
  10202. const char *path,
  10203. struct mg_file *filep)
  10204. {
  10205. char date[64];
  10206. time_t curtime = time(NULL);
  10207. const char *cors_orig_cfg;
  10208. const char *cors1, *cors2, *cors3;
  10209. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10210. return;
  10211. }
  10212. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10213. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10214. /* Cross-origin resource sharing (CORS). */
  10215. cors1 = "Access-Control-Allow-Origin: ";
  10216. cors2 = cors_orig_cfg;
  10217. cors3 = "\r\n";
  10218. } else {
  10219. cors1 = cors2 = cors3 = "";
  10220. }
  10221. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10222. /* File exists (precondition for calling this function),
  10223. * but can not be opened by the server. */
  10224. mg_send_http_error(conn,
  10225. 500,
  10226. "Error: Cannot read file\nfopen(%s): %s",
  10227. path,
  10228. strerror(ERRNO));
  10229. } else {
  10230. conn->must_close = 1;
  10231. gmt_time_string(date, sizeof(date), &curtime);
  10232. fclose_on_exec(&filep->access, conn);
  10233. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10234. send_no_cache_header(conn);
  10235. send_additional_header(conn);
  10236. mg_printf(conn,
  10237. "%s%s%s"
  10238. "Date: %s\r\n"
  10239. "Content-Type: text/html\r\n"
  10240. "Connection: %s\r\n\r\n",
  10241. cors1,
  10242. cors2,
  10243. cors3,
  10244. date,
  10245. suggest_connection_header(conn));
  10246. send_ssi_file(conn, path, filep, 0);
  10247. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10248. }
  10249. }
  10250. #endif /* NO_FILESYSTEMS */
  10251. #if !defined(NO_FILES)
  10252. static void
  10253. send_options(struct mg_connection *conn)
  10254. {
  10255. char date[64];
  10256. time_t curtime = time(NULL);
  10257. if (!conn) {
  10258. return;
  10259. }
  10260. conn->status_code = 200;
  10261. conn->must_close = 1;
  10262. gmt_time_string(date, sizeof(date), &curtime);
  10263. /* We do not set a "Cache-Control" header here, but leave the default.
  10264. * Since browsers do not send an OPTIONS request, we can not test the
  10265. * effect anyway. */
  10266. mg_printf(conn,
  10267. "HTTP/1.1 200 OK\r\n"
  10268. "Date: %s\r\n"
  10269. "Connection: %s\r\n"
  10270. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10271. "PROPFIND, MKCOL\r\n"
  10272. "DAV: 1\r\n",
  10273. date,
  10274. suggest_connection_header(conn));
  10275. send_additional_header(conn);
  10276. mg_printf(conn, "\r\n");
  10277. }
  10278. /* Writes PROPFIND properties for a collection element */
  10279. static int
  10280. print_props(struct mg_connection *conn,
  10281. const char *uri,
  10282. const char *name,
  10283. struct mg_file_stat *filep)
  10284. {
  10285. size_t href_size, i, j;
  10286. int len;
  10287. char *href, mtime[64];
  10288. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10289. return 0;
  10290. }
  10291. /* Estimate worst case size for encoding */
  10292. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10293. href = (char *)mg_malloc(href_size);
  10294. if (href == NULL) {
  10295. return 0;
  10296. }
  10297. len = mg_url_encode(uri, href, href_size);
  10298. if (len >= 0) {
  10299. /* Append an extra string */
  10300. mg_url_encode(name, href + len, href_size - (size_t)len);
  10301. }
  10302. /* Directory separator should be preserved. */
  10303. for (i = j = 0; href[i]; j++) {
  10304. if (!strncmp(href + i, "%2f", 3)) {
  10305. href[j] = '/';
  10306. i += 3;
  10307. } else {
  10308. href[j] = href[i++];
  10309. }
  10310. }
  10311. href[j] = '\0';
  10312. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10313. mg_printf(conn,
  10314. "<d:response>"
  10315. "<d:href>%s</d:href>"
  10316. "<d:propstat>"
  10317. "<d:prop>"
  10318. "<d:resourcetype>%s</d:resourcetype>"
  10319. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10320. "<d:getlastmodified>%s</d:getlastmodified>"
  10321. "</d:prop>"
  10322. "<d:status>HTTP/1.1 200 OK</d:status>"
  10323. "</d:propstat>"
  10324. "</d:response>\n",
  10325. href,
  10326. filep->is_directory ? "<d:collection/>" : "",
  10327. filep->size,
  10328. mtime);
  10329. mg_free(href);
  10330. return 1;
  10331. }
  10332. static int
  10333. print_dav_dir_entry(struct de *de, void *data)
  10334. {
  10335. struct mg_connection *conn = (struct mg_connection *)data;
  10336. if (!de || !conn
  10337. || !print_props(
  10338. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10339. return -1;
  10340. }
  10341. return 0;
  10342. }
  10343. static void
  10344. handle_propfind(struct mg_connection *conn,
  10345. const char *path,
  10346. struct mg_file_stat *filep)
  10347. {
  10348. const char *depth = mg_get_header(conn, "Depth");
  10349. char date[64];
  10350. time_t curtime = time(NULL);
  10351. gmt_time_string(date, sizeof(date), &curtime);
  10352. if (!conn || !path || !filep || !conn->dom_ctx) {
  10353. return;
  10354. }
  10355. conn->must_close = 1;
  10356. conn->status_code = 207;
  10357. mg_printf(conn,
  10358. "HTTP/1.1 207 Multi-Status\r\n"
  10359. "Date: %s\r\n",
  10360. date);
  10361. send_static_cache_header(conn);
  10362. send_additional_header(conn);
  10363. mg_printf(conn,
  10364. "Connection: %s\r\n"
  10365. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10366. suggest_connection_header(conn));
  10367. mg_printf(conn,
  10368. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10369. "<d:multistatus xmlns:d='DAV:'>\n");
  10370. /* Print properties for the requested resource itself */
  10371. print_props(conn, conn->request_info.local_uri, "", filep);
  10372. /* If it is a directory, print directory entries too if Depth is not 0
  10373. */
  10374. if (filep->is_directory
  10375. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10376. "yes")
  10377. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10378. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10379. }
  10380. mg_printf(conn, "%s\n", "</d:multistatus>");
  10381. }
  10382. #endif
  10383. void
  10384. mg_lock_connection(struct mg_connection *conn)
  10385. {
  10386. if (conn) {
  10387. (void)pthread_mutex_lock(&conn->mutex);
  10388. }
  10389. }
  10390. void
  10391. mg_unlock_connection(struct mg_connection *conn)
  10392. {
  10393. if (conn) {
  10394. (void)pthread_mutex_unlock(&conn->mutex);
  10395. }
  10396. }
  10397. void
  10398. mg_lock_context(struct mg_context *ctx)
  10399. {
  10400. if (ctx) {
  10401. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10402. }
  10403. }
  10404. void
  10405. mg_unlock_context(struct mg_context *ctx)
  10406. {
  10407. if (ctx) {
  10408. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10409. }
  10410. }
  10411. #if defined(USE_LUA)
  10412. #include "mod_lua.inl"
  10413. #endif /* USE_LUA */
  10414. #if defined(USE_DUKTAPE)
  10415. #include "mod_duktape.inl"
  10416. #endif /* USE_DUKTAPE */
  10417. #if defined(USE_WEBSOCKET)
  10418. #if !defined(NO_SSL_DL)
  10419. #define SHA_API static
  10420. #include "sha1.inl"
  10421. #endif
  10422. static int
  10423. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10424. {
  10425. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10426. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10427. SHA_CTX sha_ctx;
  10428. int truncated;
  10429. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10430. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10431. if (truncated) {
  10432. conn->must_close = 1;
  10433. return 0;
  10434. }
  10435. DEBUG_TRACE("%s", "Send websocket handshake");
  10436. SHA1_Init(&sha_ctx);
  10437. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10438. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10439. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10440. mg_printf(conn,
  10441. "HTTP/1.1 101 Switching Protocols\r\n"
  10442. "Upgrade: websocket\r\n"
  10443. "Connection: Upgrade\r\n"
  10444. "Sec-WebSocket-Accept: %s\r\n",
  10445. b64_sha);
  10446. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10447. mg_printf(conn,
  10448. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10449. conn->request_info.acceptedWebSocketSubprotocol);
  10450. } else {
  10451. mg_printf(conn, "%s", "\r\n");
  10452. }
  10453. return 1;
  10454. }
  10455. #if !defined(MG_MAX_UNANSWERED_PING)
  10456. /* Configuration of the maximum number of websocket PINGs that might
  10457. * stay unanswered before the connection is considered broken.
  10458. * Note: The name of this define may still change (until it is
  10459. * defined as a compile parameter in a documentation).
  10460. */
  10461. #define MG_MAX_UNANSWERED_PING (5)
  10462. #endif
  10463. static void
  10464. read_websocket(struct mg_connection *conn,
  10465. mg_websocket_data_handler ws_data_handler,
  10466. void *callback_data)
  10467. {
  10468. /* Pointer to the beginning of the portion of the incoming websocket
  10469. * message queue.
  10470. * The original websocket upgrade request is never removed, so the queue
  10471. * begins after it. */
  10472. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10473. int n, error, exit_by_callback;
  10474. int ret;
  10475. /* body_len is the length of the entire queue in bytes
  10476. * len is the length of the current message
  10477. * data_len is the length of the current message's data payload
  10478. * header_len is the length of the current message's header */
  10479. size_t i, len, mask_len = 0, header_len, body_len;
  10480. uint64_t data_len = 0;
  10481. /* "The masking key is a 32-bit value chosen at random by the client."
  10482. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10483. */
  10484. unsigned char mask[4];
  10485. /* data points to the place where the message is stored when passed to
  10486. * the websocket_data callback. This is either mem on the stack, or a
  10487. * dynamically allocated buffer if it is too large. */
  10488. unsigned char mem[4096];
  10489. unsigned char mop; /* mask flag and opcode */
  10490. /* Variables used for connection monitoring */
  10491. double timeout = -1.0;
  10492. int enable_ping_pong = 0;
  10493. int ping_count = 0;
  10494. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10495. enable_ping_pong =
  10496. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10497. "yes");
  10498. }
  10499. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10500. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10501. }
  10502. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10503. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10504. }
  10505. /* Enter data processing loop */
  10506. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10507. conn->request_info.remote_addr,
  10508. conn->request_info.remote_port);
  10509. conn->in_websocket_handling = 1;
  10510. mg_set_thread_name("wsock");
  10511. /* Loop continuously, reading messages from the socket, invoking the
  10512. * callback, and waiting repeatedly until an error occurs. */
  10513. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10514. header_len = 0;
  10515. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10516. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10517. len = buf[1] & 127;
  10518. mask_len = (buf[1] & 128) ? 4 : 0;
  10519. if ((len < 126) && (body_len >= mask_len)) {
  10520. /* inline 7-bit length field */
  10521. data_len = len;
  10522. header_len = 2 + mask_len;
  10523. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10524. /* 16-bit length field */
  10525. header_len = 4 + mask_len;
  10526. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10527. } else if (body_len >= (10 + mask_len)) {
  10528. /* 64-bit length field */
  10529. uint32_t l1, l2;
  10530. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10531. memcpy(&l2, &buf[6], 4);
  10532. header_len = 10 + mask_len;
  10533. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10534. if (data_len > (uint64_t)0x7FFF0000ul) {
  10535. /* no can do */
  10536. mg_cry_internal(
  10537. conn,
  10538. "%s",
  10539. "websocket out of memory; closing connection");
  10540. break;
  10541. }
  10542. }
  10543. }
  10544. if ((header_len > 0) && (body_len >= header_len)) {
  10545. /* Allocate space to hold websocket payload */
  10546. unsigned char *data = mem;
  10547. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10548. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10549. conn->phys_ctx);
  10550. if (data == NULL) {
  10551. /* Allocation failed, exit the loop and then close the
  10552. * connection */
  10553. mg_cry_internal(
  10554. conn,
  10555. "%s",
  10556. "websocket out of memory; closing connection");
  10557. break;
  10558. }
  10559. }
  10560. /* Copy the mask before we shift the queue and destroy it */
  10561. if (mask_len > 0) {
  10562. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10563. } else {
  10564. memset(mask, 0, sizeof(mask));
  10565. }
  10566. /* Read frame payload from the first message in the queue into
  10567. * data and advance the queue by moving the memory in place. */
  10568. DEBUG_ASSERT(body_len >= header_len);
  10569. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10570. mop = buf[0]; /* current mask and opcode */
  10571. /* Overflow case */
  10572. len = body_len - header_len;
  10573. memcpy(data, buf + header_len, len);
  10574. error = 0;
  10575. while ((uint64_t)len < data_len) {
  10576. n = pull_inner(NULL,
  10577. conn,
  10578. (char *)(data + len),
  10579. (int)(data_len - len),
  10580. timeout);
  10581. if (n <= -2) {
  10582. error = 1;
  10583. break;
  10584. } else if (n > 0) {
  10585. len += (size_t)n;
  10586. } else {
  10587. /* Timeout: should retry */
  10588. /* TODO: retry condition */
  10589. }
  10590. }
  10591. if (error) {
  10592. mg_cry_internal(
  10593. conn,
  10594. "%s",
  10595. "Websocket pull failed; closing connection");
  10596. if (data != mem) {
  10597. mg_free(data);
  10598. }
  10599. break;
  10600. }
  10601. conn->data_len = conn->request_len;
  10602. } else {
  10603. mop = buf[0]; /* current mask and opcode, overwritten by
  10604. * memmove() */
  10605. /* Length of the message being read at the front of the
  10606. * queue. Cast to 31 bit is OK, since we limited
  10607. * data_len before. */
  10608. len = (size_t)data_len + header_len;
  10609. /* Copy the data payload into the data pointer for the
  10610. * callback. Cast to 31 bit is OK, since we
  10611. * limited data_len */
  10612. memcpy(data, buf + header_len, (size_t)data_len);
  10613. /* Move the queue forward len bytes */
  10614. memmove(buf, buf + len, body_len - len);
  10615. /* Mark the queue as advanced */
  10616. conn->data_len -= (int)len;
  10617. }
  10618. /* Apply mask if necessary */
  10619. if (mask_len > 0) {
  10620. for (i = 0; i < (size_t)data_len; i++) {
  10621. data[i] ^= mask[i & 3];
  10622. }
  10623. }
  10624. exit_by_callback = 0;
  10625. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10626. /* filter PONG messages */
  10627. DEBUG_TRACE("PONG from %s:%u",
  10628. conn->request_info.remote_addr,
  10629. conn->request_info.remote_port);
  10630. /* No unanwered PINGs left */
  10631. ping_count = 0;
  10632. } else if (enable_ping_pong
  10633. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10634. /* reply PING messages */
  10635. DEBUG_TRACE("Reply PING from %s:%u",
  10636. conn->request_info.remote_addr,
  10637. conn->request_info.remote_port);
  10638. ret = mg_websocket_write(conn,
  10639. MG_WEBSOCKET_OPCODE_PONG,
  10640. (char *)data,
  10641. (size_t)data_len);
  10642. if (ret <= 0) {
  10643. /* Error: send failed */
  10644. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10645. break;
  10646. }
  10647. } else {
  10648. /* Exit the loop if callback signals to exit (server side),
  10649. * or "connection close" opcode received (client side). */
  10650. if ((ws_data_handler != NULL)
  10651. && !ws_data_handler(conn,
  10652. mop,
  10653. (char *)data,
  10654. (size_t)data_len,
  10655. callback_data)) {
  10656. exit_by_callback = 1;
  10657. }
  10658. }
  10659. /* It a buffer has been allocated, free it again */
  10660. if (data != mem) {
  10661. mg_free(data);
  10662. }
  10663. if (exit_by_callback) {
  10664. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10665. conn->request_info.remote_addr,
  10666. conn->request_info.remote_port);
  10667. break;
  10668. }
  10669. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10670. /* Opcode == 8, connection close */
  10671. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10672. conn->request_info.remote_addr,
  10673. conn->request_info.remote_port);
  10674. break;
  10675. }
  10676. /* Not breaking the loop, process next websocket frame. */
  10677. } else {
  10678. /* Read from the socket into the next available location in the
  10679. * message queue. */
  10680. n = pull_inner(NULL,
  10681. conn,
  10682. conn->buf + conn->data_len,
  10683. conn->buf_size - conn->data_len,
  10684. timeout);
  10685. if (n <= -2) {
  10686. /* Error, no bytes read */
  10687. DEBUG_TRACE("PULL from %s:%u failed",
  10688. conn->request_info.remote_addr,
  10689. conn->request_info.remote_port);
  10690. break;
  10691. }
  10692. if (n > 0) {
  10693. conn->data_len += n;
  10694. /* Reset open PING count */
  10695. ping_count = 0;
  10696. } else {
  10697. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10698. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10699. /* Stop sending PING */
  10700. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10701. "- closing connection",
  10702. ping_count,
  10703. conn->request_info.remote_addr,
  10704. conn->request_info.remote_port);
  10705. break;
  10706. }
  10707. if (enable_ping_pong) {
  10708. /* Send Websocket PING message */
  10709. DEBUG_TRACE("PING to %s:%u",
  10710. conn->request_info.remote_addr,
  10711. conn->request_info.remote_port);
  10712. ret = mg_websocket_write(conn,
  10713. MG_WEBSOCKET_OPCODE_PING,
  10714. NULL,
  10715. 0);
  10716. if (ret <= 0) {
  10717. /* Error: send failed */
  10718. DEBUG_TRACE("Send PING failed (%i)", ret);
  10719. break;
  10720. }
  10721. ping_count++;
  10722. }
  10723. }
  10724. /* Timeout: should retry */
  10725. /* TODO: get timeout def */
  10726. }
  10727. }
  10728. }
  10729. /* Leave data processing loop */
  10730. mg_set_thread_name("worker");
  10731. conn->in_websocket_handling = 0;
  10732. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10733. conn->request_info.remote_addr,
  10734. conn->request_info.remote_port);
  10735. }
  10736. static int
  10737. mg_websocket_write_exec(struct mg_connection *conn,
  10738. int opcode,
  10739. const char *data,
  10740. size_t dataLen,
  10741. uint32_t masking_key)
  10742. {
  10743. unsigned char header[14];
  10744. size_t headerLen;
  10745. int retval;
  10746. #if defined(GCC_DIAGNOSTIC)
  10747. /* Disable spurious conversion warning for GCC */
  10748. #pragma GCC diagnostic push
  10749. #pragma GCC diagnostic ignored "-Wconversion"
  10750. #endif
  10751. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10752. #if defined(GCC_DIAGNOSTIC)
  10753. #pragma GCC diagnostic pop
  10754. #endif
  10755. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10756. if (dataLen < 126) {
  10757. /* inline 7-bit length field */
  10758. header[1] = (unsigned char)dataLen;
  10759. headerLen = 2;
  10760. } else if (dataLen <= 0xFFFF) {
  10761. /* 16-bit length field */
  10762. uint16_t len = htons((uint16_t)dataLen);
  10763. header[1] = 126;
  10764. memcpy(header + 2, &len, 2);
  10765. headerLen = 4;
  10766. } else {
  10767. /* 64-bit length field */
  10768. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10769. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10770. header[1] = 127;
  10771. memcpy(header + 2, &len1, 4);
  10772. memcpy(header + 6, &len2, 4);
  10773. headerLen = 10;
  10774. }
  10775. if (masking_key) {
  10776. /* add mask */
  10777. header[1] |= 0x80;
  10778. memcpy(header + headerLen, &masking_key, 4);
  10779. headerLen += 4;
  10780. }
  10781. /* Note that POSIX/Winsock's send() is threadsafe
  10782. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10783. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10784. * push(), although that is only a problem if the packet is large or
  10785. * outgoing buffer is full). */
  10786. /* TODO: Check if this lock should be moved to user land.
  10787. * Currently the server sets this lock for websockets, but
  10788. * not for any other connection. It must be set for every
  10789. * conn read/written by more than one thread, no matter if
  10790. * it is a websocket or regular connection. */
  10791. (void)mg_lock_connection(conn);
  10792. retval = mg_write(conn, header, headerLen);
  10793. if (retval != (int)headerLen) {
  10794. /* Did not send complete header */
  10795. retval = -1;
  10796. } else {
  10797. if (dataLen > 0) {
  10798. retval = mg_write(conn, data, dataLen);
  10799. }
  10800. /* if dataLen == 0, the header length (2) is returned */
  10801. }
  10802. /* TODO: Remove this unlock as well, when lock is removed. */
  10803. mg_unlock_connection(conn);
  10804. return retval;
  10805. }
  10806. int
  10807. mg_websocket_write(struct mg_connection *conn,
  10808. int opcode,
  10809. const char *data,
  10810. size_t dataLen)
  10811. {
  10812. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10813. }
  10814. static void
  10815. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10816. {
  10817. size_t i = 0;
  10818. i = 0;
  10819. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10820. /* Convert in 32 bit words, if data is 4 byte aligned */
  10821. while (i < (in_len - 3)) {
  10822. *(uint32_t *)(void *)(out + i) =
  10823. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10824. i += 4;
  10825. }
  10826. }
  10827. if (i != in_len) {
  10828. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10829. while (i < in_len) {
  10830. *(uint8_t *)(void *)(out + i) =
  10831. *(uint8_t *)(void *)(in + i)
  10832. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10833. i++;
  10834. }
  10835. }
  10836. }
  10837. int
  10838. mg_websocket_client_write(struct mg_connection *conn,
  10839. int opcode,
  10840. const char *data,
  10841. size_t dataLen)
  10842. {
  10843. int retval = -1;
  10844. char *masked_data =
  10845. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10846. uint32_t masking_key = 0;
  10847. if (masked_data == NULL) {
  10848. /* Return -1 in an error case */
  10849. mg_cry_internal(conn,
  10850. "%s",
  10851. "Cannot allocate buffer for masked websocket response: "
  10852. "Out of memory");
  10853. return -1;
  10854. }
  10855. do {
  10856. /* Get a masking key - but not 0 */
  10857. masking_key = (uint32_t)get_random();
  10858. } while (masking_key == 0);
  10859. mask_data(data, dataLen, masking_key, masked_data);
  10860. retval = mg_websocket_write_exec(
  10861. conn, opcode, masked_data, dataLen, masking_key);
  10862. mg_free(masked_data);
  10863. return retval;
  10864. }
  10865. static void
  10866. handle_websocket_request(struct mg_connection *conn,
  10867. const char *path,
  10868. int is_callback_resource,
  10869. struct mg_websocket_subprotocols *subprotocols,
  10870. mg_websocket_connect_handler ws_connect_handler,
  10871. mg_websocket_ready_handler ws_ready_handler,
  10872. mg_websocket_data_handler ws_data_handler,
  10873. mg_websocket_close_handler ws_close_handler,
  10874. void *cbData)
  10875. {
  10876. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10877. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10878. ptrdiff_t lua_websock = 0;
  10879. #if !defined(USE_LUA)
  10880. (void)path;
  10881. #endif
  10882. /* Step 1: Check websocket protocol version. */
  10883. /* Step 1.1: Check Sec-WebSocket-Key. */
  10884. if (!websock_key) {
  10885. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10886. * requires a Sec-WebSocket-Key header.
  10887. */
  10888. /* It could be the hixie draft version
  10889. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10890. */
  10891. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10892. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10893. char key3[8];
  10894. if ((key1 != NULL) && (key2 != NULL)) {
  10895. /* This version uses 8 byte body data in a GET request */
  10896. conn->content_len = 8;
  10897. if (8 == mg_read(conn, key3, 8)) {
  10898. /* This is the hixie version */
  10899. mg_send_http_error(conn,
  10900. 426,
  10901. "%s",
  10902. "Protocol upgrade to RFC 6455 required");
  10903. return;
  10904. }
  10905. }
  10906. /* This is an unknown version */
  10907. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10908. return;
  10909. }
  10910. /* Step 1.2: Check websocket protocol version. */
  10911. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10912. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10913. /* Reject wrong versions */
  10914. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10915. return;
  10916. }
  10917. /* Step 1.3: Could check for "Host", but we do not really nead this
  10918. * value for anything, so just ignore it. */
  10919. /* Step 2: If a callback is responsible, call it. */
  10920. if (is_callback_resource) {
  10921. /* Step 2.1 check and select subprotocol */
  10922. const char *protocols[64]; // max 64 headers
  10923. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10924. "Sec-WebSocket-Protocol",
  10925. protocols,
  10926. 64);
  10927. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10928. int cnt = 0;
  10929. int idx;
  10930. unsigned long len;
  10931. const char *sep, *curSubProtocol,
  10932. *acceptedWebSocketSubprotocol = NULL;
  10933. /* look for matching subprotocol */
  10934. do {
  10935. const char *protocol = protocols[cnt];
  10936. do {
  10937. sep = strchr(protocol, ',');
  10938. curSubProtocol = protocol;
  10939. len = sep ? (unsigned long)(sep - protocol)
  10940. : (unsigned long)strlen(protocol);
  10941. while (sep && isspace((unsigned char)*++sep))
  10942. ; // ignore leading whitespaces
  10943. protocol = sep;
  10944. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10945. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10946. && (strncmp(curSubProtocol,
  10947. subprotocols->subprotocols[idx],
  10948. len)
  10949. == 0)) {
  10950. acceptedWebSocketSubprotocol =
  10951. subprotocols->subprotocols[idx];
  10952. break;
  10953. }
  10954. }
  10955. } while (sep && !acceptedWebSocketSubprotocol);
  10956. } while (++cnt < nbSubprotocolHeader
  10957. && !acceptedWebSocketSubprotocol);
  10958. conn->request_info.acceptedWebSocketSubprotocol =
  10959. acceptedWebSocketSubprotocol;
  10960. } else if (nbSubprotocolHeader > 0) {
  10961. /* keep legacy behavior */
  10962. const char *protocol = protocols[0];
  10963. /* The protocol is a comma separated list of names. */
  10964. /* The server must only return one value from this list. */
  10965. /* First check if it is a list or just a single value. */
  10966. const char *sep = strrchr(protocol, ',');
  10967. if (sep == NULL) {
  10968. /* Just a single protocol -> accept it. */
  10969. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10970. } else {
  10971. /* Multiple protocols -> accept the last one. */
  10972. /* This is just a quick fix if the client offers multiple
  10973. * protocols. The handler should have a list of accepted
  10974. * protocols on his own
  10975. * and use it to select one protocol among those the client
  10976. * has
  10977. * offered.
  10978. */
  10979. while (isspace((unsigned char)*++sep)) {
  10980. ; /* ignore leading whitespaces */
  10981. }
  10982. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10983. }
  10984. }
  10985. if ((ws_connect_handler != NULL)
  10986. && (ws_connect_handler(conn, cbData) != 0)) {
  10987. /* C callback has returned non-zero, do not proceed with
  10988. * handshake.
  10989. */
  10990. /* Note that C callbacks are no longer called when Lua is
  10991. * responsible, so C can no longer filter callbacks for Lua. */
  10992. return;
  10993. }
  10994. }
  10995. #if defined(USE_LUA)
  10996. /* Step 3: No callback. Check if Lua is responsible. */
  10997. else {
  10998. /* Step 3.1: Check if Lua is responsible. */
  10999. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  11000. lua_websock = match_prefix(
  11001. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  11002. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11003. path);
  11004. }
  11005. if (lua_websock) {
  11006. /* Step 3.2: Lua is responsible: call it. */
  11007. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11008. if (!conn->lua_websocket_state) {
  11009. /* Lua rejected the new client */
  11010. return;
  11011. }
  11012. }
  11013. }
  11014. #endif
  11015. /* Step 4: Check if there is a responsible websocket handler. */
  11016. if (!is_callback_resource && !lua_websock) {
  11017. /* There is no callback, and Lua is not responsible either. */
  11018. /* Reply with a 404 Not Found. We are still at a standard
  11019. * HTTP request here, before the websocket handshake, so
  11020. * we can still send standard HTTP error replies. */
  11021. mg_send_http_error(conn, 404, "%s", "Not found");
  11022. return;
  11023. }
  11024. /* Step 5: The websocket connection has been accepted */
  11025. if (!send_websocket_handshake(conn, websock_key)) {
  11026. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11027. return;
  11028. }
  11029. /* Step 6: Call the ready handler */
  11030. if (is_callback_resource) {
  11031. if (ws_ready_handler != NULL) {
  11032. ws_ready_handler(conn, cbData);
  11033. }
  11034. #if defined(USE_LUA)
  11035. } else if (lua_websock) {
  11036. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11037. /* the ready handler returned false */
  11038. return;
  11039. }
  11040. #endif
  11041. }
  11042. /* Step 7: Enter the read loop */
  11043. if (is_callback_resource) {
  11044. read_websocket(conn, ws_data_handler, cbData);
  11045. #if defined(USE_LUA)
  11046. } else if (lua_websock) {
  11047. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11048. #endif
  11049. }
  11050. /* Step 8: Call the close handler */
  11051. if (ws_close_handler) {
  11052. ws_close_handler(conn, cbData);
  11053. }
  11054. }
  11055. static int
  11056. is_websocket_protocol(const struct mg_connection *conn)
  11057. {
  11058. const char *upgrade, *connection;
  11059. /* A websocket protocoll has the following HTTP headers:
  11060. *
  11061. * Connection: Upgrade
  11062. * Upgrade: Websocket
  11063. */
  11064. upgrade = mg_get_header(conn, "Upgrade");
  11065. if (upgrade == NULL) {
  11066. return 0; /* fail early, don't waste time checking other header
  11067. * fields
  11068. */
  11069. }
  11070. DEBUG_TRACE("Upgrade: %s", upgrade);
  11071. if (!mg_strcasestr(upgrade, "websocket")) {
  11072. return 0;
  11073. }
  11074. connection = mg_get_header(conn, "Connection");
  11075. if (connection == NULL) {
  11076. return 0;
  11077. }
  11078. if (!mg_strcasestr(connection, "upgrade")) {
  11079. return 0;
  11080. }
  11081. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11082. * "Sec-WebSocket-Version" are also required.
  11083. * Don't check them here, since even an unsupported websocket protocol
  11084. * request still IS a websocket request (in contrast to a standard HTTP
  11085. * request). It will fail later in handle_websocket_request.
  11086. */
  11087. return 1;
  11088. }
  11089. #endif /* !USE_WEBSOCKET */
  11090. static int
  11091. isbyte(int n)
  11092. {
  11093. return (n >= 0) && (n <= 255);
  11094. }
  11095. static int
  11096. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11097. {
  11098. int n, a, b, c, d, slash = 32, len = 0;
  11099. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11100. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11101. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11102. && (slash < 33)) {
  11103. len = n;
  11104. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11105. | (uint32_t)d;
  11106. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11107. }
  11108. return len;
  11109. }
  11110. static int
  11111. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11112. {
  11113. int throttle = 0;
  11114. struct vec vec, val;
  11115. uint32_t net, mask;
  11116. char mult;
  11117. double v;
  11118. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11119. mult = ',';
  11120. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11121. || (v < 0)
  11122. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11123. && (mult != ','))) {
  11124. continue;
  11125. }
  11126. v *= (lowercase(&mult) == 'k')
  11127. ? 1024
  11128. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11129. if (vec.len == 1 && vec.ptr[0] == '*') {
  11130. throttle = (int)v;
  11131. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11132. if ((remote_ip & mask) == net) {
  11133. throttle = (int)v;
  11134. }
  11135. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11136. throttle = (int)v;
  11137. }
  11138. }
  11139. return throttle;
  11140. }
  11141. static uint32_t
  11142. get_remote_ip(const struct mg_connection *conn)
  11143. {
  11144. if (!conn) {
  11145. return 0;
  11146. }
  11147. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11148. }
  11149. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11150. #include "handle_form.inl"
  11151. #if defined(MG_LEGACY_INTERFACE)
  11152. /* Implement the deprecated mg_upload function by calling the new
  11153. * mg_handle_form_request function. While mg_upload could only handle
  11154. * HTML forms sent as POST request in multipart/form-data format
  11155. * containing only file input elements, mg_handle_form_request can
  11156. * handle all form input elements and all standard request methods. */
  11157. struct mg_upload_user_data {
  11158. struct mg_connection *conn;
  11159. const char *destination_dir;
  11160. int num_uploaded_files;
  11161. };
  11162. /* Helper function for deprecated mg_upload. */
  11163. static int
  11164. mg_upload_field_found(const char *key,
  11165. const char *filename,
  11166. char *path,
  11167. size_t pathlen,
  11168. void *user_data)
  11169. {
  11170. int truncated = 0;
  11171. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11172. (void)key;
  11173. if (!filename) {
  11174. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11175. return FORM_FIELD_STORAGE_ABORT;
  11176. }
  11177. mg_snprintf(fud->conn,
  11178. &truncated,
  11179. path,
  11180. pathlen - 1,
  11181. "%s/%s",
  11182. fud->destination_dir,
  11183. filename);
  11184. if (truncated) {
  11185. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11186. return FORM_FIELD_STORAGE_ABORT;
  11187. }
  11188. return FORM_FIELD_STORAGE_STORE;
  11189. }
  11190. /* Helper function for deprecated mg_upload. */
  11191. static int
  11192. mg_upload_field_get(const char *key,
  11193. const char *value,
  11194. size_t value_size,
  11195. void *user_data)
  11196. {
  11197. /* Function should never be called */
  11198. (void)key;
  11199. (void)value;
  11200. (void)value_size;
  11201. (void)user_data;
  11202. return 0;
  11203. }
  11204. /* Helper function for deprecated mg_upload. */
  11205. static int
  11206. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11207. {
  11208. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11209. (void)file_size;
  11210. fud->num_uploaded_files++;
  11211. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11212. return 0;
  11213. }
  11214. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11215. int
  11216. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11217. {
  11218. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11219. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11220. mg_upload_field_get,
  11221. mg_upload_field_stored,
  11222. 0};
  11223. int ret;
  11224. fdh.user_data = (void *)&fud;
  11225. ret = mg_handle_form_request(conn, &fdh);
  11226. if (ret < 0) {
  11227. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11228. }
  11229. return fud.num_uploaded_files;
  11230. }
  11231. #endif
  11232. static int
  11233. get_first_ssl_listener_index(const struct mg_context *ctx)
  11234. {
  11235. unsigned int i;
  11236. int idx = -1;
  11237. if (ctx) {
  11238. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11239. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11240. }
  11241. }
  11242. return idx;
  11243. }
  11244. /* Return host (without port) */
  11245. /* Use mg_free to free the result */
  11246. static const char *
  11247. alloc_get_host(struct mg_connection *conn)
  11248. {
  11249. char buf[1025];
  11250. size_t buflen = sizeof(buf);
  11251. const char *host_header = get_header(conn->request_info.http_headers,
  11252. conn->request_info.num_headers,
  11253. "Host");
  11254. char *host;
  11255. if (host_header != NULL) {
  11256. char *pos;
  11257. /* Create a local copy of the "Host" header, since it might be
  11258. * modified here. */
  11259. mg_strlcpy(buf, host_header, buflen);
  11260. buf[buflen - 1] = '\0';
  11261. host = buf;
  11262. while (isspace((unsigned char)*host)) {
  11263. host++;
  11264. }
  11265. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11266. * is found. */
  11267. if (*host == '[') {
  11268. pos = strchr(host, ']');
  11269. if (!pos) {
  11270. /* Malformed hostname starts with '[', but no ']' found */
  11271. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11272. return NULL;
  11273. }
  11274. /* terminate after ']' */
  11275. pos[1] = 0;
  11276. } else {
  11277. /* Otherwise, a ':' separates hostname and port number */
  11278. pos = strchr(host, ':');
  11279. if (pos != NULL) {
  11280. *pos = '\0';
  11281. }
  11282. }
  11283. if (conn->ssl) {
  11284. /* This is a HTTPS connection, maybe we have a hostname
  11285. * from SNI (set in ssl_servername_callback). */
  11286. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11287. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11288. /* We are not using the default domain */
  11289. if (mg_strcasecmp(host, sslhost)) {
  11290. /* Mismatch between SNI domain and HTTP domain */
  11291. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11292. sslhost,
  11293. host);
  11294. return NULL;
  11295. }
  11296. }
  11297. DEBUG_TRACE("HTTPS Host: %s", host);
  11298. } else {
  11299. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11300. while (dom) {
  11301. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11302. /* Found matching domain */
  11303. DEBUG_TRACE("HTTP domain %s found",
  11304. dom->config[AUTHENTICATION_DOMAIN]);
  11305. /* TODO: Check if this is a HTTP or HTTPS domain */
  11306. conn->dom_ctx = dom;
  11307. break;
  11308. }
  11309. dom = dom->next;
  11310. }
  11311. DEBUG_TRACE("HTTP Host: %s", host);
  11312. }
  11313. } else {
  11314. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11315. host = buf;
  11316. DEBUG_TRACE("IP: %s", host);
  11317. }
  11318. return mg_strdup_ctx(host, conn->phys_ctx);
  11319. }
  11320. static void
  11321. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11322. {
  11323. char target_url[MG_BUF_LEN];
  11324. int truncated = 0;
  11325. conn->must_close = 1;
  11326. /* Send host, port, uri and (if it exists) ?query_string */
  11327. if (conn->host) {
  11328. /* Use "308 Permanent Redirect" */
  11329. int redirect_code = 308;
  11330. /* Create target URL */
  11331. mg_snprintf(
  11332. conn,
  11333. &truncated,
  11334. target_url,
  11335. sizeof(target_url),
  11336. "https://%s:%d%s%s%s",
  11337. conn->host,
  11338. #if defined(USE_IPV6)
  11339. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11340. == AF_INET6)
  11341. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11342. .lsa.sin6.sin6_port)
  11343. :
  11344. #endif
  11345. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11346. .lsa.sin.sin_port),
  11347. conn->request_info.local_uri,
  11348. (conn->request_info.query_string == NULL) ? "" : "?",
  11349. (conn->request_info.query_string == NULL)
  11350. ? ""
  11351. : conn->request_info.query_string);
  11352. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11353. * is used as buffer size) */
  11354. if (truncated) {
  11355. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11356. return;
  11357. }
  11358. /* Use redirect helper function */
  11359. mg_send_http_redirect(conn, target_url, redirect_code);
  11360. }
  11361. }
  11362. static void
  11363. handler_info_acquire(struct mg_handler_info *handler_info)
  11364. {
  11365. pthread_mutex_lock(&handler_info->refcount_mutex);
  11366. handler_info->refcount++;
  11367. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11368. }
  11369. static void
  11370. handler_info_release(struct mg_handler_info *handler_info)
  11371. {
  11372. pthread_mutex_lock(&handler_info->refcount_mutex);
  11373. handler_info->refcount--;
  11374. pthread_cond_signal(&handler_info->refcount_cond);
  11375. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11376. }
  11377. static void
  11378. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11379. {
  11380. pthread_mutex_lock(&handler_info->refcount_mutex);
  11381. while (handler_info->refcount) {
  11382. pthread_cond_wait(&handler_info->refcount_cond,
  11383. &handler_info->refcount_mutex);
  11384. }
  11385. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11386. }
  11387. static void
  11388. mg_set_handler_type(struct mg_context *phys_ctx,
  11389. struct mg_domain_context *dom_ctx,
  11390. const char *uri,
  11391. int handler_type,
  11392. int is_delete_request,
  11393. mg_request_handler handler,
  11394. struct mg_websocket_subprotocols *subprotocols,
  11395. mg_websocket_connect_handler connect_handler,
  11396. mg_websocket_ready_handler ready_handler,
  11397. mg_websocket_data_handler data_handler,
  11398. mg_websocket_close_handler close_handler,
  11399. mg_authorization_handler auth_handler,
  11400. void *cbdata)
  11401. {
  11402. struct mg_handler_info *tmp_rh, **lastref;
  11403. size_t urilen = strlen(uri);
  11404. if (handler_type == WEBSOCKET_HANDLER) {
  11405. DEBUG_ASSERT(handler == NULL);
  11406. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11407. || ready_handler != NULL || data_handler != NULL
  11408. || close_handler != NULL);
  11409. DEBUG_ASSERT(auth_handler == NULL);
  11410. if (handler != NULL) {
  11411. return;
  11412. }
  11413. if (!is_delete_request && (connect_handler == NULL)
  11414. && (ready_handler == NULL) && (data_handler == NULL)
  11415. && (close_handler == NULL)) {
  11416. return;
  11417. }
  11418. if (auth_handler != NULL) {
  11419. return;
  11420. }
  11421. } else if (handler_type == REQUEST_HANDLER) {
  11422. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11423. && data_handler == NULL && close_handler == NULL);
  11424. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11425. DEBUG_ASSERT(auth_handler == NULL);
  11426. if ((connect_handler != NULL) || (ready_handler != NULL)
  11427. || (data_handler != NULL) || (close_handler != NULL)) {
  11428. return;
  11429. }
  11430. if (!is_delete_request && (handler == NULL)) {
  11431. return;
  11432. }
  11433. if (auth_handler != NULL) {
  11434. return;
  11435. }
  11436. } else { /* AUTH_HANDLER */
  11437. DEBUG_ASSERT(handler == NULL);
  11438. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11439. && data_handler == NULL && close_handler == NULL);
  11440. DEBUG_ASSERT(auth_handler != NULL);
  11441. if (handler != NULL) {
  11442. return;
  11443. }
  11444. if ((connect_handler != NULL) || (ready_handler != NULL)
  11445. || (data_handler != NULL) || (close_handler != NULL)) {
  11446. return;
  11447. }
  11448. if (!is_delete_request && (auth_handler == NULL)) {
  11449. return;
  11450. }
  11451. }
  11452. if (!phys_ctx || !dom_ctx) {
  11453. return;
  11454. }
  11455. mg_lock_context(phys_ctx);
  11456. /* first try to find an existing handler */
  11457. lastref = &(dom_ctx->handlers);
  11458. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11459. if (tmp_rh->handler_type == handler_type) {
  11460. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11461. if (!is_delete_request) {
  11462. /* update existing handler */
  11463. if (handler_type == REQUEST_HANDLER) {
  11464. /* Wait for end of use before updating */
  11465. handler_info_wait_unused(tmp_rh);
  11466. /* Ok, the handler is no more use -> Update it */
  11467. tmp_rh->handler = handler;
  11468. } else if (handler_type == WEBSOCKET_HANDLER) {
  11469. tmp_rh->subprotocols = subprotocols;
  11470. tmp_rh->connect_handler = connect_handler;
  11471. tmp_rh->ready_handler = ready_handler;
  11472. tmp_rh->data_handler = data_handler;
  11473. tmp_rh->close_handler = close_handler;
  11474. } else { /* AUTH_HANDLER */
  11475. tmp_rh->auth_handler = auth_handler;
  11476. }
  11477. tmp_rh->cbdata = cbdata;
  11478. } else {
  11479. /* remove existing handler */
  11480. if (handler_type == REQUEST_HANDLER) {
  11481. /* Wait for end of use before removing */
  11482. handler_info_wait_unused(tmp_rh);
  11483. /* Ok, the handler is no more used -> Destroy resources
  11484. */
  11485. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11486. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11487. }
  11488. *lastref = tmp_rh->next;
  11489. mg_free(tmp_rh->uri);
  11490. mg_free(tmp_rh);
  11491. }
  11492. mg_unlock_context(phys_ctx);
  11493. return;
  11494. }
  11495. }
  11496. lastref = &(tmp_rh->next);
  11497. }
  11498. if (is_delete_request) {
  11499. /* no handler to set, this was a remove request to a non-existing
  11500. * handler */
  11501. mg_unlock_context(phys_ctx);
  11502. return;
  11503. }
  11504. tmp_rh =
  11505. (struct mg_handler_info *)mg_calloc_ctx(1,
  11506. sizeof(struct mg_handler_info),
  11507. phys_ctx);
  11508. if (tmp_rh == NULL) {
  11509. mg_unlock_context(phys_ctx);
  11510. mg_cry_ctx_internal(phys_ctx,
  11511. "%s",
  11512. "Cannot create new request handler struct, OOM");
  11513. return;
  11514. }
  11515. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11516. if (!tmp_rh->uri) {
  11517. mg_unlock_context(phys_ctx);
  11518. mg_free(tmp_rh);
  11519. mg_cry_ctx_internal(phys_ctx,
  11520. "%s",
  11521. "Cannot create new request handler struct, OOM");
  11522. return;
  11523. }
  11524. tmp_rh->uri_len = urilen;
  11525. if (handler_type == REQUEST_HANDLER) {
  11526. /* Init refcount mutex and condition */
  11527. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11528. mg_unlock_context(phys_ctx);
  11529. mg_free(tmp_rh);
  11530. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount mutex");
  11531. return;
  11532. }
  11533. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11534. mg_unlock_context(phys_ctx);
  11535. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11536. mg_free(tmp_rh);
  11537. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount cond");
  11538. return;
  11539. }
  11540. tmp_rh->refcount = 0;
  11541. tmp_rh->handler = handler;
  11542. } else if (handler_type == WEBSOCKET_HANDLER) {
  11543. tmp_rh->subprotocols = subprotocols;
  11544. tmp_rh->connect_handler = connect_handler;
  11545. tmp_rh->ready_handler = ready_handler;
  11546. tmp_rh->data_handler = data_handler;
  11547. tmp_rh->close_handler = close_handler;
  11548. } else { /* AUTH_HANDLER */
  11549. tmp_rh->auth_handler = auth_handler;
  11550. }
  11551. tmp_rh->cbdata = cbdata;
  11552. tmp_rh->handler_type = handler_type;
  11553. tmp_rh->next = NULL;
  11554. *lastref = tmp_rh;
  11555. mg_unlock_context(phys_ctx);
  11556. }
  11557. void
  11558. mg_set_request_handler(struct mg_context *ctx,
  11559. const char *uri,
  11560. mg_request_handler handler,
  11561. void *cbdata)
  11562. {
  11563. mg_set_handler_type(ctx,
  11564. &(ctx->dd),
  11565. uri,
  11566. REQUEST_HANDLER,
  11567. handler == NULL,
  11568. handler,
  11569. NULL,
  11570. NULL,
  11571. NULL,
  11572. NULL,
  11573. NULL,
  11574. NULL,
  11575. cbdata);
  11576. }
  11577. void
  11578. mg_set_websocket_handler(struct mg_context *ctx,
  11579. const char *uri,
  11580. mg_websocket_connect_handler connect_handler,
  11581. mg_websocket_ready_handler ready_handler,
  11582. mg_websocket_data_handler data_handler,
  11583. mg_websocket_close_handler close_handler,
  11584. void *cbdata)
  11585. {
  11586. mg_set_websocket_handler_with_subprotocols(ctx,
  11587. uri,
  11588. NULL,
  11589. connect_handler,
  11590. ready_handler,
  11591. data_handler,
  11592. close_handler,
  11593. cbdata);
  11594. }
  11595. void
  11596. mg_set_websocket_handler_with_subprotocols(
  11597. struct mg_context *ctx,
  11598. const char *uri,
  11599. struct mg_websocket_subprotocols *subprotocols,
  11600. mg_websocket_connect_handler connect_handler,
  11601. mg_websocket_ready_handler ready_handler,
  11602. mg_websocket_data_handler data_handler,
  11603. mg_websocket_close_handler close_handler,
  11604. void *cbdata)
  11605. {
  11606. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11607. && (data_handler == NULL)
  11608. && (close_handler == NULL);
  11609. mg_set_handler_type(ctx,
  11610. &(ctx->dd),
  11611. uri,
  11612. WEBSOCKET_HANDLER,
  11613. is_delete_request,
  11614. NULL,
  11615. subprotocols,
  11616. connect_handler,
  11617. ready_handler,
  11618. data_handler,
  11619. close_handler,
  11620. NULL,
  11621. cbdata);
  11622. }
  11623. void
  11624. mg_set_auth_handler(struct mg_context *ctx,
  11625. const char *uri,
  11626. mg_authorization_handler handler,
  11627. void *cbdata)
  11628. {
  11629. mg_set_handler_type(ctx,
  11630. &(ctx->dd),
  11631. uri,
  11632. AUTH_HANDLER,
  11633. handler == NULL,
  11634. NULL,
  11635. NULL,
  11636. NULL,
  11637. NULL,
  11638. NULL,
  11639. NULL,
  11640. handler,
  11641. cbdata);
  11642. }
  11643. static int
  11644. get_request_handler(struct mg_connection *conn,
  11645. int handler_type,
  11646. mg_request_handler *handler,
  11647. struct mg_websocket_subprotocols **subprotocols,
  11648. mg_websocket_connect_handler *connect_handler,
  11649. mg_websocket_ready_handler *ready_handler,
  11650. mg_websocket_data_handler *data_handler,
  11651. mg_websocket_close_handler *close_handler,
  11652. mg_authorization_handler *auth_handler,
  11653. void **cbdata,
  11654. struct mg_handler_info **handler_info)
  11655. {
  11656. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11657. if (request_info) {
  11658. const char *uri = request_info->local_uri;
  11659. size_t urilen = strlen(uri);
  11660. struct mg_handler_info *tmp_rh;
  11661. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11662. return 0;
  11663. }
  11664. mg_lock_context(conn->phys_ctx);
  11665. /* first try for an exact match */
  11666. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11667. tmp_rh = tmp_rh->next) {
  11668. if (tmp_rh->handler_type == handler_type) {
  11669. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11670. if (handler_type == WEBSOCKET_HANDLER) {
  11671. *subprotocols = tmp_rh->subprotocols;
  11672. *connect_handler = tmp_rh->connect_handler;
  11673. *ready_handler = tmp_rh->ready_handler;
  11674. *data_handler = tmp_rh->data_handler;
  11675. *close_handler = tmp_rh->close_handler;
  11676. } else if (handler_type == REQUEST_HANDLER) {
  11677. *handler = tmp_rh->handler;
  11678. /* Acquire handler and give it back */
  11679. handler_info_acquire(tmp_rh);
  11680. *handler_info = tmp_rh;
  11681. } else { /* AUTH_HANDLER */
  11682. *auth_handler = tmp_rh->auth_handler;
  11683. }
  11684. *cbdata = tmp_rh->cbdata;
  11685. mg_unlock_context(conn->phys_ctx);
  11686. return 1;
  11687. }
  11688. }
  11689. }
  11690. /* next try for a partial match, we will accept uri/something */
  11691. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11692. tmp_rh = tmp_rh->next) {
  11693. if (tmp_rh->handler_type == handler_type) {
  11694. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11695. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11696. if (handler_type == WEBSOCKET_HANDLER) {
  11697. *subprotocols = tmp_rh->subprotocols;
  11698. *connect_handler = tmp_rh->connect_handler;
  11699. *ready_handler = tmp_rh->ready_handler;
  11700. *data_handler = tmp_rh->data_handler;
  11701. *close_handler = tmp_rh->close_handler;
  11702. } else if (handler_type == REQUEST_HANDLER) {
  11703. *handler = tmp_rh->handler;
  11704. /* Acquire handler and give it back */
  11705. handler_info_acquire(tmp_rh);
  11706. *handler_info = tmp_rh;
  11707. } else { /* AUTH_HANDLER */
  11708. *auth_handler = tmp_rh->auth_handler;
  11709. }
  11710. *cbdata = tmp_rh->cbdata;
  11711. mg_unlock_context(conn->phys_ctx);
  11712. return 1;
  11713. }
  11714. }
  11715. }
  11716. /* finally try for pattern match */
  11717. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11718. tmp_rh = tmp_rh->next) {
  11719. if (tmp_rh->handler_type == handler_type) {
  11720. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11721. if (handler_type == WEBSOCKET_HANDLER) {
  11722. *subprotocols = tmp_rh->subprotocols;
  11723. *connect_handler = tmp_rh->connect_handler;
  11724. *ready_handler = tmp_rh->ready_handler;
  11725. *data_handler = tmp_rh->data_handler;
  11726. *close_handler = tmp_rh->close_handler;
  11727. } else if (handler_type == REQUEST_HANDLER) {
  11728. *handler = tmp_rh->handler;
  11729. /* Acquire handler and give it back */
  11730. handler_info_acquire(tmp_rh);
  11731. *handler_info = tmp_rh;
  11732. } else { /* AUTH_HANDLER */
  11733. *auth_handler = tmp_rh->auth_handler;
  11734. }
  11735. *cbdata = tmp_rh->cbdata;
  11736. mg_unlock_context(conn->phys_ctx);
  11737. return 1;
  11738. }
  11739. }
  11740. }
  11741. mg_unlock_context(conn->phys_ctx);
  11742. }
  11743. return 0; /* none found */
  11744. }
  11745. /* Check if the script file is in a path, allowed for script files.
  11746. * This can be used if uploading files is possible not only for the server
  11747. * admin, and the upload mechanism does not check the file extension.
  11748. */
  11749. static int
  11750. is_in_script_path(const struct mg_connection *conn, const char *path)
  11751. {
  11752. /* TODO (Feature): Add config value for allowed script path.
  11753. * Default: All allowed. */
  11754. (void)conn;
  11755. (void)path;
  11756. return 1;
  11757. }
  11758. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11759. static int
  11760. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11761. void *cbdata)
  11762. {
  11763. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11764. if (pcallbacks->websocket_connect) {
  11765. return pcallbacks->websocket_connect(conn);
  11766. }
  11767. /* No handler set - assume "OK" */
  11768. return 0;
  11769. }
  11770. static void
  11771. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11772. {
  11773. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11774. if (pcallbacks->websocket_ready) {
  11775. pcallbacks->websocket_ready(conn);
  11776. }
  11777. }
  11778. static int
  11779. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11780. int bits,
  11781. char *data,
  11782. size_t len,
  11783. void *cbdata)
  11784. {
  11785. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11786. if (pcallbacks->websocket_data) {
  11787. return pcallbacks->websocket_data(conn, bits, data, len);
  11788. }
  11789. /* No handler set - assume "OK" */
  11790. return 1;
  11791. }
  11792. #endif
  11793. /* This is the heart of the Civetweb's logic.
  11794. * This function is called when the request is read, parsed and validated,
  11795. * and Civetweb must decide what action to take: serve a file, or
  11796. * a directory, or call embedded function, etcetera. */
  11797. static void
  11798. handle_request(struct mg_connection *conn)
  11799. {
  11800. struct mg_request_info *ri = &conn->request_info;
  11801. char path[PATH_MAX];
  11802. int uri_len, ssl_index;
  11803. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11804. is_put_or_delete_request = 0, is_callback_resource = 0;
  11805. int i;
  11806. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11807. mg_request_handler callback_handler = NULL;
  11808. struct mg_handler_info *handler_info = NULL;
  11809. struct mg_websocket_subprotocols *subprotocols;
  11810. mg_websocket_connect_handler ws_connect_handler = NULL;
  11811. mg_websocket_ready_handler ws_ready_handler = NULL;
  11812. mg_websocket_data_handler ws_data_handler = NULL;
  11813. mg_websocket_close_handler ws_close_handler = NULL;
  11814. void *callback_data = NULL;
  11815. mg_authorization_handler auth_handler = NULL;
  11816. void *auth_callback_data = NULL;
  11817. int handler_type;
  11818. time_t curtime = time(NULL);
  11819. char date[64];
  11820. path[0] = 0;
  11821. /* 1. get the request url */
  11822. /* 1.1. split into url and query string */
  11823. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11824. != NULL) {
  11825. *((char *)conn->request_info.query_string++) = '\0';
  11826. }
  11827. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11828. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11829. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11830. if (ssl_index >= 0) {
  11831. redirect_to_https_port(conn, ssl_index);
  11832. } else {
  11833. /* A http to https forward port has been specified,
  11834. * but no https port to forward to. */
  11835. mg_send_http_error(conn,
  11836. 503,
  11837. "%s",
  11838. "Error: SSL forward not configured properly");
  11839. mg_cry_internal(conn,
  11840. "%s",
  11841. "Can not redirect to SSL, no SSL port available");
  11842. }
  11843. return;
  11844. }
  11845. uri_len = (int)strlen(ri->local_uri);
  11846. /* 1.3. decode url (if config says so) */
  11847. if (should_decode_url(conn)) {
  11848. mg_url_decode(
  11849. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11850. }
  11851. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11852. * not possible */
  11853. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11854. /* step 1. completed, the url is known now */
  11855. uri_len = (int)strlen(ri->local_uri);
  11856. DEBUG_TRACE("URL: %s", ri->local_uri);
  11857. /* 2. if this ip has limited speed, set it for this connection */
  11858. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11859. get_remote_ip(conn),
  11860. ri->local_uri);
  11861. /* 3. call a "handle everything" callback, if registered */
  11862. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11863. /* Note that since V1.7 the "begin_request" function is called
  11864. * before an authorization check. If an authorization check is
  11865. * required, use a request_handler instead. */
  11866. i = conn->phys_ctx->callbacks.begin_request(conn);
  11867. if (i > 0) {
  11868. /* callback already processed the request. Store the
  11869. return value as a status code for the access log. */
  11870. conn->status_code = i;
  11871. discard_unread_request_data(conn);
  11872. return;
  11873. } else if (i == 0) {
  11874. /* civetweb should process the request */
  11875. } else {
  11876. /* unspecified - may change with the next version */
  11877. return;
  11878. }
  11879. }
  11880. /* request not yet handled by a handler or redirect, so the request
  11881. * is processed here */
  11882. /* 4. Check for CORS preflight requests and handle them (if configured).
  11883. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11884. */
  11885. if (!strcmp(ri->request_method, "OPTIONS")) {
  11886. /* Send a response to CORS preflights only if
  11887. * access_control_allow_methods is not NULL and not an empty string.
  11888. * In this case, scripts can still handle CORS. */
  11889. const char *cors_meth_cfg =
  11890. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11891. const char *cors_orig_cfg =
  11892. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11893. const char *cors_origin =
  11894. get_header(ri->http_headers, ri->num_headers, "Origin");
  11895. const char *cors_acrm = get_header(ri->http_headers,
  11896. ri->num_headers,
  11897. "Access-Control-Request-Method");
  11898. /* Todo: check if cors_origin is in cors_orig_cfg.
  11899. * Or, let the client check this. */
  11900. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11901. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11902. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11903. /* This is a valid CORS preflight, and the server is configured
  11904. * to
  11905. * handle it automatically. */
  11906. const char *cors_acrh =
  11907. get_header(ri->http_headers,
  11908. ri->num_headers,
  11909. "Access-Control-Request-Headers");
  11910. gmt_time_string(date, sizeof(date), &curtime);
  11911. mg_printf(conn,
  11912. "HTTP/1.1 200 OK\r\n"
  11913. "Date: %s\r\n"
  11914. "Access-Control-Allow-Origin: %s\r\n"
  11915. "Access-Control-Allow-Methods: %s\r\n"
  11916. "Content-Length: 0\r\n"
  11917. "Connection: %s\r\n",
  11918. date,
  11919. cors_orig_cfg,
  11920. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11921. suggest_connection_header(conn));
  11922. if (cors_acrh != NULL) {
  11923. /* CORS request is asking for additional headers */
  11924. const char *cors_hdr_cfg =
  11925. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11926. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11927. /* Allow only if access_control_allow_headers is
  11928. * not NULL and not an empty string. If this
  11929. * configuration is set to *, allow everything.
  11930. * Otherwise this configuration must be a list
  11931. * of allowed HTTP header names. */
  11932. mg_printf(conn,
  11933. "Access-Control-Allow-Headers: %s\r\n",
  11934. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11935. : cors_hdr_cfg));
  11936. }
  11937. }
  11938. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11939. mg_printf(conn, "\r\n");
  11940. return;
  11941. }
  11942. }
  11943. /* 5. interpret the url to find out how the request must be handled
  11944. */
  11945. /* 5.1. first test, if the request targets the regular http(s)://
  11946. * protocol namespace or the websocket ws(s):// protocol namespace.
  11947. */
  11948. is_websocket_request = is_websocket_protocol(conn);
  11949. #if defined(USE_WEBSOCKET)
  11950. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11951. #else
  11952. handler_type = REQUEST_HANDLER;
  11953. #endif /* defined(USE_WEBSOCKET) */
  11954. /* 5.2. check if the request will be handled by a callback */
  11955. if (get_request_handler(conn,
  11956. handler_type,
  11957. &callback_handler,
  11958. &subprotocols,
  11959. &ws_connect_handler,
  11960. &ws_ready_handler,
  11961. &ws_data_handler,
  11962. &ws_close_handler,
  11963. NULL,
  11964. &callback_data,
  11965. &handler_info)) {
  11966. /* 5.2.1. A callback will handle this request. All requests
  11967. * handled
  11968. * by a callback have to be considered as requests to a script
  11969. * resource. */
  11970. is_callback_resource = 1;
  11971. is_script_resource = 1;
  11972. is_put_or_delete_request = is_put_or_delete_method(conn);
  11973. } else {
  11974. no_callback_resource:
  11975. /* 5.2.2. No callback is responsible for this request. The URI
  11976. * addresses a file based resource (static content or Lua/cgi
  11977. * scripts in the file system). */
  11978. is_callback_resource = 0;
  11979. interpret_uri(conn,
  11980. path,
  11981. sizeof(path),
  11982. &file.stat,
  11983. &is_found,
  11984. &is_script_resource,
  11985. &is_websocket_request,
  11986. &is_put_or_delete_request);
  11987. }
  11988. /* 6. authorization check */
  11989. /* 6.1. a custom authorization handler is installed */
  11990. if (get_request_handler(conn,
  11991. AUTH_HANDLER,
  11992. NULL,
  11993. NULL,
  11994. NULL,
  11995. NULL,
  11996. NULL,
  11997. NULL,
  11998. &auth_handler,
  11999. &auth_callback_data,
  12000. NULL)) {
  12001. if (!auth_handler(conn, auth_callback_data)) {
  12002. return;
  12003. }
  12004. } else if (is_put_or_delete_request && !is_script_resource
  12005. && !is_callback_resource) {
  12006. /* 6.2. this request is a PUT/DELETE to a real file */
  12007. /* 6.2.1. thus, the server must have real files */
  12008. #if defined(NO_FILES)
  12009. if (1) {
  12010. #else
  12011. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12012. #endif
  12013. /* This server does not have any real files, thus the
  12014. * PUT/DELETE methods are not valid. */
  12015. mg_send_http_error(conn,
  12016. 405,
  12017. "%s method not allowed",
  12018. conn->request_info.request_method);
  12019. return;
  12020. }
  12021. #if !defined(NO_FILES)
  12022. /* 6.2.2. Check if put authorization for static files is
  12023. * available.
  12024. */
  12025. if (!is_authorized_for_put(conn)) {
  12026. send_authorization_request(conn, NULL);
  12027. return;
  12028. }
  12029. #endif
  12030. } else {
  12031. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12032. * or it is a PUT or DELETE request to a resource that does not
  12033. * correspond to a file. Check authorization. */
  12034. if (!check_authorization(conn, path)) {
  12035. send_authorization_request(conn, NULL);
  12036. return;
  12037. }
  12038. }
  12039. /* request is authorized or does not need authorization */
  12040. /* 7. check if there are request handlers for this uri */
  12041. if (is_callback_resource) {
  12042. if (!is_websocket_request) {
  12043. i = callback_handler(conn, callback_data);
  12044. /* Callback handler will not be used anymore. Release it */
  12045. handler_info_release(handler_info);
  12046. if (i > 0) {
  12047. /* Do nothing, callback has served the request. Store
  12048. * then return value as status code for the log and discard
  12049. * all data from the client not used by the callback. */
  12050. conn->status_code = i;
  12051. discard_unread_request_data(conn);
  12052. } else {
  12053. /* The handler did NOT handle the request. */
  12054. /* Some proper reactions would be:
  12055. * a) close the connections without sending anything
  12056. * b) send a 404 not found
  12057. * c) try if there is a file matching the URI
  12058. * It would be possible to do a, b or c in the callback
  12059. * implementation, and return 1 - we cannot do anything
  12060. * here, that is not possible in the callback.
  12061. *
  12062. * TODO: What would be the best reaction here?
  12063. * (Note: The reaction may change, if there is a better
  12064. *idea.)
  12065. */
  12066. /* For the moment, use option c: We look for a proper file,
  12067. * but since a file request is not always a script resource,
  12068. * the authorization check might be different. */
  12069. interpret_uri(conn,
  12070. path,
  12071. sizeof(path),
  12072. &file.stat,
  12073. &is_found,
  12074. &is_script_resource,
  12075. &is_websocket_request,
  12076. &is_put_or_delete_request);
  12077. callback_handler = NULL;
  12078. /* Here we are at a dead end:
  12079. * According to URI matching, a callback should be
  12080. * responsible for handling the request,
  12081. * we called it, but the callback declared itself
  12082. * not responsible.
  12083. * We use a goto here, to get out of this dead end,
  12084. * and continue with the default handling.
  12085. * A goto here is simpler and better to understand
  12086. * than some curious loop. */
  12087. goto no_callback_resource;
  12088. }
  12089. } else {
  12090. #if defined(USE_WEBSOCKET)
  12091. handle_websocket_request(conn,
  12092. path,
  12093. is_callback_resource,
  12094. subprotocols,
  12095. ws_connect_handler,
  12096. ws_ready_handler,
  12097. ws_data_handler,
  12098. ws_close_handler,
  12099. callback_data);
  12100. #endif
  12101. }
  12102. return;
  12103. }
  12104. /* 8. handle websocket requests */
  12105. #if defined(USE_WEBSOCKET)
  12106. if (is_websocket_request) {
  12107. if (is_script_resource) {
  12108. if (is_in_script_path(conn, path)) {
  12109. /* Websocket Lua script */
  12110. handle_websocket_request(conn,
  12111. path,
  12112. 0 /* Lua Script */,
  12113. NULL,
  12114. NULL,
  12115. NULL,
  12116. NULL,
  12117. NULL,
  12118. conn->phys_ctx->user_data);
  12119. } else {
  12120. /* Script was in an illegal path */
  12121. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12122. }
  12123. } else {
  12124. #if defined(MG_LEGACY_INTERFACE)
  12125. handle_websocket_request(
  12126. conn,
  12127. path,
  12128. !is_script_resource /* could be deprecated global callback */,
  12129. NULL,
  12130. deprecated_websocket_connect_wrapper,
  12131. deprecated_websocket_ready_wrapper,
  12132. deprecated_websocket_data_wrapper,
  12133. NULL,
  12134. conn->phys_ctx->user_data);
  12135. #else
  12136. mg_send_http_error(conn, 404, "%s", "Not found");
  12137. #endif
  12138. }
  12139. return;
  12140. } else
  12141. #endif
  12142. #if defined(NO_FILES)
  12143. /* 9a. In case the server uses only callbacks, this uri is
  12144. * unknown.
  12145. * Then, all request handling ends here. */
  12146. mg_send_http_error(conn, 404, "%s", "Not Found");
  12147. #else
  12148. /* 9b. This request is either for a static file or resource handled
  12149. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12150. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12151. mg_send_http_error(conn, 404, "%s", "Not Found");
  12152. return;
  12153. }
  12154. /* 10. Request is handled by a script */
  12155. if (is_script_resource) {
  12156. handle_file_based_request(conn, path, &file);
  12157. return;
  12158. }
  12159. /* 11. Handle put/delete/mkcol requests */
  12160. if (is_put_or_delete_request) {
  12161. /* 11.1. PUT method */
  12162. if (!strcmp(ri->request_method, "PUT")) {
  12163. put_file(conn, path);
  12164. return;
  12165. }
  12166. /* 11.2. DELETE method */
  12167. if (!strcmp(ri->request_method, "DELETE")) {
  12168. delete_file(conn, path);
  12169. return;
  12170. }
  12171. /* 11.3. MKCOL method */
  12172. if (!strcmp(ri->request_method, "MKCOL")) {
  12173. mkcol(conn, path);
  12174. return;
  12175. }
  12176. /* 11.4. PATCH method
  12177. * This method is not supported for static resources,
  12178. * only for scripts (Lua, CGI) and callbacks. */
  12179. mg_send_http_error(conn,
  12180. 405,
  12181. "%s method not allowed",
  12182. conn->request_info.request_method);
  12183. return;
  12184. }
  12185. /* 11. File does not exist, or it was configured that it should be
  12186. * hidden */
  12187. if (!is_found || (must_hide_file(conn, path))) {
  12188. mg_send_http_error(conn, 404, "%s", "Not found");
  12189. return;
  12190. }
  12191. /* 12. Directory uris should end with a slash */
  12192. if (file.stat.is_directory && (uri_len > 0)
  12193. && (ri->local_uri[uri_len - 1] != '/')) {
  12194. gmt_time_string(date, sizeof(date), &curtime);
  12195. mg_printf(conn,
  12196. "HTTP/1.1 301 Moved Permanently\r\n"
  12197. "Location: %s/\r\n"
  12198. "Date: %s\r\n"
  12199. /* "Cache-Control: private\r\n" (= default) */
  12200. "Content-Length: 0\r\n"
  12201. "Connection: %s\r\n",
  12202. ri->request_uri,
  12203. date,
  12204. suggest_connection_header(conn));
  12205. send_additional_header(conn);
  12206. mg_printf(conn, "\r\n");
  12207. return;
  12208. }
  12209. /* 13. Handle other methods than GET/HEAD */
  12210. /* 13.1. Handle PROPFIND */
  12211. if (!strcmp(ri->request_method, "PROPFIND")) {
  12212. handle_propfind(conn, path, &file.stat);
  12213. return;
  12214. }
  12215. /* 13.2. Handle OPTIONS for files */
  12216. if (!strcmp(ri->request_method, "OPTIONS")) {
  12217. /* This standard handler is only used for real files.
  12218. * Scripts should support the OPTIONS method themselves, to allow a
  12219. * maximum flexibility.
  12220. * Lua and CGI scripts may fully support CORS this way (including
  12221. * preflights). */
  12222. send_options(conn);
  12223. return;
  12224. }
  12225. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12226. if ((0 != strcmp(ri->request_method, "GET"))
  12227. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12228. mg_send_http_error(conn,
  12229. 405,
  12230. "%s method not allowed",
  12231. conn->request_info.request_method);
  12232. return;
  12233. }
  12234. /* 14. directories */
  12235. if (file.stat.is_directory) {
  12236. /* Substitute files have already been handled above. */
  12237. /* Here we can either generate and send a directory listing,
  12238. * or send an "access denied" error. */
  12239. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12240. "yes")) {
  12241. handle_directory_request(conn, path);
  12242. } else {
  12243. mg_send_http_error(conn,
  12244. 403,
  12245. "%s",
  12246. "Error: Directory listing denied");
  12247. }
  12248. return;
  12249. }
  12250. /* 15. read a normal file with GET or HEAD */
  12251. handle_file_based_request(conn, path, &file);
  12252. #endif /* !defined(NO_FILES) */
  12253. }
  12254. #if !defined(NO_FILESYSTEMS)
  12255. static void
  12256. handle_file_based_request(struct mg_connection *conn,
  12257. const char *path,
  12258. struct mg_file *file)
  12259. {
  12260. if (!conn || !conn->dom_ctx) {
  12261. return;
  12262. }
  12263. if (0) {
  12264. #if defined(USE_LUA)
  12265. } else if (match_prefix(
  12266. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12267. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12268. path)
  12269. > 0) {
  12270. if (is_in_script_path(conn, path)) {
  12271. /* Lua server page: an SSI like page containing mostly plain
  12272. * html
  12273. * code
  12274. * plus some tags with server generated contents. */
  12275. handle_lsp_request(conn, path, file, NULL);
  12276. } else {
  12277. /* Script was in an illegal path */
  12278. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12279. }
  12280. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12281. strlen(
  12282. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12283. path)
  12284. > 0) {
  12285. if (is_in_script_path(conn, path)) {
  12286. /* Lua in-server module script: a CGI like script used to
  12287. * generate
  12288. * the
  12289. * entire reply. */
  12290. mg_exec_lua_script(conn, path, NULL);
  12291. } else {
  12292. /* Script was in an illegal path */
  12293. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12294. }
  12295. #endif
  12296. #if defined(USE_DUKTAPE)
  12297. } else if (match_prefix(
  12298. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12299. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12300. path)
  12301. > 0) {
  12302. if (is_in_script_path(conn, path)) {
  12303. /* Call duktape to generate the page */
  12304. mg_exec_duktape_script(conn, path);
  12305. } else {
  12306. /* Script was in an illegal path */
  12307. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12308. }
  12309. #endif
  12310. #if !defined(NO_CGI)
  12311. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12312. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12313. path)
  12314. > 0) {
  12315. if (is_in_script_path(conn, path)) {
  12316. /* CGI scripts may support all HTTP methods */
  12317. handle_cgi_request(conn, path);
  12318. } else {
  12319. /* Script was in an illegal path */
  12320. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12321. }
  12322. #endif /* !NO_CGI */
  12323. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12324. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12325. path)
  12326. > 0) {
  12327. if (is_in_script_path(conn, path)) {
  12328. handle_ssi_file_request(conn, path, file);
  12329. } else {
  12330. /* Script was in an illegal path */
  12331. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12332. }
  12333. #if !defined(NO_CACHING)
  12334. } else if ((!conn->in_error_handler)
  12335. && is_not_modified(conn, &file->stat)) {
  12336. /* Send 304 "Not Modified" - this must not send any body data */
  12337. handle_not_modified_static_file_request(conn, file);
  12338. #endif /* !NO_CACHING */
  12339. } else {
  12340. handle_static_file_request(conn, path, file, NULL, NULL);
  12341. }
  12342. }
  12343. #endif /* NO_FILESYSTEMS */
  12344. static void
  12345. close_all_listening_sockets(struct mg_context *ctx)
  12346. {
  12347. unsigned int i;
  12348. if (!ctx) {
  12349. return;
  12350. }
  12351. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12352. closesocket(ctx->listening_sockets[i].sock);
  12353. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12354. }
  12355. mg_free(ctx->listening_sockets);
  12356. ctx->listening_sockets = NULL;
  12357. mg_free(ctx->listening_socket_fds);
  12358. ctx->listening_socket_fds = NULL;
  12359. }
  12360. /* Valid listening port specification is: [ip_address:]port[s]
  12361. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12362. * Examples for IPv6: [::]:80, [::1]:80,
  12363. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12364. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12365. * In order to bind to both, IPv4 and IPv6, you can either add
  12366. * both ports using 8080,[::]:8080, or the short form +8080.
  12367. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12368. * one only accepting IPv4 the other only IPv6. +8080 creates
  12369. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12370. * environment, they might work differently, or might not work
  12371. * at all - it must be tested what options work best in the
  12372. * relevant network environment.
  12373. */
  12374. static int
  12375. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12376. {
  12377. unsigned int a, b, c, d, port;
  12378. int ch, len;
  12379. const char *cb;
  12380. char *endptr;
  12381. #if defined(USE_IPV6)
  12382. char buf[100] = {0};
  12383. #endif
  12384. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12385. * Also, all-zeroes in the socket address means binding to all addresses
  12386. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12387. memset(so, 0, sizeof(*so));
  12388. so->lsa.sin.sin_family = AF_INET;
  12389. *ip_version = 0;
  12390. /* Initialize port and len as invalid. */
  12391. port = 0;
  12392. len = 0;
  12393. /* Test for different ways to format this string */
  12394. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12395. == 5) {
  12396. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12397. so->lsa.sin.sin_addr.s_addr =
  12398. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12399. so->lsa.sin.sin_port = htons((uint16_t)port);
  12400. *ip_version = 4;
  12401. #if defined(USE_IPV6)
  12402. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12403. && mg_inet_pton(
  12404. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12405. /* IPv6 address, examples: see above */
  12406. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12407. */
  12408. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12409. *ip_version = 6;
  12410. #endif
  12411. } else if ((vec->ptr[0] == '+')
  12412. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12413. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12414. /* Add 1 to len for the + character we skipped before */
  12415. len++;
  12416. #if defined(USE_IPV6)
  12417. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12418. so->lsa.sin6.sin6_family = AF_INET6;
  12419. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12420. *ip_version = 4 + 6;
  12421. #else
  12422. /* Bind to IPv4 only, since IPv6 is not built in. */
  12423. so->lsa.sin.sin_port = htons((uint16_t)port);
  12424. *ip_version = 4;
  12425. #endif
  12426. } else if (is_valid_port(port = strtoul(vec->ptr, &endptr, 0))
  12427. && vec->ptr != endptr) {
  12428. len = endptr - vec->ptr;
  12429. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12430. so->lsa.sin.sin_port = htons((uint16_t)port);
  12431. *ip_version = 4;
  12432. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12433. /* String could be a hostname. This check algotithm
  12434. * will only work for RFC 952 compliant hostnames,
  12435. * starting with a letter, containing only letters,
  12436. * digits and hyphen ('-'). Newer specs may allow
  12437. * more, but this is not guaranteed here, since it
  12438. * may interfere with rules for port option lists. */
  12439. /* According to RFC 1035, hostnames are restricted to 255 characters
  12440. * in total (63 between two dots). */
  12441. char hostname[256];
  12442. size_t hostnlen = (size_t)(cb - vec->ptr);
  12443. if (hostnlen >= sizeof(hostname)) {
  12444. /* This would be invalid in any case */
  12445. *ip_version = 0;
  12446. return 0;
  12447. }
  12448. memcpy(hostname, vec->ptr, hostnlen);
  12449. hostname[hostnlen] = 0;
  12450. if (mg_inet_pton(
  12451. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12452. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12453. *ip_version = 4;
  12454. so->lsa.sin.sin_family = AF_INET;
  12455. so->lsa.sin.sin_port = htons((uint16_t)port);
  12456. len += (int)(hostnlen + 1);
  12457. } else {
  12458. port = 0;
  12459. len = 0;
  12460. }
  12461. #if defined(USE_IPV6)
  12462. } else if (mg_inet_pton(AF_INET6,
  12463. vec->ptr,
  12464. &so->lsa.sin6,
  12465. sizeof(so->lsa.sin6))) {
  12466. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12467. *ip_version = 6;
  12468. so->lsa.sin6.sin6_family = AF_INET6;
  12469. so->lsa.sin.sin_port = htons((uint16_t)port);
  12470. len += (int)(hostnlen + 1);
  12471. } else {
  12472. port = 0;
  12473. len = 0;
  12474. }
  12475. #endif
  12476. }
  12477. } else {
  12478. /* Parsing failure. */
  12479. }
  12480. /* sscanf and the option splitting code ensure the following condition
  12481. */
  12482. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12483. *ip_version = 0;
  12484. return 0;
  12485. }
  12486. ch = vec->ptr[len]; /* Next character after the port number */
  12487. so->is_ssl = (ch == 's');
  12488. so->ssl_redir = (ch == 'r');
  12489. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12490. if (is_valid_port(port)
  12491. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12492. return 1;
  12493. }
  12494. /* Reset ip_version to 0 if there is an error */
  12495. *ip_version = 0;
  12496. return 0;
  12497. }
  12498. /* Is there any SSL port in use? */
  12499. static int
  12500. is_ssl_port_used(const char *ports)
  12501. {
  12502. if (ports) {
  12503. /* There are several different allowed syntax variants:
  12504. * - "80" for a single port using every network interface
  12505. * - "localhost:80" for a single port using only localhost
  12506. * - "80,localhost:8080" for two ports, one bound to localhost
  12507. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12508. * to IPv4 localhost, one to IPv6 localhost
  12509. * - "+80" use port 80 for IPv4 and IPv6
  12510. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12511. * for both: IPv4 and IPv4
  12512. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12513. * additionally port 8080 bound to localhost connections
  12514. *
  12515. * If we just look for 's' anywhere in the string, "localhost:80"
  12516. * will be detected as SSL (false positive).
  12517. * Looking for 's' after a digit may cause false positives in
  12518. * "my24service:8080".
  12519. * Looking from 's' backward if there are only ':' and numbers
  12520. * before will not work for "24service:8080" (non SSL, port 8080)
  12521. * or "24s" (SSL, port 24).
  12522. *
  12523. * Remark: Initially hostnames were not allowed to start with a
  12524. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12525. * Section 2.1).
  12526. *
  12527. * To get this correct, the entire string must be parsed as a whole,
  12528. * reading it as a list element for element and parsing with an
  12529. * algorithm equivalent to parse_port_string.
  12530. *
  12531. * In fact, we use local interface names here, not arbitrary hostnames,
  12532. * so in most cases the only name will be "localhost".
  12533. *
  12534. * So, for now, we use this simple algorithm, that may still return
  12535. * a false positive in bizarre cases.
  12536. */
  12537. int i;
  12538. int portslen = (int)strlen(ports);
  12539. char prevIsNumber = 0;
  12540. for (i = 0; i < portslen; i++) {
  12541. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12542. return 1;
  12543. }
  12544. if (ports[i] >= '0' && ports[i] <= '9') {
  12545. prevIsNumber = 1;
  12546. } else {
  12547. prevIsNumber = 0;
  12548. }
  12549. }
  12550. }
  12551. return 0;
  12552. }
  12553. static int
  12554. set_ports_option(struct mg_context *phys_ctx)
  12555. {
  12556. const char *list;
  12557. int on = 1;
  12558. #if defined(USE_IPV6)
  12559. int off = 0;
  12560. #endif
  12561. struct vec vec;
  12562. struct socket so, *ptr;
  12563. struct mg_pollfd *pfd;
  12564. union usa usa;
  12565. socklen_t len;
  12566. int ip_version;
  12567. int portsTotal = 0;
  12568. int portsOk = 0;
  12569. const char *opt_txt;
  12570. long opt_max_connections;
  12571. if (!phys_ctx) {
  12572. return 0;
  12573. }
  12574. memset(&so, 0, sizeof(so));
  12575. memset(&usa, 0, sizeof(usa));
  12576. len = sizeof(usa);
  12577. list = phys_ctx->dd.config[LISTENING_PORTS];
  12578. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12579. portsTotal++;
  12580. if (!parse_port_string(&vec, &so, &ip_version)) {
  12581. mg_cry_ctx_internal(
  12582. phys_ctx,
  12583. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12584. (int)vec.len,
  12585. vec.ptr,
  12586. portsTotal,
  12587. "[IP_ADDRESS:]PORT[s|r]");
  12588. continue;
  12589. }
  12590. #if !defined(NO_SSL)
  12591. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12592. mg_cry_ctx_internal(phys_ctx,
  12593. "Cannot add SSL socket (entry %i)",
  12594. portsTotal);
  12595. continue;
  12596. }
  12597. #endif
  12598. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12599. == INVALID_SOCKET) {
  12600. mg_cry_ctx_internal(phys_ctx,
  12601. "cannot create socket (entry %i)",
  12602. portsTotal);
  12603. continue;
  12604. }
  12605. #if defined(_WIN32)
  12606. /* Windows SO_REUSEADDR lets many procs binds to a
  12607. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12608. * if someone already has the socket -- DTL */
  12609. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12610. * Windows might need a few seconds before
  12611. * the same port can be used again in the
  12612. * same process, so a short Sleep may be
  12613. * required between mg_stop and mg_start.
  12614. */
  12615. if (setsockopt(so.sock,
  12616. SOL_SOCKET,
  12617. SO_EXCLUSIVEADDRUSE,
  12618. (SOCK_OPT_TYPE)&on,
  12619. sizeof(on))
  12620. != 0) {
  12621. /* Set reuse option, but don't abort on errors. */
  12622. mg_cry_ctx_internal(
  12623. phys_ctx,
  12624. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12625. portsTotal);
  12626. }
  12627. #else
  12628. if (setsockopt(so.sock,
  12629. SOL_SOCKET,
  12630. SO_REUSEADDR,
  12631. (SOCK_OPT_TYPE)&on,
  12632. sizeof(on))
  12633. != 0) {
  12634. /* Set reuse option, but don't abort on errors. */
  12635. mg_cry_ctx_internal(
  12636. phys_ctx,
  12637. "cannot set socket option SO_REUSEADDR (entry %i)",
  12638. portsTotal);
  12639. }
  12640. #endif
  12641. if (ip_version > 4) {
  12642. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12643. #if defined(USE_IPV6)
  12644. if (ip_version > 6) {
  12645. if (so.lsa.sa.sa_family == AF_INET6
  12646. && setsockopt(so.sock,
  12647. IPPROTO_IPV6,
  12648. IPV6_V6ONLY,
  12649. (void *)&off,
  12650. sizeof(off))
  12651. != 0) {
  12652. /* Set IPv6 only option, but don't abort on errors. */
  12653. mg_cry_ctx_internal(
  12654. phys_ctx,
  12655. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12656. portsTotal);
  12657. }
  12658. } else {
  12659. if (so.lsa.sa.sa_family == AF_INET6
  12660. && setsockopt(so.sock,
  12661. IPPROTO_IPV6,
  12662. IPV6_V6ONLY,
  12663. (void *)&on,
  12664. sizeof(on))
  12665. != 0) {
  12666. /* Set IPv6 only option, but don't abort on errors. */
  12667. mg_cry_ctx_internal(
  12668. phys_ctx,
  12669. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12670. portsTotal);
  12671. }
  12672. }
  12673. #else
  12674. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12675. closesocket(so.sock);
  12676. so.sock = INVALID_SOCKET;
  12677. continue;
  12678. #endif
  12679. }
  12680. if (so.lsa.sa.sa_family == AF_INET) {
  12681. len = sizeof(so.lsa.sin);
  12682. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12683. mg_cry_ctx_internal(phys_ctx,
  12684. "cannot bind to %.*s: %d (%s)",
  12685. (int)vec.len,
  12686. vec.ptr,
  12687. (int)ERRNO,
  12688. strerror(errno));
  12689. closesocket(so.sock);
  12690. so.sock = INVALID_SOCKET;
  12691. continue;
  12692. }
  12693. }
  12694. #if defined(USE_IPV6)
  12695. else if (so.lsa.sa.sa_family == AF_INET6) {
  12696. len = sizeof(so.lsa.sin6);
  12697. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12698. mg_cry_ctx_internal(phys_ctx,
  12699. "cannot bind to IPv6 %.*s: %d (%s)",
  12700. (int)vec.len,
  12701. vec.ptr,
  12702. (int)ERRNO,
  12703. strerror(errno));
  12704. closesocket(so.sock);
  12705. so.sock = INVALID_SOCKET;
  12706. continue;
  12707. }
  12708. }
  12709. #endif
  12710. else {
  12711. mg_cry_ctx_internal(
  12712. phys_ctx,
  12713. "cannot bind: address family not supported (entry %i)",
  12714. portsTotal);
  12715. closesocket(so.sock);
  12716. so.sock = INVALID_SOCKET;
  12717. continue;
  12718. }
  12719. opt_txt = phys_ctx->dd.config[MAX_CONNECTIONS];
  12720. opt_max_connections = strtol(opt_txt, NULL, 10);
  12721. if ((opt_max_connections > INT_MAX) || (opt_max_connections < 1)) {
  12722. mg_cry_ctx_internal(phys_ctx,
  12723. "max_connections value \"%s\" is invalid",
  12724. opt_txt);
  12725. continue;
  12726. }
  12727. if (listen(so.sock, (int)opt_max_connections) != 0) {
  12728. mg_cry_ctx_internal(phys_ctx,
  12729. "cannot listen to %.*s: %d (%s)",
  12730. (int)vec.len,
  12731. vec.ptr,
  12732. (int)ERRNO,
  12733. strerror(errno));
  12734. closesocket(so.sock);
  12735. so.sock = INVALID_SOCKET;
  12736. continue;
  12737. }
  12738. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12739. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12740. int err = (int)ERRNO;
  12741. mg_cry_ctx_internal(phys_ctx,
  12742. "call to getsockname failed %.*s: %d (%s)",
  12743. (int)vec.len,
  12744. vec.ptr,
  12745. err,
  12746. strerror(errno));
  12747. closesocket(so.sock);
  12748. so.sock = INVALID_SOCKET;
  12749. continue;
  12750. }
  12751. /* Update lsa port in case of random free ports */
  12752. #if defined(USE_IPV6)
  12753. if (so.lsa.sa.sa_family == AF_INET6) {
  12754. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12755. } else
  12756. #endif
  12757. {
  12758. so.lsa.sin.sin_port = usa.sin.sin_port;
  12759. }
  12760. if ((ptr = (struct socket *)
  12761. mg_realloc_ctx(phys_ctx->listening_sockets,
  12762. (phys_ctx->num_listening_sockets + 1)
  12763. * sizeof(phys_ctx->listening_sockets[0]),
  12764. phys_ctx))
  12765. == NULL) {
  12766. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12767. closesocket(so.sock);
  12768. so.sock = INVALID_SOCKET;
  12769. continue;
  12770. }
  12771. if ((pfd = (struct mg_pollfd *)
  12772. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12773. (phys_ctx->num_listening_sockets + 1)
  12774. * sizeof(phys_ctx->listening_socket_fds[0]),
  12775. phys_ctx))
  12776. == NULL) {
  12777. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12778. closesocket(so.sock);
  12779. so.sock = INVALID_SOCKET;
  12780. mg_free(ptr);
  12781. continue;
  12782. }
  12783. set_close_on_exec(so.sock, NULL, phys_ctx);
  12784. phys_ctx->listening_sockets = ptr;
  12785. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12786. phys_ctx->listening_socket_fds = pfd;
  12787. phys_ctx->num_listening_sockets++;
  12788. portsOk++;
  12789. }
  12790. if (portsOk != portsTotal) {
  12791. close_all_listening_sockets(phys_ctx);
  12792. portsOk = 0;
  12793. }
  12794. return portsOk;
  12795. }
  12796. static const char *
  12797. header_val(const struct mg_connection *conn, const char *header)
  12798. {
  12799. const char *header_value;
  12800. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12801. return "-";
  12802. } else {
  12803. return header_value;
  12804. }
  12805. }
  12806. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12807. static void log_access(const struct mg_connection *conn);
  12808. #include "external_log_access.inl"
  12809. #elif !defined(NO_FILESYSTEMS)
  12810. static void
  12811. log_access(const struct mg_connection *conn)
  12812. {
  12813. const struct mg_request_info *ri;
  12814. struct mg_file fi;
  12815. char date[64], src_addr[IP_ADDR_STR_LEN];
  12816. struct tm *tm;
  12817. const char *referer;
  12818. const char *user_agent;
  12819. char buf[4096];
  12820. if (!conn || !conn->dom_ctx) {
  12821. return;
  12822. }
  12823. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12824. if (mg_fopen(conn,
  12825. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12826. MG_FOPEN_MODE_APPEND,
  12827. &fi)
  12828. == 0) {
  12829. fi.access.fp = NULL;
  12830. }
  12831. } else {
  12832. fi.access.fp = NULL;
  12833. }
  12834. /* Log is written to a file and/or a callback. If both are not set,
  12835. * executing the rest of the function is pointless. */
  12836. if ((fi.access.fp == NULL)
  12837. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12838. return;
  12839. }
  12840. tm = localtime(&conn->conn_birth_time);
  12841. if (tm != NULL) {
  12842. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12843. } else {
  12844. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12845. date[sizeof(date) - 1] = '\0';
  12846. }
  12847. ri = &conn->request_info;
  12848. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12849. referer = header_val(conn, "Referer");
  12850. user_agent = header_val(conn, "User-Agent");
  12851. mg_snprintf(conn,
  12852. NULL, /* Ignore truncation in access log */
  12853. buf,
  12854. sizeof(buf),
  12855. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12856. src_addr,
  12857. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12858. date,
  12859. ri->request_method ? ri->request_method : "-",
  12860. ri->request_uri ? ri->request_uri : "-",
  12861. ri->query_string ? "?" : "",
  12862. ri->query_string ? ri->query_string : "",
  12863. ri->http_version,
  12864. conn->status_code,
  12865. conn->num_bytes_sent,
  12866. referer,
  12867. user_agent);
  12868. if (conn->phys_ctx->callbacks.log_access) {
  12869. conn->phys_ctx->callbacks.log_access(conn, buf);
  12870. }
  12871. if (fi.access.fp) {
  12872. int ok = 1;
  12873. flockfile(fi.access.fp);
  12874. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12875. ok = 0;
  12876. }
  12877. if (fflush(fi.access.fp) != 0) {
  12878. ok = 0;
  12879. }
  12880. funlockfile(fi.access.fp);
  12881. if (mg_fclose(&fi.access) != 0) {
  12882. ok = 0;
  12883. }
  12884. if (!ok) {
  12885. mg_cry_internal(conn,
  12886. "Error writing log file %s",
  12887. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12888. }
  12889. }
  12890. }
  12891. #else
  12892. #error Must either enable filesystems or provide a custom log_access implementation
  12893. #endif /* Externally provided function */
  12894. /* Verify given socket address against the ACL.
  12895. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12896. */
  12897. static int
  12898. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12899. {
  12900. int allowed, flag;
  12901. uint32_t net, mask;
  12902. struct vec vec;
  12903. if (phys_ctx) {
  12904. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12905. /* If any ACL is set, deny by default */
  12906. allowed = (list == NULL) ? '+' : '-';
  12907. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12908. flag = vec.ptr[0];
  12909. if ((flag != '+' && flag != '-')
  12910. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12911. mg_cry_ctx_internal(phys_ctx,
  12912. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12913. __func__);
  12914. return -1;
  12915. }
  12916. if (net == (remote_ip & mask)) {
  12917. allowed = flag;
  12918. }
  12919. }
  12920. return allowed == '+';
  12921. }
  12922. return -1;
  12923. }
  12924. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  12925. static int
  12926. set_uid_option(struct mg_context *phys_ctx)
  12927. {
  12928. int success = 0;
  12929. if (phys_ctx) {
  12930. /* We are currently running as curr_uid. */
  12931. const uid_t curr_uid = getuid();
  12932. /* If set, we want to run as run_as_user. */
  12933. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12934. const struct passwd *to_pw = NULL;
  12935. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12936. /* run_as_user does not exist on the system. We can't proceed
  12937. * further. */
  12938. mg_cry_ctx_internal(phys_ctx,
  12939. "%s: unknown user [%s]",
  12940. __func__,
  12941. run_as_user);
  12942. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12943. /* There was either no request to change user, or we're already
  12944. * running as run_as_user. Nothing else to do.
  12945. */
  12946. success = 1;
  12947. } else {
  12948. /* Valid change request. */
  12949. if (setgid(to_pw->pw_gid) == -1) {
  12950. mg_cry_ctx_internal(phys_ctx,
  12951. "%s: setgid(%s): %s",
  12952. __func__,
  12953. run_as_user,
  12954. strerror(errno));
  12955. } else if (setgroups(0, NULL) == -1) {
  12956. mg_cry_ctx_internal(phys_ctx,
  12957. "%s: setgroups(): %s",
  12958. __func__,
  12959. strerror(errno));
  12960. } else if (setuid(to_pw->pw_uid) == -1) {
  12961. mg_cry_ctx_internal(phys_ctx,
  12962. "%s: setuid(%s): %s",
  12963. __func__,
  12964. run_as_user,
  12965. strerror(errno));
  12966. } else {
  12967. success = 1;
  12968. }
  12969. }
  12970. }
  12971. return success;
  12972. }
  12973. #endif /* !_WIN32 */
  12974. static void
  12975. tls_dtor(void *key)
  12976. {
  12977. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12978. /* key == pthread_getspecific(sTlsKey); */
  12979. if (tls) {
  12980. if (tls->is_master == 2) {
  12981. tls->is_master = -3; /* Mark memory as dead */
  12982. mg_free(tls);
  12983. }
  12984. }
  12985. pthread_setspecific(sTlsKey, NULL);
  12986. }
  12987. #if !defined(NO_SSL)
  12988. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12989. struct mg_domain_context *dom_ctx,
  12990. const char *pem,
  12991. const char *chain);
  12992. static const char *ssl_error(void);
  12993. static int
  12994. refresh_trust(struct mg_connection *conn)
  12995. {
  12996. static int reload_lock = 0;
  12997. static long int data_check = 0;
  12998. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12999. struct stat cert_buf;
  13000. long int t;
  13001. const char *pem;
  13002. const char *chain;
  13003. int should_verify_peer;
  13004. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  13005. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13006. * refresh_trust still can not work. */
  13007. return 0;
  13008. }
  13009. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13010. if (chain == NULL) {
  13011. /* pem is not NULL here */
  13012. chain = pem;
  13013. }
  13014. if (*chain == 0) {
  13015. chain = NULL;
  13016. }
  13017. t = data_check;
  13018. if (stat(pem, &cert_buf) != -1) {
  13019. t = (long int)cert_buf.st_mtime;
  13020. }
  13021. if (data_check != t) {
  13022. data_check = t;
  13023. should_verify_peer = 0;
  13024. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13025. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13026. == 0) {
  13027. should_verify_peer = 1;
  13028. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13029. "optional")
  13030. == 0) {
  13031. should_verify_peer = 1;
  13032. }
  13033. }
  13034. if (should_verify_peer) {
  13035. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13036. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13037. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13038. ca_file,
  13039. ca_path)
  13040. != 1) {
  13041. mg_cry_ctx_internal(
  13042. conn->phys_ctx,
  13043. "SSL_CTX_load_verify_locations error: %s "
  13044. "ssl_verify_peer requires setting "
  13045. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13046. "present in "
  13047. "the .conf file?",
  13048. ssl_error());
  13049. return 0;
  13050. }
  13051. }
  13052. if (1 == mg_atomic_inc(p_reload_lock)) {
  13053. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13054. == 0) {
  13055. return 0;
  13056. }
  13057. *p_reload_lock = 0;
  13058. }
  13059. }
  13060. /* lock while cert is reloading */
  13061. while (*p_reload_lock) {
  13062. sleep(1);
  13063. }
  13064. return 1;
  13065. }
  13066. #if defined(OPENSSL_API_1_1)
  13067. #else
  13068. static pthread_mutex_t *ssl_mutexes;
  13069. #endif /* OPENSSL_API_1_1 */
  13070. static int
  13071. sslize(struct mg_connection *conn,
  13072. SSL_CTX *s,
  13073. int (*func)(SSL *),
  13074. volatile int *stop_server,
  13075. const struct mg_client_options *client_options)
  13076. {
  13077. int ret, err;
  13078. int short_trust;
  13079. unsigned timeout = 1024;
  13080. unsigned i;
  13081. if (!conn) {
  13082. return 0;
  13083. }
  13084. short_trust =
  13085. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13086. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13087. if (short_trust) {
  13088. int trust_ret = refresh_trust(conn);
  13089. if (!trust_ret) {
  13090. return trust_ret;
  13091. }
  13092. }
  13093. conn->ssl = SSL_new(s);
  13094. if (conn->ssl == NULL) {
  13095. return 0;
  13096. }
  13097. SSL_set_app_data(conn->ssl, (char *)conn);
  13098. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13099. if (ret != 1) {
  13100. err = SSL_get_error(conn->ssl, ret);
  13101. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13102. SSL_free(conn->ssl);
  13103. conn->ssl = NULL;
  13104. OPENSSL_REMOVE_THREAD_STATE();
  13105. return 0;
  13106. }
  13107. if (client_options) {
  13108. if (client_options->host_name) {
  13109. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13110. }
  13111. }
  13112. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13113. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13114. /* NOTE: The loop below acts as a back-off, so we can end
  13115. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13116. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13117. }
  13118. /* SSL functions may fail and require to be called again:
  13119. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13120. * Here "func" could be SSL_connect or SSL_accept. */
  13121. for (i = 0; i <= timeout; i += 50) {
  13122. ret = func(conn->ssl);
  13123. if (ret != 1) {
  13124. err = SSL_get_error(conn->ssl, ret);
  13125. if ((err == SSL_ERROR_WANT_CONNECT)
  13126. || (err == SSL_ERROR_WANT_ACCEPT)
  13127. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13128. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13129. if (*stop_server) {
  13130. /* Don't wait if the server is going to be stopped. */
  13131. break;
  13132. }
  13133. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13134. /* Simply retry the function call. */
  13135. mg_sleep(50);
  13136. } else {
  13137. /* Need to retry the function call "later".
  13138. * See https://linux.die.net/man/3/ssl_get_error
  13139. * This is typical for non-blocking sockets. */
  13140. struct mg_pollfd pfd;
  13141. int pollres;
  13142. pfd.fd = conn->client.sock;
  13143. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13144. || (err == SSL_ERROR_WANT_WRITE))
  13145. ? POLLOUT
  13146. : POLLIN;
  13147. pollres = mg_poll(&pfd, 1, 50, stop_server);
  13148. if (pollres < 0) {
  13149. /* Break if error occured (-1)
  13150. * or server shutdown (-2) */
  13151. break;
  13152. }
  13153. }
  13154. } else if (err == SSL_ERROR_SYSCALL) {
  13155. /* This is an IO error. Look at errno. */
  13156. err = errno;
  13157. mg_cry_internal(conn, "SSL syscall error %i", err);
  13158. break;
  13159. } else {
  13160. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13161. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13162. break;
  13163. }
  13164. ERR_clear_error();
  13165. } else {
  13166. /* success */
  13167. break;
  13168. }
  13169. }
  13170. if (ret != 1) {
  13171. SSL_free(conn->ssl);
  13172. conn->ssl = NULL;
  13173. OPENSSL_REMOVE_THREAD_STATE();
  13174. return 0;
  13175. }
  13176. return 1;
  13177. }
  13178. /* Return OpenSSL error message (from CRYPTO lib) */
  13179. static const char *
  13180. ssl_error(void)
  13181. {
  13182. unsigned long err;
  13183. err = ERR_get_error();
  13184. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13185. }
  13186. static int
  13187. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13188. {
  13189. int i;
  13190. const char hexdigit[] = "0123456789abcdef";
  13191. if ((memlen <= 0) || (buflen <= 0)) {
  13192. return 0;
  13193. }
  13194. if (buflen < (3 * memlen)) {
  13195. return 0;
  13196. }
  13197. for (i = 0; i < memlen; i++) {
  13198. if (i > 0) {
  13199. buf[3 * i - 1] = ' ';
  13200. }
  13201. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13202. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13203. }
  13204. buf[3 * memlen - 1] = 0;
  13205. return 1;
  13206. }
  13207. static void
  13208. ssl_get_client_cert_info(struct mg_connection *conn)
  13209. {
  13210. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13211. if (cert) {
  13212. char str_subject[1024];
  13213. char str_issuer[1024];
  13214. char str_finger[1024];
  13215. unsigned char buf[256];
  13216. char *str_serial = NULL;
  13217. unsigned int ulen;
  13218. int ilen;
  13219. unsigned char *tmp_buf;
  13220. unsigned char *tmp_p;
  13221. /* Handle to algorithm used for fingerprint */
  13222. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13223. /* Get Subject and issuer */
  13224. X509_NAME *subj = X509_get_subject_name(cert);
  13225. X509_NAME *iss = X509_get_issuer_name(cert);
  13226. /* Get serial number */
  13227. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13228. /* Translate serial number to a hex string */
  13229. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13230. str_serial = BN_bn2hex(serial_bn);
  13231. BN_free(serial_bn);
  13232. /* Translate subject and issuer to a string */
  13233. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13234. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13235. /* Calculate SHA1 fingerprint and store as a hex string */
  13236. ulen = 0;
  13237. /* ASN1_digest is deprecated. Do the calculation manually,
  13238. * using EVP_Digest. */
  13239. ilen = i2d_X509(cert, NULL);
  13240. tmp_buf = (ilen > 0)
  13241. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13242. conn->phys_ctx)
  13243. : NULL;
  13244. if (tmp_buf) {
  13245. tmp_p = tmp_buf;
  13246. (void)i2d_X509(cert, &tmp_p);
  13247. if (!EVP_Digest(
  13248. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13249. ulen = 0;
  13250. }
  13251. mg_free(tmp_buf);
  13252. }
  13253. if (!hexdump2string(
  13254. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13255. *str_finger = 0;
  13256. }
  13257. conn->request_info.client_cert = (struct mg_client_cert *)
  13258. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13259. if (conn->request_info.client_cert) {
  13260. conn->request_info.client_cert->peer_cert = (void *)cert;
  13261. conn->request_info.client_cert->subject =
  13262. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13263. conn->request_info.client_cert->issuer =
  13264. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13265. conn->request_info.client_cert->serial =
  13266. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13267. conn->request_info.client_cert->finger =
  13268. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13269. } else {
  13270. mg_cry_internal(conn,
  13271. "%s",
  13272. "Out of memory: Cannot allocate memory for client "
  13273. "certificate");
  13274. }
  13275. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13276. * see https://linux.die.net/man/3/bn_bn2hex */
  13277. OPENSSL_free(str_serial);
  13278. }
  13279. }
  13280. #if defined(OPENSSL_API_1_1)
  13281. #else
  13282. static void
  13283. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13284. {
  13285. (void)line;
  13286. (void)file;
  13287. if (mode & 1) {
  13288. /* 1 is CRYPTO_LOCK */
  13289. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13290. } else {
  13291. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13292. }
  13293. }
  13294. #endif /* OPENSSL_API_1_1 */
  13295. #if !defined(NO_SSL_DL)
  13296. static void *
  13297. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13298. {
  13299. union {
  13300. void *p;
  13301. void (*fp)(void);
  13302. } u;
  13303. void *dll_handle;
  13304. struct ssl_func *fp;
  13305. int ok;
  13306. int truncated = 0;
  13307. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13308. mg_snprintf(NULL,
  13309. NULL, /* No truncation check for ebuf */
  13310. ebuf,
  13311. ebuf_len,
  13312. "%s: cannot load %s",
  13313. __func__,
  13314. dll_name);
  13315. return NULL;
  13316. }
  13317. ok = 1;
  13318. for (fp = sw; fp->name != NULL; fp++) {
  13319. #if defined(_WIN32)
  13320. /* GetProcAddress() returns pointer to function */
  13321. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13322. #else
  13323. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13324. * pointers to function pointers. We need to use a union to make a
  13325. * cast. */
  13326. u.p = dlsym(dll_handle, fp->name);
  13327. #endif /* _WIN32 */
  13328. if (u.fp == NULL) {
  13329. if (ok) {
  13330. mg_snprintf(NULL,
  13331. &truncated,
  13332. ebuf,
  13333. ebuf_len,
  13334. "%s: %s: cannot find %s",
  13335. __func__,
  13336. dll_name,
  13337. fp->name);
  13338. ok = 0;
  13339. } else {
  13340. size_t cur_len = strlen(ebuf);
  13341. if (!truncated) {
  13342. mg_snprintf(NULL,
  13343. &truncated,
  13344. ebuf + cur_len,
  13345. ebuf_len - cur_len - 3,
  13346. ", %s",
  13347. fp->name);
  13348. if (truncated) {
  13349. /* If truncated, add "..." */
  13350. strcat(ebuf, "...");
  13351. }
  13352. }
  13353. }
  13354. /* Debug:
  13355. * printf("Missing function: %s\n", fp->name); */
  13356. } else {
  13357. fp->ptr = u.fp;
  13358. }
  13359. }
  13360. if (!ok) {
  13361. (void)dlclose(dll_handle);
  13362. return NULL;
  13363. }
  13364. return dll_handle;
  13365. }
  13366. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13367. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13368. #endif /* NO_SSL_DL */
  13369. #if defined(SSL_ALREADY_INITIALIZED)
  13370. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13371. #else
  13372. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13373. #endif
  13374. static int
  13375. initialize_ssl(char *ebuf, size_t ebuf_len)
  13376. {
  13377. #if defined(OPENSSL_API_1_1)
  13378. if (ebuf_len > 0) {
  13379. ebuf[0] = 0;
  13380. }
  13381. #if !defined(NO_SSL_DL)
  13382. if (!cryptolib_dll_handle) {
  13383. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13384. if (!cryptolib_dll_handle) {
  13385. mg_snprintf(NULL,
  13386. NULL, /* No truncation check for ebuf */
  13387. ebuf,
  13388. ebuf_len,
  13389. "%s: error loading library %s",
  13390. __func__,
  13391. CRYPTO_LIB);
  13392. DEBUG_TRACE("%s", ebuf);
  13393. return 0;
  13394. }
  13395. }
  13396. #endif /* NO_SSL_DL */
  13397. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13398. return 1;
  13399. }
  13400. #else /* not OPENSSL_API_1_1 */
  13401. int i, num_locks;
  13402. size_t size;
  13403. if (ebuf_len > 0) {
  13404. ebuf[0] = 0;
  13405. }
  13406. #if !defined(NO_SSL_DL)
  13407. if (!cryptolib_dll_handle) {
  13408. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13409. if (!cryptolib_dll_handle) {
  13410. mg_snprintf(NULL,
  13411. NULL, /* No truncation check for ebuf */
  13412. ebuf,
  13413. ebuf_len,
  13414. "%s: error loading library %s",
  13415. __func__,
  13416. CRYPTO_LIB);
  13417. DEBUG_TRACE("%s", ebuf);
  13418. return 0;
  13419. }
  13420. }
  13421. #endif /* NO_SSL_DL */
  13422. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13423. return 1;
  13424. }
  13425. /* Initialize locking callbacks, needed for thread safety.
  13426. * http://www.openssl.org/support/faq.html#PROG1
  13427. */
  13428. num_locks = CRYPTO_num_locks();
  13429. if (num_locks < 0) {
  13430. num_locks = 0;
  13431. }
  13432. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13433. /* allocate mutex array, if required */
  13434. if (num_locks == 0) {
  13435. /* No mutex array required */
  13436. ssl_mutexes = NULL;
  13437. } else {
  13438. /* Mutex array required - allocate it */
  13439. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13440. /* Check OOM */
  13441. if (ssl_mutexes == NULL) {
  13442. mg_snprintf(NULL,
  13443. NULL, /* No truncation check for ebuf */
  13444. ebuf,
  13445. ebuf_len,
  13446. "%s: cannot allocate mutexes: %s",
  13447. __func__,
  13448. ssl_error());
  13449. DEBUG_TRACE("%s", ebuf);
  13450. return 0;
  13451. }
  13452. /* initialize mutex array */
  13453. for (i = 0; i < num_locks; i++) {
  13454. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13455. mg_snprintf(NULL,
  13456. NULL, /* No truncation check for ebuf */
  13457. ebuf,
  13458. ebuf_len,
  13459. "%s: error initializing mutex %i of %i",
  13460. __func__,
  13461. i,
  13462. num_locks);
  13463. DEBUG_TRACE("%s", ebuf);
  13464. mg_free(ssl_mutexes);
  13465. return 0;
  13466. }
  13467. }
  13468. }
  13469. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13470. CRYPTO_set_id_callback(&mg_current_thread_id);
  13471. #endif /* OPENSSL_API_1_1 */
  13472. #if !defined(NO_SSL_DL)
  13473. if (!ssllib_dll_handle) {
  13474. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13475. if (!ssllib_dll_handle) {
  13476. #if !defined(OPENSSL_API_1_1)
  13477. mg_free(ssl_mutexes);
  13478. #endif
  13479. DEBUG_TRACE("%s", ebuf);
  13480. return 0;
  13481. }
  13482. }
  13483. #endif /* NO_SSL_DL */
  13484. #if defined(OPENSSL_API_1_1)
  13485. /* Initialize SSL library */
  13486. OPENSSL_init_ssl(0, NULL);
  13487. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13488. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13489. NULL);
  13490. #else
  13491. /* Initialize SSL library */
  13492. SSL_library_init();
  13493. SSL_load_error_strings();
  13494. #endif
  13495. return 1;
  13496. }
  13497. static int
  13498. ssl_use_pem_file(struct mg_context *phys_ctx,
  13499. struct mg_domain_context *dom_ctx,
  13500. const char *pem,
  13501. const char *chain)
  13502. {
  13503. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13504. mg_cry_ctx_internal(phys_ctx,
  13505. "%s: cannot open certificate file %s: %s",
  13506. __func__,
  13507. pem,
  13508. ssl_error());
  13509. return 0;
  13510. }
  13511. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13512. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13513. mg_cry_ctx_internal(phys_ctx,
  13514. "%s: cannot open private key file %s: %s",
  13515. __func__,
  13516. pem,
  13517. ssl_error());
  13518. return 0;
  13519. }
  13520. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13521. mg_cry_ctx_internal(phys_ctx,
  13522. "%s: certificate and private key do not match: %s",
  13523. __func__,
  13524. pem);
  13525. return 0;
  13526. }
  13527. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13528. * chain files that contain private keys and certificates in
  13529. * SSL_CTX_use_certificate_chain_file.
  13530. * The CivetWeb-Server used pem-Files that contained both information.
  13531. * In order to make wolfSSL work, it is split in two files.
  13532. * One file that contains key and certificate used by the server and
  13533. * an optional chain file for the ssl stack.
  13534. */
  13535. if (chain) {
  13536. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13537. mg_cry_ctx_internal(phys_ctx,
  13538. "%s: cannot use certificate chain file %s: %s",
  13539. __func__,
  13540. chain,
  13541. ssl_error());
  13542. return 0;
  13543. }
  13544. }
  13545. return 1;
  13546. }
  13547. #if defined(OPENSSL_API_1_1)
  13548. static unsigned long
  13549. ssl_get_protocol(int version_id)
  13550. {
  13551. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13552. if (version_id > 0)
  13553. ret |= SSL_OP_NO_SSLv2;
  13554. if (version_id > 1)
  13555. ret |= SSL_OP_NO_SSLv3;
  13556. if (version_id > 2)
  13557. ret |= SSL_OP_NO_TLSv1;
  13558. if (version_id > 3)
  13559. ret |= SSL_OP_NO_TLSv1_1;
  13560. if (version_id > 4)
  13561. ret |= SSL_OP_NO_TLSv1_2;
  13562. #if defined(SSL_OP_NO_TLSv1_3)
  13563. if (version_id > 5)
  13564. ret |= SSL_OP_NO_TLSv1_3;
  13565. #endif
  13566. return ret;
  13567. }
  13568. #else
  13569. static long
  13570. ssl_get_protocol(int version_id)
  13571. {
  13572. long ret = (long)SSL_OP_ALL;
  13573. if (version_id > 0)
  13574. ret |= SSL_OP_NO_SSLv2;
  13575. if (version_id > 1)
  13576. ret |= SSL_OP_NO_SSLv3;
  13577. if (version_id > 2)
  13578. ret |= SSL_OP_NO_TLSv1;
  13579. if (version_id > 3)
  13580. ret |= SSL_OP_NO_TLSv1_1;
  13581. if (version_id > 4)
  13582. ret |= SSL_OP_NO_TLSv1_2;
  13583. #if defined(SSL_OP_NO_TLSv1_3)
  13584. if (version_id > 5)
  13585. ret |= SSL_OP_NO_TLSv1_3;
  13586. #endif
  13587. return ret;
  13588. }
  13589. #endif /* OPENSSL_API_1_1 */
  13590. /* SSL callback documentation:
  13591. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13592. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13593. * https://linux.die.net/man/3/ssl_set_info_callback */
  13594. /* Note: There is no "const" for the first argument in the documentation
  13595. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13596. * / OpenSSL compatibility layers have it. Having a different definition will
  13597. * cause a warning in C and an error in C++. Use "const SSL *", while
  13598. * automatical conversion from "SSL *" works for all compilers, but not other
  13599. * way around */
  13600. static void
  13601. ssl_info_callback(const SSL *ssl, int what, int ret)
  13602. {
  13603. (void)ret;
  13604. if (what & SSL_CB_HANDSHAKE_START) {
  13605. SSL_get_app_data(ssl);
  13606. }
  13607. if (what & SSL_CB_HANDSHAKE_DONE) {
  13608. /* TODO: check for openSSL 1.1 */
  13609. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13610. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13611. }
  13612. }
  13613. static int
  13614. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13615. {
  13616. struct mg_context *ctx = (struct mg_context *)arg;
  13617. struct mg_domain_context *dom =
  13618. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13619. #if defined(GCC_DIAGNOSTIC)
  13620. #pragma GCC diagnostic push
  13621. #pragma GCC diagnostic ignored "-Wcast-align"
  13622. #endif /* defined(GCC_DIAGNOSTIC) */
  13623. /* We used an aligned pointer in SSL_set_app_data */
  13624. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13625. #if defined(GCC_DIAGNOSTIC)
  13626. #pragma GCC diagnostic pop
  13627. #endif /* defined(GCC_DIAGNOSTIC) */
  13628. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13629. (void)ad;
  13630. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13631. DEBUG_TRACE("%s", "internal error - assertion failed");
  13632. return SSL_TLSEXT_ERR_NOACK;
  13633. }
  13634. /* Old clients (Win XP) will not support SNI. Then, there
  13635. * is no server name available in the request - we can
  13636. * only work with the default certificate.
  13637. * Multiple HTTPS hosts on one IP+port are only possible
  13638. * with a certificate containing all alternative names.
  13639. */
  13640. if ((servername == NULL) || (*servername == 0)) {
  13641. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13642. conn->dom_ctx = &(ctx->dd);
  13643. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13644. return SSL_TLSEXT_ERR_NOACK;
  13645. }
  13646. DEBUG_TRACE("TLS connection to host %s", servername);
  13647. while (dom) {
  13648. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13649. /* Found matching domain */
  13650. DEBUG_TRACE("TLS domain %s found",
  13651. dom->config[AUTHENTICATION_DOMAIN]);
  13652. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13653. conn->dom_ctx = dom;
  13654. return SSL_TLSEXT_ERR_OK;
  13655. }
  13656. dom = dom->next;
  13657. }
  13658. /* Default domain */
  13659. DEBUG_TRACE("TLS default domain %s used",
  13660. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13661. conn->dom_ctx = &(ctx->dd);
  13662. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13663. return SSL_TLSEXT_ERR_OK;
  13664. }
  13665. /* Setup SSL CTX as required by CivetWeb */
  13666. static int
  13667. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13668. struct mg_domain_context *dom_ctx,
  13669. const char *pem,
  13670. const char *chain)
  13671. {
  13672. int callback_ret;
  13673. int should_verify_peer;
  13674. int peer_certificate_optional;
  13675. const char *ca_path;
  13676. const char *ca_file;
  13677. int use_default_verify_paths;
  13678. int verify_depth;
  13679. struct timespec now_mt;
  13680. md5_byte_t ssl_context_id[16];
  13681. md5_state_t md5state;
  13682. int protocol_ver;
  13683. #if defined(OPENSSL_API_1_1)
  13684. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13685. mg_cry_ctx_internal(phys_ctx,
  13686. "SSL_CTX_new (server) error: %s",
  13687. ssl_error());
  13688. return 0;
  13689. }
  13690. #else
  13691. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13692. mg_cry_ctx_internal(phys_ctx,
  13693. "SSL_CTX_new (server) error: %s",
  13694. ssl_error());
  13695. return 0;
  13696. }
  13697. #endif /* OPENSSL_API_1_1 */
  13698. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13699. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13700. | SSL_OP_NO_TLSv1_1);
  13701. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13702. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13703. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13704. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13705. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13706. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13707. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13708. #if defined(SSL_OP_NO_RENEGOTIATION)
  13709. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  13710. #endif
  13711. #if !defined(NO_SSL_DL)
  13712. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13713. #endif /* NO_SSL_DL */
  13714. /* In SSL documentation examples callback defined without const specifier
  13715. * 'void (*)(SSL *, int, int)' See:
  13716. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13717. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13718. * But in the source code const SSL is used:
  13719. * 'void (*)(const SSL *, int, int)' See:
  13720. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13721. * Problem about wrong documentation described, but not resolved:
  13722. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13723. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13724. * But when compiled with modern C++ compiler, correct const should be
  13725. * provided
  13726. */
  13727. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13728. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13729. ssl_servername_callback);
  13730. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13731. /* If a callback has been specified, call it. */
  13732. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13733. ? 0
  13734. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13735. phys_ctx->user_data));
  13736. /* If callback returns 0, civetweb sets up the SSL certificate.
  13737. * If it returns 1, civetweb assumes the calback already did this.
  13738. * If it returns -1, initializing ssl fails. */
  13739. if (callback_ret < 0) {
  13740. mg_cry_ctx_internal(phys_ctx,
  13741. "SSL callback returned error: %i",
  13742. callback_ret);
  13743. return 0;
  13744. }
  13745. if (callback_ret > 0) {
  13746. /* Callback did everything. */
  13747. return 1;
  13748. }
  13749. /* Use some combination of start time, domain and port as a SSL
  13750. * context ID. This should be unique on the current machine. */
  13751. md5_init(&md5state);
  13752. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13753. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13754. md5_append(&md5state,
  13755. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13756. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13757. md5_append(&md5state,
  13758. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13759. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13760. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13761. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13762. md5_finish(&md5state, ssl_context_id);
  13763. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13764. (unsigned char *)ssl_context_id,
  13765. sizeof(ssl_context_id));
  13766. if (pem != NULL) {
  13767. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13768. return 0;
  13769. }
  13770. }
  13771. /* Should we support client certificates? */
  13772. /* Default is "no". */
  13773. should_verify_peer = 0;
  13774. peer_certificate_optional = 0;
  13775. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13776. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13777. /* Yes, they are mandatory */
  13778. should_verify_peer = 1;
  13779. peer_certificate_optional = 0;
  13780. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13781. "optional")
  13782. == 0) {
  13783. /* Yes, they are optional */
  13784. should_verify_peer = 1;
  13785. peer_certificate_optional = 1;
  13786. }
  13787. }
  13788. use_default_verify_paths =
  13789. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13790. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13791. == 0);
  13792. if (should_verify_peer) {
  13793. ca_path = dom_ctx->config[SSL_CA_PATH];
  13794. ca_file = dom_ctx->config[SSL_CA_FILE];
  13795. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13796. != 1) {
  13797. mg_cry_ctx_internal(phys_ctx,
  13798. "SSL_CTX_load_verify_locations error: %s "
  13799. "ssl_verify_peer requires setting "
  13800. "either ssl_ca_path or ssl_ca_file. "
  13801. "Is any of them present in the "
  13802. ".conf file?",
  13803. ssl_error());
  13804. return 0;
  13805. }
  13806. if (peer_certificate_optional) {
  13807. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13808. } else {
  13809. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13810. SSL_VERIFY_PEER
  13811. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13812. NULL);
  13813. }
  13814. if (use_default_verify_paths
  13815. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13816. mg_cry_ctx_internal(phys_ctx,
  13817. "SSL_CTX_set_default_verify_paths error: %s",
  13818. ssl_error());
  13819. return 0;
  13820. }
  13821. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13822. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13823. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13824. }
  13825. }
  13826. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13827. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13828. dom_ctx->config[SSL_CIPHER_LIST])
  13829. != 1) {
  13830. mg_cry_ctx_internal(phys_ctx,
  13831. "SSL_CTX_set_cipher_list error: %s",
  13832. ssl_error());
  13833. }
  13834. }
  13835. return 1;
  13836. }
  13837. /* Check if SSL is required.
  13838. * If so, dynamically load SSL library
  13839. * and set up ctx->ssl_ctx pointer. */
  13840. static int
  13841. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13842. {
  13843. void *ssl_ctx = 0;
  13844. int callback_ret;
  13845. const char *pem;
  13846. const char *chain;
  13847. char ebuf[128];
  13848. if (!phys_ctx) {
  13849. return 0;
  13850. }
  13851. if (!dom_ctx) {
  13852. dom_ctx = &(phys_ctx->dd);
  13853. }
  13854. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13855. /* No SSL port is set. No need to setup SSL. */
  13856. return 1;
  13857. }
  13858. /* Check for external SSL_CTX */
  13859. callback_ret =
  13860. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13861. ? 0
  13862. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13863. phys_ctx->user_data));
  13864. if (callback_ret < 0) {
  13865. mg_cry_ctx_internal(phys_ctx,
  13866. "external_ssl_ctx callback returned error: %i",
  13867. callback_ret);
  13868. return 0;
  13869. } else if (callback_ret > 0) {
  13870. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13871. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13872. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  13873. return 0;
  13874. }
  13875. return 1;
  13876. }
  13877. /* else: external_ssl_ctx does not exist or returns 0,
  13878. * CivetWeb should continue initializing SSL */
  13879. /* If PEM file is not specified and the init_ssl callback
  13880. * is not specified, setup will fail. */
  13881. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13882. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13883. /* No certificate and no callback:
  13884. * Essential data to set up TLS is missing.
  13885. */
  13886. mg_cry_ctx_internal(phys_ctx,
  13887. "Initializing SSL failed: -%s is not set",
  13888. config_options[SSL_CERTIFICATE].name);
  13889. return 0;
  13890. }
  13891. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13892. if (chain == NULL) {
  13893. chain = pem;
  13894. }
  13895. if ((chain != NULL) && (*chain == 0)) {
  13896. chain = NULL;
  13897. }
  13898. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13899. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  13900. return 0;
  13901. }
  13902. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13903. }
  13904. static void
  13905. uninitialize_ssl(void)
  13906. {
  13907. #if defined(OPENSSL_API_1_1)
  13908. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13909. /* Shutdown according to
  13910. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13911. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13912. */
  13913. CONF_modules_unload(1);
  13914. #else
  13915. int i;
  13916. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13917. /* Shutdown according to
  13918. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13919. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13920. */
  13921. CRYPTO_set_locking_callback(NULL);
  13922. CRYPTO_set_id_callback(NULL);
  13923. ENGINE_cleanup();
  13924. CONF_modules_unload(1);
  13925. ERR_free_strings();
  13926. EVP_cleanup();
  13927. CRYPTO_cleanup_all_ex_data();
  13928. OPENSSL_REMOVE_THREAD_STATE();
  13929. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13930. pthread_mutex_destroy(&ssl_mutexes[i]);
  13931. }
  13932. mg_free(ssl_mutexes);
  13933. ssl_mutexes = NULL;
  13934. #endif /* OPENSSL_API_1_1 */
  13935. }
  13936. }
  13937. #endif /* !NO_SSL */
  13938. #if !defined(NO_FILESYSTEMS)
  13939. static int
  13940. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13941. {
  13942. if (phys_ctx) {
  13943. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13944. const char *path;
  13945. struct mg_connection fc;
  13946. if (!dom_ctx) {
  13947. dom_ctx = &(phys_ctx->dd);
  13948. }
  13949. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13950. if ((path != NULL)
  13951. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  13952. mg_cry_ctx_internal(phys_ctx,
  13953. "Cannot open %s: %s",
  13954. path,
  13955. strerror(ERRNO));
  13956. return 0;
  13957. }
  13958. return 1;
  13959. }
  13960. return 0;
  13961. }
  13962. #endif /* NO_FILESYSTEMS */
  13963. static int
  13964. set_acl_option(struct mg_context *phys_ctx)
  13965. {
  13966. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13967. }
  13968. static void
  13969. reset_per_request_attributes(struct mg_connection *conn)
  13970. {
  13971. if (!conn) {
  13972. return;
  13973. }
  13974. conn->connection_type =
  13975. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13976. conn->num_bytes_sent = conn->consumed_content = 0;
  13977. conn->path_info = NULL;
  13978. conn->status_code = -1;
  13979. conn->content_len = -1;
  13980. conn->is_chunked = 0;
  13981. conn->must_close = 0;
  13982. conn->request_len = 0;
  13983. conn->throttle = 0;
  13984. conn->accept_gzip = 0;
  13985. conn->response_info.content_length = conn->request_info.content_length = -1;
  13986. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13987. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13988. conn->response_info.status_text = NULL;
  13989. conn->response_info.status_code = 0;
  13990. conn->request_info.remote_user = NULL;
  13991. conn->request_info.request_method = NULL;
  13992. conn->request_info.request_uri = NULL;
  13993. conn->request_info.local_uri = NULL;
  13994. #if defined(MG_LEGACY_INTERFACE)
  13995. /* Legacy before split into local_uri and request_uri */
  13996. conn->request_info.uri = NULL;
  13997. #endif
  13998. }
  13999. static int
  14000. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  14001. {
  14002. if (setsockopt(sock,
  14003. IPPROTO_TCP,
  14004. TCP_NODELAY,
  14005. (SOCK_OPT_TYPE)&nodelay_on,
  14006. sizeof(nodelay_on))
  14007. != 0) {
  14008. /* Error */
  14009. return 1;
  14010. }
  14011. /* OK */
  14012. return 0;
  14013. }
  14014. #if !defined(__ZEPHYR__)
  14015. static void
  14016. close_socket_gracefully(struct mg_connection *conn)
  14017. {
  14018. #if defined(_WIN32)
  14019. char buf[MG_BUF_LEN];
  14020. int n;
  14021. #endif
  14022. struct linger linger;
  14023. int error_code = 0;
  14024. int linger_timeout = -2;
  14025. socklen_t opt_len = sizeof(error_code);
  14026. if (!conn) {
  14027. return;
  14028. }
  14029. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14030. * "Note that enabling a nonzero timeout on a nonblocking socket
  14031. * is not recommended.", so set it to blocking now */
  14032. set_blocking_mode(conn->client.sock);
  14033. /* Send FIN to the client */
  14034. shutdown(conn->client.sock, SHUTDOWN_WR);
  14035. #if defined(_WIN32)
  14036. /* Read and discard pending incoming data. If we do not do that and
  14037. * close
  14038. * the socket, the data in the send buffer may be discarded. This
  14039. * behaviour is seen on Windows, when client keeps sending data
  14040. * when server decides to close the connection; then when client
  14041. * does recv() it gets no data back. */
  14042. do {
  14043. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14044. } while (n > 0);
  14045. #endif
  14046. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14047. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14048. }
  14049. /* Set linger option according to configuration */
  14050. if (linger_timeout >= 0) {
  14051. /* Set linger option to avoid socket hanging out after close. This
  14052. * prevent ephemeral port exhaust problem under high QPS. */
  14053. linger.l_onoff = 1;
  14054. #if defined(_MSC_VER)
  14055. #pragma warning(push)
  14056. #pragma warning(disable : 4244)
  14057. #endif
  14058. #if defined(GCC_DIAGNOSTIC)
  14059. #pragma GCC diagnostic push
  14060. #pragma GCC diagnostic ignored "-Wconversion"
  14061. #endif
  14062. /* Data type of linger structure elements may differ,
  14063. * so we don't know what cast we need here.
  14064. * Disable type conversion warnings. */
  14065. linger.l_linger = (linger_timeout + 999) / 1000;
  14066. #if defined(GCC_DIAGNOSTIC)
  14067. #pragma GCC diagnostic pop
  14068. #endif
  14069. #if defined(_MSC_VER)
  14070. #pragma warning(pop)
  14071. #endif
  14072. } else {
  14073. linger.l_onoff = 0;
  14074. linger.l_linger = 0;
  14075. }
  14076. if (linger_timeout < -1) {
  14077. /* Default: don't configure any linger */
  14078. } else if (getsockopt(conn->client.sock,
  14079. SOL_SOCKET,
  14080. SO_ERROR,
  14081. #if defined(_WIN32) /* WinSock uses different data type here */
  14082. (char *)&error_code,
  14083. #else
  14084. &error_code,
  14085. #endif
  14086. &opt_len)
  14087. != 0) {
  14088. /* Cannot determine if socket is already closed. This should
  14089. * not occur and never did in a test. Log an error message
  14090. * and continue. */
  14091. mg_cry_internal(conn,
  14092. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14093. __func__,
  14094. strerror(ERRNO));
  14095. #if defined(_WIN32)
  14096. } else if (error_code == WSAECONNRESET) {
  14097. #else
  14098. } else if (error_code == ECONNRESET) {
  14099. #endif
  14100. /* Socket already closed by client/peer, close socket without linger
  14101. */
  14102. } else {
  14103. /* Set linger timeout */
  14104. if (setsockopt(conn->client.sock,
  14105. SOL_SOCKET,
  14106. SO_LINGER,
  14107. (char *)&linger,
  14108. sizeof(linger))
  14109. != 0) {
  14110. mg_cry_internal(
  14111. conn,
  14112. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14113. __func__,
  14114. linger.l_onoff,
  14115. linger.l_linger,
  14116. strerror(ERRNO));
  14117. }
  14118. }
  14119. /* Now we know that our FIN is ACK-ed, safe to close */
  14120. closesocket(conn->client.sock);
  14121. conn->client.sock = INVALID_SOCKET;
  14122. }
  14123. #endif
  14124. static void
  14125. close_connection(struct mg_connection *conn)
  14126. {
  14127. #if defined(USE_SERVER_STATS)
  14128. conn->conn_state = 6; /* to close */
  14129. #endif
  14130. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14131. if (conn->lua_websocket_state) {
  14132. lua_websocket_close(conn, conn->lua_websocket_state);
  14133. conn->lua_websocket_state = NULL;
  14134. }
  14135. #endif
  14136. mg_lock_connection(conn);
  14137. /* Set close flag, so keep-alive loops will stop */
  14138. conn->must_close = 1;
  14139. /* call the connection_close callback if assigned */
  14140. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14141. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14142. conn->phys_ctx->callbacks.connection_close(conn);
  14143. }
  14144. }
  14145. /* Reset user data, after close callback is called.
  14146. * Do not reuse it. If the user needs a destructor,
  14147. * it must be done in the connection_close callback. */
  14148. mg_set_user_connection_data(conn, NULL);
  14149. #if defined(USE_SERVER_STATS)
  14150. conn->conn_state = 7; /* closing */
  14151. #endif
  14152. #if !defined(NO_SSL)
  14153. if (conn->ssl != NULL) {
  14154. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14155. */
  14156. SSL_shutdown(conn->ssl);
  14157. SSL_free(conn->ssl);
  14158. OPENSSL_REMOVE_THREAD_STATE();
  14159. conn->ssl = NULL;
  14160. }
  14161. #endif
  14162. if (conn->client.sock != INVALID_SOCKET) {
  14163. #if defined(__ZEPHYR__)
  14164. closesocket(conn->client.sock);
  14165. #else
  14166. close_socket_gracefully(conn);
  14167. #endif
  14168. conn->client.sock = INVALID_SOCKET;
  14169. }
  14170. if (conn->host) {
  14171. mg_free((void *)conn->host);
  14172. conn->host = NULL;
  14173. }
  14174. mg_unlock_connection(conn);
  14175. #if defined(USE_SERVER_STATS)
  14176. conn->conn_state = 8; /* closed */
  14177. #endif
  14178. }
  14179. void
  14180. mg_close_connection(struct mg_connection *conn)
  14181. {
  14182. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14183. return;
  14184. }
  14185. #if defined(USE_WEBSOCKET)
  14186. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14187. if (conn->in_websocket_handling) {
  14188. /* Set close flag, so the server thread can exit. */
  14189. conn->must_close = 1;
  14190. return;
  14191. }
  14192. }
  14193. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14194. unsigned int i;
  14195. /* client context: loops must end */
  14196. conn->phys_ctx->stop_flag = 1;
  14197. conn->must_close = 1;
  14198. /* We need to get the client thread out of the select/recv call
  14199. * here. */
  14200. /* Since we use a sleep quantum of some seconds to check for recv
  14201. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14202. /* join worker thread */
  14203. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14204. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14205. }
  14206. }
  14207. #endif /* defined(USE_WEBSOCKET) */
  14208. close_connection(conn);
  14209. #if !defined(NO_SSL)
  14210. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14211. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14212. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14213. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14214. }
  14215. #endif
  14216. #if defined(USE_WEBSOCKET)
  14217. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14218. mg_free(conn->phys_ctx->worker_threadids);
  14219. (void)pthread_mutex_destroy(&conn->mutex);
  14220. mg_free(conn);
  14221. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14222. mg_free(conn);
  14223. }
  14224. #else
  14225. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14226. mg_free(conn);
  14227. }
  14228. #endif /* defined(USE_WEBSOCKET) */
  14229. }
  14230. static struct mg_connection *
  14231. mg_connect_client_impl(const struct mg_client_options *client_options,
  14232. int use_ssl,
  14233. char *ebuf,
  14234. size_t ebuf_len)
  14235. {
  14236. struct mg_connection *conn = NULL;
  14237. SOCKET sock;
  14238. union usa sa;
  14239. struct sockaddr *psa;
  14240. socklen_t len;
  14241. unsigned max_req_size =
  14242. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14243. /* Size of structures, aligned to 8 bytes */
  14244. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14245. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14246. conn =
  14247. (struct mg_connection *)mg_calloc(1,
  14248. conn_size + ctx_size + max_req_size);
  14249. if (conn == NULL) {
  14250. mg_snprintf(NULL,
  14251. NULL, /* No truncation check for ebuf */
  14252. ebuf,
  14253. ebuf_len,
  14254. "calloc(): %s",
  14255. strerror(ERRNO));
  14256. return NULL;
  14257. }
  14258. #if defined(GCC_DIAGNOSTIC)
  14259. #pragma GCC diagnostic push
  14260. #pragma GCC diagnostic ignored "-Wcast-align"
  14261. #endif /* defined(GCC_DIAGNOSTIC) */
  14262. /* conn_size is aligned to 8 bytes */
  14263. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14264. #if defined(GCC_DIAGNOSTIC)
  14265. #pragma GCC diagnostic pop
  14266. #endif /* defined(GCC_DIAGNOSTIC) */
  14267. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14268. conn->buf_size = (int)max_req_size;
  14269. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14270. conn->dom_ctx = &(conn->phys_ctx->dd);
  14271. if (!connect_socket(conn->phys_ctx,
  14272. client_options->host,
  14273. client_options->port,
  14274. use_ssl,
  14275. ebuf,
  14276. ebuf_len,
  14277. &sock,
  14278. &sa)) {
  14279. /* ebuf is set by connect_socket,
  14280. * free all memory and return NULL; */
  14281. mg_free(conn);
  14282. return NULL;
  14283. }
  14284. #if !defined(NO_SSL)
  14285. #if defined(OPENSSL_API_1_1)
  14286. if (use_ssl
  14287. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14288. == NULL) {
  14289. mg_snprintf(NULL,
  14290. NULL, /* No truncation check for ebuf */
  14291. ebuf,
  14292. ebuf_len,
  14293. "SSL_CTX_new error: %s",
  14294. ssl_error());
  14295. closesocket(sock);
  14296. mg_free(conn);
  14297. return NULL;
  14298. }
  14299. #else
  14300. if (use_ssl
  14301. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14302. == NULL) {
  14303. mg_snprintf(NULL,
  14304. NULL, /* No truncation check for ebuf */
  14305. ebuf,
  14306. ebuf_len,
  14307. "SSL_CTX_new error: %s",
  14308. ssl_error());
  14309. closesocket(sock);
  14310. mg_free(conn);
  14311. return NULL;
  14312. }
  14313. #endif /* OPENSSL_API_1_1 */
  14314. #endif /* NO_SSL */
  14315. #if defined(USE_IPV6)
  14316. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14317. : sizeof(conn->client.rsa.sin6);
  14318. psa = (sa.sa.sa_family == AF_INET)
  14319. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14320. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14321. #else
  14322. len = sizeof(conn->client.rsa.sin);
  14323. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14324. #endif
  14325. conn->client.sock = sock;
  14326. conn->client.lsa = sa;
  14327. if (getsockname(sock, psa, &len) != 0) {
  14328. mg_cry_internal(conn,
  14329. "%s: getsockname() failed: %s",
  14330. __func__,
  14331. strerror(ERRNO));
  14332. }
  14333. conn->client.is_ssl = use_ssl ? 1 : 0;
  14334. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14335. mg_snprintf(NULL,
  14336. NULL, /* No truncation check for ebuf */
  14337. ebuf,
  14338. ebuf_len,
  14339. "Can not create mutex");
  14340. #if !defined(NO_SSL)
  14341. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14342. #endif
  14343. closesocket(sock);
  14344. mg_free(conn);
  14345. return NULL;
  14346. }
  14347. #if !defined(NO_SSL)
  14348. if (use_ssl) {
  14349. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14350. * SSL_CTX_set_verify call is needed to switch off server
  14351. * certificate checking, which is off by default in OpenSSL and
  14352. * on in yaSSL. */
  14353. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14354. * SSL_VERIFY_PEER, verify_ssl_server); */
  14355. if (client_options->client_cert) {
  14356. if (!ssl_use_pem_file(conn->phys_ctx,
  14357. conn->dom_ctx,
  14358. client_options->client_cert,
  14359. NULL)) {
  14360. mg_snprintf(NULL,
  14361. NULL, /* No truncation check for ebuf */
  14362. ebuf,
  14363. ebuf_len,
  14364. "Can not use SSL client certificate");
  14365. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14366. closesocket(sock);
  14367. mg_free(conn);
  14368. return NULL;
  14369. }
  14370. }
  14371. if (client_options->server_cert) {
  14372. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14373. client_options->server_cert,
  14374. NULL)
  14375. != 1) {
  14376. mg_cry_internal(conn,
  14377. "SSL_CTX_load_verify_locations error: %s ",
  14378. ssl_error());
  14379. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14380. closesocket(sock);
  14381. mg_free(conn);
  14382. return NULL;
  14383. }
  14384. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14385. } else {
  14386. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14387. }
  14388. if (!sslize(conn,
  14389. conn->dom_ctx->ssl_ctx,
  14390. SSL_connect,
  14391. &(conn->phys_ctx->stop_flag),
  14392. client_options)) {
  14393. mg_snprintf(NULL,
  14394. NULL, /* No truncation check for ebuf */
  14395. ebuf,
  14396. ebuf_len,
  14397. "SSL connection error");
  14398. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14399. closesocket(sock);
  14400. mg_free(conn);
  14401. return NULL;
  14402. }
  14403. }
  14404. #endif
  14405. return conn;
  14406. }
  14407. CIVETWEB_API struct mg_connection *
  14408. mg_connect_client_secure(const struct mg_client_options *client_options,
  14409. char *error_buffer,
  14410. size_t error_buffer_size)
  14411. {
  14412. return mg_connect_client_impl(client_options,
  14413. 1,
  14414. error_buffer,
  14415. error_buffer_size);
  14416. }
  14417. struct mg_connection *
  14418. mg_connect_client(const char *host,
  14419. int port,
  14420. int use_ssl,
  14421. char *error_buffer,
  14422. size_t error_buffer_size)
  14423. {
  14424. struct mg_client_options opts;
  14425. memset(&opts, 0, sizeof(opts));
  14426. opts.host = host;
  14427. opts.port = port;
  14428. return mg_connect_client_impl(&opts,
  14429. use_ssl,
  14430. error_buffer,
  14431. error_buffer_size);
  14432. }
  14433. static const struct {
  14434. const char *proto;
  14435. size_t proto_len;
  14436. unsigned default_port;
  14437. } abs_uri_protocols[] = {{"http://", 7, 80},
  14438. {"https://", 8, 443},
  14439. {"ws://", 5, 80},
  14440. {"wss://", 6, 443},
  14441. {NULL, 0, 0}};
  14442. /* Check if the uri is valid.
  14443. * return 0 for invalid uri,
  14444. * return 1 for *,
  14445. * return 2 for relative uri,
  14446. * return 3 for absolute uri without port,
  14447. * return 4 for absolute uri with port */
  14448. static int
  14449. get_uri_type(const char *uri)
  14450. {
  14451. int i;
  14452. const char *hostend, *portbegin;
  14453. char *portend;
  14454. unsigned long port;
  14455. /* According to the HTTP standard
  14456. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14457. * URI can be an asterisk (*) or should start with slash (relative uri),
  14458. * or it should start with the protocol (absolute uri). */
  14459. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14460. /* asterisk */
  14461. return 1;
  14462. }
  14463. /* Valid URIs according to RFC 3986
  14464. * (https://www.ietf.org/rfc/rfc3986.txt)
  14465. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14466. * and unreserved characters A-Z a-z 0-9 and -._~
  14467. * and % encoded symbols.
  14468. */
  14469. for (i = 0; uri[i] != 0; i++) {
  14470. if (uri[i] < 33) {
  14471. /* control characters and spaces are invalid */
  14472. return 0;
  14473. }
  14474. if (uri[i] > 126) {
  14475. /* non-ascii characters must be % encoded */
  14476. return 0;
  14477. } else {
  14478. switch (uri[i]) {
  14479. case '"': /* 34 */
  14480. case '<': /* 60 */
  14481. case '>': /* 62 */
  14482. case '\\': /* 92 */
  14483. case '^': /* 94 */
  14484. case '`': /* 96 */
  14485. case '{': /* 123 */
  14486. case '|': /* 124 */
  14487. case '}': /* 125 */
  14488. return 0;
  14489. default:
  14490. /* character is ok */
  14491. break;
  14492. }
  14493. }
  14494. }
  14495. /* A relative uri starts with a / character */
  14496. if (uri[0] == '/') {
  14497. /* relative uri */
  14498. return 2;
  14499. }
  14500. /* It could be an absolute uri: */
  14501. /* This function only checks if the uri is valid, not if it is
  14502. * addressing the current server. So civetweb can also be used
  14503. * as a proxy server. */
  14504. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14505. if (mg_strncasecmp(uri,
  14506. abs_uri_protocols[i].proto,
  14507. abs_uri_protocols[i].proto_len)
  14508. == 0) {
  14509. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14510. if (!hostend) {
  14511. return 0;
  14512. }
  14513. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14514. if (!portbegin) {
  14515. return 3;
  14516. }
  14517. port = strtoul(portbegin + 1, &portend, 10);
  14518. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14519. return 0;
  14520. }
  14521. return 4;
  14522. }
  14523. }
  14524. return 0;
  14525. }
  14526. /* Return NULL or the relative uri at the current server */
  14527. static const char *
  14528. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14529. {
  14530. const char *server_domain;
  14531. size_t server_domain_len;
  14532. size_t request_domain_len = 0;
  14533. unsigned long port = 0;
  14534. int i, auth_domain_check_enabled;
  14535. const char *hostbegin = NULL;
  14536. const char *hostend = NULL;
  14537. const char *portbegin;
  14538. char *portend;
  14539. auth_domain_check_enabled =
  14540. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14541. /* DNS is case insensitive, so use case insensitive string compare here
  14542. */
  14543. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14544. if (mg_strncasecmp(uri,
  14545. abs_uri_protocols[i].proto,
  14546. abs_uri_protocols[i].proto_len)
  14547. == 0) {
  14548. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14549. hostend = strchr(hostbegin, '/');
  14550. if (!hostend) {
  14551. return 0;
  14552. }
  14553. portbegin = strchr(hostbegin, ':');
  14554. if ((!portbegin) || (portbegin > hostend)) {
  14555. port = abs_uri_protocols[i].default_port;
  14556. request_domain_len = (size_t)(hostend - hostbegin);
  14557. } else {
  14558. port = strtoul(portbegin + 1, &portend, 10);
  14559. if ((portend != hostend) || (port <= 0)
  14560. || !is_valid_port(port)) {
  14561. return 0;
  14562. }
  14563. request_domain_len = (size_t)(portbegin - hostbegin);
  14564. }
  14565. /* protocol found, port set */
  14566. break;
  14567. }
  14568. }
  14569. if (!port) {
  14570. /* port remains 0 if the protocol is not found */
  14571. return 0;
  14572. }
  14573. /* Check if the request is directed to a different server. */
  14574. /* First check if the port is the same (IPv4 and IPv6). */
  14575. #if defined(USE_IPV6)
  14576. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14577. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14578. /* Request is directed to a different port */
  14579. return 0;
  14580. }
  14581. } else
  14582. #endif
  14583. {
  14584. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14585. /* Request is directed to a different port */
  14586. return 0;
  14587. }
  14588. }
  14589. /* Finally check if the server corresponds to the authentication
  14590. * domain of the server (the server domain).
  14591. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14592. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14593. * but do not allow substrings (like
  14594. * http://notmydomain.com/path/file.ext
  14595. * or http://mydomain.com.fake/path/file.ext).
  14596. */
  14597. if (auth_domain_check_enabled) {
  14598. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14599. server_domain_len = strlen(server_domain);
  14600. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14601. return 0;
  14602. }
  14603. if ((request_domain_len == server_domain_len)
  14604. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14605. /* Request is directed to this server - full name match. */
  14606. } else {
  14607. if (request_domain_len < (server_domain_len + 2)) {
  14608. /* Request is directed to another server: The server name
  14609. * is longer than the request name.
  14610. * Drop this case here to avoid overflows in the
  14611. * following checks. */
  14612. return 0;
  14613. }
  14614. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14615. /* Request is directed to another server: It could be a
  14616. * substring
  14617. * like notmyserver.com */
  14618. return 0;
  14619. }
  14620. if (0
  14621. != memcmp(server_domain,
  14622. hostbegin + request_domain_len - server_domain_len,
  14623. server_domain_len)) {
  14624. /* Request is directed to another server:
  14625. * The server name is different. */
  14626. return 0;
  14627. }
  14628. }
  14629. }
  14630. return hostend;
  14631. }
  14632. static int
  14633. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14634. {
  14635. if (ebuf_len > 0) {
  14636. ebuf[0] = '\0';
  14637. }
  14638. *err = 0;
  14639. reset_per_request_attributes(conn);
  14640. if (!conn) {
  14641. mg_snprintf(conn,
  14642. NULL, /* No truncation check for ebuf */
  14643. ebuf,
  14644. ebuf_len,
  14645. "%s",
  14646. "Internal error");
  14647. *err = 500;
  14648. return 0;
  14649. }
  14650. /* Set the time the request was received. This value should be used for
  14651. * timeouts. */
  14652. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14653. conn->request_len =
  14654. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14655. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14656. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14657. mg_snprintf(conn,
  14658. NULL, /* No truncation check for ebuf */
  14659. ebuf,
  14660. ebuf_len,
  14661. "%s",
  14662. "Invalid message size");
  14663. *err = 500;
  14664. return 0;
  14665. }
  14666. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14667. mg_snprintf(conn,
  14668. NULL, /* No truncation check for ebuf */
  14669. ebuf,
  14670. ebuf_len,
  14671. "%s",
  14672. "Message too large");
  14673. *err = 413;
  14674. return 0;
  14675. }
  14676. if (conn->request_len <= 0) {
  14677. if (conn->data_len > 0) {
  14678. mg_snprintf(conn,
  14679. NULL, /* No truncation check for ebuf */
  14680. ebuf,
  14681. ebuf_len,
  14682. "%s",
  14683. "Malformed message");
  14684. *err = 400;
  14685. } else {
  14686. /* Server did not recv anything -> just close the connection */
  14687. conn->must_close = 1;
  14688. mg_snprintf(conn,
  14689. NULL, /* No truncation check for ebuf */
  14690. ebuf,
  14691. ebuf_len,
  14692. "%s",
  14693. "No data received");
  14694. *err = 0;
  14695. }
  14696. return 0;
  14697. }
  14698. return 1;
  14699. }
  14700. static int
  14701. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14702. {
  14703. const char *cl;
  14704. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14705. return 0;
  14706. }
  14707. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14708. <= 0) {
  14709. mg_snprintf(conn,
  14710. NULL, /* No truncation check for ebuf */
  14711. ebuf,
  14712. ebuf_len,
  14713. "%s",
  14714. "Bad request");
  14715. *err = 400;
  14716. return 0;
  14717. }
  14718. /* Message is a valid request */
  14719. /* Is there a "host" ? */
  14720. if (conn->host != NULL) {
  14721. mg_free((void *)conn->host);
  14722. }
  14723. conn->host = alloc_get_host(conn);
  14724. if (!conn->host) {
  14725. mg_snprintf(conn,
  14726. NULL, /* No truncation check for ebuf */
  14727. ebuf,
  14728. ebuf_len,
  14729. "%s",
  14730. "Bad request: Host mismatch");
  14731. *err = 400;
  14732. return 0;
  14733. }
  14734. if (((cl = get_header(conn->request_info.http_headers,
  14735. conn->request_info.num_headers,
  14736. "Transfer-Encoding"))
  14737. != NULL)
  14738. && mg_strcasecmp(cl, "identity")) {
  14739. if (mg_strcasecmp(cl, "chunked")) {
  14740. mg_snprintf(conn,
  14741. NULL, /* No truncation check for ebuf */
  14742. ebuf,
  14743. ebuf_len,
  14744. "%s",
  14745. "Bad request");
  14746. *err = 400;
  14747. return 0;
  14748. }
  14749. conn->is_chunked = 1;
  14750. conn->content_len = 0; /* not yet read */
  14751. } else if ((cl = get_header(conn->request_info.http_headers,
  14752. conn->request_info.num_headers,
  14753. "Content-Length"))
  14754. != NULL) {
  14755. /* Request has content length set */
  14756. char *endptr = NULL;
  14757. conn->content_len = strtoll(cl, &endptr, 10);
  14758. if ((endptr == cl) || (conn->content_len < 0)) {
  14759. mg_snprintf(conn,
  14760. NULL, /* No truncation check for ebuf */
  14761. ebuf,
  14762. ebuf_len,
  14763. "%s",
  14764. "Bad request");
  14765. *err = 411;
  14766. return 0;
  14767. }
  14768. /* Publish the content length back to the request info. */
  14769. conn->request_info.content_length = conn->content_len;
  14770. } else {
  14771. /* There is no exception, see RFC7230. */
  14772. conn->content_len = 0;
  14773. }
  14774. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14775. return 1;
  14776. }
  14777. /* conn is assumed to be valid in this internal function */
  14778. static int
  14779. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14780. {
  14781. const char *cl;
  14782. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14783. return 0;
  14784. }
  14785. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14786. <= 0) {
  14787. mg_snprintf(conn,
  14788. NULL, /* No truncation check for ebuf */
  14789. ebuf,
  14790. ebuf_len,
  14791. "%s",
  14792. "Bad response");
  14793. *err = 400;
  14794. return 0;
  14795. }
  14796. /* Message is a valid response */
  14797. if (((cl = get_header(conn->response_info.http_headers,
  14798. conn->response_info.num_headers,
  14799. "Transfer-Encoding"))
  14800. != NULL)
  14801. && mg_strcasecmp(cl, "identity")) {
  14802. if (mg_strcasecmp(cl, "chunked")) {
  14803. mg_snprintf(conn,
  14804. NULL, /* No truncation check for ebuf */
  14805. ebuf,
  14806. ebuf_len,
  14807. "%s",
  14808. "Bad request");
  14809. *err = 400;
  14810. return 0;
  14811. }
  14812. conn->is_chunked = 1;
  14813. conn->content_len = 0; /* not yet read */
  14814. } else if ((cl = get_header(conn->response_info.http_headers,
  14815. conn->response_info.num_headers,
  14816. "Content-Length"))
  14817. != NULL) {
  14818. char *endptr = NULL;
  14819. conn->content_len = strtoll(cl, &endptr, 10);
  14820. if ((endptr == cl) || (conn->content_len < 0)) {
  14821. mg_snprintf(conn,
  14822. NULL, /* No truncation check for ebuf */
  14823. ebuf,
  14824. ebuf_len,
  14825. "%s",
  14826. "Bad request");
  14827. *err = 411;
  14828. return 0;
  14829. }
  14830. /* Publish the content length back to the response info. */
  14831. conn->response_info.content_length = conn->content_len;
  14832. /* TODO: check if it is still used in response_info */
  14833. conn->request_info.content_length = conn->content_len;
  14834. /* TODO: we should also consider HEAD method */
  14835. if (conn->response_info.status_code == 304) {
  14836. conn->content_len = 0;
  14837. }
  14838. } else {
  14839. /* TODO: we should also consider HEAD method */
  14840. if (((conn->response_info.status_code >= 100)
  14841. && (conn->response_info.status_code <= 199))
  14842. || (conn->response_info.status_code == 204)
  14843. || (conn->response_info.status_code == 304)) {
  14844. conn->content_len = 0;
  14845. } else {
  14846. conn->content_len = -1; /* unknown content length */
  14847. }
  14848. }
  14849. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14850. return 1;
  14851. }
  14852. int
  14853. mg_get_response(struct mg_connection *conn,
  14854. char *ebuf,
  14855. size_t ebuf_len,
  14856. int timeout)
  14857. {
  14858. int err, ret;
  14859. char txt[32]; /* will not overflow */
  14860. char *save_timeout;
  14861. char *new_timeout;
  14862. if (ebuf_len > 0) {
  14863. ebuf[0] = '\0';
  14864. }
  14865. if (!conn) {
  14866. mg_snprintf(conn,
  14867. NULL, /* No truncation check for ebuf */
  14868. ebuf,
  14869. ebuf_len,
  14870. "%s",
  14871. "Parameter error");
  14872. return -1;
  14873. }
  14874. /* Reset the previous responses */
  14875. conn->data_len = 0;
  14876. /* Implementation of API function for HTTP clients */
  14877. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14878. if (timeout >= 0) {
  14879. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14880. new_timeout = txt;
  14881. } else {
  14882. new_timeout = NULL;
  14883. }
  14884. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14885. ret = get_response(conn, ebuf, ebuf_len, &err);
  14886. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14887. #if defined(MG_LEGACY_INTERFACE)
  14888. /* TODO: 1) uri is deprecated;
  14889. * 2) here, ri.uri is the http response code */
  14890. conn->request_info.uri = conn->request_info.request_uri;
  14891. #endif
  14892. conn->request_info.local_uri = conn->request_info.request_uri;
  14893. /* TODO (mid): Define proper return values - maybe return length?
  14894. * For the first test use <0 for error and >0 for OK */
  14895. return (ret == 0) ? -1 : +1;
  14896. }
  14897. struct mg_connection *
  14898. mg_download(const char *host,
  14899. int port,
  14900. int use_ssl,
  14901. char *ebuf,
  14902. size_t ebuf_len,
  14903. const char *fmt,
  14904. ...)
  14905. {
  14906. struct mg_connection *conn;
  14907. va_list ap;
  14908. int i;
  14909. int reqerr;
  14910. if (ebuf_len > 0) {
  14911. ebuf[0] = '\0';
  14912. }
  14913. va_start(ap, fmt);
  14914. /* open a connection */
  14915. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14916. if (conn != NULL) {
  14917. i = mg_vprintf(conn, fmt, ap);
  14918. if (i <= 0) {
  14919. mg_snprintf(conn,
  14920. NULL, /* No truncation check for ebuf */
  14921. ebuf,
  14922. ebuf_len,
  14923. "%s",
  14924. "Error sending request");
  14925. } else {
  14926. /* make sure the buffer is clear */
  14927. conn->data_len = 0;
  14928. get_response(conn, ebuf, ebuf_len, &reqerr);
  14929. #if defined(MG_LEGACY_INTERFACE)
  14930. /* TODO: 1) uri is deprecated;
  14931. * 2) here, ri.uri is the http response code */
  14932. conn->request_info.uri = conn->request_info.request_uri;
  14933. #endif
  14934. conn->request_info.local_uri = conn->request_info.request_uri;
  14935. }
  14936. }
  14937. /* if an error occurred, close the connection */
  14938. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14939. mg_close_connection(conn);
  14940. conn = NULL;
  14941. }
  14942. va_end(ap);
  14943. return conn;
  14944. }
  14945. struct websocket_client_thread_data {
  14946. struct mg_connection *conn;
  14947. mg_websocket_data_handler data_handler;
  14948. mg_websocket_close_handler close_handler;
  14949. void *callback_data;
  14950. };
  14951. #if defined(USE_WEBSOCKET)
  14952. #if defined(_WIN32)
  14953. static unsigned __stdcall websocket_client_thread(void *data)
  14954. #else
  14955. static void *
  14956. websocket_client_thread(void *data)
  14957. #endif
  14958. {
  14959. struct websocket_client_thread_data *cdata =
  14960. (struct websocket_client_thread_data *)data;
  14961. void *user_thread_ptr = NULL;
  14962. #if !defined(_WIN32)
  14963. struct sigaction sa;
  14964. /* Ignore SIGPIPE */
  14965. memset(&sa, 0, sizeof(sa));
  14966. sa.sa_handler = SIG_IGN;
  14967. sigaction(SIGPIPE, &sa, NULL);
  14968. #endif
  14969. mg_set_thread_name("ws-clnt");
  14970. if (cdata->conn->phys_ctx) {
  14971. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14972. /* 3 indicates a websocket client thread */
  14973. /* TODO: check if conn->phys_ctx can be set */
  14974. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  14975. cdata->conn->phys_ctx, 3);
  14976. }
  14977. }
  14978. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14979. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14980. if (cdata->close_handler != NULL) {
  14981. cdata->close_handler(cdata->conn, cdata->callback_data);
  14982. }
  14983. /* The websocket_client context has only this thread. If it runs out,
  14984. set the stop_flag to 2 (= "stopped"). */
  14985. cdata->conn->phys_ctx->stop_flag = 2;
  14986. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  14987. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  14988. 3,
  14989. user_thread_ptr);
  14990. }
  14991. mg_free((void *)cdata);
  14992. #if defined(_WIN32)
  14993. return 0;
  14994. #else
  14995. return NULL;
  14996. #endif
  14997. }
  14998. #endif
  14999. struct mg_connection *
  15000. mg_connect_websocket_client(const char *host,
  15001. int port,
  15002. int use_ssl,
  15003. char *error_buffer,
  15004. size_t error_buffer_size,
  15005. const char *path,
  15006. const char *origin,
  15007. mg_websocket_data_handler data_func,
  15008. mg_websocket_close_handler close_func,
  15009. void *user_data)
  15010. {
  15011. struct mg_connection *conn = NULL;
  15012. #if defined(USE_WEBSOCKET)
  15013. struct websocket_client_thread_data *thread_data;
  15014. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15015. static const char *handshake_req;
  15016. if (origin != NULL) {
  15017. handshake_req = "GET %s HTTP/1.1\r\n"
  15018. "Host: %s\r\n"
  15019. "Upgrade: websocket\r\n"
  15020. "Connection: Upgrade\r\n"
  15021. "Sec-WebSocket-Key: %s\r\n"
  15022. "Sec-WebSocket-Version: 13\r\n"
  15023. "Origin: %s\r\n"
  15024. "\r\n";
  15025. } else {
  15026. handshake_req = "GET %s HTTP/1.1\r\n"
  15027. "Host: %s\r\n"
  15028. "Upgrade: websocket\r\n"
  15029. "Connection: Upgrade\r\n"
  15030. "Sec-WebSocket-Key: %s\r\n"
  15031. "Sec-WebSocket-Version: 13\r\n"
  15032. "\r\n";
  15033. }
  15034. #if defined(__clang__)
  15035. #pragma clang diagnostic push
  15036. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15037. #endif
  15038. /* Establish the client connection and request upgrade */
  15039. conn = mg_download(host,
  15040. port,
  15041. use_ssl,
  15042. error_buffer,
  15043. error_buffer_size,
  15044. handshake_req,
  15045. path,
  15046. host,
  15047. magic,
  15048. origin);
  15049. #if defined(__clang__)
  15050. #pragma clang diagnostic pop
  15051. #endif
  15052. /* Connection object will be null if something goes wrong */
  15053. if (conn == NULL) {
  15054. if (!*error_buffer) {
  15055. /* There should be already an error message */
  15056. mg_snprintf(conn,
  15057. NULL, /* No truncation check for ebuf */
  15058. error_buffer,
  15059. error_buffer_size,
  15060. "Unexpected error");
  15061. }
  15062. return NULL;
  15063. }
  15064. if (conn->response_info.status_code != 101) {
  15065. /* We sent an "upgrade" request. For a correct websocket
  15066. * protocol handshake, we expect a "101 Continue" response.
  15067. * Otherwise it is a protocol violation. Maybe the HTTP
  15068. * Server does not know websockets. */
  15069. if (!*error_buffer) {
  15070. /* set an error, if not yet set */
  15071. mg_snprintf(conn,
  15072. NULL, /* No truncation check for ebuf */
  15073. error_buffer,
  15074. error_buffer_size,
  15075. "Unexpected server reply");
  15076. }
  15077. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15078. mg_close_connection(conn);
  15079. return NULL;
  15080. }
  15081. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15082. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15083. if (!thread_data) {
  15084. DEBUG_TRACE("%s\r\n", "Out of memory");
  15085. mg_close_connection(conn);
  15086. return NULL;
  15087. }
  15088. thread_data->conn = conn;
  15089. thread_data->data_handler = data_func;
  15090. thread_data->close_handler = close_func;
  15091. thread_data->callback_data = user_data;
  15092. conn->phys_ctx->worker_threadids =
  15093. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15094. if (!conn->phys_ctx->worker_threadids) {
  15095. DEBUG_TRACE("%s\r\n", "Out of memory");
  15096. mg_free(thread_data);
  15097. mg_close_connection(conn);
  15098. return NULL;
  15099. }
  15100. /* Now upgrade to ws/wss client context */
  15101. conn->phys_ctx->user_data = user_data;
  15102. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15103. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15104. /* Start a thread to read the websocket client connection
  15105. * This thread will automatically stop when mg_disconnect is
  15106. * called on the client connection */
  15107. if (mg_start_thread_with_id(websocket_client_thread,
  15108. thread_data,
  15109. conn->phys_ctx->worker_threadids)
  15110. != 0) {
  15111. conn->phys_ctx->cfg_worker_threads = 0;
  15112. mg_free(thread_data);
  15113. mg_close_connection(conn);
  15114. conn = NULL;
  15115. DEBUG_TRACE("%s",
  15116. "Websocket client connect thread could not be started\r\n");
  15117. }
  15118. #else
  15119. /* Appease "unused parameter" warnings */
  15120. (void)host;
  15121. (void)port;
  15122. (void)use_ssl;
  15123. (void)error_buffer;
  15124. (void)error_buffer_size;
  15125. (void)path;
  15126. (void)origin;
  15127. (void)user_data;
  15128. (void)data_func;
  15129. (void)close_func;
  15130. #endif
  15131. return conn;
  15132. }
  15133. /* Prepare connection data structure */
  15134. static void
  15135. init_connection(struct mg_connection *conn)
  15136. {
  15137. /* Is keep alive allowed by the server */
  15138. int keep_alive_enabled =
  15139. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15140. if (!keep_alive_enabled) {
  15141. conn->must_close = 1;
  15142. }
  15143. /* Important: on new connection, reset the receiving buffer. Credit
  15144. * goes to crule42. */
  15145. conn->data_len = 0;
  15146. conn->handled_requests = 0;
  15147. mg_set_user_connection_data(conn, NULL);
  15148. #if defined(USE_SERVER_STATS)
  15149. conn->conn_state = 2; /* init */
  15150. #endif
  15151. /* call the init_connection callback if assigned */
  15152. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15153. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15154. void *conn_data = NULL;
  15155. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15156. mg_set_user_connection_data(conn, conn_data);
  15157. }
  15158. }
  15159. }
  15160. /* Process a connection - may handle multiple requests
  15161. * using the same connection.
  15162. * Must be called with a valid connection (conn and
  15163. * conn->phys_ctx must be valid).
  15164. */
  15165. static void
  15166. process_new_connection(struct mg_connection *conn)
  15167. {
  15168. struct mg_request_info *ri = &conn->request_info;
  15169. int keep_alive, discard_len;
  15170. char ebuf[100];
  15171. const char *hostend;
  15172. int reqerr, uri_type;
  15173. #if defined(USE_SERVER_STATS)
  15174. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15175. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15176. if (mcon > (conn->phys_ctx->max_connections)) {
  15177. /* could use atomic compare exchange, but this
  15178. * seems overkill for statistics data */
  15179. conn->phys_ctx->max_connections = mcon;
  15180. }
  15181. #endif
  15182. init_connection(conn);
  15183. DEBUG_TRACE("Start processing connection from %s",
  15184. conn->request_info.remote_addr);
  15185. /* Loop over multiple requests sent using the same connection
  15186. * (while "keep alive"). */
  15187. do {
  15188. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15189. conn->handled_requests + 1);
  15190. #if defined(USE_SERVER_STATS)
  15191. conn->conn_state = 3; /* ready */
  15192. #endif
  15193. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15194. /* The request sent by the client could not be understood by
  15195. * the server, or it was incomplete or a timeout. Send an
  15196. * error message and close the connection. */
  15197. if (reqerr > 0) {
  15198. DEBUG_ASSERT(ebuf[0] != '\0');
  15199. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15200. }
  15201. } else if (strcmp(ri->http_version, "1.0")
  15202. && strcmp(ri->http_version, "1.1")) {
  15203. mg_snprintf(conn,
  15204. NULL, /* No truncation check for ebuf */
  15205. ebuf,
  15206. sizeof(ebuf),
  15207. "Bad HTTP version: [%s]",
  15208. ri->http_version);
  15209. mg_send_http_error(conn, 505, "%s", ebuf);
  15210. }
  15211. if (ebuf[0] == '\0') {
  15212. uri_type = get_uri_type(conn->request_info.request_uri);
  15213. switch (uri_type) {
  15214. case 1:
  15215. /* Asterisk */
  15216. conn->request_info.local_uri = NULL;
  15217. break;
  15218. case 2:
  15219. /* relative uri */
  15220. conn->request_info.local_uri = conn->request_info.request_uri;
  15221. break;
  15222. case 3:
  15223. case 4:
  15224. /* absolute uri (with/without port) */
  15225. hostend = get_rel_url_at_current_server(
  15226. conn->request_info.request_uri, conn);
  15227. if (hostend) {
  15228. conn->request_info.local_uri = hostend;
  15229. } else {
  15230. conn->request_info.local_uri = NULL;
  15231. }
  15232. break;
  15233. default:
  15234. mg_snprintf(conn,
  15235. NULL, /* No truncation check for ebuf */
  15236. ebuf,
  15237. sizeof(ebuf),
  15238. "Invalid URI");
  15239. mg_send_http_error(conn, 400, "%s", ebuf);
  15240. conn->request_info.local_uri = NULL;
  15241. break;
  15242. }
  15243. #if defined(MG_LEGACY_INTERFACE)
  15244. /* Legacy before split into local_uri and request_uri */
  15245. conn->request_info.uri = conn->request_info.local_uri;
  15246. #endif
  15247. }
  15248. DEBUG_TRACE("http: %s, error: %s",
  15249. (ri->http_version ? ri->http_version : "none"),
  15250. (ebuf[0] ? ebuf : "none"));
  15251. if (ebuf[0] == '\0') {
  15252. if (conn->request_info.local_uri) {
  15253. /* handle request to local server */
  15254. #if defined(USE_SERVER_STATS)
  15255. conn->conn_state = 4; /* processing */
  15256. #endif
  15257. handle_request(conn);
  15258. #if defined(USE_SERVER_STATS)
  15259. conn->conn_state = 5; /* processed */
  15260. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15261. conn->consumed_content);
  15262. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15263. conn->num_bytes_sent);
  15264. #endif
  15265. DEBUG_TRACE("%s", "handle_request done");
  15266. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15267. conn->phys_ctx->callbacks.end_request(conn,
  15268. conn->status_code);
  15269. DEBUG_TRACE("%s", "end_request callback done");
  15270. }
  15271. log_access(conn);
  15272. } else {
  15273. /* TODO: handle non-local request (PROXY) */
  15274. conn->must_close = 1;
  15275. }
  15276. } else {
  15277. conn->must_close = 1;
  15278. }
  15279. if (ri->remote_user != NULL) {
  15280. mg_free((void *)ri->remote_user);
  15281. /* Important! When having connections with and without auth
  15282. * would cause double free and then crash */
  15283. ri->remote_user = NULL;
  15284. }
  15285. /* NOTE(lsm): order is important here. should_keep_alive() call
  15286. * is using parsed request, which will be invalid after
  15287. * memmove's below.
  15288. * Therefore, memorize should_keep_alive() result now for later
  15289. * use in loop exit condition. */
  15290. /* Enable it only if this request is completely discardable. */
  15291. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15292. && (conn->content_len >= 0) && (conn->request_len > 0)
  15293. && ((conn->is_chunked == 4)
  15294. || (!conn->is_chunked
  15295. && ((conn->consumed_content == conn->content_len)
  15296. || ((conn->request_len + conn->content_len)
  15297. <= conn->data_len))));
  15298. if (keep_alive) {
  15299. /* Discard all buffered data for this request */
  15300. discard_len =
  15301. ((conn->request_len + conn->content_len) < conn->data_len)
  15302. ? (int)(conn->request_len + conn->content_len)
  15303. : conn->data_len;
  15304. conn->data_len -= discard_len;
  15305. if (conn->data_len > 0) {
  15306. DEBUG_TRACE("discard_len = %d", discard_len);
  15307. memmove(conn->buf,
  15308. conn->buf + discard_len,
  15309. (size_t)conn->data_len);
  15310. }
  15311. }
  15312. DEBUG_ASSERT(conn->data_len >= 0);
  15313. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15314. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15315. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15316. (long int)conn->data_len,
  15317. (long int)conn->buf_size);
  15318. break;
  15319. }
  15320. conn->handled_requests++;
  15321. } while (keep_alive);
  15322. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15323. conn->request_info.remote_addr,
  15324. difftime(time(NULL), conn->conn_birth_time));
  15325. close_connection(conn);
  15326. #if defined(USE_SERVER_STATS)
  15327. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15328. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15329. #endif
  15330. }
  15331. #if defined(ALTERNATIVE_QUEUE)
  15332. static void
  15333. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15334. {
  15335. unsigned int i;
  15336. while (!ctx->stop_flag) {
  15337. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15338. /* find a free worker slot and signal it */
  15339. if (ctx->client_socks[i].in_use == 2) {
  15340. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15341. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15342. ctx->client_socks[i] = *sp;
  15343. ctx->client_socks[i].in_use = 1;
  15344. /* socket has been moved to the consumer */
  15345. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15346. (void)event_signal(ctx->client_wait_events[i]);
  15347. return;
  15348. }
  15349. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15350. }
  15351. }
  15352. /* queue is full */
  15353. mg_sleep(1);
  15354. }
  15355. /* must consume */
  15356. set_blocking_mode(sp->sock);
  15357. closesocket(sp->sock);
  15358. }
  15359. static int
  15360. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15361. {
  15362. DEBUG_TRACE("%s", "going idle");
  15363. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15364. ctx->client_socks[thread_index].in_use = 2;
  15365. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15366. event_wait(ctx->client_wait_events[thread_index]);
  15367. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15368. *sp = ctx->client_socks[thread_index];
  15369. if (ctx->stop_flag) {
  15370. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15371. if (sp->in_use == 1) {
  15372. /* must consume */
  15373. set_blocking_mode(sp->sock);
  15374. closesocket(sp->sock);
  15375. }
  15376. return 0;
  15377. }
  15378. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15379. if (sp->in_use == 1) {
  15380. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15381. return 1;
  15382. }
  15383. /* must not reach here */
  15384. DEBUG_ASSERT(0);
  15385. return 0;
  15386. }
  15387. #else /* ALTERNATIVE_QUEUE */
  15388. /* Worker threads take accepted socket from the queue */
  15389. static int
  15390. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15391. {
  15392. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15393. (void)thread_index;
  15394. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15395. DEBUG_TRACE("%s", "going idle");
  15396. /* If the queue is empty, wait. We're idle at this point. */
  15397. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15398. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15399. }
  15400. /* If we're stopping, sq_head may be equal to sq_tail. */
  15401. if (ctx->sq_head > ctx->sq_tail) {
  15402. /* Copy socket from the queue and increment tail */
  15403. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15404. ctx->sq_tail++;
  15405. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15406. /* Wrap pointers if needed */
  15407. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15408. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15409. ctx->sq_head -= QUEUE_SIZE(ctx);
  15410. }
  15411. }
  15412. (void)pthread_cond_signal(&ctx->sq_empty);
  15413. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15414. return !ctx->stop_flag;
  15415. #undef QUEUE_SIZE
  15416. }
  15417. /* Master thread adds accepted socket to a queue */
  15418. static void
  15419. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15420. {
  15421. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15422. if (!ctx) {
  15423. return;
  15424. }
  15425. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15426. /* If the queue is full, wait */
  15427. while ((ctx->stop_flag == 0)
  15428. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15429. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15430. }
  15431. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15432. /* Copy socket to the queue and increment head */
  15433. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15434. ctx->sq_head++;
  15435. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15436. }
  15437. (void)pthread_cond_signal(&ctx->sq_full);
  15438. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15439. #undef QUEUE_SIZE
  15440. }
  15441. #endif /* ALTERNATIVE_QUEUE */
  15442. static void
  15443. worker_thread_run(struct mg_connection *conn)
  15444. {
  15445. struct mg_context *ctx = conn->phys_ctx;
  15446. int thread_index;
  15447. struct mg_workerTLS tls;
  15448. #if defined(MG_LEGACY_INTERFACE)
  15449. uint32_t addr;
  15450. #endif
  15451. mg_set_thread_name("worker");
  15452. tls.is_master = 0;
  15453. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15454. #if defined(_WIN32)
  15455. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15456. #endif
  15457. /* Initialize thread local storage before calling any callback */
  15458. pthread_setspecific(sTlsKey, &tls);
  15459. /* Check if there is a user callback */
  15460. if (ctx->callbacks.init_thread) {
  15461. /* call init_thread for a worker thread (type 1), and store the return
  15462. * value */
  15463. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  15464. } else {
  15465. /* No callback: set user pointer to NULL */
  15466. tls.user_ptr = NULL;
  15467. }
  15468. /* Connection structure has been pre-allocated */
  15469. thread_index = (int)(conn - ctx->worker_connections);
  15470. if ((thread_index < 0)
  15471. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  15472. mg_cry_ctx_internal(ctx,
  15473. "Internal error: Invalid worker index %i",
  15474. thread_index);
  15475. return;
  15476. }
  15477. /* Request buffers are not pre-allocated. They are private to the
  15478. * request and do not contain any state information that might be
  15479. * of interest to anyone observing a server status. */
  15480. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15481. if (conn->buf == NULL) {
  15482. mg_cry_ctx_internal(
  15483. ctx,
  15484. "Out of memory: Cannot allocate buffer for worker %i",
  15485. thread_index);
  15486. return;
  15487. }
  15488. conn->buf_size = (int)ctx->max_request_size;
  15489. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15490. conn->host = NULL; /* until we have more information. */
  15491. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  15492. conn->request_info.user_data = ctx->user_data;
  15493. /* Allocate a mutex for this connection to allow communication both
  15494. * within the request handler and from elsewhere in the application
  15495. */
  15496. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15497. mg_free(conn->buf);
  15498. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  15499. return;
  15500. }
  15501. #if defined(USE_SERVER_STATS)
  15502. conn->conn_state = 1; /* not consumed */
  15503. #endif
  15504. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15505. * signal sq_empty condvar to wake up the master waiting in
  15506. * produce_socket() */
  15507. while (consume_socket(ctx, &conn->client, thread_index)) {
  15508. conn->conn_birth_time = time(NULL);
  15509. /* Fill in IP, port info early so even if SSL setup below fails,
  15510. * error handler would have the corresponding info.
  15511. * Thanks to Johannes Winkelmann for the patch.
  15512. */
  15513. #if defined(USE_IPV6)
  15514. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15515. conn->request_info.remote_port =
  15516. ntohs(conn->client.rsa.sin6.sin6_port);
  15517. } else
  15518. #endif
  15519. {
  15520. conn->request_info.remote_port =
  15521. ntohs(conn->client.rsa.sin.sin_port);
  15522. }
  15523. sockaddr_to_string(conn->request_info.remote_addr,
  15524. sizeof(conn->request_info.remote_addr),
  15525. &conn->client.rsa);
  15526. DEBUG_TRACE("Start processing connection from %s",
  15527. conn->request_info.remote_addr);
  15528. conn->request_info.is_ssl = conn->client.is_ssl;
  15529. if (conn->client.is_ssl) {
  15530. #if !defined(NO_SSL)
  15531. /* HTTPS connection */
  15532. if (sslize(conn,
  15533. conn->dom_ctx->ssl_ctx,
  15534. SSL_accept,
  15535. &(conn->phys_ctx->stop_flag),
  15536. NULL)) {
  15537. /* conn->dom_ctx is set in get_request */
  15538. /* Get SSL client certificate information (if set) */
  15539. ssl_get_client_cert_info(conn);
  15540. /* process HTTPS connection */
  15541. process_new_connection(conn);
  15542. /* Free client certificate info */
  15543. if (conn->request_info.client_cert) {
  15544. mg_free((void *)(conn->request_info.client_cert->subject));
  15545. mg_free((void *)(conn->request_info.client_cert->issuer));
  15546. mg_free((void *)(conn->request_info.client_cert->serial));
  15547. mg_free((void *)(conn->request_info.client_cert->finger));
  15548. /* Free certificate memory */
  15549. X509_free(
  15550. (X509 *)conn->request_info.client_cert->peer_cert);
  15551. conn->request_info.client_cert->peer_cert = 0;
  15552. conn->request_info.client_cert->subject = 0;
  15553. conn->request_info.client_cert->issuer = 0;
  15554. conn->request_info.client_cert->serial = 0;
  15555. conn->request_info.client_cert->finger = 0;
  15556. mg_free(conn->request_info.client_cert);
  15557. conn->request_info.client_cert = 0;
  15558. }
  15559. } else {
  15560. /* make sure the connection is cleaned up on SSL failure */
  15561. close_connection(conn);
  15562. }
  15563. #endif
  15564. } else {
  15565. /* process HTTP connection */
  15566. process_new_connection(conn);
  15567. }
  15568. DEBUG_TRACE("%s", "Connection closed");
  15569. }
  15570. /* Call exit thread user callback */
  15571. if (ctx->callbacks.exit_thread) {
  15572. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  15573. }
  15574. /* delete thread local storage objects */
  15575. pthread_setspecific(sTlsKey, NULL);
  15576. #if defined(_WIN32)
  15577. CloseHandle(tls.pthread_cond_helper_mutex);
  15578. #endif
  15579. pthread_mutex_destroy(&conn->mutex);
  15580. /* Free the request buffer. */
  15581. conn->buf_size = 0;
  15582. mg_free(conn->buf);
  15583. conn->buf = NULL;
  15584. #if defined(USE_SERVER_STATS)
  15585. conn->conn_state = 9; /* done */
  15586. #endif
  15587. DEBUG_TRACE("%s", "exiting");
  15588. }
  15589. /* Threads have different return types on Windows and Unix. */
  15590. #if defined(_WIN32)
  15591. static unsigned __stdcall worker_thread(void *thread_func_param)
  15592. {
  15593. worker_thread_run((struct mg_connection *)thread_func_param);
  15594. return 0;
  15595. }
  15596. #else
  15597. static void *
  15598. worker_thread(void *thread_func_param)
  15599. {
  15600. #if !defined(__ZEPHYR__)
  15601. struct sigaction sa;
  15602. /* Ignore SIGPIPE */
  15603. memset(&sa, 0, sizeof(sa));
  15604. sa.sa_handler = SIG_IGN;
  15605. sigaction(SIGPIPE, &sa, NULL);
  15606. #endif
  15607. worker_thread_run((struct mg_connection *)thread_func_param);
  15608. return NULL;
  15609. }
  15610. #endif /* _WIN32 */
  15611. /* This is an internal function, thus all arguments are expected to be
  15612. * valid - a NULL check is not required. */
  15613. static void
  15614. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15615. {
  15616. struct socket so;
  15617. char src_addr[IP_ADDR_STR_LEN];
  15618. socklen_t len = sizeof(so.rsa);
  15619. #if !defined(__ZEPHYR__)
  15620. int on = 1;
  15621. #endif
  15622. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15623. == INVALID_SOCKET) {
  15624. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15625. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15626. mg_cry_ctx_internal(ctx,
  15627. "%s: %s is not allowed to connect",
  15628. __func__,
  15629. src_addr);
  15630. closesocket(so.sock);
  15631. } else {
  15632. /* Put so socket structure into the queue */
  15633. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15634. set_close_on_exec(so.sock, NULL, ctx);
  15635. so.is_ssl = listener->is_ssl;
  15636. so.ssl_redir = listener->ssl_redir;
  15637. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15638. mg_cry_ctx_internal(ctx,
  15639. "%s: getsockname() failed: %s",
  15640. __func__,
  15641. strerror(ERRNO));
  15642. }
  15643. #if !defined(__ZEPHYR__)
  15644. /* Set TCP keep-alive. This is needed because if HTTP-level
  15645. * keep-alive
  15646. * is enabled, and client resets the connection, server won't get
  15647. * TCP FIN or RST and will keep the connection open forever. With
  15648. * TCP keep-alive, next keep-alive handshake will figure out that
  15649. * the client is down and will close the server end.
  15650. * Thanks to Igor Klopov who suggested the patch. */
  15651. if (setsockopt(so.sock,
  15652. SOL_SOCKET,
  15653. SO_KEEPALIVE,
  15654. (SOCK_OPT_TYPE)&on,
  15655. sizeof(on))
  15656. != 0) {
  15657. mg_cry_ctx_internal(
  15658. ctx,
  15659. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15660. __func__,
  15661. strerror(ERRNO));
  15662. }
  15663. #endif
  15664. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15665. * to effectively fill up the underlying IP packet payload and
  15666. * reduce the overhead of sending lots of small buffers. However
  15667. * this hurts the server's throughput (ie. operations per second)
  15668. * when HTTP 1.1 persistent connections are used and the responses
  15669. * are relatively small (eg. less than 1400 bytes).
  15670. */
  15671. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15672. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15673. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15674. mg_cry_ctx_internal(
  15675. ctx,
  15676. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15677. __func__,
  15678. strerror(ERRNO));
  15679. }
  15680. }
  15681. /* The "non blocking" property should already be
  15682. * inherited from the parent socket. Set it for
  15683. * non-compliant socket implementations. */
  15684. set_non_blocking_mode(so.sock);
  15685. so.in_use = 0;
  15686. produce_socket(ctx, &so);
  15687. }
  15688. }
  15689. static void
  15690. master_thread_run(struct mg_context *ctx)
  15691. {
  15692. struct mg_workerTLS tls;
  15693. struct mg_pollfd *pfd;
  15694. unsigned int i;
  15695. unsigned int workerthreadcount;
  15696. if (!ctx) {
  15697. return;
  15698. }
  15699. mg_set_thread_name("master");
  15700. /* Increase priority of the master thread */
  15701. #if defined(_WIN32)
  15702. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15703. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15704. int min_prio = sched_get_priority_min(SCHED_RR);
  15705. int max_prio = sched_get_priority_max(SCHED_RR);
  15706. if ((min_prio >= 0) && (max_prio >= 0)
  15707. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15708. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15709. struct sched_param sched_param = {0};
  15710. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15711. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15712. }
  15713. #endif
  15714. /* Initialize thread local storage */
  15715. #if defined(_WIN32)
  15716. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15717. #endif
  15718. tls.is_master = 1;
  15719. pthread_setspecific(sTlsKey, &tls);
  15720. if (ctx->callbacks.init_thread) {
  15721. /* Callback for the master thread (type 0) */
  15722. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  15723. } else {
  15724. tls.user_ptr = NULL;
  15725. }
  15726. /* Server starts *now* */
  15727. ctx->start_time = time(NULL);
  15728. /* Start the server */
  15729. pfd = ctx->listening_socket_fds;
  15730. while (ctx->stop_flag == 0) {
  15731. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15732. pfd[i].fd = ctx->listening_sockets[i].sock;
  15733. pfd[i].events = POLLIN;
  15734. }
  15735. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15736. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15737. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15738. * successful poll, and POLLIN is defined as
  15739. * (POLLRDNORM | POLLRDBAND)
  15740. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15741. * pfd[i].revents == POLLIN. */
  15742. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15743. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15744. }
  15745. }
  15746. }
  15747. }
  15748. /* Here stop_flag is 1 - Initiate shutdown. */
  15749. DEBUG_TRACE("%s", "stopping workers");
  15750. /* Stop signal received: somebody called mg_stop. Quit. */
  15751. close_all_listening_sockets(ctx);
  15752. /* Wakeup workers that are waiting for connections to handle. */
  15753. #if defined(ALTERNATIVE_QUEUE)
  15754. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15755. event_signal(ctx->client_wait_events[i]);
  15756. }
  15757. #else
  15758. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15759. pthread_cond_broadcast(&ctx->sq_full);
  15760. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15761. #endif
  15762. /* Join all worker threads to avoid leaking threads. */
  15763. workerthreadcount = ctx->cfg_worker_threads;
  15764. for (i = 0; i < workerthreadcount; i++) {
  15765. if (ctx->worker_threadids[i] != 0) {
  15766. mg_join_thread(ctx->worker_threadids[i]);
  15767. }
  15768. }
  15769. #if defined(USE_LUA)
  15770. /* Free Lua state of lua background task */
  15771. if (ctx->lua_background_state) {
  15772. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15773. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15774. if (lua_istable(lstate, -1)) {
  15775. reg_boolean(lstate, "shutdown", 1);
  15776. lua_pop(lstate, 1);
  15777. mg_sleep(2);
  15778. }
  15779. lua_close(lstate);
  15780. ctx->lua_background_state = 0;
  15781. }
  15782. #endif
  15783. DEBUG_TRACE("%s", "exiting");
  15784. /* call exit thread callback */
  15785. if (ctx->callbacks.exit_thread) {
  15786. /* Callback for the master thread (type 0) */
  15787. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  15788. }
  15789. #if defined(_WIN32)
  15790. CloseHandle(tls.pthread_cond_helper_mutex);
  15791. #endif
  15792. pthread_setspecific(sTlsKey, NULL);
  15793. /* Signal mg_stop() that we're done.
  15794. * WARNING: This must be the very last thing this
  15795. * thread does, as ctx becomes invalid after this line. */
  15796. ctx->stop_flag = 2;
  15797. }
  15798. /* Threads have different return types on Windows and Unix. */
  15799. #if defined(_WIN32)
  15800. static unsigned __stdcall master_thread(void *thread_func_param)
  15801. {
  15802. master_thread_run((struct mg_context *)thread_func_param);
  15803. return 0;
  15804. }
  15805. #else
  15806. static void *
  15807. master_thread(void *thread_func_param)
  15808. {
  15809. #if !defined(__ZEPHYR__)
  15810. struct sigaction sa;
  15811. /* Ignore SIGPIPE */
  15812. memset(&sa, 0, sizeof(sa));
  15813. sa.sa_handler = SIG_IGN;
  15814. sigaction(SIGPIPE, &sa, NULL);
  15815. #endif
  15816. master_thread_run((struct mg_context *)thread_func_param);
  15817. return NULL;
  15818. }
  15819. #endif /* _WIN32 */
  15820. static void
  15821. free_context(struct mg_context *ctx)
  15822. {
  15823. int i;
  15824. struct mg_handler_info *tmp_rh;
  15825. if (ctx == NULL) {
  15826. return;
  15827. }
  15828. if (ctx->callbacks.exit_context) {
  15829. ctx->callbacks.exit_context(ctx);
  15830. }
  15831. /* All threads exited, no sync is needed. Destroy thread mutex and
  15832. * condvars
  15833. */
  15834. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15835. #if defined(ALTERNATIVE_QUEUE)
  15836. mg_free(ctx->client_socks);
  15837. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15838. event_destroy(ctx->client_wait_events[i]);
  15839. }
  15840. mg_free(ctx->client_wait_events);
  15841. #else
  15842. (void)pthread_cond_destroy(&ctx->sq_empty);
  15843. (void)pthread_cond_destroy(&ctx->sq_full);
  15844. #endif
  15845. /* Destroy other context global data structures mutex */
  15846. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15847. #if defined(USE_TIMERS)
  15848. timers_exit(ctx);
  15849. #endif
  15850. /* Deallocate config parameters */
  15851. for (i = 0; i < NUM_OPTIONS; i++) {
  15852. if (ctx->dd.config[i] != NULL) {
  15853. #if defined(_MSC_VER)
  15854. #pragma warning(suppress : 6001)
  15855. #endif
  15856. mg_free(ctx->dd.config[i]);
  15857. }
  15858. }
  15859. /* Deallocate request handlers */
  15860. while (ctx->dd.handlers) {
  15861. tmp_rh = ctx->dd.handlers;
  15862. ctx->dd.handlers = tmp_rh->next;
  15863. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15864. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15865. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15866. }
  15867. mg_free(tmp_rh->uri);
  15868. mg_free(tmp_rh);
  15869. }
  15870. #if !defined(NO_SSL)
  15871. /* Deallocate SSL context */
  15872. if (ctx->dd.ssl_ctx != NULL) {
  15873. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15874. int callback_ret =
  15875. (ctx->callbacks.external_ssl_ctx == NULL)
  15876. ? 0
  15877. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15878. if (callback_ret == 0) {
  15879. SSL_CTX_free(ctx->dd.ssl_ctx);
  15880. }
  15881. /* else: ignore error and ommit SSL_CTX_free in case
  15882. * callback_ret is 1 */
  15883. }
  15884. #endif /* !NO_SSL */
  15885. /* Deallocate worker thread ID array */
  15886. mg_free(ctx->worker_threadids);
  15887. /* Deallocate worker thread ID array */
  15888. mg_free(ctx->worker_connections);
  15889. /* deallocate system name string */
  15890. mg_free(ctx->systemName);
  15891. /* Deallocate context itself */
  15892. mg_free(ctx);
  15893. }
  15894. void
  15895. mg_stop(struct mg_context *ctx)
  15896. {
  15897. pthread_t mt;
  15898. if (!ctx) {
  15899. return;
  15900. }
  15901. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15902. * two threads is not allowed. */
  15903. mt = ctx->masterthreadid;
  15904. if (mt == 0) {
  15905. return;
  15906. }
  15907. ctx->masterthreadid = 0;
  15908. /* Set stop flag, so all threads know they have to exit. */
  15909. ctx->stop_flag = 1;
  15910. /* Wait until everything has stopped. */
  15911. while (ctx->stop_flag != 2) {
  15912. (void)mg_sleep(10);
  15913. }
  15914. mg_join_thread(mt);
  15915. free_context(ctx);
  15916. #if defined(_WIN32)
  15917. (void)WSACleanup();
  15918. #endif /* _WIN32 */
  15919. }
  15920. static void
  15921. get_system_name(char **sysName)
  15922. {
  15923. #if defined(_WIN32)
  15924. #if !defined(__SYMBIAN32__)
  15925. #if defined(_WIN32_WCE)
  15926. *sysName = mg_strdup("WinCE");
  15927. #else
  15928. char name[128];
  15929. DWORD dwVersion = 0;
  15930. DWORD dwMajorVersion = 0;
  15931. DWORD dwMinorVersion = 0;
  15932. DWORD dwBuild = 0;
  15933. BOOL wowRet, isWoW = FALSE;
  15934. #if defined(_MSC_VER)
  15935. #pragma warning(push)
  15936. /* GetVersion was declared deprecated */
  15937. #pragma warning(disable : 4996)
  15938. #endif
  15939. dwVersion = GetVersion();
  15940. #if defined(_MSC_VER)
  15941. #pragma warning(pop)
  15942. #endif
  15943. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15944. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15945. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15946. (void)dwBuild;
  15947. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15948. sprintf(name,
  15949. "Windows %u.%u%s",
  15950. (unsigned)dwMajorVersion,
  15951. (unsigned)dwMinorVersion,
  15952. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15953. *sysName = mg_strdup(name);
  15954. #endif
  15955. #else
  15956. *sysName = mg_strdup("Symbian");
  15957. #endif
  15958. #elif defined(__ZEPHYR__)
  15959. *sysName = mg_strdup("Zephyr OS");
  15960. #else
  15961. struct utsname name;
  15962. memset(&name, 0, sizeof(name));
  15963. uname(&name);
  15964. *sysName = mg_strdup(name.sysname);
  15965. #endif
  15966. }
  15967. struct mg_context *
  15968. mg_start(const struct mg_callbacks *callbacks,
  15969. void *user_data,
  15970. const char **options)
  15971. {
  15972. struct mg_context *ctx;
  15973. const char *name, *value, *default_value;
  15974. int idx, ok, workerthreadcount;
  15975. unsigned int i;
  15976. int itmp;
  15977. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15978. struct mg_workerTLS tls;
  15979. #if defined(_WIN32)
  15980. WSADATA data;
  15981. WSAStartup(MAKEWORD(2, 2), &data);
  15982. #endif /* _WIN32 */
  15983. /* Allocate context and initialize reasonable general case defaults. */
  15984. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15985. return NULL;
  15986. }
  15987. /* Random number generator will initialize at the first call */
  15988. ctx->dd.auth_nonce_mask =
  15989. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15990. if (mg_init_library_called == 0) {
  15991. /* Legacy INIT, if mg_start is called without mg_init_library.
  15992. * Note: This may cause a memory leak */
  15993. const char *ports_option =
  15994. config_options[LISTENING_PORTS].default_value;
  15995. if (options) {
  15996. const char **run_options = options;
  15997. const char *optname = config_options[LISTENING_PORTS].name;
  15998. /* Try to find the "listening_ports" option */
  15999. while (*run_options) {
  16000. if (!strcmp(*run_options, optname)) {
  16001. ports_option = run_options[1];
  16002. }
  16003. run_options += 2;
  16004. }
  16005. }
  16006. if (is_ssl_port_used(ports_option)) {
  16007. /* Initialize with SSL support */
  16008. mg_init_library(MG_FEATURES_TLS);
  16009. } else {
  16010. /* Initialize without SSL support */
  16011. mg_init_library(MG_FEATURES_DEFAULT);
  16012. }
  16013. }
  16014. tls.is_master = -1;
  16015. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16016. #if defined(_WIN32)
  16017. tls.pthread_cond_helper_mutex = NULL;
  16018. #endif
  16019. pthread_setspecific(sTlsKey, &tls);
  16020. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16021. #if !defined(ALTERNATIVE_QUEUE)
  16022. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16023. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16024. #endif
  16025. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16026. if (!ok) {
  16027. /* Fatal error - abort start. However, this situation should never
  16028. * occur in practice. */
  16029. mg_cry_ctx_internal(ctx,
  16030. "%s",
  16031. "Cannot initialize thread synchronization objects");
  16032. mg_free(ctx);
  16033. pthread_setspecific(sTlsKey, NULL);
  16034. return NULL;
  16035. }
  16036. if (callbacks) {
  16037. ctx->callbacks = *callbacks;
  16038. exit_callback = callbacks->exit_context;
  16039. ctx->callbacks.exit_context = 0;
  16040. }
  16041. ctx->user_data = user_data;
  16042. ctx->dd.handlers = NULL;
  16043. ctx->dd.next = NULL;
  16044. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16045. ctx->dd.shared_lua_websockets = NULL;
  16046. #endif
  16047. /* Store options */
  16048. while (options && (name = *options++) != NULL) {
  16049. if ((idx = get_option_index(name)) == -1) {
  16050. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16051. free_context(ctx);
  16052. pthread_setspecific(sTlsKey, NULL);
  16053. return NULL;
  16054. } else if ((value = *options++) == NULL) {
  16055. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16056. free_context(ctx);
  16057. pthread_setspecific(sTlsKey, NULL);
  16058. return NULL;
  16059. }
  16060. if (ctx->dd.config[idx] != NULL) {
  16061. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16062. mg_free(ctx->dd.config[idx]);
  16063. }
  16064. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16065. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16066. }
  16067. /* Set default value if needed */
  16068. for (i = 0; config_options[i].name != NULL; i++) {
  16069. default_value = config_options[i].default_value;
  16070. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16071. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16072. }
  16073. }
  16074. /* Request size option */
  16075. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16076. if (itmp < 1024) {
  16077. mg_cry_ctx_internal(ctx, "%s", "max_request_size too small");
  16078. free_context(ctx);
  16079. pthread_setspecific(sTlsKey, NULL);
  16080. return NULL;
  16081. }
  16082. ctx->max_request_size = (unsigned)itmp;
  16083. /* Worker thread count option */
  16084. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16085. if (workerthreadcount > MAX_WORKER_THREADS) {
  16086. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16087. free_context(ctx);
  16088. pthread_setspecific(sTlsKey, NULL);
  16089. return NULL;
  16090. }
  16091. if (workerthreadcount <= 0) {
  16092. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16093. free_context(ctx);
  16094. pthread_setspecific(sTlsKey, NULL);
  16095. return NULL;
  16096. }
  16097. /* Document root */
  16098. #if defined(NO_FILES)
  16099. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16100. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16101. free_context(ctx);
  16102. pthread_setspecific(sTlsKey, NULL);
  16103. return NULL;
  16104. }
  16105. #endif
  16106. get_system_name(&ctx->systemName);
  16107. #if defined(USE_LUA)
  16108. /* If a Lua background script has been configured, start it. */
  16109. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16110. char ebuf[256];
  16111. struct vec opt_vec;
  16112. struct vec eq_vec;
  16113. const char *sparams;
  16114. lua_State *state = mg_prepare_lua_context_script(
  16115. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16116. if (!state) {
  16117. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16118. free_context(ctx);
  16119. pthread_setspecific(sTlsKey, NULL);
  16120. return NULL;
  16121. }
  16122. ctx->lua_background_state = (void *)state;
  16123. lua_newtable(state);
  16124. reg_boolean(state, "shutdown", 0);
  16125. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16126. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16127. reg_llstring(
  16128. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16129. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16130. break;
  16131. }
  16132. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16133. } else {
  16134. ctx->lua_background_state = 0;
  16135. }
  16136. #endif
  16137. /* NOTE(lsm): order is important here. SSL certificates must
  16138. * be initialized before listening ports. UID must be set last. */
  16139. if (
  16140. #if !defined(NO_FILESYSTEMS)
  16141. !set_gpass_option(ctx, NULL) ||
  16142. #endif
  16143. #if !defined(NO_SSL)
  16144. !init_ssl_ctx(ctx, NULL) ||
  16145. #endif
  16146. !set_ports_option(ctx) ||
  16147. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16148. !set_uid_option(ctx) ||
  16149. #endif
  16150. !set_acl_option(ctx)) {
  16151. free_context(ctx);
  16152. pthread_setspecific(sTlsKey, NULL);
  16153. return NULL;
  16154. }
  16155. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16156. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16157. sizeof(pthread_t),
  16158. ctx);
  16159. if (ctx->worker_threadids == NULL) {
  16160. mg_cry_ctx_internal(ctx,
  16161. "%s",
  16162. "Not enough memory for worker thread ID array");
  16163. free_context(ctx);
  16164. pthread_setspecific(sTlsKey, NULL);
  16165. return NULL;
  16166. }
  16167. ctx->worker_connections =
  16168. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16169. sizeof(struct mg_connection),
  16170. ctx);
  16171. if (ctx->worker_connections == NULL) {
  16172. mg_cry_ctx_internal(
  16173. ctx, "%s", "Not enough memory for worker thread connection array");
  16174. free_context(ctx);
  16175. pthread_setspecific(sTlsKey, NULL);
  16176. return NULL;
  16177. }
  16178. #if defined(ALTERNATIVE_QUEUE)
  16179. ctx->client_wait_events =
  16180. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  16181. sizeof(ctx->client_wait_events[0]),
  16182. ctx);
  16183. if (ctx->client_wait_events == NULL) {
  16184. mg_cry_ctx_internal(ctx,
  16185. "%s",
  16186. "Not enough memory for worker event array");
  16187. mg_free(ctx->worker_threadids);
  16188. free_context(ctx);
  16189. pthread_setspecific(sTlsKey, NULL);
  16190. return NULL;
  16191. }
  16192. ctx->client_socks =
  16193. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16194. sizeof(ctx->client_socks[0]),
  16195. ctx);
  16196. if (ctx->client_socks == NULL) {
  16197. mg_cry_ctx_internal(ctx,
  16198. "%s",
  16199. "Not enough memory for worker socket array");
  16200. mg_free(ctx->client_wait_events);
  16201. mg_free(ctx->worker_threadids);
  16202. free_context(ctx);
  16203. pthread_setspecific(sTlsKey, NULL);
  16204. return NULL;
  16205. }
  16206. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16207. ctx->client_wait_events[i] = event_create();
  16208. if (ctx->client_wait_events[i] == 0) {
  16209. mg_cry_ctx_internal(ctx, "Error creating worker event %i", i);
  16210. while (i > 0) {
  16211. i--;
  16212. event_destroy(ctx->client_wait_events[i]);
  16213. }
  16214. mg_free(ctx->client_socks);
  16215. mg_free(ctx->client_wait_events);
  16216. mg_free(ctx->worker_threadids);
  16217. free_context(ctx);
  16218. pthread_setspecific(sTlsKey, NULL);
  16219. return NULL;
  16220. }
  16221. }
  16222. #endif
  16223. #if defined(USE_TIMERS)
  16224. if (timers_init(ctx) != 0) {
  16225. mg_cry_ctx_internal(ctx, "%s", "Error creating timers");
  16226. free_context(ctx);
  16227. pthread_setspecific(sTlsKey, NULL);
  16228. return NULL;
  16229. }
  16230. #endif
  16231. /* Context has been created - init user libraries */
  16232. if (ctx->callbacks.init_context) {
  16233. ctx->callbacks.init_context(ctx);
  16234. }
  16235. ctx->callbacks.exit_context = exit_callback;
  16236. ctx->context_type = CONTEXT_SERVER; /* server context */
  16237. /* Start master (listening) thread */
  16238. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16239. /* Start worker threads */
  16240. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16241. /* worker_thread sets up the other fields */
  16242. ctx->worker_connections[i].phys_ctx = ctx;
  16243. if (mg_start_thread_with_id(worker_thread,
  16244. &ctx->worker_connections[i],
  16245. &ctx->worker_threadids[i])
  16246. != 0) {
  16247. /* thread was not created */
  16248. if (i > 0) {
  16249. mg_cry_ctx_internal(ctx,
  16250. "Cannot start worker thread %i: error %ld",
  16251. i + 1,
  16252. (long)ERRNO);
  16253. } else {
  16254. mg_cry_ctx_internal(ctx,
  16255. "Cannot create threads: error %ld",
  16256. (long)ERRNO);
  16257. free_context(ctx);
  16258. pthread_setspecific(sTlsKey, NULL);
  16259. return NULL;
  16260. }
  16261. break;
  16262. }
  16263. }
  16264. pthread_setspecific(sTlsKey, NULL);
  16265. return ctx;
  16266. }
  16267. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16268. /* Add an additional domain to an already running web server. */
  16269. int
  16270. mg_start_domain(struct mg_context *ctx, const char **options)
  16271. {
  16272. const char *name;
  16273. const char *value;
  16274. const char *default_value;
  16275. struct mg_domain_context *new_dom;
  16276. struct mg_domain_context *dom;
  16277. int idx, i;
  16278. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  16279. return -1;
  16280. }
  16281. new_dom = (struct mg_domain_context *)
  16282. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16283. if (!new_dom) {
  16284. /* Out of memory */
  16285. return -6;
  16286. }
  16287. /* Store options - TODO: unite duplicate code */
  16288. while (options && (name = *options++) != NULL) {
  16289. if ((idx = get_option_index(name)) == -1) {
  16290. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16291. mg_free(new_dom);
  16292. return -2;
  16293. } else if ((value = *options++) == NULL) {
  16294. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16295. mg_free(new_dom);
  16296. return -2;
  16297. }
  16298. if (new_dom->config[idx] != NULL) {
  16299. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16300. mg_free(new_dom->config[idx]);
  16301. }
  16302. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16303. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16304. }
  16305. /* Authentication domain is mandatory */
  16306. /* TODO: Maybe use a new option hostname? */
  16307. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16308. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  16309. mg_free(new_dom);
  16310. return -4;
  16311. }
  16312. /* Set default value if needed. Take the config value from
  16313. * ctx as a default value. */
  16314. for (i = 0; config_options[i].name != NULL; i++) {
  16315. default_value = ctx->dd.config[i];
  16316. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16317. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16318. }
  16319. }
  16320. new_dom->handlers = NULL;
  16321. new_dom->next = NULL;
  16322. new_dom->nonce_count = 0;
  16323. new_dom->auth_nonce_mask =
  16324. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16325. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16326. new_dom->shared_lua_websockets = NULL;
  16327. #endif
  16328. if (!init_ssl_ctx(ctx, new_dom)) {
  16329. /* Init SSL failed */
  16330. mg_free(new_dom);
  16331. return -3;
  16332. }
  16333. /* Add element to linked list. */
  16334. mg_lock_context(ctx);
  16335. idx = 0;
  16336. dom = &(ctx->dd);
  16337. for (;;) {
  16338. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16339. dom->config[AUTHENTICATION_DOMAIN])) {
  16340. /* Domain collision */
  16341. mg_cry_ctx_internal(ctx,
  16342. "domain %s already in use",
  16343. new_dom->config[AUTHENTICATION_DOMAIN]);
  16344. mg_free(new_dom);
  16345. return -5;
  16346. }
  16347. /* Count number of domains */
  16348. idx++;
  16349. if (dom->next == NULL) {
  16350. dom->next = new_dom;
  16351. break;
  16352. }
  16353. dom = dom->next;
  16354. }
  16355. mg_unlock_context(ctx);
  16356. /* Return domain number */
  16357. return idx;
  16358. }
  16359. #endif
  16360. /* Feature check API function */
  16361. unsigned
  16362. mg_check_feature(unsigned feature)
  16363. {
  16364. static const unsigned feature_set = 0
  16365. /* Set bits for available features according to API documentation.
  16366. * This bit mask is created at compile time, according to the active
  16367. * preprocessor defines. It is a single const value at runtime. */
  16368. #if !defined(NO_FILES)
  16369. | MG_FEATURES_FILES
  16370. #endif
  16371. #if !defined(NO_SSL)
  16372. | MG_FEATURES_SSL
  16373. #endif
  16374. #if !defined(NO_CGI)
  16375. | MG_FEATURES_CGI
  16376. #endif
  16377. #if defined(USE_IPV6)
  16378. | MG_FEATURES_IPV6
  16379. #endif
  16380. #if defined(USE_WEBSOCKET)
  16381. | MG_FEATURES_WEBSOCKET
  16382. #endif
  16383. #if defined(USE_LUA)
  16384. | MG_FEATURES_LUA
  16385. #endif
  16386. #if defined(USE_DUKTAPE)
  16387. | MG_FEATURES_SSJS
  16388. #endif
  16389. #if !defined(NO_CACHING)
  16390. | MG_FEATURES_CACHE
  16391. #endif
  16392. #if defined(USE_SERVER_STATS)
  16393. | MG_FEATURES_STATS
  16394. #endif
  16395. #if defined(USE_ZLIB)
  16396. | MG_FEATURES_COMPRESSION
  16397. #endif
  16398. /* Set some extra bits not defined in the API documentation.
  16399. * These bits may change without further notice. */
  16400. #if defined(MG_LEGACY_INTERFACE)
  16401. | 0x00008000u
  16402. #endif
  16403. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16404. | 0x00004000u
  16405. #endif
  16406. #if defined(MEMORY_DEBUGGING)
  16407. | 0x00001000u
  16408. #endif
  16409. #if defined(USE_TIMERS)
  16410. | 0x00020000u
  16411. #endif
  16412. #if !defined(NO_NONCE_CHECK)
  16413. | 0x00040000u
  16414. #endif
  16415. #if !defined(NO_POPEN)
  16416. | 0x00080000u
  16417. #endif
  16418. ;
  16419. return (feature & feature_set);
  16420. }
  16421. static size_t
  16422. mg_str_append(char **dst, char *end, const char *src)
  16423. {
  16424. size_t len = strlen(src);
  16425. if (*dst != end) {
  16426. /* Append src if enough space, or close dst. */
  16427. if ((size_t)(end - *dst) > len) {
  16428. strcpy(*dst, src);
  16429. *dst += len;
  16430. } else {
  16431. *dst = end;
  16432. }
  16433. }
  16434. return len;
  16435. }
  16436. /* Get system information. It can be printed or stored by the caller.
  16437. * Return the size of available information. */
  16438. int
  16439. mg_get_system_info(char *buffer, int buflen)
  16440. {
  16441. char *end, *append_eoobj = NULL, block[256];
  16442. size_t system_info_length = 0;
  16443. #if defined(_WIN32)
  16444. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16445. #else
  16446. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16447. #endif
  16448. if ((buffer == NULL) || (buflen < 1)) {
  16449. buflen = 0;
  16450. end = buffer;
  16451. } else {
  16452. *buffer = 0;
  16453. end = buffer + buflen;
  16454. }
  16455. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16456. /* has enough space to append eoobj */
  16457. append_eoobj = buffer;
  16458. end -= sizeof(eoobj) - 1;
  16459. }
  16460. system_info_length += mg_str_append(&buffer, end, "{");
  16461. /* Server version */
  16462. {
  16463. const char *version = mg_version();
  16464. mg_snprintf(NULL,
  16465. NULL,
  16466. block,
  16467. sizeof(block),
  16468. "%s\"version\" : \"%s\"",
  16469. eol,
  16470. version);
  16471. system_info_length += mg_str_append(&buffer, end, block);
  16472. }
  16473. /* System info */
  16474. {
  16475. #if defined(_WIN32)
  16476. DWORD dwVersion = 0;
  16477. DWORD dwMajorVersion = 0;
  16478. DWORD dwMinorVersion = 0;
  16479. SYSTEM_INFO si;
  16480. GetSystemInfo(&si);
  16481. #if defined(_MSC_VER)
  16482. #pragma warning(push)
  16483. /* GetVersion was declared deprecated */
  16484. #pragma warning(disable : 4996)
  16485. #endif
  16486. dwVersion = GetVersion();
  16487. #if defined(_MSC_VER)
  16488. #pragma warning(pop)
  16489. #endif
  16490. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16491. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16492. mg_snprintf(NULL,
  16493. NULL,
  16494. block,
  16495. sizeof(block),
  16496. ",%s\"os\" : \"Windows %u.%u\"",
  16497. eol,
  16498. (unsigned)dwMajorVersion,
  16499. (unsigned)dwMinorVersion);
  16500. system_info_length += mg_str_append(&buffer, end, block);
  16501. mg_snprintf(NULL,
  16502. NULL,
  16503. block,
  16504. sizeof(block),
  16505. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  16506. eol,
  16507. (unsigned)si.wProcessorArchitecture,
  16508. (unsigned)si.dwNumberOfProcessors,
  16509. (unsigned)si.dwActiveProcessorMask);
  16510. system_info_length += mg_str_append(&buffer, end, block);
  16511. #elif defined(__ZEPHYR__)
  16512. mg_snprintf(NULL,
  16513. NULL,
  16514. block,
  16515. sizeof(block),
  16516. ",%s\"os\" : \"%s %s\"",
  16517. eol,
  16518. "Zephyr OS",
  16519. ZEPHYR_VERSION);
  16520. system_info_length += mg_str_append(&buffer, end, block);
  16521. #else
  16522. struct utsname name;
  16523. memset(&name, 0, sizeof(name));
  16524. uname(&name);
  16525. mg_snprintf(NULL,
  16526. NULL,
  16527. block,
  16528. sizeof(block),
  16529. ",%s\"os\" : \"%s %s (%s) - %s\"",
  16530. eol,
  16531. name.sysname,
  16532. name.version,
  16533. name.release,
  16534. name.machine);
  16535. system_info_length += mg_str_append(&buffer, end, block);
  16536. #endif
  16537. }
  16538. /* Features */
  16539. {
  16540. mg_snprintf(NULL,
  16541. NULL,
  16542. block,
  16543. sizeof(block),
  16544. ",%s\"features\" : %lu"
  16545. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  16546. eol,
  16547. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16548. eol,
  16549. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16550. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16551. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16552. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16553. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16554. : "",
  16555. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16556. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16557. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16558. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  16559. system_info_length += mg_str_append(&buffer, end, block);
  16560. #if defined(USE_LUA)
  16561. mg_snprintf(NULL,
  16562. NULL,
  16563. block,
  16564. sizeof(block),
  16565. ",%s\"lua_version\" : \"%u (%s)\"",
  16566. eol,
  16567. (unsigned)LUA_VERSION_NUM,
  16568. LUA_RELEASE);
  16569. system_info_length += mg_str_append(&buffer, end, block);
  16570. #endif
  16571. #if defined(USE_DUKTAPE)
  16572. mg_snprintf(NULL,
  16573. NULL,
  16574. block,
  16575. sizeof(block),
  16576. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  16577. eol,
  16578. (unsigned)DUK_VERSION / 10000,
  16579. ((unsigned)DUK_VERSION / 100) % 100,
  16580. (unsigned)DUK_VERSION % 100);
  16581. system_info_length += mg_str_append(&buffer, end, block);
  16582. #endif
  16583. }
  16584. /* Build date */
  16585. {
  16586. #if defined(GCC_DIAGNOSTIC)
  16587. #if GCC_VERSION >= 40900
  16588. #pragma GCC diagnostic push
  16589. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  16590. #pragma GCC diagnostic ignored "-Wdate-time"
  16591. #endif
  16592. #endif
  16593. mg_snprintf(NULL,
  16594. NULL,
  16595. block,
  16596. sizeof(block),
  16597. ",%s\"build\" : \"%s\"",
  16598. eol,
  16599. __DATE__);
  16600. #if defined(GCC_DIAGNOSTIC)
  16601. #if GCC_VERSION >= 40900
  16602. #pragma GCC diagnostic pop
  16603. #endif
  16604. #endif
  16605. system_info_length += mg_str_append(&buffer, end, block);
  16606. }
  16607. /* Compiler information */
  16608. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16609. {
  16610. #if defined(_MSC_VER)
  16611. mg_snprintf(NULL,
  16612. NULL,
  16613. block,
  16614. sizeof(block),
  16615. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  16616. eol,
  16617. (unsigned)_MSC_VER,
  16618. (unsigned)_MSC_FULL_VER);
  16619. system_info_length += mg_str_append(&buffer, end, block);
  16620. #elif defined(__MINGW64__)
  16621. mg_snprintf(NULL,
  16622. NULL,
  16623. block,
  16624. sizeof(block),
  16625. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  16626. eol,
  16627. (unsigned)__MINGW64_VERSION_MAJOR,
  16628. (unsigned)__MINGW64_VERSION_MINOR);
  16629. system_info_length += mg_str_append(&buffer, end, block);
  16630. mg_snprintf(NULL,
  16631. NULL,
  16632. block,
  16633. sizeof(block),
  16634. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16635. eol,
  16636. (unsigned)__MINGW32_MAJOR_VERSION,
  16637. (unsigned)__MINGW32_MINOR_VERSION);
  16638. system_info_length += mg_str_append(&buffer, end, block);
  16639. #elif defined(__MINGW32__)
  16640. mg_snprintf(NULL,
  16641. NULL,
  16642. block,
  16643. sizeof(block),
  16644. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16645. eol,
  16646. (unsigned)__MINGW32_MAJOR_VERSION,
  16647. (unsigned)__MINGW32_MINOR_VERSION);
  16648. system_info_length += mg_str_append(&buffer, end, block);
  16649. #elif defined(__clang__)
  16650. mg_snprintf(NULL,
  16651. NULL,
  16652. block,
  16653. sizeof(block),
  16654. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  16655. eol,
  16656. __clang_major__,
  16657. __clang_minor__,
  16658. __clang_patchlevel__,
  16659. __clang_version__);
  16660. system_info_length += mg_str_append(&buffer, end, block);
  16661. #elif defined(__GNUC__)
  16662. mg_snprintf(NULL,
  16663. NULL,
  16664. block,
  16665. sizeof(block),
  16666. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  16667. eol,
  16668. (unsigned)__GNUC__,
  16669. (unsigned)__GNUC_MINOR__,
  16670. (unsigned)__GNUC_PATCHLEVEL__);
  16671. system_info_length += mg_str_append(&buffer, end, block);
  16672. #elif defined(__INTEL_COMPILER)
  16673. mg_snprintf(NULL,
  16674. NULL,
  16675. block,
  16676. sizeof(block),
  16677. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  16678. eol,
  16679. (unsigned)__INTEL_COMPILER);
  16680. system_info_length += mg_str_append(&buffer, end, block);
  16681. #elif defined(__BORLANDC__)
  16682. mg_snprintf(NULL,
  16683. NULL,
  16684. block,
  16685. sizeof(block),
  16686. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  16687. eol,
  16688. (unsigned)__BORLANDC__);
  16689. system_info_length += mg_str_append(&buffer, end, block);
  16690. #elif defined(__SUNPRO_C)
  16691. mg_snprintf(NULL,
  16692. NULL,
  16693. block,
  16694. sizeof(block),
  16695. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  16696. eol,
  16697. (unsigned)__SUNPRO_C);
  16698. system_info_length += mg_str_append(&buffer, end, block);
  16699. #else
  16700. mg_snprintf(NULL,
  16701. NULL,
  16702. block,
  16703. sizeof(block),
  16704. ",%s\"compiler\" : \"other\"",
  16705. eol);
  16706. system_info_length += mg_str_append(&buffer, end, block);
  16707. #endif
  16708. }
  16709. /* Determine 32/64 bit data mode.
  16710. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16711. {
  16712. mg_snprintf(NULL,
  16713. NULL,
  16714. block,
  16715. sizeof(block),
  16716. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16717. "char:%u/%u, "
  16718. "ptr:%u, size:%u, time:%u\"",
  16719. eol,
  16720. (unsigned)sizeof(short),
  16721. (unsigned)sizeof(int),
  16722. (unsigned)sizeof(long),
  16723. (unsigned)sizeof(long long),
  16724. (unsigned)sizeof(float),
  16725. (unsigned)sizeof(double),
  16726. (unsigned)sizeof(long double),
  16727. (unsigned)sizeof(char),
  16728. (unsigned)sizeof(wchar_t),
  16729. (unsigned)sizeof(void *),
  16730. (unsigned)sizeof(size_t),
  16731. (unsigned)sizeof(time_t));
  16732. system_info_length += mg_str_append(&buffer, end, block);
  16733. }
  16734. /* Terminate string */
  16735. if (append_eoobj) {
  16736. strcat(append_eoobj, eoobj);
  16737. }
  16738. system_info_length += sizeof(eoobj) - 1;
  16739. return (int)system_info_length;
  16740. }
  16741. /* Get context information. It can be printed or stored by the caller.
  16742. * Return the size of available information. */
  16743. int
  16744. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16745. {
  16746. #if defined(USE_SERVER_STATS)
  16747. char *end, *append_eoobj = NULL, block[256];
  16748. size_t context_info_length = 0;
  16749. #if defined(_WIN32)
  16750. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16751. #else
  16752. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16753. #endif
  16754. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16755. if ((buffer == NULL) || (buflen < 1)) {
  16756. buflen = 0;
  16757. end = buffer;
  16758. } else {
  16759. *buffer = 0;
  16760. end = buffer + buflen;
  16761. }
  16762. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16763. /* has enough space to append eoobj */
  16764. append_eoobj = buffer;
  16765. end -= sizeof(eoobj) - 1;
  16766. }
  16767. context_info_length += mg_str_append(&buffer, end, "{");
  16768. if (ms) { /* <-- should be always true */
  16769. /* Memory information */
  16770. mg_snprintf(NULL,
  16771. NULL,
  16772. block,
  16773. sizeof(block),
  16774. "%s\"memory\" : {%s"
  16775. "\"blocks\" : %i,%s"
  16776. "\"used\" : %" INT64_FMT ",%s"
  16777. "\"maxUsed\" : %" INT64_FMT "%s"
  16778. "}",
  16779. eol,
  16780. eol,
  16781. ms->blockCount,
  16782. eol,
  16783. ms->totalMemUsed,
  16784. eol,
  16785. ms->maxMemUsed,
  16786. eol);
  16787. context_info_length += mg_str_append(&buffer, end, block);
  16788. }
  16789. if (ctx) {
  16790. /* Declare all variables at begin of the block, to comply
  16791. * with old C standards. */
  16792. char start_time_str[64] = {0};
  16793. char now_str[64] = {0};
  16794. time_t start_time = ctx->start_time;
  16795. time_t now = time(NULL);
  16796. /* Connections information */
  16797. mg_snprintf(NULL,
  16798. NULL,
  16799. block,
  16800. sizeof(block),
  16801. ",%s\"connections\" : {%s"
  16802. "\"active\" : %i,%s"
  16803. "\"maxActive\" : %i,%s"
  16804. "\"total\" : %" INT64_FMT "%s"
  16805. "}",
  16806. eol,
  16807. eol,
  16808. ctx->active_connections,
  16809. eol,
  16810. ctx->max_connections,
  16811. eol,
  16812. ctx->total_connections,
  16813. eol);
  16814. context_info_length += mg_str_append(&buffer, end, block);
  16815. /* Requests information */
  16816. mg_snprintf(NULL,
  16817. NULL,
  16818. block,
  16819. sizeof(block),
  16820. ",%s\"requests\" : {%s"
  16821. "\"total\" : %" INT64_FMT "%s"
  16822. "}",
  16823. eol,
  16824. eol,
  16825. ctx->total_requests,
  16826. eol);
  16827. context_info_length += mg_str_append(&buffer, end, block);
  16828. /* Data information */
  16829. mg_snprintf(NULL,
  16830. NULL,
  16831. block,
  16832. sizeof(block),
  16833. ",%s\"data\" : {%s"
  16834. "\"read\" : %" INT64_FMT ",%s"
  16835. "\"written\" : %" INT64_FMT "%s"
  16836. "}",
  16837. eol,
  16838. eol,
  16839. ctx->total_data_read,
  16840. eol,
  16841. ctx->total_data_written,
  16842. eol);
  16843. context_info_length += mg_str_append(&buffer, end, block);
  16844. /* Execution time information */
  16845. gmt_time_string(start_time_str,
  16846. sizeof(start_time_str) - 1,
  16847. &start_time);
  16848. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16849. mg_snprintf(NULL,
  16850. NULL,
  16851. block,
  16852. sizeof(block),
  16853. ",%s\"time\" : {%s"
  16854. "\"uptime\" : %.0f,%s"
  16855. "\"start\" : \"%s\",%s"
  16856. "\"now\" : \"%s\"%s"
  16857. "}",
  16858. eol,
  16859. eol,
  16860. difftime(now, start_time),
  16861. eol,
  16862. start_time_str,
  16863. eol,
  16864. now_str,
  16865. eol);
  16866. context_info_length += mg_str_append(&buffer, end, block);
  16867. }
  16868. /* Terminate string */
  16869. if (append_eoobj) {
  16870. strcat(append_eoobj, eoobj);
  16871. }
  16872. context_info_length += sizeof(eoobj) - 1;
  16873. return (int)context_info_length;
  16874. #else
  16875. (void)ctx;
  16876. if ((buffer != NULL) && (buflen > 0)) {
  16877. *buffer = 0;
  16878. }
  16879. return 0;
  16880. #endif
  16881. }
  16882. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16883. /* Get connection information. It can be printed or stored by the caller.
  16884. * Return the size of available information. */
  16885. int
  16886. mg_get_connection_info(const struct mg_context *ctx,
  16887. int idx,
  16888. char *buffer,
  16889. int buflen)
  16890. {
  16891. const struct mg_connection *conn;
  16892. const struct mg_request_info *ri;
  16893. char *end, *append_eoobj = NULL, block[256];
  16894. size_t connection_info_length = 0;
  16895. int state = 0;
  16896. const char *state_str = "unknown";
  16897. #if defined(_WIN32)
  16898. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16899. #else
  16900. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16901. #endif
  16902. if ((buffer == NULL) || (buflen < 1)) {
  16903. buflen = 0;
  16904. end = buffer;
  16905. } else {
  16906. *buffer = 0;
  16907. end = buffer + buflen;
  16908. }
  16909. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16910. /* has enough space to append eoobj */
  16911. append_eoobj = buffer;
  16912. end -= sizeof(eoobj) - 1;
  16913. }
  16914. if ((ctx == NULL) || (idx < 0)) {
  16915. /* Parameter error */
  16916. return 0;
  16917. }
  16918. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16919. /* Out of range */
  16920. return 0;
  16921. }
  16922. /* Take connection [idx]. This connection is not locked in
  16923. * any way, so some other thread might use it. */
  16924. conn = (ctx->worker_connections) + idx;
  16925. /* Initialize output string */
  16926. connection_info_length += mg_str_append(&buffer, end, "{");
  16927. /* Init variables */
  16928. ri = &(conn->request_info);
  16929. #if defined(USE_SERVER_STATS)
  16930. state = conn->conn_state;
  16931. /* State as string */
  16932. switch (state) {
  16933. case 0:
  16934. state_str = "undefined";
  16935. break;
  16936. case 1:
  16937. state_str = "not used";
  16938. break;
  16939. case 2:
  16940. state_str = "init";
  16941. break;
  16942. case 3:
  16943. state_str = "ready";
  16944. break;
  16945. case 4:
  16946. state_str = "processing";
  16947. break;
  16948. case 5:
  16949. state_str = "processed";
  16950. break;
  16951. case 6:
  16952. state_str = "to close";
  16953. break;
  16954. case 7:
  16955. state_str = "closing";
  16956. break;
  16957. case 8:
  16958. state_str = "closed";
  16959. break;
  16960. case 9:
  16961. state_str = "done";
  16962. break;
  16963. }
  16964. #endif
  16965. /* Connection info */
  16966. if ((state >= 3) && (state < 9)) {
  16967. mg_snprintf(NULL,
  16968. NULL,
  16969. block,
  16970. sizeof(block),
  16971. "%s\"connection\" : {%s"
  16972. "\"remote\" : {%s"
  16973. "\"protocol\" : \"%s\",%s"
  16974. "\"addr\" : \"%s\",%s"
  16975. "\"port\" : %u%s"
  16976. "},%s"
  16977. "\"handled_requests\" : %u%s"
  16978. "}",
  16979. eol,
  16980. eol,
  16981. eol,
  16982. get_proto_name(conn),
  16983. eol,
  16984. ri->remote_addr,
  16985. eol,
  16986. ri->remote_port,
  16987. eol,
  16988. eol,
  16989. conn->handled_requests,
  16990. eol);
  16991. connection_info_length += mg_str_append(&buffer, end, block);
  16992. }
  16993. /* Request info */
  16994. if ((state >= 4) && (state < 6)) {
  16995. mg_snprintf(NULL,
  16996. NULL,
  16997. block,
  16998. sizeof(block),
  16999. "%s%s\"request_info\" : {%s"
  17000. "\"method\" : \"%s\",%s"
  17001. "\"uri\" : \"%s\",%s"
  17002. "\"query\" : %s%s%s%s"
  17003. "}",
  17004. (connection_info_length > 1 ? "," : ""),
  17005. eol,
  17006. eol,
  17007. ri->request_method,
  17008. eol,
  17009. ri->request_uri,
  17010. eol,
  17011. ri->query_string ? "\"" : "",
  17012. ri->query_string ? ri->query_string : "null",
  17013. ri->query_string ? "\"" : "",
  17014. eol);
  17015. connection_info_length += mg_str_append(&buffer, end, block);
  17016. }
  17017. /* Execution time information */
  17018. if ((state >= 2) && (state < 9)) {
  17019. char start_time_str[64] = {0};
  17020. char now_str[64] = {0};
  17021. time_t start_time = conn->conn_birth_time;
  17022. time_t now = time(NULL);
  17023. gmt_time_string(start_time_str,
  17024. sizeof(start_time_str) - 1,
  17025. &start_time);
  17026. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17027. mg_snprintf(NULL,
  17028. NULL,
  17029. block,
  17030. sizeof(block),
  17031. "%s%s\"time\" : {%s"
  17032. "\"uptime\" : %.0f,%s"
  17033. "\"start\" : \"%s\",%s"
  17034. "\"now\" : \"%s\"%s"
  17035. "}",
  17036. (connection_info_length > 1 ? "," : ""),
  17037. eol,
  17038. eol,
  17039. difftime(now, start_time),
  17040. eol,
  17041. start_time_str,
  17042. eol,
  17043. now_str,
  17044. eol);
  17045. connection_info_length += mg_str_append(&buffer, end, block);
  17046. }
  17047. /* Remote user name */
  17048. if ((ri->remote_user) && (state < 9)) {
  17049. mg_snprintf(NULL,
  17050. NULL,
  17051. block,
  17052. sizeof(block),
  17053. "%s%s\"user\" : {%s"
  17054. "\"name\" : \"%s\",%s"
  17055. "}",
  17056. (connection_info_length > 1 ? "," : ""),
  17057. eol,
  17058. eol,
  17059. ri->remote_user,
  17060. eol);
  17061. connection_info_length += mg_str_append(&buffer, end, block);
  17062. }
  17063. /* Data block */
  17064. if (state >= 3) {
  17065. mg_snprintf(NULL,
  17066. NULL,
  17067. block,
  17068. sizeof(block),
  17069. "%s%s\"data\" : {%s"
  17070. "\"read\" : %" INT64_FMT ",%s"
  17071. "\"written\" : %" INT64_FMT "%s"
  17072. "}",
  17073. (connection_info_length > 1 ? "," : ""),
  17074. eol,
  17075. eol,
  17076. conn->consumed_content,
  17077. eol,
  17078. conn->num_bytes_sent,
  17079. eol);
  17080. connection_info_length += mg_str_append(&buffer, end, block);
  17081. }
  17082. /* State */
  17083. mg_snprintf(NULL,
  17084. NULL,
  17085. block,
  17086. sizeof(block),
  17087. "%s%s\"state\" : \"%s\"",
  17088. (connection_info_length > 1 ? "," : ""),
  17089. eol,
  17090. state_str);
  17091. connection_info_length += mg_str_append(&buffer, end, block);
  17092. /* Terminate string */
  17093. if (append_eoobj) {
  17094. strcat(append_eoobj, eoobj);
  17095. }
  17096. connection_info_length += sizeof(eoobj) - 1;
  17097. return (int)connection_info_length;
  17098. }
  17099. #endif
  17100. /* Initialize this library. This function does not need to be thread safe.
  17101. */
  17102. unsigned
  17103. mg_init_library(unsigned features)
  17104. {
  17105. #if !defined(NO_SSL)
  17106. char ebuf[128];
  17107. #endif
  17108. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17109. unsigned features_inited = features_to_init;
  17110. if (mg_init_library_called <= 0) {
  17111. /* Not initialized yet */
  17112. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17113. return 0;
  17114. }
  17115. }
  17116. mg_global_lock();
  17117. if (mg_init_library_called <= 0) {
  17118. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17119. /* Fatal error - abort start. However, this situation should
  17120. * never occur in practice. */
  17121. mg_global_unlock();
  17122. return 0;
  17123. }
  17124. #if defined(_WIN32)
  17125. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  17126. #else
  17127. pthread_mutexattr_init(&pthread_mutex_attr);
  17128. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17129. #endif
  17130. #if defined(USE_LUA)
  17131. lua_init_optional_libraries();
  17132. #endif
  17133. }
  17134. mg_global_unlock();
  17135. #if !defined(NO_SSL)
  17136. if (features_to_init & MG_FEATURES_SSL) {
  17137. if (!mg_ssl_initialized) {
  17138. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17139. mg_ssl_initialized = 1;
  17140. } else {
  17141. (void)ebuf;
  17142. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17143. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17144. }
  17145. } else {
  17146. /* ssl already initialized */
  17147. }
  17148. }
  17149. #endif
  17150. /* Start WinSock for Windows */
  17151. mg_global_lock();
  17152. if (mg_init_library_called <= 0) {
  17153. #if defined(_WIN32)
  17154. WSADATA data;
  17155. WSAStartup(MAKEWORD(2, 2), &data);
  17156. #endif /* _WIN32 */
  17157. mg_init_library_called = 1;
  17158. } else {
  17159. mg_init_library_called++;
  17160. }
  17161. mg_global_unlock();
  17162. return features_inited;
  17163. }
  17164. /* Un-initialize this library. */
  17165. unsigned
  17166. mg_exit_library(void)
  17167. {
  17168. if (mg_init_library_called <= 0) {
  17169. return 0;
  17170. }
  17171. mg_global_lock();
  17172. mg_init_library_called--;
  17173. if (mg_init_library_called == 0) {
  17174. #if defined(_WIN32)
  17175. (void)WSACleanup();
  17176. #endif /* _WIN32 */
  17177. #if !defined(NO_SSL)
  17178. if (mg_ssl_initialized) {
  17179. uninitialize_ssl();
  17180. mg_ssl_initialized = 0;
  17181. }
  17182. #endif
  17183. #if defined(_WIN32)
  17184. (void)pthread_mutex_destroy(&global_log_file_lock);
  17185. #else
  17186. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17187. #endif
  17188. (void)pthread_key_delete(sTlsKey);
  17189. #if defined(USE_LUA)
  17190. lua_exit_optional_libraries();
  17191. #endif
  17192. mg_global_unlock();
  17193. (void)pthread_mutex_destroy(&global_lock_mutex);
  17194. return 1;
  17195. }
  17196. mg_global_unlock();
  17197. return 1;
  17198. }
  17199. /* End of civetweb.c */