civetweb.c 530 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869
  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 <zephyr.h>
  151. #include <posix/time.h>
  152. #include <net/socket.h>
  153. #include <posix/pthread.h>
  154. #include <string.h>
  155. #include <stdio.h>
  156. #include <stdlib.h>
  157. #include <ctype.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, MAX_WORKER_THREADS, ZEPHYR_STACK_SIZE);
  171. static int zephyr_worker_stack_index;
  172. #endif
  173. #if !defined(CIVETWEB_HEADER_INCLUDED)
  174. /* Include the header file here, so the CivetWeb interface is defined for the
  175. * entire implementation, including the following forward definitions. */
  176. #include "civetweb.h"
  177. #endif
  178. #if !defined(DEBUG_TRACE)
  179. #if defined(DEBUG)
  180. static void DEBUG_TRACE_FUNC(const char *func,
  181. unsigned line,
  182. PRINTF_FORMAT_STRING(const char *fmt),
  183. ...) PRINTF_ARGS(3, 4);
  184. #define DEBUG_TRACE(fmt, ...) \
  185. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  186. #define NEED_DEBUG_TRACE_FUNC
  187. #else
  188. #define DEBUG_TRACE(fmt, ...) \
  189. do { \
  190. } while (0)
  191. #endif /* DEBUG */
  192. #endif /* DEBUG_TRACE */
  193. #if !defined(DEBUG_ASSERT)
  194. #if defined(DEBUG)
  195. #define DEBUG_ASSERT(cond) \
  196. do { \
  197. if (!(cond)) { \
  198. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  199. exit(2); /* Exit with error */ \
  200. } \
  201. } while (0)
  202. #else
  203. #define DEBUG_ASSERT(cond)
  204. #endif /* DEBUG */
  205. #endif
  206. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  207. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  208. __attribute__((no_instrument_function));
  209. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  210. __attribute__((no_instrument_function));
  211. void
  212. __cyg_profile_func_enter(void *this_fn, void *call_site)
  213. {
  214. if ((void *)this_fn != (void *)printf) {
  215. printf("E %p %p\n", this_fn, call_site);
  216. }
  217. }
  218. void
  219. __cyg_profile_func_exit(void *this_fn, void *call_site)
  220. {
  221. if ((void *)this_fn != (void *)printf) {
  222. printf("X %p %p\n", this_fn, call_site);
  223. }
  224. }
  225. #endif
  226. #if !defined(IGNORE_UNUSED_RESULT)
  227. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  228. #endif
  229. #if defined(__GNUC__) || defined(__MINGW32__)
  230. /* GCC unused function attribute seems fundamentally broken.
  231. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  232. * OR UNUSED" for individual functions failed.
  233. * Either the compiler creates an "unused-function" warning if a
  234. * function is not marked with __attribute__((unused)).
  235. * On the other hand, if the function is marked with this attribute,
  236. * but is used, the compiler raises a completely idiotic
  237. * "used-but-marked-unused" warning - and
  238. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  239. * raises error: unknown option after "#pragma GCC diagnostic".
  240. * Disable this warning completely, until the GCC guys sober up
  241. * again.
  242. */
  243. #pragma GCC diagnostic ignored "-Wunused-function"
  244. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  245. #else
  246. #define FUNCTION_MAY_BE_UNUSED
  247. #endif
  248. /* Some ANSI #includes are not available on Windows CE */
  249. #if !defined(_WIN32_WCE) && !defined(__ZEPHYR__)
  250. #include <errno.h>
  251. #include <fcntl.h>
  252. #include <signal.h>
  253. #include <sys/stat.h>
  254. #include <sys/types.h>
  255. #endif /* !_WIN32_WCE */
  256. #if defined(__clang__)
  257. /* When using -Weverything, clang does not accept it's own headers
  258. * in a release build configuration. Disable what is too much in
  259. * -Weverything. */
  260. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  261. #endif
  262. #if defined(__GNUC__) || defined(__MINGW32__)
  263. /* Who on earth came to the conclusion, using __DATE__ should rise
  264. * an "expansion of date or time macro is not reproducible"
  265. * warning. That's exactly what was intended by using this macro.
  266. * Just disable this nonsense warning. */
  267. /* And disabling them does not work either:
  268. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  269. * #pragma clang diagnostic ignored "-Wdate-time"
  270. * So we just have to disable ALL warnings for some lines
  271. * of code.
  272. * This seems to be a known GCC bug, not resolved since 2012:
  273. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  274. */
  275. #endif
  276. #if defined(__MACH__) /* Apple OSX section */
  277. #if defined(__clang__)
  278. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  279. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  280. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  281. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  282. #endif
  283. #endif
  284. #define CLOCK_MONOTONIC (1)
  285. #define CLOCK_REALTIME (2)
  286. #include <mach/clock.h>
  287. #include <mach/mach.h>
  288. #include <mach/mach_time.h>
  289. #include <sys/errno.h>
  290. #include <sys/time.h>
  291. /* clock_gettime is not implemented on OSX prior to 10.12 */
  292. static int
  293. _civet_clock_gettime(int clk_id, struct timespec *t)
  294. {
  295. memset(t, 0, sizeof(*t));
  296. if (clk_id == CLOCK_REALTIME) {
  297. struct timeval now;
  298. int rv = gettimeofday(&now, NULL);
  299. if (rv) {
  300. return rv;
  301. }
  302. t->tv_sec = now.tv_sec;
  303. t->tv_nsec = now.tv_usec * 1000;
  304. return 0;
  305. } else if (clk_id == CLOCK_MONOTONIC) {
  306. static uint64_t clock_start_time = 0;
  307. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  308. uint64_t now = mach_absolute_time();
  309. if (clock_start_time == 0) {
  310. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  311. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  312. /* appease "unused variable" warning for release builds */
  313. (void)mach_status;
  314. clock_start_time = now;
  315. }
  316. now = (uint64_t)((double)(now - clock_start_time)
  317. * (double)timebase_ifo.numer
  318. / (double)timebase_ifo.denom);
  319. t->tv_sec = now / 1000000000;
  320. t->tv_nsec = now % 1000000000;
  321. return 0;
  322. }
  323. return -1; /* EINVAL - Clock ID is unknown */
  324. }
  325. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  326. #if defined(__CLOCK_AVAILABILITY)
  327. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  328. * declared but it may be NULL at runtime. So we need to check before using
  329. * it. */
  330. static int
  331. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  332. {
  333. if (clock_gettime) {
  334. return clock_gettime(clk_id, t);
  335. }
  336. return _civet_clock_gettime(clk_id, t);
  337. }
  338. #define clock_gettime _civet_safe_clock_gettime
  339. #else
  340. #define clock_gettime _civet_clock_gettime
  341. #endif
  342. #endif
  343. /********************************************************************/
  344. /* CivetWeb configuration defines */
  345. /********************************************************************/
  346. /* Maximum number of threads that can be configured.
  347. * The number of threads actually created depends on the "num_threads"
  348. * configuration parameter, but this is the upper limit. */
  349. #if !defined(MAX_WORKER_THREADS)
  350. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  351. #endif
  352. /* Timeout interval for select/poll calls.
  353. * The timeouts depend on "*_timeout_ms" configuration values, but long
  354. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  355. * This reduces the time required to stop the server. */
  356. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  357. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  358. #endif
  359. /* Do not try to compress files smaller than this limit. */
  360. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  361. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  362. #endif
  363. #if !defined(PASSWORDS_FILE_NAME)
  364. #define PASSWORDS_FILE_NAME ".htpasswd"
  365. #endif
  366. /* Initial buffer size for all CGI environment variables. In case there is
  367. * not enough space, another block is allocated. */
  368. #if !defined(CGI_ENVIRONMENT_SIZE)
  369. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  370. #endif
  371. /* Maximum number of environment variables. */
  372. #if !defined(MAX_CGI_ENVIR_VARS)
  373. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  374. #endif
  375. /* General purpose buffer size. */
  376. #if !defined(MG_BUF_LEN) /* in bytes */
  377. #define MG_BUF_LEN (1024 * 8)
  378. #endif
  379. /* Size of the accepted socket queue (in case the old queue implementation
  380. * is used). */
  381. #if !defined(MGSQLEN)
  382. #define MGSQLEN (20) /* count */
  383. #endif
  384. /********************************************************************/
  385. /* Helper makros */
  386. #if !defined(ARRAY_SIZE)
  387. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  388. #endif
  389. #include <stdint.h>
  390. /* Standard defines */
  391. #if !defined(INT64_MAX)
  392. #define INT64_MAX (9223372036854775807)
  393. #endif
  394. #define SHUTDOWN_RD (0)
  395. #define SHUTDOWN_WR (1)
  396. #define SHUTDOWN_BOTH (2)
  397. mg_static_assert(MAX_WORKER_THREADS >= 1,
  398. "worker threads must be a positive number");
  399. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  400. "size_t data type size check");
  401. #if defined(_WIN32) /* WINDOWS include block */
  402. #include <windows.h>
  403. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  404. #include <ws2tcpip.h>
  405. #include <time.h> /* struct timespec */
  406. #include <stdlib.h> /* *alloc( */
  407. #include <malloc.h> /* *alloc( */
  408. typedef const char *SOCK_OPT_TYPE;
  409. #if !defined(PATH_MAX)
  410. #define W_PATH_MAX (MAX_PATH)
  411. /* at most three UTF-8 chars per wchar_t */
  412. #define PATH_MAX (W_PATH_MAX * 3)
  413. #else
  414. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  415. #endif
  416. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  417. #if !defined(_IN_PORT_T)
  418. #if !defined(in_port_t)
  419. #define in_port_t u_short
  420. #endif
  421. #endif
  422. #if !defined(_WIN32_WCE)
  423. #include <direct.h>
  424. #include <io.h>
  425. #include <process.h>
  426. #else /* _WIN32_WCE */
  427. #define NO_CGI /* WinCE has no pipes */
  428. #define NO_POPEN /* WinCE has no popen */
  429. typedef long off_t;
  430. #define errno ((int)(GetLastError()))
  431. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  432. #endif /* _WIN32_WCE */
  433. #define MAKEUQUAD(lo, hi) \
  434. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  435. #define RATE_DIFF (10000000) /* 100 nsecs */
  436. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  437. #define SYS2UNIX_TIME(lo, hi) \
  438. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  439. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  440. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  441. * Also use _strtoui64 on modern M$ compilers */
  442. #if defined(_MSC_VER)
  443. #if (_MSC_VER < 1300)
  444. #define STRX(x) #x
  445. #define STR(x) STRX(x)
  446. #define __func__ __FILE__ ":" STR(__LINE__)
  447. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  448. #define strtoll(x, y, z) (_atoi64(x))
  449. #else
  450. #define __func__ __FUNCTION__
  451. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  452. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  453. #endif
  454. #endif /* _MSC_VER */
  455. #define ERRNO ((int)(GetLastError()))
  456. #define NO_SOCKLEN_T
  457. #if defined(_WIN64) || defined(__MINGW64__)
  458. #if !defined(SSL_LIB)
  459. #define SSL_LIB "ssleay64.dll"
  460. #endif
  461. #if !defined(CRYPTO_LIB)
  462. #define CRYPTO_LIB "libeay64.dll"
  463. #endif
  464. #else
  465. #if !defined(SSL_LIB)
  466. #define SSL_LIB "ssleay32.dll"
  467. #endif
  468. #if !defined(CRYPTO_LIB)
  469. #define CRYPTO_LIB "libeay32.dll"
  470. #endif
  471. #endif
  472. #define O_NONBLOCK (0)
  473. #if !defined(W_OK)
  474. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  475. #endif
  476. #define _POSIX_
  477. #define INT64_FMT "I64d"
  478. #define UINT64_FMT "I64u"
  479. #define WINCDECL __cdecl
  480. #define vsnprintf_impl _vsnprintf
  481. #define access _access
  482. #define mg_sleep(x) (Sleep(x))
  483. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  484. #if !defined(popen)
  485. #define popen(x, y) (_popen(x, y))
  486. #endif
  487. #if !defined(pclose)
  488. #define pclose(x) (_pclose(x))
  489. #endif
  490. #define close(x) (_close(x))
  491. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  492. #define RTLD_LAZY (0)
  493. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  494. #define fdopen(x, y) (_fdopen((x), (y)))
  495. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  496. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  497. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  498. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  499. #define sleep(x) (Sleep((x)*1000))
  500. #define rmdir(x) (_rmdir(x))
  501. #if defined(_WIN64) || !defined(__MINGW32__)
  502. /* Only MinGW 32 bit is missing this function */
  503. #define timegm(x) (_mkgmtime(x))
  504. #else
  505. time_t timegm(struct tm *tm);
  506. #define NEED_TIMEGM
  507. #endif
  508. #if !defined(fileno)
  509. #define fileno(x) (_fileno(x))
  510. #endif /* !fileno MINGW #defines fileno */
  511. typedef struct {
  512. CRITICAL_SECTION sec; /* Immovable */
  513. } pthread_mutex_t;
  514. typedef DWORD pthread_key_t;
  515. typedef HANDLE pthread_t;
  516. typedef struct {
  517. pthread_mutex_t threadIdSec;
  518. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  519. } pthread_cond_t;
  520. #if !defined(__clockid_t_defined)
  521. typedef DWORD clockid_t;
  522. #endif
  523. #if !defined(CLOCK_MONOTONIC)
  524. #define CLOCK_MONOTONIC (1)
  525. #endif
  526. #if !defined(CLOCK_REALTIME)
  527. #define CLOCK_REALTIME (2)
  528. #endif
  529. #if !defined(CLOCK_THREAD)
  530. #define CLOCK_THREAD (3)
  531. #endif
  532. #if !defined(CLOCK_PROCESS)
  533. #define CLOCK_PROCESS (4)
  534. #endif
  535. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  536. #define _TIMESPEC_DEFINED
  537. #endif
  538. #if !defined(_TIMESPEC_DEFINED)
  539. struct timespec {
  540. time_t tv_sec; /* seconds */
  541. long tv_nsec; /* nanoseconds */
  542. };
  543. #endif
  544. #if !defined(WIN_PTHREADS_TIME_H)
  545. #define MUST_IMPLEMENT_CLOCK_GETTIME
  546. #endif
  547. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  548. #define clock_gettime mg_clock_gettime
  549. static int
  550. clock_gettime(clockid_t clk_id, struct timespec *tp)
  551. {
  552. FILETIME ft;
  553. ULARGE_INTEGER li, li2;
  554. BOOL ok = FALSE;
  555. double d;
  556. static double perfcnt_per_sec = 0.0;
  557. static BOOL initialized = FALSE;
  558. if (!initialized) {
  559. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  560. perfcnt_per_sec = 1.0 / li.QuadPart;
  561. initialized = TRUE;
  562. }
  563. if (tp) {
  564. memset(tp, 0, sizeof(*tp));
  565. if (clk_id == CLOCK_REALTIME) {
  566. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  567. GetSystemTimeAsFileTime(&ft);
  568. li.LowPart = ft.dwLowDateTime;
  569. li.HighPart = ft.dwHighDateTime;
  570. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  571. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  572. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  573. ok = TRUE;
  574. /* END: CLOCK_REALTIME */
  575. } else if (clk_id == CLOCK_MONOTONIC) {
  576. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  577. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  578. d = li.QuadPart * perfcnt_per_sec;
  579. tp->tv_sec = (time_t)d;
  580. d -= (double)tp->tv_sec;
  581. tp->tv_nsec = (long)(d * 1.0E9);
  582. ok = TRUE;
  583. /* END: CLOCK_MONOTONIC */
  584. } else if (clk_id == CLOCK_THREAD) {
  585. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  586. FILETIME t_create, t_exit, t_kernel, t_user;
  587. if (GetThreadTimes(GetCurrentThread(),
  588. &t_create,
  589. &t_exit,
  590. &t_kernel,
  591. &t_user)) {
  592. li.LowPart = t_user.dwLowDateTime;
  593. li.HighPart = t_user.dwHighDateTime;
  594. li2.LowPart = t_kernel.dwLowDateTime;
  595. li2.HighPart = t_kernel.dwHighDateTime;
  596. li.QuadPart += li2.QuadPart;
  597. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  598. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  599. ok = TRUE;
  600. }
  601. /* END: CLOCK_THREAD */
  602. } else if (clk_id == CLOCK_PROCESS) {
  603. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  604. FILETIME t_create, t_exit, t_kernel, t_user;
  605. if (GetProcessTimes(GetCurrentProcess(),
  606. &t_create,
  607. &t_exit,
  608. &t_kernel,
  609. &t_user)) {
  610. li.LowPart = t_user.dwLowDateTime;
  611. li.HighPart = t_user.dwHighDateTime;
  612. li2.LowPart = t_kernel.dwLowDateTime;
  613. li2.HighPart = t_kernel.dwHighDateTime;
  614. li.QuadPart += li2.QuadPart;
  615. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  616. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  617. ok = TRUE;
  618. }
  619. /* END: CLOCK_PROCESS */
  620. } else {
  621. /* BEGIN: unknown clock */
  622. /* ok = FALSE; already set by init */
  623. /* END: unknown clock */
  624. }
  625. }
  626. return ok ? 0 : -1;
  627. }
  628. #endif
  629. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  630. static int pthread_mutex_lock(pthread_mutex_t *);
  631. static int pthread_mutex_unlock(pthread_mutex_t *);
  632. static void path_to_unicode(const struct mg_connection *conn,
  633. const char *path,
  634. wchar_t *wbuf,
  635. size_t wbuf_len);
  636. /* All file operations need to be rewritten to solve #246. */
  637. struct mg_file;
  638. static const char *
  639. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  640. /* POSIX dirent interface */
  641. struct dirent {
  642. char d_name[PATH_MAX];
  643. };
  644. typedef struct DIR {
  645. HANDLE handle;
  646. WIN32_FIND_DATAW info;
  647. struct dirent result;
  648. } DIR;
  649. #if defined(HAVE_POLL)
  650. #define mg_pollfd pollfd
  651. #else
  652. struct mg_pollfd {
  653. SOCKET fd;
  654. short events;
  655. short revents;
  656. };
  657. #endif
  658. /* Mark required libraries */
  659. #if defined(_MSC_VER)
  660. #pragma comment(lib, "Ws2_32.lib")
  661. #endif
  662. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  663. #include <inttypes.h>
  664. typedef const void *SOCK_OPT_TYPE;
  665. #if defined(ANDROID)
  666. typedef unsigned short int in_port_t;
  667. #endif
  668. #if !defined(__ZEPHYR__)
  669. #include <ctype.h>
  670. #include <limits.h>
  671. #include <stdarg.h>
  672. #include <stddef.h>
  673. #include <stdio.h>
  674. #include <stdlib.h>
  675. #include <string.h>
  676. #include <time.h>
  677. #include <arpa/inet.h>
  678. #include <netdb.h>
  679. #include <netinet/in.h>
  680. #include <netinet/tcp.h>
  681. #include <sys/poll.h>
  682. #include <sys/socket.h>
  683. #include <sys/time.h>
  684. #include <sys/utsname.h>
  685. #include <sys/wait.h>
  686. #include <dirent.h>
  687. #include <grp.h>
  688. #include <pwd.h>
  689. #include <unistd.h>
  690. #include <pthread.h>
  691. #endif
  692. #define vsnprintf_impl vsnprintf
  693. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  694. #include <dlfcn.h>
  695. #endif
  696. #if defined(__MACH__)
  697. #define SSL_LIB "libssl.dylib"
  698. #define CRYPTO_LIB "libcrypto.dylib"
  699. #else
  700. #if !defined(SSL_LIB)
  701. #define SSL_LIB "libssl.so"
  702. #endif
  703. #if !defined(CRYPTO_LIB)
  704. #define CRYPTO_LIB "libcrypto.so"
  705. #endif
  706. #endif
  707. #if !defined(O_BINARY)
  708. #define O_BINARY (0)
  709. #endif /* O_BINARY */
  710. #define closesocket(a) (close(a))
  711. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  712. #define mg_remove(conn, x) (remove(x))
  713. #define mg_sleep(x) (usleep((x)*1000))
  714. #define mg_opendir(conn, x) (opendir(x))
  715. #define mg_closedir(x) (closedir(x))
  716. #define mg_readdir(x) (readdir(x))
  717. #define ERRNO (errno)
  718. #define INVALID_SOCKET (-1)
  719. #define INT64_FMT PRId64
  720. #define UINT64_FMT PRIu64
  721. typedef int SOCKET;
  722. #define WINCDECL
  723. #if defined(__hpux)
  724. /* HPUX 11 does not have monotonic, fall back to realtime */
  725. #if !defined(CLOCK_MONOTONIC)
  726. #define CLOCK_MONOTONIC CLOCK_REALTIME
  727. #endif
  728. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  729. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  730. * the prototypes use int* rather than socklen_t* which matches the
  731. * actual library expectation. When called with the wrong size arg
  732. * accept() returns a zero client inet addr and check_acl() always
  733. * fails. Since socklen_t is widely used below, just force replace
  734. * their typedef with int. - DTL
  735. */
  736. #define socklen_t int
  737. #endif /* hpux */
  738. #define mg_pollfd pollfd
  739. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  740. /* In case our C library is missing "timegm", provide an implementation */
  741. #if defined(NEED_TIMEGM)
  742. static inline int
  743. is_leap(int y)
  744. {
  745. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  746. }
  747. static inline int
  748. count_leap(int y)
  749. {
  750. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  751. }
  752. time_t
  753. timegm(struct tm *tm)
  754. {
  755. static const unsigned short ydays[] = {
  756. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  757. int year = tm->tm_year + 1900;
  758. int mon = tm->tm_mon;
  759. int mday = tm->tm_mday - 1;
  760. int hour = tm->tm_hour;
  761. int min = tm->tm_min;
  762. int sec = tm->tm_sec;
  763. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  764. || (mday >= ydays[mon + 1] - ydays[mon]
  765. + (mon == 1 && is_leap(year) ? 1 : 0))
  766. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  767. return -1;
  768. time_t res = year - 1970;
  769. res *= 365;
  770. res += mday;
  771. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  772. res += count_leap(year);
  773. res *= 24;
  774. res += hour;
  775. res *= 60;
  776. res += min;
  777. res *= 60;
  778. res += sec;
  779. return res;
  780. }
  781. #endif /* NEED_TIMEGM */
  782. /* va_copy should always be a macro, C99 and C++11 - DTL */
  783. #if !defined(va_copy)
  784. #define va_copy(x, y) ((x) = (y))
  785. #endif
  786. #if defined(_WIN32)
  787. /* Create substitutes for POSIX functions in Win32. */
  788. #if defined(GCC_DIAGNOSTIC)
  789. /* Show no warning in case system functions are not used. */
  790. #pragma GCC diagnostic push
  791. #pragma GCC diagnostic ignored "-Wunused-function"
  792. #endif
  793. static pthread_mutex_t global_log_file_lock;
  794. FUNCTION_MAY_BE_UNUSED
  795. static DWORD
  796. pthread_self(void)
  797. {
  798. return GetCurrentThreadId();
  799. }
  800. FUNCTION_MAY_BE_UNUSED
  801. static int
  802. pthread_key_create(
  803. pthread_key_t *key,
  804. void (*_ignored)(void *) /* destructor not supported for Windows */
  805. )
  806. {
  807. (void)_ignored;
  808. if ((key != 0)) {
  809. *key = TlsAlloc();
  810. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  811. }
  812. return -2;
  813. }
  814. FUNCTION_MAY_BE_UNUSED
  815. static int
  816. pthread_key_delete(pthread_key_t key)
  817. {
  818. return TlsFree(key) ? 0 : 1;
  819. }
  820. FUNCTION_MAY_BE_UNUSED
  821. static int
  822. pthread_setspecific(pthread_key_t key, void *value)
  823. {
  824. return TlsSetValue(key, value) ? 0 : 1;
  825. }
  826. FUNCTION_MAY_BE_UNUSED
  827. static void *
  828. pthread_getspecific(pthread_key_t key)
  829. {
  830. return TlsGetValue(key);
  831. }
  832. #if defined(GCC_DIAGNOSTIC)
  833. /* Enable unused function warning again */
  834. #pragma GCC diagnostic pop
  835. #endif
  836. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  837. #else
  838. static pthread_mutexattr_t pthread_mutex_attr;
  839. #endif /* _WIN32 */
  840. #if defined(_WIN32_WCE)
  841. /* Create substitutes for POSIX functions in Win32. */
  842. #if defined(GCC_DIAGNOSTIC)
  843. /* Show no warning in case system functions are not used. */
  844. #pragma GCC diagnostic push
  845. #pragma GCC diagnostic ignored "-Wunused-function"
  846. #endif
  847. FUNCTION_MAY_BE_UNUSED
  848. static time_t
  849. time(time_t *ptime)
  850. {
  851. time_t t;
  852. SYSTEMTIME st;
  853. FILETIME ft;
  854. GetSystemTime(&st);
  855. SystemTimeToFileTime(&st, &ft);
  856. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  857. if (ptime != NULL) {
  858. *ptime = t;
  859. }
  860. return t;
  861. }
  862. FUNCTION_MAY_BE_UNUSED
  863. static struct tm *
  864. localtime_s(const time_t *ptime, struct tm *ptm)
  865. {
  866. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  867. FILETIME ft, lft;
  868. SYSTEMTIME st;
  869. TIME_ZONE_INFORMATION tzinfo;
  870. if (ptm == NULL) {
  871. return NULL;
  872. }
  873. *(int64_t *)&ft = t;
  874. FileTimeToLocalFileTime(&ft, &lft);
  875. FileTimeToSystemTime(&lft, &st);
  876. ptm->tm_year = st.wYear - 1900;
  877. ptm->tm_mon = st.wMonth - 1;
  878. ptm->tm_wday = st.wDayOfWeek;
  879. ptm->tm_mday = st.wDay;
  880. ptm->tm_hour = st.wHour;
  881. ptm->tm_min = st.wMinute;
  882. ptm->tm_sec = st.wSecond;
  883. ptm->tm_yday = 0; /* hope nobody uses this */
  884. ptm->tm_isdst =
  885. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  886. return ptm;
  887. }
  888. FUNCTION_MAY_BE_UNUSED
  889. static struct tm *
  890. gmtime_s(const time_t *ptime, struct tm *ptm)
  891. {
  892. /* FIXME(lsm): fix this. */
  893. return localtime_s(ptime, ptm);
  894. }
  895. static int mg_atomic_inc(volatile int *addr);
  896. static struct tm tm_array[MAX_WORKER_THREADS];
  897. static int tm_index = 0;
  898. FUNCTION_MAY_BE_UNUSED
  899. static struct tm *
  900. localtime(const time_t *ptime)
  901. {
  902. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  903. return localtime_s(ptime, tm_array + i);
  904. }
  905. FUNCTION_MAY_BE_UNUSED
  906. static struct tm *
  907. gmtime(const time_t *ptime)
  908. {
  909. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  910. return gmtime_s(ptime, tm_array + i);
  911. }
  912. FUNCTION_MAY_BE_UNUSED
  913. static size_t
  914. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  915. {
  916. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  917. * for WinCE"); */
  918. return 0;
  919. }
  920. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  921. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  922. #define remove(f) mg_remove(NULL, f)
  923. FUNCTION_MAY_BE_UNUSED
  924. static int
  925. rename(const char *a, const char *b)
  926. {
  927. wchar_t wa[W_PATH_MAX];
  928. wchar_t wb[W_PATH_MAX];
  929. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  930. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  931. return MoveFileW(wa, wb) ? 0 : -1;
  932. }
  933. struct stat {
  934. int64_t st_size;
  935. time_t st_mtime;
  936. };
  937. FUNCTION_MAY_BE_UNUSED
  938. static int
  939. stat(const char *name, struct stat *st)
  940. {
  941. wchar_t wbuf[W_PATH_MAX];
  942. WIN32_FILE_ATTRIBUTE_DATA attr;
  943. time_t creation_time, write_time;
  944. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  945. memset(&attr, 0, sizeof(attr));
  946. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  947. st->st_size =
  948. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  949. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  950. attr.ftLastWriteTime.dwHighDateTime);
  951. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  952. attr.ftCreationTime.dwHighDateTime);
  953. if (creation_time > write_time) {
  954. st->st_mtime = creation_time;
  955. } else {
  956. st->st_mtime = write_time;
  957. }
  958. return 0;
  959. }
  960. #define access(x, a) 1 /* not required anyway */
  961. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  962. /* Values from errno.h in Windows SDK (Visual Studio). */
  963. #define EEXIST 17
  964. #define EACCES 13
  965. #define ENOENT 2
  966. #if defined(GCC_DIAGNOSTIC)
  967. /* Enable unused function warning again */
  968. #pragma GCC diagnostic pop
  969. #endif
  970. #endif /* defined(_WIN32_WCE) */
  971. #if defined(GCC_DIAGNOSTIC)
  972. /* Show no warning in case system functions are not used. */
  973. #pragma GCC diagnostic push
  974. #pragma GCC diagnostic ignored "-Wunused-function"
  975. #endif /* defined(GCC_DIAGNOSTIC) */
  976. #if defined(__clang__)
  977. /* Show no warning in case system functions are not used. */
  978. #pragma clang diagnostic push
  979. #pragma clang diagnostic ignored "-Wunused-function"
  980. #endif
  981. static pthread_mutex_t global_lock_mutex;
  982. FUNCTION_MAY_BE_UNUSED
  983. static void
  984. mg_global_lock(void)
  985. {
  986. (void)pthread_mutex_lock(&global_lock_mutex);
  987. }
  988. FUNCTION_MAY_BE_UNUSED
  989. static void
  990. mg_global_unlock(void)
  991. {
  992. (void)pthread_mutex_unlock(&global_lock_mutex);
  993. }
  994. FUNCTION_MAY_BE_UNUSED
  995. static int
  996. mg_atomic_inc(volatile int *addr)
  997. {
  998. int ret;
  999. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1000. /* Depending on the SDK, this function uses either
  1001. * (volatile unsigned int *) or (volatile LONG *),
  1002. * so whatever you use, the other SDK is likely to raise a warning. */
  1003. ret = InterlockedIncrement((volatile long *)addr);
  1004. #elif defined(__GNUC__) \
  1005. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1006. && !defined(NO_ATOMICS)
  1007. ret = __sync_add_and_fetch(addr, 1);
  1008. #else
  1009. mg_global_lock();
  1010. ret = (++(*addr));
  1011. mg_global_unlock();
  1012. #endif
  1013. return ret;
  1014. }
  1015. FUNCTION_MAY_BE_UNUSED
  1016. static int
  1017. mg_atomic_dec(volatile int *addr)
  1018. {
  1019. int ret;
  1020. #if defined(_WIN32) && !defined(NO_ATOMICS)
  1021. /* Depending on the SDK, this function uses either
  1022. * (volatile unsigned int *) or (volatile LONG *),
  1023. * so whatever you use, the other SDK is likely to raise a warning. */
  1024. ret = InterlockedDecrement((volatile long *)addr);
  1025. #elif defined(__GNUC__) \
  1026. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1027. && !defined(NO_ATOMICS)
  1028. ret = __sync_sub_and_fetch(addr, 1);
  1029. #else
  1030. mg_global_lock();
  1031. ret = (--(*addr));
  1032. mg_global_unlock();
  1033. #endif
  1034. return ret;
  1035. }
  1036. #if defined(USE_SERVER_STATS)
  1037. static int64_t
  1038. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1039. {
  1040. int64_t ret;
  1041. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1042. ret = InterlockedAdd64(addr, value);
  1043. #elif defined(__GNUC__) \
  1044. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1045. && !defined(NO_ATOMICS)
  1046. ret = __sync_add_and_fetch(addr, value);
  1047. #else
  1048. mg_global_lock();
  1049. *addr += value;
  1050. ret = (*addr);
  1051. mg_global_unlock();
  1052. #endif
  1053. return ret;
  1054. }
  1055. #endif
  1056. #if defined(GCC_DIAGNOSTIC)
  1057. /* Show no warning in case system functions are not used. */
  1058. #pragma GCC diagnostic pop
  1059. #endif /* defined(GCC_DIAGNOSTIC) */
  1060. #if defined(__clang__)
  1061. /* Show no warning in case system functions are not used. */
  1062. #pragma clang diagnostic pop
  1063. #endif
  1064. #if defined(USE_SERVER_STATS)
  1065. struct mg_memory_stat {
  1066. volatile int64_t totalMemUsed;
  1067. volatile int64_t maxMemUsed;
  1068. volatile int blockCount;
  1069. };
  1070. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1071. static void *
  1072. mg_malloc_ex(size_t size,
  1073. struct mg_context *ctx,
  1074. const char *file,
  1075. unsigned line)
  1076. {
  1077. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1078. void *memory = 0;
  1079. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1080. #if defined(MEMORY_DEBUGGING)
  1081. char mallocStr[256];
  1082. #else
  1083. (void)file;
  1084. (void)line;
  1085. #endif
  1086. if (data) {
  1087. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1088. if (mmem > mstat->maxMemUsed) {
  1089. /* could use atomic compare exchange, but this
  1090. * seems overkill for statistics data */
  1091. mstat->maxMemUsed = mmem;
  1092. }
  1093. mg_atomic_inc(&mstat->blockCount);
  1094. ((uintptr_t *)data)[0] = size;
  1095. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1096. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1097. }
  1098. #if defined(MEMORY_DEBUGGING)
  1099. sprintf(mallocStr,
  1100. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1101. memory,
  1102. (unsigned long)size,
  1103. (unsigned long)mstat->totalMemUsed,
  1104. (unsigned long)mstat->blockCount,
  1105. file,
  1106. line);
  1107. #if defined(_WIN32)
  1108. OutputDebugStringA(mallocStr);
  1109. #else
  1110. DEBUG_TRACE("%s", mallocStr);
  1111. #endif
  1112. #endif
  1113. return memory;
  1114. }
  1115. static void *
  1116. mg_calloc_ex(size_t count,
  1117. size_t size,
  1118. struct mg_context *ctx,
  1119. const char *file,
  1120. unsigned line)
  1121. {
  1122. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1123. if (data) {
  1124. memset(data, 0, size * count);
  1125. }
  1126. return data;
  1127. }
  1128. static void
  1129. mg_free_ex(void *memory, const char *file, unsigned line)
  1130. {
  1131. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1132. #if defined(MEMORY_DEBUGGING)
  1133. char mallocStr[256];
  1134. #else
  1135. (void)file;
  1136. (void)line;
  1137. #endif
  1138. if (memory) {
  1139. uintptr_t size = ((uintptr_t *)data)[0];
  1140. struct mg_memory_stat *mstat =
  1141. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1142. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1143. mg_atomic_dec(&mstat->blockCount);
  1144. #if defined(MEMORY_DEBUGGING)
  1145. sprintf(mallocStr,
  1146. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1147. memory,
  1148. (unsigned long)size,
  1149. (unsigned long)mstat->totalMemUsed,
  1150. (unsigned long)mstat->blockCount,
  1151. file,
  1152. line);
  1153. #if defined(_WIN32)
  1154. OutputDebugStringA(mallocStr);
  1155. #else
  1156. DEBUG_TRACE("%s", mallocStr);
  1157. #endif
  1158. #endif
  1159. free(data);
  1160. }
  1161. }
  1162. static void *
  1163. mg_realloc_ex(void *memory,
  1164. size_t newsize,
  1165. struct mg_context *ctx,
  1166. const char *file,
  1167. unsigned line)
  1168. {
  1169. void *data;
  1170. void *_realloc;
  1171. uintptr_t oldsize;
  1172. #if defined(MEMORY_DEBUGGING)
  1173. char mallocStr[256];
  1174. #else
  1175. (void)file;
  1176. (void)line;
  1177. #endif
  1178. if (newsize) {
  1179. if (memory) {
  1180. /* Reallocate existing block */
  1181. struct mg_memory_stat *mstat;
  1182. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1183. oldsize = ((uintptr_t *)data)[0];
  1184. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1185. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1186. if (_realloc) {
  1187. data = _realloc;
  1188. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1189. #if defined(MEMORY_DEBUGGING)
  1190. sprintf(mallocStr,
  1191. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1192. memory,
  1193. (unsigned long)oldsize,
  1194. (unsigned long)mstat->totalMemUsed,
  1195. (unsigned long)mstat->blockCount,
  1196. file,
  1197. line);
  1198. #if defined(_WIN32)
  1199. OutputDebugStringA(mallocStr);
  1200. #else
  1201. DEBUG_TRACE("%s", mallocStr);
  1202. #endif
  1203. #endif
  1204. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1205. #if defined(MEMORY_DEBUGGING)
  1206. sprintf(mallocStr,
  1207. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1208. memory,
  1209. (unsigned long)newsize,
  1210. (unsigned long)mstat->totalMemUsed,
  1211. (unsigned long)mstat->blockCount,
  1212. file,
  1213. line);
  1214. #if defined(_WIN32)
  1215. OutputDebugStringA(mallocStr);
  1216. #else
  1217. DEBUG_TRACE("%s", mallocStr);
  1218. #endif
  1219. #endif
  1220. *(uintptr_t *)data = newsize;
  1221. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1222. } else {
  1223. #if defined(MEMORY_DEBUGGING)
  1224. #if defined(_WIN32)
  1225. OutputDebugStringA("MEM: realloc failed\n");
  1226. #else
  1227. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1228. #endif
  1229. #endif
  1230. return _realloc;
  1231. }
  1232. } else {
  1233. /* Allocate new block */
  1234. data = mg_malloc_ex(newsize, ctx, file, line);
  1235. }
  1236. } else {
  1237. /* Free existing block */
  1238. data = 0;
  1239. mg_free_ex(memory, file, line);
  1240. }
  1241. return data;
  1242. }
  1243. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1244. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1245. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1246. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1247. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1248. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1249. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1250. #else /* USE_SERVER_STATS */
  1251. static __inline void *
  1252. mg_malloc(size_t a)
  1253. {
  1254. return malloc(a);
  1255. }
  1256. static __inline void *
  1257. mg_calloc(size_t a, size_t b)
  1258. {
  1259. return calloc(a, b);
  1260. }
  1261. static __inline void *
  1262. mg_realloc(void *a, size_t b)
  1263. {
  1264. return realloc(a, b);
  1265. }
  1266. static __inline void
  1267. mg_free(void *a)
  1268. {
  1269. free(a);
  1270. }
  1271. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1272. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1273. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1274. #define mg_free_ctx(a, c) mg_free(a)
  1275. #endif /* USE_SERVER_STATS */
  1276. static void mg_vsnprintf(const struct mg_connection *conn,
  1277. int *truncated,
  1278. char *buf,
  1279. size_t buflen,
  1280. const char *fmt,
  1281. va_list ap);
  1282. static void mg_snprintf(const struct mg_connection *conn,
  1283. int *truncated,
  1284. char *buf,
  1285. size_t buflen,
  1286. PRINTF_FORMAT_STRING(const char *fmt),
  1287. ...) PRINTF_ARGS(5, 6);
  1288. /* This following lines are just meant as a reminder to use the mg-functions
  1289. * for memory management */
  1290. #if defined(malloc)
  1291. #undef malloc
  1292. #endif
  1293. #if defined(calloc)
  1294. #undef calloc
  1295. #endif
  1296. #if defined(realloc)
  1297. #undef realloc
  1298. #endif
  1299. #if defined(free)
  1300. #undef free
  1301. #endif
  1302. #if defined(snprintf)
  1303. #undef snprintf
  1304. #endif
  1305. #if defined(vsnprintf)
  1306. #undef vsnprintf
  1307. #endif
  1308. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1309. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1310. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1311. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1312. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1313. #if defined(_WIN32)
  1314. /* vsnprintf must not be used in any system,
  1315. * but this define only works well for Windows. */
  1316. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1317. #endif
  1318. /* mg_init_library counter */
  1319. static int mg_init_library_called = 0;
  1320. #if !defined(NO_SSL)
  1321. static int mg_ssl_initialized = 0;
  1322. #endif
  1323. static pthread_key_t sTlsKey; /* Thread local storage index */
  1324. static int thread_idx_max = 0;
  1325. #if defined(MG_LEGACY_INTERFACE)
  1326. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1327. #endif
  1328. struct mg_workerTLS {
  1329. int is_master;
  1330. unsigned long thread_idx;
  1331. void *user_ptr;
  1332. #if defined(_WIN32)
  1333. HANDLE pthread_cond_helper_mutex;
  1334. struct mg_workerTLS *next_waiting_thread;
  1335. #endif
  1336. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1337. char txtbuf[4];
  1338. #endif
  1339. };
  1340. #if defined(GCC_DIAGNOSTIC)
  1341. /* Show no warning in case system functions are not used. */
  1342. #pragma GCC diagnostic push
  1343. #pragma GCC diagnostic ignored "-Wunused-function"
  1344. #endif /* defined(GCC_DIAGNOSTIC) */
  1345. #if defined(__clang__)
  1346. /* Show no warning in case system functions are not used. */
  1347. #pragma clang diagnostic push
  1348. #pragma clang diagnostic ignored "-Wunused-function"
  1349. #endif
  1350. /* Get a unique thread ID as unsigned long, independent from the data type
  1351. * of thread IDs defined by the operating system API.
  1352. * If two calls to mg_current_thread_id return the same value, they calls
  1353. * are done from the same thread. If they return different values, they are
  1354. * done from different threads. (Provided this function is used in the same
  1355. * process context and threads are not repeatedly created and deleted, but
  1356. * CivetWeb does not do that).
  1357. * This function must match the signature required for SSL id callbacks:
  1358. * CRYPTO_set_id_callback
  1359. */
  1360. FUNCTION_MAY_BE_UNUSED
  1361. static unsigned long
  1362. mg_current_thread_id(void)
  1363. {
  1364. #if defined(_WIN32)
  1365. return GetCurrentThreadId();
  1366. #else
  1367. #if defined(__clang__)
  1368. #pragma clang diagnostic push
  1369. #pragma clang diagnostic ignored "-Wunreachable-code"
  1370. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1371. * or not, so one of the two conditions will be unreachable by construction.
  1372. * Unfortunately the C standard does not define a way to check this at
  1373. * compile time, since the #if preprocessor conditions can not use the sizeof
  1374. * operator as an argument. */
  1375. #endif
  1376. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1377. /* This is the problematic case for CRYPTO_set_id_callback:
  1378. * The OS pthread_t can not be cast to unsigned long. */
  1379. struct mg_workerTLS *tls =
  1380. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1381. if (tls == NULL) {
  1382. /* SSL called from an unknown thread: Create some thread index.
  1383. */
  1384. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1385. tls->is_master = -2; /* -2 means "3rd party thread" */
  1386. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1387. pthread_setspecific(sTlsKey, tls);
  1388. }
  1389. return tls->thread_idx;
  1390. } else {
  1391. /* pthread_t may be any data type, so a simple cast to unsigned long
  1392. * can rise a warning/error, depending on the platform.
  1393. * Here memcpy is used as an anything-to-anything cast. */
  1394. unsigned long ret = 0;
  1395. pthread_t t = pthread_self();
  1396. memcpy(&ret, &t, sizeof(pthread_t));
  1397. return ret;
  1398. }
  1399. #if defined(__clang__)
  1400. #pragma clang diagnostic pop
  1401. #endif
  1402. #endif
  1403. }
  1404. FUNCTION_MAY_BE_UNUSED
  1405. static uint64_t
  1406. mg_get_current_time_ns(void)
  1407. {
  1408. struct timespec tsnow;
  1409. clock_gettime(CLOCK_REALTIME, &tsnow);
  1410. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1411. }
  1412. #if defined(GCC_DIAGNOSTIC)
  1413. /* Show no warning in case system functions are not used. */
  1414. #pragma GCC diagnostic pop
  1415. #endif /* defined(GCC_DIAGNOSTIC) */
  1416. #if defined(__clang__)
  1417. /* Show no warning in case system functions are not used. */
  1418. #pragma clang diagnostic pop
  1419. #endif
  1420. #if defined(NEED_DEBUG_TRACE_FUNC)
  1421. static void
  1422. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1423. {
  1424. va_list args;
  1425. uint64_t nsnow;
  1426. static uint64_t nslast;
  1427. struct timespec tsnow;
  1428. /* Get some operating system independent thread id */
  1429. unsigned long thread_id = mg_current_thread_id();
  1430. clock_gettime(CLOCK_REALTIME, &tsnow);
  1431. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1432. + ((uint64_t)tsnow.tv_nsec);
  1433. if (!nslast) {
  1434. nslast = nsnow;
  1435. }
  1436. flockfile(stdout);
  1437. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1438. (unsigned long)tsnow.tv_sec,
  1439. (unsigned long)tsnow.tv_nsec,
  1440. nsnow - nslast,
  1441. thread_id,
  1442. func,
  1443. line);
  1444. va_start(args, fmt);
  1445. vprintf(fmt, args);
  1446. va_end(args);
  1447. putchar('\n');
  1448. fflush(stdout);
  1449. funlockfile(stdout);
  1450. nslast = nsnow;
  1451. }
  1452. #endif /* NEED_DEBUG_TRACE_FUNC */
  1453. #define MD5_STATIC static
  1454. #include "md5.inl"
  1455. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1456. #if defined(NO_SOCKLEN_T)
  1457. typedef int socklen_t;
  1458. #endif /* NO_SOCKLEN_T */
  1459. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1460. #if !defined(MSG_NOSIGNAL)
  1461. #define MSG_NOSIGNAL (0)
  1462. #endif
  1463. #if defined(NO_SSL)
  1464. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1465. typedef struct SSL_CTX SSL_CTX;
  1466. #else
  1467. #if defined(NO_SSL_DL)
  1468. #include <openssl/bn.h>
  1469. #include <openssl/conf.h>
  1470. #include <openssl/crypto.h>
  1471. #include <openssl/dh.h>
  1472. #include <openssl/engine.h>
  1473. #include <openssl/err.h>
  1474. #include <openssl/opensslv.h>
  1475. #include <openssl/pem.h>
  1476. #include <openssl/ssl.h>
  1477. #include <openssl/tls1.h>
  1478. #include <openssl/x509.h>
  1479. #if defined(WOLFSSL_VERSION)
  1480. /* Additional defines for WolfSSL, see
  1481. * https://github.com/civetweb/civetweb/issues/583 */
  1482. #include "wolfssl_extras.inl"
  1483. #endif
  1484. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1485. /* If OpenSSL headers are included, automatically select the API version */
  1486. #if !defined(OPENSSL_API_1_1)
  1487. #define OPENSSL_API_1_1
  1488. #endif
  1489. #define OPENSSL_REMOVE_THREAD_STATE()
  1490. #else
  1491. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1492. #endif
  1493. #else
  1494. /* SSL loaded dynamically from DLL.
  1495. * I put the prototypes here to be independent from OpenSSL source
  1496. * installation. */
  1497. typedef struct ssl_st SSL;
  1498. typedef struct ssl_method_st SSL_METHOD;
  1499. typedef struct ssl_ctx_st SSL_CTX;
  1500. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1501. typedef struct x509_name X509_NAME;
  1502. typedef struct asn1_integer ASN1_INTEGER;
  1503. typedef struct bignum BIGNUM;
  1504. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1505. typedef struct evp_md EVP_MD;
  1506. typedef struct x509 X509;
  1507. #define SSL_CTRL_OPTIONS (32)
  1508. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1509. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1510. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1511. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1512. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1513. #define SSL_VERIFY_NONE (0)
  1514. #define SSL_VERIFY_PEER (1)
  1515. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1516. #define SSL_VERIFY_CLIENT_ONCE (4)
  1517. #define SSL_OP_ALL (0x80000BFFul)
  1518. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1519. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1520. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1521. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1522. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1523. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1524. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1525. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1526. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1527. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1528. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1529. #define SSL_CB_HANDSHAKE_START (0x10)
  1530. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1531. #define SSL_ERROR_NONE (0)
  1532. #define SSL_ERROR_SSL (1)
  1533. #define SSL_ERROR_WANT_READ (2)
  1534. #define SSL_ERROR_WANT_WRITE (3)
  1535. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1536. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1537. #define SSL_ERROR_ZERO_RETURN (6)
  1538. #define SSL_ERROR_WANT_CONNECT (7)
  1539. #define SSL_ERROR_WANT_ACCEPT (8)
  1540. #define TLSEXT_TYPE_server_name (0)
  1541. #define TLSEXT_NAMETYPE_host_name (0)
  1542. #define SSL_TLSEXT_ERR_OK (0)
  1543. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1544. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1545. #define SSL_TLSEXT_ERR_NOACK (3)
  1546. struct ssl_func {
  1547. const char *name; /* SSL function name */
  1548. void (*ptr)(void); /* Function pointer */
  1549. };
  1550. #if defined(OPENSSL_API_1_1)
  1551. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1552. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1553. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1554. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1555. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1556. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1557. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1558. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1559. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1560. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1561. #define OPENSSL_init_ssl \
  1562. (*(int (*)(uint64_t opts, \
  1563. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1564. .ptr)
  1565. #define SSL_CTX_use_PrivateKey_file \
  1566. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1567. #define SSL_CTX_use_certificate_file \
  1568. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1569. #define SSL_CTX_set_default_passwd_cb \
  1570. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1571. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1572. #define SSL_CTX_use_certificate_chain_file \
  1573. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1574. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1575. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1576. #define SSL_CTX_set_verify \
  1577. (*(void (*)(SSL_CTX *, \
  1578. int, \
  1579. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1580. .ptr)
  1581. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1582. #define SSL_CTX_load_verify_locations \
  1583. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1584. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1585. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1586. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1587. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1588. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1589. #define SSL_CIPHER_get_name \
  1590. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1591. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1592. #define SSL_CTX_set_session_id_context \
  1593. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1594. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1595. #define SSL_CTX_set_cipher_list \
  1596. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1597. #define SSL_CTX_set_options \
  1598. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1599. #define SSL_CTX_set_info_callback \
  1600. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1601. ssl_sw[32] \
  1602. .ptr)
  1603. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1604. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1605. #define SSL_CTX_callback_ctrl \
  1606. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1607. #define SSL_get_servername \
  1608. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1609. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1610. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1611. #define SSL_CTX_clear_options(ctx, op) \
  1612. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1613. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1614. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1615. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1616. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1617. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1618. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1619. SSL_CTX_callback_ctrl(ctx, \
  1620. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1621. (void (*)(void))cb)
  1622. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1623. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1624. #define SSL_set_tlsext_host_name(ctx, arg) \
  1625. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1626. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1627. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1628. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1629. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1630. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1631. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1632. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1633. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1634. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1635. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1636. #define X509_NAME_oneline \
  1637. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1638. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1639. #define EVP_get_digestbyname \
  1640. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1641. #define EVP_Digest \
  1642. (*(int (*)( \
  1643. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1644. crypto_sw[9] \
  1645. .ptr)
  1646. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1647. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1648. #define ASN1_INTEGER_to_BN \
  1649. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1650. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1651. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1652. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1653. #define OPENSSL_free(a) CRYPTO_free(a)
  1654. #define OPENSSL_REMOVE_THREAD_STATE()
  1655. /* init_ssl_ctx() function updates this array.
  1656. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1657. * of respective functions. The macros above (like SSL_connect()) are really
  1658. * just calling these functions indirectly via the pointer. */
  1659. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1660. {"SSL_accept", NULL},
  1661. {"SSL_connect", NULL},
  1662. {"SSL_read", NULL},
  1663. {"SSL_write", NULL},
  1664. {"SSL_get_error", NULL},
  1665. {"SSL_set_fd", NULL},
  1666. {"SSL_new", NULL},
  1667. {"SSL_CTX_new", NULL},
  1668. {"TLS_server_method", NULL},
  1669. {"OPENSSL_init_ssl", NULL},
  1670. {"SSL_CTX_use_PrivateKey_file", NULL},
  1671. {"SSL_CTX_use_certificate_file", NULL},
  1672. {"SSL_CTX_set_default_passwd_cb", NULL},
  1673. {"SSL_CTX_free", NULL},
  1674. {"SSL_CTX_use_certificate_chain_file", NULL},
  1675. {"TLS_client_method", NULL},
  1676. {"SSL_pending", NULL},
  1677. {"SSL_CTX_set_verify", NULL},
  1678. {"SSL_shutdown", NULL},
  1679. {"SSL_CTX_load_verify_locations", NULL},
  1680. {"SSL_CTX_set_default_verify_paths", NULL},
  1681. {"SSL_CTX_set_verify_depth", NULL},
  1682. {"SSL_get_peer_certificate", NULL},
  1683. {"SSL_get_version", NULL},
  1684. {"SSL_get_current_cipher", NULL},
  1685. {"SSL_CIPHER_get_name", NULL},
  1686. {"SSL_CTX_check_private_key", NULL},
  1687. {"SSL_CTX_set_session_id_context", NULL},
  1688. {"SSL_CTX_ctrl", NULL},
  1689. {"SSL_CTX_set_cipher_list", NULL},
  1690. {"SSL_CTX_set_options", NULL},
  1691. {"SSL_CTX_set_info_callback", NULL},
  1692. {"SSL_get_ex_data", NULL},
  1693. {"SSL_set_ex_data", NULL},
  1694. {"SSL_CTX_callback_ctrl", NULL},
  1695. {"SSL_get_servername", NULL},
  1696. {"SSL_set_SSL_CTX", NULL},
  1697. {"SSL_ctrl", NULL},
  1698. {NULL, NULL}};
  1699. /* Similar array as ssl_sw. These functions could be located in different
  1700. * lib. */
  1701. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1702. {"ERR_error_string", NULL},
  1703. {"CONF_modules_unload", NULL},
  1704. {"X509_free", NULL},
  1705. {"X509_get_subject_name", NULL},
  1706. {"X509_get_issuer_name", NULL},
  1707. {"X509_NAME_oneline", NULL},
  1708. {"X509_get_serialNumber", NULL},
  1709. {"EVP_get_digestbyname", NULL},
  1710. {"EVP_Digest", NULL},
  1711. {"i2d_X509", NULL},
  1712. {"BN_bn2hex", NULL},
  1713. {"ASN1_INTEGER_to_BN", NULL},
  1714. {"BN_free", NULL},
  1715. {"CRYPTO_free", NULL},
  1716. {"ERR_clear_error", NULL},
  1717. {NULL, NULL}};
  1718. #else
  1719. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1720. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1721. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1722. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1723. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1724. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1725. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1726. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1727. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1728. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1729. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1730. #define SSL_CTX_use_PrivateKey_file \
  1731. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1732. #define SSL_CTX_use_certificate_file \
  1733. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1734. #define SSL_CTX_set_default_passwd_cb \
  1735. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1736. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1737. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1738. #define SSL_CTX_use_certificate_chain_file \
  1739. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1740. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1741. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1742. #define SSL_CTX_set_verify \
  1743. (*(void (*)(SSL_CTX *, \
  1744. int, \
  1745. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1746. .ptr)
  1747. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1748. #define SSL_CTX_load_verify_locations \
  1749. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1750. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1751. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1752. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1753. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1754. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1755. #define SSL_CIPHER_get_name \
  1756. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1757. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1758. #define SSL_CTX_set_session_id_context \
  1759. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1760. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1761. #define SSL_CTX_set_cipher_list \
  1762. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1763. #define SSL_CTX_set_info_callback \
  1764. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1765. .ptr)
  1766. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1767. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1768. #define SSL_CTX_callback_ctrl \
  1769. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1770. #define SSL_get_servername \
  1771. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1772. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1773. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1774. #define SSL_CTX_set_options(ctx, op) \
  1775. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1776. #define SSL_CTX_clear_options(ctx, op) \
  1777. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1778. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1779. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1780. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1781. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1782. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1783. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1784. SSL_CTX_callback_ctrl(ctx, \
  1785. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1786. (void (*)(void))cb)
  1787. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1788. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1789. #define SSL_set_tlsext_host_name(ctx, arg) \
  1790. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1791. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1792. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1793. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1794. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1795. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1796. #define CRYPTO_set_locking_callback \
  1797. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1798. #define CRYPTO_set_id_callback \
  1799. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1800. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1801. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1802. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1803. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1804. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1805. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1806. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1807. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1808. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1809. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1810. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1811. #define X509_NAME_oneline \
  1812. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1813. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1814. #define i2c_ASN1_INTEGER \
  1815. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1816. #define EVP_get_digestbyname \
  1817. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1818. #define EVP_Digest \
  1819. (*(int (*)( \
  1820. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1821. crypto_sw[18] \
  1822. .ptr)
  1823. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1824. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1825. #define ASN1_INTEGER_to_BN \
  1826. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1827. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1828. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1829. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1830. #define OPENSSL_free(a) CRYPTO_free(a)
  1831. /* use here ERR_remove_state,
  1832. * while on some platforms function is not included into library due to
  1833. * deprication */
  1834. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1835. /* init_ssl_ctx() function updates this array.
  1836. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1837. * of respective functions. The macros above (like SSL_connect()) are really
  1838. * just calling these functions indirectly via the pointer. */
  1839. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1840. {"SSL_accept", NULL},
  1841. {"SSL_connect", NULL},
  1842. {"SSL_read", NULL},
  1843. {"SSL_write", NULL},
  1844. {"SSL_get_error", NULL},
  1845. {"SSL_set_fd", NULL},
  1846. {"SSL_new", NULL},
  1847. {"SSL_CTX_new", NULL},
  1848. {"SSLv23_server_method", NULL},
  1849. {"SSL_library_init", NULL},
  1850. {"SSL_CTX_use_PrivateKey_file", NULL},
  1851. {"SSL_CTX_use_certificate_file", NULL},
  1852. {"SSL_CTX_set_default_passwd_cb", NULL},
  1853. {"SSL_CTX_free", NULL},
  1854. {"SSL_load_error_strings", NULL},
  1855. {"SSL_CTX_use_certificate_chain_file", NULL},
  1856. {"SSLv23_client_method", NULL},
  1857. {"SSL_pending", NULL},
  1858. {"SSL_CTX_set_verify", NULL},
  1859. {"SSL_shutdown", NULL},
  1860. {"SSL_CTX_load_verify_locations", NULL},
  1861. {"SSL_CTX_set_default_verify_paths", NULL},
  1862. {"SSL_CTX_set_verify_depth", NULL},
  1863. {"SSL_get_peer_certificate", NULL},
  1864. {"SSL_get_version", NULL},
  1865. {"SSL_get_current_cipher", NULL},
  1866. {"SSL_CIPHER_get_name", NULL},
  1867. {"SSL_CTX_check_private_key", NULL},
  1868. {"SSL_CTX_set_session_id_context", NULL},
  1869. {"SSL_CTX_ctrl", NULL},
  1870. {"SSL_CTX_set_cipher_list", NULL},
  1871. {"SSL_CTX_set_info_callback", NULL},
  1872. {"SSL_get_ex_data", NULL},
  1873. {"SSL_set_ex_data", NULL},
  1874. {"SSL_CTX_callback_ctrl", NULL},
  1875. {"SSL_get_servername", NULL},
  1876. {"SSL_set_SSL_CTX", NULL},
  1877. {"SSL_ctrl", NULL},
  1878. {NULL, NULL}};
  1879. /* Similar array as ssl_sw. These functions could be located in different
  1880. * lib. */
  1881. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1882. {"CRYPTO_set_locking_callback", NULL},
  1883. {"CRYPTO_set_id_callback", NULL},
  1884. {"ERR_get_error", NULL},
  1885. {"ERR_error_string", NULL},
  1886. {"ERR_remove_state", NULL},
  1887. {"ERR_free_strings", NULL},
  1888. {"ENGINE_cleanup", NULL},
  1889. {"CONF_modules_unload", NULL},
  1890. {"CRYPTO_cleanup_all_ex_data", NULL},
  1891. {"EVP_cleanup", NULL},
  1892. {"X509_free", NULL},
  1893. {"X509_get_subject_name", NULL},
  1894. {"X509_get_issuer_name", NULL},
  1895. {"X509_NAME_oneline", NULL},
  1896. {"X509_get_serialNumber", NULL},
  1897. {"i2c_ASN1_INTEGER", NULL},
  1898. {"EVP_get_digestbyname", NULL},
  1899. {"EVP_Digest", NULL},
  1900. {"i2d_X509", NULL},
  1901. {"BN_bn2hex", NULL},
  1902. {"ASN1_INTEGER_to_BN", NULL},
  1903. {"BN_free", NULL},
  1904. {"CRYPTO_free", NULL},
  1905. {"ERR_clear_error", NULL},
  1906. {NULL, NULL}};
  1907. #endif /* OPENSSL_API_1_1 */
  1908. #endif /* NO_SSL_DL */
  1909. #endif /* NO_SSL */
  1910. #if !defined(NO_CACHING)
  1911. static const char month_names[][4] = {"Jan",
  1912. "Feb",
  1913. "Mar",
  1914. "Apr",
  1915. "May",
  1916. "Jun",
  1917. "Jul",
  1918. "Aug",
  1919. "Sep",
  1920. "Oct",
  1921. "Nov",
  1922. "Dec"};
  1923. #endif /* !NO_CACHING */
  1924. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1925. * the
  1926. * union u. */
  1927. union usa {
  1928. struct sockaddr sa;
  1929. struct sockaddr_in sin;
  1930. #if defined(USE_IPV6)
  1931. struct sockaddr_in6 sin6;
  1932. #endif
  1933. };
  1934. /* Describes a string (chunk of memory). */
  1935. struct vec {
  1936. const char *ptr;
  1937. size_t len;
  1938. };
  1939. struct mg_file_stat {
  1940. /* File properties filled by mg_stat: */
  1941. uint64_t size;
  1942. time_t last_modified;
  1943. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1944. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1945. * case we need a "Content-Eencoding: gzip" header */
  1946. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1947. };
  1948. struct mg_file_in_memory {
  1949. char *p;
  1950. uint32_t pos;
  1951. char mode;
  1952. };
  1953. struct mg_file_access {
  1954. /* File properties filled by mg_fopen: */
  1955. FILE *fp;
  1956. #if defined(MG_USE_OPEN_FILE)
  1957. /* TODO (low): Remove obsolete "file in memory" implementation.
  1958. * In an "early 2017" discussion at Google groups
  1959. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1960. * we decided to get rid of this feature (after some fade-out
  1961. * phase). */
  1962. const char *membuf;
  1963. #endif
  1964. };
  1965. struct mg_file {
  1966. struct mg_file_stat stat;
  1967. struct mg_file_access access;
  1968. };
  1969. #if defined(MG_USE_OPEN_FILE)
  1970. #define STRUCT_FILE_INITIALIZER \
  1971. { \
  1972. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1973. { \
  1974. (FILE *)NULL, (const char *)NULL \
  1975. } \
  1976. }
  1977. #else
  1978. #define STRUCT_FILE_INITIALIZER \
  1979. { \
  1980. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1981. { \
  1982. (FILE *)NULL \
  1983. } \
  1984. }
  1985. #endif
  1986. /* Describes listening socket, or socket which was accept()-ed by the master
  1987. * thread and queued for future handling by the worker thread. */
  1988. struct socket {
  1989. SOCKET sock; /* Listening socket */
  1990. union usa lsa; /* Local socket address */
  1991. union usa rsa; /* Remote socket address */
  1992. unsigned char is_ssl; /* Is port SSL-ed */
  1993. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1994. * port */
  1995. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1996. };
  1997. /* Enum const for all options must be in sync with
  1998. * static struct mg_option config_options[]
  1999. * This is tested in the unit test (test/private.c)
  2000. * "Private Config Options"
  2001. */
  2002. enum {
  2003. /* Once for each server */
  2004. LISTENING_PORTS,
  2005. NUM_THREADS,
  2006. RUN_AS_USER,
  2007. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  2008. * socket option typedef TCP_NODELAY. */
  2009. MAX_REQUEST_SIZE,
  2010. LINGER_TIMEOUT,
  2011. MAX_CONNECTIONS,
  2012. #if defined(__linux__)
  2013. ALLOW_SENDFILE_CALL,
  2014. #endif
  2015. #if defined(_WIN32)
  2016. CASE_SENSITIVE_FILES,
  2017. #endif
  2018. THROTTLE,
  2019. ACCESS_LOG_FILE,
  2020. ERROR_LOG_FILE,
  2021. ENABLE_KEEP_ALIVE,
  2022. REQUEST_TIMEOUT,
  2023. KEEP_ALIVE_TIMEOUT,
  2024. #if defined(USE_WEBSOCKET)
  2025. WEBSOCKET_TIMEOUT,
  2026. ENABLE_WEBSOCKET_PING_PONG,
  2027. #endif
  2028. DECODE_URL,
  2029. #if defined(USE_LUA)
  2030. LUA_BACKGROUND_SCRIPT,
  2031. LUA_BACKGROUND_SCRIPT_PARAMS,
  2032. #endif
  2033. #if defined(USE_TIMERS)
  2034. CGI_TIMEOUT,
  2035. #endif
  2036. /* Once for each domain */
  2037. DOCUMENT_ROOT,
  2038. CGI_EXTENSIONS,
  2039. CGI_ENVIRONMENT,
  2040. PUT_DELETE_PASSWORDS_FILE,
  2041. CGI_INTERPRETER,
  2042. PROTECT_URI,
  2043. AUTHENTICATION_DOMAIN,
  2044. ENABLE_AUTH_DOMAIN_CHECK,
  2045. SSI_EXTENSIONS,
  2046. ENABLE_DIRECTORY_LISTING,
  2047. GLOBAL_PASSWORDS_FILE,
  2048. INDEX_FILES,
  2049. ACCESS_CONTROL_LIST,
  2050. EXTRA_MIME_TYPES,
  2051. SSL_CERTIFICATE,
  2052. SSL_CERTIFICATE_CHAIN,
  2053. URL_REWRITE_PATTERN,
  2054. HIDE_FILES,
  2055. SSL_DO_VERIFY_PEER,
  2056. SSL_CA_PATH,
  2057. SSL_CA_FILE,
  2058. SSL_VERIFY_DEPTH,
  2059. SSL_DEFAULT_VERIFY_PATHS,
  2060. SSL_CIPHER_LIST,
  2061. SSL_PROTOCOL_VERSION,
  2062. SSL_SHORT_TRUST,
  2063. #if defined(USE_LUA)
  2064. LUA_PRELOAD_FILE,
  2065. LUA_SCRIPT_EXTENSIONS,
  2066. LUA_SERVER_PAGE_EXTENSIONS,
  2067. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2068. LUA_DEBUG_PARAMS,
  2069. #endif
  2070. #endif
  2071. #if defined(USE_DUKTAPE)
  2072. DUKTAPE_SCRIPT_EXTENSIONS,
  2073. #endif
  2074. #if defined(USE_WEBSOCKET)
  2075. WEBSOCKET_ROOT,
  2076. #endif
  2077. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2078. LUA_WEBSOCKET_EXTENSIONS,
  2079. #endif
  2080. ACCESS_CONTROL_ALLOW_ORIGIN,
  2081. ACCESS_CONTROL_ALLOW_METHODS,
  2082. ACCESS_CONTROL_ALLOW_HEADERS,
  2083. ERROR_PAGES,
  2084. #if !defined(NO_CACHING)
  2085. STATIC_FILE_MAX_AGE,
  2086. #endif
  2087. #if !defined(NO_SSL)
  2088. STRICT_HTTPS_MAX_AGE,
  2089. #endif
  2090. ADDITIONAL_HEADER,
  2091. ALLOW_INDEX_SCRIPT_SUB_RES,
  2092. #if defined(DAEMONIZE)
  2093. ENABLE_DAEMONIZE,
  2094. #endif
  2095. NUM_OPTIONS
  2096. };
  2097. /* Config option name, config types, default value.
  2098. * Must be in the same order as the enum const above.
  2099. */
  2100. static const struct mg_option config_options[] = {
  2101. /* Once for each server */
  2102. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2103. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2104. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2105. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2106. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2107. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2108. {"max_connections", MG_CONFIG_TYPE_NUMBER, "100"},
  2109. #if defined(__linux__)
  2110. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2111. #endif
  2112. #if defined(_WIN32)
  2113. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2114. #endif
  2115. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2116. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2117. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2118. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2119. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2120. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2121. #if defined(USE_WEBSOCKET)
  2122. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2123. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2124. #endif
  2125. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2126. #if defined(USE_LUA)
  2127. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2128. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2129. #endif
  2130. #if defined(USE_TIMERS)
  2131. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2132. #endif
  2133. /* Once for each domain */
  2134. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2135. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2136. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2137. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2138. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2139. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2140. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2141. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2142. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2143. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2144. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2145. {"index_files",
  2146. MG_CONFIG_TYPE_STRING_LIST,
  2147. #if defined(USE_LUA)
  2148. "index.xhtml,index.html,index.htm,"
  2149. "index.lp,index.lsp,index.lua,index.cgi,"
  2150. "index.shtml,index.php"},
  2151. #else
  2152. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2153. #endif
  2154. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2155. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2156. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2157. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2158. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2159. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2160. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2161. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2162. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2163. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2164. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2165. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2166. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2167. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2168. #if defined(USE_LUA)
  2169. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2170. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2171. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2172. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2173. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2174. #endif
  2175. #endif
  2176. #if defined(USE_DUKTAPE)
  2177. /* The support for duktape is still in alpha version state.
  2178. * The name of this config option might change. */
  2179. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2180. #endif
  2181. #if defined(USE_WEBSOCKET)
  2182. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2183. #endif
  2184. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2185. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2186. #endif
  2187. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2188. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2189. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2190. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2191. #if !defined(NO_CACHING)
  2192. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2193. #endif
  2194. #if !defined(NO_SSL)
  2195. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2196. #endif
  2197. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2198. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2199. #if defined(DAEMONIZE)
  2200. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2201. #endif
  2202. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2203. /* Check if the config_options and the corresponding enum have compatible
  2204. * sizes. */
  2205. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2206. == (NUM_OPTIONS + 1),
  2207. "config_options and enum not sync");
  2208. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2209. struct mg_handler_info {
  2210. /* Name/Pattern of the URI. */
  2211. char *uri;
  2212. size_t uri_len;
  2213. /* handler type */
  2214. int handler_type;
  2215. /* Handler for http/https or authorization requests. */
  2216. mg_request_handler handler;
  2217. unsigned int refcount;
  2218. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2219. pthread_cond_t
  2220. refcount_cond; /* Signaled when handler refcount is decremented */
  2221. /* Handler for ws/wss (websocket) requests. */
  2222. mg_websocket_connect_handler connect_handler;
  2223. mg_websocket_ready_handler ready_handler;
  2224. mg_websocket_data_handler data_handler;
  2225. mg_websocket_close_handler close_handler;
  2226. /* accepted subprotocols for ws/wss requests. */
  2227. struct mg_websocket_subprotocols *subprotocols;
  2228. /* Handler for authorization requests */
  2229. mg_authorization_handler auth_handler;
  2230. /* User supplied argument for the handler function. */
  2231. void *cbdata;
  2232. /* next handler in a linked list */
  2233. struct mg_handler_info *next;
  2234. };
  2235. enum {
  2236. CONTEXT_INVALID,
  2237. CONTEXT_SERVER,
  2238. CONTEXT_HTTP_CLIENT,
  2239. CONTEXT_WS_CLIENT
  2240. };
  2241. struct mg_domain_context {
  2242. SSL_CTX *ssl_ctx; /* SSL context */
  2243. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2244. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2245. /* Server nonce */
  2246. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2247. unsigned long nonce_count; /* Used nonces, used for authentication */
  2248. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2249. /* linked list of shared lua websockets */
  2250. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2251. #endif
  2252. /* Linked list of domains */
  2253. struct mg_domain_context *next;
  2254. };
  2255. struct mg_context {
  2256. /* Part 1 - Physical context:
  2257. * This holds threads, ports, timeouts, ...
  2258. * set for the entire server, independent from the
  2259. * addressed hostname.
  2260. */
  2261. /* Connection related */
  2262. int context_type; /* See CONTEXT_* above */
  2263. struct socket *listening_sockets;
  2264. struct mg_pollfd *listening_socket_fds;
  2265. unsigned int num_listening_sockets;
  2266. struct mg_connection *worker_connections; /* The connection struct, pre-
  2267. * allocated for each worker */
  2268. #if defined(USE_SERVER_STATS)
  2269. int active_connections;
  2270. int max_connections;
  2271. int64_t total_connections;
  2272. int64_t total_requests;
  2273. int64_t total_data_read;
  2274. int64_t total_data_written;
  2275. #endif
  2276. /* Thread related */
  2277. volatile int stop_flag; /* Should we stop event loop */
  2278. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2279. pthread_t masterthreadid; /* The master thread ID */
  2280. unsigned int
  2281. cfg_worker_threads; /* The number of configured worker threads. */
  2282. pthread_t *worker_threadids; /* The worker thread IDs */
  2283. /* Connection to thread dispatching */
  2284. #if defined(ALTERNATIVE_QUEUE)
  2285. struct socket *client_socks;
  2286. void **client_wait_events;
  2287. #else
  2288. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2289. volatile int sq_head; /* Head of the socket queue */
  2290. volatile int sq_tail; /* Tail of the socket queue */
  2291. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2292. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2293. #endif
  2294. /* Memory related */
  2295. unsigned int max_request_size; /* The max request size */
  2296. #if defined(USE_SERVER_STATS)
  2297. struct mg_memory_stat ctx_memory;
  2298. #endif
  2299. /* Operating system related */
  2300. char *systemName; /* What operating system is running */
  2301. time_t start_time; /* Server start time, used for authentication
  2302. * and for diagnstics. */
  2303. #if defined(USE_TIMERS)
  2304. struct ttimers *timers;
  2305. #endif
  2306. /* Lua specific: Background operations and shared websockets */
  2307. #if defined(USE_LUA)
  2308. void *lua_background_state;
  2309. #endif
  2310. /* Server nonce */
  2311. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2312. /* Server callbacks */
  2313. struct mg_callbacks callbacks; /* User-defined callback function */
  2314. void *user_data; /* User-defined data */
  2315. /* Part 2 - Logical domain:
  2316. * This holds hostname, TLS certificate, document root, ...
  2317. * set for a domain hosted at the server.
  2318. * There may be multiple domains hosted at one physical server.
  2319. * The default domain "dd" is the first element of a list of
  2320. * domains.
  2321. */
  2322. struct mg_domain_context dd; /* default domain */
  2323. };
  2324. #if defined(USE_SERVER_STATS)
  2325. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2326. static struct mg_memory_stat *
  2327. get_memory_stat(struct mg_context *ctx)
  2328. {
  2329. if (ctx) {
  2330. return &(ctx->ctx_memory);
  2331. }
  2332. return &mg_common_memory;
  2333. }
  2334. #endif
  2335. enum {
  2336. CONNECTION_TYPE_INVALID,
  2337. CONNECTION_TYPE_REQUEST,
  2338. CONNECTION_TYPE_RESPONSE
  2339. };
  2340. struct mg_connection {
  2341. int connection_type; /* see CONNECTION_TYPE_* above */
  2342. struct mg_request_info request_info;
  2343. struct mg_response_info response_info;
  2344. struct mg_context *phys_ctx;
  2345. struct mg_domain_context *dom_ctx;
  2346. #if defined(USE_SERVER_STATS)
  2347. int conn_state; /* 0 = undef, numerical value may change in different
  2348. * versions. For the current definition, see
  2349. * mg_get_connection_info_impl */
  2350. #endif
  2351. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2352. SSL *ssl; /* SSL descriptor */
  2353. struct socket client; /* Connected client */
  2354. time_t conn_birth_time; /* Time (wall clock) when connection was
  2355. * established */
  2356. struct timespec req_time; /* Time (since system start) when the request
  2357. * was received */
  2358. int64_t num_bytes_sent; /* Total bytes sent to client */
  2359. int64_t content_len; /* How many bytes of content can be read
  2360. * !is_chunked: Content-Length header value
  2361. * or -1 (until connection closed,
  2362. * not allowed for a request)
  2363. * is_chunked: >= 0, appended gradually
  2364. */
  2365. int64_t consumed_content; /* How many bytes of content have been read */
  2366. int is_chunked; /* Transfer-Encoding is chunked:
  2367. * 0 = not chunked,
  2368. * 1 = chunked, not yet, or some data read,
  2369. * 2 = chunked, has error,
  2370. * 3 = chunked, all data read except trailer,
  2371. * 4 = chunked, all data read
  2372. */
  2373. char *buf; /* Buffer for received data */
  2374. char *path_info; /* PATH_INFO part of the URL */
  2375. int must_close; /* 1 if connection must be closed */
  2376. int accept_gzip; /* 1 if gzip encoding is accepted */
  2377. int in_error_handler; /* 1 if in handler for user defined error
  2378. * pages */
  2379. #if defined(USE_WEBSOCKET)
  2380. int in_websocket_handling; /* 1 if in read_websocket */
  2381. #endif
  2382. int handled_requests; /* Number of requests handled by this connection
  2383. */
  2384. int buf_size; /* Buffer size */
  2385. int request_len; /* Size of the request + headers in a buffer */
  2386. int data_len; /* Total size of data in a buffer */
  2387. int status_code; /* HTTP reply status code, e.g. 200 */
  2388. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2389. * throttle */
  2390. time_t last_throttle_time; /* Last time throttled data was sent */
  2391. int last_throttle_bytes; /* Bytes sent this second */
  2392. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2393. * atomic transmissions for websockets */
  2394. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2395. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2396. #endif
  2397. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2398. * for quick access */
  2399. };
  2400. /* Directory entry */
  2401. struct de {
  2402. struct mg_connection *conn;
  2403. char *file_name;
  2404. struct mg_file_stat file;
  2405. };
  2406. #if defined(USE_WEBSOCKET)
  2407. static int is_websocket_protocol(const struct mg_connection *conn);
  2408. #else
  2409. #define is_websocket_protocol(conn) (0)
  2410. #endif
  2411. #define mg_cry_internal(conn, fmt, ...) \
  2412. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2413. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2414. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2415. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2416. struct mg_context *ctx,
  2417. const char *func,
  2418. unsigned line,
  2419. const char *fmt,
  2420. ...) PRINTF_ARGS(5, 6);
  2421. #if !defined(NO_THREAD_NAME)
  2422. #if defined(_WIN32) && defined(_MSC_VER)
  2423. /* Set the thread name for debugging purposes in Visual Studio
  2424. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2425. */
  2426. #pragma pack(push, 8)
  2427. typedef struct tagTHREADNAME_INFO {
  2428. DWORD dwType; /* Must be 0x1000. */
  2429. LPCSTR szName; /* Pointer to name (in user addr space). */
  2430. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2431. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2432. } THREADNAME_INFO;
  2433. #pragma pack(pop)
  2434. #elif defined(__linux__)
  2435. #include <sys/prctl.h>
  2436. #include <sys/sendfile.h>
  2437. #if defined(ALTERNATIVE_QUEUE)
  2438. #include <sys/eventfd.h>
  2439. #endif /* ALTERNATIVE_QUEUE */
  2440. #if defined(ALTERNATIVE_QUEUE)
  2441. static void *
  2442. event_create(void)
  2443. {
  2444. int evhdl = eventfd(0, EFD_CLOEXEC);
  2445. int *ret;
  2446. if (evhdl == -1) {
  2447. /* Linux uses -1 on error, Windows NULL. */
  2448. /* However, Linux does not return 0 on success either. */
  2449. return 0;
  2450. }
  2451. ret = (int *)mg_malloc(sizeof(int));
  2452. if (ret) {
  2453. *ret = evhdl;
  2454. } else {
  2455. (void)close(evhdl);
  2456. }
  2457. return (void *)ret;
  2458. }
  2459. static int
  2460. event_wait(void *eventhdl)
  2461. {
  2462. uint64_t u;
  2463. int evhdl, s;
  2464. if (!eventhdl) {
  2465. /* error */
  2466. return 0;
  2467. }
  2468. evhdl = *(int *)eventhdl;
  2469. s = (int)read(evhdl, &u, sizeof(u));
  2470. if (s != sizeof(u)) {
  2471. /* error */
  2472. return 0;
  2473. }
  2474. (void)u; /* the value is not required */
  2475. return 1;
  2476. }
  2477. static int
  2478. event_signal(void *eventhdl)
  2479. {
  2480. uint64_t u = 1;
  2481. int evhdl, s;
  2482. if (!eventhdl) {
  2483. /* error */
  2484. return 0;
  2485. }
  2486. evhdl = *(int *)eventhdl;
  2487. s = (int)write(evhdl, &u, sizeof(u));
  2488. if (s != sizeof(u)) {
  2489. /* error */
  2490. return 0;
  2491. }
  2492. return 1;
  2493. }
  2494. static void
  2495. event_destroy(void *eventhdl)
  2496. {
  2497. int evhdl;
  2498. if (!eventhdl) {
  2499. /* error */
  2500. return;
  2501. }
  2502. evhdl = *(int *)eventhdl;
  2503. close(evhdl);
  2504. mg_free(eventhdl);
  2505. }
  2506. #endif
  2507. #endif
  2508. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2509. struct posix_event {
  2510. pthread_mutex_t mutex;
  2511. pthread_cond_t cond;
  2512. int signaled;
  2513. };
  2514. static void *
  2515. event_create(void)
  2516. {
  2517. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2518. if (ret == 0) {
  2519. /* out of memory */
  2520. return 0;
  2521. }
  2522. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2523. /* pthread mutex not available */
  2524. mg_free(ret);
  2525. return 0;
  2526. }
  2527. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2528. /* pthread cond not available */
  2529. pthread_mutex_destroy(&(ret->mutex));
  2530. mg_free(ret);
  2531. return 0;
  2532. }
  2533. ret->signaled = 0;
  2534. return (void *)ret;
  2535. }
  2536. static int
  2537. event_wait(void *eventhdl)
  2538. {
  2539. struct posix_event *ev = (struct posix_event *)eventhdl;
  2540. pthread_mutex_lock(&(ev->mutex));
  2541. while (!ev->signaled) {
  2542. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2543. }
  2544. ev->signaled = 0;
  2545. pthread_mutex_unlock(&(ev->mutex));
  2546. return 1;
  2547. }
  2548. static int
  2549. event_signal(void *eventhdl)
  2550. {
  2551. struct posix_event *ev = (struct posix_event *)eventhdl;
  2552. pthread_mutex_lock(&(ev->mutex));
  2553. pthread_cond_signal(&(ev->cond));
  2554. ev->signaled = 1;
  2555. pthread_mutex_unlock(&(ev->mutex));
  2556. return 1;
  2557. }
  2558. static void
  2559. event_destroy(void *eventhdl)
  2560. {
  2561. struct posix_event *ev = (struct posix_event *)eventhdl;
  2562. pthread_cond_destroy(&(ev->cond));
  2563. pthread_mutex_destroy(&(ev->mutex));
  2564. mg_free(ev);
  2565. }
  2566. #endif
  2567. static void
  2568. mg_set_thread_name(const char *name)
  2569. {
  2570. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2571. mg_snprintf(
  2572. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2573. #if defined(_WIN32)
  2574. #if defined(_MSC_VER)
  2575. /* Windows and Visual Studio Compiler */
  2576. __try {
  2577. THREADNAME_INFO info;
  2578. info.dwType = 0x1000;
  2579. info.szName = threadName;
  2580. info.dwThreadID = ~0U;
  2581. info.dwFlags = 0;
  2582. RaiseException(0x406D1388,
  2583. 0,
  2584. sizeof(info) / sizeof(ULONG_PTR),
  2585. (ULONG_PTR *)&info);
  2586. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2587. }
  2588. #elif defined(__MINGW32__)
  2589. /* No option known to set thread name for MinGW */
  2590. #endif
  2591. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2592. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2593. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2594. #if defined(__MACH__)
  2595. /* OS X only current thread name can be changed */
  2596. (void)pthread_setname_np(threadName);
  2597. #else
  2598. (void)pthread_setname_np(pthread_self(), threadName);
  2599. #endif
  2600. #elif defined(__linux__)
  2601. /* on linux we can use the old prctl function */
  2602. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2603. #endif
  2604. }
  2605. #else /* !defined(NO_THREAD_NAME) */
  2606. void
  2607. mg_set_thread_name(const char *threadName)
  2608. {
  2609. }
  2610. #endif
  2611. #if defined(MG_LEGACY_INTERFACE)
  2612. const char **
  2613. mg_get_valid_option_names(void)
  2614. {
  2615. /* This function is deprecated. Use mg_get_valid_options instead. */
  2616. static const char
  2617. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2618. int i;
  2619. for (i = 0; config_options[i].name != NULL; i++) {
  2620. data[i * 2] = config_options[i].name;
  2621. data[i * 2 + 1] = config_options[i].default_value;
  2622. }
  2623. return data;
  2624. }
  2625. #endif
  2626. const struct mg_option *
  2627. mg_get_valid_options(void)
  2628. {
  2629. return config_options;
  2630. }
  2631. /* Do not open file (used in is_file_in_memory) */
  2632. #define MG_FOPEN_MODE_NONE (0)
  2633. /* Open file for read only access */
  2634. #define MG_FOPEN_MODE_READ (1)
  2635. /* Open file for writing, create and overwrite */
  2636. #define MG_FOPEN_MODE_WRITE (2)
  2637. /* Open file for writing, create and append */
  2638. #define MG_FOPEN_MODE_APPEND (4)
  2639. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2640. * output filep and return 1, otherwise return 0 and don't modify anything.
  2641. */
  2642. static int
  2643. open_file_in_memory(const struct mg_connection *conn,
  2644. const char *path,
  2645. struct mg_file *filep,
  2646. int mode)
  2647. {
  2648. #if defined(MG_USE_OPEN_FILE)
  2649. size_t size = 0;
  2650. const char *buf = NULL;
  2651. if (!conn) {
  2652. return 0;
  2653. }
  2654. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2655. return 0;
  2656. }
  2657. if (conn->phys_ctx->callbacks.open_file) {
  2658. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2659. if (buf != NULL) {
  2660. if (filep == NULL) {
  2661. /* This is a file in memory, but we cannot store the
  2662. * properties
  2663. * now.
  2664. * Called from "is_file_in_memory" function. */
  2665. return 1;
  2666. }
  2667. /* NOTE: override filep->size only on success. Otherwise, it
  2668. * might
  2669. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2670. filep->access.membuf = buf;
  2671. filep->access.fp = NULL;
  2672. /* Size was set by the callback */
  2673. filep->stat.size = size;
  2674. /* Assume the data may change during runtime by setting
  2675. * last_modified = now */
  2676. filep->stat.last_modified = time(NULL);
  2677. filep->stat.is_directory = 0;
  2678. filep->stat.is_gzipped = 0;
  2679. }
  2680. }
  2681. return (buf != NULL);
  2682. #else
  2683. (void)conn;
  2684. (void)path;
  2685. (void)filep;
  2686. (void)mode;
  2687. return 0;
  2688. #endif
  2689. }
  2690. static int
  2691. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2692. {
  2693. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2694. }
  2695. static int
  2696. is_file_opened(const struct mg_file_access *fileacc)
  2697. {
  2698. if (!fileacc) {
  2699. return 0;
  2700. }
  2701. #if defined(MG_USE_OPEN_FILE)
  2702. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2703. #else
  2704. return (fileacc->fp != NULL);
  2705. #endif
  2706. }
  2707. #if !defined(NO_FILESYSTEMS)
  2708. static int mg_stat(const struct mg_connection *conn,
  2709. const char *path,
  2710. struct mg_file_stat *filep);
  2711. /* mg_fopen will open a file either in memory or on the disk.
  2712. * The input parameter path is a string in UTF-8 encoding.
  2713. * The input parameter mode is MG_FOPEN_MODE_*
  2714. * On success, either fp or membuf will be set in the output
  2715. * struct file. All status members will also be set.
  2716. * The function returns 1 on success, 0 on error. */
  2717. static int
  2718. mg_fopen(const struct mg_connection *conn,
  2719. const char *path,
  2720. int mode,
  2721. struct mg_file *filep)
  2722. {
  2723. int found;
  2724. if (!filep) {
  2725. return 0;
  2726. }
  2727. filep->access.fp = NULL;
  2728. #if defined(MG_USE_OPEN_FILE)
  2729. filep->access.membuf = NULL;
  2730. #endif
  2731. if (!is_file_in_memory(conn, path)) {
  2732. /* filep is initialized in mg_stat: all fields with memset to,
  2733. * some fields like size and modification date with values */
  2734. found = mg_stat(conn, path, &(filep->stat));
  2735. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2736. /* file does not exist and will not be created */
  2737. return 0;
  2738. }
  2739. #if defined(_WIN32)
  2740. {
  2741. wchar_t wbuf[W_PATH_MAX];
  2742. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2743. switch (mode) {
  2744. case MG_FOPEN_MODE_READ:
  2745. filep->access.fp = _wfopen(wbuf, L"rb");
  2746. break;
  2747. case MG_FOPEN_MODE_WRITE:
  2748. filep->access.fp = _wfopen(wbuf, L"wb");
  2749. break;
  2750. case MG_FOPEN_MODE_APPEND:
  2751. filep->access.fp = _wfopen(wbuf, L"ab");
  2752. break;
  2753. }
  2754. }
  2755. #else
  2756. /* Linux et al already use unicode. No need to convert. */
  2757. switch (mode) {
  2758. case MG_FOPEN_MODE_READ:
  2759. filep->access.fp = fopen(path, "r");
  2760. break;
  2761. case MG_FOPEN_MODE_WRITE:
  2762. filep->access.fp = fopen(path, "w");
  2763. break;
  2764. case MG_FOPEN_MODE_APPEND:
  2765. filep->access.fp = fopen(path, "a");
  2766. break;
  2767. }
  2768. #endif
  2769. if (!found) {
  2770. /* File did not exist before fopen was called.
  2771. * Maybe it has been created now. Get stat info
  2772. * like creation time now. */
  2773. found = mg_stat(conn, path, &(filep->stat));
  2774. (void)found;
  2775. }
  2776. /* file is on disk */
  2777. return (filep->access.fp != NULL);
  2778. } else {
  2779. #if defined(MG_USE_OPEN_FILE)
  2780. /* is_file_in_memory returned true */
  2781. if (open_file_in_memory(conn, path, filep, mode)) {
  2782. /* file is in memory */
  2783. return (filep->access.membuf != NULL);
  2784. }
  2785. #endif
  2786. }
  2787. /* Open failed */
  2788. return 0;
  2789. }
  2790. /* return 0 on success, just like fclose */
  2791. static int
  2792. mg_fclose(struct mg_file_access *fileacc)
  2793. {
  2794. int ret = -1;
  2795. if (fileacc != NULL) {
  2796. if (fileacc->fp != NULL) {
  2797. ret = fclose(fileacc->fp);
  2798. #if defined(MG_USE_OPEN_FILE)
  2799. } else if (fileacc->membuf != NULL) {
  2800. ret = 0;
  2801. #endif
  2802. }
  2803. /* reset all members of fileacc */
  2804. memset(fileacc, 0, sizeof(*fileacc));
  2805. }
  2806. return ret;
  2807. }
  2808. #endif /* NO_FILESYSTEMS */
  2809. static void
  2810. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2811. {
  2812. for (; *src != '\0' && n > 1; n--) {
  2813. *dst++ = *src++;
  2814. }
  2815. *dst = '\0';
  2816. }
  2817. static int
  2818. lowercase(const char *s)
  2819. {
  2820. return tolower((unsigned char)*s);
  2821. }
  2822. int
  2823. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2824. {
  2825. int diff = 0;
  2826. if (len > 0) {
  2827. do {
  2828. diff = lowercase(s1++) - lowercase(s2++);
  2829. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2830. }
  2831. return diff;
  2832. }
  2833. int
  2834. mg_strcasecmp(const char *s1, const char *s2)
  2835. {
  2836. int diff;
  2837. do {
  2838. diff = lowercase(s1++) - lowercase(s2++);
  2839. } while (diff == 0 && s1[-1] != '\0');
  2840. return diff;
  2841. }
  2842. static char *
  2843. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2844. {
  2845. char *p;
  2846. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2847. * defined */
  2848. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2849. mg_strlcpy(p, ptr, len + 1);
  2850. }
  2851. return p;
  2852. }
  2853. static char *
  2854. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2855. {
  2856. return mg_strndup_ctx(str, strlen(str), ctx);
  2857. }
  2858. static char *
  2859. mg_strdup(const char *str)
  2860. {
  2861. return mg_strndup_ctx(str, strlen(str), NULL);
  2862. }
  2863. static const char *
  2864. mg_strcasestr(const char *big_str, const char *small_str)
  2865. {
  2866. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2867. if (big_len >= small_len) {
  2868. for (i = 0; i <= (big_len - small_len); i++) {
  2869. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2870. return big_str + i;
  2871. }
  2872. }
  2873. }
  2874. return NULL;
  2875. }
  2876. /* Return null terminated string of given maximum length.
  2877. * Report errors if length is exceeded. */
  2878. static void
  2879. mg_vsnprintf(const struct mg_connection *conn,
  2880. int *truncated,
  2881. char *buf,
  2882. size_t buflen,
  2883. const char *fmt,
  2884. va_list ap)
  2885. {
  2886. int n, ok;
  2887. if (buflen == 0) {
  2888. if (truncated) {
  2889. *truncated = 1;
  2890. }
  2891. return;
  2892. }
  2893. #if defined(__clang__)
  2894. #pragma clang diagnostic push
  2895. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2896. /* Using fmt as a non-literal is intended here, since it is mostly called
  2897. * indirectly by mg_snprintf */
  2898. #endif
  2899. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2900. ok = (n >= 0) && ((size_t)n < buflen);
  2901. #if defined(__clang__)
  2902. #pragma clang diagnostic pop
  2903. #endif
  2904. if (ok) {
  2905. if (truncated) {
  2906. *truncated = 0;
  2907. }
  2908. } else {
  2909. if (truncated) {
  2910. *truncated = 1;
  2911. }
  2912. mg_cry_internal(conn,
  2913. "truncating vsnprintf buffer: [%.*s]",
  2914. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2915. buf);
  2916. n = (int)buflen - 1;
  2917. }
  2918. buf[n] = '\0';
  2919. }
  2920. static void
  2921. mg_snprintf(const struct mg_connection *conn,
  2922. int *truncated,
  2923. char *buf,
  2924. size_t buflen,
  2925. const char *fmt,
  2926. ...)
  2927. {
  2928. va_list ap;
  2929. va_start(ap, fmt);
  2930. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2931. va_end(ap);
  2932. }
  2933. static int
  2934. get_option_index(const char *name)
  2935. {
  2936. int i;
  2937. for (i = 0; config_options[i].name != NULL; i++) {
  2938. if (strcmp(config_options[i].name, name) == 0) {
  2939. return i;
  2940. }
  2941. }
  2942. return -1;
  2943. }
  2944. const char *
  2945. mg_get_option(const struct mg_context *ctx, const char *name)
  2946. {
  2947. int i;
  2948. if ((i = get_option_index(name)) == -1) {
  2949. return NULL;
  2950. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2951. return "";
  2952. } else {
  2953. return ctx->dd.config[i];
  2954. }
  2955. }
  2956. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2957. struct mg_context *
  2958. mg_get_context(const struct mg_connection *conn)
  2959. {
  2960. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2961. }
  2962. void *
  2963. mg_get_user_data(const struct mg_context *ctx)
  2964. {
  2965. return (ctx == NULL) ? NULL : ctx->user_data;
  2966. }
  2967. void *
  2968. mg_get_thread_pointer(const struct mg_connection *conn)
  2969. {
  2970. /* both methods should return the same pointer */
  2971. if (conn) {
  2972. /* quick access, in case conn is known */
  2973. return conn->tls_user_ptr;
  2974. } else {
  2975. /* otherwise get pointer from thread local storage (TLS) */
  2976. struct mg_workerTLS *tls =
  2977. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2978. return tls->user_ptr;
  2979. }
  2980. }
  2981. void
  2982. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2983. {
  2984. if (conn != NULL) {
  2985. conn->request_info.conn_data = data;
  2986. }
  2987. }
  2988. void *
  2989. mg_get_user_connection_data(const struct mg_connection *conn)
  2990. {
  2991. if (conn != NULL) {
  2992. return conn->request_info.conn_data;
  2993. }
  2994. return NULL;
  2995. }
  2996. #if defined(MG_LEGACY_INTERFACE)
  2997. /* Deprecated: Use mg_get_server_ports instead. */
  2998. size_t
  2999. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  3000. {
  3001. size_t i;
  3002. if (!ctx) {
  3003. return 0;
  3004. }
  3005. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  3006. ssl[i] = ctx->listening_sockets[i].is_ssl;
  3007. ports[i] =
  3008. #if defined(USE_IPV6)
  3009. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3010. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3011. :
  3012. #endif
  3013. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3014. }
  3015. return i;
  3016. }
  3017. #endif
  3018. int
  3019. mg_get_server_ports(const struct mg_context *ctx,
  3020. int size,
  3021. struct mg_server_port *ports)
  3022. {
  3023. int i, cnt = 0;
  3024. if (size <= 0) {
  3025. return -1;
  3026. }
  3027. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3028. if (!ctx) {
  3029. return -1;
  3030. }
  3031. if (!ctx->listening_sockets) {
  3032. return -1;
  3033. }
  3034. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3035. ports[cnt].port =
  3036. #if defined(USE_IPV6)
  3037. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3038. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3039. :
  3040. #endif
  3041. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3042. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3043. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3044. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3045. /* IPv4 */
  3046. ports[cnt].protocol = 1;
  3047. cnt++;
  3048. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3049. /* IPv6 */
  3050. ports[cnt].protocol = 3;
  3051. cnt++;
  3052. }
  3053. }
  3054. return cnt;
  3055. }
  3056. static void
  3057. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3058. {
  3059. buf[0] = '\0';
  3060. if (!usa) {
  3061. return;
  3062. }
  3063. if (usa->sa.sa_family == AF_INET) {
  3064. getnameinfo(&usa->sa,
  3065. sizeof(usa->sin),
  3066. buf,
  3067. (unsigned)len,
  3068. NULL,
  3069. 0,
  3070. NI_NUMERICHOST);
  3071. }
  3072. #if defined(USE_IPV6)
  3073. else if (usa->sa.sa_family == AF_INET6) {
  3074. getnameinfo(&usa->sa,
  3075. sizeof(usa->sin6),
  3076. buf,
  3077. (unsigned)len,
  3078. NULL,
  3079. 0,
  3080. NI_NUMERICHOST);
  3081. }
  3082. #endif
  3083. }
  3084. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3085. * included in all responses other than 100, 101, 5xx. */
  3086. static void
  3087. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3088. {
  3089. #if !defined(REENTRANT_TIME)
  3090. struct tm *tm;
  3091. tm = ((t != NULL) ? gmtime(t) : NULL);
  3092. if (tm != NULL) {
  3093. #else
  3094. struct tm _tm;
  3095. struct tm *tm = &_tm;
  3096. if (t != NULL) {
  3097. gmtime_r(t, tm);
  3098. #endif
  3099. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3100. } else {
  3101. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3102. buf[buf_len - 1] = '\0';
  3103. }
  3104. }
  3105. /* difftime for struct timespec. Return value is in seconds. */
  3106. static double
  3107. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3108. {
  3109. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3110. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3111. }
  3112. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3113. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3114. const char *func,
  3115. unsigned line,
  3116. const char *fmt,
  3117. va_list ap);
  3118. #include "external_mg_cry_internal_impl.inl"
  3119. #elif !defined(NO_FILESYSTEMS)
  3120. /* Print error message to the opened error log stream. */
  3121. static void
  3122. mg_cry_internal_impl(const struct mg_connection *conn,
  3123. const char *func,
  3124. unsigned line,
  3125. const char *fmt,
  3126. va_list ap)
  3127. {
  3128. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3129. struct mg_file fi;
  3130. time_t timestamp;
  3131. /* Unused, in the RELEASE build */
  3132. (void)func;
  3133. (void)line;
  3134. #if defined(GCC_DIAGNOSTIC)
  3135. #pragma GCC diagnostic push
  3136. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3137. #endif
  3138. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3139. #if defined(GCC_DIAGNOSTIC)
  3140. #pragma GCC diagnostic pop
  3141. #endif
  3142. buf[sizeof(buf) - 1] = 0;
  3143. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3144. if (!conn) {
  3145. puts(buf);
  3146. return;
  3147. }
  3148. /* Do not lock when getting the callback value, here and below.
  3149. * I suppose this is fine, since function cannot disappear in the
  3150. * same way string option can. */
  3151. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3152. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3153. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3154. if (mg_fopen(conn,
  3155. conn->dom_ctx->config[ERROR_LOG_FILE],
  3156. MG_FOPEN_MODE_APPEND,
  3157. &fi)
  3158. == 0) {
  3159. fi.access.fp = NULL;
  3160. }
  3161. } else {
  3162. fi.access.fp = NULL;
  3163. }
  3164. if (fi.access.fp != NULL) {
  3165. flockfile(fi.access.fp);
  3166. timestamp = time(NULL);
  3167. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3168. fprintf(fi.access.fp,
  3169. "[%010lu] [error] [client %s] ",
  3170. (unsigned long)timestamp,
  3171. src_addr);
  3172. if (conn->request_info.request_method != NULL) {
  3173. fprintf(fi.access.fp,
  3174. "%s %s: ",
  3175. conn->request_info.request_method,
  3176. conn->request_info.request_uri
  3177. ? conn->request_info.request_uri
  3178. : "");
  3179. }
  3180. fprintf(fi.access.fp, "%s", buf);
  3181. fputc('\n', fi.access.fp);
  3182. fflush(fi.access.fp);
  3183. funlockfile(fi.access.fp);
  3184. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3185. * mg_cry here anyway ;-) */
  3186. }
  3187. }
  3188. }
  3189. #else
  3190. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3191. #endif /* Externally provided function */
  3192. /* Construct fake connection structure. Used for logging, if connection
  3193. * is not applicable at the moment of logging. */
  3194. static struct mg_connection *
  3195. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3196. {
  3197. static const struct mg_connection conn_zero = {0};
  3198. *fc = conn_zero;
  3199. fc->phys_ctx = ctx;
  3200. fc->dom_ctx = &(ctx->dd);
  3201. return fc;
  3202. }
  3203. static void
  3204. mg_cry_internal_wrap(const struct mg_connection *conn,
  3205. struct mg_context *ctx,
  3206. const char *func,
  3207. unsigned line,
  3208. const char *fmt,
  3209. ...)
  3210. {
  3211. va_list ap;
  3212. va_start(ap, fmt);
  3213. if (!conn && ctx) {
  3214. struct mg_connection fc;
  3215. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3216. } else {
  3217. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3218. }
  3219. va_end(ap);
  3220. }
  3221. void
  3222. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3223. {
  3224. va_list ap;
  3225. va_start(ap, fmt);
  3226. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3227. va_end(ap);
  3228. }
  3229. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3230. const char *
  3231. mg_version(void)
  3232. {
  3233. return CIVETWEB_VERSION;
  3234. }
  3235. const struct mg_request_info *
  3236. mg_get_request_info(const struct mg_connection *conn)
  3237. {
  3238. if (!conn) {
  3239. return NULL;
  3240. }
  3241. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3242. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3243. char txt[16];
  3244. struct mg_workerTLS *tls =
  3245. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3246. sprintf(txt, "%03i", conn->response_info.status_code);
  3247. if (strlen(txt) == 3) {
  3248. memcpy(tls->txtbuf, txt, 4);
  3249. } else {
  3250. strcpy(tls->txtbuf, "ERR");
  3251. }
  3252. ((struct mg_connection *)conn)->request_info.local_uri =
  3253. ((struct mg_connection *)conn)->request_info.request_uri =
  3254. tls->txtbuf; /* use thread safe buffer */
  3255. ((struct mg_connection *)conn)->request_info.num_headers =
  3256. conn->response_info.num_headers;
  3257. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3258. conn->response_info.http_headers,
  3259. sizeof(conn->response_info.http_headers));
  3260. } else
  3261. #endif
  3262. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3263. return NULL;
  3264. }
  3265. return &conn->request_info;
  3266. }
  3267. const struct mg_response_info *
  3268. mg_get_response_info(const struct mg_connection *conn)
  3269. {
  3270. if (!conn) {
  3271. return NULL;
  3272. }
  3273. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3274. return NULL;
  3275. }
  3276. return &conn->response_info;
  3277. }
  3278. static const char *
  3279. get_proto_name(const struct mg_connection *conn)
  3280. {
  3281. #if defined(__clang__)
  3282. #pragma clang diagnostic push
  3283. #pragma clang diagnostic ignored "-Wunreachable-code"
  3284. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3285. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3286. * unreachable, but splitting into four different #ifdef clauses here is more
  3287. * complicated.
  3288. */
  3289. #endif
  3290. const struct mg_request_info *ri = &conn->request_info;
  3291. const char *proto =
  3292. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3293. : (ri->is_ssl ? "https" : "http"));
  3294. return proto;
  3295. #if defined(__clang__)
  3296. #pragma clang diagnostic pop
  3297. #endif
  3298. }
  3299. int
  3300. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3301. {
  3302. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3303. return -1;
  3304. } else {
  3305. int truncated = 0;
  3306. const struct mg_request_info *ri = &conn->request_info;
  3307. const char *proto = get_proto_name(conn);
  3308. if (ri->local_uri == NULL) {
  3309. return -1;
  3310. }
  3311. if ((ri->request_uri != NULL)
  3312. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3313. /* The request uri is different from the local uri.
  3314. * This is usually if an absolute URI, including server
  3315. * name has been provided. */
  3316. mg_snprintf(conn,
  3317. &truncated,
  3318. buf,
  3319. buflen,
  3320. "%s://%s",
  3321. proto,
  3322. ri->request_uri);
  3323. if (truncated) {
  3324. return -1;
  3325. }
  3326. return 0;
  3327. } else {
  3328. /* The common case is a relative URI, so we have to
  3329. * construct an absolute URI from server name and port */
  3330. #if defined(USE_IPV6)
  3331. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3332. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3333. : htons(conn->client.lsa.sin.sin_port);
  3334. #else
  3335. int port = htons(conn->client.lsa.sin.sin_port);
  3336. #endif
  3337. int def_port = ri->is_ssl ? 443 : 80;
  3338. int auth_domain_check_enabled =
  3339. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3340. && (!mg_strcasecmp(
  3341. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3342. const char *server_domain =
  3343. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3344. char portstr[16];
  3345. char server_ip[48];
  3346. if (port != def_port) {
  3347. sprintf(portstr, ":%u", (unsigned)port);
  3348. } else {
  3349. portstr[0] = 0;
  3350. }
  3351. if (!auth_domain_check_enabled || !server_domain) {
  3352. sockaddr_to_string(server_ip,
  3353. sizeof(server_ip),
  3354. &conn->client.lsa);
  3355. server_domain = server_ip;
  3356. }
  3357. mg_snprintf(conn,
  3358. &truncated,
  3359. buf,
  3360. buflen,
  3361. "%s://%s%s%s",
  3362. proto,
  3363. server_domain,
  3364. portstr,
  3365. ri->local_uri);
  3366. if (truncated) {
  3367. return -1;
  3368. }
  3369. return 0;
  3370. }
  3371. }
  3372. }
  3373. /* Skip the characters until one of the delimiters characters found.
  3374. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3375. * Advance pointer to buffer to the next word. Return found 0-terminated
  3376. * word.
  3377. * Delimiters can be quoted with quotechar. */
  3378. static char *
  3379. skip_quoted(char **buf,
  3380. const char *delimiters,
  3381. const char *whitespace,
  3382. char quotechar)
  3383. {
  3384. char *p, *begin_word, *end_word, *end_whitespace;
  3385. begin_word = *buf;
  3386. end_word = begin_word + strcspn(begin_word, delimiters);
  3387. /* Check for quotechar */
  3388. if (end_word > begin_word) {
  3389. p = end_word - 1;
  3390. while (*p == quotechar) {
  3391. /* While the delimiter is quoted, look for the next delimiter.
  3392. */
  3393. /* This happens, e.g., in calls from parse_auth_header,
  3394. * if the user name contains a " character. */
  3395. /* If there is anything beyond end_word, copy it. */
  3396. if (*end_word != '\0') {
  3397. size_t end_off = strcspn(end_word + 1, delimiters);
  3398. memmove(p, end_word, end_off + 1);
  3399. p += end_off; /* p must correspond to end_word - 1 */
  3400. end_word += end_off + 1;
  3401. } else {
  3402. *p = '\0';
  3403. break;
  3404. }
  3405. }
  3406. for (p++; p < end_word; p++) {
  3407. *p = '\0';
  3408. }
  3409. }
  3410. if (*end_word == '\0') {
  3411. *buf = end_word;
  3412. } else {
  3413. #if defined(GCC_DIAGNOSTIC)
  3414. /* Disable spurious conversion warning for GCC */
  3415. #pragma GCC diagnostic push
  3416. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3417. #endif /* defined(GCC_DIAGNOSTIC) */
  3418. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3419. #if defined(GCC_DIAGNOSTIC)
  3420. #pragma GCC diagnostic pop
  3421. #endif /* defined(GCC_DIAGNOSTIC) */
  3422. for (p = end_word; p < end_whitespace; p++) {
  3423. *p = '\0';
  3424. }
  3425. *buf = end_whitespace;
  3426. }
  3427. return begin_word;
  3428. }
  3429. /* Return HTTP header value, or NULL if not found. */
  3430. static const char *
  3431. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3432. {
  3433. int i;
  3434. for (i = 0; i < num_hdr; i++) {
  3435. if (!mg_strcasecmp(name, hdr[i].name)) {
  3436. return hdr[i].value;
  3437. }
  3438. }
  3439. return NULL;
  3440. }
  3441. #if defined(USE_WEBSOCKET)
  3442. /* Retrieve requested HTTP header multiple values, and return the number of
  3443. * found occurrences */
  3444. static int
  3445. get_req_headers(const struct mg_request_info *ri,
  3446. const char *name,
  3447. const char **output,
  3448. int output_max_size)
  3449. {
  3450. int i;
  3451. int cnt = 0;
  3452. if (ri) {
  3453. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3454. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3455. output[cnt++] = ri->http_headers[i].value;
  3456. }
  3457. }
  3458. }
  3459. return cnt;
  3460. }
  3461. #endif
  3462. const char *
  3463. mg_get_header(const struct mg_connection *conn, const char *name)
  3464. {
  3465. if (!conn) {
  3466. return NULL;
  3467. }
  3468. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3469. return get_header(conn->request_info.http_headers,
  3470. conn->request_info.num_headers,
  3471. name);
  3472. }
  3473. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3474. return get_header(conn->response_info.http_headers,
  3475. conn->response_info.num_headers,
  3476. name);
  3477. }
  3478. return NULL;
  3479. }
  3480. static const char *
  3481. get_http_version(const struct mg_connection *conn)
  3482. {
  3483. if (!conn) {
  3484. return NULL;
  3485. }
  3486. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3487. return conn->request_info.http_version;
  3488. }
  3489. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3490. return conn->response_info.http_version;
  3491. }
  3492. return NULL;
  3493. }
  3494. /* A helper function for traversing a comma separated list of values.
  3495. * It returns a list pointer shifted to the next value, or NULL if the end
  3496. * of the list found.
  3497. * Value is stored in val vector. If value has form "x=y", then eq_val
  3498. * vector is initialized to point to the "y" part, and val vector length
  3499. * is adjusted to point only to "x". */
  3500. static const char *
  3501. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3502. {
  3503. int end;
  3504. reparse:
  3505. if (val == NULL || list == NULL || *list == '\0') {
  3506. /* End of the list */
  3507. return NULL;
  3508. }
  3509. /* Skip over leading LWS */
  3510. while (*list == ' ' || *list == '\t')
  3511. list++;
  3512. val->ptr = list;
  3513. if ((list = strchr(val->ptr, ',')) != NULL) {
  3514. /* Comma found. Store length and shift the list ptr */
  3515. val->len = ((size_t)(list - val->ptr));
  3516. list++;
  3517. } else {
  3518. /* This value is the last one */
  3519. list = val->ptr + strlen(val->ptr);
  3520. val->len = ((size_t)(list - val->ptr));
  3521. }
  3522. /* Adjust length for trailing LWS */
  3523. end = (int)val->len - 1;
  3524. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3525. end--;
  3526. val->len = (size_t)(end) + (size_t)(1);
  3527. if (val->len == 0) {
  3528. /* Ignore any empty entries. */
  3529. goto reparse;
  3530. }
  3531. if (eq_val != NULL) {
  3532. /* Value has form "x=y", adjust pointers and lengths
  3533. * so that val points to "x", and eq_val points to "y". */
  3534. eq_val->len = 0;
  3535. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3536. if (eq_val->ptr != NULL) {
  3537. eq_val->ptr++; /* Skip over '=' character */
  3538. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3539. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3540. }
  3541. }
  3542. return list;
  3543. }
  3544. /* A helper function for checking if a comma separated list of values
  3545. * contains
  3546. * the given option (case insensitvely).
  3547. * 'header' can be NULL, in which case false is returned. */
  3548. static int
  3549. header_has_option(const char *header, const char *option)
  3550. {
  3551. struct vec opt_vec;
  3552. struct vec eq_vec;
  3553. DEBUG_ASSERT(option != NULL);
  3554. DEBUG_ASSERT(option[0] != '\0');
  3555. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3556. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3557. return 1;
  3558. }
  3559. return 0;
  3560. }
  3561. /* Perform case-insensitive match of string against pattern */
  3562. static ptrdiff_t
  3563. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3564. {
  3565. const char *or_str;
  3566. ptrdiff_t i, j, len, res;
  3567. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3568. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3569. return (res > 0) ? res
  3570. : match_prefix(or_str + 1,
  3571. (size_t)((pattern + pattern_len)
  3572. - (or_str + 1)),
  3573. str);
  3574. }
  3575. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3576. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3577. continue;
  3578. } else if (pattern[i] == '$') {
  3579. return (str[j] == '\0') ? j : -1;
  3580. } else if (pattern[i] == '*') {
  3581. i++;
  3582. if (pattern[i] == '*') {
  3583. i++;
  3584. len = strlen(str + j);
  3585. } else {
  3586. len = strcspn(str + j, "/");
  3587. }
  3588. if (i == (ptrdiff_t)pattern_len) {
  3589. return j + len;
  3590. }
  3591. do {
  3592. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3593. } while (res == -1 && len-- > 0);
  3594. return (res == -1) ? -1 : j + res + len;
  3595. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3596. return -1;
  3597. }
  3598. }
  3599. return (ptrdiff_t)j;
  3600. }
  3601. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3602. * This function must tolerate situations when connection info is not
  3603. * set up, for example if request parsing failed. */
  3604. static int
  3605. should_keep_alive(const struct mg_connection *conn)
  3606. {
  3607. const char *http_version;
  3608. const char *header;
  3609. /* First satisfy needs of the server */
  3610. if ((conn == NULL) || conn->must_close) {
  3611. /* Close, if civetweb framework needs to close */
  3612. return 0;
  3613. }
  3614. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3615. /* Close, if keep alive is not enabled */
  3616. return 0;
  3617. }
  3618. /* Check explicit wish of the client */
  3619. header = mg_get_header(conn, "Connection");
  3620. if (header) {
  3621. /* If there is a connection header from the client, obey */
  3622. if (header_has_option(header, "keep-alive")) {
  3623. return 1;
  3624. }
  3625. return 0;
  3626. }
  3627. /* Use default of the standard */
  3628. http_version = get_http_version(conn);
  3629. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3630. /* HTTP 1.1 default is keep alive */
  3631. return 1;
  3632. }
  3633. /* HTTP 1.0 (and earlier) default is to close the connection */
  3634. return 0;
  3635. }
  3636. static int
  3637. should_decode_url(const struct mg_connection *conn)
  3638. {
  3639. if (!conn || !conn->dom_ctx) {
  3640. return 0;
  3641. }
  3642. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3643. }
  3644. static const char *
  3645. suggest_connection_header(const struct mg_connection *conn)
  3646. {
  3647. return should_keep_alive(conn) ? "keep-alive" : "close";
  3648. }
  3649. static int
  3650. send_no_cache_header(struct mg_connection *conn)
  3651. {
  3652. /* Send all current and obsolete cache opt-out directives. */
  3653. return mg_printf(conn,
  3654. "Cache-Control: no-cache, no-store, "
  3655. "must-revalidate, private, max-age=0\r\n"
  3656. "Pragma: no-cache\r\n"
  3657. "Expires: 0\r\n");
  3658. }
  3659. static int
  3660. send_static_cache_header(struct mg_connection *conn)
  3661. {
  3662. #if !defined(NO_CACHING)
  3663. /* Read the server config to check how long a file may be cached.
  3664. * The configuration is in seconds. */
  3665. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3666. if (max_age <= 0) {
  3667. /* 0 means "do not cache". All values <0 are reserved
  3668. * and may be used differently in the future. */
  3669. /* If a file should not be cached, do not only send
  3670. * max-age=0, but also pragmas and Expires headers. */
  3671. return send_no_cache_header(conn);
  3672. }
  3673. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3674. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3675. /* See also https://www.mnot.net/cache_docs/ */
  3676. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3677. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3678. * leap
  3679. * year to 31622400 seconds. For the moment, we just send whatever has
  3680. * been configured, still the behavior for >1 year should be considered
  3681. * as undefined. */
  3682. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3683. #else /* NO_CACHING */
  3684. return send_no_cache_header(conn);
  3685. #endif /* !NO_CACHING */
  3686. }
  3687. static int
  3688. send_additional_header(struct mg_connection *conn)
  3689. {
  3690. int i = 0;
  3691. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3692. #if !defined(NO_SSL)
  3693. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3694. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3695. if (max_age >= 0) {
  3696. i += mg_printf(conn,
  3697. "Strict-Transport-Security: max-age=%u\r\n",
  3698. (unsigned)max_age);
  3699. }
  3700. }
  3701. #endif
  3702. if (header && header[0]) {
  3703. i += mg_printf(conn, "%s\r\n", header);
  3704. }
  3705. return i;
  3706. }
  3707. #if !defined(NO_FILESYSTEMS)
  3708. static void handle_file_based_request(struct mg_connection *conn,
  3709. const char *path,
  3710. struct mg_file *filep);
  3711. #endif /* NO_FILESYSTEMS */
  3712. const char *
  3713. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3714. {
  3715. /* See IANA HTTP status code assignment:
  3716. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3717. */
  3718. switch (response_code) {
  3719. /* RFC2616 Section 10.1 - Informational 1xx */
  3720. case 100:
  3721. return "Continue"; /* RFC2616 Section 10.1.1 */
  3722. case 101:
  3723. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3724. case 102:
  3725. return "Processing"; /* RFC2518 Section 10.1 */
  3726. /* RFC2616 Section 10.2 - Successful 2xx */
  3727. case 200:
  3728. return "OK"; /* RFC2616 Section 10.2.1 */
  3729. case 201:
  3730. return "Created"; /* RFC2616 Section 10.2.2 */
  3731. case 202:
  3732. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3733. case 203:
  3734. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3735. case 204:
  3736. return "No Content"; /* RFC2616 Section 10.2.5 */
  3737. case 205:
  3738. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3739. case 206:
  3740. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3741. case 207:
  3742. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3743. */
  3744. case 208:
  3745. return "Already Reported"; /* RFC5842 Section 7.1 */
  3746. case 226:
  3747. return "IM used"; /* RFC3229 Section 10.4.1 */
  3748. /* RFC2616 Section 10.3 - Redirection 3xx */
  3749. case 300:
  3750. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3751. case 301:
  3752. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3753. case 302:
  3754. return "Found"; /* RFC2616 Section 10.3.3 */
  3755. case 303:
  3756. return "See Other"; /* RFC2616 Section 10.3.4 */
  3757. case 304:
  3758. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3759. case 305:
  3760. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3761. case 307:
  3762. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3763. case 308:
  3764. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3765. /* RFC2616 Section 10.4 - Client Error 4xx */
  3766. case 400:
  3767. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3768. case 401:
  3769. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3770. case 402:
  3771. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3772. case 403:
  3773. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3774. case 404:
  3775. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3776. case 405:
  3777. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3778. case 406:
  3779. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3780. case 407:
  3781. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3782. case 408:
  3783. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3784. case 409:
  3785. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3786. case 410:
  3787. return "Gone"; /* RFC2616 Section 10.4.11 */
  3788. case 411:
  3789. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3790. case 412:
  3791. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3792. case 413:
  3793. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3794. case 414:
  3795. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3796. case 415:
  3797. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3798. case 416:
  3799. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3800. */
  3801. case 417:
  3802. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3803. case 421:
  3804. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3805. case 422:
  3806. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3807. * Section 11.2 */
  3808. case 423:
  3809. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3810. case 424:
  3811. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3812. * Section 11.4 */
  3813. case 426:
  3814. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3815. case 428:
  3816. return "Precondition Required"; /* RFC 6585, Section 3 */
  3817. case 429:
  3818. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3819. case 431:
  3820. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3821. case 451:
  3822. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3823. * Section 3 */
  3824. /* RFC2616 Section 10.5 - Server Error 5xx */
  3825. case 500:
  3826. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3827. case 501:
  3828. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3829. case 502:
  3830. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3831. case 503:
  3832. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3833. case 504:
  3834. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3835. case 505:
  3836. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3837. case 506:
  3838. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3839. case 507:
  3840. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3841. * Section 11.5 */
  3842. case 508:
  3843. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3844. case 510:
  3845. return "Not Extended"; /* RFC 2774, Section 7 */
  3846. case 511:
  3847. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3848. /* Other status codes, not shown in the IANA HTTP status code
  3849. * assignment.
  3850. * E.g., "de facto" standards due to common use, ... */
  3851. case 418:
  3852. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3853. case 419:
  3854. return "Authentication Timeout"; /* common use */
  3855. case 420:
  3856. return "Enhance Your Calm"; /* common use */
  3857. case 440:
  3858. return "Login Timeout"; /* common use */
  3859. case 509:
  3860. return "Bandwidth Limit Exceeded"; /* common use */
  3861. default:
  3862. /* This error code is unknown. This should not happen. */
  3863. if (conn) {
  3864. mg_cry_internal(conn,
  3865. "Unknown HTTP response code: %u",
  3866. response_code);
  3867. }
  3868. /* Return at least a category according to RFC 2616 Section 10. */
  3869. if (response_code >= 100 && response_code < 200) {
  3870. /* Unknown informational status code */
  3871. return "Information";
  3872. }
  3873. if (response_code >= 200 && response_code < 300) {
  3874. /* Unknown success code */
  3875. return "Success";
  3876. }
  3877. if (response_code >= 300 && response_code < 400) {
  3878. /* Unknown redirection code */
  3879. return "Redirection";
  3880. }
  3881. if (response_code >= 400 && response_code < 500) {
  3882. /* Unknown request error code */
  3883. return "Client Error";
  3884. }
  3885. if (response_code >= 500 && response_code < 600) {
  3886. /* Unknown server error code */
  3887. return "Server Error";
  3888. }
  3889. /* Response code not even within reasonable range */
  3890. return "";
  3891. }
  3892. }
  3893. static int
  3894. mg_send_http_error_impl(struct mg_connection *conn,
  3895. int status,
  3896. const char *fmt,
  3897. va_list args)
  3898. {
  3899. char errmsg_buf[MG_BUF_LEN];
  3900. va_list ap;
  3901. int has_body;
  3902. char date[64];
  3903. time_t curtime = time(NULL);
  3904. #if !defined(NO_FILESYSTEMS)
  3905. char path_buf[PATH_MAX];
  3906. int len, i, page_handler_found, scope, truncated;
  3907. const char *error_handler = NULL;
  3908. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3909. const char *error_page_file_ext, *tstr;
  3910. #endif /* NO_FILESYSTEMS */
  3911. int handled_by_callback = 0;
  3912. const char *status_text = mg_get_response_code_text(conn, status);
  3913. if ((conn == NULL) || (fmt == NULL)) {
  3914. return -2;
  3915. }
  3916. /* Set status (for log) */
  3917. conn->status_code = status;
  3918. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3919. has_body = ((status > 199) && (status != 204) && (status != 304));
  3920. /* Prepare message in buf, if required */
  3921. if (has_body
  3922. || (!conn->in_error_handler
  3923. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3924. /* Store error message in errmsg_buf */
  3925. va_copy(ap, args);
  3926. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3927. va_end(ap);
  3928. /* In a debug build, print all html errors */
  3929. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3930. }
  3931. /* If there is a http_error callback, call it.
  3932. * But don't do it recursively, if callback calls mg_send_http_error again.
  3933. */
  3934. if (!conn->in_error_handler
  3935. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3936. /* Mark in_error_handler to avoid recursion and call user callback. */
  3937. conn->in_error_handler = 1;
  3938. handled_by_callback =
  3939. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3940. == 0);
  3941. conn->in_error_handler = 0;
  3942. }
  3943. if (!handled_by_callback) {
  3944. /* Check for recursion */
  3945. if (conn->in_error_handler) {
  3946. DEBUG_TRACE(
  3947. "Recursion when handling error %u - fall back to default",
  3948. status);
  3949. #if !defined(NO_FILESYSTEMS)
  3950. } else {
  3951. /* Send user defined error pages, if defined */
  3952. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3953. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3954. page_handler_found = 0;
  3955. if (error_handler != NULL) {
  3956. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3957. switch (scope) {
  3958. case 1: /* Handler for specific error, e.g. 404 error */
  3959. mg_snprintf(conn,
  3960. &truncated,
  3961. path_buf,
  3962. sizeof(path_buf) - 32,
  3963. "%serror%03u.",
  3964. error_handler,
  3965. status);
  3966. break;
  3967. case 2: /* Handler for error group, e.g., 5xx error
  3968. * handler
  3969. * for all server errors (500-599) */
  3970. mg_snprintf(conn,
  3971. &truncated,
  3972. path_buf,
  3973. sizeof(path_buf) - 32,
  3974. "%serror%01uxx.",
  3975. error_handler,
  3976. status / 100);
  3977. break;
  3978. default: /* Handler for all errors */
  3979. mg_snprintf(conn,
  3980. &truncated,
  3981. path_buf,
  3982. sizeof(path_buf) - 32,
  3983. "%serror.",
  3984. error_handler);
  3985. break;
  3986. }
  3987. /* String truncation in buf may only occur if
  3988. * error_handler is too long. This string is
  3989. * from the config, not from a client. */
  3990. (void)truncated;
  3991. len = (int)strlen(path_buf);
  3992. tstr = strchr(error_page_file_ext, '.');
  3993. while (tstr) {
  3994. for (i = 1;
  3995. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3996. i++) {
  3997. /* buffer overrun is not possible here, since
  3998. * (i < 32) && (len < sizeof(path_buf) - 32)
  3999. * ==> (i + len) < sizeof(path_buf) */
  4000. path_buf[len + i - 1] = tstr[i];
  4001. }
  4002. /* buffer overrun is not possible here, since
  4003. * (i <= 32) && (len < sizeof(path_buf) - 32)
  4004. * ==> (i + len) <= sizeof(path_buf) */
  4005. path_buf[len + i - 1] = 0;
  4006. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  4007. DEBUG_TRACE("Check error page %s - found",
  4008. path_buf);
  4009. page_handler_found = 1;
  4010. break;
  4011. }
  4012. DEBUG_TRACE("Check error page %s - not found",
  4013. path_buf);
  4014. tstr = strchr(tstr + i, '.');
  4015. }
  4016. }
  4017. }
  4018. if (page_handler_found) {
  4019. conn->in_error_handler = 1;
  4020. handle_file_based_request(conn, path_buf, &error_page_file);
  4021. conn->in_error_handler = 0;
  4022. return 0;
  4023. }
  4024. #endif /* NO_FILESYSTEMS */
  4025. }
  4026. /* No custom error page. Send default error page. */
  4027. gmt_time_string(date, sizeof(date), &curtime);
  4028. conn->must_close = 1;
  4029. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4030. send_no_cache_header(conn);
  4031. send_additional_header(conn);
  4032. if (has_body) {
  4033. mg_printf(conn,
  4034. "%s",
  4035. "Content-Type: text/plain; charset=utf-8\r\n");
  4036. }
  4037. mg_printf(conn,
  4038. "Date: %s\r\n"
  4039. "Connection: close\r\n\r\n",
  4040. date);
  4041. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4042. if (has_body) {
  4043. /* For other errors, send a generic error message. */
  4044. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4045. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4046. } else {
  4047. /* No body allowed. Close the connection. */
  4048. DEBUG_TRACE("Error %i", status);
  4049. }
  4050. }
  4051. return 0;
  4052. }
  4053. int
  4054. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4055. {
  4056. va_list ap;
  4057. int ret;
  4058. va_start(ap, fmt);
  4059. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4060. va_end(ap);
  4061. return ret;
  4062. }
  4063. int
  4064. mg_send_http_ok(struct mg_connection *conn,
  4065. const char *mime_type,
  4066. long long content_length)
  4067. {
  4068. char date[64];
  4069. time_t curtime = time(NULL);
  4070. if ((mime_type == NULL) || (*mime_type == 0)) {
  4071. /* Parameter error */
  4072. return -2;
  4073. }
  4074. gmt_time_string(date, sizeof(date), &curtime);
  4075. mg_printf(conn,
  4076. "HTTP/1.1 200 OK\r\n"
  4077. "Content-Type: %s\r\n"
  4078. "Date: %s\r\n"
  4079. "Connection: %s\r\n",
  4080. mime_type,
  4081. date,
  4082. suggest_connection_header(conn));
  4083. send_no_cache_header(conn);
  4084. send_additional_header(conn);
  4085. if (content_length < 0) {
  4086. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4087. } else {
  4088. mg_printf(conn,
  4089. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4090. (uint64_t)content_length);
  4091. }
  4092. return 0;
  4093. }
  4094. int
  4095. mg_send_http_redirect(struct mg_connection *conn,
  4096. const char *target_url,
  4097. int redirect_code)
  4098. {
  4099. /* Send a 30x redirect response.
  4100. *
  4101. * Redirect types (status codes):
  4102. *
  4103. * Status | Perm/Temp | Method | Version
  4104. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4105. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4106. * 303 | temporary | always use GET | HTTP/1.1
  4107. * 307 | temporary | always keep method | HTTP/1.1
  4108. * 308 | permanent | always keep method | HTTP/1.1
  4109. */
  4110. const char *redirect_text;
  4111. int ret;
  4112. size_t content_len = 0;
  4113. char reply[MG_BUF_LEN];
  4114. /* In case redirect_code=0, use 307. */
  4115. if (redirect_code == 0) {
  4116. redirect_code = 307;
  4117. }
  4118. /* In case redirect_code is none of the above, return error. */
  4119. if ((redirect_code != 301) && (redirect_code != 302)
  4120. && (redirect_code != 303) && (redirect_code != 307)
  4121. && (redirect_code != 308)) {
  4122. /* Parameter error */
  4123. return -2;
  4124. }
  4125. /* Get proper text for response code */
  4126. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4127. /* If target_url is not defined, redirect to "/". */
  4128. if ((target_url == NULL) || (*target_url == 0)) {
  4129. target_url = "/";
  4130. }
  4131. #if defined(MG_SEND_REDIRECT_BODY)
  4132. /* TODO: condition name? */
  4133. /* Prepare a response body with a hyperlink.
  4134. *
  4135. * According to RFC2616 (and RFC1945 before):
  4136. * Unless the request method was HEAD, the entity of the
  4137. * response SHOULD contain a short hypertext note with a hyperlink to
  4138. * the new URI(s).
  4139. *
  4140. * However, this response body is not useful in M2M communication.
  4141. * Probably the original reason in the RFC was, clients not supporting
  4142. * a 30x HTTP redirect could still show the HTML page and let the user
  4143. * press the link. Since current browsers support 30x HTTP, the additional
  4144. * HTML body does not seem to make sense anymore.
  4145. *
  4146. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4147. * but it only notes:
  4148. * The server's response payload usually contains a short
  4149. * hypertext note with a hyperlink to the new URI(s).
  4150. *
  4151. * Deactivated by default. If you need the 30x body, set the define.
  4152. */
  4153. mg_snprintf(
  4154. conn,
  4155. NULL /* ignore truncation */,
  4156. reply,
  4157. sizeof(reply),
  4158. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4159. redirect_text,
  4160. target_url,
  4161. target_url);
  4162. content_len = strlen(reply);
  4163. #else
  4164. reply[0] = 0;
  4165. #endif
  4166. /* Do not send any additional header. For all other options,
  4167. * including caching, there are suitable defaults. */
  4168. ret = mg_printf(conn,
  4169. "HTTP/1.1 %i %s\r\n"
  4170. "Location: %s\r\n"
  4171. "Content-Length: %u\r\n"
  4172. "Connection: %s\r\n\r\n",
  4173. redirect_code,
  4174. redirect_text,
  4175. target_url,
  4176. (unsigned int)content_len,
  4177. suggest_connection_header(conn));
  4178. /* Send response body */
  4179. if (ret > 0) {
  4180. /* ... unless it is a HEAD request */
  4181. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4182. ret = mg_write(conn, reply, content_len);
  4183. }
  4184. }
  4185. return (ret > 0) ? ret : -1;
  4186. }
  4187. #if defined(_WIN32)
  4188. /* Create substitutes for POSIX functions in Win32. */
  4189. #if defined(GCC_DIAGNOSTIC)
  4190. /* Show no warning in case system functions are not used. */
  4191. #pragma GCC diagnostic push
  4192. #pragma GCC diagnostic ignored "-Wunused-function"
  4193. #endif
  4194. static int
  4195. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4196. {
  4197. (void)unused;
  4198. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4199. InitializeCriticalSection(&mutex->sec);
  4200. return 0;
  4201. }
  4202. static int
  4203. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4204. {
  4205. DeleteCriticalSection(&mutex->sec);
  4206. return 0;
  4207. }
  4208. static int
  4209. pthread_mutex_lock(pthread_mutex_t *mutex)
  4210. {
  4211. EnterCriticalSection(&mutex->sec);
  4212. return 0;
  4213. }
  4214. static int
  4215. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4216. {
  4217. LeaveCriticalSection(&mutex->sec);
  4218. return 0;
  4219. }
  4220. FUNCTION_MAY_BE_UNUSED
  4221. static int
  4222. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4223. {
  4224. (void)unused;
  4225. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4226. cv->waiting_thread = NULL;
  4227. return 0;
  4228. }
  4229. FUNCTION_MAY_BE_UNUSED
  4230. static int
  4231. pthread_cond_timedwait(pthread_cond_t *cv,
  4232. pthread_mutex_t *mutex,
  4233. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4234. {
  4235. struct mg_workerTLS **ptls,
  4236. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4237. int ok;
  4238. int64_t nsnow, nswaitabs, nswaitrel;
  4239. DWORD mswaitrel;
  4240. pthread_mutex_lock(&cv->threadIdSec);
  4241. /* Add this thread to cv's waiting list */
  4242. ptls = &cv->waiting_thread;
  4243. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4244. ;
  4245. tls->next_waiting_thread = NULL;
  4246. *ptls = tls;
  4247. pthread_mutex_unlock(&cv->threadIdSec);
  4248. if (abstime) {
  4249. nsnow = mg_get_current_time_ns();
  4250. nswaitabs =
  4251. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4252. nswaitrel = nswaitabs - nsnow;
  4253. if (nswaitrel < 0) {
  4254. nswaitrel = 0;
  4255. }
  4256. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4257. } else {
  4258. mswaitrel = (DWORD)INFINITE;
  4259. }
  4260. pthread_mutex_unlock(mutex);
  4261. ok = (WAIT_OBJECT_0
  4262. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4263. if (!ok) {
  4264. ok = 1;
  4265. pthread_mutex_lock(&cv->threadIdSec);
  4266. ptls = &cv->waiting_thread;
  4267. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4268. if (*ptls == tls) {
  4269. *ptls = tls->next_waiting_thread;
  4270. ok = 0;
  4271. break;
  4272. }
  4273. }
  4274. pthread_mutex_unlock(&cv->threadIdSec);
  4275. if (ok) {
  4276. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4277. (DWORD)INFINITE);
  4278. }
  4279. }
  4280. /* This thread has been removed from cv's waiting list */
  4281. pthread_mutex_lock(mutex);
  4282. return ok ? 0 : -1;
  4283. }
  4284. FUNCTION_MAY_BE_UNUSED
  4285. static int
  4286. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4287. {
  4288. return pthread_cond_timedwait(cv, mutex, NULL);
  4289. }
  4290. FUNCTION_MAY_BE_UNUSED
  4291. static int
  4292. pthread_cond_signal(pthread_cond_t *cv)
  4293. {
  4294. HANDLE wkup = NULL;
  4295. BOOL ok = FALSE;
  4296. pthread_mutex_lock(&cv->threadIdSec);
  4297. if (cv->waiting_thread) {
  4298. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4299. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4300. ok = SetEvent(wkup);
  4301. DEBUG_ASSERT(ok);
  4302. }
  4303. pthread_mutex_unlock(&cv->threadIdSec);
  4304. return ok ? 0 : 1;
  4305. }
  4306. FUNCTION_MAY_BE_UNUSED
  4307. static int
  4308. pthread_cond_broadcast(pthread_cond_t *cv)
  4309. {
  4310. pthread_mutex_lock(&cv->threadIdSec);
  4311. while (cv->waiting_thread) {
  4312. pthread_cond_signal(cv);
  4313. }
  4314. pthread_mutex_unlock(&cv->threadIdSec);
  4315. return 0;
  4316. }
  4317. FUNCTION_MAY_BE_UNUSED
  4318. static int
  4319. pthread_cond_destroy(pthread_cond_t *cv)
  4320. {
  4321. pthread_mutex_lock(&cv->threadIdSec);
  4322. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4323. pthread_mutex_unlock(&cv->threadIdSec);
  4324. pthread_mutex_destroy(&cv->threadIdSec);
  4325. return 0;
  4326. }
  4327. #if defined(ALTERNATIVE_QUEUE)
  4328. FUNCTION_MAY_BE_UNUSED
  4329. static void *
  4330. event_create(void)
  4331. {
  4332. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4333. }
  4334. FUNCTION_MAY_BE_UNUSED
  4335. static int
  4336. event_wait(void *eventhdl)
  4337. {
  4338. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4339. return (res == WAIT_OBJECT_0);
  4340. }
  4341. FUNCTION_MAY_BE_UNUSED
  4342. static int
  4343. event_signal(void *eventhdl)
  4344. {
  4345. return (int)SetEvent((HANDLE)eventhdl);
  4346. }
  4347. FUNCTION_MAY_BE_UNUSED
  4348. static void
  4349. event_destroy(void *eventhdl)
  4350. {
  4351. CloseHandle((HANDLE)eventhdl);
  4352. }
  4353. #endif
  4354. #if defined(GCC_DIAGNOSTIC)
  4355. /* Enable unused function warning again */
  4356. #pragma GCC diagnostic pop
  4357. #endif
  4358. /* For Windows, change all slashes to backslashes in path names. */
  4359. static void
  4360. change_slashes_to_backslashes(char *path)
  4361. {
  4362. int i;
  4363. for (i = 0; path[i] != '\0'; i++) {
  4364. if (path[i] == '/') {
  4365. path[i] = '\\';
  4366. }
  4367. /* remove double backslash (check i > 0 to preserve UNC paths,
  4368. * like \\server\file.txt) */
  4369. if ((path[i] == '\\') && (i > 0)) {
  4370. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4371. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4372. }
  4373. }
  4374. }
  4375. }
  4376. static int
  4377. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4378. {
  4379. int diff;
  4380. do {
  4381. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4382. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4383. s1++;
  4384. s2++;
  4385. } while ((diff == 0) && (s1[-1] != L'\0'));
  4386. return diff;
  4387. }
  4388. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4389. * wbuf and wbuf_len is a target buffer and its length. */
  4390. static void
  4391. path_to_unicode(const struct mg_connection *conn,
  4392. const char *path,
  4393. wchar_t *wbuf,
  4394. size_t wbuf_len)
  4395. {
  4396. char buf[PATH_MAX], buf2[PATH_MAX];
  4397. wchar_t wbuf2[W_PATH_MAX + 1];
  4398. DWORD long_len, err;
  4399. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4400. mg_strlcpy(buf, path, sizeof(buf));
  4401. change_slashes_to_backslashes(buf);
  4402. /* Convert to Unicode and back. If doubly-converted string does not
  4403. * match the original, something is fishy, reject. */
  4404. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4405. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4406. WideCharToMultiByte(
  4407. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4408. if (strcmp(buf, buf2) != 0) {
  4409. wbuf[0] = L'\0';
  4410. }
  4411. /* Windows file systems are not case sensitive, but you can still use
  4412. * uppercase and lowercase letters (on all modern file systems).
  4413. * The server can check if the URI uses the same upper/lowercase
  4414. * letters an the file system, effectively making Windows servers
  4415. * case sensitive (like Linux servers are). It is still not possible
  4416. * to use two files with the same name in different cases on Windows
  4417. * (like /a and /A) - this would be possible in Linux.
  4418. * As a default, Windows is not case sensitive, but the case sensitive
  4419. * file name check can be activated by an additional configuration. */
  4420. if (conn) {
  4421. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4422. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4423. "yes")) {
  4424. /* Use case sensitive compare function */
  4425. fcompare = wcscmp;
  4426. }
  4427. }
  4428. (void)conn; /* conn is currently unused */
  4429. #if !defined(_WIN32_WCE)
  4430. /* Only accept a full file path, not a Windows short (8.3) path. */
  4431. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4432. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4433. if (long_len == 0) {
  4434. err = GetLastError();
  4435. if (err == ERROR_FILE_NOT_FOUND) {
  4436. /* File does not exist. This is not always a problem here. */
  4437. return;
  4438. }
  4439. }
  4440. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4441. /* Short name is used. */
  4442. wbuf[0] = L'\0';
  4443. }
  4444. #else
  4445. (void)long_len;
  4446. (void)wbuf2;
  4447. (void)err;
  4448. if (strchr(path, '~')) {
  4449. wbuf[0] = L'\0';
  4450. }
  4451. #endif
  4452. }
  4453. #if !defined(NO_FILESYSTEMS)
  4454. static int
  4455. mg_stat(const struct mg_connection *conn,
  4456. const char *path,
  4457. struct mg_file_stat *filep)
  4458. {
  4459. wchar_t wbuf[W_PATH_MAX];
  4460. WIN32_FILE_ATTRIBUTE_DATA info;
  4461. time_t creation_time;
  4462. size_t len;
  4463. if (!filep) {
  4464. return 0;
  4465. }
  4466. memset(filep, 0, sizeof(*filep));
  4467. if (conn && is_file_in_memory(conn, path)) {
  4468. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4469. * memset */
  4470. /* Quick fix (for 1.9.x): */
  4471. /* mg_stat must fill all fields, also for files in memory */
  4472. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4473. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4474. filep->size = tmp_file.stat.size;
  4475. filep->location = 2;
  4476. /* TODO: for 1.10: restructure how files in memory are handled */
  4477. /* The "file in memory" feature is a candidate for deletion.
  4478. * Please join the discussion at
  4479. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4480. */
  4481. filep->last_modified = time(NULL); /* TODO */
  4482. /* last_modified = now ... assumes the file may change during
  4483. * runtime,
  4484. * so every mg_fopen call may return different data */
  4485. /* last_modified = conn->phys_ctx.start_time;
  4486. * May be used it the data does not change during runtime. This
  4487. * allows
  4488. * browser caching. Since we do not know, we have to assume the file
  4489. * in memory may change. */
  4490. return 1;
  4491. }
  4492. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4493. /* Windows happily opens files with some garbage at the end of file name.
  4494. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4495. * "a.cgi", despite one would expect an error back. */
  4496. len = strlen(path);
  4497. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4498. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4499. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4500. filep->last_modified =
  4501. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4502. info.ftLastWriteTime.dwHighDateTime);
  4503. /* On Windows, the file creation time can be higher than the
  4504. * modification time, e.g. when a file is copied.
  4505. * Since the Last-Modified timestamp is used for caching
  4506. * it should be based on the most recent timestamp. */
  4507. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4508. info.ftCreationTime.dwHighDateTime);
  4509. if (creation_time > filep->last_modified) {
  4510. filep->last_modified = creation_time;
  4511. }
  4512. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4513. return 1;
  4514. }
  4515. return 0;
  4516. }
  4517. #endif
  4518. static int
  4519. mg_remove(const struct mg_connection *conn, const char *path)
  4520. {
  4521. wchar_t wbuf[W_PATH_MAX];
  4522. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4523. return DeleteFileW(wbuf) ? 0 : -1;
  4524. }
  4525. static int
  4526. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4527. {
  4528. wchar_t wbuf[W_PATH_MAX];
  4529. (void)mode;
  4530. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4531. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4532. }
  4533. /* Create substitutes for POSIX functions in Win32. */
  4534. #if defined(GCC_DIAGNOSTIC)
  4535. /* Show no warning in case system functions are not used. */
  4536. #pragma GCC diagnostic push
  4537. #pragma GCC diagnostic ignored "-Wunused-function"
  4538. #endif
  4539. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4540. FUNCTION_MAY_BE_UNUSED
  4541. static DIR *
  4542. mg_opendir(const struct mg_connection *conn, const char *name)
  4543. {
  4544. DIR *dir = NULL;
  4545. wchar_t wpath[W_PATH_MAX];
  4546. DWORD attrs;
  4547. if (name == NULL) {
  4548. SetLastError(ERROR_BAD_ARGUMENTS);
  4549. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4550. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4551. } else {
  4552. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4553. attrs = GetFileAttributesW(wpath);
  4554. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4555. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4556. (void)wcscat(wpath, L"\\*");
  4557. dir->handle = FindFirstFileW(wpath, &dir->info);
  4558. dir->result.d_name[0] = '\0';
  4559. } else {
  4560. mg_free(dir);
  4561. dir = NULL;
  4562. }
  4563. }
  4564. return dir;
  4565. }
  4566. FUNCTION_MAY_BE_UNUSED
  4567. static int
  4568. mg_closedir(DIR *dir)
  4569. {
  4570. int result = 0;
  4571. if (dir != NULL) {
  4572. if (dir->handle != INVALID_HANDLE_VALUE)
  4573. result = FindClose(dir->handle) ? 0 : -1;
  4574. mg_free(dir);
  4575. } else {
  4576. result = -1;
  4577. SetLastError(ERROR_BAD_ARGUMENTS);
  4578. }
  4579. return result;
  4580. }
  4581. FUNCTION_MAY_BE_UNUSED
  4582. static struct dirent *
  4583. mg_readdir(DIR *dir)
  4584. {
  4585. struct dirent *result = 0;
  4586. if (dir) {
  4587. if (dir->handle != INVALID_HANDLE_VALUE) {
  4588. result = &dir->result;
  4589. (void)WideCharToMultiByte(CP_UTF8,
  4590. 0,
  4591. dir->info.cFileName,
  4592. -1,
  4593. result->d_name,
  4594. sizeof(result->d_name),
  4595. NULL,
  4596. NULL);
  4597. if (!FindNextFileW(dir->handle, &dir->info)) {
  4598. (void)FindClose(dir->handle);
  4599. dir->handle = INVALID_HANDLE_VALUE;
  4600. }
  4601. } else {
  4602. SetLastError(ERROR_FILE_NOT_FOUND);
  4603. }
  4604. } else {
  4605. SetLastError(ERROR_BAD_ARGUMENTS);
  4606. }
  4607. return result;
  4608. }
  4609. #if !defined(HAVE_POLL)
  4610. #undef POLLIN
  4611. #undef POLLPRI
  4612. #undef POLLOUT
  4613. #define POLLIN (1) /* Data ready - read will not block. */
  4614. #define POLLPRI (2) /* Priority data ready. */
  4615. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4616. FUNCTION_MAY_BE_UNUSED
  4617. static int
  4618. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4619. {
  4620. struct timeval tv;
  4621. fd_set rset;
  4622. fd_set wset;
  4623. unsigned int i;
  4624. int result;
  4625. SOCKET maxfd = 0;
  4626. memset(&tv, 0, sizeof(tv));
  4627. tv.tv_sec = milliseconds / 1000;
  4628. tv.tv_usec = (milliseconds % 1000) * 1000;
  4629. FD_ZERO(&rset);
  4630. FD_ZERO(&wset);
  4631. for (i = 0; i < n; i++) {
  4632. if (pfd[i].events & POLLIN) {
  4633. FD_SET(pfd[i].fd, &rset);
  4634. }
  4635. if (pfd[i].events & POLLOUT) {
  4636. FD_SET(pfd[i].fd, &wset);
  4637. }
  4638. pfd[i].revents = 0;
  4639. if (pfd[i].fd > maxfd) {
  4640. maxfd = pfd[i].fd;
  4641. }
  4642. }
  4643. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4644. for (i = 0; i < n; i++) {
  4645. if (FD_ISSET(pfd[i].fd, &rset)) {
  4646. pfd[i].revents |= POLLIN;
  4647. }
  4648. if (FD_ISSET(pfd[i].fd, &wset)) {
  4649. pfd[i].revents |= POLLOUT;
  4650. }
  4651. }
  4652. }
  4653. /* We should subtract the time used in select from remaining
  4654. * "milliseconds", in particular if called from mg_poll with a
  4655. * timeout quantum.
  4656. * Unfortunately, the remaining time is not stored in "tv" in all
  4657. * implementations, so the result in "tv" must be considered undefined.
  4658. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4659. return result;
  4660. }
  4661. #endif /* HAVE_POLL */
  4662. #if defined(GCC_DIAGNOSTIC)
  4663. /* Enable unused function warning again */
  4664. #pragma GCC diagnostic pop
  4665. #endif
  4666. static void
  4667. set_close_on_exec(SOCKET sock,
  4668. const struct mg_connection *conn /* may be null */,
  4669. struct mg_context *ctx /* may be null */)
  4670. {
  4671. (void)conn; /* Unused. */
  4672. (void)ctx;
  4673. #if defined(_WIN32_WCE)
  4674. (void)sock;
  4675. #else
  4676. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4677. #endif
  4678. }
  4679. int
  4680. mg_start_thread(mg_thread_func_t f, void *p)
  4681. {
  4682. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4683. /* Compile-time option to control stack size, e.g.
  4684. * -DUSE_STACK_SIZE=16384
  4685. */
  4686. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4687. == ((uintptr_t)(-1L)))
  4688. ? -1
  4689. : 0);
  4690. #else
  4691. return (
  4692. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4693. ? -1
  4694. : 0);
  4695. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4696. }
  4697. /* Start a thread storing the thread context. */
  4698. static int
  4699. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4700. void *p,
  4701. pthread_t *threadidptr)
  4702. {
  4703. uintptr_t uip;
  4704. HANDLE threadhandle;
  4705. int result = -1;
  4706. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4707. threadhandle = (HANDLE)uip;
  4708. if ((uip != 0) && (threadidptr != NULL)) {
  4709. *threadidptr = threadhandle;
  4710. result = 0;
  4711. }
  4712. return result;
  4713. }
  4714. /* Wait for a thread to finish. */
  4715. static int
  4716. mg_join_thread(pthread_t threadid)
  4717. {
  4718. int result;
  4719. DWORD dwevent;
  4720. result = -1;
  4721. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4722. if (dwevent == WAIT_FAILED) {
  4723. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4724. } else {
  4725. if (dwevent == WAIT_OBJECT_0) {
  4726. CloseHandle(threadid);
  4727. result = 0;
  4728. }
  4729. }
  4730. return result;
  4731. }
  4732. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4733. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4734. /* Create substitutes for POSIX functions in Win32. */
  4735. #if defined(GCC_DIAGNOSTIC)
  4736. /* Show no warning in case system functions are not used. */
  4737. #pragma GCC diagnostic push
  4738. #pragma GCC diagnostic ignored "-Wunused-function"
  4739. #endif
  4740. FUNCTION_MAY_BE_UNUSED
  4741. static HANDLE
  4742. dlopen(const char *dll_name, int flags)
  4743. {
  4744. wchar_t wbuf[W_PATH_MAX];
  4745. (void)flags;
  4746. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4747. return LoadLibraryW(wbuf);
  4748. }
  4749. FUNCTION_MAY_BE_UNUSED
  4750. static int
  4751. dlclose(void *handle)
  4752. {
  4753. int result;
  4754. if (FreeLibrary((HMODULE)handle) != 0) {
  4755. result = 0;
  4756. } else {
  4757. result = -1;
  4758. }
  4759. return result;
  4760. }
  4761. #if defined(GCC_DIAGNOSTIC)
  4762. /* Enable unused function warning again */
  4763. #pragma GCC diagnostic pop
  4764. #endif
  4765. #endif
  4766. #if !defined(NO_CGI)
  4767. #define SIGKILL (0)
  4768. static int
  4769. kill(pid_t pid, int sig_num)
  4770. {
  4771. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4772. (void)CloseHandle((HANDLE)pid);
  4773. return 0;
  4774. }
  4775. #if !defined(WNOHANG)
  4776. #define WNOHANG (1)
  4777. #endif
  4778. static pid_t
  4779. waitpid(pid_t pid, int *status, int flags)
  4780. {
  4781. DWORD timeout = INFINITE;
  4782. DWORD waitres;
  4783. (void)status; /* Currently not used by any client here */
  4784. if ((flags | WNOHANG) == WNOHANG) {
  4785. timeout = 0;
  4786. }
  4787. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4788. if (waitres == WAIT_OBJECT_0) {
  4789. return pid;
  4790. }
  4791. if (waitres == WAIT_TIMEOUT) {
  4792. return 0;
  4793. }
  4794. return (pid_t)-1;
  4795. }
  4796. static void
  4797. trim_trailing_whitespaces(char *s)
  4798. {
  4799. char *e = s + strlen(s);
  4800. while ((e > s) && isspace((unsigned char)e[-1])) {
  4801. *(--e) = '\0';
  4802. }
  4803. }
  4804. static pid_t
  4805. spawn_process(struct mg_connection *conn,
  4806. const char *prog,
  4807. char *envblk,
  4808. char *envp[],
  4809. int fdin[2],
  4810. int fdout[2],
  4811. int fderr[2],
  4812. const char *dir)
  4813. {
  4814. HANDLE me;
  4815. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4816. cmdline[PATH_MAX], buf[PATH_MAX];
  4817. int truncated;
  4818. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4819. STARTUPINFOA si;
  4820. PROCESS_INFORMATION pi = {0};
  4821. (void)envp;
  4822. memset(&si, 0, sizeof(si));
  4823. si.cb = sizeof(si);
  4824. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4825. si.wShowWindow = SW_HIDE;
  4826. me = GetCurrentProcess();
  4827. DuplicateHandle(me,
  4828. (HANDLE)_get_osfhandle(fdin[0]),
  4829. me,
  4830. &si.hStdInput,
  4831. 0,
  4832. TRUE,
  4833. DUPLICATE_SAME_ACCESS);
  4834. DuplicateHandle(me,
  4835. (HANDLE)_get_osfhandle(fdout[1]),
  4836. me,
  4837. &si.hStdOutput,
  4838. 0,
  4839. TRUE,
  4840. DUPLICATE_SAME_ACCESS);
  4841. DuplicateHandle(me,
  4842. (HANDLE)_get_osfhandle(fderr[1]),
  4843. me,
  4844. &si.hStdError,
  4845. 0,
  4846. TRUE,
  4847. DUPLICATE_SAME_ACCESS);
  4848. /* Mark handles that should not be inherited. See
  4849. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4850. */
  4851. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4852. HANDLE_FLAG_INHERIT,
  4853. 0);
  4854. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4855. HANDLE_FLAG_INHERIT,
  4856. 0);
  4857. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4858. HANDLE_FLAG_INHERIT,
  4859. 0);
  4860. /* If CGI file is a script, try to read the interpreter line */
  4861. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4862. if (interp == NULL) {
  4863. buf[0] = buf[1] = '\0';
  4864. /* Read the first line of the script into the buffer */
  4865. mg_snprintf(
  4866. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4867. if (truncated) {
  4868. pi.hProcess = (pid_t)-1;
  4869. goto spawn_cleanup;
  4870. }
  4871. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4872. #if defined(MG_USE_OPEN_FILE)
  4873. p = (char *)file.access.membuf;
  4874. #else
  4875. p = (char *)NULL;
  4876. #endif
  4877. mg_fgets(buf, sizeof(buf), &file, &p);
  4878. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4879. buf[sizeof(buf) - 1] = '\0';
  4880. }
  4881. if ((buf[0] == '#') && (buf[1] == '!')) {
  4882. trim_trailing_whitespaces(buf + 2);
  4883. } else {
  4884. buf[2] = '\0';
  4885. }
  4886. interp = buf + 2;
  4887. }
  4888. if (interp[0] != '\0') {
  4889. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4890. interp = full_interp;
  4891. }
  4892. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4893. if (interp[0] != '\0') {
  4894. mg_snprintf(conn,
  4895. &truncated,
  4896. cmdline,
  4897. sizeof(cmdline),
  4898. "\"%s\" \"%s\\%s\"",
  4899. interp,
  4900. full_dir,
  4901. prog);
  4902. } else {
  4903. mg_snprintf(conn,
  4904. &truncated,
  4905. cmdline,
  4906. sizeof(cmdline),
  4907. "\"%s\\%s\"",
  4908. full_dir,
  4909. prog);
  4910. }
  4911. if (truncated) {
  4912. pi.hProcess = (pid_t)-1;
  4913. goto spawn_cleanup;
  4914. }
  4915. DEBUG_TRACE("Running [%s]", cmdline);
  4916. if (CreateProcessA(NULL,
  4917. cmdline,
  4918. NULL,
  4919. NULL,
  4920. TRUE,
  4921. CREATE_NEW_PROCESS_GROUP,
  4922. envblk,
  4923. NULL,
  4924. &si,
  4925. &pi)
  4926. == 0) {
  4927. mg_cry_internal(
  4928. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4929. pi.hProcess = (pid_t)-1;
  4930. /* goto spawn_cleanup; */
  4931. }
  4932. spawn_cleanup:
  4933. (void)CloseHandle(si.hStdOutput);
  4934. (void)CloseHandle(si.hStdError);
  4935. (void)CloseHandle(si.hStdInput);
  4936. if (pi.hThread != NULL) {
  4937. (void)CloseHandle(pi.hThread);
  4938. }
  4939. return (pid_t)pi.hProcess;
  4940. }
  4941. #endif /* !NO_CGI */
  4942. static int
  4943. set_blocking_mode(SOCKET sock)
  4944. {
  4945. unsigned long non_blocking = 0;
  4946. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4947. }
  4948. static int
  4949. set_non_blocking_mode(SOCKET sock)
  4950. {
  4951. unsigned long non_blocking = 1;
  4952. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4953. }
  4954. #else
  4955. #if !defined(NO_FILESYSTEMS)
  4956. static int
  4957. mg_stat(const struct mg_connection *conn,
  4958. const char *path,
  4959. struct mg_file_stat *filep)
  4960. {
  4961. struct stat st;
  4962. if (!filep) {
  4963. return 0;
  4964. }
  4965. memset(filep, 0, sizeof(*filep));
  4966. if (conn && is_file_in_memory(conn, path)) {
  4967. /* Quick fix (for 1.9.x): */
  4968. /* mg_stat must fill all fields, also for files in memory */
  4969. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4970. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4971. filep->size = tmp_file.stat.size;
  4972. filep->last_modified = time(NULL);
  4973. filep->location = 2;
  4974. /* TODO: remove legacy "files in memory" feature */
  4975. return 1;
  4976. }
  4977. if (0 == stat(path, &st)) {
  4978. filep->size = (uint64_t)(st.st_size);
  4979. filep->last_modified = st.st_mtime;
  4980. filep->is_directory = S_ISDIR(st.st_mode);
  4981. return 1;
  4982. }
  4983. return 0;
  4984. }
  4985. #endif /* NO_FILESYSTEMS */
  4986. static void
  4987. set_close_on_exec(int fd,
  4988. const struct mg_connection *conn /* may be null */,
  4989. struct mg_context *ctx /* may be null */)
  4990. {
  4991. #if defined(__ZEPHYR__)
  4992. (void) fd;
  4993. (void) conn;
  4994. (void) ctx;
  4995. #else
  4996. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4997. if (conn || ctx) {
  4998. struct mg_connection fc;
  4999. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  5000. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  5001. __func__,
  5002. strerror(ERRNO));
  5003. }
  5004. }
  5005. #endif
  5006. }
  5007. int
  5008. mg_start_thread(mg_thread_func_t func, void *param)
  5009. {
  5010. pthread_t thread_id;
  5011. pthread_attr_t attr;
  5012. int result;
  5013. (void)pthread_attr_init(&attr);
  5014. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  5015. #if defined(__ZEPHYR__)
  5016. pthread_attr_setstack(&attr, &civetweb_main_stack, ZEPHYR_STACK_SIZE);
  5017. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5018. /* Compile-time option to control stack size,
  5019. * e.g. -DUSE_STACK_SIZE=16384 */
  5020. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5021. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  5022. result = pthread_create(&thread_id, &attr, func, param);
  5023. pthread_attr_destroy(&attr);
  5024. return result;
  5025. }
  5026. /* Start a thread storing the thread context. */
  5027. static int
  5028. mg_start_thread_with_id(mg_thread_func_t func,
  5029. void *param,
  5030. pthread_t *threadidptr)
  5031. {
  5032. pthread_t thread_id;
  5033. pthread_attr_t attr;
  5034. int result;
  5035. (void)pthread_attr_init(&attr);
  5036. #if defined(__ZEPHYR__)
  5037. pthread_attr_setstack(&attr,
  5038. &civetweb_worker_stacks[zephyr_worker_stack_index++],
  5039. ZEPHYR_STACK_SIZE);
  5040. #elif defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5041. /* Compile-time option to control stack size,
  5042. * e.g. -DUSE_STACK_SIZE=16384 */
  5043. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5044. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5045. result = pthread_create(&thread_id, &attr, func, param);
  5046. pthread_attr_destroy(&attr);
  5047. if ((result == 0) && (threadidptr != NULL)) {
  5048. *threadidptr = thread_id;
  5049. }
  5050. return result;
  5051. }
  5052. /* Wait for a thread to finish. */
  5053. static int
  5054. mg_join_thread(pthread_t threadid)
  5055. {
  5056. int result;
  5057. result = pthread_join(threadid, NULL);
  5058. return result;
  5059. }
  5060. #if !defined(NO_CGI)
  5061. static pid_t
  5062. spawn_process(struct mg_connection *conn,
  5063. const char *prog,
  5064. char *envblk,
  5065. char *envp[],
  5066. int fdin[2],
  5067. int fdout[2],
  5068. int fderr[2],
  5069. const char *dir)
  5070. {
  5071. pid_t pid;
  5072. const char *interp;
  5073. (void)envblk;
  5074. if ((pid = fork()) == -1) {
  5075. /* Parent */
  5076. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5077. } else if (pid != 0) {
  5078. /* Make sure children close parent-side descriptors.
  5079. * The caller will close the child-side immediately. */
  5080. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5081. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5082. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5083. } else {
  5084. /* Child */
  5085. if (chdir(dir) != 0) {
  5086. mg_cry_internal(
  5087. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5088. } else if (dup2(fdin[0], 0) == -1) {
  5089. mg_cry_internal(conn,
  5090. "%s: dup2(%d, 0): %s",
  5091. __func__,
  5092. fdin[0],
  5093. strerror(ERRNO));
  5094. } else if (dup2(fdout[1], 1) == -1) {
  5095. mg_cry_internal(conn,
  5096. "%s: dup2(%d, 1): %s",
  5097. __func__,
  5098. fdout[1],
  5099. strerror(ERRNO));
  5100. } else if (dup2(fderr[1], 2) == -1) {
  5101. mg_cry_internal(conn,
  5102. "%s: dup2(%d, 2): %s",
  5103. __func__,
  5104. fderr[1],
  5105. strerror(ERRNO));
  5106. } else {
  5107. struct sigaction sa;
  5108. /* Keep stderr and stdout in two different pipes.
  5109. * Stdout will be sent back to the client,
  5110. * stderr should go into a server error log. */
  5111. (void)close(fdin[0]);
  5112. (void)close(fdout[1]);
  5113. (void)close(fderr[1]);
  5114. /* Close write end fdin and read end fdout and fderr */
  5115. (void)close(fdin[1]);
  5116. (void)close(fdout[0]);
  5117. (void)close(fderr[0]);
  5118. /* After exec, all signal handlers are restored to their default
  5119. * values, with one exception of SIGCHLD. According to
  5120. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5121. * will leave unchanged after exec if it was set to be ignored.
  5122. * Restore it to default action. */
  5123. memset(&sa, 0, sizeof(sa));
  5124. sa.sa_handler = SIG_DFL;
  5125. sigaction(SIGCHLD, &sa, NULL);
  5126. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5127. if (interp == NULL) {
  5128. (void)execle(prog, prog, NULL, envp);
  5129. mg_cry_internal(conn,
  5130. "%s: execle(%s): %s",
  5131. __func__,
  5132. prog,
  5133. strerror(ERRNO));
  5134. } else {
  5135. (void)execle(interp, interp, prog, NULL, envp);
  5136. mg_cry_internal(conn,
  5137. "%s: execle(%s %s): %s",
  5138. __func__,
  5139. interp,
  5140. prog,
  5141. strerror(ERRNO));
  5142. }
  5143. }
  5144. exit(EXIT_FAILURE);
  5145. }
  5146. return pid;
  5147. }
  5148. #endif /* !NO_CGI */
  5149. static int
  5150. set_non_blocking_mode(SOCKET sock)
  5151. {
  5152. int flags = fcntl(sock, F_GETFL, 0);
  5153. if (flags < 0) {
  5154. return -1;
  5155. }
  5156. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5157. return -1;
  5158. }
  5159. return 0;
  5160. }
  5161. static int
  5162. set_blocking_mode(SOCKET sock)
  5163. {
  5164. int flags = fcntl(sock, F_GETFL, 0);
  5165. if (flags < 0) {
  5166. return -1;
  5167. }
  5168. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5169. return -1;
  5170. }
  5171. return 0;
  5172. }
  5173. #endif /* _WIN32 / else */
  5174. /* End of initial operating system specific define block. */
  5175. /* Get a random number (independent of C rand function) */
  5176. static uint64_t
  5177. get_random(void)
  5178. {
  5179. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5180. static uint64_t lcg = 0; /* Linear congruential generator */
  5181. uint64_t now = mg_get_current_time_ns();
  5182. if (lfsr == 0) {
  5183. /* lfsr will be only 0 if has not been initialized,
  5184. * so this code is called only once. */
  5185. lfsr = mg_get_current_time_ns();
  5186. lcg = mg_get_current_time_ns();
  5187. } else {
  5188. /* Get the next step of both random number generators. */
  5189. lfsr = (lfsr >> 1)
  5190. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5191. << 63);
  5192. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5193. }
  5194. /* Combining two pseudo-random number generators and a high resolution
  5195. * part
  5196. * of the current server time will make it hard (impossible?) to guess
  5197. * the
  5198. * next number. */
  5199. return (lfsr ^ lcg ^ now);
  5200. }
  5201. static int
  5202. mg_poll(struct mg_pollfd *pfd,
  5203. unsigned int n,
  5204. int milliseconds,
  5205. volatile int *stop_server)
  5206. {
  5207. /* Call poll, but only for a maximum time of a few seconds.
  5208. * This will allow to stop the server after some seconds, instead
  5209. * of having to wait for a long socket timeout. */
  5210. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5211. do {
  5212. int result;
  5213. if (*stop_server) {
  5214. /* Shut down signal */
  5215. return -2;
  5216. }
  5217. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5218. ms_now = milliseconds;
  5219. }
  5220. result = poll(pfd, n, ms_now);
  5221. if (result != 0) {
  5222. /* Poll returned either success (1) or error (-1).
  5223. * Forward both to the caller. */
  5224. return result;
  5225. }
  5226. /* Poll returned timeout (0). */
  5227. if (milliseconds > 0) {
  5228. milliseconds -= ms_now;
  5229. }
  5230. } while (milliseconds != 0);
  5231. /* timeout: return 0 */
  5232. return 0;
  5233. }
  5234. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5235. * descriptor.
  5236. * Return value:
  5237. * >=0 .. number of bytes successfully written
  5238. * -1 .. timeout
  5239. * -2 .. error
  5240. */
  5241. static int
  5242. push_inner(struct mg_context *ctx,
  5243. FILE *fp,
  5244. SOCKET sock,
  5245. SSL *ssl,
  5246. const char *buf,
  5247. int len,
  5248. double timeout)
  5249. {
  5250. uint64_t start = 0, now = 0, timeout_ns = 0;
  5251. int n, err;
  5252. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5253. #if defined(_WIN32)
  5254. typedef int len_t;
  5255. #else
  5256. typedef size_t len_t;
  5257. #endif
  5258. if (timeout > 0) {
  5259. now = mg_get_current_time_ns();
  5260. start = now;
  5261. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5262. }
  5263. if (ctx == NULL) {
  5264. return -2;
  5265. }
  5266. #if defined(NO_SSL)
  5267. if (ssl) {
  5268. return -2;
  5269. }
  5270. #endif
  5271. /* Try to read until it succeeds, fails, times out, or the server
  5272. * shuts down. */
  5273. for (;;) {
  5274. #if !defined(NO_SSL)
  5275. if (ssl != NULL) {
  5276. n = SSL_write(ssl, buf, len);
  5277. if (n <= 0) {
  5278. err = SSL_get_error(ssl, n);
  5279. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5280. err = ERRNO;
  5281. } else if ((err == SSL_ERROR_WANT_READ)
  5282. || (err == SSL_ERROR_WANT_WRITE)) {
  5283. n = 0;
  5284. } else {
  5285. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5286. return -2;
  5287. }
  5288. } else {
  5289. err = 0;
  5290. }
  5291. } else
  5292. #endif
  5293. if (fp != NULL) {
  5294. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5295. if (ferror(fp)) {
  5296. n = -1;
  5297. err = ERRNO;
  5298. } else {
  5299. err = 0;
  5300. }
  5301. } else {
  5302. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5303. err = (n < 0) ? ERRNO : 0;
  5304. #if defined(_WIN32)
  5305. if (err == WSAEWOULDBLOCK) {
  5306. err = 0;
  5307. n = 0;
  5308. }
  5309. #else
  5310. if (err == EWOULDBLOCK) {
  5311. err = 0;
  5312. n = 0;
  5313. }
  5314. #endif
  5315. if (n < 0) {
  5316. /* shutdown of the socket at client side */
  5317. return -2;
  5318. }
  5319. }
  5320. if (ctx->stop_flag) {
  5321. return -2;
  5322. }
  5323. if ((n > 0) || ((n == 0) && (len == 0))) {
  5324. /* some data has been read, or no data was requested */
  5325. return n;
  5326. }
  5327. if (n < 0) {
  5328. /* socket error - check errno */
  5329. DEBUG_TRACE("send() failed, error %d", err);
  5330. /* TODO (mid): error handling depending on the error code.
  5331. * These codes are different between Windows and Linux.
  5332. * Currently there is no problem with failing send calls,
  5333. * if there is a reproducible situation, it should be
  5334. * investigated in detail.
  5335. */
  5336. return -2;
  5337. }
  5338. /* Only in case n=0 (timeout), repeat calling the write function */
  5339. /* If send failed, wait before retry */
  5340. if (fp != NULL) {
  5341. /* For files, just wait a fixed time.
  5342. * Maybe it helps, maybe not. */
  5343. mg_sleep(5);
  5344. } else {
  5345. /* For sockets, wait for the socket using poll */
  5346. struct mg_pollfd pfd[1];
  5347. int pollres;
  5348. pfd[0].fd = sock;
  5349. pfd[0].events = POLLOUT;
  5350. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5351. if (ctx->stop_flag) {
  5352. return -2;
  5353. }
  5354. if (pollres > 0) {
  5355. continue;
  5356. }
  5357. }
  5358. if (timeout > 0) {
  5359. now = mg_get_current_time_ns();
  5360. if ((now - start) > timeout_ns) {
  5361. /* Timeout */
  5362. break;
  5363. }
  5364. }
  5365. }
  5366. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5367. used */
  5368. return -1;
  5369. }
  5370. static int
  5371. push_all(struct mg_context *ctx,
  5372. FILE *fp,
  5373. SOCKET sock,
  5374. SSL *ssl,
  5375. const char *buf,
  5376. int len)
  5377. {
  5378. double timeout = -1.0;
  5379. int n, nwritten = 0;
  5380. if (ctx == NULL) {
  5381. return -1;
  5382. }
  5383. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5384. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5385. }
  5386. while ((len > 0) && (ctx->stop_flag == 0)) {
  5387. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5388. if (n < 0) {
  5389. if (nwritten == 0) {
  5390. nwritten = -1; /* Propagate the error */
  5391. }
  5392. break;
  5393. } else if (n == 0) {
  5394. break; /* No more data to write */
  5395. } else {
  5396. nwritten += n;
  5397. len -= n;
  5398. }
  5399. }
  5400. return nwritten;
  5401. }
  5402. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5403. * Return value:
  5404. * >=0 .. number of bytes successfully read
  5405. * -1 .. timeout
  5406. * -2 .. error
  5407. */
  5408. static int
  5409. pull_inner(FILE *fp,
  5410. struct mg_connection *conn,
  5411. char *buf,
  5412. int len,
  5413. double timeout)
  5414. {
  5415. int nread, err = 0;
  5416. #if defined(_WIN32)
  5417. typedef int len_t;
  5418. #else
  5419. typedef size_t len_t;
  5420. #endif
  5421. #if !defined(NO_SSL)
  5422. int ssl_pending;
  5423. #endif
  5424. /* We need an additional wait loop around this, because in some cases
  5425. * with TLSwe may get data from the socket but not from SSL_read.
  5426. * In this case we need to repeat at least once.
  5427. */
  5428. if (fp != NULL) {
  5429. #if !defined(_WIN32_WCE)
  5430. /* Use read() instead of fread(), because if we're reading from the
  5431. * CGI pipe, fread() may block until IO buffer is filled up. We
  5432. * cannot afford to block and must pass all read bytes immediately
  5433. * to the client. */
  5434. nread = (int)read(fileno(fp), buf, (size_t)len);
  5435. #else
  5436. /* WinCE does not support CGI pipes */
  5437. nread = (int)fread(buf, 1, (size_t)len, fp);
  5438. #endif
  5439. err = (nread < 0) ? ERRNO : 0;
  5440. if ((nread == 0) && (len > 0)) {
  5441. /* Should get data, but got EOL */
  5442. return -2;
  5443. }
  5444. #if !defined(NO_SSL)
  5445. } else if ((conn->ssl != NULL)
  5446. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5447. /* We already know there is no more data buffered in conn->buf
  5448. * but there is more available in the SSL layer. So don't poll
  5449. * conn->client.sock yet. */
  5450. if (ssl_pending > len) {
  5451. ssl_pending = len;
  5452. }
  5453. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5454. if (nread <= 0) {
  5455. err = SSL_get_error(conn->ssl, nread);
  5456. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5457. err = ERRNO;
  5458. } else if ((err == SSL_ERROR_WANT_READ)
  5459. || (err == SSL_ERROR_WANT_WRITE)) {
  5460. nread = 0;
  5461. } else {
  5462. /* All errors should return -2 */
  5463. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5464. return -2;
  5465. }
  5466. ERR_clear_error();
  5467. } else {
  5468. err = 0;
  5469. }
  5470. } else if (conn->ssl != NULL) {
  5471. struct mg_pollfd pfd[1];
  5472. int pollres;
  5473. pfd[0].fd = conn->client.sock;
  5474. pfd[0].events = POLLIN;
  5475. pollres = mg_poll(pfd,
  5476. 1,
  5477. (int)(timeout * 1000.0),
  5478. &(conn->phys_ctx->stop_flag));
  5479. if (conn->phys_ctx->stop_flag) {
  5480. return -2;
  5481. }
  5482. if (pollres > 0) {
  5483. nread = SSL_read(conn->ssl, buf, len);
  5484. if (nread <= 0) {
  5485. err = SSL_get_error(conn->ssl, nread);
  5486. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5487. err = ERRNO;
  5488. } else if ((err == SSL_ERROR_WANT_READ)
  5489. || (err == SSL_ERROR_WANT_WRITE)) {
  5490. nread = 0;
  5491. } else {
  5492. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5493. return -2;
  5494. }
  5495. } else {
  5496. err = 0;
  5497. }
  5498. ERR_clear_error();
  5499. } else if (pollres < 0) {
  5500. /* Error */
  5501. return -2;
  5502. } else {
  5503. /* pollres = 0 means timeout */
  5504. nread = 0;
  5505. }
  5506. #endif
  5507. } else {
  5508. struct mg_pollfd pfd[1];
  5509. int pollres;
  5510. pfd[0].fd = conn->client.sock;
  5511. pfd[0].events = POLLIN;
  5512. pollres = mg_poll(pfd,
  5513. 1,
  5514. (int)(timeout * 1000.0),
  5515. &(conn->phys_ctx->stop_flag));
  5516. if (conn->phys_ctx->stop_flag) {
  5517. return -2;
  5518. }
  5519. if (pollres > 0) {
  5520. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5521. err = (nread < 0) ? ERRNO : 0;
  5522. if (nread <= 0) {
  5523. /* shutdown of the socket at client side */
  5524. return -2;
  5525. }
  5526. } else if (pollres < 0) {
  5527. /* error callint poll */
  5528. return -2;
  5529. } else {
  5530. /* pollres = 0 means timeout */
  5531. nread = 0;
  5532. }
  5533. }
  5534. if (conn->phys_ctx->stop_flag) {
  5535. return -2;
  5536. }
  5537. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5538. /* some data has been read, or no data was requested */
  5539. return nread;
  5540. }
  5541. if (nread < 0) {
  5542. /* socket error - check errno */
  5543. #if defined(_WIN32)
  5544. if (err == WSAEWOULDBLOCK) {
  5545. /* TODO (low): check if this is still required */
  5546. /* standard case if called from close_socket_gracefully */
  5547. return -2;
  5548. } else if (err == WSAETIMEDOUT) {
  5549. /* TODO (low): check if this is still required */
  5550. /* timeout is handled by the while loop */
  5551. return 0;
  5552. } else if (err == WSAECONNABORTED) {
  5553. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5554. return -2;
  5555. } else {
  5556. DEBUG_TRACE("recv() failed, error %d", err);
  5557. return -2;
  5558. }
  5559. #else
  5560. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5561. * if the timeout is reached and if the socket was set to non-
  5562. * blocking in close_socket_gracefully, so we can not distinguish
  5563. * here. We have to wait for the timeout in both cases for now.
  5564. */
  5565. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5566. /* TODO (low): check if this is still required */
  5567. /* EAGAIN/EWOULDBLOCK:
  5568. * standard case if called from close_socket_gracefully
  5569. * => should return -1 */
  5570. /* or timeout occurred
  5571. * => the code must stay in the while loop */
  5572. /* EINTR can be generated on a socket with a timeout set even
  5573. * when SA_RESTART is effective for all relevant signals
  5574. * (see signal(7)).
  5575. * => stay in the while loop */
  5576. } else {
  5577. DEBUG_TRACE("recv() failed, error %d", err);
  5578. return -2;
  5579. }
  5580. #endif
  5581. }
  5582. /* Timeout occurred, but no data available. */
  5583. return -1;
  5584. }
  5585. static int
  5586. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5587. {
  5588. int n, nread = 0;
  5589. double timeout = -1.0;
  5590. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5591. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5592. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5593. }
  5594. if (timeout >= 0.0) {
  5595. start_time = mg_get_current_time_ns();
  5596. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5597. }
  5598. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5599. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5600. if (n == -2) {
  5601. if (nread == 0) {
  5602. nread = -1; /* Propagate the error */
  5603. }
  5604. break;
  5605. } else if (n == -1) {
  5606. /* timeout */
  5607. if (timeout >= 0.0) {
  5608. now = mg_get_current_time_ns();
  5609. if ((now - start_time) <= timeout_ns) {
  5610. continue;
  5611. }
  5612. }
  5613. break;
  5614. } else if (n == 0) {
  5615. break; /* No more data to read */
  5616. } else {
  5617. nread += n;
  5618. len -= n;
  5619. }
  5620. }
  5621. return nread;
  5622. }
  5623. static void
  5624. discard_unread_request_data(struct mg_connection *conn)
  5625. {
  5626. char buf[MG_BUF_LEN];
  5627. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5628. ;
  5629. }
  5630. static int
  5631. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5632. {
  5633. int64_t content_len, n, buffered_len, nread;
  5634. int64_t len64 =
  5635. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5636. * int, we may not read more
  5637. * bytes */
  5638. const char *body;
  5639. if (conn == NULL) {
  5640. return 0;
  5641. }
  5642. /* If Content-Length is not set for a response with body data,
  5643. * we do not know in advance how much data should be read. */
  5644. content_len = conn->content_len;
  5645. if (content_len < 0) {
  5646. /* The body data is completed when the connection is closed. */
  5647. content_len = INT64_MAX;
  5648. }
  5649. nread = 0;
  5650. if (conn->consumed_content < content_len) {
  5651. /* Adjust number of bytes to read. */
  5652. int64_t left_to_read = content_len - conn->consumed_content;
  5653. if (left_to_read < len64) {
  5654. /* Do not read more than the total content length of the
  5655. * request.
  5656. */
  5657. len64 = left_to_read;
  5658. }
  5659. /* Return buffered data */
  5660. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5661. - conn->consumed_content;
  5662. if (buffered_len > 0) {
  5663. if (len64 < buffered_len) {
  5664. buffered_len = len64;
  5665. }
  5666. body = conn->buf + conn->request_len + conn->consumed_content;
  5667. memcpy(buf, body, (size_t)buffered_len);
  5668. len64 -= buffered_len;
  5669. conn->consumed_content += buffered_len;
  5670. nread += buffered_len;
  5671. buf = (char *)buf + buffered_len;
  5672. }
  5673. /* We have returned all buffered data. Read new data from the remote
  5674. * socket.
  5675. */
  5676. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5677. conn->consumed_content += n;
  5678. nread += n;
  5679. } else {
  5680. nread = ((nread > 0) ? nread : n);
  5681. }
  5682. }
  5683. return (int)nread;
  5684. }
  5685. int
  5686. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5687. {
  5688. if (len > INT_MAX) {
  5689. len = INT_MAX;
  5690. }
  5691. if (conn == NULL) {
  5692. return 0;
  5693. }
  5694. if (conn->is_chunked) {
  5695. size_t all_read = 0;
  5696. while (len > 0) {
  5697. if (conn->is_chunked >= 3) {
  5698. /* No more data left to read */
  5699. return 0;
  5700. }
  5701. if (conn->is_chunked != 1) {
  5702. /* Has error */
  5703. return -1;
  5704. }
  5705. if (conn->consumed_content != conn->content_len) {
  5706. /* copy from the current chunk */
  5707. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5708. if (read_ret < 1) {
  5709. /* read error */
  5710. conn->is_chunked = 2;
  5711. return -1;
  5712. }
  5713. all_read += (size_t)read_ret;
  5714. len -= (size_t)read_ret;
  5715. if (conn->consumed_content == conn->content_len) {
  5716. /* Add data bytes in the current chunk have been read,
  5717. * so we are expecting \r\n now. */
  5718. char x[2];
  5719. conn->content_len += 2;
  5720. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5721. || (x[1] != '\n')) {
  5722. /* Protocol violation */
  5723. conn->is_chunked = 2;
  5724. return -1;
  5725. }
  5726. }
  5727. } else {
  5728. /* fetch a new chunk */
  5729. size_t i;
  5730. char lenbuf[64];
  5731. char *end = NULL;
  5732. unsigned long chunkSize = 0;
  5733. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5734. conn->content_len++;
  5735. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5736. lenbuf[i] = 0;
  5737. }
  5738. if ((i > 0) && (lenbuf[i] == '\r')
  5739. && (lenbuf[i - 1] != '\r')) {
  5740. continue;
  5741. }
  5742. if ((i > 1) && (lenbuf[i] == '\n')
  5743. && (lenbuf[i - 1] == '\r')) {
  5744. lenbuf[i + 1] = 0;
  5745. chunkSize = strtoul(lenbuf, &end, 16);
  5746. if (chunkSize == 0) {
  5747. /* regular end of content */
  5748. conn->is_chunked = 3;
  5749. }
  5750. break;
  5751. }
  5752. if (!isxdigit((unsigned char)lenbuf[i])) {
  5753. /* illegal character for chunk length */
  5754. conn->is_chunked = 2;
  5755. return -1;
  5756. }
  5757. }
  5758. if ((end == NULL) || (*end != '\r')) {
  5759. /* chunksize not set correctly */
  5760. conn->is_chunked = 2;
  5761. return -1;
  5762. }
  5763. if (chunkSize == 0) {
  5764. /* try discarding trailer for keep-alive */
  5765. conn->content_len += 2;
  5766. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5767. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5768. conn->is_chunked = 4;
  5769. }
  5770. break;
  5771. }
  5772. /* append a new chunk */
  5773. conn->content_len += chunkSize;
  5774. }
  5775. }
  5776. return (int)all_read;
  5777. }
  5778. return mg_read_inner(conn, buf, len);
  5779. }
  5780. int
  5781. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5782. {
  5783. time_t now;
  5784. int n, total, allowed;
  5785. if (conn == NULL) {
  5786. return 0;
  5787. }
  5788. if (len > INT_MAX) {
  5789. return -1;
  5790. }
  5791. if (conn->throttle > 0) {
  5792. if ((now = time(NULL)) != conn->last_throttle_time) {
  5793. conn->last_throttle_time = now;
  5794. conn->last_throttle_bytes = 0;
  5795. }
  5796. allowed = conn->throttle - conn->last_throttle_bytes;
  5797. if (allowed > (int)len) {
  5798. allowed = (int)len;
  5799. }
  5800. if ((total = push_all(conn->phys_ctx,
  5801. NULL,
  5802. conn->client.sock,
  5803. conn->ssl,
  5804. (const char *)buf,
  5805. allowed))
  5806. == allowed) {
  5807. buf = (const char *)buf + total;
  5808. conn->last_throttle_bytes += total;
  5809. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5810. allowed = (conn->throttle > ((int)len - total))
  5811. ? (int)len - total
  5812. : conn->throttle;
  5813. if ((n = push_all(conn->phys_ctx,
  5814. NULL,
  5815. conn->client.sock,
  5816. conn->ssl,
  5817. (const char *)buf,
  5818. allowed))
  5819. != allowed) {
  5820. break;
  5821. }
  5822. sleep(1);
  5823. conn->last_throttle_bytes = allowed;
  5824. conn->last_throttle_time = time(NULL);
  5825. buf = (const char *)buf + n;
  5826. total += n;
  5827. }
  5828. }
  5829. } else {
  5830. total = push_all(conn->phys_ctx,
  5831. NULL,
  5832. conn->client.sock,
  5833. conn->ssl,
  5834. (const char *)buf,
  5835. (int)len);
  5836. }
  5837. if (total > 0) {
  5838. conn->num_bytes_sent += total;
  5839. }
  5840. return total;
  5841. }
  5842. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5843. int
  5844. mg_send_chunk(struct mg_connection *conn,
  5845. const char *chunk,
  5846. unsigned int chunk_len)
  5847. {
  5848. char lenbuf[16];
  5849. size_t lenbuf_len;
  5850. int ret;
  5851. int t;
  5852. /* First store the length information in a text buffer. */
  5853. sprintf(lenbuf, "%x\r\n", chunk_len);
  5854. lenbuf_len = strlen(lenbuf);
  5855. /* Then send length information, chunk and terminating \r\n. */
  5856. ret = mg_write(conn, lenbuf, lenbuf_len);
  5857. if (ret != (int)lenbuf_len) {
  5858. return -1;
  5859. }
  5860. t = ret;
  5861. ret = mg_write(conn, chunk, chunk_len);
  5862. if (ret != (int)chunk_len) {
  5863. return -1;
  5864. }
  5865. t += ret;
  5866. ret = mg_write(conn, "\r\n", 2);
  5867. if (ret != 2) {
  5868. return -1;
  5869. }
  5870. t += ret;
  5871. return t;
  5872. }
  5873. #if defined(GCC_DIAGNOSTIC)
  5874. /* This block forwards format strings to printf implementations,
  5875. * so we need to disable the format-nonliteral warning. */
  5876. #pragma GCC diagnostic push
  5877. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5878. #endif
  5879. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5880. static int
  5881. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5882. {
  5883. va_list ap_copy;
  5884. size_t size = MG_BUF_LEN / 4;
  5885. int len = -1;
  5886. *buf = NULL;
  5887. while (len < 0) {
  5888. if (*buf) {
  5889. mg_free(*buf);
  5890. }
  5891. size *= 4;
  5892. *buf = (char *)mg_malloc(size);
  5893. if (!*buf) {
  5894. break;
  5895. }
  5896. va_copy(ap_copy, ap);
  5897. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5898. va_end(ap_copy);
  5899. (*buf)[size - 1] = 0;
  5900. }
  5901. return len;
  5902. }
  5903. /* Print message to buffer. If buffer is large enough to hold the message,
  5904. * return buffer. If buffer is to small, allocate large enough buffer on
  5905. * heap,
  5906. * and return allocated buffer. */
  5907. static int
  5908. alloc_vprintf(char **out_buf,
  5909. char *prealloc_buf,
  5910. size_t prealloc_size,
  5911. const char *fmt,
  5912. va_list ap)
  5913. {
  5914. va_list ap_copy;
  5915. int len;
  5916. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5917. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5918. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5919. * Therefore, we make two passes: on first pass, get required message
  5920. * length.
  5921. * On second pass, actually print the message. */
  5922. va_copy(ap_copy, ap);
  5923. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5924. va_end(ap_copy);
  5925. if (len < 0) {
  5926. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5927. * Switch to alternative code path that uses incremental
  5928. * allocations.
  5929. */
  5930. va_copy(ap_copy, ap);
  5931. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5932. va_end(ap_copy);
  5933. } else if ((size_t)(len) >= prealloc_size) {
  5934. /* The pre-allocated buffer not large enough. */
  5935. /* Allocate a new buffer. */
  5936. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5937. if (!*out_buf) {
  5938. /* Allocation failed. Return -1 as "out of memory" error. */
  5939. return -1;
  5940. }
  5941. /* Buffer allocation successful. Store the string there. */
  5942. va_copy(ap_copy, ap);
  5943. IGNORE_UNUSED_RESULT(
  5944. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5945. va_end(ap_copy);
  5946. } else {
  5947. /* The pre-allocated buffer is large enough.
  5948. * Use it to store the string and return the address. */
  5949. va_copy(ap_copy, ap);
  5950. IGNORE_UNUSED_RESULT(
  5951. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5952. va_end(ap_copy);
  5953. *out_buf = prealloc_buf;
  5954. }
  5955. return len;
  5956. }
  5957. #if defined(GCC_DIAGNOSTIC)
  5958. /* Enable format-nonliteral warning again. */
  5959. #pragma GCC diagnostic pop
  5960. #endif
  5961. static int
  5962. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5963. {
  5964. char mem[MG_BUF_LEN];
  5965. char *buf = NULL;
  5966. int len;
  5967. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5968. len = mg_write(conn, buf, (size_t)len);
  5969. }
  5970. if (buf != mem) {
  5971. mg_free(buf);
  5972. }
  5973. return len;
  5974. }
  5975. int
  5976. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5977. {
  5978. va_list ap;
  5979. int result;
  5980. va_start(ap, fmt);
  5981. result = mg_vprintf(conn, fmt, ap);
  5982. va_end(ap);
  5983. return result;
  5984. }
  5985. int
  5986. mg_url_decode(const char *src,
  5987. int src_len,
  5988. char *dst,
  5989. int dst_len,
  5990. int is_form_url_encoded)
  5991. {
  5992. int i, j, a, b;
  5993. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5994. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5995. if ((i < src_len - 2) && (src[i] == '%')
  5996. && isxdigit((unsigned char)src[i + 1])
  5997. && isxdigit((unsigned char)src[i + 2])) {
  5998. a = tolower((unsigned char)src[i + 1]);
  5999. b = tolower((unsigned char)src[i + 2]);
  6000. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  6001. i += 2;
  6002. } else if (is_form_url_encoded && (src[i] == '+')) {
  6003. dst[j] = ' ';
  6004. } else {
  6005. dst[j] = src[i];
  6006. }
  6007. }
  6008. dst[j] = '\0'; /* Null-terminate the destination */
  6009. return (i >= src_len) ? j : -1;
  6010. }
  6011. int
  6012. mg_get_var(const char *data,
  6013. size_t data_len,
  6014. const char *name,
  6015. char *dst,
  6016. size_t dst_len)
  6017. {
  6018. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  6019. }
  6020. int
  6021. mg_get_var2(const char *data,
  6022. size_t data_len,
  6023. const char *name,
  6024. char *dst,
  6025. size_t dst_len,
  6026. size_t occurrence)
  6027. {
  6028. const char *p, *e, *s;
  6029. size_t name_len;
  6030. int len;
  6031. if ((dst == NULL) || (dst_len == 0)) {
  6032. len = -2;
  6033. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6034. len = -1;
  6035. dst[0] = '\0';
  6036. } else {
  6037. name_len = strlen(name);
  6038. e = data + data_len;
  6039. len = -1;
  6040. dst[0] = '\0';
  6041. /* data is "var1=val1&var2=val2...". Find variable first */
  6042. for (p = data; p + name_len < e; p++) {
  6043. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6044. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6045. /* Point p to variable value */
  6046. p += name_len + 1;
  6047. /* Point s to the end of the value */
  6048. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6049. if (s == NULL) {
  6050. s = e;
  6051. }
  6052. DEBUG_ASSERT(s >= p);
  6053. if (s < p) {
  6054. return -3;
  6055. }
  6056. /* Decode variable into destination buffer */
  6057. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6058. /* Redirect error code from -1 to -2 (destination buffer too
  6059. * small). */
  6060. if (len == -1) {
  6061. len = -2;
  6062. }
  6063. break;
  6064. }
  6065. }
  6066. }
  6067. return len;
  6068. }
  6069. /* HCP24: some changes to compare hole var_name */
  6070. int
  6071. mg_get_cookie(const char *cookie_header,
  6072. const char *var_name,
  6073. char *dst,
  6074. size_t dst_size)
  6075. {
  6076. const char *s, *p, *end;
  6077. int name_len, len = -1;
  6078. if ((dst == NULL) || (dst_size == 0)) {
  6079. return -2;
  6080. }
  6081. dst[0] = '\0';
  6082. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6083. return -1;
  6084. }
  6085. name_len = (int)strlen(var_name);
  6086. end = s + strlen(s);
  6087. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6088. if (s[name_len] == '=') {
  6089. /* HCP24: now check is it a substring or a full cookie name */
  6090. if ((s == cookie_header) || (s[-1] == ' ')) {
  6091. s += name_len + 1;
  6092. if ((p = strchr(s, ' ')) == NULL) {
  6093. p = end;
  6094. }
  6095. if (p[-1] == ';') {
  6096. p--;
  6097. }
  6098. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6099. s++;
  6100. p--;
  6101. }
  6102. if ((size_t)(p - s) < dst_size) {
  6103. len = (int)(p - s);
  6104. mg_strlcpy(dst, s, (size_t)len + 1);
  6105. } else {
  6106. len = -3;
  6107. }
  6108. break;
  6109. }
  6110. }
  6111. }
  6112. return len;
  6113. }
  6114. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6115. static void
  6116. base64_encode(const unsigned char *src, int src_len, char *dst)
  6117. {
  6118. static const char *b64 =
  6119. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6120. int i, j, a, b, c;
  6121. for (i = j = 0; i < src_len; i += 3) {
  6122. a = src[i];
  6123. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6124. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6125. dst[j++] = b64[a >> 2];
  6126. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6127. if (i + 1 < src_len) {
  6128. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6129. }
  6130. if (i + 2 < src_len) {
  6131. dst[j++] = b64[c & 63];
  6132. }
  6133. }
  6134. while (j % 4 != 0) {
  6135. dst[j++] = '=';
  6136. }
  6137. dst[j++] = '\0';
  6138. }
  6139. #endif
  6140. #if defined(USE_LUA)
  6141. static unsigned char
  6142. b64reverse(char letter)
  6143. {
  6144. if ((letter >= 'A') && (letter <= 'Z')) {
  6145. return letter - 'A';
  6146. }
  6147. if ((letter >= 'a') && (letter <= 'z')) {
  6148. return letter - 'a' + 26;
  6149. }
  6150. if ((letter >= '0') && (letter <= '9')) {
  6151. return letter - '0' + 52;
  6152. }
  6153. if (letter == '+') {
  6154. return 62;
  6155. }
  6156. if (letter == '/') {
  6157. return 63;
  6158. }
  6159. if (letter == '=') {
  6160. return 255; /* normal end */
  6161. }
  6162. return 254; /* error */
  6163. }
  6164. static int
  6165. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6166. {
  6167. int i;
  6168. unsigned char a, b, c, d;
  6169. *dst_len = 0;
  6170. for (i = 0; i < src_len; i += 4) {
  6171. a = b64reverse(src[i]);
  6172. if (a >= 254) {
  6173. return i;
  6174. }
  6175. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6176. if (b >= 254) {
  6177. return i + 1;
  6178. }
  6179. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6180. if (c == 254) {
  6181. return i + 2;
  6182. }
  6183. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6184. if (d == 254) {
  6185. return i + 3;
  6186. }
  6187. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6188. if (c != 255) {
  6189. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6190. if (d != 255) {
  6191. dst[(*dst_len)++] = (c << 6) + d;
  6192. }
  6193. }
  6194. }
  6195. return -1;
  6196. }
  6197. #endif
  6198. static int
  6199. is_put_or_delete_method(const struct mg_connection *conn)
  6200. {
  6201. if (conn) {
  6202. const char *s = conn->request_info.request_method;
  6203. return (s != NULL)
  6204. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6205. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6206. }
  6207. return 0;
  6208. }
  6209. #if !defined(NO_FILES)
  6210. static int
  6211. extention_matches_script(
  6212. struct mg_connection *conn, /* in: request (must be valid) */
  6213. const char *filename /* in: filename (must be valid) */
  6214. )
  6215. {
  6216. #if !defined(NO_CGI)
  6217. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6218. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6219. filename)
  6220. > 0) {
  6221. return 1;
  6222. }
  6223. #endif
  6224. #if defined(USE_LUA)
  6225. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6226. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6227. filename)
  6228. > 0) {
  6229. return 1;
  6230. }
  6231. #endif
  6232. #if defined(USE_DUKTAPE)
  6233. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6234. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6235. filename)
  6236. > 0) {
  6237. return 1;
  6238. }
  6239. #endif
  6240. /* filename and conn could be unused, if all preocessor conditions
  6241. * are false (no script language supported). */
  6242. (void)filename;
  6243. (void)conn;
  6244. return 0;
  6245. }
  6246. /* For given directory path, substitute it to valid index file.
  6247. * Return 1 if index file has been found, 0 if not found.
  6248. * If the file is found, it's stats is returned in stp. */
  6249. static int
  6250. substitute_index_file(struct mg_connection *conn,
  6251. char *path,
  6252. size_t path_len,
  6253. struct mg_file_stat *filestat)
  6254. {
  6255. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6256. struct vec filename_vec;
  6257. size_t n = strlen(path);
  6258. int found = 0;
  6259. /* The 'path' given to us points to the directory. Remove all trailing
  6260. * directory separator characters from the end of the path, and
  6261. * then append single directory separator character. */
  6262. while ((n > 0) && (path[n - 1] == '/')) {
  6263. n--;
  6264. }
  6265. path[n] = '/';
  6266. /* Traverse index files list. For each entry, append it to the given
  6267. * path and see if the file exists. If it exists, break the loop */
  6268. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6269. /* Ignore too long entries that may overflow path buffer */
  6270. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6271. continue;
  6272. }
  6273. /* Prepare full path to the index file */
  6274. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6275. /* Does it exist? */
  6276. if (mg_stat(conn, path, filestat)) {
  6277. /* Yes it does, break the loop */
  6278. found = 1;
  6279. break;
  6280. }
  6281. }
  6282. /* If no index file exists, restore directory path */
  6283. if (!found) {
  6284. path[n] = '\0';
  6285. }
  6286. return found;
  6287. }
  6288. #endif
  6289. static void
  6290. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6291. char *filename, /* out: filename */
  6292. size_t filename_buf_len, /* in: size of filename buffer */
  6293. struct mg_file_stat *filestat, /* out: file status structure */
  6294. int *is_found, /* out: file found (directly) */
  6295. int *is_script_resource, /* out: handled by a script? */
  6296. int *is_websocket_request, /* out: websocket connetion? */
  6297. int *is_put_or_delete_request /* out: put/delete a file? */
  6298. )
  6299. {
  6300. char const *accept_encoding;
  6301. #if !defined(NO_FILES)
  6302. const char *uri = conn->request_info.local_uri;
  6303. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6304. const char *rewrite;
  6305. struct vec a, b;
  6306. ptrdiff_t match_len;
  6307. char gz_path[PATH_MAX];
  6308. int truncated;
  6309. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6310. char *tmp_str;
  6311. size_t tmp_str_len, sep_pos;
  6312. int allow_substitute_script_subresources;
  6313. #endif
  6314. #else
  6315. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6316. #endif
  6317. /* Step 1: Set all initially unknown outputs to zero */
  6318. memset(filestat, 0, sizeof(*filestat));
  6319. *filename = 0;
  6320. *is_found = 0;
  6321. *is_script_resource = 0;
  6322. /* Step 2: Check if the request attempts to modify the file system */
  6323. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6324. /* Step 3: Check if it is a websocket request, and modify the document
  6325. * root if required */
  6326. #if defined(USE_WEBSOCKET)
  6327. *is_websocket_request = is_websocket_protocol(conn);
  6328. #if !defined(NO_FILES)
  6329. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6330. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6331. }
  6332. #endif /* !NO_FILES */
  6333. #else /* USE_WEBSOCKET */
  6334. *is_websocket_request = 0;
  6335. #endif /* USE_WEBSOCKET */
  6336. /* Step 4: Check if gzip encoded response is allowed */
  6337. conn->accept_gzip = 0;
  6338. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6339. if (strstr(accept_encoding, "gzip") != NULL) {
  6340. conn->accept_gzip = 1;
  6341. }
  6342. }
  6343. #if !defined(NO_FILES)
  6344. /* Step 5: If there is no root directory, don't look for files. */
  6345. /* Note that root == NULL is a regular use case here. This occurs,
  6346. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6347. * config is not required. */
  6348. if (root == NULL) {
  6349. /* all file related outputs have already been set to 0, just return
  6350. */
  6351. return;
  6352. }
  6353. /* Step 6: Determine the local file path from the root path and the
  6354. * request uri. */
  6355. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6356. * part of the path one byte on the right. */
  6357. mg_snprintf(
  6358. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6359. if (truncated) {
  6360. goto interpret_cleanup;
  6361. }
  6362. /* Step 7: URI rewriting */
  6363. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6364. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6365. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6366. mg_snprintf(conn,
  6367. &truncated,
  6368. filename,
  6369. filename_buf_len - 1,
  6370. "%.*s%s",
  6371. (int)b.len,
  6372. b.ptr,
  6373. uri + match_len);
  6374. break;
  6375. }
  6376. }
  6377. if (truncated) {
  6378. goto interpret_cleanup;
  6379. }
  6380. /* Step 8: Check if the file exists at the server */
  6381. /* Local file path and name, corresponding to requested URI
  6382. * is now stored in "filename" variable. */
  6383. if (mg_stat(conn, filename, filestat)) {
  6384. int uri_len = (int)strlen(uri);
  6385. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6386. /* 8.1: File exists. */
  6387. *is_found = 1;
  6388. /* 8.2: Check if it is a script type. */
  6389. if (extention_matches_script(conn, filename)) {
  6390. /* The request addresses a CGI resource, Lua script or
  6391. * server-side javascript.
  6392. * The URI corresponds to the script itself (like
  6393. * /path/script.cgi), and there is no additional resource
  6394. * path (like /path/script.cgi/something).
  6395. * Requests that modify (replace or delete) a resource, like
  6396. * PUT and DELETE requests, should replace/delete the script
  6397. * file.
  6398. * Requests that read or write from/to a resource, like GET and
  6399. * POST requests, should call the script and return the
  6400. * generated response. */
  6401. *is_script_resource = (!*is_put_or_delete_request);
  6402. }
  6403. /* 8.3: If the request target is a directory, there could be
  6404. * a substitute file (index.html, index.cgi, ...). */
  6405. if (filestat->is_directory && is_uri_end_slash) {
  6406. /* Use a local copy here, since substitute_index_file will
  6407. * change the content of the file status */
  6408. struct mg_file_stat tmp_filestat;
  6409. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6410. if (substitute_index_file(
  6411. conn, filename, filename_buf_len, &tmp_filestat)) {
  6412. /* Substitute file found. Copy stat to the output, then
  6413. * check if the file is a script file */
  6414. *filestat = tmp_filestat;
  6415. if (extention_matches_script(conn, filename)) {
  6416. /* Substitute file is a script file */
  6417. *is_script_resource = 1;
  6418. } else {
  6419. /* Substitute file is a regular file */
  6420. *is_script_resource = 0;
  6421. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6422. }
  6423. }
  6424. /* If there is no substitute file, the server could return
  6425. * a directory listing in a later step */
  6426. }
  6427. return;
  6428. }
  6429. /* Step 9: Check for zipped files: */
  6430. /* If we can't find the actual file, look for the file
  6431. * with the same name but a .gz extension. If we find it,
  6432. * use that and set the gzipped flag in the file struct
  6433. * to indicate that the response need to have the content-
  6434. * encoding: gzip header.
  6435. * We can only do this if the browser declares support. */
  6436. if (conn->accept_gzip) {
  6437. mg_snprintf(
  6438. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6439. if (truncated) {
  6440. goto interpret_cleanup;
  6441. }
  6442. if (mg_stat(conn, gz_path, filestat)) {
  6443. if (filestat) {
  6444. filestat->is_gzipped = 1;
  6445. *is_found = 1;
  6446. }
  6447. /* Currently gz files can not be scripts. */
  6448. return;
  6449. }
  6450. }
  6451. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6452. /* Step 10: Script resources may handle sub-resources */
  6453. /* Support PATH_INFO for CGI scripts. */
  6454. tmp_str_len = strlen(filename);
  6455. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6456. if (!tmp_str) {
  6457. /* Out of memory */
  6458. goto interpret_cleanup;
  6459. }
  6460. memcpy(tmp_str, filename, tmp_str_len + 1);
  6461. /* Check config, if index scripts may have sub-resources */
  6462. allow_substitute_script_subresources =
  6463. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6464. "yes");
  6465. sep_pos = tmp_str_len;
  6466. while (sep_pos > 0) {
  6467. sep_pos--;
  6468. if (tmp_str[sep_pos] == '/') {
  6469. int is_script = 0, does_exist = 0;
  6470. tmp_str[sep_pos] = 0;
  6471. if (tmp_str[0]) {
  6472. is_script = extention_matches_script(conn, tmp_str);
  6473. does_exist = mg_stat(conn, tmp_str, filestat);
  6474. }
  6475. if (does_exist && is_script) {
  6476. filename[sep_pos] = 0;
  6477. memmove(filename + sep_pos + 2,
  6478. filename + sep_pos + 1,
  6479. strlen(filename + sep_pos + 1) + 1);
  6480. conn->path_info = filename + sep_pos + 1;
  6481. filename[sep_pos + 1] = '/';
  6482. *is_script_resource = 1;
  6483. *is_found = 1;
  6484. break;
  6485. }
  6486. if (allow_substitute_script_subresources) {
  6487. if (substitute_index_file(
  6488. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6489. /* some intermediate directory has an index file */
  6490. if (extention_matches_script(conn, tmp_str)) {
  6491. char *tmp_str2;
  6492. DEBUG_TRACE("Substitute script %s serving path %s",
  6493. tmp_str,
  6494. filename);
  6495. /* this index file is a script */
  6496. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6497. conn->phys_ctx);
  6498. mg_snprintf(conn,
  6499. &truncated,
  6500. filename,
  6501. filename_buf_len,
  6502. "%s//%s",
  6503. tmp_str,
  6504. tmp_str2);
  6505. mg_free(tmp_str2);
  6506. if (truncated) {
  6507. mg_free(tmp_str);
  6508. goto interpret_cleanup;
  6509. }
  6510. sep_pos = strlen(tmp_str);
  6511. filename[sep_pos] = 0;
  6512. conn->path_info = filename + sep_pos + 1;
  6513. *is_script_resource = 1;
  6514. *is_found = 1;
  6515. break;
  6516. } else {
  6517. DEBUG_TRACE("Substitute file %s serving path %s",
  6518. tmp_str,
  6519. filename);
  6520. /* non-script files will not have sub-resources */
  6521. filename[sep_pos] = 0;
  6522. conn->path_info = 0;
  6523. *is_script_resource = 0;
  6524. *is_found = 0;
  6525. break;
  6526. }
  6527. }
  6528. }
  6529. tmp_str[sep_pos] = '/';
  6530. }
  6531. }
  6532. mg_free(tmp_str);
  6533. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6534. #endif /* !defined(NO_FILES) */
  6535. return;
  6536. #if !defined(NO_FILES)
  6537. /* Reset all outputs */
  6538. interpret_cleanup:
  6539. memset(filestat, 0, sizeof(*filestat));
  6540. *filename = 0;
  6541. *is_found = 0;
  6542. *is_script_resource = 0;
  6543. *is_websocket_request = 0;
  6544. *is_put_or_delete_request = 0;
  6545. #endif /* !defined(NO_FILES) */
  6546. }
  6547. /* Check whether full request is buffered. Return:
  6548. * -1 if request or response is malformed
  6549. * 0 if request or response is not yet fully buffered
  6550. * >0 actual request length, including last \r\n\r\n */
  6551. static int
  6552. get_http_header_len(const char *buf, int buflen)
  6553. {
  6554. int i;
  6555. for (i = 0; i < buflen; i++) {
  6556. /* Do an unsigned comparison in some conditions below */
  6557. const unsigned char c = (unsigned char)buf[i];
  6558. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6559. && !isprint(c)) {
  6560. /* abort scan as soon as one malformed character is found */
  6561. return -1;
  6562. }
  6563. if (i < buflen - 1) {
  6564. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6565. /* Two newline, no carriage return - not standard compliant,
  6566. * but
  6567. * it
  6568. * should be accepted */
  6569. return i + 2;
  6570. }
  6571. }
  6572. if (i < buflen - 3) {
  6573. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6574. && (buf[i + 3] == '\n')) {
  6575. /* Two \r\n - standard compliant */
  6576. return i + 4;
  6577. }
  6578. }
  6579. }
  6580. return 0;
  6581. }
  6582. #if !defined(NO_CACHING)
  6583. /* Convert month to the month number. Return -1 on error, or month number */
  6584. static int
  6585. get_month_index(const char *s)
  6586. {
  6587. size_t i;
  6588. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6589. if (!strcmp(s, month_names[i])) {
  6590. return (int)i;
  6591. }
  6592. }
  6593. return -1;
  6594. }
  6595. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6596. static time_t
  6597. parse_date_string(const char *datetime)
  6598. {
  6599. char month_str[32] = {0};
  6600. int second, minute, hour, day, month, year;
  6601. time_t result = (time_t)0;
  6602. struct tm tm;
  6603. if ((sscanf(datetime,
  6604. "%d/%3s/%d %d:%d:%d",
  6605. &day,
  6606. month_str,
  6607. &year,
  6608. &hour,
  6609. &minute,
  6610. &second)
  6611. == 6)
  6612. || (sscanf(datetime,
  6613. "%d %3s %d %d:%d:%d",
  6614. &day,
  6615. month_str,
  6616. &year,
  6617. &hour,
  6618. &minute,
  6619. &second)
  6620. == 6)
  6621. || (sscanf(datetime,
  6622. "%*3s, %d %3s %d %d:%d:%d",
  6623. &day,
  6624. month_str,
  6625. &year,
  6626. &hour,
  6627. &minute,
  6628. &second)
  6629. == 6)
  6630. || (sscanf(datetime,
  6631. "%d-%3s-%d %d:%d:%d",
  6632. &day,
  6633. month_str,
  6634. &year,
  6635. &hour,
  6636. &minute,
  6637. &second)
  6638. == 6)) {
  6639. month = get_month_index(month_str);
  6640. if ((month >= 0) && (year >= 1970)) {
  6641. memset(&tm, 0, sizeof(tm));
  6642. tm.tm_year = year - 1900;
  6643. tm.tm_mon = month;
  6644. tm.tm_mday = day;
  6645. tm.tm_hour = hour;
  6646. tm.tm_min = minute;
  6647. tm.tm_sec = second;
  6648. result = timegm(&tm);
  6649. }
  6650. }
  6651. return result;
  6652. }
  6653. #endif /* !NO_CACHING */
  6654. /* Protect against directory disclosure attack by removing '..',
  6655. * excessive '/' and '\' characters */
  6656. static void
  6657. remove_double_dots_and_double_slashes(char *s)
  6658. {
  6659. char *p = s;
  6660. while ((s[0] == '.') && (s[1] == '.')) {
  6661. s++;
  6662. }
  6663. while (*s != '\0') {
  6664. *p++ = *s++;
  6665. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6666. /* Skip all following slashes, backslashes and double-dots */
  6667. while (s[0] != '\0') {
  6668. if ((s[0] == '/') || (s[0] == '\\')) {
  6669. s++;
  6670. } else if ((s[0] == '.') && (s[1] == '.')) {
  6671. s += 2;
  6672. } else {
  6673. break;
  6674. }
  6675. }
  6676. }
  6677. }
  6678. *p = '\0';
  6679. }
  6680. static const struct {
  6681. const char *extension;
  6682. size_t ext_len;
  6683. const char *mime_type;
  6684. } builtin_mime_types[] = {
  6685. /* IANA registered MIME types
  6686. * (http://www.iana.org/assignments/media-types)
  6687. * application types */
  6688. {".doc", 4, "application/msword"},
  6689. {".eps", 4, "application/postscript"},
  6690. {".exe", 4, "application/octet-stream"},
  6691. {".js", 3, "application/javascript"},
  6692. {".json", 5, "application/json"},
  6693. {".pdf", 4, "application/pdf"},
  6694. {".ps", 3, "application/postscript"},
  6695. {".rtf", 4, "application/rtf"},
  6696. {".xhtml", 6, "application/xhtml+xml"},
  6697. {".xsl", 4, "application/xml"},
  6698. {".xslt", 5, "application/xml"},
  6699. /* fonts */
  6700. {".ttf", 4, "application/font-sfnt"},
  6701. {".cff", 4, "application/font-sfnt"},
  6702. {".otf", 4, "application/font-sfnt"},
  6703. {".aat", 4, "application/font-sfnt"},
  6704. {".sil", 4, "application/font-sfnt"},
  6705. {".pfr", 4, "application/font-tdpfr"},
  6706. {".woff", 5, "application/font-woff"},
  6707. /* audio */
  6708. {".mp3", 4, "audio/mpeg"},
  6709. {".oga", 4, "audio/ogg"},
  6710. {".ogg", 4, "audio/ogg"},
  6711. /* image */
  6712. {".gif", 4, "image/gif"},
  6713. {".ief", 4, "image/ief"},
  6714. {".jpeg", 5, "image/jpeg"},
  6715. {".jpg", 4, "image/jpeg"},
  6716. {".jpm", 4, "image/jpm"},
  6717. {".jpx", 4, "image/jpx"},
  6718. {".png", 4, "image/png"},
  6719. {".svg", 4, "image/svg+xml"},
  6720. {".tif", 4, "image/tiff"},
  6721. {".tiff", 5, "image/tiff"},
  6722. /* model */
  6723. {".wrl", 4, "model/vrml"},
  6724. /* text */
  6725. {".css", 4, "text/css"},
  6726. {".csv", 4, "text/csv"},
  6727. {".htm", 4, "text/html"},
  6728. {".html", 5, "text/html"},
  6729. {".sgm", 4, "text/sgml"},
  6730. {".shtm", 5, "text/html"},
  6731. {".shtml", 6, "text/html"},
  6732. {".txt", 4, "text/plain"},
  6733. {".xml", 4, "text/xml"},
  6734. /* video */
  6735. {".mov", 4, "video/quicktime"},
  6736. {".mp4", 4, "video/mp4"},
  6737. {".mpeg", 5, "video/mpeg"},
  6738. {".mpg", 4, "video/mpeg"},
  6739. {".ogv", 4, "video/ogg"},
  6740. {".qt", 3, "video/quicktime"},
  6741. /* not registered types
  6742. * (http://reference.sitepoint.com/html/mime-types-full,
  6743. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6744. {".arj", 4, "application/x-arj-compressed"},
  6745. {".gz", 3, "application/x-gunzip"},
  6746. {".rar", 4, "application/x-arj-compressed"},
  6747. {".swf", 4, "application/x-shockwave-flash"},
  6748. {".tar", 4, "application/x-tar"},
  6749. {".tgz", 4, "application/x-tar-gz"},
  6750. {".torrent", 8, "application/x-bittorrent"},
  6751. {".ppt", 4, "application/x-mspowerpoint"},
  6752. {".xls", 4, "application/x-msexcel"},
  6753. {".zip", 4, "application/x-zip-compressed"},
  6754. {".aac",
  6755. 4,
  6756. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6757. {".aif", 4, "audio/x-aif"},
  6758. {".m3u", 4, "audio/x-mpegurl"},
  6759. {".mid", 4, "audio/x-midi"},
  6760. {".ra", 3, "audio/x-pn-realaudio"},
  6761. {".ram", 4, "audio/x-pn-realaudio"},
  6762. {".wav", 4, "audio/x-wav"},
  6763. {".bmp", 4, "image/bmp"},
  6764. {".ico", 4, "image/x-icon"},
  6765. {".pct", 4, "image/x-pct"},
  6766. {".pict", 5, "image/pict"},
  6767. {".rgb", 4, "image/x-rgb"},
  6768. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6769. {".asf", 4, "video/x-ms-asf"},
  6770. {".avi", 4, "video/x-msvideo"},
  6771. {".m4v", 4, "video/x-m4v"},
  6772. {NULL, 0, NULL}};
  6773. const char *
  6774. mg_get_builtin_mime_type(const char *path)
  6775. {
  6776. const char *ext;
  6777. size_t i, path_len;
  6778. path_len = strlen(path);
  6779. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6780. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6781. if ((path_len > builtin_mime_types[i].ext_len)
  6782. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6783. return builtin_mime_types[i].mime_type;
  6784. }
  6785. }
  6786. return "text/plain";
  6787. }
  6788. /* Look at the "path" extension and figure what mime type it has.
  6789. * Store mime type in the vector. */
  6790. static void
  6791. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6792. {
  6793. struct vec ext_vec, mime_vec;
  6794. const char *list, *ext;
  6795. size_t path_len;
  6796. path_len = strlen(path);
  6797. if ((conn == NULL) || (vec == NULL)) {
  6798. if (vec != NULL) {
  6799. memset(vec, '\0', sizeof(struct vec));
  6800. }
  6801. return;
  6802. }
  6803. /* Scan user-defined mime types first, in case user wants to
  6804. * override default mime types. */
  6805. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6806. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6807. /* ext now points to the path suffix */
  6808. ext = path + path_len - ext_vec.len;
  6809. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6810. *vec = mime_vec;
  6811. return;
  6812. }
  6813. }
  6814. vec->ptr = mg_get_builtin_mime_type(path);
  6815. vec->len = strlen(vec->ptr);
  6816. }
  6817. /* Stringify binary data. Output buffer must be twice as big as input,
  6818. * because each byte takes 2 bytes in string representation */
  6819. static void
  6820. bin2str(char *to, const unsigned char *p, size_t len)
  6821. {
  6822. static const char *hex = "0123456789abcdef";
  6823. for (; len--; p++) {
  6824. *to++ = hex[p[0] >> 4];
  6825. *to++ = hex[p[0] & 0x0f];
  6826. }
  6827. *to = '\0';
  6828. }
  6829. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6830. */
  6831. char *
  6832. mg_md5(char buf[33], ...)
  6833. {
  6834. md5_byte_t hash[16];
  6835. const char *p;
  6836. va_list ap;
  6837. md5_state_t ctx;
  6838. md5_init(&ctx);
  6839. va_start(ap, buf);
  6840. while ((p = va_arg(ap, const char *)) != NULL) {
  6841. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6842. }
  6843. va_end(ap);
  6844. md5_finish(&ctx, hash);
  6845. bin2str(buf, hash, sizeof(hash));
  6846. return buf;
  6847. }
  6848. /* Check the user's password, return 1 if OK */
  6849. static int
  6850. check_password(const char *method,
  6851. const char *ha1,
  6852. const char *uri,
  6853. const char *nonce,
  6854. const char *nc,
  6855. const char *cnonce,
  6856. const char *qop,
  6857. const char *response)
  6858. {
  6859. char ha2[32 + 1], expected_response[32 + 1];
  6860. /* Some of the parameters may be NULL */
  6861. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6862. || (qop == NULL) || (response == NULL)) {
  6863. return 0;
  6864. }
  6865. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6866. if (strlen(response) != 32) {
  6867. return 0;
  6868. }
  6869. mg_md5(ha2, method, ":", uri, NULL);
  6870. mg_md5(expected_response,
  6871. ha1,
  6872. ":",
  6873. nonce,
  6874. ":",
  6875. nc,
  6876. ":",
  6877. cnonce,
  6878. ":",
  6879. qop,
  6880. ":",
  6881. ha2,
  6882. NULL);
  6883. return mg_strcasecmp(response, expected_response) == 0;
  6884. }
  6885. #if !defined(NO_FILESYSTEMS)
  6886. /* Use the global passwords file, if specified by auth_gpass option,
  6887. * or search for .htpasswd in the requested directory. */
  6888. static void
  6889. open_auth_file(struct mg_connection *conn,
  6890. const char *path,
  6891. struct mg_file *filep)
  6892. {
  6893. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6894. char name[PATH_MAX];
  6895. const char *p, *e,
  6896. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6897. int truncated;
  6898. if (gpass != NULL) {
  6899. /* Use global passwords file */
  6900. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6901. #if defined(DEBUG)
  6902. /* Use mg_cry_internal here, since gpass has been configured. */
  6903. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6904. #endif
  6905. }
  6906. /* Important: using local struct mg_file to test path for
  6907. * is_directory flag. If filep is used, mg_stat() makes it
  6908. * appear as if auth file was opened.
  6909. * TODO(mid): Check if this is still required after rewriting
  6910. * mg_stat */
  6911. } else if (mg_stat(conn, path, &filep->stat)
  6912. && filep->stat.is_directory) {
  6913. mg_snprintf(conn,
  6914. &truncated,
  6915. name,
  6916. sizeof(name),
  6917. "%s/%s",
  6918. path,
  6919. PASSWORDS_FILE_NAME);
  6920. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6921. #if defined(DEBUG)
  6922. /* Don't use mg_cry_internal here, but only a trace, since this
  6923. * is
  6924. * a typical case. It will occur for every directory
  6925. * without a password file. */
  6926. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6927. #endif
  6928. }
  6929. } else {
  6930. /* Try to find .htpasswd in requested directory. */
  6931. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6932. if (e[0] == '/') {
  6933. break;
  6934. }
  6935. }
  6936. mg_snprintf(conn,
  6937. &truncated,
  6938. name,
  6939. sizeof(name),
  6940. "%.*s/%s",
  6941. (int)(e - p),
  6942. p,
  6943. PASSWORDS_FILE_NAME);
  6944. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6945. #if defined(DEBUG)
  6946. /* Don't use mg_cry_internal here, but only a trace, since this
  6947. * is
  6948. * a typical case. It will occur for every directory
  6949. * without a password file. */
  6950. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6951. #endif
  6952. }
  6953. }
  6954. }
  6955. }
  6956. #endif /* NO_FILESYSTEMS */
  6957. /* Parsed Authorization header */
  6958. struct ah {
  6959. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6960. };
  6961. /* Return 1 on success. Always initializes the ah structure. */
  6962. static int
  6963. parse_auth_header(struct mg_connection *conn,
  6964. char *buf,
  6965. size_t buf_size,
  6966. struct ah *ah)
  6967. {
  6968. char *name, *value, *s;
  6969. const char *auth_header;
  6970. uint64_t nonce;
  6971. if (!ah || !conn) {
  6972. return 0;
  6973. }
  6974. (void)memset(ah, 0, sizeof(*ah));
  6975. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6976. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6977. return 0;
  6978. }
  6979. /* Make modifiable copy of the auth header */
  6980. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6981. s = buf;
  6982. /* Parse authorization header */
  6983. for (;;) {
  6984. /* Gobble initial spaces */
  6985. while (isspace((unsigned char)*s)) {
  6986. s++;
  6987. }
  6988. name = skip_quoted(&s, "=", " ", 0);
  6989. /* Value is either quote-delimited, or ends at first comma or space.
  6990. */
  6991. if (s[0] == '\"') {
  6992. s++;
  6993. value = skip_quoted(&s, "\"", " ", '\\');
  6994. if (s[0] == ',') {
  6995. s++;
  6996. }
  6997. } else {
  6998. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6999. * spaces */
  7000. }
  7001. if (*name == '\0') {
  7002. break;
  7003. }
  7004. if (!strcmp(name, "username")) {
  7005. ah->user = value;
  7006. } else if (!strcmp(name, "cnonce")) {
  7007. ah->cnonce = value;
  7008. } else if (!strcmp(name, "response")) {
  7009. ah->response = value;
  7010. } else if (!strcmp(name, "uri")) {
  7011. ah->uri = value;
  7012. } else if (!strcmp(name, "qop")) {
  7013. ah->qop = value;
  7014. } else if (!strcmp(name, "nc")) {
  7015. ah->nc = value;
  7016. } else if (!strcmp(name, "nonce")) {
  7017. ah->nonce = value;
  7018. }
  7019. }
  7020. #if !defined(NO_NONCE_CHECK)
  7021. /* Read the nonce from the response. */
  7022. if (ah->nonce == NULL) {
  7023. return 0;
  7024. }
  7025. s = NULL;
  7026. nonce = strtoull(ah->nonce, &s, 10);
  7027. if ((s == NULL) || (*s != 0)) {
  7028. return 0;
  7029. }
  7030. /* Convert the nonce from the client to a number. */
  7031. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7032. /* The converted number corresponds to the time the nounce has been
  7033. * created. This should not be earlier than the server start. */
  7034. /* Server side nonce check is valuable in all situations but one:
  7035. * if the server restarts frequently, but the client should not see
  7036. * that, so the server should accept nonces from previous starts. */
  7037. /* However, the reasonable default is to not accept a nonce from a
  7038. * previous start, so if anyone changed the access rights between
  7039. * two restarts, a new login is required. */
  7040. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7041. /* nonce is from a previous start of the server and no longer valid
  7042. * (replay attack?) */
  7043. return 0;
  7044. }
  7045. /* Check if the nonce is too high, so it has not (yet) been used by the
  7046. * server. */
  7047. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7048. + conn->dom_ctx->nonce_count)) {
  7049. return 0;
  7050. }
  7051. #else
  7052. (void)nonce;
  7053. #endif
  7054. /* CGI needs it as REMOTE_USER */
  7055. if (ah->user != NULL) {
  7056. conn->request_info.remote_user =
  7057. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7058. } else {
  7059. return 0;
  7060. }
  7061. return 1;
  7062. }
  7063. static const char *
  7064. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7065. {
  7066. #if defined(MG_USE_OPEN_FILE)
  7067. const char *eof;
  7068. size_t len;
  7069. const char *memend;
  7070. #else
  7071. (void)p; /* parameter is unused */
  7072. #endif
  7073. if (!filep) {
  7074. return NULL;
  7075. }
  7076. #if defined(MG_USE_OPEN_FILE)
  7077. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7078. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7079. /* Search for \n from p till the end of stream */
  7080. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7081. if (eof != NULL) {
  7082. eof += 1; /* Include \n */
  7083. } else {
  7084. eof = memend; /* Copy remaining data */
  7085. }
  7086. len =
  7087. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7088. memcpy(buf, *p, len);
  7089. buf[len] = '\0';
  7090. *p += len;
  7091. return len ? eof : NULL;
  7092. } else /* filep->access.fp block below */
  7093. #endif
  7094. if (filep->access.fp != NULL) {
  7095. return fgets(buf, (int)size, filep->access.fp);
  7096. } else {
  7097. return NULL;
  7098. }
  7099. }
  7100. /* Define the initial recursion depth for procesesing htpasswd files that
  7101. * include other htpasswd
  7102. * (or even the same) files. It is not difficult to provide a file or files
  7103. * s.t. they force civetweb
  7104. * to infinitely recurse and then crash.
  7105. */
  7106. #define INITIAL_DEPTH 9
  7107. #if INITIAL_DEPTH <= 0
  7108. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7109. #endif
  7110. #if !defined(NO_FILESYSTEMS)
  7111. struct read_auth_file_struct {
  7112. struct mg_connection *conn;
  7113. struct ah ah;
  7114. const char *domain;
  7115. char buf[256 + 256 + 40];
  7116. const char *f_user;
  7117. const char *f_domain;
  7118. const char *f_ha1;
  7119. };
  7120. static int
  7121. read_auth_file(struct mg_file *filep,
  7122. struct read_auth_file_struct *workdata,
  7123. int depth)
  7124. {
  7125. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7126. int is_authorized = 0;
  7127. struct mg_file fp;
  7128. size_t l;
  7129. if (!filep || !workdata || (0 == depth)) {
  7130. return 0;
  7131. }
  7132. /* Loop over passwords file */
  7133. #if defined(MG_USE_OPEN_FILE)
  7134. p = (char *)filep->access.membuf;
  7135. #endif
  7136. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7137. l = strlen(workdata->buf);
  7138. while (l > 0) {
  7139. if (isspace((unsigned char)workdata->buf[l - 1])
  7140. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7141. l--;
  7142. workdata->buf[l] = 0;
  7143. } else
  7144. break;
  7145. }
  7146. if (l < 1) {
  7147. continue;
  7148. }
  7149. workdata->f_user = workdata->buf;
  7150. if (workdata->f_user[0] == ':') {
  7151. /* user names may not contain a ':' and may not be empty,
  7152. * so lines starting with ':' may be used for a special purpose
  7153. */
  7154. if (workdata->f_user[1] == '#') {
  7155. /* :# is a comment */
  7156. continue;
  7157. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7158. if (mg_fopen(workdata->conn,
  7159. workdata->f_user + 9,
  7160. MG_FOPEN_MODE_READ,
  7161. &fp)) {
  7162. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7163. (void)mg_fclose(
  7164. &fp.access); /* ignore error on read only file */
  7165. /* No need to continue processing files once we have a
  7166. * match, since nothing will reset it back
  7167. * to 0.
  7168. */
  7169. if (is_authorized) {
  7170. return is_authorized;
  7171. }
  7172. } else {
  7173. mg_cry_internal(workdata->conn,
  7174. "%s: cannot open authorization file: %s",
  7175. __func__,
  7176. workdata->buf);
  7177. }
  7178. continue;
  7179. }
  7180. /* everything is invalid for the moment (might change in the
  7181. * future) */
  7182. mg_cry_internal(workdata->conn,
  7183. "%s: syntax error in authorization file: %s",
  7184. __func__,
  7185. workdata->buf);
  7186. continue;
  7187. }
  7188. workdata->f_domain = strchr(workdata->f_user, ':');
  7189. if (workdata->f_domain == NULL) {
  7190. mg_cry_internal(workdata->conn,
  7191. "%s: syntax error in authorization file: %s",
  7192. __func__,
  7193. workdata->buf);
  7194. continue;
  7195. }
  7196. *(char *)(workdata->f_domain) = 0;
  7197. (workdata->f_domain)++;
  7198. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7199. if (workdata->f_ha1 == NULL) {
  7200. mg_cry_internal(workdata->conn,
  7201. "%s: syntax error in authorization file: %s",
  7202. __func__,
  7203. workdata->buf);
  7204. continue;
  7205. }
  7206. *(char *)(workdata->f_ha1) = 0;
  7207. (workdata->f_ha1)++;
  7208. if (!strcmp(workdata->ah.user, workdata->f_user)
  7209. && !strcmp(workdata->domain, workdata->f_domain)) {
  7210. return check_password(workdata->conn->request_info.request_method,
  7211. workdata->f_ha1,
  7212. workdata->ah.uri,
  7213. workdata->ah.nonce,
  7214. workdata->ah.nc,
  7215. workdata->ah.cnonce,
  7216. workdata->ah.qop,
  7217. workdata->ah.response);
  7218. }
  7219. }
  7220. return is_authorized;
  7221. }
  7222. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7223. static int
  7224. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7225. {
  7226. struct read_auth_file_struct workdata;
  7227. char buf[MG_BUF_LEN];
  7228. if (!conn || !conn->dom_ctx) {
  7229. return 0;
  7230. }
  7231. memset(&workdata, 0, sizeof(workdata));
  7232. workdata.conn = conn;
  7233. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7234. return 0;
  7235. }
  7236. if (realm) {
  7237. workdata.domain = realm;
  7238. } else {
  7239. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7240. }
  7241. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7242. }
  7243. /* Public function to check http digest authentication header */
  7244. int
  7245. mg_check_digest_access_authentication(struct mg_connection *conn,
  7246. const char *realm,
  7247. const char *filename)
  7248. {
  7249. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7250. int auth;
  7251. if (!conn || !filename) {
  7252. return -1;
  7253. }
  7254. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7255. return -2;
  7256. }
  7257. auth = authorize(conn, &file, realm);
  7258. mg_fclose(&file.access);
  7259. return auth;
  7260. }
  7261. #endif /* NO_FILESYSTEMS */
  7262. /* Return 1 if request is authorised, 0 otherwise. */
  7263. static int
  7264. check_authorization(struct mg_connection *conn, const char *path)
  7265. {
  7266. #if !defined(NO_FILESYSTEMS)
  7267. char fname[PATH_MAX];
  7268. struct vec uri_vec, filename_vec;
  7269. const char *list;
  7270. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7271. int authorized = 1, truncated;
  7272. if (!conn || !conn->dom_ctx) {
  7273. return 0;
  7274. }
  7275. list = conn->dom_ctx->config[PROTECT_URI];
  7276. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7277. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7278. mg_snprintf(conn,
  7279. &truncated,
  7280. fname,
  7281. sizeof(fname),
  7282. "%.*s",
  7283. (int)filename_vec.len,
  7284. filename_vec.ptr);
  7285. if (truncated
  7286. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7287. mg_cry_internal(conn,
  7288. "%s: cannot open %s: %s",
  7289. __func__,
  7290. fname,
  7291. strerror(errno));
  7292. }
  7293. break;
  7294. }
  7295. }
  7296. if (!is_file_opened(&file.access)) {
  7297. open_auth_file(conn, path, &file);
  7298. }
  7299. if (is_file_opened(&file.access)) {
  7300. authorized = authorize(conn, &file, NULL);
  7301. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7302. }
  7303. return authorized;
  7304. #else
  7305. (void)conn;
  7306. (void)path;
  7307. return 1;
  7308. #endif /* NO_FILESYSTEMS */
  7309. }
  7310. /* Internal function. Assumes conn is valid */
  7311. static void
  7312. send_authorization_request(struct mg_connection *conn, const char *realm)
  7313. {
  7314. char date[64];
  7315. time_t curtime = time(NULL);
  7316. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7317. if (!realm) {
  7318. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7319. }
  7320. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7321. nonce += conn->dom_ctx->nonce_count;
  7322. ++conn->dom_ctx->nonce_count;
  7323. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7324. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7325. conn->status_code = 401;
  7326. conn->must_close = 1;
  7327. gmt_time_string(date, sizeof(date), &curtime);
  7328. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7329. send_no_cache_header(conn);
  7330. send_additional_header(conn);
  7331. mg_printf(conn,
  7332. "Date: %s\r\n"
  7333. "Connection: %s\r\n"
  7334. "Content-Length: 0\r\n"
  7335. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7336. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7337. date,
  7338. suggest_connection_header(conn),
  7339. realm,
  7340. nonce);
  7341. }
  7342. /* Interface function. Parameters are provided by the user, so do
  7343. * at least some basic checks.
  7344. */
  7345. int
  7346. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7347. const char *realm)
  7348. {
  7349. if (conn && conn->dom_ctx) {
  7350. send_authorization_request(conn, realm);
  7351. return 0;
  7352. }
  7353. return -1;
  7354. }
  7355. #if !defined(NO_FILES)
  7356. static int
  7357. is_authorized_for_put(struct mg_connection *conn)
  7358. {
  7359. if (conn) {
  7360. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7361. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7362. int ret = 0;
  7363. if (passfile != NULL
  7364. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7365. ret = authorize(conn, &file, NULL);
  7366. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7367. }
  7368. return ret;
  7369. }
  7370. return 0;
  7371. }
  7372. #endif
  7373. int
  7374. mg_modify_passwords_file(const char *fname,
  7375. const char *domain,
  7376. const char *user,
  7377. const char *pass)
  7378. {
  7379. int found, i;
  7380. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7381. FILE *fp, *fp2;
  7382. found = 0;
  7383. fp = fp2 = NULL;
  7384. /* Regard empty password as no password - remove user record. */
  7385. if ((pass != NULL) && (pass[0] == '\0')) {
  7386. pass = NULL;
  7387. }
  7388. /* Other arguments must not be empty */
  7389. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7390. return 0;
  7391. }
  7392. /* Using the given file format, user name and domain must not contain
  7393. * ':'
  7394. */
  7395. if (strchr(user, ':') != NULL) {
  7396. return 0;
  7397. }
  7398. if (strchr(domain, ':') != NULL) {
  7399. return 0;
  7400. }
  7401. /* Do not allow control characters like newline in user name and domain.
  7402. * Do not allow excessively long names either. */
  7403. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7404. if (iscntrl((unsigned char)user[i])) {
  7405. return 0;
  7406. }
  7407. }
  7408. if (user[i]) {
  7409. return 0;
  7410. }
  7411. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7412. if (iscntrl((unsigned char)domain[i])) {
  7413. return 0;
  7414. }
  7415. }
  7416. if (domain[i]) {
  7417. return 0;
  7418. }
  7419. /* The maximum length of the path to the password file is limited */
  7420. if ((strlen(fname) + 4) >= PATH_MAX) {
  7421. return 0;
  7422. }
  7423. /* Create a temporary file name. Length has been checked before. */
  7424. strcpy(tmp, fname);
  7425. strcat(tmp, ".tmp");
  7426. /* Create the file if does not exist */
  7427. /* Use of fopen here is OK, since fname is only ASCII */
  7428. if ((fp = fopen(fname, "a+")) != NULL) {
  7429. (void)fclose(fp);
  7430. }
  7431. /* Open the given file and temporary file */
  7432. if ((fp = fopen(fname, "r")) == NULL) {
  7433. return 0;
  7434. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7435. fclose(fp);
  7436. return 0;
  7437. }
  7438. /* Copy the stuff to temporary file */
  7439. while (fgets(line, sizeof(line), fp) != NULL) {
  7440. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7441. continue;
  7442. }
  7443. u[255] = 0;
  7444. d[255] = 0;
  7445. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7446. found++;
  7447. if (pass != NULL) {
  7448. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7449. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7450. }
  7451. } else {
  7452. fprintf(fp2, "%s", line);
  7453. }
  7454. }
  7455. /* If new user, just add it */
  7456. if (!found && (pass != NULL)) {
  7457. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7458. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7459. }
  7460. /* Close files */
  7461. fclose(fp);
  7462. fclose(fp2);
  7463. /* Put the temp file in place of real file */
  7464. IGNORE_UNUSED_RESULT(remove(fname));
  7465. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7466. return 1;
  7467. }
  7468. static int
  7469. is_valid_port(unsigned long port)
  7470. {
  7471. return (port <= 0xffff);
  7472. }
  7473. static int
  7474. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7475. {
  7476. struct addrinfo hints, *res, *ressave;
  7477. int func_ret = 0;
  7478. int gai_ret;
  7479. memset(&hints, 0, sizeof(struct addrinfo));
  7480. hints.ai_family = af;
  7481. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7482. if (gai_ret != 0) {
  7483. /* gai_strerror could be used to convert gai_ret to a string */
  7484. /* POSIX return values: see
  7485. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7486. */
  7487. /* Windows return values: see
  7488. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7489. */
  7490. return 0;
  7491. }
  7492. ressave = res;
  7493. while (res) {
  7494. if (dstlen >= (size_t)res->ai_addrlen) {
  7495. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7496. func_ret = 1;
  7497. }
  7498. res = res->ai_next;
  7499. }
  7500. freeaddrinfo(ressave);
  7501. return func_ret;
  7502. }
  7503. static int
  7504. connect_socket(struct mg_context *ctx /* may be NULL */,
  7505. const char *host,
  7506. int port,
  7507. int use_ssl,
  7508. char *ebuf,
  7509. size_t ebuf_len,
  7510. SOCKET *sock /* output: socket, must not be NULL */,
  7511. union usa *sa /* output: socket address, must not be NULL */
  7512. )
  7513. {
  7514. int ip_ver = 0;
  7515. int conn_ret = -1;
  7516. int sockerr = 0;
  7517. *sock = INVALID_SOCKET;
  7518. memset(sa, 0, sizeof(*sa));
  7519. if (ebuf_len > 0) {
  7520. *ebuf = 0;
  7521. }
  7522. if (host == NULL) {
  7523. mg_snprintf(NULL,
  7524. NULL, /* No truncation check for ebuf */
  7525. ebuf,
  7526. ebuf_len,
  7527. "%s",
  7528. "NULL host");
  7529. return 0;
  7530. }
  7531. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7532. mg_snprintf(NULL,
  7533. NULL, /* No truncation check for ebuf */
  7534. ebuf,
  7535. ebuf_len,
  7536. "%s",
  7537. "invalid port");
  7538. return 0;
  7539. }
  7540. #if !defined(NO_SSL)
  7541. #if !defined(NO_SSL_DL)
  7542. #if defined(OPENSSL_API_1_1)
  7543. if (use_ssl && (TLS_client_method == NULL)) {
  7544. mg_snprintf(NULL,
  7545. NULL, /* No truncation check for ebuf */
  7546. ebuf,
  7547. ebuf_len,
  7548. "%s",
  7549. "SSL is not initialized");
  7550. return 0;
  7551. }
  7552. #else
  7553. if (use_ssl && (SSLv23_client_method == NULL)) {
  7554. mg_snprintf(NULL,
  7555. NULL, /* No truncation check for ebuf */
  7556. ebuf,
  7557. ebuf_len,
  7558. "%s",
  7559. "SSL is not initialized");
  7560. return 0;
  7561. }
  7562. #endif /* OPENSSL_API_1_1 */
  7563. #else
  7564. (void)use_ssl;
  7565. #endif /* NO_SSL_DL */
  7566. #else
  7567. (void)use_ssl;
  7568. #endif /* !defined(NO_SSL) */
  7569. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7570. sa->sin.sin_family = AF_INET;
  7571. sa->sin.sin_port = htons((uint16_t)port);
  7572. ip_ver = 4;
  7573. #if defined(USE_IPV6)
  7574. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7575. sa->sin6.sin6_family = AF_INET6;
  7576. sa->sin6.sin6_port = htons((uint16_t)port);
  7577. ip_ver = 6;
  7578. } else if (host[0] == '[') {
  7579. /* While getaddrinfo on Windows will work with [::1],
  7580. * getaddrinfo on Linux only works with ::1 (without []). */
  7581. size_t l = strlen(host + 1);
  7582. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7583. if (h) {
  7584. h[l - 1] = 0;
  7585. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7586. sa->sin6.sin6_family = AF_INET6;
  7587. sa->sin6.sin6_port = htons((uint16_t)port);
  7588. ip_ver = 6;
  7589. }
  7590. mg_free(h);
  7591. }
  7592. #endif
  7593. }
  7594. if (ip_ver == 0) {
  7595. mg_snprintf(NULL,
  7596. NULL, /* No truncation check for ebuf */
  7597. ebuf,
  7598. ebuf_len,
  7599. "%s",
  7600. "host not found");
  7601. return 0;
  7602. }
  7603. if (ip_ver == 4) {
  7604. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7605. }
  7606. #if defined(USE_IPV6)
  7607. else if (ip_ver == 6) {
  7608. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7609. }
  7610. #endif
  7611. if (*sock == INVALID_SOCKET) {
  7612. mg_snprintf(NULL,
  7613. NULL, /* No truncation check for ebuf */
  7614. ebuf,
  7615. ebuf_len,
  7616. "socket(): %s",
  7617. strerror(ERRNO));
  7618. return 0;
  7619. }
  7620. if (0 != set_non_blocking_mode(*sock)) {
  7621. mg_snprintf(NULL,
  7622. NULL, /* No truncation check for ebuf */
  7623. ebuf,
  7624. ebuf_len,
  7625. "Cannot set socket to non-blocking: %s",
  7626. strerror(ERRNO));
  7627. closesocket(*sock);
  7628. *sock = INVALID_SOCKET;
  7629. return 0;
  7630. }
  7631. set_close_on_exec(*sock, NULL, ctx);
  7632. if (ip_ver == 4) {
  7633. /* connected with IPv4 */
  7634. conn_ret = connect(*sock,
  7635. (struct sockaddr *)((void *)&sa->sin),
  7636. sizeof(sa->sin));
  7637. }
  7638. #if defined(USE_IPV6)
  7639. else if (ip_ver == 6) {
  7640. /* connected with IPv6 */
  7641. conn_ret = connect(*sock,
  7642. (struct sockaddr *)((void *)&sa->sin6),
  7643. sizeof(sa->sin6));
  7644. }
  7645. #endif
  7646. if (conn_ret != 0) {
  7647. sockerr = ERRNO;
  7648. }
  7649. #if defined(_WIN32)
  7650. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7651. #else
  7652. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7653. #endif
  7654. /* Data for getsockopt */
  7655. void *psockerr = &sockerr;
  7656. int ret;
  7657. #if defined(_WIN32)
  7658. int len = (int)sizeof(sockerr);
  7659. #else
  7660. socklen_t len = (socklen_t)sizeof(sockerr);
  7661. #endif
  7662. /* Data for poll */
  7663. struct mg_pollfd pfd[1];
  7664. int pollres;
  7665. int ms_wait = 10000; /* 10 second timeout */
  7666. int nonstop = 0;
  7667. /* For a non-blocking socket, the connect sequence is:
  7668. * 1) call connect (will not block)
  7669. * 2) wait until the socket is ready for writing (select or poll)
  7670. * 3) check connection state with getsockopt
  7671. */
  7672. pfd[0].fd = *sock;
  7673. pfd[0].events = POLLOUT;
  7674. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7675. if (pollres != 1) {
  7676. /* Not connected */
  7677. mg_snprintf(NULL,
  7678. NULL, /* No truncation check for ebuf */
  7679. ebuf,
  7680. ebuf_len,
  7681. "connect(%s:%d): timeout",
  7682. host,
  7683. port);
  7684. closesocket(*sock);
  7685. *sock = INVALID_SOCKET;
  7686. return 0;
  7687. }
  7688. #if defined(_WIN32)
  7689. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7690. #else
  7691. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7692. #endif
  7693. if ((ret == 0) && (sockerr == 0)) {
  7694. conn_ret = 0;
  7695. }
  7696. }
  7697. if (conn_ret != 0) {
  7698. /* Not connected */
  7699. mg_snprintf(NULL,
  7700. NULL, /* No truncation check for ebuf */
  7701. ebuf,
  7702. ebuf_len,
  7703. "connect(%s:%d): error %s",
  7704. host,
  7705. port,
  7706. strerror(sockerr));
  7707. closesocket(*sock);
  7708. *sock = INVALID_SOCKET;
  7709. return 0;
  7710. }
  7711. return 1;
  7712. }
  7713. int
  7714. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7715. {
  7716. static const char *dont_escape = "._-$,;~()";
  7717. static const char *hex = "0123456789abcdef";
  7718. char *pos = dst;
  7719. const char *end = dst + dst_len - 1;
  7720. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7721. if (isalnum((unsigned char)*src)
  7722. || (strchr(dont_escape, *src) != NULL)) {
  7723. *pos = *src;
  7724. } else if (pos + 2 < end) {
  7725. pos[0] = '%';
  7726. pos[1] = hex[(unsigned char)*src >> 4];
  7727. pos[2] = hex[(unsigned char)*src & 0xf];
  7728. pos += 2;
  7729. } else {
  7730. break;
  7731. }
  7732. }
  7733. *pos = '\0';
  7734. return (*src == '\0') ? (int)(pos - dst) : -1;
  7735. }
  7736. /* Return 0 on success, non-zero if an error occurs. */
  7737. static int
  7738. print_dir_entry(struct de *de)
  7739. {
  7740. size_t namesize, escsize, i;
  7741. char *href, *esc, *p;
  7742. char size[64], mod[64];
  7743. #if defined(REENTRANT_TIME)
  7744. struct tm _tm;
  7745. struct tm *tm = &_tm;
  7746. #else
  7747. struct tm *tm;
  7748. #endif
  7749. /* Estimate worst case size for encoding and escaping */
  7750. namesize = strlen(de->file_name) + 1;
  7751. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7752. href = (char *)mg_malloc(namesize * 3 + escsize);
  7753. if (href == NULL) {
  7754. return -1;
  7755. }
  7756. mg_url_encode(de->file_name, href, namesize * 3);
  7757. esc = NULL;
  7758. if (escsize > 0) {
  7759. /* HTML escaping needed */
  7760. esc = href + namesize * 3;
  7761. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7762. mg_strlcpy(p, de->file_name + i, 2);
  7763. if (*p == '&') {
  7764. strcpy(p, "&amp;");
  7765. } else if (*p == '<') {
  7766. strcpy(p, "&lt;");
  7767. } else if (*p == '>') {
  7768. strcpy(p, "&gt;");
  7769. }
  7770. }
  7771. }
  7772. if (de->file.is_directory) {
  7773. mg_snprintf(de->conn,
  7774. NULL, /* Buffer is big enough */
  7775. size,
  7776. sizeof(size),
  7777. "%s",
  7778. "[DIRECTORY]");
  7779. } else {
  7780. /* We use (signed) cast below because MSVC 6 compiler cannot
  7781. * convert unsigned __int64 to double. Sigh. */
  7782. if (de->file.size < 1024) {
  7783. mg_snprintf(de->conn,
  7784. NULL, /* Buffer is big enough */
  7785. size,
  7786. sizeof(size),
  7787. "%d",
  7788. (int)de->file.size);
  7789. } else if (de->file.size < 0x100000) {
  7790. mg_snprintf(de->conn,
  7791. NULL, /* Buffer is big enough */
  7792. size,
  7793. sizeof(size),
  7794. "%.1fk",
  7795. (double)de->file.size / 1024.0);
  7796. } else if (de->file.size < 0x40000000) {
  7797. mg_snprintf(de->conn,
  7798. NULL, /* Buffer is big enough */
  7799. size,
  7800. sizeof(size),
  7801. "%.1fM",
  7802. (double)de->file.size / 1048576);
  7803. } else {
  7804. mg_snprintf(de->conn,
  7805. NULL, /* Buffer is big enough */
  7806. size,
  7807. sizeof(size),
  7808. "%.1fG",
  7809. (double)de->file.size / 1073741824);
  7810. }
  7811. }
  7812. /* Note: mg_snprintf will not cause a buffer overflow above.
  7813. * So, string truncation checks are not required here. */
  7814. #if defined(REENTRANT_TIME)
  7815. localtime_r(&de->file.last_modified, tm);
  7816. #else
  7817. tm = localtime(&de->file.last_modified);
  7818. #endif
  7819. if (tm != NULL) {
  7820. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7821. } else {
  7822. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7823. mod[sizeof(mod) - 1] = '\0';
  7824. }
  7825. mg_printf(de->conn,
  7826. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7827. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7828. href,
  7829. de->file.is_directory ? "/" : "",
  7830. esc ? esc : de->file_name,
  7831. de->file.is_directory ? "/" : "",
  7832. mod,
  7833. size);
  7834. mg_free(href);
  7835. return 0;
  7836. }
  7837. /* This function is called from send_directory() and used for
  7838. * sorting directory entries by size, or name, or modification time.
  7839. * On windows, __cdecl specification is needed in case if project is built
  7840. * with __stdcall convention. qsort always requires __cdels callback. */
  7841. static int WINCDECL
  7842. compare_dir_entries(const void *p1, const void *p2)
  7843. {
  7844. if (p1 && p2) {
  7845. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7846. const char *query_string = a->conn->request_info.query_string;
  7847. int cmp_result = 0;
  7848. if ((query_string == NULL) || (query_string[0] == '\0')) {
  7849. query_string = "n";
  7850. }
  7851. if (a->file.is_directory && !b->file.is_directory) {
  7852. return -1; /* Always put directories on top */
  7853. } else if (!a->file.is_directory && b->file.is_directory) {
  7854. return 1; /* Always put directories on top */
  7855. } else if (*query_string == 'n') {
  7856. cmp_result = strcmp(a->file_name, b->file_name);
  7857. } else if (*query_string == 's') {
  7858. cmp_result = (a->file.size == b->file.size)
  7859. ? 0
  7860. : ((a->file.size > b->file.size) ? 1 : -1);
  7861. } else if (*query_string == 'd') {
  7862. cmp_result =
  7863. (a->file.last_modified == b->file.last_modified)
  7864. ? 0
  7865. : ((a->file.last_modified > b->file.last_modified) ? 1
  7866. : -1);
  7867. }
  7868. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7869. }
  7870. return 0;
  7871. }
  7872. static int
  7873. must_hide_file(struct mg_connection *conn, const char *path)
  7874. {
  7875. if (conn && conn->dom_ctx) {
  7876. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7877. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7878. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7879. || ((pattern != NULL)
  7880. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7881. }
  7882. return 0;
  7883. }
  7884. #if !defined(NO_FILESYSTEMS)
  7885. static int
  7886. scan_directory(struct mg_connection *conn,
  7887. const char *dir,
  7888. void *data,
  7889. int (*cb)(struct de *, void *))
  7890. {
  7891. char path[PATH_MAX];
  7892. struct dirent *dp;
  7893. DIR *dirp;
  7894. struct de de;
  7895. int truncated;
  7896. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7897. return 0;
  7898. } else {
  7899. de.conn = conn;
  7900. while ((dp = mg_readdir(dirp)) != NULL) {
  7901. /* Do not show current dir and hidden files */
  7902. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7903. || must_hide_file(conn, dp->d_name)) {
  7904. continue;
  7905. }
  7906. mg_snprintf(
  7907. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7908. /* If we don't memset stat structure to zero, mtime will have
  7909. * garbage and strftime() will segfault later on in
  7910. * print_dir_entry(). memset is required only if mg_stat()
  7911. * fails. For more details, see
  7912. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7913. memset(&de.file, 0, sizeof(de.file));
  7914. if (truncated) {
  7915. /* If the path is not complete, skip processing. */
  7916. continue;
  7917. }
  7918. if (!mg_stat(conn, path, &de.file)) {
  7919. mg_cry_internal(conn,
  7920. "%s: mg_stat(%s) failed: %s",
  7921. __func__,
  7922. path,
  7923. strerror(ERRNO));
  7924. }
  7925. de.file_name = dp->d_name;
  7926. cb(&de, data);
  7927. }
  7928. (void)mg_closedir(dirp);
  7929. }
  7930. return 1;
  7931. }
  7932. #endif /* NO_FILESYSTEMS */
  7933. #if !defined(NO_FILES)
  7934. static int
  7935. remove_directory(struct mg_connection *conn, const char *dir)
  7936. {
  7937. char path[PATH_MAX];
  7938. struct dirent *dp;
  7939. DIR *dirp;
  7940. struct de de;
  7941. int truncated;
  7942. int ok = 1;
  7943. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7944. return 0;
  7945. } else {
  7946. de.conn = conn;
  7947. while ((dp = mg_readdir(dirp)) != NULL) {
  7948. /* Do not show current dir (but show hidden files as they will
  7949. * also be removed) */
  7950. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7951. continue;
  7952. }
  7953. mg_snprintf(
  7954. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7955. /* If we don't memset stat structure to zero, mtime will have
  7956. * garbage and strftime() will segfault later on in
  7957. * print_dir_entry(). memset is required only if mg_stat()
  7958. * fails. For more details, see
  7959. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7960. memset(&de.file, 0, sizeof(de.file));
  7961. if (truncated) {
  7962. /* Do not delete anything shorter */
  7963. ok = 0;
  7964. continue;
  7965. }
  7966. if (!mg_stat(conn, path, &de.file)) {
  7967. mg_cry_internal(conn,
  7968. "%s: mg_stat(%s) failed: %s",
  7969. __func__,
  7970. path,
  7971. strerror(ERRNO));
  7972. ok = 0;
  7973. }
  7974. if (de.file.is_directory) {
  7975. if (remove_directory(conn, path) == 0) {
  7976. ok = 0;
  7977. }
  7978. } else {
  7979. /* This will fail file is the file is in memory */
  7980. if (mg_remove(conn, path) == 0) {
  7981. ok = 0;
  7982. }
  7983. }
  7984. }
  7985. (void)mg_closedir(dirp);
  7986. IGNORE_UNUSED_RESULT(rmdir(dir));
  7987. }
  7988. return ok;
  7989. }
  7990. #endif
  7991. struct dir_scan_data {
  7992. struct de *entries;
  7993. unsigned int num_entries;
  7994. unsigned int arr_size;
  7995. };
  7996. /* Behaves like realloc(), but frees original pointer on failure */
  7997. static void *
  7998. realloc2(void *ptr, size_t size)
  7999. {
  8000. void *new_ptr = mg_realloc(ptr, size);
  8001. if (new_ptr == NULL) {
  8002. mg_free(ptr);
  8003. }
  8004. return new_ptr;
  8005. }
  8006. #if !defined(NO_FILESYSTEMS)
  8007. static int
  8008. dir_scan_callback(struct de *de, void *data)
  8009. {
  8010. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  8011. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  8012. dsd->arr_size *= 2;
  8013. dsd->entries =
  8014. (struct de *)realloc2(dsd->entries,
  8015. dsd->arr_size * sizeof(dsd->entries[0]));
  8016. }
  8017. if (dsd->entries == NULL) {
  8018. /* TODO(lsm, low): propagate an error to the caller */
  8019. dsd->num_entries = 0;
  8020. } else {
  8021. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  8022. dsd->entries[dsd->num_entries].file = de->file;
  8023. dsd->entries[dsd->num_entries].conn = de->conn;
  8024. dsd->num_entries++;
  8025. }
  8026. return 0;
  8027. }
  8028. static void
  8029. handle_directory_request(struct mg_connection *conn, const char *dir)
  8030. {
  8031. unsigned int i;
  8032. int sort_direction;
  8033. struct dir_scan_data data = {NULL, 0, 128};
  8034. char date[64], *esc, *p;
  8035. const char *title;
  8036. time_t curtime = time(NULL);
  8037. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  8038. mg_send_http_error(conn,
  8039. 500,
  8040. "Error: Cannot open directory\nopendir(%s): %s",
  8041. dir,
  8042. strerror(ERRNO));
  8043. return;
  8044. }
  8045. gmt_time_string(date, sizeof(date), &curtime);
  8046. if (!conn) {
  8047. return;
  8048. }
  8049. esc = NULL;
  8050. title = conn->request_info.local_uri;
  8051. if (title[strcspn(title, "&<>")]) {
  8052. /* HTML escaping needed */
  8053. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8054. if (esc) {
  8055. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8056. mg_strlcpy(p, title + i, 2);
  8057. if (*p == '&') {
  8058. strcpy(p, "&amp;");
  8059. } else if (*p == '<') {
  8060. strcpy(p, "&lt;");
  8061. } else if (*p == '>') {
  8062. strcpy(p, "&gt;");
  8063. }
  8064. }
  8065. } else {
  8066. title = "";
  8067. }
  8068. }
  8069. sort_direction = ((conn->request_info.query_string != NULL)
  8070. && (conn->request_info.query_string[0] != '\0')
  8071. && (conn->request_info.query_string[1] == 'd'))
  8072. ? 'a'
  8073. : 'd';
  8074. conn->must_close = 1;
  8075. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8076. send_static_cache_header(conn);
  8077. send_additional_header(conn);
  8078. mg_printf(conn,
  8079. "Date: %s\r\n"
  8080. "Connection: close\r\n"
  8081. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8082. date);
  8083. mg_printf(conn,
  8084. "<html><head><title>Index of %s</title>"
  8085. "<style>th {text-align: left;}</style></head>"
  8086. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8087. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8088. "<th><a href=\"?d%c\">Modified</a></th>"
  8089. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8090. "<tr><td colspan=\"3\"><hr></td></tr>",
  8091. esc ? esc : title,
  8092. esc ? esc : title,
  8093. sort_direction,
  8094. sort_direction,
  8095. sort_direction);
  8096. mg_free(esc);
  8097. /* Print first entry - link to a parent directory */
  8098. mg_printf(conn,
  8099. "<tr><td><a href=\"%s\">%s</a></td>"
  8100. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8101. "..",
  8102. "Parent directory",
  8103. "-",
  8104. "-");
  8105. /* Sort and print directory entries */
  8106. if (data.entries != NULL) {
  8107. qsort(data.entries,
  8108. (size_t)data.num_entries,
  8109. sizeof(data.entries[0]),
  8110. compare_dir_entries);
  8111. for (i = 0; i < data.num_entries; i++) {
  8112. print_dir_entry(&data.entries[i]);
  8113. mg_free(data.entries[i].file_name);
  8114. }
  8115. mg_free(data.entries);
  8116. }
  8117. mg_printf(conn, "%s", "</table></pre></body></html>");
  8118. conn->status_code = 200;
  8119. }
  8120. #endif /* NO_FILESYSTEMS */
  8121. /* Send len bytes from the opened file to the client. */
  8122. static void
  8123. send_file_data(struct mg_connection *conn,
  8124. struct mg_file *filep,
  8125. int64_t offset,
  8126. int64_t len)
  8127. {
  8128. char buf[MG_BUF_LEN];
  8129. int to_read, num_read, num_written;
  8130. int64_t size;
  8131. if (!filep || !conn) {
  8132. return;
  8133. }
  8134. /* Sanity check the offset */
  8135. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8136. : (int64_t)(filep->stat.size);
  8137. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8138. #if defined(MG_USE_OPEN_FILE)
  8139. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8140. /* file stored in memory */
  8141. if (len > size - offset) {
  8142. len = size - offset;
  8143. }
  8144. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8145. } else /* else block below */
  8146. #endif
  8147. if (len > 0 && filep->access.fp != NULL) {
  8148. /* file stored on disk */
  8149. #if defined(__linux__)
  8150. /* sendfile is only available for Linux */
  8151. if ((conn->ssl == 0) && (conn->throttle == 0)
  8152. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8153. "yes"))) {
  8154. off_t sf_offs = (off_t)offset;
  8155. ssize_t sf_sent;
  8156. int sf_file = fileno(filep->access.fp);
  8157. int loop_cnt = 0;
  8158. do {
  8159. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8160. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8161. size_t sf_tosend =
  8162. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8163. sf_sent =
  8164. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8165. if (sf_sent > 0) {
  8166. len -= sf_sent;
  8167. offset += sf_sent;
  8168. } else if (loop_cnt == 0) {
  8169. /* This file can not be sent using sendfile.
  8170. * This might be the case for pseudo-files in the
  8171. * /sys/ and /proc/ file system.
  8172. * Use the regular user mode copy code instead. */
  8173. break;
  8174. } else if (sf_sent == 0) {
  8175. /* No error, but 0 bytes sent. May be EOF? */
  8176. return;
  8177. }
  8178. loop_cnt++;
  8179. } while ((len > 0) && (sf_sent >= 0));
  8180. if (sf_sent > 0) {
  8181. return; /* OK */
  8182. }
  8183. /* sf_sent<0 means error, thus fall back to the classic way */
  8184. /* This is always the case, if sf_file is not a "normal" file,
  8185. * e.g., for sending data from the output of a CGI process. */
  8186. offset = (int64_t)sf_offs;
  8187. }
  8188. #endif
  8189. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8190. mg_cry_internal(conn,
  8191. "%s: fseeko() failed: %s",
  8192. __func__,
  8193. strerror(ERRNO));
  8194. mg_send_http_error(
  8195. conn,
  8196. 500,
  8197. "%s",
  8198. "Error: Unable to access file at requested position.");
  8199. } else {
  8200. while (len > 0) {
  8201. /* Calculate how much to read from the file in the buffer */
  8202. to_read = sizeof(buf);
  8203. if ((int64_t)to_read > len) {
  8204. to_read = (int)len;
  8205. }
  8206. /* Read from file, exit the loop on error */
  8207. if ((num_read =
  8208. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8209. <= 0) {
  8210. break;
  8211. }
  8212. /* Send read bytes to the client, exit the loop on error */
  8213. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8214. != num_read) {
  8215. break;
  8216. }
  8217. /* Both read and were successful, adjust counters */
  8218. len -= num_written;
  8219. }
  8220. }
  8221. }
  8222. }
  8223. static int
  8224. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8225. {
  8226. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8227. }
  8228. static void
  8229. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8230. {
  8231. if ((filestat != NULL) && (buf != NULL)) {
  8232. mg_snprintf(NULL,
  8233. NULL, /* All calls to construct_etag use 64 byte buffer */
  8234. buf,
  8235. buf_len,
  8236. "\"%lx.%" INT64_FMT "\"",
  8237. (unsigned long)filestat->last_modified,
  8238. filestat->size);
  8239. }
  8240. }
  8241. static void
  8242. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8243. {
  8244. if (filep != NULL && filep->fp != NULL) {
  8245. #if defined(_WIN32)
  8246. (void)conn; /* Unused. */
  8247. #else
  8248. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8249. mg_cry_internal(conn,
  8250. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8251. __func__,
  8252. strerror(ERRNO));
  8253. }
  8254. #endif
  8255. }
  8256. }
  8257. #if defined(USE_ZLIB)
  8258. #include "mod_zlib.inl"
  8259. #endif
  8260. #if !defined(NO_FILESYSTEMS)
  8261. static void
  8262. handle_static_file_request(struct mg_connection *conn,
  8263. const char *path,
  8264. struct mg_file *filep,
  8265. const char *mime_type,
  8266. const char *additional_headers)
  8267. {
  8268. char date[64], lm[64], etag[64];
  8269. char range[128]; /* large enough, so there will be no overflow */
  8270. const char *msg = "OK";
  8271. const char *range_hdr;
  8272. time_t curtime = time(NULL);
  8273. int64_t cl, r1, r2;
  8274. struct vec mime_vec;
  8275. int n, truncated;
  8276. char gz_path[PATH_MAX];
  8277. const char *encoding = "";
  8278. const char *origin_hdr;
  8279. const char *cors_orig_cfg;
  8280. const char *cors1, *cors2, *cors3;
  8281. int is_head_request;
  8282. #if defined(USE_ZLIB)
  8283. /* Compression is allowed, unless there is a reason not to use compression.
  8284. * If the file is already compressed, too small or a "range" request was
  8285. * made, on the fly compression is not possible. */
  8286. int allow_on_the_fly_compression = 1;
  8287. #endif
  8288. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8289. return;
  8290. }
  8291. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8292. if (mime_type == NULL) {
  8293. get_mime_type(conn, path, &mime_vec);
  8294. } else {
  8295. mime_vec.ptr = mime_type;
  8296. mime_vec.len = strlen(mime_type);
  8297. }
  8298. if (filep->stat.size > INT64_MAX) {
  8299. mg_send_http_error(conn,
  8300. 500,
  8301. "Error: File size is too large to send\n%" INT64_FMT,
  8302. filep->stat.size);
  8303. return;
  8304. }
  8305. cl = (int64_t)filep->stat.size;
  8306. conn->status_code = 200;
  8307. range[0] = '\0';
  8308. #if defined(USE_ZLIB)
  8309. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8310. * it's important to rewrite the filename after resolving
  8311. * the mime type from it, to preserve the actual file's type */
  8312. if (!conn->accept_gzip) {
  8313. allow_on_the_fly_compression = 0;
  8314. }
  8315. #endif
  8316. /* Check if there is a range header */
  8317. range_hdr = mg_get_header(conn, "Range");
  8318. /* For gzipped files, add *.gz */
  8319. if (filep->stat.is_gzipped) {
  8320. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8321. if (truncated) {
  8322. mg_send_http_error(conn,
  8323. 500,
  8324. "Error: Path of zipped file too long (%s)",
  8325. path);
  8326. return;
  8327. }
  8328. path = gz_path;
  8329. encoding = "Content-Encoding: gzip\r\n";
  8330. #if defined(USE_ZLIB)
  8331. /* File is already compressed. No "on the fly" compression. */
  8332. allow_on_the_fly_compression = 0;
  8333. #endif
  8334. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8335. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8336. struct mg_file_stat file_stat;
  8337. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8338. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8339. && !file_stat.is_directory) {
  8340. file_stat.is_gzipped = 1;
  8341. filep->stat = file_stat;
  8342. cl = (int64_t)filep->stat.size;
  8343. path = gz_path;
  8344. encoding = "Content-Encoding: gzip\r\n";
  8345. #if defined(USE_ZLIB)
  8346. /* File is already compressed. No "on the fly" compression. */
  8347. allow_on_the_fly_compression = 0;
  8348. #endif
  8349. }
  8350. }
  8351. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8352. mg_send_http_error(conn,
  8353. 500,
  8354. "Error: Cannot open file\nfopen(%s): %s",
  8355. path,
  8356. strerror(ERRNO));
  8357. return;
  8358. }
  8359. fclose_on_exec(&filep->access, conn);
  8360. /* If "Range" request was made: parse header, send only selected part
  8361. * of the file. */
  8362. r1 = r2 = 0;
  8363. if ((range_hdr != NULL)
  8364. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8365. && (r2 >= 0)) {
  8366. /* actually, range requests don't play well with a pre-gzipped
  8367. * file (since the range is specified in the uncompressed space) */
  8368. if (filep->stat.is_gzipped) {
  8369. mg_send_http_error(
  8370. conn,
  8371. 416, /* 416 = Range Not Satisfiable */
  8372. "%s",
  8373. "Error: Range requests in gzipped files are not supported");
  8374. (void)mg_fclose(
  8375. &filep->access); /* ignore error on read only file */
  8376. return;
  8377. }
  8378. conn->status_code = 206;
  8379. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8380. mg_snprintf(conn,
  8381. NULL, /* range buffer is big enough */
  8382. range,
  8383. sizeof(range),
  8384. "Content-Range: bytes "
  8385. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8386. r1,
  8387. r1 + cl - 1,
  8388. filep->stat.size);
  8389. msg = "Partial Content";
  8390. #if defined(USE_ZLIB)
  8391. /* Do not compress ranges. */
  8392. allow_on_the_fly_compression = 0;
  8393. #endif
  8394. }
  8395. /* Do not compress small files. Small files do not benefit from file
  8396. * compression, but there is still some overhead. */
  8397. #if defined(USE_ZLIB)
  8398. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8399. /* File is below the size limit. */
  8400. allow_on_the_fly_compression = 0;
  8401. }
  8402. #endif
  8403. /* Standard CORS header */
  8404. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8405. origin_hdr = mg_get_header(conn, "Origin");
  8406. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8407. /* Cross-origin resource sharing (CORS), see
  8408. * http://www.html5rocks.com/en/tutorials/cors/,
  8409. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8410. * -
  8411. * preflight is not supported for files. */
  8412. cors1 = "Access-Control-Allow-Origin: ";
  8413. cors2 = cors_orig_cfg;
  8414. cors3 = "\r\n";
  8415. } else {
  8416. cors1 = cors2 = cors3 = "";
  8417. }
  8418. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8419. * according to
  8420. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8421. gmt_time_string(date, sizeof(date), &curtime);
  8422. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8423. construct_etag(etag, sizeof(etag), &filep->stat);
  8424. /* Send header */
  8425. (void)mg_printf(conn,
  8426. "HTTP/1.1 %d %s\r\n"
  8427. "%s%s%s" /* CORS */
  8428. "Date: %s\r\n"
  8429. "Last-Modified: %s\r\n"
  8430. "Etag: %s\r\n"
  8431. "Content-Type: %.*s\r\n"
  8432. "Connection: %s\r\n",
  8433. conn->status_code,
  8434. msg,
  8435. cors1,
  8436. cors2,
  8437. cors3,
  8438. date,
  8439. lm,
  8440. etag,
  8441. (int)mime_vec.len,
  8442. mime_vec.ptr,
  8443. suggest_connection_header(conn));
  8444. send_static_cache_header(conn);
  8445. send_additional_header(conn);
  8446. #if defined(USE_ZLIB)
  8447. /* On the fly compression allowed */
  8448. if (allow_on_the_fly_compression) {
  8449. /* For on the fly compression, we don't know the content size in
  8450. * advance, so we have to use chunked encoding */
  8451. (void)mg_printf(conn,
  8452. "Content-Encoding: gzip\r\n"
  8453. "Transfer-Encoding: chunked\r\n");
  8454. } else
  8455. #endif
  8456. {
  8457. /* Without on-the-fly compression, we know the content-length
  8458. * and we can use ranges (with on-the-fly compression we cannot).
  8459. * So we send these response headers only in this case. */
  8460. (void)mg_printf(conn,
  8461. "Content-Length: %" INT64_FMT "\r\n"
  8462. "Accept-Ranges: bytes\r\n"
  8463. "%s" /* range */
  8464. "%s" /* encoding */,
  8465. cl,
  8466. range,
  8467. encoding);
  8468. }
  8469. /* The previous code must not add any header starting with X- to make
  8470. * sure no one of the additional_headers is included twice */
  8471. if (additional_headers != NULL) {
  8472. (void)mg_printf(conn,
  8473. "%.*s\r\n\r\n",
  8474. (int)strlen(additional_headers),
  8475. additional_headers);
  8476. } else {
  8477. (void)mg_printf(conn, "\r\n");
  8478. }
  8479. if (!is_head_request) {
  8480. #if defined(USE_ZLIB)
  8481. if (allow_on_the_fly_compression) {
  8482. /* Compress and send */
  8483. send_compressed_data(conn, filep);
  8484. } else
  8485. #endif
  8486. {
  8487. /* Send file directly */
  8488. send_file_data(conn, filep, r1, cl);
  8489. }
  8490. }
  8491. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8492. }
  8493. int
  8494. mg_send_file_body(struct mg_connection *conn, const char *path)
  8495. {
  8496. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8497. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8498. return -1;
  8499. }
  8500. fclose_on_exec(&file.access, conn);
  8501. send_file_data(conn, &file, 0, INT64_MAX);
  8502. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8503. return 0; /* >= 0 for OK */
  8504. }
  8505. #endif /* NO_FILESYSTEMS */
  8506. #if !defined(NO_CACHING)
  8507. /* Return True if we should reply 304 Not Modified. */
  8508. static int
  8509. is_not_modified(const struct mg_connection *conn,
  8510. const struct mg_file_stat *filestat)
  8511. {
  8512. char etag[64];
  8513. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8514. const char *inm = mg_get_header(conn, "If-None-Match");
  8515. construct_etag(etag, sizeof(etag), filestat);
  8516. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8517. || ((ims != NULL)
  8518. && (filestat->last_modified <= parse_date_string(ims)));
  8519. }
  8520. static void
  8521. handle_not_modified_static_file_request(struct mg_connection *conn,
  8522. struct mg_file *filep)
  8523. {
  8524. char date[64], lm[64], etag[64];
  8525. time_t curtime = time(NULL);
  8526. if ((conn == NULL) || (filep == NULL)) {
  8527. return;
  8528. }
  8529. conn->status_code = 304;
  8530. gmt_time_string(date, sizeof(date), &curtime);
  8531. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8532. construct_etag(etag, sizeof(etag), &filep->stat);
  8533. (void)mg_printf(conn,
  8534. "HTTP/1.1 %d %s\r\n"
  8535. "Date: %s\r\n",
  8536. conn->status_code,
  8537. mg_get_response_code_text(conn, conn->status_code),
  8538. date);
  8539. send_static_cache_header(conn);
  8540. send_additional_header(conn);
  8541. (void)mg_printf(conn,
  8542. "Last-Modified: %s\r\n"
  8543. "Etag: %s\r\n"
  8544. "Connection: %s\r\n"
  8545. "\r\n",
  8546. lm,
  8547. etag,
  8548. suggest_connection_header(conn));
  8549. }
  8550. #endif
  8551. #if !defined(NO_FILESYSTEMS)
  8552. void
  8553. mg_send_file(struct mg_connection *conn, const char *path)
  8554. {
  8555. mg_send_mime_file2(conn, path, NULL, NULL);
  8556. }
  8557. void
  8558. mg_send_mime_file(struct mg_connection *conn,
  8559. const char *path,
  8560. const char *mime_type)
  8561. {
  8562. mg_send_mime_file2(conn, path, mime_type, NULL);
  8563. }
  8564. void
  8565. mg_send_mime_file2(struct mg_connection *conn,
  8566. const char *path,
  8567. const char *mime_type,
  8568. const char *additional_headers)
  8569. {
  8570. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8571. if (!conn) {
  8572. /* No conn */
  8573. return;
  8574. }
  8575. if (mg_stat(conn, path, &file.stat)) {
  8576. #if !defined(NO_CACHING)
  8577. if (is_not_modified(conn, &file.stat)) {
  8578. /* Send 304 "Not Modified" - this must not send any body data */
  8579. handle_not_modified_static_file_request(conn, &file);
  8580. } else
  8581. #endif /* NO_CACHING */
  8582. if (file.stat.is_directory) {
  8583. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8584. "yes")) {
  8585. handle_directory_request(conn, path);
  8586. } else {
  8587. mg_send_http_error(conn,
  8588. 403,
  8589. "%s",
  8590. "Error: Directory listing denied");
  8591. }
  8592. } else {
  8593. handle_static_file_request(
  8594. conn, path, &file, mime_type, additional_headers);
  8595. }
  8596. } else {
  8597. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8598. }
  8599. }
  8600. /* For a given PUT path, create all intermediate subdirectories.
  8601. * Return 0 if the path itself is a directory.
  8602. * Return 1 if the path leads to a file.
  8603. * Return -1 for if the path is too long.
  8604. * Return -2 if path can not be created.
  8605. */
  8606. static int
  8607. put_dir(struct mg_connection *conn, const char *path)
  8608. {
  8609. char buf[PATH_MAX];
  8610. const char *s, *p;
  8611. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8612. size_t len;
  8613. int res = 1;
  8614. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8615. len = (size_t)(p - path);
  8616. if (len >= sizeof(buf)) {
  8617. /* path too long */
  8618. res = -1;
  8619. break;
  8620. }
  8621. memcpy(buf, path, len);
  8622. buf[len] = '\0';
  8623. /* Try to create intermediate directory */
  8624. DEBUG_TRACE("mkdir(%s)", buf);
  8625. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8626. /* path does not exixt and can not be created */
  8627. res = -2;
  8628. break;
  8629. }
  8630. /* Is path itself a directory? */
  8631. if (p[1] == '\0') {
  8632. res = 0;
  8633. }
  8634. }
  8635. return res;
  8636. }
  8637. static void
  8638. remove_bad_file(const struct mg_connection *conn, const char *path)
  8639. {
  8640. int r = mg_remove(conn, path);
  8641. if (r != 0) {
  8642. mg_cry_internal(conn,
  8643. "%s: Cannot remove invalid file %s",
  8644. __func__,
  8645. path);
  8646. }
  8647. }
  8648. long long
  8649. mg_store_body(struct mg_connection *conn, const char *path)
  8650. {
  8651. char buf[MG_BUF_LEN];
  8652. long long len = 0;
  8653. int ret, n;
  8654. struct mg_file fi;
  8655. if (conn->consumed_content != 0) {
  8656. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8657. return -11;
  8658. }
  8659. ret = put_dir(conn, path);
  8660. if (ret < 0) {
  8661. /* -1 for path too long,
  8662. * -2 for path can not be created. */
  8663. return ret;
  8664. }
  8665. if (ret != 1) {
  8666. /* Return 0 means, path itself is a directory. */
  8667. return 0;
  8668. }
  8669. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8670. return -12;
  8671. }
  8672. ret = mg_read(conn, buf, sizeof(buf));
  8673. while (ret > 0) {
  8674. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8675. if (n != ret) {
  8676. (void)mg_fclose(
  8677. &fi.access); /* File is bad and will be removed anyway. */
  8678. remove_bad_file(conn, path);
  8679. return -13;
  8680. }
  8681. len += ret;
  8682. ret = mg_read(conn, buf, sizeof(buf));
  8683. }
  8684. /* File is open for writing. If fclose fails, there was probably an
  8685. * error flushing the buffer to disk, so the file on disk might be
  8686. * broken. Delete it and return an error to the caller. */
  8687. if (mg_fclose(&fi.access) != 0) {
  8688. remove_bad_file(conn, path);
  8689. return -14;
  8690. }
  8691. return len;
  8692. }
  8693. #endif /* NO_FILESYSTEMS */
  8694. /* Parse a buffer:
  8695. * Forward the string pointer till the end of a word, then
  8696. * terminate it and forward till the begin of the next word.
  8697. */
  8698. static int
  8699. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8700. {
  8701. /* Forward until a space is found - use isgraph here */
  8702. /* See http://www.cplusplus.com/reference/cctype/ */
  8703. while (isgraph((unsigned char)**ppw)) {
  8704. (*ppw)++;
  8705. }
  8706. /* Check end of word */
  8707. if (eol) {
  8708. /* must be a end of line */
  8709. if ((**ppw != '\r') && (**ppw != '\n')) {
  8710. return -1;
  8711. }
  8712. } else {
  8713. /* must be a end of a word, but not a line */
  8714. if (**ppw != ' ') {
  8715. return -1;
  8716. }
  8717. }
  8718. /* Terminate and forward to the next word */
  8719. do {
  8720. **ppw = 0;
  8721. (*ppw)++;
  8722. } while (isspace((unsigned char)**ppw));
  8723. /* Check after term */
  8724. if (!eol) {
  8725. /* if it's not the end of line, there must be a next word */
  8726. if (!isgraph((unsigned char)**ppw)) {
  8727. return -1;
  8728. }
  8729. }
  8730. /* ok */
  8731. return 1;
  8732. }
  8733. /* Parse HTTP headers from the given buffer, advance buf pointer
  8734. * to the point where parsing stopped.
  8735. * All parameters must be valid pointers (not NULL).
  8736. * Return <0 on error. */
  8737. static int
  8738. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8739. {
  8740. int i;
  8741. int num_headers = 0;
  8742. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8743. char *dp = *buf;
  8744. /* Skip all ASCII characters (>SPACE, <127), to find a ':' */
  8745. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8746. dp++;
  8747. }
  8748. if (dp == *buf) {
  8749. /* End of headers reached. */
  8750. break;
  8751. }
  8752. if (*dp != ':') {
  8753. /* This is not a valid field. */
  8754. return -1;
  8755. }
  8756. /* End of header key (*dp == ':') */
  8757. /* Truncate here and set the key name */
  8758. *dp = 0;
  8759. hdr[i].name = *buf;
  8760. /* Skip all spaces */
  8761. do {
  8762. dp++;
  8763. } while ((*dp == ' ') || (*dp == '\t'));
  8764. /* The rest of the line is the value */
  8765. hdr[i].value = dp;
  8766. /* Find end of line */
  8767. while ((*dp != 0) && (*dp != '\r') && (*dp != '\n')) {
  8768. dp++;
  8769. };
  8770. /* eliminate \r */
  8771. if (*dp == '\r') {
  8772. *dp = 0;
  8773. dp++;
  8774. if (*dp != '\n') {
  8775. /* This is not a valid line. */
  8776. return -1;
  8777. }
  8778. }
  8779. /* here *dp is either 0 or '\n' */
  8780. /* in any case, we have a new header */
  8781. num_headers = i + 1;
  8782. if (*dp) {
  8783. *dp = 0;
  8784. dp++;
  8785. *buf = dp;
  8786. if ((dp[0] == '\r') || (dp[0] == '\n')) {
  8787. /* This is the end of the header */
  8788. break;
  8789. }
  8790. } else {
  8791. *buf = dp;
  8792. break;
  8793. }
  8794. }
  8795. return num_headers;
  8796. }
  8797. struct mg_http_method_info {
  8798. const char *name;
  8799. int request_has_body;
  8800. int response_has_body;
  8801. int is_safe;
  8802. int is_idempotent;
  8803. int is_cacheable;
  8804. };
  8805. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8806. static struct mg_http_method_info http_methods[] = {
  8807. /* HTTP (RFC 2616) */
  8808. {"GET", 0, 1, 1, 1, 1},
  8809. {"POST", 1, 1, 0, 0, 0},
  8810. {"PUT", 1, 0, 0, 1, 0},
  8811. {"DELETE", 0, 0, 0, 1, 0},
  8812. {"HEAD", 0, 0, 1, 1, 1},
  8813. {"OPTIONS", 0, 0, 1, 1, 0},
  8814. {"CONNECT", 1, 1, 0, 0, 0},
  8815. /* TRACE method (RFC 2616) is not supported for security reasons */
  8816. /* PATCH method (RFC 5789) */
  8817. {"PATCH", 1, 0, 0, 0, 0},
  8818. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8819. /* WEBDAV (RFC 2518) */
  8820. {"PROPFIND", 0, 1, 1, 1, 0},
  8821. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8822. * Some PROPFIND results MAY be cached, with care,
  8823. * as there is no cache validation mechanism for
  8824. * most properties. This method is both safe and
  8825. * idempotent (see Section 9.1 of [RFC2616]). */
  8826. {"MKCOL", 0, 0, 0, 1, 0},
  8827. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8828. * When MKCOL is invoked without a request body,
  8829. * the newly created collection SHOULD have no
  8830. * members. A MKCOL request message may contain
  8831. * a message body. The precise behavior of a MKCOL
  8832. * request when the body is present is undefined,
  8833. * ... ==> We do not support MKCOL with body data.
  8834. * This method is idempotent, but not safe (see
  8835. * Section 9.1 of [RFC2616]). Responses to this
  8836. * method MUST NOT be cached. */
  8837. /* Unsupported WEBDAV Methods: */
  8838. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8839. /* + 11 methods from RFC 3253 */
  8840. /* ORDERPATCH (RFC 3648) */
  8841. /* ACL (RFC 3744) */
  8842. /* SEARCH (RFC 5323) */
  8843. /* + MicroSoft extensions
  8844. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8845. /* REPORT method (RFC 3253) */
  8846. {"REPORT", 1, 1, 1, 1, 1},
  8847. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8848. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8849. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8850. * to be useful for REST in case a "GET request with body" is
  8851. * required. */
  8852. {NULL, 0, 0, 0, 0, 0}
  8853. /* end of list */
  8854. };
  8855. static const struct mg_http_method_info *
  8856. get_http_method_info(const char *method)
  8857. {
  8858. /* Check if the method is known to the server. The list of all known
  8859. * HTTP methods can be found here at
  8860. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8861. */
  8862. const struct mg_http_method_info *m = http_methods;
  8863. while (m->name) {
  8864. if (!strcmp(m->name, method)) {
  8865. return m;
  8866. }
  8867. m++;
  8868. }
  8869. return NULL;
  8870. }
  8871. static int
  8872. is_valid_http_method(const char *method)
  8873. {
  8874. return (get_http_method_info(method) != NULL);
  8875. }
  8876. /* Parse HTTP request, fill in mg_request_info structure.
  8877. * This function modifies the buffer by NUL-terminating
  8878. * HTTP request components, header names and header values.
  8879. * Parameters:
  8880. * buf (in/out): pointer to the HTTP header to parse and split
  8881. * len (in): length of HTTP header buffer
  8882. * re (out): parsed header as mg_request_info
  8883. * buf and ri must be valid pointers (not NULL), len>0.
  8884. * Returns <0 on error. */
  8885. static int
  8886. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8887. {
  8888. int request_length;
  8889. int init_skip = 0;
  8890. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8891. * remote_port */
  8892. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8893. NULL;
  8894. ri->num_headers = 0;
  8895. /* RFC says that all initial whitespaces should be ingored */
  8896. /* This included all leading \r and \n (isspace) */
  8897. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8898. while ((len > 0) && isspace((unsigned char)*buf)) {
  8899. buf++;
  8900. len--;
  8901. init_skip++;
  8902. }
  8903. if (len == 0) {
  8904. /* Incomplete request */
  8905. return 0;
  8906. }
  8907. /* Control characters are not allowed, including zero */
  8908. if (iscntrl((unsigned char)*buf)) {
  8909. return -1;
  8910. }
  8911. /* Find end of HTTP header */
  8912. request_length = get_http_header_len(buf, len);
  8913. if (request_length <= 0) {
  8914. return request_length;
  8915. }
  8916. buf[request_length - 1] = '\0';
  8917. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8918. return -1;
  8919. }
  8920. /* The first word has to be the HTTP method */
  8921. ri->request_method = buf;
  8922. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8923. return -1;
  8924. }
  8925. /* Check for a valid http method */
  8926. if (!is_valid_http_method(ri->request_method)) {
  8927. return -1;
  8928. }
  8929. /* The second word is the URI */
  8930. ri->request_uri = buf;
  8931. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8932. return -1;
  8933. }
  8934. /* Next would be the HTTP version */
  8935. ri->http_version = buf;
  8936. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8937. return -1;
  8938. }
  8939. /* Check for a valid HTTP version key */
  8940. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8941. /* Invalid request */
  8942. return -1;
  8943. }
  8944. ri->http_version += 5;
  8945. /* Parse all HTTP headers */
  8946. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8947. if (ri->num_headers < 0) {
  8948. /* Error while parsing headers */
  8949. return -1;
  8950. }
  8951. return request_length + init_skip;
  8952. }
  8953. static int
  8954. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8955. {
  8956. int response_length;
  8957. int init_skip = 0;
  8958. char *tmp, *tmp2;
  8959. long l;
  8960. /* Initialize elements. */
  8961. ri->http_version = ri->status_text = NULL;
  8962. ri->num_headers = ri->status_code = 0;
  8963. /* RFC says that all initial whitespaces should be ingored */
  8964. /* This included all leading \r and \n (isspace) */
  8965. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8966. while ((len > 0) && isspace((unsigned char)*buf)) {
  8967. buf++;
  8968. len--;
  8969. init_skip++;
  8970. }
  8971. if (len == 0) {
  8972. /* Incomplete request */
  8973. return 0;
  8974. }
  8975. /* Control characters are not allowed, including zero */
  8976. if (iscntrl((unsigned char)*buf)) {
  8977. return -1;
  8978. }
  8979. /* Find end of HTTP header */
  8980. response_length = get_http_header_len(buf, len);
  8981. if (response_length <= 0) {
  8982. return response_length;
  8983. }
  8984. buf[response_length - 1] = '\0';
  8985. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8986. return -1;
  8987. }
  8988. /* The first word is the HTTP version */
  8989. /* Check for a valid HTTP version key */
  8990. if (strncmp(buf, "HTTP/", 5) != 0) {
  8991. /* Invalid request */
  8992. return -1;
  8993. }
  8994. buf += 5;
  8995. if (!isgraph((unsigned char)buf[0])) {
  8996. /* Invalid request */
  8997. return -1;
  8998. }
  8999. ri->http_version = buf;
  9000. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9001. return -1;
  9002. }
  9003. /* The second word is the status as a number */
  9004. tmp = buf;
  9005. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  9006. return -1;
  9007. }
  9008. l = strtol(tmp, &tmp2, 10);
  9009. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  9010. /* Everything else but a 3 digit code is invalid */
  9011. return -1;
  9012. }
  9013. ri->status_code = (int)l;
  9014. /* The rest of the line is the status text */
  9015. ri->status_text = buf;
  9016. /* Find end of status text */
  9017. /* isgraph or isspace = isprint */
  9018. while (isprint((unsigned char)*buf)) {
  9019. buf++;
  9020. }
  9021. if ((*buf != '\r') && (*buf != '\n')) {
  9022. return -1;
  9023. }
  9024. /* Terminate string and forward buf to next line */
  9025. do {
  9026. *buf = 0;
  9027. buf++;
  9028. } while (isspace((unsigned char)*buf));
  9029. /* Parse all HTTP headers */
  9030. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  9031. if (ri->num_headers < 0) {
  9032. /* Error while parsing headers */
  9033. return -1;
  9034. }
  9035. return response_length + init_skip;
  9036. }
  9037. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  9038. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  9039. * buffer (which marks the end of HTTP request). Buffer buf may already
  9040. * have some data. The length of the data is stored in nread.
  9041. * Upon every read operation, increase nread by the number of bytes read. */
  9042. static int
  9043. read_message(FILE *fp,
  9044. struct mg_connection *conn,
  9045. char *buf,
  9046. int bufsiz,
  9047. int *nread)
  9048. {
  9049. int request_len, n = 0;
  9050. struct timespec last_action_time;
  9051. double request_timeout;
  9052. if (!conn) {
  9053. return 0;
  9054. }
  9055. memset(&last_action_time, 0, sizeof(last_action_time));
  9056. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9057. /* value of request_timeout is in seconds, config in milliseconds */
  9058. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9059. } else {
  9060. request_timeout = -1.0;
  9061. }
  9062. if (conn->handled_requests > 0) {
  9063. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9064. request_timeout =
  9065. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9066. }
  9067. }
  9068. request_len = get_http_header_len(buf, *nread);
  9069. while (request_len == 0) {
  9070. /* Full request not yet received */
  9071. if (conn->phys_ctx->stop_flag != 0) {
  9072. /* Server is to be stopped. */
  9073. return -1;
  9074. }
  9075. if (*nread >= bufsiz) {
  9076. /* Request too long */
  9077. return -2;
  9078. }
  9079. n = pull_inner(
  9080. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9081. if (n == -2) {
  9082. /* Receive error */
  9083. return -1;
  9084. }
  9085. /* update clock after every read request */
  9086. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9087. if (n > 0) {
  9088. *nread += n;
  9089. request_len = get_http_header_len(buf, *nread);
  9090. } else {
  9091. request_len = 0;
  9092. }
  9093. if ((request_len == 0) && (request_timeout >= 0)) {
  9094. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9095. > request_timeout) {
  9096. /* Timeout */
  9097. return -1;
  9098. }
  9099. }
  9100. }
  9101. return request_len;
  9102. }
  9103. #if !defined(NO_CGI) || !defined(NO_FILES)
  9104. static int
  9105. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9106. {
  9107. const char *expect;
  9108. char buf[MG_BUF_LEN];
  9109. int success = 0;
  9110. if (!conn) {
  9111. return 0;
  9112. }
  9113. expect = mg_get_header(conn, "Expect");
  9114. DEBUG_ASSERT(fp != NULL);
  9115. if (!fp) {
  9116. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9117. return 0;
  9118. }
  9119. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9120. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9121. */
  9122. mg_send_http_error(conn, 417, "Error: Can not fulfill expectation");
  9123. } else {
  9124. if (expect != NULL) {
  9125. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9126. conn->status_code = 100;
  9127. } else {
  9128. conn->status_code = 200;
  9129. }
  9130. DEBUG_ASSERT(conn->consumed_content == 0);
  9131. if (conn->consumed_content != 0) {
  9132. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9133. return 0;
  9134. }
  9135. for (;;) {
  9136. int nread = mg_read(conn, buf, sizeof(buf));
  9137. if (nread <= 0) {
  9138. success = (nread == 0);
  9139. break;
  9140. }
  9141. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9142. break;
  9143. }
  9144. }
  9145. /* Each error code path in this function must send an error */
  9146. if (!success) {
  9147. /* NOTE: Maybe some data has already been sent. */
  9148. /* TODO (low): If some data has been sent, a correct error
  9149. * reply can no longer be sent, so just close the connection */
  9150. mg_send_http_error(conn, 500, "%s", "");
  9151. }
  9152. }
  9153. return success;
  9154. }
  9155. #endif
  9156. #if defined(USE_TIMERS)
  9157. #define TIMER_API static
  9158. #include "timer.inl"
  9159. #endif /* USE_TIMERS */
  9160. #if !defined(NO_CGI)
  9161. /* This structure helps to create an environment for the spawned CGI
  9162. * program.
  9163. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9164. * last element must be NULL.
  9165. * However, on Windows there is a requirement that all these
  9166. * VARIABLE=VALUE\0
  9167. * strings must reside in a contiguous buffer. The end of the buffer is
  9168. * marked by two '\0' characters.
  9169. * We satisfy both worlds: we create an envp array (which is vars), all
  9170. * entries are actually pointers inside buf. */
  9171. struct cgi_environment {
  9172. struct mg_connection *conn;
  9173. /* Data block */
  9174. char *buf; /* Environment buffer */
  9175. size_t buflen; /* Space available in buf */
  9176. size_t bufused; /* Space taken in buf */
  9177. /* Index block */
  9178. char **var; /* char **envp */
  9179. size_t varlen; /* Number of variables available in var */
  9180. size_t varused; /* Number of variables stored in var */
  9181. };
  9182. static void addenv(struct cgi_environment *env,
  9183. PRINTF_FORMAT_STRING(const char *fmt),
  9184. ...) PRINTF_ARGS(2, 3);
  9185. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9186. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9187. static void
  9188. addenv(struct cgi_environment *env, const char *fmt, ...)
  9189. {
  9190. size_t i, n, space;
  9191. int truncated = 0;
  9192. char *added;
  9193. va_list ap;
  9194. if ((env->varlen - env->varused) < 2) {
  9195. mg_cry_internal(env->conn,
  9196. "%s: Cannot register CGI variable [%s]",
  9197. __func__,
  9198. fmt);
  9199. return;
  9200. }
  9201. /* Calculate how much space is left in the buffer */
  9202. space = (env->buflen - env->bufused);
  9203. do {
  9204. /* Space for "\0\0" is always needed. */
  9205. if (space <= 2) {
  9206. /* Allocate new buffer */
  9207. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9208. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9209. if (!added) {
  9210. /* Out of memory */
  9211. mg_cry_internal(
  9212. env->conn,
  9213. "%s: Cannot allocate memory for CGI variable [%s]",
  9214. __func__,
  9215. fmt);
  9216. return;
  9217. }
  9218. /* Retarget pointers */
  9219. env->buf = added;
  9220. env->buflen = n;
  9221. for (i = 0, n = 0; i < env->varused; i++) {
  9222. env->var[i] = added + n;
  9223. n += strlen(added + n) + 1;
  9224. }
  9225. space = (env->buflen - env->bufused);
  9226. }
  9227. /* Make a pointer to the free space int the buffer */
  9228. added = env->buf + env->bufused;
  9229. /* Copy VARIABLE=VALUE\0 string into the free space */
  9230. va_start(ap, fmt);
  9231. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9232. va_end(ap);
  9233. /* Do not add truncated strings to the environment */
  9234. if (truncated) {
  9235. /* Reallocate the buffer */
  9236. space = 0;
  9237. }
  9238. } while (truncated);
  9239. /* Calculate number of bytes added to the environment */
  9240. n = strlen(added) + 1;
  9241. env->bufused += n;
  9242. /* Append a pointer to the added string into the envp array */
  9243. env->var[env->varused] = added;
  9244. env->varused++;
  9245. }
  9246. /* Return 0 on success, non-zero if an error occurs. */
  9247. static int
  9248. prepare_cgi_environment(struct mg_connection *conn,
  9249. const char *prog,
  9250. struct cgi_environment *env)
  9251. {
  9252. const char *s;
  9253. struct vec var_vec;
  9254. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9255. int i, truncated, uri_len;
  9256. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9257. return -1;
  9258. }
  9259. env->conn = conn;
  9260. env->buflen = CGI_ENVIRONMENT_SIZE;
  9261. env->bufused = 0;
  9262. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9263. if (env->buf == NULL) {
  9264. mg_cry_internal(conn,
  9265. "%s: Not enough memory for environmental buffer",
  9266. __func__);
  9267. return -1;
  9268. }
  9269. env->varlen = MAX_CGI_ENVIR_VARS;
  9270. env->varused = 0;
  9271. env->var =
  9272. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9273. if (env->var == NULL) {
  9274. mg_cry_internal(conn,
  9275. "%s: Not enough memory for environmental variables",
  9276. __func__);
  9277. mg_free(env->buf);
  9278. return -1;
  9279. }
  9280. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9281. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9282. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9283. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9284. /* Prepare the environment block */
  9285. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9286. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9287. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9288. #if defined(USE_IPV6)
  9289. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9290. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9291. } else
  9292. #endif
  9293. {
  9294. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9295. }
  9296. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9297. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9298. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9299. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9300. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9301. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9302. /* SCRIPT_NAME */
  9303. uri_len = (int)strlen(conn->request_info.local_uri);
  9304. if (conn->path_info == NULL) {
  9305. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9306. /* URI: /path_to_script/script.cgi */
  9307. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9308. } else {
  9309. /* URI: /path_to_script/ ... using index.cgi */
  9310. const char *index_file = strrchr(prog, '/');
  9311. if (index_file) {
  9312. addenv(env,
  9313. "SCRIPT_NAME=%s%s",
  9314. conn->request_info.local_uri,
  9315. index_file + 1);
  9316. }
  9317. }
  9318. } else {
  9319. /* URI: /path_to_script/script.cgi/path_info */
  9320. addenv(env,
  9321. "SCRIPT_NAME=%.*s",
  9322. uri_len - (int)strlen(conn->path_info),
  9323. conn->request_info.local_uri);
  9324. }
  9325. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9326. if (conn->path_info == NULL) {
  9327. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9328. } else {
  9329. addenv(env,
  9330. "PATH_TRANSLATED=%s%s",
  9331. conn->dom_ctx->config[DOCUMENT_ROOT],
  9332. conn->path_info);
  9333. }
  9334. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9335. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9336. addenv(env, "CONTENT_TYPE=%s", s);
  9337. }
  9338. if (conn->request_info.query_string != NULL) {
  9339. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9340. }
  9341. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9342. addenv(env, "CONTENT_LENGTH=%s", s);
  9343. }
  9344. if ((s = getenv("PATH")) != NULL) {
  9345. addenv(env, "PATH=%s", s);
  9346. }
  9347. if (conn->path_info != NULL) {
  9348. addenv(env, "PATH_INFO=%s", conn->path_info);
  9349. }
  9350. if (conn->status_code > 0) {
  9351. /* CGI error handler should show the status code */
  9352. addenv(env, "STATUS=%d", conn->status_code);
  9353. }
  9354. #if defined(_WIN32)
  9355. if ((s = getenv("COMSPEC")) != NULL) {
  9356. addenv(env, "COMSPEC=%s", s);
  9357. }
  9358. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9359. addenv(env, "SYSTEMROOT=%s", s);
  9360. }
  9361. if ((s = getenv("SystemDrive")) != NULL) {
  9362. addenv(env, "SystemDrive=%s", s);
  9363. }
  9364. if ((s = getenv("ProgramFiles")) != NULL) {
  9365. addenv(env, "ProgramFiles=%s", s);
  9366. }
  9367. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9368. addenv(env, "ProgramFiles(x86)=%s", s);
  9369. }
  9370. #else
  9371. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9372. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9373. }
  9374. #endif /* _WIN32 */
  9375. if ((s = getenv("PERLLIB")) != NULL) {
  9376. addenv(env, "PERLLIB=%s", s);
  9377. }
  9378. if (conn->request_info.remote_user != NULL) {
  9379. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9380. addenv(env, "%s", "AUTH_TYPE=Digest");
  9381. }
  9382. /* Add all headers as HTTP_* variables */
  9383. for (i = 0; i < conn->request_info.num_headers; i++) {
  9384. (void)mg_snprintf(conn,
  9385. &truncated,
  9386. http_var_name,
  9387. sizeof(http_var_name),
  9388. "HTTP_%s",
  9389. conn->request_info.http_headers[i].name);
  9390. if (truncated) {
  9391. mg_cry_internal(conn,
  9392. "%s: HTTP header variable too long [%s]",
  9393. __func__,
  9394. conn->request_info.http_headers[i].name);
  9395. continue;
  9396. }
  9397. /* Convert variable name into uppercase, and change - to _ */
  9398. for (p = http_var_name; *p != '\0'; p++) {
  9399. if (*p == '-') {
  9400. *p = '_';
  9401. }
  9402. *p = (char)toupper((unsigned char)*p);
  9403. }
  9404. addenv(env,
  9405. "%s=%s",
  9406. http_var_name,
  9407. conn->request_info.http_headers[i].value);
  9408. }
  9409. /* Add user-specified variables */
  9410. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9411. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9412. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9413. }
  9414. env->var[env->varused] = NULL;
  9415. env->buf[env->bufused] = '\0';
  9416. return 0;
  9417. }
  9418. /* Data for CGI process control: PID and number of references */
  9419. struct process_control_data {
  9420. pid_t pid;
  9421. int references;
  9422. };
  9423. static int
  9424. abort_process(void *data)
  9425. {
  9426. /* Waitpid checks for child status and won't work for a pid that does not
  9427. * identify a child of the current process. Thus, if the pid is reused,
  9428. * we will not affect a different process. */
  9429. struct process_control_data *proc = (struct process_control_data *)data;
  9430. int status = 0;
  9431. int refs;
  9432. pid_t ret_pid;
  9433. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9434. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9435. /* Stop child process */
  9436. DEBUG_TRACE("CGI timer: Stop child process %p\n", proc->pid);
  9437. kill(proc->pid, SIGABRT);
  9438. /* Wait until process is terminated (don't leave zombies) */
  9439. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9440. ;
  9441. } else {
  9442. DEBUG_TRACE("CGI timer: Child process %p already stopped\n", proc->pid);
  9443. }
  9444. /* Dec reference counter */
  9445. refs = mg_atomic_dec(&proc->references);
  9446. if (refs == 0) {
  9447. /* no more references - free data */
  9448. mg_free(data);
  9449. }
  9450. return 0;
  9451. }
  9452. /* Local (static) function assumes all arguments are valid. */
  9453. static void
  9454. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9455. {
  9456. char *buf;
  9457. size_t buflen;
  9458. int headers_len, data_len, i, truncated;
  9459. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9460. const char *status, *status_text, *connection_state;
  9461. char *pbuf, dir[PATH_MAX], *p;
  9462. struct mg_request_info ri;
  9463. struct cgi_environment blk;
  9464. FILE *in = NULL, *out = NULL, *err = NULL;
  9465. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9466. pid_t pid = (pid_t)-1;
  9467. struct process_control_data *proc = NULL;
  9468. #if defined(USE_TIMERS)
  9469. double cgi_timeout = -1.0;
  9470. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9471. /* Get timeout in seconds */
  9472. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9473. }
  9474. #endif
  9475. buf = NULL;
  9476. buflen = conn->phys_ctx->max_request_size;
  9477. i = prepare_cgi_environment(conn, prog, &blk);
  9478. if (i != 0) {
  9479. blk.buf = NULL;
  9480. blk.var = NULL;
  9481. goto done;
  9482. }
  9483. /* CGI must be executed in its own directory. 'dir' must point to the
  9484. * directory containing executable program, 'p' must point to the
  9485. * executable program name relative to 'dir'. */
  9486. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9487. if (truncated) {
  9488. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9489. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9490. goto done;
  9491. }
  9492. if ((p = strrchr(dir, '/')) != NULL) {
  9493. *p++ = '\0';
  9494. } else {
  9495. dir[0] = '.';
  9496. dir[1] = '\0';
  9497. p = (char *)prog;
  9498. }
  9499. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9500. status = strerror(ERRNO);
  9501. mg_cry_internal(
  9502. conn,
  9503. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9504. prog,
  9505. status);
  9506. mg_send_http_error(conn,
  9507. 500,
  9508. "Error: Cannot create CGI pipe: %s",
  9509. status);
  9510. goto done;
  9511. }
  9512. proc = (struct process_control_data *)
  9513. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9514. if (proc == NULL) {
  9515. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9516. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9517. goto done;
  9518. }
  9519. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9520. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9521. if (pid == (pid_t)-1) {
  9522. status = strerror(ERRNO);
  9523. mg_cry_internal(
  9524. conn,
  9525. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9526. prog,
  9527. status);
  9528. mg_send_http_error(conn,
  9529. 500,
  9530. "Error: Cannot spawn CGI process [%s]: %s",
  9531. prog,
  9532. status);
  9533. mg_free(proc);
  9534. proc = NULL;
  9535. goto done;
  9536. }
  9537. /* Store data in shared process_control_data */
  9538. proc->pid = pid;
  9539. proc->references = 1;
  9540. #if defined(USE_TIMERS)
  9541. if (cgi_timeout > 0.0) {
  9542. proc->references = 2;
  9543. // Start a timer for CGI
  9544. timer_add(conn->phys_ctx,
  9545. cgi_timeout /* in seconds */,
  9546. 0.0,
  9547. 1,
  9548. abort_process,
  9549. (void *)proc);
  9550. }
  9551. #endif
  9552. /* Parent closes only one side of the pipes.
  9553. * If we don't mark them as closed, close() attempt before
  9554. * return from this function throws an exception on Windows.
  9555. * Windows does not like when closed descriptor is closed again. */
  9556. (void)close(fdin[0]);
  9557. (void)close(fdout[1]);
  9558. (void)close(fderr[1]);
  9559. fdin[0] = fdout[1] = fderr[1] = -1;
  9560. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9561. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9562. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9563. status = strerror(ERRNO);
  9564. mg_cry_internal(conn,
  9565. "Error: CGI program \"%s\": Can not open fd: %s",
  9566. prog,
  9567. status);
  9568. mg_send_http_error(conn,
  9569. 500,
  9570. "Error: CGI can not open fd\nfdopen: %s",
  9571. status);
  9572. goto done;
  9573. }
  9574. setbuf(in, NULL);
  9575. setbuf(out, NULL);
  9576. setbuf(err, NULL);
  9577. fout.access.fp = out;
  9578. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9579. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9580. conn->content_len);
  9581. /* This is a POST/PUT request, or another request with body data. */
  9582. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9583. /* Error sending the body data */
  9584. mg_cry_internal(
  9585. conn,
  9586. "Error: CGI program \"%s\": Forward body data failed",
  9587. prog);
  9588. goto done;
  9589. }
  9590. }
  9591. /* Close so child gets an EOF. */
  9592. fclose(in);
  9593. in = NULL;
  9594. fdin[1] = -1;
  9595. /* Now read CGI reply into a buffer. We need to set correct
  9596. * status code, thus we need to see all HTTP headers first.
  9597. * Do not send anything back to client, until we buffer in all
  9598. * HTTP headers. */
  9599. data_len = 0;
  9600. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9601. if (buf == NULL) {
  9602. mg_send_http_error(conn,
  9603. 500,
  9604. "Error: Not enough memory for CGI buffer (%u bytes)",
  9605. (unsigned int)buflen);
  9606. mg_cry_internal(
  9607. conn,
  9608. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9609. "bytes)",
  9610. prog,
  9611. (unsigned int)buflen);
  9612. goto done;
  9613. }
  9614. DEBUG_TRACE("CGI: %s", "wait for response");
  9615. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9616. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9617. if (headers_len <= 0) {
  9618. /* Could not parse the CGI response. Check if some error message on
  9619. * stderr. */
  9620. i = pull_all(err, conn, buf, (int)buflen);
  9621. if (i > 0) {
  9622. /* CGI program explicitly sent an error */
  9623. /* Write the error message to the internal log */
  9624. mg_cry_internal(conn,
  9625. "Error: CGI program \"%s\" sent error "
  9626. "message: [%.*s]",
  9627. prog,
  9628. i,
  9629. buf);
  9630. /* Don't send the error message back to the client */
  9631. mg_send_http_error(conn,
  9632. 500,
  9633. "Error: CGI program \"%s\" failed.",
  9634. prog);
  9635. } else {
  9636. /* CGI program did not explicitly send an error, but a broken
  9637. * respon header */
  9638. mg_cry_internal(conn,
  9639. "Error: CGI program sent malformed or too big "
  9640. "(>%u bytes) HTTP headers: [%.*s]",
  9641. (unsigned)buflen,
  9642. data_len,
  9643. buf);
  9644. mg_send_http_error(conn,
  9645. 500,
  9646. "Error: CGI program sent malformed or too big "
  9647. "(>%u bytes) HTTP headers: [%.*s]",
  9648. (unsigned)buflen,
  9649. data_len,
  9650. buf);
  9651. }
  9652. /* in both cases, abort processing CGI */
  9653. goto done;
  9654. }
  9655. pbuf = buf;
  9656. buf[headers_len - 1] = '\0';
  9657. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9658. /* Make up and send the status line */
  9659. status_text = "OK";
  9660. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9661. != NULL) {
  9662. conn->status_code = atoi(status);
  9663. status_text = status;
  9664. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9665. status_text++;
  9666. }
  9667. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9668. != NULL) {
  9669. conn->status_code = 307;
  9670. } else {
  9671. conn->status_code = 200;
  9672. }
  9673. connection_state =
  9674. get_header(ri.http_headers, ri.num_headers, "Connection");
  9675. if (!header_has_option(connection_state, "keep-alive")) {
  9676. conn->must_close = 1;
  9677. }
  9678. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9679. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9680. /* Send headers */
  9681. for (i = 0; i < ri.num_headers; i++) {
  9682. DEBUG_TRACE("CGI header: %s: %s",
  9683. ri.http_headers[i].name,
  9684. ri.http_headers[i].value);
  9685. mg_printf(conn,
  9686. "%s: %s\r\n",
  9687. ri.http_headers[i].name,
  9688. ri.http_headers[i].value);
  9689. }
  9690. mg_write(conn, "\r\n", 2);
  9691. /* Send chunk of data that may have been read after the headers */
  9692. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9693. /* Read the rest of CGI output and send to the client */
  9694. DEBUG_TRACE("CGI: %s", "forward all data");
  9695. send_file_data(conn, &fout, 0, INT64_MAX);
  9696. DEBUG_TRACE("CGI: %s", "all data sent");
  9697. done:
  9698. mg_free(blk.var);
  9699. mg_free(blk.buf);
  9700. if (pid != (pid_t)-1) {
  9701. abort_process((void *)proc);
  9702. }
  9703. if (fdin[0] != -1) {
  9704. close(fdin[0]);
  9705. }
  9706. if (fdout[1] != -1) {
  9707. close(fdout[1]);
  9708. }
  9709. if (fderr[1] != -1) {
  9710. close(fderr[1]);
  9711. }
  9712. if (in != NULL) {
  9713. fclose(in);
  9714. } else if (fdin[1] != -1) {
  9715. close(fdin[1]);
  9716. }
  9717. if (out != NULL) {
  9718. fclose(out);
  9719. } else if (fdout[0] != -1) {
  9720. close(fdout[0]);
  9721. }
  9722. if (err != NULL) {
  9723. fclose(err);
  9724. } else if (fderr[0] != -1) {
  9725. close(fderr[0]);
  9726. }
  9727. mg_free(buf);
  9728. }
  9729. #endif /* !NO_CGI */
  9730. #if !defined(NO_FILES)
  9731. static void
  9732. mkcol(struct mg_connection *conn, const char *path)
  9733. {
  9734. int rc, body_len;
  9735. struct de de;
  9736. char date[64];
  9737. time_t curtime = time(NULL);
  9738. if (conn == NULL) {
  9739. return;
  9740. }
  9741. /* TODO (mid): Check the mg_send_http_error situations in this function
  9742. */
  9743. memset(&de.file, 0, sizeof(de.file));
  9744. if (!mg_stat(conn, path, &de.file)) {
  9745. mg_cry_internal(conn,
  9746. "%s: mg_stat(%s) failed: %s",
  9747. __func__,
  9748. path,
  9749. strerror(ERRNO));
  9750. }
  9751. if (de.file.last_modified) {
  9752. /* TODO (mid): This check does not seem to make any sense ! */
  9753. /* TODO (mid): Add a webdav unit test first, before changing
  9754. * anything here. */
  9755. mg_send_http_error(
  9756. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9757. return;
  9758. }
  9759. body_len = conn->data_len - conn->request_len;
  9760. if (body_len > 0) {
  9761. mg_send_http_error(
  9762. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9763. return;
  9764. }
  9765. rc = mg_mkdir(conn, path, 0755);
  9766. if (rc == 0) {
  9767. conn->status_code = 201;
  9768. gmt_time_string(date, sizeof(date), &curtime);
  9769. mg_printf(conn,
  9770. "HTTP/1.1 %d Created\r\n"
  9771. "Date: %s\r\n",
  9772. conn->status_code,
  9773. date);
  9774. send_static_cache_header(conn);
  9775. send_additional_header(conn);
  9776. mg_printf(conn,
  9777. "Content-Length: 0\r\n"
  9778. "Connection: %s\r\n\r\n",
  9779. suggest_connection_header(conn));
  9780. } else {
  9781. if (errno == EEXIST) {
  9782. mg_send_http_error(
  9783. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9784. } else if (errno == EACCES) {
  9785. mg_send_http_error(
  9786. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9787. } else if (errno == ENOENT) {
  9788. mg_send_http_error(
  9789. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9790. } else {
  9791. mg_send_http_error(
  9792. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9793. }
  9794. }
  9795. }
  9796. static void
  9797. put_file(struct mg_connection *conn, const char *path)
  9798. {
  9799. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9800. const char *range;
  9801. int64_t r1, r2;
  9802. int rc;
  9803. char date[64];
  9804. time_t curtime = time(NULL);
  9805. if (conn == NULL) {
  9806. return;
  9807. }
  9808. if (mg_stat(conn, path, &file.stat)) {
  9809. /* File already exists */
  9810. conn->status_code = 200;
  9811. if (file.stat.is_directory) {
  9812. /* This is an already existing directory,
  9813. * so there is nothing to do for the server. */
  9814. rc = 0;
  9815. } else {
  9816. /* File exists and is not a directory. */
  9817. /* Can it be replaced? */
  9818. #if defined(MG_USE_OPEN_FILE)
  9819. if (file.access.membuf != NULL) {
  9820. /* This is an "in-memory" file, that can not be replaced */
  9821. mg_send_http_error(conn,
  9822. 405,
  9823. "Error: Put not possible\nReplacing %s "
  9824. "is not supported",
  9825. path);
  9826. return;
  9827. }
  9828. #endif
  9829. /* Check if the server may write this file */
  9830. if (access(path, W_OK) == 0) {
  9831. /* Access granted */
  9832. conn->status_code = 200;
  9833. rc = 1;
  9834. } else {
  9835. mg_send_http_error(
  9836. conn,
  9837. 403,
  9838. "Error: Put not possible\nReplacing %s is not allowed",
  9839. path);
  9840. return;
  9841. }
  9842. }
  9843. } else {
  9844. /* File should be created */
  9845. conn->status_code = 201;
  9846. rc = put_dir(conn, path);
  9847. }
  9848. if (rc == 0) {
  9849. /* put_dir returns 0 if path is a directory */
  9850. gmt_time_string(date, sizeof(date), &curtime);
  9851. mg_printf(conn,
  9852. "HTTP/1.1 %d %s\r\n",
  9853. conn->status_code,
  9854. mg_get_response_code_text(NULL, conn->status_code));
  9855. send_no_cache_header(conn);
  9856. send_additional_header(conn);
  9857. mg_printf(conn,
  9858. "Date: %s\r\n"
  9859. "Content-Length: 0\r\n"
  9860. "Connection: %s\r\n\r\n",
  9861. date,
  9862. suggest_connection_header(conn));
  9863. /* Request to create a directory has been fulfilled successfully.
  9864. * No need to put a file. */
  9865. return;
  9866. }
  9867. if (rc == -1) {
  9868. /* put_dir returns -1 if the path is too long */
  9869. mg_send_http_error(conn,
  9870. 414,
  9871. "Error: Path too long\nput_dir(%s): %s",
  9872. path,
  9873. strerror(ERRNO));
  9874. return;
  9875. }
  9876. if (rc == -2) {
  9877. /* put_dir returns -2 if the directory can not be created */
  9878. mg_send_http_error(conn,
  9879. 500,
  9880. "Error: Can not create directory\nput_dir(%s): %s",
  9881. path,
  9882. strerror(ERRNO));
  9883. return;
  9884. }
  9885. /* A file should be created or overwritten. */
  9886. /* Currently CivetWeb does not nead read+write access. */
  9887. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9888. || file.access.fp == NULL) {
  9889. (void)mg_fclose(&file.access);
  9890. mg_send_http_error(conn,
  9891. 500,
  9892. "Error: Can not create file\nfopen(%s): %s",
  9893. path,
  9894. strerror(ERRNO));
  9895. return;
  9896. }
  9897. fclose_on_exec(&file.access, conn);
  9898. range = mg_get_header(conn, "Content-Range");
  9899. r1 = r2 = 0;
  9900. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9901. conn->status_code = 206; /* Partial content */
  9902. fseeko(file.access.fp, r1, SEEK_SET);
  9903. }
  9904. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9905. /* forward_body_data failed.
  9906. * The error code has already been sent to the client,
  9907. * and conn->status_code is already set. */
  9908. (void)mg_fclose(&file.access);
  9909. return;
  9910. }
  9911. if (mg_fclose(&file.access) != 0) {
  9912. /* fclose failed. This might have different reasons, but a likely
  9913. * one is "no space on disk", http 507. */
  9914. conn->status_code = 507;
  9915. }
  9916. gmt_time_string(date, sizeof(date), &curtime);
  9917. mg_printf(conn,
  9918. "HTTP/1.1 %d %s\r\n",
  9919. conn->status_code,
  9920. mg_get_response_code_text(NULL, conn->status_code));
  9921. send_no_cache_header(conn);
  9922. send_additional_header(conn);
  9923. mg_printf(conn,
  9924. "Date: %s\r\n"
  9925. "Content-Length: 0\r\n"
  9926. "Connection: %s\r\n\r\n",
  9927. date,
  9928. suggest_connection_header(conn));
  9929. }
  9930. static void
  9931. delete_file(struct mg_connection *conn, const char *path)
  9932. {
  9933. struct de de;
  9934. memset(&de.file, 0, sizeof(de.file));
  9935. if (!mg_stat(conn, path, &de.file)) {
  9936. /* mg_stat returns 0 if the file does not exist */
  9937. mg_send_http_error(conn,
  9938. 404,
  9939. "Error: Cannot delete file\nFile %s not found",
  9940. path);
  9941. return;
  9942. }
  9943. #if 0 /* Ignore if a file in memory is inside a folder */
  9944. if (de.access.membuf != NULL) {
  9945. /* the file is cached in memory */
  9946. mg_send_http_error(
  9947. conn,
  9948. 405,
  9949. "Error: Delete not possible\nDeleting %s is not supported",
  9950. path);
  9951. return;
  9952. }
  9953. #endif
  9954. if (de.file.is_directory) {
  9955. if (remove_directory(conn, path)) {
  9956. /* Delete is successful: Return 204 without content. */
  9957. mg_send_http_error(conn, 204, "%s", "");
  9958. } else {
  9959. /* Delete is not successful: Return 500 (Server error). */
  9960. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9961. }
  9962. return;
  9963. }
  9964. /* This is an existing file (not a directory).
  9965. * Check if write permission is granted. */
  9966. if (access(path, W_OK) != 0) {
  9967. /* File is read only */
  9968. mg_send_http_error(
  9969. conn,
  9970. 403,
  9971. "Error: Delete not possible\nDeleting %s is not allowed",
  9972. path);
  9973. return;
  9974. }
  9975. /* Try to delete it. */
  9976. if (mg_remove(conn, path) == 0) {
  9977. /* Delete was successful: Return 204 without content. */
  9978. mg_send_http_error(conn, 204, "%s", "");
  9979. } else {
  9980. /* Delete not successful (file locked). */
  9981. mg_send_http_error(conn,
  9982. 423,
  9983. "Error: Cannot delete file\nremove(%s): %s",
  9984. path,
  9985. strerror(ERRNO));
  9986. }
  9987. }
  9988. #endif /* !NO_FILES */
  9989. #if !defined(NO_FILESYSTEMS)
  9990. static void
  9991. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9992. static void
  9993. do_ssi_include(struct mg_connection *conn,
  9994. const char *ssi,
  9995. char *tag,
  9996. int include_level)
  9997. {
  9998. char file_name[MG_BUF_LEN], path[512], *p;
  9999. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10000. size_t len;
  10001. int truncated = 0;
  10002. if (conn == NULL) {
  10003. return;
  10004. }
  10005. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10006. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10007. * always < MG_BUF_LEN. */
  10008. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10009. /* File name is relative to the webserver root */
  10010. file_name[511] = 0;
  10011. (void)mg_snprintf(conn,
  10012. &truncated,
  10013. path,
  10014. sizeof(path),
  10015. "%s/%s",
  10016. conn->dom_ctx->config[DOCUMENT_ROOT],
  10017. file_name);
  10018. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10019. /* File name is relative to the webserver working directory
  10020. * or it is absolute system path */
  10021. file_name[511] = 0;
  10022. (void)
  10023. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10024. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10025. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10026. /* File name is relative to the currect document */
  10027. file_name[511] = 0;
  10028. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10029. if (!truncated) {
  10030. if ((p = strrchr(path, '/')) != NULL) {
  10031. p[1] = '\0';
  10032. }
  10033. len = strlen(path);
  10034. (void)mg_snprintf(conn,
  10035. &truncated,
  10036. path + len,
  10037. sizeof(path) - len,
  10038. "%s",
  10039. file_name);
  10040. }
  10041. } else {
  10042. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10043. return;
  10044. }
  10045. if (truncated) {
  10046. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10047. return;
  10048. }
  10049. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10050. mg_cry_internal(conn,
  10051. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10052. tag,
  10053. path,
  10054. strerror(ERRNO));
  10055. } else {
  10056. fclose_on_exec(&file.access, conn);
  10057. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10058. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10059. path)
  10060. > 0) {
  10061. send_ssi_file(conn, path, &file, include_level + 1);
  10062. } else {
  10063. send_file_data(conn, &file, 0, INT64_MAX);
  10064. }
  10065. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10066. }
  10067. }
  10068. #if !defined(NO_POPEN)
  10069. static void
  10070. do_ssi_exec(struct mg_connection *conn, char *tag)
  10071. {
  10072. char cmd[1024] = "";
  10073. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10074. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10075. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10076. } else {
  10077. cmd[1023] = 0;
  10078. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10079. mg_cry_internal(conn,
  10080. "Cannot SSI #exec: [%s]: %s",
  10081. cmd,
  10082. strerror(ERRNO));
  10083. } else {
  10084. send_file_data(conn, &file, 0, INT64_MAX);
  10085. pclose(file.access.fp);
  10086. }
  10087. }
  10088. }
  10089. #endif /* !NO_POPEN */
  10090. static int
  10091. mg_fgetc(struct mg_file *filep, int offset)
  10092. {
  10093. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10094. if (filep == NULL) {
  10095. return EOF;
  10096. }
  10097. #if defined(MG_USE_OPEN_FILE)
  10098. if ((filep->access.membuf != NULL) && (offset >= 0)
  10099. && (((unsigned int)(offset)) < filep->stat.size)) {
  10100. return ((const unsigned char *)filep->access.membuf)[offset];
  10101. } else /* else block below */
  10102. #endif
  10103. if (filep->access.fp != NULL) {
  10104. return fgetc(filep->access.fp);
  10105. } else {
  10106. return EOF;
  10107. }
  10108. }
  10109. static void
  10110. send_ssi_file(struct mg_connection *conn,
  10111. const char *path,
  10112. struct mg_file *filep,
  10113. int include_level)
  10114. {
  10115. char buf[MG_BUF_LEN];
  10116. int ch, offset, len, in_tag, in_ssi_tag;
  10117. if (include_level > 10) {
  10118. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10119. return;
  10120. }
  10121. in_tag = in_ssi_tag = len = offset = 0;
  10122. /* Read file, byte by byte, and look for SSI include tags */
  10123. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10124. if (in_tag) {
  10125. /* We are in a tag, either SSI tag or html tag */
  10126. if (ch == '>') {
  10127. /* Tag is closing */
  10128. buf[len++] = '>';
  10129. if (in_ssi_tag) {
  10130. /* Handle SSI tag */
  10131. buf[len] = 0;
  10132. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10133. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10134. #if !defined(NO_POPEN)
  10135. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10136. do_ssi_exec(conn, buf + 9);
  10137. #endif /* !NO_POPEN */
  10138. } else {
  10139. mg_cry_internal(conn,
  10140. "%s: unknown SSI "
  10141. "command: \"%s\"",
  10142. path,
  10143. buf);
  10144. }
  10145. len = 0;
  10146. in_ssi_tag = in_tag = 0;
  10147. } else {
  10148. /* Not an SSI tag */
  10149. /* Flush buffer */
  10150. (void)mg_write(conn, buf, (size_t)len);
  10151. len = 0;
  10152. in_tag = 0;
  10153. }
  10154. } else {
  10155. /* Tag is still open */
  10156. buf[len++] = (char)(ch & 0xff);
  10157. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10158. /* All SSI tags start with <!--# */
  10159. in_ssi_tag = 1;
  10160. }
  10161. if ((len + 2) > (int)sizeof(buf)) {
  10162. /* Tag to long for buffer */
  10163. mg_cry_internal(conn, "%s: tag is too large", path);
  10164. return;
  10165. }
  10166. }
  10167. } else {
  10168. /* We are not in a tag yet. */
  10169. if (ch == '<') {
  10170. /* Tag is opening */
  10171. in_tag = 1;
  10172. if (len > 0) {
  10173. /* Flush current buffer.
  10174. * Buffer is filled with "len" bytes. */
  10175. (void)mg_write(conn, buf, (size_t)len);
  10176. }
  10177. /* Store the < */
  10178. len = 1;
  10179. buf[0] = '<';
  10180. } else {
  10181. /* No Tag */
  10182. /* Add data to buffer */
  10183. buf[len++] = (char)(ch & 0xff);
  10184. /* Flush if buffer is full */
  10185. if (len == (int)sizeof(buf)) {
  10186. mg_write(conn, buf, (size_t)len);
  10187. len = 0;
  10188. }
  10189. }
  10190. }
  10191. }
  10192. /* Send the rest of buffered data */
  10193. if (len > 0) {
  10194. mg_write(conn, buf, (size_t)len);
  10195. }
  10196. }
  10197. static void
  10198. handle_ssi_file_request(struct mg_connection *conn,
  10199. const char *path,
  10200. struct mg_file *filep)
  10201. {
  10202. char date[64];
  10203. time_t curtime = time(NULL);
  10204. const char *cors_orig_cfg;
  10205. const char *cors1, *cors2, *cors3;
  10206. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10207. return;
  10208. }
  10209. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10210. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10211. /* Cross-origin resource sharing (CORS). */
  10212. cors1 = "Access-Control-Allow-Origin: ";
  10213. cors2 = cors_orig_cfg;
  10214. cors3 = "\r\n";
  10215. } else {
  10216. cors1 = cors2 = cors3 = "";
  10217. }
  10218. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10219. /* File exists (precondition for calling this function),
  10220. * but can not be opened by the server. */
  10221. mg_send_http_error(conn,
  10222. 500,
  10223. "Error: Cannot read file\nfopen(%s): %s",
  10224. path,
  10225. strerror(ERRNO));
  10226. } else {
  10227. conn->must_close = 1;
  10228. gmt_time_string(date, sizeof(date), &curtime);
  10229. fclose_on_exec(&filep->access, conn);
  10230. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10231. send_no_cache_header(conn);
  10232. send_additional_header(conn);
  10233. mg_printf(conn,
  10234. "%s%s%s"
  10235. "Date: %s\r\n"
  10236. "Content-Type: text/html\r\n"
  10237. "Connection: %s\r\n\r\n",
  10238. cors1,
  10239. cors2,
  10240. cors3,
  10241. date,
  10242. suggest_connection_header(conn));
  10243. send_ssi_file(conn, path, filep, 0);
  10244. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10245. }
  10246. }
  10247. #endif /* NO_FILESYSTEMS */
  10248. #if !defined(NO_FILES)
  10249. static void
  10250. send_options(struct mg_connection *conn)
  10251. {
  10252. char date[64];
  10253. time_t curtime = time(NULL);
  10254. if (!conn) {
  10255. return;
  10256. }
  10257. conn->status_code = 200;
  10258. conn->must_close = 1;
  10259. gmt_time_string(date, sizeof(date), &curtime);
  10260. /* We do not set a "Cache-Control" header here, but leave the default.
  10261. * Since browsers do not send an OPTIONS request, we can not test the
  10262. * effect anyway. */
  10263. mg_printf(conn,
  10264. "HTTP/1.1 200 OK\r\n"
  10265. "Date: %s\r\n"
  10266. "Connection: %s\r\n"
  10267. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10268. "PROPFIND, MKCOL\r\n"
  10269. "DAV: 1\r\n",
  10270. date,
  10271. suggest_connection_header(conn));
  10272. send_additional_header(conn);
  10273. mg_printf(conn, "\r\n");
  10274. }
  10275. /* Writes PROPFIND properties for a collection element */
  10276. static int
  10277. print_props(struct mg_connection *conn,
  10278. const char *uri,
  10279. const char *name,
  10280. struct mg_file_stat *filep)
  10281. {
  10282. size_t href_size, i, j;
  10283. int len;
  10284. char *href, mtime[64];
  10285. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10286. return 0;
  10287. }
  10288. /* Estimate worst case size for encoding */
  10289. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10290. href = (char *)mg_malloc(href_size);
  10291. if (href == NULL) {
  10292. return 0;
  10293. }
  10294. len = mg_url_encode(uri, href, href_size);
  10295. if (len >= 0) {
  10296. /* Append an extra string */
  10297. mg_url_encode(name, href + len, href_size - (size_t)len);
  10298. }
  10299. /* Directory separator should be preserved. */
  10300. for (i = j = 0; href[i]; j++) {
  10301. if (!strncmp(href + i, "%2f", 3)) {
  10302. href[j] = '/';
  10303. i += 3;
  10304. } else {
  10305. href[j] = href[i++];
  10306. }
  10307. }
  10308. href[j] = '\0';
  10309. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10310. mg_printf(conn,
  10311. "<d:response>"
  10312. "<d:href>%s</d:href>"
  10313. "<d:propstat>"
  10314. "<d:prop>"
  10315. "<d:resourcetype>%s</d:resourcetype>"
  10316. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10317. "<d:getlastmodified>%s</d:getlastmodified>"
  10318. "</d:prop>"
  10319. "<d:status>HTTP/1.1 200 OK</d:status>"
  10320. "</d:propstat>"
  10321. "</d:response>\n",
  10322. href,
  10323. filep->is_directory ? "<d:collection/>" : "",
  10324. filep->size,
  10325. mtime);
  10326. mg_free(href);
  10327. return 1;
  10328. }
  10329. static int
  10330. print_dav_dir_entry(struct de *de, void *data)
  10331. {
  10332. struct mg_connection *conn = (struct mg_connection *)data;
  10333. if (!de || !conn
  10334. || !print_props(
  10335. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10336. return -1;
  10337. }
  10338. return 0;
  10339. }
  10340. static void
  10341. handle_propfind(struct mg_connection *conn,
  10342. const char *path,
  10343. struct mg_file_stat *filep)
  10344. {
  10345. const char *depth = mg_get_header(conn, "Depth");
  10346. char date[64];
  10347. time_t curtime = time(NULL);
  10348. gmt_time_string(date, sizeof(date), &curtime);
  10349. if (!conn || !path || !filep || !conn->dom_ctx) {
  10350. return;
  10351. }
  10352. conn->must_close = 1;
  10353. conn->status_code = 207;
  10354. mg_printf(conn,
  10355. "HTTP/1.1 207 Multi-Status\r\n"
  10356. "Date: %s\r\n",
  10357. date);
  10358. send_static_cache_header(conn);
  10359. send_additional_header(conn);
  10360. mg_printf(conn,
  10361. "Connection: %s\r\n"
  10362. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10363. suggest_connection_header(conn));
  10364. mg_printf(conn,
  10365. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10366. "<d:multistatus xmlns:d='DAV:'>\n");
  10367. /* Print properties for the requested resource itself */
  10368. print_props(conn, conn->request_info.local_uri, "", filep);
  10369. /* If it is a directory, print directory entries too if Depth is not 0
  10370. */
  10371. if (filep->is_directory
  10372. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10373. "yes")
  10374. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10375. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10376. }
  10377. mg_printf(conn, "%s\n", "</d:multistatus>");
  10378. }
  10379. #endif
  10380. void
  10381. mg_lock_connection(struct mg_connection *conn)
  10382. {
  10383. if (conn) {
  10384. (void)pthread_mutex_lock(&conn->mutex);
  10385. }
  10386. }
  10387. void
  10388. mg_unlock_connection(struct mg_connection *conn)
  10389. {
  10390. if (conn) {
  10391. (void)pthread_mutex_unlock(&conn->mutex);
  10392. }
  10393. }
  10394. void
  10395. mg_lock_context(struct mg_context *ctx)
  10396. {
  10397. if (ctx) {
  10398. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10399. }
  10400. }
  10401. void
  10402. mg_unlock_context(struct mg_context *ctx)
  10403. {
  10404. if (ctx) {
  10405. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10406. }
  10407. }
  10408. #if defined(USE_LUA)
  10409. #include "mod_lua.inl"
  10410. #endif /* USE_LUA */
  10411. #if defined(USE_DUKTAPE)
  10412. #include "mod_duktape.inl"
  10413. #endif /* USE_DUKTAPE */
  10414. #if defined(USE_WEBSOCKET)
  10415. #if !defined(NO_SSL_DL)
  10416. #define SHA_API static
  10417. #include "sha1.inl"
  10418. #endif
  10419. static int
  10420. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10421. {
  10422. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10423. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10424. SHA_CTX sha_ctx;
  10425. int truncated;
  10426. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10427. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10428. if (truncated) {
  10429. conn->must_close = 1;
  10430. return 0;
  10431. }
  10432. DEBUG_TRACE("%s", "Send websocket handshake");
  10433. SHA1_Init(&sha_ctx);
  10434. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10435. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10436. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10437. mg_printf(conn,
  10438. "HTTP/1.1 101 Switching Protocols\r\n"
  10439. "Upgrade: websocket\r\n"
  10440. "Connection: Upgrade\r\n"
  10441. "Sec-WebSocket-Accept: %s\r\n",
  10442. b64_sha);
  10443. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10444. mg_printf(conn,
  10445. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10446. conn->request_info.acceptedWebSocketSubprotocol);
  10447. } else {
  10448. mg_printf(conn, "%s", "\r\n");
  10449. }
  10450. return 1;
  10451. }
  10452. #if !defined(MG_MAX_UNANSWERED_PING)
  10453. /* Configuration of the maximum number of websocket PINGs that might
  10454. * stay unanswered before the connection is considered broken.
  10455. * Note: The name of this define may still change (until it is
  10456. * defined as a compile parameter in a documentation).
  10457. */
  10458. #define MG_MAX_UNANSWERED_PING (5)
  10459. #endif
  10460. static void
  10461. read_websocket(struct mg_connection *conn,
  10462. mg_websocket_data_handler ws_data_handler,
  10463. void *callback_data)
  10464. {
  10465. /* Pointer to the beginning of the portion of the incoming websocket
  10466. * message queue.
  10467. * The original websocket upgrade request is never removed, so the queue
  10468. * begins after it. */
  10469. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10470. int n, error, exit_by_callback;
  10471. int ret;
  10472. /* body_len is the length of the entire queue in bytes
  10473. * len is the length of the current message
  10474. * data_len is the length of the current message's data payload
  10475. * header_len is the length of the current message's header */
  10476. size_t i, len, mask_len = 0, header_len, body_len;
  10477. uint64_t data_len = 0;
  10478. /* "The masking key is a 32-bit value chosen at random by the client."
  10479. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10480. */
  10481. unsigned char mask[4];
  10482. /* data points to the place where the message is stored when passed to
  10483. * the websocket_data callback. This is either mem on the stack, or a
  10484. * dynamically allocated buffer if it is too large. */
  10485. unsigned char mem[4096];
  10486. unsigned char mop; /* mask flag and opcode */
  10487. /* Variables used for connection monitoring */
  10488. double timeout = -1.0;
  10489. int enable_ping_pong = 0;
  10490. int ping_count = 0;
  10491. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10492. enable_ping_pong =
  10493. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10494. "yes");
  10495. }
  10496. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10497. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10498. }
  10499. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10500. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10501. }
  10502. /* Enter data processing loop */
  10503. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10504. conn->request_info.remote_addr,
  10505. conn->request_info.remote_port);
  10506. conn->in_websocket_handling = 1;
  10507. mg_set_thread_name("wsock");
  10508. /* Loop continuously, reading messages from the socket, invoking the
  10509. * callback, and waiting repeatedly until an error occurs. */
  10510. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10511. header_len = 0;
  10512. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10513. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10514. len = buf[1] & 127;
  10515. mask_len = (buf[1] & 128) ? 4 : 0;
  10516. if ((len < 126) && (body_len >= mask_len)) {
  10517. /* inline 7-bit length field */
  10518. data_len = len;
  10519. header_len = 2 + mask_len;
  10520. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10521. /* 16-bit length field */
  10522. header_len = 4 + mask_len;
  10523. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10524. } else if (body_len >= (10 + mask_len)) {
  10525. /* 64-bit length field */
  10526. uint32_t l1, l2;
  10527. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10528. memcpy(&l2, &buf[6], 4);
  10529. header_len = 10 + mask_len;
  10530. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10531. if (data_len > (uint64_t)0x7FFF0000ul) {
  10532. /* no can do */
  10533. mg_cry_internal(
  10534. conn,
  10535. "%s",
  10536. "websocket out of memory; closing connection");
  10537. break;
  10538. }
  10539. }
  10540. }
  10541. if ((header_len > 0) && (body_len >= header_len)) {
  10542. /* Allocate space to hold websocket payload */
  10543. unsigned char *data = mem;
  10544. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10545. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10546. conn->phys_ctx);
  10547. if (data == NULL) {
  10548. /* Allocation failed, exit the loop and then close the
  10549. * connection */
  10550. mg_cry_internal(
  10551. conn,
  10552. "%s",
  10553. "websocket out of memory; closing connection");
  10554. break;
  10555. }
  10556. }
  10557. /* Copy the mask before we shift the queue and destroy it */
  10558. if (mask_len > 0) {
  10559. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10560. } else {
  10561. memset(mask, 0, sizeof(mask));
  10562. }
  10563. /* Read frame payload from the first message in the queue into
  10564. * data and advance the queue by moving the memory in place. */
  10565. DEBUG_ASSERT(body_len >= header_len);
  10566. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10567. mop = buf[0]; /* current mask and opcode */
  10568. /* Overflow case */
  10569. len = body_len - header_len;
  10570. memcpy(data, buf + header_len, len);
  10571. error = 0;
  10572. while ((uint64_t)len < data_len) {
  10573. n = pull_inner(NULL,
  10574. conn,
  10575. (char *)(data + len),
  10576. (int)(data_len - len),
  10577. timeout);
  10578. if (n <= -2) {
  10579. error = 1;
  10580. break;
  10581. } else if (n > 0) {
  10582. len += (size_t)n;
  10583. } else {
  10584. /* Timeout: should retry */
  10585. /* TODO: retry condition */
  10586. }
  10587. }
  10588. if (error) {
  10589. mg_cry_internal(
  10590. conn,
  10591. "%s",
  10592. "Websocket pull failed; closing connection");
  10593. if (data != mem) {
  10594. mg_free(data);
  10595. }
  10596. break;
  10597. }
  10598. conn->data_len = conn->request_len;
  10599. } else {
  10600. mop = buf[0]; /* current mask and opcode, overwritten by
  10601. * memmove() */
  10602. /* Length of the message being read at the front of the
  10603. * queue. Cast to 31 bit is OK, since we limited
  10604. * data_len before. */
  10605. len = (size_t)data_len + header_len;
  10606. /* Copy the data payload into the data pointer for the
  10607. * callback. Cast to 31 bit is OK, since we
  10608. * limited data_len */
  10609. memcpy(data, buf + header_len, (size_t)data_len);
  10610. /* Move the queue forward len bytes */
  10611. memmove(buf, buf + len, body_len - len);
  10612. /* Mark the queue as advanced */
  10613. conn->data_len -= (int)len;
  10614. }
  10615. /* Apply mask if necessary */
  10616. if (mask_len > 0) {
  10617. for (i = 0; i < (size_t)data_len; i++) {
  10618. data[i] ^= mask[i & 3];
  10619. }
  10620. }
  10621. exit_by_callback = 0;
  10622. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10623. /* filter PONG messages */
  10624. DEBUG_TRACE("PONG from %s:%u",
  10625. conn->request_info.remote_addr,
  10626. conn->request_info.remote_port);
  10627. /* No unanwered PINGs left */
  10628. ping_count = 0;
  10629. } else if (enable_ping_pong
  10630. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10631. /* reply PING messages */
  10632. DEBUG_TRACE("Reply PING from %s:%u",
  10633. conn->request_info.remote_addr,
  10634. conn->request_info.remote_port);
  10635. ret = mg_websocket_write(conn,
  10636. MG_WEBSOCKET_OPCODE_PONG,
  10637. (char *)data,
  10638. (size_t)data_len);
  10639. if (ret <= 0) {
  10640. /* Error: send failed */
  10641. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10642. break;
  10643. }
  10644. } else {
  10645. /* Exit the loop if callback signals to exit (server side),
  10646. * or "connection close" opcode received (client side). */
  10647. if ((ws_data_handler != NULL)
  10648. && !ws_data_handler(conn,
  10649. mop,
  10650. (char *)data,
  10651. (size_t)data_len,
  10652. callback_data)) {
  10653. exit_by_callback = 1;
  10654. }
  10655. }
  10656. /* It a buffer has been allocated, free it again */
  10657. if (data != mem) {
  10658. mg_free(data);
  10659. }
  10660. if (exit_by_callback) {
  10661. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10662. conn->request_info.remote_addr,
  10663. conn->request_info.remote_port);
  10664. break;
  10665. }
  10666. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10667. /* Opcode == 8, connection close */
  10668. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10669. conn->request_info.remote_addr,
  10670. conn->request_info.remote_port);
  10671. break;
  10672. }
  10673. /* Not breaking the loop, process next websocket frame. */
  10674. } else {
  10675. /* Read from the socket into the next available location in the
  10676. * message queue. */
  10677. n = pull_inner(NULL,
  10678. conn,
  10679. conn->buf + conn->data_len,
  10680. conn->buf_size - conn->data_len,
  10681. timeout);
  10682. if (n <= -2) {
  10683. /* Error, no bytes read */
  10684. DEBUG_TRACE("PULL from %s:%u failed",
  10685. conn->request_info.remote_addr,
  10686. conn->request_info.remote_port);
  10687. break;
  10688. }
  10689. if (n > 0) {
  10690. conn->data_len += n;
  10691. /* Reset open PING count */
  10692. ping_count = 0;
  10693. } else {
  10694. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10695. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10696. /* Stop sending PING */
  10697. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10698. "- closing connection",
  10699. ping_count,
  10700. conn->request_info.remote_addr,
  10701. conn->request_info.remote_port);
  10702. break;
  10703. }
  10704. if (enable_ping_pong) {
  10705. /* Send Websocket PING message */
  10706. DEBUG_TRACE("PING to %s:%u",
  10707. conn->request_info.remote_addr,
  10708. conn->request_info.remote_port);
  10709. ret = mg_websocket_write(conn,
  10710. MG_WEBSOCKET_OPCODE_PING,
  10711. NULL,
  10712. 0);
  10713. if (ret <= 0) {
  10714. /* Error: send failed */
  10715. DEBUG_TRACE("Send PING failed (%i)", ret);
  10716. break;
  10717. }
  10718. ping_count++;
  10719. }
  10720. }
  10721. /* Timeout: should retry */
  10722. /* TODO: get timeout def */
  10723. }
  10724. }
  10725. }
  10726. /* Leave data processing loop */
  10727. mg_set_thread_name("worker");
  10728. conn->in_websocket_handling = 0;
  10729. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10730. conn->request_info.remote_addr,
  10731. conn->request_info.remote_port);
  10732. }
  10733. static int
  10734. mg_websocket_write_exec(struct mg_connection *conn,
  10735. int opcode,
  10736. const char *data,
  10737. size_t dataLen,
  10738. uint32_t masking_key)
  10739. {
  10740. unsigned char header[14];
  10741. size_t headerLen;
  10742. int retval;
  10743. #if defined(GCC_DIAGNOSTIC)
  10744. /* Disable spurious conversion warning for GCC */
  10745. #pragma GCC diagnostic push
  10746. #pragma GCC diagnostic ignored "-Wconversion"
  10747. #endif
  10748. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10749. #if defined(GCC_DIAGNOSTIC)
  10750. #pragma GCC diagnostic pop
  10751. #endif
  10752. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10753. if (dataLen < 126) {
  10754. /* inline 7-bit length field */
  10755. header[1] = (unsigned char)dataLen;
  10756. headerLen = 2;
  10757. } else if (dataLen <= 0xFFFF) {
  10758. /* 16-bit length field */
  10759. uint16_t len = htons((uint16_t)dataLen);
  10760. header[1] = 126;
  10761. memcpy(header + 2, &len, 2);
  10762. headerLen = 4;
  10763. } else {
  10764. /* 64-bit length field */
  10765. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10766. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10767. header[1] = 127;
  10768. memcpy(header + 2, &len1, 4);
  10769. memcpy(header + 6, &len2, 4);
  10770. headerLen = 10;
  10771. }
  10772. if (masking_key) {
  10773. /* add mask */
  10774. header[1] |= 0x80;
  10775. memcpy(header + headerLen, &masking_key, 4);
  10776. headerLen += 4;
  10777. }
  10778. /* Note that POSIX/Winsock's send() is threadsafe
  10779. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10780. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10781. * push(), although that is only a problem if the packet is large or
  10782. * outgoing buffer is full). */
  10783. /* TODO: Check if this lock should be moved to user land.
  10784. * Currently the server sets this lock for websockets, but
  10785. * not for any other connection. It must be set for every
  10786. * conn read/written by more than one thread, no matter if
  10787. * it is a websocket or regular connection. */
  10788. (void)mg_lock_connection(conn);
  10789. retval = mg_write(conn, header, headerLen);
  10790. if (retval != (int)headerLen) {
  10791. /* Did not send complete header */
  10792. retval = -1;
  10793. } else {
  10794. if (dataLen > 0) {
  10795. retval = mg_write(conn, data, dataLen);
  10796. }
  10797. /* if dataLen == 0, the header length (2) is returned */
  10798. }
  10799. /* TODO: Remove this unlock as well, when lock is removed. */
  10800. mg_unlock_connection(conn);
  10801. return retval;
  10802. }
  10803. int
  10804. mg_websocket_write(struct mg_connection *conn,
  10805. int opcode,
  10806. const char *data,
  10807. size_t dataLen)
  10808. {
  10809. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10810. }
  10811. static void
  10812. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10813. {
  10814. size_t i = 0;
  10815. i = 0;
  10816. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10817. /* Convert in 32 bit words, if data is 4 byte aligned */
  10818. while (i < (in_len - 3)) {
  10819. *(uint32_t *)(void *)(out + i) =
  10820. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10821. i += 4;
  10822. }
  10823. }
  10824. if (i != in_len) {
  10825. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10826. while (i < in_len) {
  10827. *(uint8_t *)(void *)(out + i) =
  10828. *(uint8_t *)(void *)(in + i)
  10829. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10830. i++;
  10831. }
  10832. }
  10833. }
  10834. int
  10835. mg_websocket_client_write(struct mg_connection *conn,
  10836. int opcode,
  10837. const char *data,
  10838. size_t dataLen)
  10839. {
  10840. int retval = -1;
  10841. char *masked_data =
  10842. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10843. uint32_t masking_key = 0;
  10844. if (masked_data == NULL) {
  10845. /* Return -1 in an error case */
  10846. mg_cry_internal(conn,
  10847. "%s",
  10848. "Cannot allocate buffer for masked websocket response: "
  10849. "Out of memory");
  10850. return -1;
  10851. }
  10852. do {
  10853. /* Get a masking key - but not 0 */
  10854. masking_key = (uint32_t)get_random();
  10855. } while (masking_key == 0);
  10856. mask_data(data, dataLen, masking_key, masked_data);
  10857. retval = mg_websocket_write_exec(
  10858. conn, opcode, masked_data, dataLen, masking_key);
  10859. mg_free(masked_data);
  10860. return retval;
  10861. }
  10862. static void
  10863. handle_websocket_request(struct mg_connection *conn,
  10864. const char *path,
  10865. int is_callback_resource,
  10866. struct mg_websocket_subprotocols *subprotocols,
  10867. mg_websocket_connect_handler ws_connect_handler,
  10868. mg_websocket_ready_handler ws_ready_handler,
  10869. mg_websocket_data_handler ws_data_handler,
  10870. mg_websocket_close_handler ws_close_handler,
  10871. void *cbData)
  10872. {
  10873. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10874. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10875. ptrdiff_t lua_websock = 0;
  10876. #if !defined(USE_LUA)
  10877. (void)path;
  10878. #endif
  10879. /* Step 1: Check websocket protocol version. */
  10880. /* Step 1.1: Check Sec-WebSocket-Key. */
  10881. if (!websock_key) {
  10882. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10883. * requires a Sec-WebSocket-Key header.
  10884. */
  10885. /* It could be the hixie draft version
  10886. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10887. */
  10888. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10889. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10890. char key3[8];
  10891. if ((key1 != NULL) && (key2 != NULL)) {
  10892. /* This version uses 8 byte body data in a GET request */
  10893. conn->content_len = 8;
  10894. if (8 == mg_read(conn, key3, 8)) {
  10895. /* This is the hixie version */
  10896. mg_send_http_error(conn,
  10897. 426,
  10898. "%s",
  10899. "Protocol upgrade to RFC 6455 required");
  10900. return;
  10901. }
  10902. }
  10903. /* This is an unknown version */
  10904. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10905. return;
  10906. }
  10907. /* Step 1.2: Check websocket protocol version. */
  10908. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10909. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10910. /* Reject wrong versions */
  10911. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10912. return;
  10913. }
  10914. /* Step 1.3: Could check for "Host", but we do not really nead this
  10915. * value for anything, so just ignore it. */
  10916. /* Step 2: If a callback is responsible, call it. */
  10917. if (is_callback_resource) {
  10918. /* Step 2.1 check and select subprotocol */
  10919. const char *protocols[64]; // max 64 headers
  10920. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10921. "Sec-WebSocket-Protocol",
  10922. protocols,
  10923. 64);
  10924. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10925. int cnt = 0;
  10926. int idx;
  10927. unsigned long len;
  10928. const char *sep, *curSubProtocol,
  10929. *acceptedWebSocketSubprotocol = NULL;
  10930. /* look for matching subprotocol */
  10931. do {
  10932. const char *protocol = protocols[cnt];
  10933. do {
  10934. sep = strchr(protocol, ',');
  10935. curSubProtocol = protocol;
  10936. len = sep ? (unsigned long)(sep - protocol)
  10937. : (unsigned long)strlen(protocol);
  10938. while (sep && isspace((unsigned char)*++sep))
  10939. ; // ignore leading whitespaces
  10940. protocol = sep;
  10941. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10942. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10943. && (strncmp(curSubProtocol,
  10944. subprotocols->subprotocols[idx],
  10945. len)
  10946. == 0)) {
  10947. acceptedWebSocketSubprotocol =
  10948. subprotocols->subprotocols[idx];
  10949. break;
  10950. }
  10951. }
  10952. } while (sep && !acceptedWebSocketSubprotocol);
  10953. } while (++cnt < nbSubprotocolHeader
  10954. && !acceptedWebSocketSubprotocol);
  10955. conn->request_info.acceptedWebSocketSubprotocol =
  10956. acceptedWebSocketSubprotocol;
  10957. } else if (nbSubprotocolHeader > 0) {
  10958. /* keep legacy behavior */
  10959. const char *protocol = protocols[0];
  10960. /* The protocol is a comma separated list of names. */
  10961. /* The server must only return one value from this list. */
  10962. /* First check if it is a list or just a single value. */
  10963. const char *sep = strrchr(protocol, ',');
  10964. if (sep == NULL) {
  10965. /* Just a single protocol -> accept it. */
  10966. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10967. } else {
  10968. /* Multiple protocols -> accept the last one. */
  10969. /* This is just a quick fix if the client offers multiple
  10970. * protocols. The handler should have a list of accepted
  10971. * protocols on his own
  10972. * and use it to select one protocol among those the client
  10973. * has
  10974. * offered.
  10975. */
  10976. while (isspace((unsigned char)*++sep)) {
  10977. ; /* ignore leading whitespaces */
  10978. }
  10979. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10980. }
  10981. }
  10982. if ((ws_connect_handler != NULL)
  10983. && (ws_connect_handler(conn, cbData) != 0)) {
  10984. /* C callback has returned non-zero, do not proceed with
  10985. * handshake.
  10986. */
  10987. /* Note that C callbacks are no longer called when Lua is
  10988. * responsible, so C can no longer filter callbacks for Lua. */
  10989. return;
  10990. }
  10991. }
  10992. #if defined(USE_LUA)
  10993. /* Step 3: No callback. Check if Lua is responsible. */
  10994. else {
  10995. /* Step 3.1: Check if Lua is responsible. */
  10996. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10997. lua_websock = match_prefix(
  10998. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10999. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  11000. path);
  11001. }
  11002. if (lua_websock) {
  11003. /* Step 3.2: Lua is responsible: call it. */
  11004. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11005. if (!conn->lua_websocket_state) {
  11006. /* Lua rejected the new client */
  11007. return;
  11008. }
  11009. }
  11010. }
  11011. #endif
  11012. /* Step 4: Check if there is a responsible websocket handler. */
  11013. if (!is_callback_resource && !lua_websock) {
  11014. /* There is no callback, and Lua is not responsible either. */
  11015. /* Reply with a 404 Not Found. We are still at a standard
  11016. * HTTP request here, before the websocket handshake, so
  11017. * we can still send standard HTTP error replies. */
  11018. mg_send_http_error(conn, 404, "%s", "Not found");
  11019. return;
  11020. }
  11021. /* Step 5: The websocket connection has been accepted */
  11022. if (!send_websocket_handshake(conn, websock_key)) {
  11023. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11024. return;
  11025. }
  11026. /* Step 6: Call the ready handler */
  11027. if (is_callback_resource) {
  11028. if (ws_ready_handler != NULL) {
  11029. ws_ready_handler(conn, cbData);
  11030. }
  11031. #if defined(USE_LUA)
  11032. } else if (lua_websock) {
  11033. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11034. /* the ready handler returned false */
  11035. return;
  11036. }
  11037. #endif
  11038. }
  11039. /* Step 7: Enter the read loop */
  11040. if (is_callback_resource) {
  11041. read_websocket(conn, ws_data_handler, cbData);
  11042. #if defined(USE_LUA)
  11043. } else if (lua_websock) {
  11044. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11045. #endif
  11046. }
  11047. /* Step 8: Call the close handler */
  11048. if (ws_close_handler) {
  11049. ws_close_handler(conn, cbData);
  11050. }
  11051. }
  11052. static int
  11053. is_websocket_protocol(const struct mg_connection *conn)
  11054. {
  11055. const char *upgrade, *connection;
  11056. /* A websocket protocoll has the following HTTP headers:
  11057. *
  11058. * Connection: Upgrade
  11059. * Upgrade: Websocket
  11060. */
  11061. upgrade = mg_get_header(conn, "Upgrade");
  11062. if (upgrade == NULL) {
  11063. return 0; /* fail early, don't waste time checking other header
  11064. * fields
  11065. */
  11066. }
  11067. DEBUG_TRACE("Upgrade: %s", upgrade);
  11068. if (!mg_strcasestr(upgrade, "websocket")) {
  11069. return 0;
  11070. }
  11071. connection = mg_get_header(conn, "Connection");
  11072. if (connection == NULL) {
  11073. return 0;
  11074. }
  11075. if (!mg_strcasestr(connection, "upgrade")) {
  11076. return 0;
  11077. }
  11078. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11079. * "Sec-WebSocket-Version" are also required.
  11080. * Don't check them here, since even an unsupported websocket protocol
  11081. * request still IS a websocket request (in contrast to a standard HTTP
  11082. * request). It will fail later in handle_websocket_request.
  11083. */
  11084. return 1;
  11085. }
  11086. #endif /* !USE_WEBSOCKET */
  11087. static int
  11088. isbyte(int n)
  11089. {
  11090. return (n >= 0) && (n <= 255);
  11091. }
  11092. static int
  11093. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11094. {
  11095. int n, a, b, c, d, slash = 32, len = 0;
  11096. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11097. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11098. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11099. && (slash < 33)) {
  11100. len = n;
  11101. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11102. | (uint32_t)d;
  11103. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11104. }
  11105. return len;
  11106. }
  11107. static int
  11108. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11109. {
  11110. int throttle = 0;
  11111. struct vec vec, val;
  11112. uint32_t net, mask;
  11113. char mult;
  11114. double v;
  11115. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11116. mult = ',';
  11117. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11118. || (v < 0)
  11119. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11120. && (mult != ','))) {
  11121. continue;
  11122. }
  11123. v *= (lowercase(&mult) == 'k')
  11124. ? 1024
  11125. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11126. if (vec.len == 1 && vec.ptr[0] == '*') {
  11127. throttle = (int)v;
  11128. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11129. if ((remote_ip & mask) == net) {
  11130. throttle = (int)v;
  11131. }
  11132. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11133. throttle = (int)v;
  11134. }
  11135. }
  11136. return throttle;
  11137. }
  11138. static uint32_t
  11139. get_remote_ip(const struct mg_connection *conn)
  11140. {
  11141. if (!conn) {
  11142. return 0;
  11143. }
  11144. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11145. }
  11146. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11147. #include "handle_form.inl"
  11148. #if defined(MG_LEGACY_INTERFACE)
  11149. /* Implement the deprecated mg_upload function by calling the new
  11150. * mg_handle_form_request function. While mg_upload could only handle
  11151. * HTML forms sent as POST request in multipart/form-data format
  11152. * containing only file input elements, mg_handle_form_request can
  11153. * handle all form input elements and all standard request methods. */
  11154. struct mg_upload_user_data {
  11155. struct mg_connection *conn;
  11156. const char *destination_dir;
  11157. int num_uploaded_files;
  11158. };
  11159. /* Helper function for deprecated mg_upload. */
  11160. static int
  11161. mg_upload_field_found(const char *key,
  11162. const char *filename,
  11163. char *path,
  11164. size_t pathlen,
  11165. void *user_data)
  11166. {
  11167. int truncated = 0;
  11168. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11169. (void)key;
  11170. if (!filename) {
  11171. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11172. return FORM_FIELD_STORAGE_ABORT;
  11173. }
  11174. mg_snprintf(fud->conn,
  11175. &truncated,
  11176. path,
  11177. pathlen - 1,
  11178. "%s/%s",
  11179. fud->destination_dir,
  11180. filename);
  11181. if (truncated) {
  11182. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11183. return FORM_FIELD_STORAGE_ABORT;
  11184. }
  11185. return FORM_FIELD_STORAGE_STORE;
  11186. }
  11187. /* Helper function for deprecated mg_upload. */
  11188. static int
  11189. mg_upload_field_get(const char *key,
  11190. const char *value,
  11191. size_t value_size,
  11192. void *user_data)
  11193. {
  11194. /* Function should never be called */
  11195. (void)key;
  11196. (void)value;
  11197. (void)value_size;
  11198. (void)user_data;
  11199. return 0;
  11200. }
  11201. /* Helper function for deprecated mg_upload. */
  11202. static int
  11203. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11204. {
  11205. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11206. (void)file_size;
  11207. fud->num_uploaded_files++;
  11208. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11209. return 0;
  11210. }
  11211. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11212. int
  11213. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11214. {
  11215. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11216. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11217. mg_upload_field_get,
  11218. mg_upload_field_stored,
  11219. 0};
  11220. int ret;
  11221. fdh.user_data = (void *)&fud;
  11222. ret = mg_handle_form_request(conn, &fdh);
  11223. if (ret < 0) {
  11224. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11225. }
  11226. return fud.num_uploaded_files;
  11227. }
  11228. #endif
  11229. static int
  11230. get_first_ssl_listener_index(const struct mg_context *ctx)
  11231. {
  11232. unsigned int i;
  11233. int idx = -1;
  11234. if (ctx) {
  11235. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11236. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11237. }
  11238. }
  11239. return idx;
  11240. }
  11241. /* Return host (without port) */
  11242. /* Use mg_free to free the result */
  11243. static const char *
  11244. alloc_get_host(struct mg_connection *conn)
  11245. {
  11246. char buf[1025];
  11247. size_t buflen = sizeof(buf);
  11248. const char *host_header = get_header(conn->request_info.http_headers,
  11249. conn->request_info.num_headers,
  11250. "Host");
  11251. char *host;
  11252. if (host_header != NULL) {
  11253. char *pos;
  11254. /* Create a local copy of the "Host" header, since it might be
  11255. * modified here. */
  11256. mg_strlcpy(buf, host_header, buflen);
  11257. buf[buflen - 1] = '\0';
  11258. host = buf;
  11259. while (isspace((unsigned char)*host)) {
  11260. host++;
  11261. }
  11262. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11263. * is found. */
  11264. if (*host == '[') {
  11265. pos = strchr(host, ']');
  11266. if (!pos) {
  11267. /* Malformed hostname starts with '[', but no ']' found */
  11268. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11269. return NULL;
  11270. }
  11271. /* terminate after ']' */
  11272. pos[1] = 0;
  11273. } else {
  11274. /* Otherwise, a ':' separates hostname and port number */
  11275. pos = strchr(host, ':');
  11276. if (pos != NULL) {
  11277. *pos = '\0';
  11278. }
  11279. }
  11280. if (conn->ssl) {
  11281. /* This is a HTTPS connection, maybe we have a hostname
  11282. * from SNI (set in ssl_servername_callback). */
  11283. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11284. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11285. /* We are not using the default domain */
  11286. if (mg_strcasecmp(host, sslhost)) {
  11287. /* Mismatch between SNI domain and HTTP domain */
  11288. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11289. sslhost,
  11290. host);
  11291. return NULL;
  11292. }
  11293. }
  11294. DEBUG_TRACE("HTTPS Host: %s", host);
  11295. } else {
  11296. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11297. while (dom) {
  11298. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11299. /* Found matching domain */
  11300. DEBUG_TRACE("HTTP domain %s found",
  11301. dom->config[AUTHENTICATION_DOMAIN]);
  11302. /* TODO: Check if this is a HTTP or HTTPS domain */
  11303. conn->dom_ctx = dom;
  11304. break;
  11305. }
  11306. dom = dom->next;
  11307. }
  11308. DEBUG_TRACE("HTTP Host: %s", host);
  11309. }
  11310. } else {
  11311. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11312. host = buf;
  11313. DEBUG_TRACE("IP: %s", host);
  11314. }
  11315. return mg_strdup_ctx(host, conn->phys_ctx);
  11316. }
  11317. static void
  11318. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11319. {
  11320. char target_url[MG_BUF_LEN];
  11321. int truncated = 0;
  11322. conn->must_close = 1;
  11323. /* Send host, port, uri and (if it exists) ?query_string */
  11324. if (conn->host) {
  11325. /* Use "308 Permanent Redirect" */
  11326. int redirect_code = 308;
  11327. /* Create target URL */
  11328. mg_snprintf(
  11329. conn,
  11330. &truncated,
  11331. target_url,
  11332. sizeof(target_url),
  11333. "https://%s:%d%s%s%s",
  11334. conn->host,
  11335. #if defined(USE_IPV6)
  11336. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11337. == AF_INET6)
  11338. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11339. .lsa.sin6.sin6_port)
  11340. :
  11341. #endif
  11342. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11343. .lsa.sin.sin_port),
  11344. conn->request_info.local_uri,
  11345. (conn->request_info.query_string == NULL) ? "" : "?",
  11346. (conn->request_info.query_string == NULL)
  11347. ? ""
  11348. : conn->request_info.query_string);
  11349. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11350. * is used as buffer size) */
  11351. if (truncated) {
  11352. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11353. return;
  11354. }
  11355. /* Use redirect helper function */
  11356. mg_send_http_redirect(conn, target_url, redirect_code);
  11357. }
  11358. }
  11359. static void
  11360. handler_info_acquire(struct mg_handler_info *handler_info)
  11361. {
  11362. pthread_mutex_lock(&handler_info->refcount_mutex);
  11363. handler_info->refcount++;
  11364. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11365. }
  11366. static void
  11367. handler_info_release(struct mg_handler_info *handler_info)
  11368. {
  11369. pthread_mutex_lock(&handler_info->refcount_mutex);
  11370. handler_info->refcount--;
  11371. pthread_cond_signal(&handler_info->refcount_cond);
  11372. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11373. }
  11374. static void
  11375. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11376. {
  11377. pthread_mutex_lock(&handler_info->refcount_mutex);
  11378. while (handler_info->refcount) {
  11379. pthread_cond_wait(&handler_info->refcount_cond,
  11380. &handler_info->refcount_mutex);
  11381. }
  11382. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11383. }
  11384. static void
  11385. mg_set_handler_type(struct mg_context *phys_ctx,
  11386. struct mg_domain_context *dom_ctx,
  11387. const char *uri,
  11388. int handler_type,
  11389. int is_delete_request,
  11390. mg_request_handler handler,
  11391. struct mg_websocket_subprotocols *subprotocols,
  11392. mg_websocket_connect_handler connect_handler,
  11393. mg_websocket_ready_handler ready_handler,
  11394. mg_websocket_data_handler data_handler,
  11395. mg_websocket_close_handler close_handler,
  11396. mg_authorization_handler auth_handler,
  11397. void *cbdata)
  11398. {
  11399. struct mg_handler_info *tmp_rh, **lastref;
  11400. size_t urilen = strlen(uri);
  11401. if (handler_type == WEBSOCKET_HANDLER) {
  11402. DEBUG_ASSERT(handler == NULL);
  11403. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11404. || ready_handler != NULL || data_handler != NULL
  11405. || close_handler != NULL);
  11406. DEBUG_ASSERT(auth_handler == NULL);
  11407. if (handler != NULL) {
  11408. return;
  11409. }
  11410. if (!is_delete_request && (connect_handler == NULL)
  11411. && (ready_handler == NULL) && (data_handler == NULL)
  11412. && (close_handler == NULL)) {
  11413. return;
  11414. }
  11415. if (auth_handler != NULL) {
  11416. return;
  11417. }
  11418. } else if (handler_type == REQUEST_HANDLER) {
  11419. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11420. && data_handler == NULL && close_handler == NULL);
  11421. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11422. DEBUG_ASSERT(auth_handler == NULL);
  11423. if ((connect_handler != NULL) || (ready_handler != NULL)
  11424. || (data_handler != NULL) || (close_handler != NULL)) {
  11425. return;
  11426. }
  11427. if (!is_delete_request && (handler == NULL)) {
  11428. return;
  11429. }
  11430. if (auth_handler != NULL) {
  11431. return;
  11432. }
  11433. } else { /* AUTH_HANDLER */
  11434. DEBUG_ASSERT(handler == NULL);
  11435. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11436. && data_handler == NULL && close_handler == NULL);
  11437. DEBUG_ASSERT(auth_handler != NULL);
  11438. if (handler != NULL) {
  11439. return;
  11440. }
  11441. if ((connect_handler != NULL) || (ready_handler != NULL)
  11442. || (data_handler != NULL) || (close_handler != NULL)) {
  11443. return;
  11444. }
  11445. if (!is_delete_request && (auth_handler == NULL)) {
  11446. return;
  11447. }
  11448. }
  11449. if (!phys_ctx || !dom_ctx) {
  11450. return;
  11451. }
  11452. mg_lock_context(phys_ctx);
  11453. /* first try to find an existing handler */
  11454. lastref = &(dom_ctx->handlers);
  11455. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11456. if (tmp_rh->handler_type == handler_type) {
  11457. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11458. if (!is_delete_request) {
  11459. /* update existing handler */
  11460. if (handler_type == REQUEST_HANDLER) {
  11461. /* Wait for end of use before updating */
  11462. handler_info_wait_unused(tmp_rh);
  11463. /* Ok, the handler is no more use -> Update it */
  11464. tmp_rh->handler = handler;
  11465. } else if (handler_type == WEBSOCKET_HANDLER) {
  11466. tmp_rh->subprotocols = subprotocols;
  11467. tmp_rh->connect_handler = connect_handler;
  11468. tmp_rh->ready_handler = ready_handler;
  11469. tmp_rh->data_handler = data_handler;
  11470. tmp_rh->close_handler = close_handler;
  11471. } else { /* AUTH_HANDLER */
  11472. tmp_rh->auth_handler = auth_handler;
  11473. }
  11474. tmp_rh->cbdata = cbdata;
  11475. } else {
  11476. /* remove existing handler */
  11477. if (handler_type == REQUEST_HANDLER) {
  11478. /* Wait for end of use before removing */
  11479. handler_info_wait_unused(tmp_rh);
  11480. /* Ok, the handler is no more used -> Destroy resources
  11481. */
  11482. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11483. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11484. }
  11485. *lastref = tmp_rh->next;
  11486. mg_free(tmp_rh->uri);
  11487. mg_free(tmp_rh);
  11488. }
  11489. mg_unlock_context(phys_ctx);
  11490. return;
  11491. }
  11492. }
  11493. lastref = &(tmp_rh->next);
  11494. }
  11495. if (is_delete_request) {
  11496. /* no handler to set, this was a remove request to a non-existing
  11497. * handler */
  11498. mg_unlock_context(phys_ctx);
  11499. return;
  11500. }
  11501. tmp_rh =
  11502. (struct mg_handler_info *)mg_calloc_ctx(1, sizeof(struct mg_handler_info),
  11503. phys_ctx);
  11504. if (tmp_rh == NULL) {
  11505. mg_unlock_context(phys_ctx);
  11506. mg_cry_ctx_internal(phys_ctx,
  11507. "%s",
  11508. "Cannot create new request handler struct, OOM");
  11509. return;
  11510. }
  11511. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11512. if (!tmp_rh->uri) {
  11513. mg_unlock_context(phys_ctx);
  11514. mg_free(tmp_rh);
  11515. mg_cry_ctx_internal(phys_ctx,
  11516. "%s",
  11517. "Cannot create new request handler struct, OOM");
  11518. return;
  11519. }
  11520. tmp_rh->uri_len = urilen;
  11521. if (handler_type == REQUEST_HANDLER) {
  11522. /* Init refcount mutex and condition */
  11523. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11524. mg_unlock_context(phys_ctx);
  11525. mg_free(tmp_rh);
  11526. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount mutex");
  11527. return;
  11528. }
  11529. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11530. mg_unlock_context(phys_ctx);
  11531. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11532. mg_free(tmp_rh);
  11533. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount cond");
  11534. return;
  11535. }
  11536. tmp_rh->refcount = 0;
  11537. tmp_rh->handler = handler;
  11538. } else if (handler_type == WEBSOCKET_HANDLER) {
  11539. tmp_rh->subprotocols = subprotocols;
  11540. tmp_rh->connect_handler = connect_handler;
  11541. tmp_rh->ready_handler = ready_handler;
  11542. tmp_rh->data_handler = data_handler;
  11543. tmp_rh->close_handler = close_handler;
  11544. } else { /* AUTH_HANDLER */
  11545. tmp_rh->auth_handler = auth_handler;
  11546. }
  11547. tmp_rh->cbdata = cbdata;
  11548. tmp_rh->handler_type = handler_type;
  11549. tmp_rh->next = NULL;
  11550. *lastref = tmp_rh;
  11551. mg_unlock_context(phys_ctx);
  11552. }
  11553. void
  11554. mg_set_request_handler(struct mg_context *ctx,
  11555. const char *uri,
  11556. mg_request_handler handler,
  11557. void *cbdata)
  11558. {
  11559. mg_set_handler_type(ctx,
  11560. &(ctx->dd),
  11561. uri,
  11562. REQUEST_HANDLER,
  11563. handler == NULL,
  11564. handler,
  11565. NULL,
  11566. NULL,
  11567. NULL,
  11568. NULL,
  11569. NULL,
  11570. NULL,
  11571. cbdata);
  11572. }
  11573. void
  11574. mg_set_websocket_handler(struct mg_context *ctx,
  11575. const char *uri,
  11576. mg_websocket_connect_handler connect_handler,
  11577. mg_websocket_ready_handler ready_handler,
  11578. mg_websocket_data_handler data_handler,
  11579. mg_websocket_close_handler close_handler,
  11580. void *cbdata)
  11581. {
  11582. mg_set_websocket_handler_with_subprotocols(ctx,
  11583. uri,
  11584. NULL,
  11585. connect_handler,
  11586. ready_handler,
  11587. data_handler,
  11588. close_handler,
  11589. cbdata);
  11590. }
  11591. void
  11592. mg_set_websocket_handler_with_subprotocols(
  11593. struct mg_context *ctx,
  11594. const char *uri,
  11595. struct mg_websocket_subprotocols *subprotocols,
  11596. mg_websocket_connect_handler connect_handler,
  11597. mg_websocket_ready_handler ready_handler,
  11598. mg_websocket_data_handler data_handler,
  11599. mg_websocket_close_handler close_handler,
  11600. void *cbdata)
  11601. {
  11602. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11603. && (data_handler == NULL)
  11604. && (close_handler == NULL);
  11605. mg_set_handler_type(ctx,
  11606. &(ctx->dd),
  11607. uri,
  11608. WEBSOCKET_HANDLER,
  11609. is_delete_request,
  11610. NULL,
  11611. subprotocols,
  11612. connect_handler,
  11613. ready_handler,
  11614. data_handler,
  11615. close_handler,
  11616. NULL,
  11617. cbdata);
  11618. }
  11619. void
  11620. mg_set_auth_handler(struct mg_context *ctx,
  11621. const char *uri,
  11622. mg_authorization_handler handler,
  11623. void *cbdata)
  11624. {
  11625. mg_set_handler_type(ctx,
  11626. &(ctx->dd),
  11627. uri,
  11628. AUTH_HANDLER,
  11629. handler == NULL,
  11630. NULL,
  11631. NULL,
  11632. NULL,
  11633. NULL,
  11634. NULL,
  11635. NULL,
  11636. handler,
  11637. cbdata);
  11638. }
  11639. static int
  11640. get_request_handler(struct mg_connection *conn,
  11641. int handler_type,
  11642. mg_request_handler *handler,
  11643. struct mg_websocket_subprotocols **subprotocols,
  11644. mg_websocket_connect_handler *connect_handler,
  11645. mg_websocket_ready_handler *ready_handler,
  11646. mg_websocket_data_handler *data_handler,
  11647. mg_websocket_close_handler *close_handler,
  11648. mg_authorization_handler *auth_handler,
  11649. void **cbdata,
  11650. struct mg_handler_info **handler_info)
  11651. {
  11652. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11653. if (request_info) {
  11654. const char *uri = request_info->local_uri;
  11655. size_t urilen = strlen(uri);
  11656. struct mg_handler_info *tmp_rh;
  11657. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11658. return 0;
  11659. }
  11660. mg_lock_context(conn->phys_ctx);
  11661. /* first try for an exact match */
  11662. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11663. tmp_rh = tmp_rh->next) {
  11664. if (tmp_rh->handler_type == handler_type) {
  11665. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11666. if (handler_type == WEBSOCKET_HANDLER) {
  11667. *subprotocols = tmp_rh->subprotocols;
  11668. *connect_handler = tmp_rh->connect_handler;
  11669. *ready_handler = tmp_rh->ready_handler;
  11670. *data_handler = tmp_rh->data_handler;
  11671. *close_handler = tmp_rh->close_handler;
  11672. } else if (handler_type == REQUEST_HANDLER) {
  11673. *handler = tmp_rh->handler;
  11674. /* Acquire handler and give it back */
  11675. handler_info_acquire(tmp_rh);
  11676. *handler_info = tmp_rh;
  11677. } else { /* AUTH_HANDLER */
  11678. *auth_handler = tmp_rh->auth_handler;
  11679. }
  11680. *cbdata = tmp_rh->cbdata;
  11681. mg_unlock_context(conn->phys_ctx);
  11682. return 1;
  11683. }
  11684. }
  11685. }
  11686. /* next try for a partial match, we will accept uri/something */
  11687. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11688. tmp_rh = tmp_rh->next) {
  11689. if (tmp_rh->handler_type == handler_type) {
  11690. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11691. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11692. if (handler_type == WEBSOCKET_HANDLER) {
  11693. *subprotocols = tmp_rh->subprotocols;
  11694. *connect_handler = tmp_rh->connect_handler;
  11695. *ready_handler = tmp_rh->ready_handler;
  11696. *data_handler = tmp_rh->data_handler;
  11697. *close_handler = tmp_rh->close_handler;
  11698. } else if (handler_type == REQUEST_HANDLER) {
  11699. *handler = tmp_rh->handler;
  11700. /* Acquire handler and give it back */
  11701. handler_info_acquire(tmp_rh);
  11702. *handler_info = tmp_rh;
  11703. } else { /* AUTH_HANDLER */
  11704. *auth_handler = tmp_rh->auth_handler;
  11705. }
  11706. *cbdata = tmp_rh->cbdata;
  11707. mg_unlock_context(conn->phys_ctx);
  11708. return 1;
  11709. }
  11710. }
  11711. }
  11712. /* finally try for pattern match */
  11713. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11714. tmp_rh = tmp_rh->next) {
  11715. if (tmp_rh->handler_type == handler_type) {
  11716. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11717. if (handler_type == WEBSOCKET_HANDLER) {
  11718. *subprotocols = tmp_rh->subprotocols;
  11719. *connect_handler = tmp_rh->connect_handler;
  11720. *ready_handler = tmp_rh->ready_handler;
  11721. *data_handler = tmp_rh->data_handler;
  11722. *close_handler = tmp_rh->close_handler;
  11723. } else if (handler_type == REQUEST_HANDLER) {
  11724. *handler = tmp_rh->handler;
  11725. /* Acquire handler and give it back */
  11726. handler_info_acquire(tmp_rh);
  11727. *handler_info = tmp_rh;
  11728. } else { /* AUTH_HANDLER */
  11729. *auth_handler = tmp_rh->auth_handler;
  11730. }
  11731. *cbdata = tmp_rh->cbdata;
  11732. mg_unlock_context(conn->phys_ctx);
  11733. return 1;
  11734. }
  11735. }
  11736. }
  11737. mg_unlock_context(conn->phys_ctx);
  11738. }
  11739. return 0; /* none found */
  11740. }
  11741. /* Check if the script file is in a path, allowed for script files.
  11742. * This can be used if uploading files is possible not only for the server
  11743. * admin, and the upload mechanism does not check the file extension.
  11744. */
  11745. static int
  11746. is_in_script_path(const struct mg_connection *conn, const char *path)
  11747. {
  11748. /* TODO (Feature): Add config value for allowed script path.
  11749. * Default: All allowed. */
  11750. (void)conn;
  11751. (void)path;
  11752. return 1;
  11753. }
  11754. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11755. static int
  11756. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11757. void *cbdata)
  11758. {
  11759. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11760. if (pcallbacks->websocket_connect) {
  11761. return pcallbacks->websocket_connect(conn);
  11762. }
  11763. /* No handler set - assume "OK" */
  11764. return 0;
  11765. }
  11766. static void
  11767. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11768. {
  11769. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11770. if (pcallbacks->websocket_ready) {
  11771. pcallbacks->websocket_ready(conn);
  11772. }
  11773. }
  11774. static int
  11775. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11776. int bits,
  11777. char *data,
  11778. size_t len,
  11779. void *cbdata)
  11780. {
  11781. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11782. if (pcallbacks->websocket_data) {
  11783. return pcallbacks->websocket_data(conn, bits, data, len);
  11784. }
  11785. /* No handler set - assume "OK" */
  11786. return 1;
  11787. }
  11788. #endif
  11789. /* This is the heart of the Civetweb's logic.
  11790. * This function is called when the request is read, parsed and validated,
  11791. * and Civetweb must decide what action to take: serve a file, or
  11792. * a directory, or call embedded function, etcetera. */
  11793. static void
  11794. handle_request(struct mg_connection *conn)
  11795. {
  11796. struct mg_request_info *ri = &conn->request_info;
  11797. char path[PATH_MAX];
  11798. int uri_len, ssl_index;
  11799. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11800. is_put_or_delete_request = 0, is_callback_resource = 0;
  11801. int i;
  11802. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11803. mg_request_handler callback_handler = NULL;
  11804. struct mg_handler_info *handler_info = NULL;
  11805. struct mg_websocket_subprotocols *subprotocols;
  11806. mg_websocket_connect_handler ws_connect_handler = NULL;
  11807. mg_websocket_ready_handler ws_ready_handler = NULL;
  11808. mg_websocket_data_handler ws_data_handler = NULL;
  11809. mg_websocket_close_handler ws_close_handler = NULL;
  11810. void *callback_data = NULL;
  11811. mg_authorization_handler auth_handler = NULL;
  11812. void *auth_callback_data = NULL;
  11813. int handler_type;
  11814. time_t curtime = time(NULL);
  11815. char date[64];
  11816. path[0] = 0;
  11817. /* 1. get the request url */
  11818. /* 1.1. split into url and query string */
  11819. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11820. != NULL) {
  11821. *((char *)conn->request_info.query_string++) = '\0';
  11822. }
  11823. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11824. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11825. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11826. if (ssl_index >= 0) {
  11827. redirect_to_https_port(conn, ssl_index);
  11828. } else {
  11829. /* A http to https forward port has been specified,
  11830. * but no https port to forward to. */
  11831. mg_send_http_error(conn,
  11832. 503,
  11833. "%s",
  11834. "Error: SSL forward not configured properly");
  11835. mg_cry_internal(conn,
  11836. "%s",
  11837. "Can not redirect to SSL, no SSL port available");
  11838. }
  11839. return;
  11840. }
  11841. uri_len = (int)strlen(ri->local_uri);
  11842. /* 1.3. decode url (if config says so) */
  11843. if (should_decode_url(conn)) {
  11844. mg_url_decode(
  11845. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11846. }
  11847. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11848. * not possible */
  11849. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11850. /* step 1. completed, the url is known now */
  11851. uri_len = (int)strlen(ri->local_uri);
  11852. DEBUG_TRACE("URL: %s", ri->local_uri);
  11853. /* 2. if this ip has limited speed, set it for this connection */
  11854. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11855. get_remote_ip(conn),
  11856. ri->local_uri);
  11857. /* 3. call a "handle everything" callback, if registered */
  11858. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11859. /* Note that since V1.7 the "begin_request" function is called
  11860. * before an authorization check. If an authorization check is
  11861. * required, use a request_handler instead. */
  11862. i = conn->phys_ctx->callbacks.begin_request(conn);
  11863. if (i > 0) {
  11864. /* callback already processed the request. Store the
  11865. return value as a status code for the access log. */
  11866. conn->status_code = i;
  11867. discard_unread_request_data(conn);
  11868. return;
  11869. } else if (i == 0) {
  11870. /* civetweb should process the request */
  11871. } else {
  11872. /* unspecified - may change with the next version */
  11873. return;
  11874. }
  11875. }
  11876. /* request not yet handled by a handler or redirect, so the request
  11877. * is processed here */
  11878. /* 4. Check for CORS preflight requests and handle them (if configured).
  11879. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11880. */
  11881. if (!strcmp(ri->request_method, "OPTIONS")) {
  11882. /* Send a response to CORS preflights only if
  11883. * access_control_allow_methods is not NULL and not an empty string.
  11884. * In this case, scripts can still handle CORS. */
  11885. const char *cors_meth_cfg =
  11886. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11887. const char *cors_orig_cfg =
  11888. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11889. const char *cors_origin =
  11890. get_header(ri->http_headers, ri->num_headers, "Origin");
  11891. const char *cors_acrm = get_header(ri->http_headers,
  11892. ri->num_headers,
  11893. "Access-Control-Request-Method");
  11894. /* Todo: check if cors_origin is in cors_orig_cfg.
  11895. * Or, let the client check this. */
  11896. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11897. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11898. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11899. /* This is a valid CORS preflight, and the server is configured
  11900. * to
  11901. * handle it automatically. */
  11902. const char *cors_acrh =
  11903. get_header(ri->http_headers,
  11904. ri->num_headers,
  11905. "Access-Control-Request-Headers");
  11906. gmt_time_string(date, sizeof(date), &curtime);
  11907. mg_printf(conn,
  11908. "HTTP/1.1 200 OK\r\n"
  11909. "Date: %s\r\n"
  11910. "Access-Control-Allow-Origin: %s\r\n"
  11911. "Access-Control-Allow-Methods: %s\r\n"
  11912. "Content-Length: 0\r\n"
  11913. "Connection: %s\r\n",
  11914. date,
  11915. cors_orig_cfg,
  11916. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11917. suggest_connection_header(conn));
  11918. if (cors_acrh != NULL) {
  11919. /* CORS request is asking for additional headers */
  11920. const char *cors_hdr_cfg =
  11921. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11922. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11923. /* Allow only if access_control_allow_headers is
  11924. * not NULL and not an empty string. If this
  11925. * configuration is set to *, allow everything.
  11926. * Otherwise this configuration must be a list
  11927. * of allowed HTTP header names. */
  11928. mg_printf(conn,
  11929. "Access-Control-Allow-Headers: %s\r\n",
  11930. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11931. : cors_hdr_cfg));
  11932. }
  11933. }
  11934. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11935. mg_printf(conn, "\r\n");
  11936. return;
  11937. }
  11938. }
  11939. /* 5. interpret the url to find out how the request must be handled
  11940. */
  11941. /* 5.1. first test, if the request targets the regular http(s)://
  11942. * protocol namespace or the websocket ws(s):// protocol namespace.
  11943. */
  11944. is_websocket_request = is_websocket_protocol(conn);
  11945. #if defined(USE_WEBSOCKET)
  11946. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11947. #else
  11948. handler_type = REQUEST_HANDLER;
  11949. #endif /* defined(USE_WEBSOCKET) */
  11950. /* 5.2. check if the request will be handled by a callback */
  11951. if (get_request_handler(conn,
  11952. handler_type,
  11953. &callback_handler,
  11954. &subprotocols,
  11955. &ws_connect_handler,
  11956. &ws_ready_handler,
  11957. &ws_data_handler,
  11958. &ws_close_handler,
  11959. NULL,
  11960. &callback_data,
  11961. &handler_info)) {
  11962. /* 5.2.1. A callback will handle this request. All requests
  11963. * handled
  11964. * by a callback have to be considered as requests to a script
  11965. * resource. */
  11966. is_callback_resource = 1;
  11967. is_script_resource = 1;
  11968. is_put_or_delete_request = is_put_or_delete_method(conn);
  11969. } else {
  11970. no_callback_resource:
  11971. /* 5.2.2. No callback is responsible for this request. The URI
  11972. * addresses a file based resource (static content or Lua/cgi
  11973. * scripts in the file system). */
  11974. is_callback_resource = 0;
  11975. interpret_uri(conn,
  11976. path,
  11977. sizeof(path),
  11978. &file.stat,
  11979. &is_found,
  11980. &is_script_resource,
  11981. &is_websocket_request,
  11982. &is_put_or_delete_request);
  11983. }
  11984. /* 6. authorization check */
  11985. /* 6.1. a custom authorization handler is installed */
  11986. if (get_request_handler(conn,
  11987. AUTH_HANDLER,
  11988. NULL,
  11989. NULL,
  11990. NULL,
  11991. NULL,
  11992. NULL,
  11993. NULL,
  11994. &auth_handler,
  11995. &auth_callback_data,
  11996. NULL)) {
  11997. if (!auth_handler(conn, auth_callback_data)) {
  11998. return;
  11999. }
  12000. } else if (is_put_or_delete_request && !is_script_resource
  12001. && !is_callback_resource) {
  12002. /* 6.2. this request is a PUT/DELETE to a real file */
  12003. /* 6.2.1. thus, the server must have real files */
  12004. #if defined(NO_FILES)
  12005. if (1) {
  12006. #else
  12007. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12008. #endif
  12009. /* This server does not have any real files, thus the
  12010. * PUT/DELETE methods are not valid. */
  12011. mg_send_http_error(conn,
  12012. 405,
  12013. "%s method not allowed",
  12014. conn->request_info.request_method);
  12015. return;
  12016. }
  12017. #if !defined(NO_FILES)
  12018. /* 6.2.2. Check if put authorization for static files is
  12019. * available.
  12020. */
  12021. if (!is_authorized_for_put(conn)) {
  12022. send_authorization_request(conn, NULL);
  12023. return;
  12024. }
  12025. #endif
  12026. } else {
  12027. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12028. * or it is a PUT or DELETE request to a resource that does not
  12029. * correspond to a file. Check authorization. */
  12030. if (!check_authorization(conn, path)) {
  12031. send_authorization_request(conn, NULL);
  12032. return;
  12033. }
  12034. }
  12035. /* request is authorized or does not need authorization */
  12036. /* 7. check if there are request handlers for this uri */
  12037. if (is_callback_resource) {
  12038. if (!is_websocket_request) {
  12039. i = callback_handler(conn, callback_data);
  12040. /* Callback handler will not be used anymore. Release it */
  12041. handler_info_release(handler_info);
  12042. if (i > 0) {
  12043. /* Do nothing, callback has served the request. Store
  12044. * then return value as status code for the log and discard
  12045. * all data from the client not used by the callback. */
  12046. conn->status_code = i;
  12047. discard_unread_request_data(conn);
  12048. } else {
  12049. /* The handler did NOT handle the request. */
  12050. /* Some proper reactions would be:
  12051. * a) close the connections without sending anything
  12052. * b) send a 404 not found
  12053. * c) try if there is a file matching the URI
  12054. * It would be possible to do a, b or c in the callback
  12055. * implementation, and return 1 - we cannot do anything
  12056. * here, that is not possible in the callback.
  12057. *
  12058. * TODO: What would be the best reaction here?
  12059. * (Note: The reaction may change, if there is a better
  12060. *idea.)
  12061. */
  12062. /* For the moment, use option c: We look for a proper file,
  12063. * but since a file request is not always a script resource,
  12064. * the authorization check might be different. */
  12065. interpret_uri(conn,
  12066. path,
  12067. sizeof(path),
  12068. &file.stat,
  12069. &is_found,
  12070. &is_script_resource,
  12071. &is_websocket_request,
  12072. &is_put_or_delete_request);
  12073. callback_handler = NULL;
  12074. /* Here we are at a dead end:
  12075. * According to URI matching, a callback should be
  12076. * responsible for handling the request,
  12077. * we called it, but the callback declared itself
  12078. * not responsible.
  12079. * We use a goto here, to get out of this dead end,
  12080. * and continue with the default handling.
  12081. * A goto here is simpler and better to understand
  12082. * than some curious loop. */
  12083. goto no_callback_resource;
  12084. }
  12085. } else {
  12086. #if defined(USE_WEBSOCKET)
  12087. handle_websocket_request(conn,
  12088. path,
  12089. is_callback_resource,
  12090. subprotocols,
  12091. ws_connect_handler,
  12092. ws_ready_handler,
  12093. ws_data_handler,
  12094. ws_close_handler,
  12095. callback_data);
  12096. #endif
  12097. }
  12098. return;
  12099. }
  12100. /* 8. handle websocket requests */
  12101. #if defined(USE_WEBSOCKET)
  12102. if (is_websocket_request) {
  12103. if (is_script_resource) {
  12104. if (is_in_script_path(conn, path)) {
  12105. /* Websocket Lua script */
  12106. handle_websocket_request(conn,
  12107. path,
  12108. 0 /* Lua Script */,
  12109. NULL,
  12110. NULL,
  12111. NULL,
  12112. NULL,
  12113. NULL,
  12114. conn->phys_ctx->user_data);
  12115. } else {
  12116. /* Script was in an illegal path */
  12117. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12118. }
  12119. } else {
  12120. #if defined(MG_LEGACY_INTERFACE)
  12121. handle_websocket_request(
  12122. conn,
  12123. path,
  12124. !is_script_resource /* could be deprecated global callback */,
  12125. NULL,
  12126. deprecated_websocket_connect_wrapper,
  12127. deprecated_websocket_ready_wrapper,
  12128. deprecated_websocket_data_wrapper,
  12129. NULL,
  12130. conn->phys_ctx->user_data);
  12131. #else
  12132. mg_send_http_error(conn, 404, "%s", "Not found");
  12133. #endif
  12134. }
  12135. return;
  12136. } else
  12137. #endif
  12138. #if defined(NO_FILES)
  12139. /* 9a. In case the server uses only callbacks, this uri is
  12140. * unknown.
  12141. * Then, all request handling ends here. */
  12142. mg_send_http_error(conn, 404, "%s", "Not Found");
  12143. #else
  12144. /* 9b. This request is either for a static file or resource handled
  12145. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12146. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12147. mg_send_http_error(conn, 404, "%s", "Not Found");
  12148. return;
  12149. }
  12150. /* 10. Request is handled by a script */
  12151. if (is_script_resource) {
  12152. handle_file_based_request(conn, path, &file);
  12153. return;
  12154. }
  12155. /* 11. Handle put/delete/mkcol requests */
  12156. if (is_put_or_delete_request) {
  12157. /* 11.1. PUT method */
  12158. if (!strcmp(ri->request_method, "PUT")) {
  12159. put_file(conn, path);
  12160. return;
  12161. }
  12162. /* 11.2. DELETE method */
  12163. if (!strcmp(ri->request_method, "DELETE")) {
  12164. delete_file(conn, path);
  12165. return;
  12166. }
  12167. /* 11.3. MKCOL method */
  12168. if (!strcmp(ri->request_method, "MKCOL")) {
  12169. mkcol(conn, path);
  12170. return;
  12171. }
  12172. /* 11.4. PATCH method
  12173. * This method is not supported for static resources,
  12174. * only for scripts (Lua, CGI) and callbacks. */
  12175. mg_send_http_error(conn,
  12176. 405,
  12177. "%s method not allowed",
  12178. conn->request_info.request_method);
  12179. return;
  12180. }
  12181. /* 11. File does not exist, or it was configured that it should be
  12182. * hidden */
  12183. if (!is_found || (must_hide_file(conn, path))) {
  12184. mg_send_http_error(conn, 404, "%s", "Not found");
  12185. return;
  12186. }
  12187. /* 12. Directory uris should end with a slash */
  12188. if (file.stat.is_directory && (uri_len > 0)
  12189. && (ri->local_uri[uri_len - 1] != '/')) {
  12190. gmt_time_string(date, sizeof(date), &curtime);
  12191. mg_printf(conn,
  12192. "HTTP/1.1 301 Moved Permanently\r\n"
  12193. "Location: %s/\r\n"
  12194. "Date: %s\r\n"
  12195. /* "Cache-Control: private\r\n" (= default) */
  12196. "Content-Length: 0\r\n"
  12197. "Connection: %s\r\n",
  12198. ri->request_uri,
  12199. date,
  12200. suggest_connection_header(conn));
  12201. send_additional_header(conn);
  12202. mg_printf(conn, "\r\n");
  12203. return;
  12204. }
  12205. /* 13. Handle other methods than GET/HEAD */
  12206. /* 13.1. Handle PROPFIND */
  12207. if (!strcmp(ri->request_method, "PROPFIND")) {
  12208. handle_propfind(conn, path, &file.stat);
  12209. return;
  12210. }
  12211. /* 13.2. Handle OPTIONS for files */
  12212. if (!strcmp(ri->request_method, "OPTIONS")) {
  12213. /* This standard handler is only used for real files.
  12214. * Scripts should support the OPTIONS method themselves, to allow a
  12215. * maximum flexibility.
  12216. * Lua and CGI scripts may fully support CORS this way (including
  12217. * preflights). */
  12218. send_options(conn);
  12219. return;
  12220. }
  12221. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12222. if ((0 != strcmp(ri->request_method, "GET"))
  12223. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12224. mg_send_http_error(conn,
  12225. 405,
  12226. "%s method not allowed",
  12227. conn->request_info.request_method);
  12228. return;
  12229. }
  12230. /* 14. directories */
  12231. if (file.stat.is_directory) {
  12232. /* Substitute files have already been handled above. */
  12233. /* Here we can either generate and send a directory listing,
  12234. * or send an "access denied" error. */
  12235. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12236. "yes")) {
  12237. handle_directory_request(conn, path);
  12238. } else {
  12239. mg_send_http_error(conn,
  12240. 403,
  12241. "%s",
  12242. "Error: Directory listing denied");
  12243. }
  12244. return;
  12245. }
  12246. /* 15. read a normal file with GET or HEAD */
  12247. handle_file_based_request(conn, path, &file);
  12248. #endif /* !defined(NO_FILES) */
  12249. }
  12250. #if !defined(NO_FILESYSTEMS)
  12251. static void
  12252. handle_file_based_request(struct mg_connection *conn,
  12253. const char *path,
  12254. struct mg_file *file)
  12255. {
  12256. if (!conn || !conn->dom_ctx) {
  12257. return;
  12258. }
  12259. if (0) {
  12260. #if defined(USE_LUA)
  12261. } else if (match_prefix(
  12262. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12263. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12264. path)
  12265. > 0) {
  12266. if (is_in_script_path(conn, path)) {
  12267. /* Lua server page: an SSI like page containing mostly plain
  12268. * html
  12269. * code
  12270. * plus some tags with server generated contents. */
  12271. handle_lsp_request(conn, path, file, NULL);
  12272. } else {
  12273. /* Script was in an illegal path */
  12274. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12275. }
  12276. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12277. strlen(
  12278. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12279. path)
  12280. > 0) {
  12281. if (is_in_script_path(conn, path)) {
  12282. /* Lua in-server module script: a CGI like script used to
  12283. * generate
  12284. * the
  12285. * entire reply. */
  12286. mg_exec_lua_script(conn, path, NULL);
  12287. } else {
  12288. /* Script was in an illegal path */
  12289. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12290. }
  12291. #endif
  12292. #if defined(USE_DUKTAPE)
  12293. } else if (match_prefix(
  12294. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12295. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12296. path)
  12297. > 0) {
  12298. if (is_in_script_path(conn, path)) {
  12299. /* Call duktape to generate the page */
  12300. mg_exec_duktape_script(conn, path);
  12301. } else {
  12302. /* Script was in an illegal path */
  12303. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12304. }
  12305. #endif
  12306. #if !defined(NO_CGI)
  12307. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12308. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12309. path)
  12310. > 0) {
  12311. if (is_in_script_path(conn, path)) {
  12312. /* CGI scripts may support all HTTP methods */
  12313. handle_cgi_request(conn, path);
  12314. } else {
  12315. /* Script was in an illegal path */
  12316. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12317. }
  12318. #endif /* !NO_CGI */
  12319. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12320. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12321. path)
  12322. > 0) {
  12323. if (is_in_script_path(conn, path)) {
  12324. handle_ssi_file_request(conn, path, file);
  12325. } else {
  12326. /* Script was in an illegal path */
  12327. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12328. }
  12329. #if !defined(NO_CACHING)
  12330. } else if ((!conn->in_error_handler)
  12331. && is_not_modified(conn, &file->stat)) {
  12332. /* Send 304 "Not Modified" - this must not send any body data */
  12333. handle_not_modified_static_file_request(conn, file);
  12334. #endif /* !NO_CACHING */
  12335. } else {
  12336. handle_static_file_request(conn, path, file, NULL, NULL);
  12337. }
  12338. }
  12339. #endif /* NO_FILESYSTEMS */
  12340. static void
  12341. close_all_listening_sockets(struct mg_context *ctx)
  12342. {
  12343. unsigned int i;
  12344. if (!ctx) {
  12345. return;
  12346. }
  12347. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12348. closesocket(ctx->listening_sockets[i].sock);
  12349. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12350. }
  12351. mg_free(ctx->listening_sockets);
  12352. ctx->listening_sockets = NULL;
  12353. mg_free(ctx->listening_socket_fds);
  12354. ctx->listening_socket_fds = NULL;
  12355. }
  12356. /* Valid listening port specification is: [ip_address:]port[s]
  12357. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12358. * Examples for IPv6: [::]:80, [::1]:80,
  12359. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12360. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12361. * In order to bind to both, IPv4 and IPv6, you can either add
  12362. * both ports using 8080,[::]:8080, or the short form +8080.
  12363. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12364. * one only accepting IPv4 the other only IPv6. +8080 creates
  12365. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12366. * environment, they might work differently, or might not work
  12367. * at all - it must be tested what options work best in the
  12368. * relevant network environment.
  12369. */
  12370. static int
  12371. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12372. {
  12373. unsigned int a, b, c, d, port;
  12374. int ch, len;
  12375. const char *cb;
  12376. char *endptr;
  12377. #if defined(USE_IPV6)
  12378. char buf[100] = {0};
  12379. #endif
  12380. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12381. * Also, all-zeroes in the socket address means binding to all addresses
  12382. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12383. memset(so, 0, sizeof(*so));
  12384. so->lsa.sin.sin_family = AF_INET;
  12385. *ip_version = 0;
  12386. /* Initialize port and len as invalid. */
  12387. port = 0;
  12388. len = 0;
  12389. /* Test for different ways to format this string */
  12390. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12391. == 5) {
  12392. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12393. so->lsa.sin.sin_addr.s_addr =
  12394. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12395. so->lsa.sin.sin_port = htons((uint16_t)port);
  12396. *ip_version = 4;
  12397. #if defined(USE_IPV6)
  12398. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12399. && mg_inet_pton(
  12400. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12401. /* IPv6 address, examples: see above */
  12402. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12403. */
  12404. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12405. *ip_version = 6;
  12406. #endif
  12407. } else if ((vec->ptr[0] == '+')
  12408. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12409. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12410. /* Add 1 to len for the + character we skipped before */
  12411. len++;
  12412. #if defined(USE_IPV6)
  12413. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12414. so->lsa.sin6.sin6_family = AF_INET6;
  12415. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12416. *ip_version = 4 + 6;
  12417. #else
  12418. /* Bind to IPv4 only, since IPv6 is not built in. */
  12419. so->lsa.sin.sin_port = htons((uint16_t)port);
  12420. *ip_version = 4;
  12421. #endif
  12422. } else if (is_valid_port(port = strtoul(vec->ptr, &endptr, 0))
  12423. && vec->ptr != endptr) {
  12424. len = endptr - vec->ptr;
  12425. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12426. so->lsa.sin.sin_port = htons((uint16_t)port);
  12427. *ip_version = 4;
  12428. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12429. /* String could be a hostname. This check algotithm
  12430. * will only work for RFC 952 compliant hostnames,
  12431. * starting with a letter, containing only letters,
  12432. * digits and hyphen ('-'). Newer specs may allow
  12433. * more, but this is not guaranteed here, since it
  12434. * may interfere with rules for port option lists. */
  12435. /* According to RFC 1035, hostnames are restricted to 255 characters
  12436. * in total (63 between two dots). */
  12437. char hostname[256];
  12438. size_t hostnlen = (size_t)(cb - vec->ptr);
  12439. if (hostnlen >= sizeof(hostname)) {
  12440. /* This would be invalid in any case */
  12441. *ip_version = 0;
  12442. return 0;
  12443. }
  12444. memcpy(hostname, vec->ptr, hostnlen);
  12445. hostname[hostnlen] = 0;
  12446. if (mg_inet_pton(
  12447. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12448. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12449. *ip_version = 4;
  12450. so->lsa.sin.sin_family = AF_INET;
  12451. so->lsa.sin.sin_port = htons((uint16_t)port);
  12452. len += (int)(hostnlen + 1);
  12453. } else {
  12454. port = 0;
  12455. len = 0;
  12456. }
  12457. #if defined(USE_IPV6)
  12458. } else if (mg_inet_pton(AF_INET6,
  12459. vec->ptr,
  12460. &so->lsa.sin6,
  12461. sizeof(so->lsa.sin6))) {
  12462. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12463. *ip_version = 6;
  12464. so->lsa.sin6.sin6_family = AF_INET6;
  12465. so->lsa.sin.sin_port = htons((uint16_t)port);
  12466. len += (int)(hostnlen + 1);
  12467. } else {
  12468. port = 0;
  12469. len = 0;
  12470. }
  12471. #endif
  12472. }
  12473. } else {
  12474. /* Parsing failure. */
  12475. }
  12476. /* sscanf and the option splitting code ensure the following condition
  12477. */
  12478. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12479. *ip_version = 0;
  12480. return 0;
  12481. }
  12482. ch = vec->ptr[len]; /* Next character after the port number */
  12483. so->is_ssl = (ch == 's');
  12484. so->ssl_redir = (ch == 'r');
  12485. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12486. if (is_valid_port(port)
  12487. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12488. return 1;
  12489. }
  12490. /* Reset ip_version to 0 if there is an error */
  12491. *ip_version = 0;
  12492. return 0;
  12493. }
  12494. /* Is there any SSL port in use? */
  12495. static int
  12496. is_ssl_port_used(const char *ports)
  12497. {
  12498. if (ports) {
  12499. /* There are several different allowed syntax variants:
  12500. * - "80" for a single port using every network interface
  12501. * - "localhost:80" for a single port using only localhost
  12502. * - "80,localhost:8080" for two ports, one bound to localhost
  12503. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12504. * to IPv4 localhost, one to IPv6 localhost
  12505. * - "+80" use port 80 for IPv4 and IPv6
  12506. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12507. * for both: IPv4 and IPv4
  12508. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12509. * additionally port 8080 bound to localhost connections
  12510. *
  12511. * If we just look for 's' anywhere in the string, "localhost:80"
  12512. * will be detected as SSL (false positive).
  12513. * Looking for 's' after a digit may cause false positives in
  12514. * "my24service:8080".
  12515. * Looking from 's' backward if there are only ':' and numbers
  12516. * before will not work for "24service:8080" (non SSL, port 8080)
  12517. * or "24s" (SSL, port 24).
  12518. *
  12519. * Remark: Initially hostnames were not allowed to start with a
  12520. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12521. * Section 2.1).
  12522. *
  12523. * To get this correct, the entire string must be parsed as a whole,
  12524. * reading it as a list element for element and parsing with an
  12525. * algorithm equivalent to parse_port_string.
  12526. *
  12527. * In fact, we use local interface names here, not arbitrary hostnames,
  12528. * so in most cases the only name will be "localhost".
  12529. *
  12530. * So, for now, we use this simple algorithm, that may still return
  12531. * a false positive in bizarre cases.
  12532. */
  12533. int i;
  12534. int portslen = (int)strlen(ports);
  12535. char prevIsNumber = 0;
  12536. for (i = 0; i < portslen; i++) {
  12537. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12538. return 1;
  12539. }
  12540. if (ports[i] >= '0' && ports[i] <= '9') {
  12541. prevIsNumber = 1;
  12542. } else {
  12543. prevIsNumber = 0;
  12544. }
  12545. }
  12546. }
  12547. return 0;
  12548. }
  12549. static int
  12550. set_ports_option(struct mg_context *phys_ctx)
  12551. {
  12552. const char *list;
  12553. int on = 1;
  12554. #if defined(USE_IPV6)
  12555. int off = 0;
  12556. #endif
  12557. struct vec vec;
  12558. struct socket so, *ptr;
  12559. struct mg_pollfd *pfd;
  12560. union usa usa;
  12561. socklen_t len;
  12562. int ip_version;
  12563. int portsTotal = 0;
  12564. int portsOk = 0;
  12565. if (!phys_ctx) {
  12566. return 0;
  12567. }
  12568. memset(&so, 0, sizeof(so));
  12569. memset(&usa, 0, sizeof(usa));
  12570. len = sizeof(usa);
  12571. list = phys_ctx->dd.config[LISTENING_PORTS];
  12572. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12573. portsTotal++;
  12574. if (!parse_port_string(&vec, &so, &ip_version)) {
  12575. mg_cry_ctx_internal(
  12576. phys_ctx,
  12577. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12578. (int)vec.len,
  12579. vec.ptr,
  12580. portsTotal,
  12581. "[IP_ADDRESS:]PORT[s|r]");
  12582. continue;
  12583. }
  12584. #if !defined(NO_SSL)
  12585. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12586. mg_cry_ctx_internal(phys_ctx,
  12587. "Cannot add SSL socket (entry %i)",
  12588. portsTotal);
  12589. continue;
  12590. }
  12591. #endif
  12592. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12593. == INVALID_SOCKET) {
  12594. mg_cry_ctx_internal(phys_ctx,
  12595. "cannot create socket (entry %i)",
  12596. portsTotal);
  12597. continue;
  12598. }
  12599. #if defined(_WIN32)
  12600. /* Windows SO_REUSEADDR lets many procs binds to a
  12601. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12602. * if someone already has the socket -- DTL */
  12603. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12604. * Windows might need a few seconds before
  12605. * the same port can be used again in the
  12606. * same process, so a short Sleep may be
  12607. * required between mg_stop and mg_start.
  12608. */
  12609. if (setsockopt(so.sock,
  12610. SOL_SOCKET,
  12611. SO_EXCLUSIVEADDRUSE,
  12612. (SOCK_OPT_TYPE)&on,
  12613. sizeof(on))
  12614. != 0) {
  12615. /* Set reuse option, but don't abort on errors. */
  12616. mg_cry_ctx_internal(
  12617. phys_ctx,
  12618. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12619. portsTotal);
  12620. }
  12621. #else
  12622. if (setsockopt(so.sock,
  12623. SOL_SOCKET,
  12624. SO_REUSEADDR,
  12625. (SOCK_OPT_TYPE)&on,
  12626. sizeof(on))
  12627. != 0) {
  12628. /* Set reuse option, but don't abort on errors. */
  12629. mg_cry_ctx_internal(
  12630. phys_ctx,
  12631. "cannot set socket option SO_REUSEADDR (entry %i)",
  12632. portsTotal);
  12633. }
  12634. #endif
  12635. if (ip_version > 4) {
  12636. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12637. #if defined(USE_IPV6)
  12638. if (ip_version > 6) {
  12639. if (so.lsa.sa.sa_family == AF_INET6
  12640. && setsockopt(so.sock,
  12641. IPPROTO_IPV6,
  12642. IPV6_V6ONLY,
  12643. (void *)&off,
  12644. sizeof(off))
  12645. != 0) {
  12646. /* Set IPv6 only option, but don't abort on errors. */
  12647. mg_cry_ctx_internal(
  12648. phys_ctx,
  12649. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12650. portsTotal);
  12651. }
  12652. } else {
  12653. if (so.lsa.sa.sa_family == AF_INET6
  12654. && setsockopt(so.sock,
  12655. IPPROTO_IPV6,
  12656. IPV6_V6ONLY,
  12657. (void *)&on,
  12658. sizeof(on))
  12659. != 0) {
  12660. /* Set IPv6 only option, but don't abort on errors. */
  12661. mg_cry_ctx_internal(
  12662. phys_ctx,
  12663. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12664. portsTotal);
  12665. }
  12666. }
  12667. #else
  12668. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12669. closesocket(so.sock);
  12670. so.sock = INVALID_SOCKET;
  12671. continue;
  12672. #endif
  12673. }
  12674. if (so.lsa.sa.sa_family == AF_INET) {
  12675. len = sizeof(so.lsa.sin);
  12676. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12677. mg_cry_ctx_internal(phys_ctx,
  12678. "cannot bind to %.*s: %d (%s)",
  12679. (int)vec.len,
  12680. vec.ptr,
  12681. (int)ERRNO,
  12682. strerror(errno));
  12683. closesocket(so.sock);
  12684. so.sock = INVALID_SOCKET;
  12685. continue;
  12686. }
  12687. }
  12688. #if defined(USE_IPV6)
  12689. else if (so.lsa.sa.sa_family == AF_INET6) {
  12690. len = sizeof(so.lsa.sin6);
  12691. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12692. mg_cry_ctx_internal(phys_ctx,
  12693. "cannot bind to IPv6 %.*s: %d (%s)",
  12694. (int)vec.len,
  12695. vec.ptr,
  12696. (int)ERRNO,
  12697. strerror(errno));
  12698. closesocket(so.sock);
  12699. so.sock = INVALID_SOCKET;
  12700. continue;
  12701. }
  12702. }
  12703. #endif
  12704. else {
  12705. mg_cry_ctx_internal(
  12706. phys_ctx,
  12707. "cannot bind: address family not supported (entry %i)",
  12708. portsTotal);
  12709. closesocket(so.sock);
  12710. so.sock = INVALID_SOCKET;
  12711. continue;
  12712. }
  12713. const char* p = phys_ctx->dd.config[MAX_CONNECTIONS];
  12714. const long opt_max_connections = strtol(p, NULL, 10);
  12715. if(opt_max_connections > INT_MAX || opt_max_connections < 1) {
  12716. mg_cry_ctx_internal(phys_ctx,
  12717. "max_connections value \"%s\" is invalid",
  12718. p);
  12719. continue;
  12720. }
  12721. if (listen(so.sock, (int)opt_max_connections) != 0) {
  12722. mg_cry_ctx_internal(phys_ctx,
  12723. "cannot listen to %.*s: %d (%s)",
  12724. (int)vec.len,
  12725. vec.ptr,
  12726. (int)ERRNO,
  12727. strerror(errno));
  12728. closesocket(so.sock);
  12729. so.sock = INVALID_SOCKET;
  12730. continue;
  12731. }
  12732. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12733. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12734. int err = (int)ERRNO;
  12735. mg_cry_ctx_internal(phys_ctx,
  12736. "call to getsockname failed %.*s: %d (%s)",
  12737. (int)vec.len,
  12738. vec.ptr,
  12739. err,
  12740. strerror(errno));
  12741. closesocket(so.sock);
  12742. so.sock = INVALID_SOCKET;
  12743. continue;
  12744. }
  12745. /* Update lsa port in case of random free ports */
  12746. #if defined(USE_IPV6)
  12747. if (so.lsa.sa.sa_family == AF_INET6) {
  12748. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12749. } else
  12750. #endif
  12751. {
  12752. so.lsa.sin.sin_port = usa.sin.sin_port;
  12753. }
  12754. if ((ptr = (struct socket *)
  12755. mg_realloc_ctx(phys_ctx->listening_sockets,
  12756. (phys_ctx->num_listening_sockets + 1)
  12757. * sizeof(phys_ctx->listening_sockets[0]),
  12758. phys_ctx))
  12759. == NULL) {
  12760. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12761. closesocket(so.sock);
  12762. so.sock = INVALID_SOCKET;
  12763. continue;
  12764. }
  12765. if ((pfd = (struct mg_pollfd *)
  12766. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12767. (phys_ctx->num_listening_sockets + 1)
  12768. * sizeof(phys_ctx->listening_socket_fds[0]),
  12769. phys_ctx))
  12770. == NULL) {
  12771. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12772. closesocket(so.sock);
  12773. so.sock = INVALID_SOCKET;
  12774. mg_free(ptr);
  12775. continue;
  12776. }
  12777. set_close_on_exec(so.sock, NULL, phys_ctx);
  12778. phys_ctx->listening_sockets = ptr;
  12779. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12780. phys_ctx->listening_socket_fds = pfd;
  12781. phys_ctx->num_listening_sockets++;
  12782. portsOk++;
  12783. }
  12784. if (portsOk != portsTotal) {
  12785. close_all_listening_sockets(phys_ctx);
  12786. portsOk = 0;
  12787. }
  12788. return portsOk;
  12789. }
  12790. static const char *
  12791. header_val(const struct mg_connection *conn, const char *header)
  12792. {
  12793. const char *header_value;
  12794. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12795. return "-";
  12796. } else {
  12797. return header_value;
  12798. }
  12799. }
  12800. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12801. static void log_access(const struct mg_connection *conn);
  12802. #include "external_log_access.inl"
  12803. #elif !defined(NO_FILESYSTEMS)
  12804. static void
  12805. log_access(const struct mg_connection *conn)
  12806. {
  12807. const struct mg_request_info *ri;
  12808. struct mg_file fi;
  12809. char date[64], src_addr[IP_ADDR_STR_LEN];
  12810. struct tm *tm;
  12811. const char *referer;
  12812. const char *user_agent;
  12813. char buf[4096];
  12814. if (!conn || !conn->dom_ctx) {
  12815. return;
  12816. }
  12817. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12818. if (mg_fopen(conn,
  12819. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12820. MG_FOPEN_MODE_APPEND,
  12821. &fi)
  12822. == 0) {
  12823. fi.access.fp = NULL;
  12824. }
  12825. } else {
  12826. fi.access.fp = NULL;
  12827. }
  12828. /* Log is written to a file and/or a callback. If both are not set,
  12829. * executing the rest of the function is pointless. */
  12830. if ((fi.access.fp == NULL)
  12831. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12832. return;
  12833. }
  12834. tm = localtime(&conn->conn_birth_time);
  12835. if (tm != NULL) {
  12836. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12837. } else {
  12838. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12839. date[sizeof(date) - 1] = '\0';
  12840. }
  12841. ri = &conn->request_info;
  12842. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12843. referer = header_val(conn, "Referer");
  12844. user_agent = header_val(conn, "User-Agent");
  12845. mg_snprintf(conn,
  12846. NULL, /* Ignore truncation in access log */
  12847. buf,
  12848. sizeof(buf),
  12849. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12850. src_addr,
  12851. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12852. date,
  12853. ri->request_method ? ri->request_method : "-",
  12854. ri->request_uri ? ri->request_uri : "-",
  12855. ri->query_string ? "?" : "",
  12856. ri->query_string ? ri->query_string : "",
  12857. ri->http_version,
  12858. conn->status_code,
  12859. conn->num_bytes_sent,
  12860. referer,
  12861. user_agent);
  12862. if (conn->phys_ctx->callbacks.log_access) {
  12863. conn->phys_ctx->callbacks.log_access(conn, buf);
  12864. }
  12865. if (fi.access.fp) {
  12866. int ok = 1;
  12867. flockfile(fi.access.fp);
  12868. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12869. ok = 0;
  12870. }
  12871. if (fflush(fi.access.fp) != 0) {
  12872. ok = 0;
  12873. }
  12874. funlockfile(fi.access.fp);
  12875. if (mg_fclose(&fi.access) != 0) {
  12876. ok = 0;
  12877. }
  12878. if (!ok) {
  12879. mg_cry_internal(conn,
  12880. "Error writing log file %s",
  12881. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12882. }
  12883. }
  12884. }
  12885. #else
  12886. #error Must either enable filesystems or provide a custom log_access implementation
  12887. #endif /* Externally provided function */
  12888. /* Verify given socket address against the ACL.
  12889. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12890. */
  12891. static int
  12892. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12893. {
  12894. int allowed, flag;
  12895. uint32_t net, mask;
  12896. struct vec vec;
  12897. if (phys_ctx) {
  12898. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12899. /* If any ACL is set, deny by default */
  12900. allowed = (list == NULL) ? '+' : '-';
  12901. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12902. flag = vec.ptr[0];
  12903. if ((flag != '+' && flag != '-')
  12904. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12905. mg_cry_ctx_internal(phys_ctx,
  12906. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12907. __func__);
  12908. return -1;
  12909. }
  12910. if (net == (remote_ip & mask)) {
  12911. allowed = flag;
  12912. }
  12913. }
  12914. return allowed == '+';
  12915. }
  12916. return -1;
  12917. }
  12918. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  12919. static int
  12920. set_uid_option(struct mg_context *phys_ctx)
  12921. {
  12922. int success = 0;
  12923. if (phys_ctx) {
  12924. /* We are currently running as curr_uid. */
  12925. const uid_t curr_uid = getuid();
  12926. /* If set, we want to run as run_as_user. */
  12927. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12928. const struct passwd *to_pw = NULL;
  12929. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12930. /* run_as_user does not exist on the system. We can't proceed
  12931. * further. */
  12932. mg_cry_ctx_internal(phys_ctx,
  12933. "%s: unknown user [%s]",
  12934. __func__,
  12935. run_as_user);
  12936. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12937. /* There was either no request to change user, or we're already
  12938. * running as run_as_user. Nothing else to do.
  12939. */
  12940. success = 1;
  12941. } else {
  12942. /* Valid change request. */
  12943. if (setgid(to_pw->pw_gid) == -1) {
  12944. mg_cry_ctx_internal(phys_ctx,
  12945. "%s: setgid(%s): %s",
  12946. __func__,
  12947. run_as_user,
  12948. strerror(errno));
  12949. } else if (setgroups(0, NULL) == -1) {
  12950. mg_cry_ctx_internal(phys_ctx,
  12951. "%s: setgroups(): %s",
  12952. __func__,
  12953. strerror(errno));
  12954. } else if (setuid(to_pw->pw_uid) == -1) {
  12955. mg_cry_ctx_internal(phys_ctx,
  12956. "%s: setuid(%s): %s",
  12957. __func__,
  12958. run_as_user,
  12959. strerror(errno));
  12960. } else {
  12961. success = 1;
  12962. }
  12963. }
  12964. }
  12965. return success;
  12966. }
  12967. #endif /* !_WIN32 */
  12968. static void
  12969. tls_dtor(void *key)
  12970. {
  12971. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12972. /* key == pthread_getspecific(sTlsKey); */
  12973. if (tls) {
  12974. if (tls->is_master == 2) {
  12975. tls->is_master = -3; /* Mark memory as dead */
  12976. mg_free(tls);
  12977. }
  12978. }
  12979. pthread_setspecific(sTlsKey, NULL);
  12980. }
  12981. #if !defined(NO_SSL)
  12982. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12983. struct mg_domain_context *dom_ctx,
  12984. const char *pem,
  12985. const char *chain);
  12986. static const char *ssl_error(void);
  12987. static int
  12988. refresh_trust(struct mg_connection *conn)
  12989. {
  12990. static int reload_lock = 0;
  12991. static long int data_check = 0;
  12992. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12993. struct stat cert_buf;
  12994. long int t;
  12995. const char *pem;
  12996. const char *chain;
  12997. int should_verify_peer;
  12998. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12999. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  13000. * refresh_trust still can not work. */
  13001. return 0;
  13002. }
  13003. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13004. if (chain == NULL) {
  13005. /* pem is not NULL here */
  13006. chain = pem;
  13007. }
  13008. if (*chain == 0) {
  13009. chain = NULL;
  13010. }
  13011. t = data_check;
  13012. if (stat(pem, &cert_buf) != -1) {
  13013. t = (long int)cert_buf.st_mtime;
  13014. }
  13015. if (data_check != t) {
  13016. data_check = t;
  13017. should_verify_peer = 0;
  13018. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13019. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13020. == 0) {
  13021. should_verify_peer = 1;
  13022. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13023. "optional")
  13024. == 0) {
  13025. should_verify_peer = 1;
  13026. }
  13027. }
  13028. if (should_verify_peer) {
  13029. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13030. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13031. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13032. ca_file,
  13033. ca_path)
  13034. != 1) {
  13035. mg_cry_ctx_internal(
  13036. conn->phys_ctx,
  13037. "SSL_CTX_load_verify_locations error: %s "
  13038. "ssl_verify_peer requires setting "
  13039. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13040. "present in "
  13041. "the .conf file?",
  13042. ssl_error());
  13043. return 0;
  13044. }
  13045. }
  13046. if (1 == mg_atomic_inc(p_reload_lock)) {
  13047. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13048. == 0) {
  13049. return 0;
  13050. }
  13051. *p_reload_lock = 0;
  13052. }
  13053. }
  13054. /* lock while cert is reloading */
  13055. while (*p_reload_lock) {
  13056. sleep(1);
  13057. }
  13058. return 1;
  13059. }
  13060. #if defined(OPENSSL_API_1_1)
  13061. #else
  13062. static pthread_mutex_t *ssl_mutexes;
  13063. #endif /* OPENSSL_API_1_1 */
  13064. static int
  13065. sslize(struct mg_connection *conn,
  13066. SSL_CTX *s,
  13067. int (*func)(SSL *),
  13068. volatile int *stop_server,
  13069. const struct mg_client_options *client_options)
  13070. {
  13071. int ret, err;
  13072. int short_trust;
  13073. unsigned timeout = 1024;
  13074. unsigned i;
  13075. if (!conn) {
  13076. return 0;
  13077. }
  13078. short_trust =
  13079. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13080. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13081. if (short_trust) {
  13082. int trust_ret = refresh_trust(conn);
  13083. if (!trust_ret) {
  13084. return trust_ret;
  13085. }
  13086. }
  13087. conn->ssl = SSL_new(s);
  13088. if (conn->ssl == NULL) {
  13089. return 0;
  13090. }
  13091. SSL_set_app_data(conn->ssl, (char *)conn);
  13092. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13093. if (ret != 1) {
  13094. err = SSL_get_error(conn->ssl, ret);
  13095. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13096. SSL_free(conn->ssl);
  13097. conn->ssl = NULL;
  13098. OPENSSL_REMOVE_THREAD_STATE();
  13099. return 0;
  13100. }
  13101. if (client_options) {
  13102. if (client_options->host_name) {
  13103. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13104. }
  13105. }
  13106. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13107. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13108. /* NOTE: The loop below acts as a back-off, so we can end
  13109. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13110. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13111. }
  13112. /* SSL functions may fail and require to be called again:
  13113. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13114. * Here "func" could be SSL_connect or SSL_accept. */
  13115. for (i = 0; i <= timeout; i += 50) {
  13116. ret = func(conn->ssl);
  13117. if (ret != 1) {
  13118. err = SSL_get_error(conn->ssl, ret);
  13119. if ((err == SSL_ERROR_WANT_CONNECT)
  13120. || (err == SSL_ERROR_WANT_ACCEPT)
  13121. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13122. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13123. if (*stop_server) {
  13124. /* Don't wait if the server is going to be stopped. */
  13125. break;
  13126. }
  13127. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13128. /* Simply retry the function call. */
  13129. mg_sleep(50);
  13130. } else {
  13131. /* Need to retry the function call "later".
  13132. * See https://linux.die.net/man/3/ssl_get_error
  13133. * This is typical for non-blocking sockets. */
  13134. struct mg_pollfd pfd;
  13135. int pollres;
  13136. pfd.fd = conn->client.sock;
  13137. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13138. || (err == SSL_ERROR_WANT_WRITE))
  13139. ? POLLOUT
  13140. : POLLIN;
  13141. pollres = mg_poll(&pfd, 1, 50, stop_server);
  13142. if (pollres < 0) {
  13143. /* Break if error occured (-1)
  13144. * or server shutdown (-2) */
  13145. break;
  13146. }
  13147. }
  13148. } else if (err == SSL_ERROR_SYSCALL) {
  13149. /* This is an IO error. Look at errno. */
  13150. err = errno;
  13151. mg_cry_internal(conn, "SSL syscall error %i", err);
  13152. break;
  13153. } else {
  13154. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13155. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13156. break;
  13157. }
  13158. ERR_clear_error();
  13159. } else {
  13160. /* success */
  13161. break;
  13162. }
  13163. }
  13164. if (ret != 1) {
  13165. SSL_free(conn->ssl);
  13166. conn->ssl = NULL;
  13167. OPENSSL_REMOVE_THREAD_STATE();
  13168. return 0;
  13169. }
  13170. return 1;
  13171. }
  13172. /* Return OpenSSL error message (from CRYPTO lib) */
  13173. static const char *
  13174. ssl_error(void)
  13175. {
  13176. unsigned long err;
  13177. err = ERR_get_error();
  13178. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13179. }
  13180. static int
  13181. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13182. {
  13183. int i;
  13184. const char hexdigit[] = "0123456789abcdef";
  13185. if ((memlen <= 0) || (buflen <= 0)) {
  13186. return 0;
  13187. }
  13188. if (buflen < (3 * memlen)) {
  13189. return 0;
  13190. }
  13191. for (i = 0; i < memlen; i++) {
  13192. if (i > 0) {
  13193. buf[3 * i - 1] = ' ';
  13194. }
  13195. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13196. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13197. }
  13198. buf[3 * memlen - 1] = 0;
  13199. return 1;
  13200. }
  13201. static void
  13202. ssl_get_client_cert_info(struct mg_connection *conn)
  13203. {
  13204. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13205. if (cert) {
  13206. char str_subject[1024];
  13207. char str_issuer[1024];
  13208. char str_finger[1024];
  13209. unsigned char buf[256];
  13210. char *str_serial = NULL;
  13211. unsigned int ulen;
  13212. int ilen;
  13213. unsigned char *tmp_buf;
  13214. unsigned char *tmp_p;
  13215. /* Handle to algorithm used for fingerprint */
  13216. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13217. /* Get Subject and issuer */
  13218. X509_NAME *subj = X509_get_subject_name(cert);
  13219. X509_NAME *iss = X509_get_issuer_name(cert);
  13220. /* Get serial number */
  13221. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13222. /* Translate serial number to a hex string */
  13223. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13224. str_serial = BN_bn2hex(serial_bn);
  13225. BN_free(serial_bn);
  13226. /* Translate subject and issuer to a string */
  13227. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13228. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13229. /* Calculate SHA1 fingerprint and store as a hex string */
  13230. ulen = 0;
  13231. /* ASN1_digest is deprecated. Do the calculation manually,
  13232. * using EVP_Digest. */
  13233. ilen = i2d_X509(cert, NULL);
  13234. tmp_buf = (ilen > 0)
  13235. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13236. conn->phys_ctx)
  13237. : NULL;
  13238. if (tmp_buf) {
  13239. tmp_p = tmp_buf;
  13240. (void)i2d_X509(cert, &tmp_p);
  13241. if (!EVP_Digest(
  13242. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13243. ulen = 0;
  13244. }
  13245. mg_free(tmp_buf);
  13246. }
  13247. if (!hexdump2string(
  13248. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13249. *str_finger = 0;
  13250. }
  13251. conn->request_info.client_cert = (struct mg_client_cert *)
  13252. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13253. if (conn->request_info.client_cert) {
  13254. conn->request_info.client_cert->peer_cert = (void *)cert;
  13255. conn->request_info.client_cert->subject =
  13256. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13257. conn->request_info.client_cert->issuer =
  13258. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13259. conn->request_info.client_cert->serial =
  13260. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13261. conn->request_info.client_cert->finger =
  13262. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13263. } else {
  13264. mg_cry_internal(conn,
  13265. "%s",
  13266. "Out of memory: Cannot allocate memory for client "
  13267. "certificate");
  13268. }
  13269. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13270. * see https://linux.die.net/man/3/bn_bn2hex */
  13271. OPENSSL_free(str_serial);
  13272. }
  13273. }
  13274. #if defined(OPENSSL_API_1_1)
  13275. #else
  13276. static void
  13277. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13278. {
  13279. (void)line;
  13280. (void)file;
  13281. if (mode & 1) {
  13282. /* 1 is CRYPTO_LOCK */
  13283. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13284. } else {
  13285. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13286. }
  13287. }
  13288. #endif /* OPENSSL_API_1_1 */
  13289. #if !defined(NO_SSL_DL)
  13290. static void *
  13291. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13292. {
  13293. union {
  13294. void *p;
  13295. void (*fp)(void);
  13296. } u;
  13297. void *dll_handle;
  13298. struct ssl_func *fp;
  13299. int ok;
  13300. int truncated = 0;
  13301. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13302. mg_snprintf(NULL,
  13303. NULL, /* No truncation check for ebuf */
  13304. ebuf,
  13305. ebuf_len,
  13306. "%s: cannot load %s",
  13307. __func__,
  13308. dll_name);
  13309. return NULL;
  13310. }
  13311. ok = 1;
  13312. for (fp = sw; fp->name != NULL; fp++) {
  13313. #if defined(_WIN32)
  13314. /* GetProcAddress() returns pointer to function */
  13315. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13316. #else
  13317. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13318. * pointers to function pointers. We need to use a union to make a
  13319. * cast. */
  13320. u.p = dlsym(dll_handle, fp->name);
  13321. #endif /* _WIN32 */
  13322. if (u.fp == NULL) {
  13323. if (ok) {
  13324. mg_snprintf(NULL,
  13325. &truncated,
  13326. ebuf,
  13327. ebuf_len,
  13328. "%s: %s: cannot find %s",
  13329. __func__,
  13330. dll_name,
  13331. fp->name);
  13332. ok = 0;
  13333. } else {
  13334. size_t cur_len = strlen(ebuf);
  13335. if (!truncated) {
  13336. mg_snprintf(NULL,
  13337. &truncated,
  13338. ebuf + cur_len,
  13339. ebuf_len - cur_len - 3,
  13340. ", %s",
  13341. fp->name);
  13342. if (truncated) {
  13343. /* If truncated, add "..." */
  13344. strcat(ebuf, "...");
  13345. }
  13346. }
  13347. }
  13348. /* Debug:
  13349. * printf("Missing function: %s\n", fp->name); */
  13350. } else {
  13351. fp->ptr = u.fp;
  13352. }
  13353. }
  13354. if (!ok) {
  13355. (void)dlclose(dll_handle);
  13356. return NULL;
  13357. }
  13358. return dll_handle;
  13359. }
  13360. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13361. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13362. #endif /* NO_SSL_DL */
  13363. #if defined(SSL_ALREADY_INITIALIZED)
  13364. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13365. #else
  13366. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13367. #endif
  13368. static int
  13369. initialize_ssl(char *ebuf, size_t ebuf_len)
  13370. {
  13371. #if defined(OPENSSL_API_1_1)
  13372. if (ebuf_len > 0) {
  13373. ebuf[0] = 0;
  13374. }
  13375. #if !defined(NO_SSL_DL)
  13376. if (!cryptolib_dll_handle) {
  13377. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13378. if (!cryptolib_dll_handle) {
  13379. mg_snprintf(NULL,
  13380. NULL, /* No truncation check for ebuf */
  13381. ebuf,
  13382. ebuf_len,
  13383. "%s: error loading library %s",
  13384. __func__,
  13385. CRYPTO_LIB);
  13386. DEBUG_TRACE("%s", ebuf);
  13387. return 0;
  13388. }
  13389. }
  13390. #endif /* NO_SSL_DL */
  13391. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13392. return 1;
  13393. }
  13394. #else /* not OPENSSL_API_1_1 */
  13395. int i, num_locks;
  13396. size_t size;
  13397. if (ebuf_len > 0) {
  13398. ebuf[0] = 0;
  13399. }
  13400. #if !defined(NO_SSL_DL)
  13401. if (!cryptolib_dll_handle) {
  13402. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13403. if (!cryptolib_dll_handle) {
  13404. mg_snprintf(NULL,
  13405. NULL, /* No truncation check for ebuf */
  13406. ebuf,
  13407. ebuf_len,
  13408. "%s: error loading library %s",
  13409. __func__,
  13410. CRYPTO_LIB);
  13411. DEBUG_TRACE("%s", ebuf);
  13412. return 0;
  13413. }
  13414. }
  13415. #endif /* NO_SSL_DL */
  13416. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13417. return 1;
  13418. }
  13419. /* Initialize locking callbacks, needed for thread safety.
  13420. * http://www.openssl.org/support/faq.html#PROG1
  13421. */
  13422. num_locks = CRYPTO_num_locks();
  13423. if (num_locks < 0) {
  13424. num_locks = 0;
  13425. }
  13426. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13427. /* allocate mutex array, if required */
  13428. if (num_locks == 0) {
  13429. /* No mutex array required */
  13430. ssl_mutexes = NULL;
  13431. } else {
  13432. /* Mutex array required - allocate it */
  13433. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13434. /* Check OOM */
  13435. if (ssl_mutexes == NULL) {
  13436. mg_snprintf(NULL,
  13437. NULL, /* No truncation check for ebuf */
  13438. ebuf,
  13439. ebuf_len,
  13440. "%s: cannot allocate mutexes: %s",
  13441. __func__,
  13442. ssl_error());
  13443. DEBUG_TRACE("%s", ebuf);
  13444. return 0;
  13445. }
  13446. /* initialize mutex array */
  13447. for (i = 0; i < num_locks; i++) {
  13448. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13449. mg_snprintf(NULL,
  13450. NULL, /* No truncation check for ebuf */
  13451. ebuf,
  13452. ebuf_len,
  13453. "%s: error initializing mutex %i of %i",
  13454. __func__,
  13455. i,
  13456. num_locks);
  13457. DEBUG_TRACE("%s", ebuf);
  13458. mg_free(ssl_mutexes);
  13459. return 0;
  13460. }
  13461. }
  13462. }
  13463. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13464. CRYPTO_set_id_callback(&mg_current_thread_id);
  13465. #endif /* OPENSSL_API_1_1 */
  13466. #if !defined(NO_SSL_DL)
  13467. if (!ssllib_dll_handle) {
  13468. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13469. if (!ssllib_dll_handle) {
  13470. #if !defined(OPENSSL_API_1_1)
  13471. mg_free(ssl_mutexes);
  13472. #endif
  13473. DEBUG_TRACE("%s", ebuf);
  13474. return 0;
  13475. }
  13476. }
  13477. #endif /* NO_SSL_DL */
  13478. #if defined(OPENSSL_API_1_1)
  13479. /* Initialize SSL library */
  13480. OPENSSL_init_ssl(0, NULL);
  13481. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13482. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13483. NULL);
  13484. #else
  13485. /* Initialize SSL library */
  13486. SSL_library_init();
  13487. SSL_load_error_strings();
  13488. #endif
  13489. return 1;
  13490. }
  13491. static int
  13492. ssl_use_pem_file(struct mg_context *phys_ctx,
  13493. struct mg_domain_context *dom_ctx,
  13494. const char *pem,
  13495. const char *chain)
  13496. {
  13497. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13498. mg_cry_ctx_internal(phys_ctx,
  13499. "%s: cannot open certificate file %s: %s",
  13500. __func__,
  13501. pem,
  13502. ssl_error());
  13503. return 0;
  13504. }
  13505. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13506. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13507. mg_cry_ctx_internal(phys_ctx,
  13508. "%s: cannot open private key file %s: %s",
  13509. __func__,
  13510. pem,
  13511. ssl_error());
  13512. return 0;
  13513. }
  13514. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13515. mg_cry_ctx_internal(phys_ctx,
  13516. "%s: certificate and private key do not match: %s",
  13517. __func__,
  13518. pem);
  13519. return 0;
  13520. }
  13521. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13522. * chain files that contain private keys and certificates in
  13523. * SSL_CTX_use_certificate_chain_file.
  13524. * The CivetWeb-Server used pem-Files that contained both information.
  13525. * In order to make wolfSSL work, it is split in two files.
  13526. * One file that contains key and certificate used by the server and
  13527. * an optional chain file for the ssl stack.
  13528. */
  13529. if (chain) {
  13530. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13531. mg_cry_ctx_internal(phys_ctx,
  13532. "%s: cannot use certificate chain file %s: %s",
  13533. __func__,
  13534. chain,
  13535. ssl_error());
  13536. return 0;
  13537. }
  13538. }
  13539. return 1;
  13540. }
  13541. #if defined(OPENSSL_API_1_1)
  13542. static unsigned long
  13543. ssl_get_protocol(int version_id)
  13544. {
  13545. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13546. if (version_id > 0)
  13547. ret |= SSL_OP_NO_SSLv2;
  13548. if (version_id > 1)
  13549. ret |= SSL_OP_NO_SSLv3;
  13550. if (version_id > 2)
  13551. ret |= SSL_OP_NO_TLSv1;
  13552. if (version_id > 3)
  13553. ret |= SSL_OP_NO_TLSv1_1;
  13554. if (version_id > 4)
  13555. ret |= SSL_OP_NO_TLSv1_2;
  13556. #if defined(SSL_OP_NO_TLSv1_3)
  13557. if (version_id > 5)
  13558. ret |= SSL_OP_NO_TLSv1_3;
  13559. #endif
  13560. return ret;
  13561. }
  13562. #else
  13563. static long
  13564. ssl_get_protocol(int version_id)
  13565. {
  13566. long ret = (long)SSL_OP_ALL;
  13567. if (version_id > 0)
  13568. ret |= SSL_OP_NO_SSLv2;
  13569. if (version_id > 1)
  13570. ret |= SSL_OP_NO_SSLv3;
  13571. if (version_id > 2)
  13572. ret |= SSL_OP_NO_TLSv1;
  13573. if (version_id > 3)
  13574. ret |= SSL_OP_NO_TLSv1_1;
  13575. if (version_id > 4)
  13576. ret |= SSL_OP_NO_TLSv1_2;
  13577. #if defined(SSL_OP_NO_TLSv1_3)
  13578. if (version_id > 5)
  13579. ret |= SSL_OP_NO_TLSv1_3;
  13580. #endif
  13581. return ret;
  13582. }
  13583. #endif /* OPENSSL_API_1_1 */
  13584. /* SSL callback documentation:
  13585. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13586. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13587. * https://linux.die.net/man/3/ssl_set_info_callback */
  13588. /* Note: There is no "const" for the first argument in the documentation
  13589. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13590. * / OpenSSL compatibility layers have it. Having a different definition will
  13591. * cause a warning in C and an error in C++. Use "const SSL *", while
  13592. * automatical conversion from "SSL *" works for all compilers, but not other
  13593. * way around */
  13594. static void
  13595. ssl_info_callback(const SSL *ssl, int what, int ret)
  13596. {
  13597. (void)ret;
  13598. if (what & SSL_CB_HANDSHAKE_START) {
  13599. SSL_get_app_data(ssl);
  13600. }
  13601. if (what & SSL_CB_HANDSHAKE_DONE) {
  13602. /* TODO: check for openSSL 1.1 */
  13603. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13604. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13605. }
  13606. }
  13607. static int
  13608. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13609. {
  13610. struct mg_context *ctx = (struct mg_context *)arg;
  13611. struct mg_domain_context *dom =
  13612. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13613. #if defined(GCC_DIAGNOSTIC)
  13614. #pragma GCC diagnostic push
  13615. #pragma GCC diagnostic ignored "-Wcast-align"
  13616. #endif /* defined(GCC_DIAGNOSTIC) */
  13617. /* We used an aligned pointer in SSL_set_app_data */
  13618. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13619. #if defined(GCC_DIAGNOSTIC)
  13620. #pragma GCC diagnostic pop
  13621. #endif /* defined(GCC_DIAGNOSTIC) */
  13622. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13623. (void)ad;
  13624. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13625. DEBUG_TRACE("%s", "internal error - assertion failed");
  13626. return SSL_TLSEXT_ERR_NOACK;
  13627. }
  13628. /* Old clients (Win XP) will not support SNI. Then, there
  13629. * is no server name available in the request - we can
  13630. * only work with the default certificate.
  13631. * Multiple HTTPS hosts on one IP+port are only possible
  13632. * with a certificate containing all alternative names.
  13633. */
  13634. if ((servername == NULL) || (*servername == 0)) {
  13635. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13636. conn->dom_ctx = &(ctx->dd);
  13637. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13638. return SSL_TLSEXT_ERR_NOACK;
  13639. }
  13640. DEBUG_TRACE("TLS connection to host %s", servername);
  13641. while (dom) {
  13642. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13643. /* Found matching domain */
  13644. DEBUG_TRACE("TLS domain %s found",
  13645. dom->config[AUTHENTICATION_DOMAIN]);
  13646. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13647. conn->dom_ctx = dom;
  13648. return SSL_TLSEXT_ERR_OK;
  13649. }
  13650. dom = dom->next;
  13651. }
  13652. /* Default domain */
  13653. DEBUG_TRACE("TLS default domain %s used",
  13654. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13655. conn->dom_ctx = &(ctx->dd);
  13656. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13657. return SSL_TLSEXT_ERR_OK;
  13658. }
  13659. /* Setup SSL CTX as required by CivetWeb */
  13660. static int
  13661. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13662. struct mg_domain_context *dom_ctx,
  13663. const char *pem,
  13664. const char *chain)
  13665. {
  13666. int callback_ret;
  13667. int should_verify_peer;
  13668. int peer_certificate_optional;
  13669. const char *ca_path;
  13670. const char *ca_file;
  13671. int use_default_verify_paths;
  13672. int verify_depth;
  13673. struct timespec now_mt;
  13674. md5_byte_t ssl_context_id[16];
  13675. md5_state_t md5state;
  13676. int protocol_ver;
  13677. #if defined(OPENSSL_API_1_1)
  13678. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13679. mg_cry_ctx_internal(phys_ctx,
  13680. "SSL_CTX_new (server) error: %s",
  13681. ssl_error());
  13682. return 0;
  13683. }
  13684. #else
  13685. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13686. mg_cry_ctx_internal(phys_ctx,
  13687. "SSL_CTX_new (server) error: %s",
  13688. ssl_error());
  13689. return 0;
  13690. }
  13691. #endif /* OPENSSL_API_1_1 */
  13692. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13693. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13694. | SSL_OP_NO_TLSv1_1);
  13695. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13696. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13697. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13698. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13699. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13700. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13701. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13702. #if defined(SSL_OP_NO_RENEGOTIATION)
  13703. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  13704. #endif
  13705. #if !defined(NO_SSL_DL)
  13706. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13707. #endif /* NO_SSL_DL */
  13708. /* In SSL documentation examples callback defined without const specifier
  13709. * 'void (*)(SSL *, int, int)' See:
  13710. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13711. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13712. * But in the source code const SSL is used:
  13713. * 'void (*)(const SSL *, int, int)' See:
  13714. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13715. * Problem about wrong documentation described, but not resolved:
  13716. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13717. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13718. * But when compiled with modern C++ compiler, correct const should be
  13719. * provided
  13720. */
  13721. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13722. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13723. ssl_servername_callback);
  13724. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13725. /* If a callback has been specified, call it. */
  13726. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13727. ? 0
  13728. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13729. phys_ctx->user_data));
  13730. /* If callback returns 0, civetweb sets up the SSL certificate.
  13731. * If it returns 1, civetweb assumes the calback already did this.
  13732. * If it returns -1, initializing ssl fails. */
  13733. if (callback_ret < 0) {
  13734. mg_cry_ctx_internal(phys_ctx,
  13735. "SSL callback returned error: %i",
  13736. callback_ret);
  13737. return 0;
  13738. }
  13739. if (callback_ret > 0) {
  13740. /* Callback did everything. */
  13741. return 1;
  13742. }
  13743. /* Use some combination of start time, domain and port as a SSL
  13744. * context ID. This should be unique on the current machine. */
  13745. md5_init(&md5state);
  13746. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13747. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13748. md5_append(&md5state,
  13749. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13750. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13751. md5_append(&md5state,
  13752. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13753. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13754. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13755. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13756. md5_finish(&md5state, ssl_context_id);
  13757. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13758. (unsigned char *)ssl_context_id,
  13759. sizeof(ssl_context_id));
  13760. if (pem != NULL) {
  13761. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13762. return 0;
  13763. }
  13764. }
  13765. /* Should we support client certificates? */
  13766. /* Default is "no". */
  13767. should_verify_peer = 0;
  13768. peer_certificate_optional = 0;
  13769. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13770. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13771. /* Yes, they are mandatory */
  13772. should_verify_peer = 1;
  13773. peer_certificate_optional = 0;
  13774. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13775. "optional")
  13776. == 0) {
  13777. /* Yes, they are optional */
  13778. should_verify_peer = 1;
  13779. peer_certificate_optional = 1;
  13780. }
  13781. }
  13782. use_default_verify_paths =
  13783. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13784. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13785. == 0);
  13786. if (should_verify_peer) {
  13787. ca_path = dom_ctx->config[SSL_CA_PATH];
  13788. ca_file = dom_ctx->config[SSL_CA_FILE];
  13789. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13790. != 1) {
  13791. mg_cry_ctx_internal(phys_ctx,
  13792. "SSL_CTX_load_verify_locations error: %s "
  13793. "ssl_verify_peer requires setting "
  13794. "either ssl_ca_path or ssl_ca_file. "
  13795. "Is any of them present in the "
  13796. ".conf file?",
  13797. ssl_error());
  13798. return 0;
  13799. }
  13800. if (peer_certificate_optional) {
  13801. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13802. } else {
  13803. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13804. SSL_VERIFY_PEER
  13805. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13806. NULL);
  13807. }
  13808. if (use_default_verify_paths
  13809. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13810. mg_cry_ctx_internal(phys_ctx,
  13811. "SSL_CTX_set_default_verify_paths error: %s",
  13812. ssl_error());
  13813. return 0;
  13814. }
  13815. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13816. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13817. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13818. }
  13819. }
  13820. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13821. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13822. dom_ctx->config[SSL_CIPHER_LIST])
  13823. != 1) {
  13824. mg_cry_ctx_internal(phys_ctx,
  13825. "SSL_CTX_set_cipher_list error: %s",
  13826. ssl_error());
  13827. }
  13828. }
  13829. return 1;
  13830. }
  13831. /* Check if SSL is required.
  13832. * If so, dynamically load SSL library
  13833. * and set up ctx->ssl_ctx pointer. */
  13834. static int
  13835. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13836. {
  13837. void *ssl_ctx = 0;
  13838. int callback_ret;
  13839. const char *pem;
  13840. const char *chain;
  13841. char ebuf[128];
  13842. if (!phys_ctx) {
  13843. return 0;
  13844. }
  13845. if (!dom_ctx) {
  13846. dom_ctx = &(phys_ctx->dd);
  13847. }
  13848. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13849. /* No SSL port is set. No need to setup SSL. */
  13850. return 1;
  13851. }
  13852. /* Check for external SSL_CTX */
  13853. callback_ret =
  13854. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13855. ? 0
  13856. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13857. phys_ctx->user_data));
  13858. if (callback_ret < 0) {
  13859. mg_cry_ctx_internal(phys_ctx,
  13860. "external_ssl_ctx callback returned error: %i",
  13861. callback_ret);
  13862. return 0;
  13863. } else if (callback_ret > 0) {
  13864. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13865. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13866. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  13867. return 0;
  13868. }
  13869. return 1;
  13870. }
  13871. /* else: external_ssl_ctx does not exist or returns 0,
  13872. * CivetWeb should continue initializing SSL */
  13873. /* If PEM file is not specified and the init_ssl callback
  13874. * is not specified, setup will fail. */
  13875. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13876. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13877. /* No certificate and no callback:
  13878. * Essential data to set up TLS is missing.
  13879. */
  13880. mg_cry_ctx_internal(phys_ctx,
  13881. "Initializing SSL failed: -%s is not set",
  13882. config_options[SSL_CERTIFICATE].name);
  13883. return 0;
  13884. }
  13885. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13886. if (chain == NULL) {
  13887. chain = pem;
  13888. }
  13889. if ((chain != NULL) && (*chain == 0)) {
  13890. chain = NULL;
  13891. }
  13892. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13893. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  13894. return 0;
  13895. }
  13896. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13897. }
  13898. static void
  13899. uninitialize_ssl(void)
  13900. {
  13901. #if defined(OPENSSL_API_1_1)
  13902. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13903. /* Shutdown according to
  13904. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13905. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13906. */
  13907. CONF_modules_unload(1);
  13908. #else
  13909. int i;
  13910. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13911. /* Shutdown according to
  13912. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13913. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13914. */
  13915. CRYPTO_set_locking_callback(NULL);
  13916. CRYPTO_set_id_callback(NULL);
  13917. ENGINE_cleanup();
  13918. CONF_modules_unload(1);
  13919. ERR_free_strings();
  13920. EVP_cleanup();
  13921. CRYPTO_cleanup_all_ex_data();
  13922. OPENSSL_REMOVE_THREAD_STATE();
  13923. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13924. pthread_mutex_destroy(&ssl_mutexes[i]);
  13925. }
  13926. mg_free(ssl_mutexes);
  13927. ssl_mutexes = NULL;
  13928. #endif /* OPENSSL_API_1_1 */
  13929. }
  13930. }
  13931. #endif /* !NO_SSL */
  13932. #if !defined(NO_FILESYSTEMS)
  13933. static int
  13934. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13935. {
  13936. if (phys_ctx) {
  13937. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13938. const char *path;
  13939. struct mg_connection fc;
  13940. if (!dom_ctx) {
  13941. dom_ctx = &(phys_ctx->dd);
  13942. }
  13943. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13944. if ((path != NULL)
  13945. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  13946. mg_cry_ctx_internal(phys_ctx,
  13947. "Cannot open %s: %s",
  13948. path,
  13949. strerror(ERRNO));
  13950. return 0;
  13951. }
  13952. return 1;
  13953. }
  13954. return 0;
  13955. }
  13956. #endif /* NO_FILESYSTEMS */
  13957. static int
  13958. set_acl_option(struct mg_context *phys_ctx)
  13959. {
  13960. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13961. }
  13962. static void
  13963. reset_per_request_attributes(struct mg_connection *conn)
  13964. {
  13965. if (!conn) {
  13966. return;
  13967. }
  13968. conn->connection_type =
  13969. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13970. conn->num_bytes_sent = conn->consumed_content = 0;
  13971. conn->path_info = NULL;
  13972. conn->status_code = -1;
  13973. conn->content_len = -1;
  13974. conn->is_chunked = 0;
  13975. conn->must_close = 0;
  13976. conn->request_len = 0;
  13977. conn->throttle = 0;
  13978. conn->accept_gzip = 0;
  13979. conn->response_info.content_length = conn->request_info.content_length = -1;
  13980. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13981. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13982. conn->response_info.status_text = NULL;
  13983. conn->response_info.status_code = 0;
  13984. conn->request_info.remote_user = NULL;
  13985. conn->request_info.request_method = NULL;
  13986. conn->request_info.request_uri = NULL;
  13987. conn->request_info.local_uri = NULL;
  13988. #if defined(MG_LEGACY_INTERFACE)
  13989. /* Legacy before split into local_uri and request_uri */
  13990. conn->request_info.uri = NULL;
  13991. #endif
  13992. }
  13993. static int
  13994. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13995. {
  13996. if (setsockopt(sock,
  13997. IPPROTO_TCP,
  13998. TCP_NODELAY,
  13999. (SOCK_OPT_TYPE)&nodelay_on,
  14000. sizeof(nodelay_on))
  14001. != 0) {
  14002. /* Error */
  14003. return 1;
  14004. }
  14005. /* OK */
  14006. return 0;
  14007. }
  14008. #if !defined(__ZEPHYR__)
  14009. static void
  14010. close_socket_gracefully(struct mg_connection *conn)
  14011. {
  14012. #if defined(_WIN32)
  14013. char buf[MG_BUF_LEN];
  14014. int n;
  14015. #endif
  14016. struct linger linger;
  14017. int error_code = 0;
  14018. int linger_timeout = -2;
  14019. socklen_t opt_len = sizeof(error_code);
  14020. if (!conn) {
  14021. return;
  14022. }
  14023. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14024. * "Note that enabling a nonzero timeout on a nonblocking socket
  14025. * is not recommended.", so set it to blocking now */
  14026. set_blocking_mode(conn->client.sock);
  14027. /* Send FIN to the client */
  14028. shutdown(conn->client.sock, SHUTDOWN_WR);
  14029. #if defined(_WIN32)
  14030. /* Read and discard pending incoming data. If we do not do that and
  14031. * close
  14032. * the socket, the data in the send buffer may be discarded. This
  14033. * behaviour is seen on Windows, when client keeps sending data
  14034. * when server decides to close the connection; then when client
  14035. * does recv() it gets no data back. */
  14036. do {
  14037. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14038. } while (n > 0);
  14039. #endif
  14040. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14041. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14042. }
  14043. /* Set linger option according to configuration */
  14044. if (linger_timeout >= 0) {
  14045. /* Set linger option to avoid socket hanging out after close. This
  14046. * prevent ephemeral port exhaust problem under high QPS. */
  14047. linger.l_onoff = 1;
  14048. #if defined(_MSC_VER)
  14049. #pragma warning(push)
  14050. #pragma warning(disable : 4244)
  14051. #endif
  14052. #if defined(GCC_DIAGNOSTIC)
  14053. #pragma GCC diagnostic push
  14054. #pragma GCC diagnostic ignored "-Wconversion"
  14055. #endif
  14056. /* Data type of linger structure elements may differ,
  14057. * so we don't know what cast we need here.
  14058. * Disable type conversion warnings. */
  14059. linger.l_linger = (linger_timeout + 999) / 1000;
  14060. #if defined(GCC_DIAGNOSTIC)
  14061. #pragma GCC diagnostic pop
  14062. #endif
  14063. #if defined(_MSC_VER)
  14064. #pragma warning(pop)
  14065. #endif
  14066. } else {
  14067. linger.l_onoff = 0;
  14068. linger.l_linger = 0;
  14069. }
  14070. if (linger_timeout < -1) {
  14071. /* Default: don't configure any linger */
  14072. } else if (getsockopt(conn->client.sock,
  14073. SOL_SOCKET,
  14074. SO_ERROR,
  14075. #if defined(_WIN32) /* WinSock uses different data type here */
  14076. (char *)&error_code,
  14077. #else
  14078. &error_code,
  14079. #endif
  14080. &opt_len)
  14081. != 0) {
  14082. /* Cannot determine if socket is already closed. This should
  14083. * not occur and never did in a test. Log an error message
  14084. * and continue. */
  14085. mg_cry_internal(conn,
  14086. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14087. __func__,
  14088. strerror(ERRNO));
  14089. #if defined(_WIN32)
  14090. } else if (error_code == WSAECONNRESET) {
  14091. #else
  14092. } else if (error_code == ECONNRESET) {
  14093. #endif
  14094. /* Socket already closed by client/peer, close socket without linger
  14095. */
  14096. } else {
  14097. /* Set linger timeout */
  14098. if (setsockopt(conn->client.sock,
  14099. SOL_SOCKET,
  14100. SO_LINGER,
  14101. (char *)&linger,
  14102. sizeof(linger))
  14103. != 0) {
  14104. mg_cry_internal(
  14105. conn,
  14106. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14107. __func__,
  14108. linger.l_onoff,
  14109. linger.l_linger,
  14110. strerror(ERRNO));
  14111. }
  14112. }
  14113. /* Now we know that our FIN is ACK-ed, safe to close */
  14114. closesocket(conn->client.sock);
  14115. conn->client.sock = INVALID_SOCKET;
  14116. }
  14117. #endif
  14118. static void
  14119. close_connection(struct mg_connection *conn)
  14120. {
  14121. #if defined(USE_SERVER_STATS)
  14122. conn->conn_state = 6; /* to close */
  14123. #endif
  14124. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14125. if (conn->lua_websocket_state) {
  14126. lua_websocket_close(conn, conn->lua_websocket_state);
  14127. conn->lua_websocket_state = NULL;
  14128. }
  14129. #endif
  14130. mg_lock_connection(conn);
  14131. /* Set close flag, so keep-alive loops will stop */
  14132. conn->must_close = 1;
  14133. /* call the connection_close callback if assigned */
  14134. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14135. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14136. conn->phys_ctx->callbacks.connection_close(conn);
  14137. }
  14138. }
  14139. /* Reset user data, after close callback is called.
  14140. * Do not reuse it. If the user needs a destructor,
  14141. * it must be done in the connection_close callback. */
  14142. mg_set_user_connection_data(conn, NULL);
  14143. #if defined(USE_SERVER_STATS)
  14144. conn->conn_state = 7; /* closing */
  14145. #endif
  14146. #if !defined(NO_SSL)
  14147. if (conn->ssl != NULL) {
  14148. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14149. */
  14150. SSL_shutdown(conn->ssl);
  14151. SSL_free(conn->ssl);
  14152. OPENSSL_REMOVE_THREAD_STATE();
  14153. conn->ssl = NULL;
  14154. }
  14155. #endif
  14156. if (conn->client.sock != INVALID_SOCKET) {
  14157. #if defined(__ZEPHYR__)
  14158. closesocket(conn->client.sock);
  14159. #else
  14160. close_socket_gracefully(conn);
  14161. #endif
  14162. conn->client.sock = INVALID_SOCKET;
  14163. }
  14164. if (conn->host) {
  14165. mg_free((void *)conn->host);
  14166. conn->host = NULL;
  14167. }
  14168. mg_unlock_connection(conn);
  14169. #if defined(USE_SERVER_STATS)
  14170. conn->conn_state = 8; /* closed */
  14171. #endif
  14172. }
  14173. void
  14174. mg_close_connection(struct mg_connection *conn)
  14175. {
  14176. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14177. return;
  14178. }
  14179. #if defined(USE_WEBSOCKET)
  14180. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14181. if (conn->in_websocket_handling) {
  14182. /* Set close flag, so the server thread can exit. */
  14183. conn->must_close = 1;
  14184. return;
  14185. }
  14186. }
  14187. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14188. unsigned int i;
  14189. /* client context: loops must end */
  14190. conn->phys_ctx->stop_flag = 1;
  14191. conn->must_close = 1;
  14192. /* We need to get the client thread out of the select/recv call
  14193. * here. */
  14194. /* Since we use a sleep quantum of some seconds to check for recv
  14195. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14196. /* join worker thread */
  14197. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14198. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14199. }
  14200. }
  14201. #endif /* defined(USE_WEBSOCKET) */
  14202. close_connection(conn);
  14203. #if !defined(NO_SSL)
  14204. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14205. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14206. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14207. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14208. }
  14209. #endif
  14210. #if defined(USE_WEBSOCKET)
  14211. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14212. mg_free(conn->phys_ctx->worker_threadids);
  14213. (void)pthread_mutex_destroy(&conn->mutex);
  14214. mg_free(conn);
  14215. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14216. mg_free(conn);
  14217. }
  14218. #else
  14219. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14220. mg_free(conn);
  14221. }
  14222. #endif /* defined(USE_WEBSOCKET) */
  14223. }
  14224. static struct mg_connection *
  14225. mg_connect_client_impl(const struct mg_client_options *client_options,
  14226. int use_ssl,
  14227. char *ebuf,
  14228. size_t ebuf_len)
  14229. {
  14230. struct mg_connection *conn = NULL;
  14231. SOCKET sock;
  14232. union usa sa;
  14233. struct sockaddr *psa;
  14234. socklen_t len;
  14235. unsigned max_req_size =
  14236. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14237. /* Size of structures, aligned to 8 bytes */
  14238. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14239. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14240. conn =
  14241. (struct mg_connection *)mg_calloc(1,
  14242. conn_size + ctx_size + max_req_size);
  14243. if (conn == NULL) {
  14244. mg_snprintf(NULL,
  14245. NULL, /* No truncation check for ebuf */
  14246. ebuf,
  14247. ebuf_len,
  14248. "calloc(): %s",
  14249. strerror(ERRNO));
  14250. return NULL;
  14251. }
  14252. #if defined(GCC_DIAGNOSTIC)
  14253. #pragma GCC diagnostic push
  14254. #pragma GCC diagnostic ignored "-Wcast-align"
  14255. #endif /* defined(GCC_DIAGNOSTIC) */
  14256. /* conn_size is aligned to 8 bytes */
  14257. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14258. #if defined(GCC_DIAGNOSTIC)
  14259. #pragma GCC diagnostic pop
  14260. #endif /* defined(GCC_DIAGNOSTIC) */
  14261. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14262. conn->buf_size = (int)max_req_size;
  14263. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14264. conn->dom_ctx = &(conn->phys_ctx->dd);
  14265. if (!connect_socket(conn->phys_ctx,
  14266. client_options->host,
  14267. client_options->port,
  14268. use_ssl,
  14269. ebuf,
  14270. ebuf_len,
  14271. &sock,
  14272. &sa)) {
  14273. /* ebuf is set by connect_socket,
  14274. * free all memory and return NULL; */
  14275. mg_free(conn);
  14276. return NULL;
  14277. }
  14278. #if !defined(NO_SSL)
  14279. #if defined(OPENSSL_API_1_1)
  14280. if (use_ssl
  14281. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14282. == NULL) {
  14283. mg_snprintf(NULL,
  14284. NULL, /* No truncation check for ebuf */
  14285. ebuf,
  14286. ebuf_len,
  14287. "SSL_CTX_new error: %s",
  14288. ssl_error());
  14289. closesocket(sock);
  14290. mg_free(conn);
  14291. return NULL;
  14292. }
  14293. #else
  14294. if (use_ssl
  14295. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14296. == NULL) {
  14297. mg_snprintf(NULL,
  14298. NULL, /* No truncation check for ebuf */
  14299. ebuf,
  14300. ebuf_len,
  14301. "SSL_CTX_new error: %s",
  14302. ssl_error());
  14303. closesocket(sock);
  14304. mg_free(conn);
  14305. return NULL;
  14306. }
  14307. #endif /* OPENSSL_API_1_1 */
  14308. #endif /* NO_SSL */
  14309. #if defined(USE_IPV6)
  14310. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14311. : sizeof(conn->client.rsa.sin6);
  14312. psa = (sa.sa.sa_family == AF_INET)
  14313. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14314. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14315. #else
  14316. len = sizeof(conn->client.rsa.sin);
  14317. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14318. #endif
  14319. conn->client.sock = sock;
  14320. conn->client.lsa = sa;
  14321. if (getsockname(sock, psa, &len) != 0) {
  14322. mg_cry_internal(conn,
  14323. "%s: getsockname() failed: %s",
  14324. __func__,
  14325. strerror(ERRNO));
  14326. }
  14327. conn->client.is_ssl = use_ssl ? 1 : 0;
  14328. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14329. mg_snprintf(NULL,
  14330. NULL, /* No truncation check for ebuf */
  14331. ebuf,
  14332. ebuf_len,
  14333. "Can not create mutex");
  14334. #if !defined(NO_SSL)
  14335. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14336. #endif
  14337. closesocket(sock);
  14338. mg_free(conn);
  14339. return NULL;
  14340. }
  14341. #if !defined(NO_SSL)
  14342. if (use_ssl) {
  14343. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14344. * SSL_CTX_set_verify call is needed to switch off server
  14345. * certificate checking, which is off by default in OpenSSL and
  14346. * on in yaSSL. */
  14347. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14348. * SSL_VERIFY_PEER, verify_ssl_server); */
  14349. if (client_options->client_cert) {
  14350. if (!ssl_use_pem_file(conn->phys_ctx,
  14351. conn->dom_ctx,
  14352. client_options->client_cert,
  14353. NULL)) {
  14354. mg_snprintf(NULL,
  14355. NULL, /* No truncation check for ebuf */
  14356. ebuf,
  14357. ebuf_len,
  14358. "Can not use SSL client certificate");
  14359. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14360. closesocket(sock);
  14361. mg_free(conn);
  14362. return NULL;
  14363. }
  14364. }
  14365. if (client_options->server_cert) {
  14366. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14367. client_options->server_cert,
  14368. NULL)
  14369. != 1) {
  14370. mg_cry_internal(conn,
  14371. "SSL_CTX_load_verify_locations error: %s ",
  14372. ssl_error());
  14373. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14374. closesocket(sock);
  14375. mg_free(conn);
  14376. return NULL;
  14377. }
  14378. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14379. } else {
  14380. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14381. }
  14382. if (!sslize(conn,
  14383. conn->dom_ctx->ssl_ctx,
  14384. SSL_connect,
  14385. &(conn->phys_ctx->stop_flag),
  14386. client_options)) {
  14387. mg_snprintf(NULL,
  14388. NULL, /* No truncation check for ebuf */
  14389. ebuf,
  14390. ebuf_len,
  14391. "SSL connection error");
  14392. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14393. closesocket(sock);
  14394. mg_free(conn);
  14395. return NULL;
  14396. }
  14397. }
  14398. #endif
  14399. return conn;
  14400. }
  14401. CIVETWEB_API struct mg_connection *
  14402. mg_connect_client_secure(const struct mg_client_options *client_options,
  14403. char *error_buffer,
  14404. size_t error_buffer_size)
  14405. {
  14406. return mg_connect_client_impl(client_options,
  14407. 1,
  14408. error_buffer,
  14409. error_buffer_size);
  14410. }
  14411. struct mg_connection *
  14412. mg_connect_client(const char *host,
  14413. int port,
  14414. int use_ssl,
  14415. char *error_buffer,
  14416. size_t error_buffer_size)
  14417. {
  14418. struct mg_client_options opts;
  14419. memset(&opts, 0, sizeof(opts));
  14420. opts.host = host;
  14421. opts.port = port;
  14422. return mg_connect_client_impl(&opts,
  14423. use_ssl,
  14424. error_buffer,
  14425. error_buffer_size);
  14426. }
  14427. static const struct {
  14428. const char *proto;
  14429. size_t proto_len;
  14430. unsigned default_port;
  14431. } abs_uri_protocols[] = {{"http://", 7, 80},
  14432. {"https://", 8, 443},
  14433. {"ws://", 5, 80},
  14434. {"wss://", 6, 443},
  14435. {NULL, 0, 0}};
  14436. /* Check if the uri is valid.
  14437. * return 0 for invalid uri,
  14438. * return 1 for *,
  14439. * return 2 for relative uri,
  14440. * return 3 for absolute uri without port,
  14441. * return 4 for absolute uri with port */
  14442. static int
  14443. get_uri_type(const char *uri)
  14444. {
  14445. int i;
  14446. const char *hostend, *portbegin;
  14447. char *portend;
  14448. unsigned long port;
  14449. /* According to the HTTP standard
  14450. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14451. * URI can be an asterisk (*) or should start with slash (relative uri),
  14452. * or it should start with the protocol (absolute uri). */
  14453. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14454. /* asterisk */
  14455. return 1;
  14456. }
  14457. /* Valid URIs according to RFC 3986
  14458. * (https://www.ietf.org/rfc/rfc3986.txt)
  14459. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14460. * and unreserved characters A-Z a-z 0-9 and -._~
  14461. * and % encoded symbols.
  14462. */
  14463. for (i = 0; uri[i] != 0; i++) {
  14464. if (uri[i] < 33) {
  14465. /* control characters and spaces are invalid */
  14466. return 0;
  14467. }
  14468. if (uri[i] > 126) {
  14469. /* non-ascii characters must be % encoded */
  14470. return 0;
  14471. } else {
  14472. switch (uri[i]) {
  14473. case '"': /* 34 */
  14474. case '<': /* 60 */
  14475. case '>': /* 62 */
  14476. case '\\': /* 92 */
  14477. case '^': /* 94 */
  14478. case '`': /* 96 */
  14479. case '{': /* 123 */
  14480. case '|': /* 124 */
  14481. case '}': /* 125 */
  14482. return 0;
  14483. default:
  14484. /* character is ok */
  14485. break;
  14486. }
  14487. }
  14488. }
  14489. /* A relative uri starts with a / character */
  14490. if (uri[0] == '/') {
  14491. /* relative uri */
  14492. return 2;
  14493. }
  14494. /* It could be an absolute uri: */
  14495. /* This function only checks if the uri is valid, not if it is
  14496. * addressing the current server. So civetweb can also be used
  14497. * as a proxy server. */
  14498. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14499. if (mg_strncasecmp(uri,
  14500. abs_uri_protocols[i].proto,
  14501. abs_uri_protocols[i].proto_len)
  14502. == 0) {
  14503. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14504. if (!hostend) {
  14505. return 0;
  14506. }
  14507. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14508. if (!portbegin) {
  14509. return 3;
  14510. }
  14511. port = strtoul(portbegin + 1, &portend, 10);
  14512. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14513. return 0;
  14514. }
  14515. return 4;
  14516. }
  14517. }
  14518. return 0;
  14519. }
  14520. /* Return NULL or the relative uri at the current server */
  14521. static const char *
  14522. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14523. {
  14524. const char *server_domain;
  14525. size_t server_domain_len;
  14526. size_t request_domain_len = 0;
  14527. unsigned long port = 0;
  14528. int i, auth_domain_check_enabled;
  14529. const char *hostbegin = NULL;
  14530. const char *hostend = NULL;
  14531. const char *portbegin;
  14532. char *portend;
  14533. auth_domain_check_enabled =
  14534. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14535. /* DNS is case insensitive, so use case insensitive string compare here
  14536. */
  14537. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14538. if (mg_strncasecmp(uri,
  14539. abs_uri_protocols[i].proto,
  14540. abs_uri_protocols[i].proto_len)
  14541. == 0) {
  14542. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14543. hostend = strchr(hostbegin, '/');
  14544. if (!hostend) {
  14545. return 0;
  14546. }
  14547. portbegin = strchr(hostbegin, ':');
  14548. if ((!portbegin) || (portbegin > hostend)) {
  14549. port = abs_uri_protocols[i].default_port;
  14550. request_domain_len = (size_t)(hostend - hostbegin);
  14551. } else {
  14552. port = strtoul(portbegin + 1, &portend, 10);
  14553. if ((portend != hostend) || (port <= 0)
  14554. || !is_valid_port(port)) {
  14555. return 0;
  14556. }
  14557. request_domain_len = (size_t)(portbegin - hostbegin);
  14558. }
  14559. /* protocol found, port set */
  14560. break;
  14561. }
  14562. }
  14563. if (!port) {
  14564. /* port remains 0 if the protocol is not found */
  14565. return 0;
  14566. }
  14567. /* Check if the request is directed to a different server. */
  14568. /* First check if the port is the same (IPv4 and IPv6). */
  14569. #if defined(USE_IPV6)
  14570. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14571. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14572. /* Request is directed to a different port */
  14573. return 0;
  14574. }
  14575. } else
  14576. #endif
  14577. {
  14578. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14579. /* Request is directed to a different port */
  14580. return 0;
  14581. }
  14582. }
  14583. /* Finally check if the server corresponds to the authentication
  14584. * domain of the server (the server domain).
  14585. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14586. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14587. * but do not allow substrings (like
  14588. * http://notmydomain.com/path/file.ext
  14589. * or http://mydomain.com.fake/path/file.ext).
  14590. */
  14591. if (auth_domain_check_enabled) {
  14592. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14593. server_domain_len = strlen(server_domain);
  14594. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14595. return 0;
  14596. }
  14597. if ((request_domain_len == server_domain_len)
  14598. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14599. /* Request is directed to this server - full name match. */
  14600. } else {
  14601. if (request_domain_len < (server_domain_len + 2)) {
  14602. /* Request is directed to another server: The server name
  14603. * is longer than the request name.
  14604. * Drop this case here to avoid overflows in the
  14605. * following checks. */
  14606. return 0;
  14607. }
  14608. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14609. /* Request is directed to another server: It could be a
  14610. * substring
  14611. * like notmyserver.com */
  14612. return 0;
  14613. }
  14614. if (0
  14615. != memcmp(server_domain,
  14616. hostbegin + request_domain_len - server_domain_len,
  14617. server_domain_len)) {
  14618. /* Request is directed to another server:
  14619. * The server name is different. */
  14620. return 0;
  14621. }
  14622. }
  14623. }
  14624. return hostend;
  14625. }
  14626. static int
  14627. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14628. {
  14629. if (ebuf_len > 0) {
  14630. ebuf[0] = '\0';
  14631. }
  14632. *err = 0;
  14633. reset_per_request_attributes(conn);
  14634. if (!conn) {
  14635. mg_snprintf(conn,
  14636. NULL, /* No truncation check for ebuf */
  14637. ebuf,
  14638. ebuf_len,
  14639. "%s",
  14640. "Internal error");
  14641. *err = 500;
  14642. return 0;
  14643. }
  14644. /* Set the time the request was received. This value should be used for
  14645. * timeouts. */
  14646. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14647. conn->request_len =
  14648. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14649. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14650. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14651. mg_snprintf(conn,
  14652. NULL, /* No truncation check for ebuf */
  14653. ebuf,
  14654. ebuf_len,
  14655. "%s",
  14656. "Invalid message size");
  14657. *err = 500;
  14658. return 0;
  14659. }
  14660. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14661. mg_snprintf(conn,
  14662. NULL, /* No truncation check for ebuf */
  14663. ebuf,
  14664. ebuf_len,
  14665. "%s",
  14666. "Message too large");
  14667. *err = 413;
  14668. return 0;
  14669. }
  14670. if (conn->request_len <= 0) {
  14671. if (conn->data_len > 0) {
  14672. mg_snprintf(conn,
  14673. NULL, /* No truncation check for ebuf */
  14674. ebuf,
  14675. ebuf_len,
  14676. "%s",
  14677. "Malformed message");
  14678. *err = 400;
  14679. } else {
  14680. /* Server did not recv anything -> just close the connection */
  14681. conn->must_close = 1;
  14682. mg_snprintf(conn,
  14683. NULL, /* No truncation check for ebuf */
  14684. ebuf,
  14685. ebuf_len,
  14686. "%s",
  14687. "No data received");
  14688. *err = 0;
  14689. }
  14690. return 0;
  14691. }
  14692. return 1;
  14693. }
  14694. static int
  14695. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14696. {
  14697. const char *cl;
  14698. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14699. return 0;
  14700. }
  14701. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14702. <= 0) {
  14703. mg_snprintf(conn,
  14704. NULL, /* No truncation check for ebuf */
  14705. ebuf,
  14706. ebuf_len,
  14707. "%s",
  14708. "Bad request");
  14709. *err = 400;
  14710. return 0;
  14711. }
  14712. /* Message is a valid request */
  14713. /* Is there a "host" ? */
  14714. if (conn->host != NULL) {
  14715. mg_free((void *)conn->host);
  14716. }
  14717. conn->host = alloc_get_host(conn);
  14718. if (!conn->host) {
  14719. mg_snprintf(conn,
  14720. NULL, /* No truncation check for ebuf */
  14721. ebuf,
  14722. ebuf_len,
  14723. "%s",
  14724. "Bad request: Host mismatch");
  14725. *err = 400;
  14726. return 0;
  14727. }
  14728. if (((cl = get_header(conn->request_info.http_headers,
  14729. conn->request_info.num_headers,
  14730. "Transfer-Encoding"))
  14731. != NULL)
  14732. && mg_strcasecmp(cl, "identity")) {
  14733. if (mg_strcasecmp(cl, "chunked")) {
  14734. mg_snprintf(conn,
  14735. NULL, /* No truncation check for ebuf */
  14736. ebuf,
  14737. ebuf_len,
  14738. "%s",
  14739. "Bad request");
  14740. *err = 400;
  14741. return 0;
  14742. }
  14743. conn->is_chunked = 1;
  14744. conn->content_len = 0; /* not yet read */
  14745. } else if ((cl = get_header(conn->request_info.http_headers,
  14746. conn->request_info.num_headers,
  14747. "Content-Length"))
  14748. != NULL) {
  14749. /* Request has content length set */
  14750. char *endptr = NULL;
  14751. conn->content_len = strtoll(cl, &endptr, 10);
  14752. if ((endptr == cl) || (conn->content_len < 0)) {
  14753. mg_snprintf(conn,
  14754. NULL, /* No truncation check for ebuf */
  14755. ebuf,
  14756. ebuf_len,
  14757. "%s",
  14758. "Bad request");
  14759. *err = 411;
  14760. return 0;
  14761. }
  14762. /* Publish the content length back to the request info. */
  14763. conn->request_info.content_length = conn->content_len;
  14764. } else {
  14765. /* There is no exception, see RFC7230. */
  14766. conn->content_len = 0;
  14767. }
  14768. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14769. return 1;
  14770. }
  14771. /* conn is assumed to be valid in this internal function */
  14772. static int
  14773. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14774. {
  14775. const char *cl;
  14776. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14777. return 0;
  14778. }
  14779. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14780. <= 0) {
  14781. mg_snprintf(conn,
  14782. NULL, /* No truncation check for ebuf */
  14783. ebuf,
  14784. ebuf_len,
  14785. "%s",
  14786. "Bad response");
  14787. *err = 400;
  14788. return 0;
  14789. }
  14790. /* Message is a valid response */
  14791. if (((cl = get_header(conn->response_info.http_headers,
  14792. conn->response_info.num_headers,
  14793. "Transfer-Encoding"))
  14794. != NULL)
  14795. && mg_strcasecmp(cl, "identity")) {
  14796. if (mg_strcasecmp(cl, "chunked")) {
  14797. mg_snprintf(conn,
  14798. NULL, /* No truncation check for ebuf */
  14799. ebuf,
  14800. ebuf_len,
  14801. "%s",
  14802. "Bad request");
  14803. *err = 400;
  14804. return 0;
  14805. }
  14806. conn->is_chunked = 1;
  14807. conn->content_len = 0; /* not yet read */
  14808. } else if ((cl = get_header(conn->response_info.http_headers,
  14809. conn->response_info.num_headers,
  14810. "Content-Length"))
  14811. != NULL) {
  14812. char *endptr = NULL;
  14813. conn->content_len = strtoll(cl, &endptr, 10);
  14814. if ((endptr == cl) || (conn->content_len < 0)) {
  14815. mg_snprintf(conn,
  14816. NULL, /* No truncation check for ebuf */
  14817. ebuf,
  14818. ebuf_len,
  14819. "%s",
  14820. "Bad request");
  14821. *err = 411;
  14822. return 0;
  14823. }
  14824. /* Publish the content length back to the response info. */
  14825. conn->response_info.content_length = conn->content_len;
  14826. /* TODO: check if it is still used in response_info */
  14827. conn->request_info.content_length = conn->content_len;
  14828. /* TODO: we should also consider HEAD method */
  14829. if (conn->response_info.status_code == 304) {
  14830. conn->content_len = 0;
  14831. }
  14832. } else {
  14833. /* TODO: we should also consider HEAD method */
  14834. if (((conn->response_info.status_code >= 100)
  14835. && (conn->response_info.status_code <= 199))
  14836. || (conn->response_info.status_code == 204)
  14837. || (conn->response_info.status_code == 304)) {
  14838. conn->content_len = 0;
  14839. } else {
  14840. conn->content_len = -1; /* unknown content length */
  14841. }
  14842. }
  14843. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14844. return 1;
  14845. }
  14846. int
  14847. mg_get_response(struct mg_connection *conn,
  14848. char *ebuf,
  14849. size_t ebuf_len,
  14850. int timeout)
  14851. {
  14852. int err, ret;
  14853. char txt[32]; /* will not overflow */
  14854. char *save_timeout;
  14855. char *new_timeout;
  14856. if (ebuf_len > 0) {
  14857. ebuf[0] = '\0';
  14858. }
  14859. if (!conn) {
  14860. mg_snprintf(conn,
  14861. NULL, /* No truncation check for ebuf */
  14862. ebuf,
  14863. ebuf_len,
  14864. "%s",
  14865. "Parameter error");
  14866. return -1;
  14867. }
  14868. /* Reset the previous responses */
  14869. conn->data_len = 0;
  14870. /* Implementation of API function for HTTP clients */
  14871. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14872. if (timeout >= 0) {
  14873. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14874. new_timeout = txt;
  14875. } else {
  14876. new_timeout = NULL;
  14877. }
  14878. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14879. ret = get_response(conn, ebuf, ebuf_len, &err);
  14880. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14881. #if defined(MG_LEGACY_INTERFACE)
  14882. /* TODO: 1) uri is deprecated;
  14883. * 2) here, ri.uri is the http response code */
  14884. conn->request_info.uri = conn->request_info.request_uri;
  14885. #endif
  14886. conn->request_info.local_uri = conn->request_info.request_uri;
  14887. /* TODO (mid): Define proper return values - maybe return length?
  14888. * For the first test use <0 for error and >0 for OK */
  14889. return (ret == 0) ? -1 : +1;
  14890. }
  14891. struct mg_connection *
  14892. mg_download(const char *host,
  14893. int port,
  14894. int use_ssl,
  14895. char *ebuf,
  14896. size_t ebuf_len,
  14897. const char *fmt,
  14898. ...)
  14899. {
  14900. struct mg_connection *conn;
  14901. va_list ap;
  14902. int i;
  14903. int reqerr;
  14904. if (ebuf_len > 0) {
  14905. ebuf[0] = '\0';
  14906. }
  14907. va_start(ap, fmt);
  14908. /* open a connection */
  14909. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14910. if (conn != NULL) {
  14911. i = mg_vprintf(conn, fmt, ap);
  14912. if (i <= 0) {
  14913. mg_snprintf(conn,
  14914. NULL, /* No truncation check for ebuf */
  14915. ebuf,
  14916. ebuf_len,
  14917. "%s",
  14918. "Error sending request");
  14919. } else {
  14920. /* make sure the buffer is clear */
  14921. conn->data_len = 0;
  14922. get_response(conn, ebuf, ebuf_len, &reqerr);
  14923. #if defined(MG_LEGACY_INTERFACE)
  14924. /* TODO: 1) uri is deprecated;
  14925. * 2) here, ri.uri is the http response code */
  14926. conn->request_info.uri = conn->request_info.request_uri;
  14927. #endif
  14928. conn->request_info.local_uri = conn->request_info.request_uri;
  14929. }
  14930. }
  14931. /* if an error occurred, close the connection */
  14932. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14933. mg_close_connection(conn);
  14934. conn = NULL;
  14935. }
  14936. va_end(ap);
  14937. return conn;
  14938. }
  14939. struct websocket_client_thread_data {
  14940. struct mg_connection *conn;
  14941. mg_websocket_data_handler data_handler;
  14942. mg_websocket_close_handler close_handler;
  14943. void *callback_data;
  14944. };
  14945. #if defined(USE_WEBSOCKET)
  14946. #if defined(_WIN32)
  14947. static unsigned __stdcall websocket_client_thread(void *data)
  14948. #else
  14949. static void *
  14950. websocket_client_thread(void *data)
  14951. #endif
  14952. {
  14953. struct websocket_client_thread_data *cdata =
  14954. (struct websocket_client_thread_data *)data;
  14955. void *user_thread_ptr = NULL;
  14956. #if !defined(_WIN32)
  14957. struct sigaction sa;
  14958. /* Ignore SIGPIPE */
  14959. memset(&sa, 0, sizeof(sa));
  14960. sa.sa_handler = SIG_IGN;
  14961. sigaction(SIGPIPE, &sa, NULL);
  14962. #endif
  14963. mg_set_thread_name("ws-clnt");
  14964. if (cdata->conn->phys_ctx) {
  14965. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14966. /* 3 indicates a websocket client thread */
  14967. /* TODO: check if conn->phys_ctx can be set */
  14968. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  14969. cdata->conn->phys_ctx, 3);
  14970. }
  14971. }
  14972. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14973. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14974. if (cdata->close_handler != NULL) {
  14975. cdata->close_handler(cdata->conn, cdata->callback_data);
  14976. }
  14977. /* The websocket_client context has only this thread. If it runs out,
  14978. set the stop_flag to 2 (= "stopped"). */
  14979. cdata->conn->phys_ctx->stop_flag = 2;
  14980. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  14981. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  14982. 3,
  14983. user_thread_ptr);
  14984. }
  14985. mg_free((void *)cdata);
  14986. #if defined(_WIN32)
  14987. return 0;
  14988. #else
  14989. return NULL;
  14990. #endif
  14991. }
  14992. #endif
  14993. struct mg_connection *
  14994. mg_connect_websocket_client(const char *host,
  14995. int port,
  14996. int use_ssl,
  14997. char *error_buffer,
  14998. size_t error_buffer_size,
  14999. const char *path,
  15000. const char *origin,
  15001. mg_websocket_data_handler data_func,
  15002. mg_websocket_close_handler close_func,
  15003. void *user_data)
  15004. {
  15005. struct mg_connection *conn = NULL;
  15006. #if defined(USE_WEBSOCKET)
  15007. struct websocket_client_thread_data *thread_data;
  15008. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  15009. static const char *handshake_req;
  15010. if (origin != NULL) {
  15011. handshake_req = "GET %s HTTP/1.1\r\n"
  15012. "Host: %s\r\n"
  15013. "Upgrade: websocket\r\n"
  15014. "Connection: Upgrade\r\n"
  15015. "Sec-WebSocket-Key: %s\r\n"
  15016. "Sec-WebSocket-Version: 13\r\n"
  15017. "Origin: %s\r\n"
  15018. "\r\n";
  15019. } else {
  15020. handshake_req = "GET %s HTTP/1.1\r\n"
  15021. "Host: %s\r\n"
  15022. "Upgrade: websocket\r\n"
  15023. "Connection: Upgrade\r\n"
  15024. "Sec-WebSocket-Key: %s\r\n"
  15025. "Sec-WebSocket-Version: 13\r\n"
  15026. "\r\n";
  15027. }
  15028. #if defined(__clang__)
  15029. #pragma clang diagnostic push
  15030. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15031. #endif
  15032. /* Establish the client connection and request upgrade */
  15033. conn = mg_download(host,
  15034. port,
  15035. use_ssl,
  15036. error_buffer,
  15037. error_buffer_size,
  15038. handshake_req,
  15039. path,
  15040. host,
  15041. magic,
  15042. origin);
  15043. #if defined(__clang__)
  15044. #pragma clang diagnostic pop
  15045. #endif
  15046. /* Connection object will be null if something goes wrong */
  15047. if (conn == NULL) {
  15048. if (!*error_buffer) {
  15049. /* There should be already an error message */
  15050. mg_snprintf(conn,
  15051. NULL, /* No truncation check for ebuf */
  15052. error_buffer,
  15053. error_buffer_size,
  15054. "Unexpected error");
  15055. }
  15056. return NULL;
  15057. }
  15058. if (conn->response_info.status_code != 101) {
  15059. /* We sent an "upgrade" request. For a correct websocket
  15060. * protocol handshake, we expect a "101 Continue" response.
  15061. * Otherwise it is a protocol violation. Maybe the HTTP
  15062. * Server does not know websockets. */
  15063. if (!*error_buffer) {
  15064. /* set an error, if not yet set */
  15065. mg_snprintf(conn,
  15066. NULL, /* No truncation check for ebuf */
  15067. error_buffer,
  15068. error_buffer_size,
  15069. "Unexpected server reply");
  15070. }
  15071. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15072. mg_close_connection(conn);
  15073. return NULL;
  15074. }
  15075. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15076. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15077. if (!thread_data) {
  15078. DEBUG_TRACE("%s\r\n", "Out of memory");
  15079. mg_close_connection(conn);
  15080. return NULL;
  15081. }
  15082. thread_data->conn = conn;
  15083. thread_data->data_handler = data_func;
  15084. thread_data->close_handler = close_func;
  15085. thread_data->callback_data = user_data;
  15086. conn->phys_ctx->worker_threadids =
  15087. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15088. if (!conn->phys_ctx->worker_threadids) {
  15089. DEBUG_TRACE("%s\r\n", "Out of memory");
  15090. mg_free(thread_data);
  15091. mg_close_connection(conn);
  15092. return NULL;
  15093. }
  15094. /* Now upgrade to ws/wss client context */
  15095. conn->phys_ctx->user_data = user_data;
  15096. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15097. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15098. /* Start a thread to read the websocket client connection
  15099. * This thread will automatically stop when mg_disconnect is
  15100. * called on the client connection */
  15101. if (mg_start_thread_with_id(websocket_client_thread,
  15102. thread_data,
  15103. conn->phys_ctx->worker_threadids)
  15104. != 0) {
  15105. conn->phys_ctx->cfg_worker_threads = 0;
  15106. mg_free(thread_data);
  15107. mg_close_connection(conn);
  15108. conn = NULL;
  15109. DEBUG_TRACE("%s",
  15110. "Websocket client connect thread could not be started\r\n");
  15111. }
  15112. #else
  15113. /* Appease "unused parameter" warnings */
  15114. (void)host;
  15115. (void)port;
  15116. (void)use_ssl;
  15117. (void)error_buffer;
  15118. (void)error_buffer_size;
  15119. (void)path;
  15120. (void)origin;
  15121. (void)user_data;
  15122. (void)data_func;
  15123. (void)close_func;
  15124. #endif
  15125. return conn;
  15126. }
  15127. /* Prepare connection data structure */
  15128. static void
  15129. init_connection(struct mg_connection *conn)
  15130. {
  15131. /* Is keep alive allowed by the server */
  15132. int keep_alive_enabled =
  15133. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15134. if (!keep_alive_enabled) {
  15135. conn->must_close = 1;
  15136. }
  15137. /* Important: on new connection, reset the receiving buffer. Credit
  15138. * goes to crule42. */
  15139. conn->data_len = 0;
  15140. conn->handled_requests = 0;
  15141. mg_set_user_connection_data(conn, NULL);
  15142. #if defined(USE_SERVER_STATS)
  15143. conn->conn_state = 2; /* init */
  15144. #endif
  15145. /* call the init_connection callback if assigned */
  15146. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15147. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15148. void *conn_data = NULL;
  15149. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15150. mg_set_user_connection_data(conn, conn_data);
  15151. }
  15152. }
  15153. }
  15154. /* Process a connection - may handle multiple requests
  15155. * using the same connection.
  15156. * Must be called with a valid connection (conn and
  15157. * conn->phys_ctx must be valid).
  15158. */
  15159. static void
  15160. process_new_connection(struct mg_connection *conn)
  15161. {
  15162. struct mg_request_info *ri = &conn->request_info;
  15163. int keep_alive, discard_len;
  15164. char ebuf[100];
  15165. const char *hostend;
  15166. int reqerr, uri_type;
  15167. #if defined(USE_SERVER_STATS)
  15168. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15169. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15170. if (mcon > (conn->phys_ctx->max_connections)) {
  15171. /* could use atomic compare exchange, but this
  15172. * seems overkill for statistics data */
  15173. conn->phys_ctx->max_connections = mcon;
  15174. }
  15175. #endif
  15176. init_connection(conn);
  15177. DEBUG_TRACE("Start processing connection from %s",
  15178. conn->request_info.remote_addr);
  15179. /* Loop over multiple requests sent using the same connection
  15180. * (while "keep alive"). */
  15181. do {
  15182. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15183. conn->handled_requests + 1);
  15184. #if defined(USE_SERVER_STATS)
  15185. conn->conn_state = 3; /* ready */
  15186. #endif
  15187. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15188. /* The request sent by the client could not be understood by
  15189. * the server, or it was incomplete or a timeout. Send an
  15190. * error message and close the connection. */
  15191. if (reqerr > 0) {
  15192. DEBUG_ASSERT(ebuf[0] != '\0');
  15193. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15194. }
  15195. } else if (strcmp(ri->http_version, "1.0")
  15196. && strcmp(ri->http_version, "1.1")) {
  15197. mg_snprintf(conn,
  15198. NULL, /* No truncation check for ebuf */
  15199. ebuf,
  15200. sizeof(ebuf),
  15201. "Bad HTTP version: [%s]",
  15202. ri->http_version);
  15203. mg_send_http_error(conn, 505, "%s", ebuf);
  15204. }
  15205. if (ebuf[0] == '\0') {
  15206. uri_type = get_uri_type(conn->request_info.request_uri);
  15207. switch (uri_type) {
  15208. case 1:
  15209. /* Asterisk */
  15210. conn->request_info.local_uri = NULL;
  15211. break;
  15212. case 2:
  15213. /* relative uri */
  15214. conn->request_info.local_uri = conn->request_info.request_uri;
  15215. break;
  15216. case 3:
  15217. case 4:
  15218. /* absolute uri (with/without port) */
  15219. hostend = get_rel_url_at_current_server(
  15220. conn->request_info.request_uri, conn);
  15221. if (hostend) {
  15222. conn->request_info.local_uri = hostend;
  15223. } else {
  15224. conn->request_info.local_uri = NULL;
  15225. }
  15226. break;
  15227. default:
  15228. mg_snprintf(conn,
  15229. NULL, /* No truncation check for ebuf */
  15230. ebuf,
  15231. sizeof(ebuf),
  15232. "Invalid URI");
  15233. mg_send_http_error(conn, 400, "%s", ebuf);
  15234. conn->request_info.local_uri = NULL;
  15235. break;
  15236. }
  15237. #if defined(MG_LEGACY_INTERFACE)
  15238. /* Legacy before split into local_uri and request_uri */
  15239. conn->request_info.uri = conn->request_info.local_uri;
  15240. #endif
  15241. }
  15242. DEBUG_TRACE("http: %s, error: %s",
  15243. (ri->http_version ? ri->http_version : "none"),
  15244. (ebuf[0] ? ebuf : "none"));
  15245. if (ebuf[0] == '\0') {
  15246. if (conn->request_info.local_uri) {
  15247. /* handle request to local server */
  15248. #if defined(USE_SERVER_STATS)
  15249. conn->conn_state = 4; /* processing */
  15250. #endif
  15251. handle_request(conn);
  15252. #if defined(USE_SERVER_STATS)
  15253. conn->conn_state = 5; /* processed */
  15254. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15255. conn->consumed_content);
  15256. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15257. conn->num_bytes_sent);
  15258. #endif
  15259. DEBUG_TRACE("%s", "handle_request done");
  15260. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15261. conn->phys_ctx->callbacks.end_request(conn,
  15262. conn->status_code);
  15263. DEBUG_TRACE("%s", "end_request callback done");
  15264. }
  15265. log_access(conn);
  15266. } else {
  15267. /* TODO: handle non-local request (PROXY) */
  15268. conn->must_close = 1;
  15269. }
  15270. } else {
  15271. conn->must_close = 1;
  15272. }
  15273. if (ri->remote_user != NULL) {
  15274. mg_free((void *)ri->remote_user);
  15275. /* Important! When having connections with and without auth
  15276. * would cause double free and then crash */
  15277. ri->remote_user = NULL;
  15278. }
  15279. /* NOTE(lsm): order is important here. should_keep_alive() call
  15280. * is using parsed request, which will be invalid after
  15281. * memmove's below.
  15282. * Therefore, memorize should_keep_alive() result now for later
  15283. * use in loop exit condition. */
  15284. /* Enable it only if this request is completely discardable. */
  15285. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15286. && (conn->content_len >= 0) && (conn->request_len > 0)
  15287. && ((conn->is_chunked == 4)
  15288. || (!conn->is_chunked
  15289. && ((conn->consumed_content == conn->content_len)
  15290. || ((conn->request_len + conn->content_len)
  15291. <= conn->data_len))));
  15292. if (keep_alive) {
  15293. /* Discard all buffered data for this request */
  15294. discard_len =
  15295. ((conn->request_len + conn->content_len) < conn->data_len)
  15296. ? (int)(conn->request_len + conn->content_len)
  15297. : conn->data_len;
  15298. conn->data_len -= discard_len;
  15299. if (conn->data_len > 0) {
  15300. DEBUG_TRACE("discard_len = %d", discard_len);
  15301. memmove(conn->buf,
  15302. conn->buf + discard_len,
  15303. (size_t)conn->data_len);
  15304. }
  15305. }
  15306. DEBUG_ASSERT(conn->data_len >= 0);
  15307. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15308. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15309. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15310. (long int)conn->data_len,
  15311. (long int)conn->buf_size);
  15312. break;
  15313. }
  15314. conn->handled_requests++;
  15315. } while (keep_alive);
  15316. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15317. conn->request_info.remote_addr,
  15318. difftime(time(NULL), conn->conn_birth_time));
  15319. close_connection(conn);
  15320. #if defined(USE_SERVER_STATS)
  15321. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15322. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15323. #endif
  15324. }
  15325. #if defined(ALTERNATIVE_QUEUE)
  15326. static void
  15327. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15328. {
  15329. unsigned int i;
  15330. while (!ctx->stop_flag) {
  15331. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15332. /* find a free worker slot and signal it */
  15333. if (ctx->client_socks[i].in_use == 2) {
  15334. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15335. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15336. ctx->client_socks[i] = *sp;
  15337. ctx->client_socks[i].in_use = 1;
  15338. /* socket has been moved to the consumer */
  15339. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15340. (void)event_signal(ctx->client_wait_events[i]);
  15341. return;
  15342. }
  15343. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15344. }
  15345. }
  15346. /* queue is full */
  15347. mg_sleep(1);
  15348. }
  15349. /* must consume */
  15350. set_blocking_mode(sp->sock);
  15351. closesocket(sp->sock);
  15352. }
  15353. static int
  15354. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15355. {
  15356. DEBUG_TRACE("%s", "going idle");
  15357. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15358. ctx->client_socks[thread_index].in_use = 2;
  15359. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15360. event_wait(ctx->client_wait_events[thread_index]);
  15361. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15362. *sp = ctx->client_socks[thread_index];
  15363. if (ctx->stop_flag) {
  15364. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15365. if (sp->in_use == 1) {
  15366. /* must consume */
  15367. set_blocking_mode(sp->sock);
  15368. closesocket(sp->sock);
  15369. }
  15370. return 0;
  15371. }
  15372. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15373. if (sp->in_use == 1) {
  15374. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15375. return 1;
  15376. }
  15377. /* must not reach here */
  15378. DEBUG_ASSERT(0);
  15379. return 0;
  15380. }
  15381. #else /* ALTERNATIVE_QUEUE */
  15382. /* Worker threads take accepted socket from the queue */
  15383. static int
  15384. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15385. {
  15386. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15387. (void)thread_index;
  15388. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15389. DEBUG_TRACE("%s", "going idle");
  15390. /* If the queue is empty, wait. We're idle at this point. */
  15391. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15392. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15393. }
  15394. /* If we're stopping, sq_head may be equal to sq_tail. */
  15395. if (ctx->sq_head > ctx->sq_tail) {
  15396. /* Copy socket from the queue and increment tail */
  15397. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15398. ctx->sq_tail++;
  15399. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15400. /* Wrap pointers if needed */
  15401. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15402. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15403. ctx->sq_head -= QUEUE_SIZE(ctx);
  15404. }
  15405. }
  15406. (void)pthread_cond_signal(&ctx->sq_empty);
  15407. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15408. return !ctx->stop_flag;
  15409. #undef QUEUE_SIZE
  15410. }
  15411. /* Master thread adds accepted socket to a queue */
  15412. static void
  15413. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15414. {
  15415. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15416. if (!ctx) {
  15417. return;
  15418. }
  15419. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15420. /* If the queue is full, wait */
  15421. while ((ctx->stop_flag == 0)
  15422. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15423. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15424. }
  15425. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15426. /* Copy socket to the queue and increment head */
  15427. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15428. ctx->sq_head++;
  15429. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15430. }
  15431. (void)pthread_cond_signal(&ctx->sq_full);
  15432. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15433. #undef QUEUE_SIZE
  15434. }
  15435. #endif /* ALTERNATIVE_QUEUE */
  15436. static void
  15437. worker_thread_run(struct mg_connection *conn)
  15438. {
  15439. struct mg_context *ctx = conn->phys_ctx;
  15440. int thread_index;
  15441. struct mg_workerTLS tls;
  15442. #if defined(MG_LEGACY_INTERFACE)
  15443. uint32_t addr;
  15444. #endif
  15445. mg_set_thread_name("worker");
  15446. tls.is_master = 0;
  15447. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15448. #if defined(_WIN32)
  15449. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15450. #endif
  15451. /* Initialize thread local storage before calling any callback */
  15452. pthread_setspecific(sTlsKey, &tls);
  15453. /* Check if there is a user callback */
  15454. if (ctx->callbacks.init_thread) {
  15455. /* call init_thread for a worker thread (type 1), and store the return
  15456. * value */
  15457. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  15458. } else {
  15459. /* No callback: set user pointer to NULL */
  15460. tls.user_ptr = NULL;
  15461. }
  15462. /* Connection structure has been pre-allocated */
  15463. thread_index = (int)(conn - ctx->worker_connections);
  15464. if ((thread_index < 0)
  15465. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  15466. mg_cry_ctx_internal(ctx,
  15467. "Internal error: Invalid worker index %i",
  15468. thread_index);
  15469. return;
  15470. }
  15471. /* Request buffers are not pre-allocated. They are private to the
  15472. * request and do not contain any state information that might be
  15473. * of interest to anyone observing a server status. */
  15474. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15475. if (conn->buf == NULL) {
  15476. mg_cry_ctx_internal(
  15477. ctx,
  15478. "Out of memory: Cannot allocate buffer for worker %i",
  15479. thread_index);
  15480. return;
  15481. }
  15482. conn->buf_size = (int)ctx->max_request_size;
  15483. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15484. conn->host = NULL; /* until we have more information. */
  15485. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  15486. conn->request_info.user_data = ctx->user_data;
  15487. /* Allocate a mutex for this connection to allow communication both
  15488. * within the request handler and from elsewhere in the application
  15489. */
  15490. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15491. mg_free(conn->buf);
  15492. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  15493. return;
  15494. }
  15495. #if defined(USE_SERVER_STATS)
  15496. conn->conn_state = 1; /* not consumed */
  15497. #endif
  15498. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15499. * signal sq_empty condvar to wake up the master waiting in
  15500. * produce_socket() */
  15501. while (consume_socket(ctx, &conn->client, thread_index)) {
  15502. conn->conn_birth_time = time(NULL);
  15503. /* Fill in IP, port info early so even if SSL setup below fails,
  15504. * error handler would have the corresponding info.
  15505. * Thanks to Johannes Winkelmann for the patch.
  15506. */
  15507. #if defined(USE_IPV6)
  15508. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15509. conn->request_info.remote_port =
  15510. ntohs(conn->client.rsa.sin6.sin6_port);
  15511. } else
  15512. #endif
  15513. {
  15514. conn->request_info.remote_port =
  15515. ntohs(conn->client.rsa.sin.sin_port);
  15516. }
  15517. sockaddr_to_string(conn->request_info.remote_addr,
  15518. sizeof(conn->request_info.remote_addr),
  15519. &conn->client.rsa);
  15520. DEBUG_TRACE("Start processing connection from %s",
  15521. conn->request_info.remote_addr);
  15522. conn->request_info.is_ssl = conn->client.is_ssl;
  15523. if (conn->client.is_ssl) {
  15524. #if !defined(NO_SSL)
  15525. /* HTTPS connection */
  15526. if (sslize(conn,
  15527. conn->dom_ctx->ssl_ctx,
  15528. SSL_accept,
  15529. &(conn->phys_ctx->stop_flag),
  15530. NULL)) {
  15531. /* conn->dom_ctx is set in get_request */
  15532. /* Get SSL client certificate information (if set) */
  15533. ssl_get_client_cert_info(conn);
  15534. /* process HTTPS connection */
  15535. process_new_connection(conn);
  15536. /* Free client certificate info */
  15537. if (conn->request_info.client_cert) {
  15538. mg_free((void *)(conn->request_info.client_cert->subject));
  15539. mg_free((void *)(conn->request_info.client_cert->issuer));
  15540. mg_free((void *)(conn->request_info.client_cert->serial));
  15541. mg_free((void *)(conn->request_info.client_cert->finger));
  15542. /* Free certificate memory */
  15543. X509_free(
  15544. (X509 *)conn->request_info.client_cert->peer_cert);
  15545. conn->request_info.client_cert->peer_cert = 0;
  15546. conn->request_info.client_cert->subject = 0;
  15547. conn->request_info.client_cert->issuer = 0;
  15548. conn->request_info.client_cert->serial = 0;
  15549. conn->request_info.client_cert->finger = 0;
  15550. mg_free(conn->request_info.client_cert);
  15551. conn->request_info.client_cert = 0;
  15552. }
  15553. } else {
  15554. /* make sure the connection is cleaned up on SSL failure */
  15555. close_connection(conn);
  15556. }
  15557. #endif
  15558. } else {
  15559. /* process HTTP connection */
  15560. process_new_connection(conn);
  15561. }
  15562. DEBUG_TRACE("%s", "Connection closed");
  15563. }
  15564. /* Call exit thread user callback */
  15565. if (ctx->callbacks.exit_thread) {
  15566. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  15567. }
  15568. /* delete thread local storage objects */
  15569. pthread_setspecific(sTlsKey, NULL);
  15570. #if defined(_WIN32)
  15571. CloseHandle(tls.pthread_cond_helper_mutex);
  15572. #endif
  15573. pthread_mutex_destroy(&conn->mutex);
  15574. /* Free the request buffer. */
  15575. conn->buf_size = 0;
  15576. mg_free(conn->buf);
  15577. conn->buf = NULL;
  15578. #if defined(USE_SERVER_STATS)
  15579. conn->conn_state = 9; /* done */
  15580. #endif
  15581. DEBUG_TRACE("%s", "exiting");
  15582. }
  15583. /* Threads have different return types on Windows and Unix. */
  15584. #if defined(_WIN32)
  15585. static unsigned __stdcall worker_thread(void *thread_func_param)
  15586. {
  15587. worker_thread_run((struct mg_connection *)thread_func_param);
  15588. return 0;
  15589. }
  15590. #else
  15591. static void *
  15592. worker_thread(void *thread_func_param)
  15593. {
  15594. #if !defined(__ZEPHYR__)
  15595. struct sigaction sa;
  15596. /* Ignore SIGPIPE */
  15597. memset(&sa, 0, sizeof(sa));
  15598. sa.sa_handler = SIG_IGN;
  15599. sigaction(SIGPIPE, &sa, NULL);
  15600. #endif
  15601. worker_thread_run((struct mg_connection *)thread_func_param);
  15602. return NULL;
  15603. }
  15604. #endif /* _WIN32 */
  15605. /* This is an internal function, thus all arguments are expected to be
  15606. * valid - a NULL check is not required. */
  15607. static void
  15608. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15609. {
  15610. struct socket so;
  15611. char src_addr[IP_ADDR_STR_LEN];
  15612. socklen_t len = sizeof(so.rsa);
  15613. #if !defined(__ZEPHYR__)
  15614. int on = 1;
  15615. #endif
  15616. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15617. == INVALID_SOCKET) {
  15618. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15619. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15620. mg_cry_ctx_internal(ctx,
  15621. "%s: %s is not allowed to connect",
  15622. __func__,
  15623. src_addr);
  15624. closesocket(so.sock);
  15625. } else {
  15626. /* Put so socket structure into the queue */
  15627. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15628. set_close_on_exec(so.sock, NULL, ctx);
  15629. so.is_ssl = listener->is_ssl;
  15630. so.ssl_redir = listener->ssl_redir;
  15631. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15632. mg_cry_ctx_internal(ctx,
  15633. "%s: getsockname() failed: %s",
  15634. __func__,
  15635. strerror(ERRNO));
  15636. }
  15637. #if !defined(__ZEPHYR__)
  15638. /* Set TCP keep-alive. This is needed because if HTTP-level
  15639. * keep-alive
  15640. * is enabled, and client resets the connection, server won't get
  15641. * TCP FIN or RST and will keep the connection open forever. With
  15642. * TCP keep-alive, next keep-alive handshake will figure out that
  15643. * the client is down and will close the server end.
  15644. * Thanks to Igor Klopov who suggested the patch. */
  15645. if (setsockopt(so.sock,
  15646. SOL_SOCKET,
  15647. SO_KEEPALIVE,
  15648. (SOCK_OPT_TYPE)&on,
  15649. sizeof(on))
  15650. != 0) {
  15651. mg_cry_ctx_internal(
  15652. ctx,
  15653. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15654. __func__,
  15655. strerror(ERRNO));
  15656. }
  15657. #endif
  15658. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15659. * to effectively fill up the underlying IP packet payload and
  15660. * reduce the overhead of sending lots of small buffers. However
  15661. * this hurts the server's throughput (ie. operations per second)
  15662. * when HTTP 1.1 persistent connections are used and the responses
  15663. * are relatively small (eg. less than 1400 bytes).
  15664. */
  15665. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15666. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15667. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15668. mg_cry_ctx_internal(
  15669. ctx,
  15670. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15671. __func__,
  15672. strerror(ERRNO));
  15673. }
  15674. }
  15675. /* The "non blocking" property should already be
  15676. * inherited from the parent socket. Set it for
  15677. * non-compliant socket implementations. */
  15678. set_non_blocking_mode(so.sock);
  15679. so.in_use = 0;
  15680. produce_socket(ctx, &so);
  15681. }
  15682. }
  15683. static void
  15684. master_thread_run(struct mg_context *ctx)
  15685. {
  15686. struct mg_workerTLS tls;
  15687. struct mg_pollfd *pfd;
  15688. unsigned int i;
  15689. unsigned int workerthreadcount;
  15690. if (!ctx) {
  15691. return;
  15692. }
  15693. mg_set_thread_name("master");
  15694. /* Increase priority of the master thread */
  15695. #if defined(_WIN32)
  15696. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15697. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15698. int min_prio = sched_get_priority_min(SCHED_RR);
  15699. int max_prio = sched_get_priority_max(SCHED_RR);
  15700. if ((min_prio >= 0) && (max_prio >= 0)
  15701. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15702. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15703. struct sched_param sched_param = {0};
  15704. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15705. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15706. }
  15707. #endif
  15708. /* Initialize thread local storage */
  15709. #if defined(_WIN32)
  15710. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15711. #endif
  15712. tls.is_master = 1;
  15713. pthread_setspecific(sTlsKey, &tls);
  15714. if (ctx->callbacks.init_thread) {
  15715. /* Callback for the master thread (type 0) */
  15716. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  15717. } else {
  15718. tls.user_ptr = NULL;
  15719. }
  15720. /* Server starts *now* */
  15721. ctx->start_time = time(NULL);
  15722. /* Start the server */
  15723. pfd = ctx->listening_socket_fds;
  15724. while (ctx->stop_flag == 0) {
  15725. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15726. pfd[i].fd = ctx->listening_sockets[i].sock;
  15727. pfd[i].events = POLLIN;
  15728. }
  15729. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15730. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15731. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15732. * successful poll, and POLLIN is defined as
  15733. * (POLLRDNORM | POLLRDBAND)
  15734. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15735. * pfd[i].revents == POLLIN. */
  15736. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15737. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15738. }
  15739. }
  15740. }
  15741. }
  15742. /* Here stop_flag is 1 - Initiate shutdown. */
  15743. DEBUG_TRACE("%s", "stopping workers");
  15744. /* Stop signal received: somebody called mg_stop. Quit. */
  15745. close_all_listening_sockets(ctx);
  15746. /* Wakeup workers that are waiting for connections to handle. */
  15747. #if defined(ALTERNATIVE_QUEUE)
  15748. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15749. event_signal(ctx->client_wait_events[i]);
  15750. }
  15751. #else
  15752. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15753. pthread_cond_broadcast(&ctx->sq_full);
  15754. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15755. #endif
  15756. /* Join all worker threads to avoid leaking threads. */
  15757. workerthreadcount = ctx->cfg_worker_threads;
  15758. for (i = 0; i < workerthreadcount; i++) {
  15759. if (ctx->worker_threadids[i] != 0) {
  15760. mg_join_thread(ctx->worker_threadids[i]);
  15761. }
  15762. }
  15763. #if defined(USE_LUA)
  15764. /* Free Lua state of lua background task */
  15765. if (ctx->lua_background_state) {
  15766. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15767. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15768. if (lua_istable(lstate, -1)) {
  15769. reg_boolean(lstate, "shutdown", 1);
  15770. lua_pop(lstate, 1);
  15771. mg_sleep(2);
  15772. }
  15773. lua_close(lstate);
  15774. ctx->lua_background_state = 0;
  15775. }
  15776. #endif
  15777. DEBUG_TRACE("%s", "exiting");
  15778. /* call exit thread callback */
  15779. if (ctx->callbacks.exit_thread) {
  15780. /* Callback for the master thread (type 0) */
  15781. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  15782. }
  15783. #if defined(_WIN32)
  15784. CloseHandle(tls.pthread_cond_helper_mutex);
  15785. #endif
  15786. pthread_setspecific(sTlsKey, NULL);
  15787. /* Signal mg_stop() that we're done.
  15788. * WARNING: This must be the very last thing this
  15789. * thread does, as ctx becomes invalid after this line. */
  15790. ctx->stop_flag = 2;
  15791. }
  15792. /* Threads have different return types on Windows and Unix. */
  15793. #if defined(_WIN32)
  15794. static unsigned __stdcall master_thread(void *thread_func_param)
  15795. {
  15796. master_thread_run((struct mg_context *)thread_func_param);
  15797. return 0;
  15798. }
  15799. #else
  15800. static void *
  15801. master_thread(void *thread_func_param)
  15802. {
  15803. #if !defined(__ZEPHYR__)
  15804. struct sigaction sa;
  15805. /* Ignore SIGPIPE */
  15806. memset(&sa, 0, sizeof(sa));
  15807. sa.sa_handler = SIG_IGN;
  15808. sigaction(SIGPIPE, &sa, NULL);
  15809. #endif
  15810. master_thread_run((struct mg_context *)thread_func_param);
  15811. return NULL;
  15812. }
  15813. #endif /* _WIN32 */
  15814. static void
  15815. free_context(struct mg_context *ctx)
  15816. {
  15817. int i;
  15818. struct mg_handler_info *tmp_rh;
  15819. if (ctx == NULL) {
  15820. return;
  15821. }
  15822. if (ctx->callbacks.exit_context) {
  15823. ctx->callbacks.exit_context(ctx);
  15824. }
  15825. /* All threads exited, no sync is needed. Destroy thread mutex and
  15826. * condvars
  15827. */
  15828. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15829. #if defined(ALTERNATIVE_QUEUE)
  15830. mg_free(ctx->client_socks);
  15831. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15832. event_destroy(ctx->client_wait_events[i]);
  15833. }
  15834. mg_free(ctx->client_wait_events);
  15835. #else
  15836. (void)pthread_cond_destroy(&ctx->sq_empty);
  15837. (void)pthread_cond_destroy(&ctx->sq_full);
  15838. #endif
  15839. /* Destroy other context global data structures mutex */
  15840. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15841. #if defined(USE_TIMERS)
  15842. timers_exit(ctx);
  15843. #endif
  15844. /* Deallocate config parameters */
  15845. for (i = 0; i < NUM_OPTIONS; i++) {
  15846. if (ctx->dd.config[i] != NULL) {
  15847. #if defined(_MSC_VER)
  15848. #pragma warning(suppress : 6001)
  15849. #endif
  15850. mg_free(ctx->dd.config[i]);
  15851. }
  15852. }
  15853. /* Deallocate request handlers */
  15854. while (ctx->dd.handlers) {
  15855. tmp_rh = ctx->dd.handlers;
  15856. ctx->dd.handlers = tmp_rh->next;
  15857. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15858. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15859. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15860. }
  15861. mg_free(tmp_rh->uri);
  15862. mg_free(tmp_rh);
  15863. }
  15864. #if !defined(NO_SSL)
  15865. /* Deallocate SSL context */
  15866. if (ctx->dd.ssl_ctx != NULL) {
  15867. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15868. int callback_ret =
  15869. (ctx->callbacks.external_ssl_ctx == NULL)
  15870. ? 0
  15871. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15872. if (callback_ret == 0) {
  15873. SSL_CTX_free(ctx->dd.ssl_ctx);
  15874. }
  15875. /* else: ignore error and ommit SSL_CTX_free in case
  15876. * callback_ret is 1 */
  15877. }
  15878. #endif /* !NO_SSL */
  15879. /* Deallocate worker thread ID array */
  15880. mg_free(ctx->worker_threadids);
  15881. /* Deallocate worker thread ID array */
  15882. mg_free(ctx->worker_connections);
  15883. /* deallocate system name string */
  15884. mg_free(ctx->systemName);
  15885. /* Deallocate context itself */
  15886. mg_free(ctx);
  15887. }
  15888. void
  15889. mg_stop(struct mg_context *ctx)
  15890. {
  15891. pthread_t mt;
  15892. if (!ctx) {
  15893. return;
  15894. }
  15895. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15896. * two threads is not allowed. */
  15897. mt = ctx->masterthreadid;
  15898. if (mt == 0) {
  15899. return;
  15900. }
  15901. ctx->masterthreadid = 0;
  15902. /* Set stop flag, so all threads know they have to exit. */
  15903. ctx->stop_flag = 1;
  15904. /* Wait until everything has stopped. */
  15905. while (ctx->stop_flag != 2) {
  15906. (void)mg_sleep(10);
  15907. }
  15908. mg_join_thread(mt);
  15909. free_context(ctx);
  15910. #if defined(_WIN32)
  15911. (void)WSACleanup();
  15912. #endif /* _WIN32 */
  15913. }
  15914. static void
  15915. get_system_name(char **sysName)
  15916. {
  15917. #if defined(_WIN32)
  15918. #if !defined(__SYMBIAN32__)
  15919. #if defined(_WIN32_WCE)
  15920. *sysName = mg_strdup("WinCE");
  15921. #else
  15922. char name[128];
  15923. DWORD dwVersion = 0;
  15924. DWORD dwMajorVersion = 0;
  15925. DWORD dwMinorVersion = 0;
  15926. DWORD dwBuild = 0;
  15927. BOOL wowRet, isWoW = FALSE;
  15928. #if defined(_MSC_VER)
  15929. #pragma warning(push)
  15930. /* GetVersion was declared deprecated */
  15931. #pragma warning(disable : 4996)
  15932. #endif
  15933. dwVersion = GetVersion();
  15934. #if defined(_MSC_VER)
  15935. #pragma warning(pop)
  15936. #endif
  15937. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15938. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15939. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15940. (void)dwBuild;
  15941. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15942. sprintf(name,
  15943. "Windows %u.%u%s",
  15944. (unsigned)dwMajorVersion,
  15945. (unsigned)dwMinorVersion,
  15946. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15947. *sysName = mg_strdup(name);
  15948. #endif
  15949. #else
  15950. *sysName = mg_strdup("Symbian");
  15951. #endif
  15952. #elif defined(__ZEPHYR__)
  15953. *sysName = mg_strdup("Zephyr OS");
  15954. #else
  15955. struct utsname name;
  15956. memset(&name, 0, sizeof(name));
  15957. uname(&name);
  15958. *sysName = mg_strdup(name.sysname);
  15959. #endif
  15960. }
  15961. struct mg_context *
  15962. mg_start(const struct mg_callbacks *callbacks,
  15963. void *user_data,
  15964. const char **options)
  15965. {
  15966. struct mg_context *ctx;
  15967. const char *name, *value, *default_value;
  15968. int idx, ok, workerthreadcount;
  15969. unsigned int i;
  15970. int itmp;
  15971. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15972. struct mg_workerTLS tls;
  15973. #if defined(_WIN32)
  15974. WSADATA data;
  15975. WSAStartup(MAKEWORD(2, 2), &data);
  15976. #endif /* _WIN32 */
  15977. /* Allocate context and initialize reasonable general case defaults. */
  15978. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15979. return NULL;
  15980. }
  15981. /* Random number generator will initialize at the first call */
  15982. ctx->dd.auth_nonce_mask =
  15983. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15984. if (mg_init_library_called == 0) {
  15985. /* Legacy INIT, if mg_start is called without mg_init_library.
  15986. * Note: This may cause a memory leak */
  15987. const char *ports_option =
  15988. config_options[LISTENING_PORTS].default_value;
  15989. if (options) {
  15990. const char **run_options = options;
  15991. const char *optname = config_options[LISTENING_PORTS].name;
  15992. /* Try to find the "listening_ports" option */
  15993. while (*run_options) {
  15994. if (!strcmp(*run_options, optname)) {
  15995. ports_option = run_options[1];
  15996. }
  15997. run_options += 2;
  15998. }
  15999. }
  16000. if (is_ssl_port_used(ports_option)) {
  16001. /* Initialize with SSL support */
  16002. mg_init_library(MG_FEATURES_TLS);
  16003. } else {
  16004. /* Initialize without SSL support */
  16005. mg_init_library(MG_FEATURES_DEFAULT);
  16006. }
  16007. }
  16008. tls.is_master = -1;
  16009. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  16010. #if defined(_WIN32)
  16011. tls.pthread_cond_helper_mutex = NULL;
  16012. #endif
  16013. pthread_setspecific(sTlsKey, &tls);
  16014. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16015. #if !defined(ALTERNATIVE_QUEUE)
  16016. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16017. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16018. #endif
  16019. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16020. if (!ok) {
  16021. /* Fatal error - abort start. However, this situation should never
  16022. * occur in practice. */
  16023. mg_cry_ctx_internal(ctx,
  16024. "%s",
  16025. "Cannot initialize thread synchronization objects");
  16026. mg_free(ctx);
  16027. pthread_setspecific(sTlsKey, NULL);
  16028. return NULL;
  16029. }
  16030. if (callbacks) {
  16031. ctx->callbacks = *callbacks;
  16032. exit_callback = callbacks->exit_context;
  16033. ctx->callbacks.exit_context = 0;
  16034. }
  16035. ctx->user_data = user_data;
  16036. ctx->dd.handlers = NULL;
  16037. ctx->dd.next = NULL;
  16038. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16039. ctx->dd.shared_lua_websockets = NULL;
  16040. #endif
  16041. /* Store options */
  16042. while (options && (name = *options++) != NULL) {
  16043. if ((idx = get_option_index(name)) == -1) {
  16044. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16045. free_context(ctx);
  16046. pthread_setspecific(sTlsKey, NULL);
  16047. return NULL;
  16048. } else if ((value = *options++) == NULL) {
  16049. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16050. free_context(ctx);
  16051. pthread_setspecific(sTlsKey, NULL);
  16052. return NULL;
  16053. }
  16054. if (ctx->dd.config[idx] != NULL) {
  16055. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16056. mg_free(ctx->dd.config[idx]);
  16057. }
  16058. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16059. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16060. }
  16061. /* Set default value if needed */
  16062. for (i = 0; config_options[i].name != NULL; i++) {
  16063. default_value = config_options[i].default_value;
  16064. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16065. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16066. }
  16067. }
  16068. /* Request size option */
  16069. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16070. if (itmp < 1024) {
  16071. mg_cry_ctx_internal(ctx, "%s", "max_request_size too small");
  16072. free_context(ctx);
  16073. pthread_setspecific(sTlsKey, NULL);
  16074. return NULL;
  16075. }
  16076. ctx->max_request_size = (unsigned)itmp;
  16077. /* Worker thread count option */
  16078. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16079. if (workerthreadcount > MAX_WORKER_THREADS) {
  16080. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  16081. free_context(ctx);
  16082. pthread_setspecific(sTlsKey, NULL);
  16083. return NULL;
  16084. }
  16085. if (workerthreadcount <= 0) {
  16086. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16087. free_context(ctx);
  16088. pthread_setspecific(sTlsKey, NULL);
  16089. return NULL;
  16090. }
  16091. /* Document root */
  16092. #if defined(NO_FILES)
  16093. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16094. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16095. free_context(ctx);
  16096. pthread_setspecific(sTlsKey, NULL);
  16097. return NULL;
  16098. }
  16099. #endif
  16100. get_system_name(&ctx->systemName);
  16101. #if defined(USE_LUA)
  16102. /* If a Lua background script has been configured, start it. */
  16103. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16104. char ebuf[256];
  16105. struct vec opt_vec;
  16106. struct vec eq_vec;
  16107. const char *sparams;
  16108. lua_State *state = mg_prepare_lua_context_script(
  16109. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16110. if (!state) {
  16111. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16112. free_context(ctx);
  16113. pthread_setspecific(sTlsKey, NULL);
  16114. return NULL;
  16115. }
  16116. ctx->lua_background_state = (void *)state;
  16117. lua_newtable(state);
  16118. reg_boolean(state, "shutdown", 0);
  16119. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16120. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16121. reg_llstring(
  16122. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16123. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16124. break;
  16125. }
  16126. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16127. } else {
  16128. ctx->lua_background_state = 0;
  16129. }
  16130. #endif
  16131. /* NOTE(lsm): order is important here. SSL certificates must
  16132. * be initialized before listening ports. UID must be set last. */
  16133. if (
  16134. #if !defined(NO_FILESYSTEMS)
  16135. !set_gpass_option(ctx, NULL) ||
  16136. #endif
  16137. #if !defined(NO_SSL)
  16138. !init_ssl_ctx(ctx, NULL) ||
  16139. #endif
  16140. !set_ports_option(ctx) ||
  16141. #if !defined(_WIN32) && !defined(__ZEPHYR__)
  16142. !set_uid_option(ctx) ||
  16143. #endif
  16144. !set_acl_option(ctx)) {
  16145. free_context(ctx);
  16146. pthread_setspecific(sTlsKey, NULL);
  16147. return NULL;
  16148. }
  16149. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16150. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16151. sizeof(pthread_t),
  16152. ctx);
  16153. if (ctx->worker_threadids == NULL) {
  16154. mg_cry_ctx_internal(ctx,
  16155. "%s",
  16156. "Not enough memory for worker thread ID array");
  16157. free_context(ctx);
  16158. pthread_setspecific(sTlsKey, NULL);
  16159. return NULL;
  16160. }
  16161. ctx->worker_connections =
  16162. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16163. sizeof(struct mg_connection),
  16164. ctx);
  16165. if (ctx->worker_connections == NULL) {
  16166. mg_cry_ctx_internal(
  16167. ctx, "%s", "Not enough memory for worker thread connection array");
  16168. free_context(ctx);
  16169. pthread_setspecific(sTlsKey, NULL);
  16170. return NULL;
  16171. }
  16172. #if defined(ALTERNATIVE_QUEUE)
  16173. ctx->client_wait_events =
  16174. (void **)mg_calloc_ctx(ctx->cfg_worker_threads,
  16175. sizeof(ctx->client_wait_events[0]),
  16176. ctx);
  16177. if (ctx->client_wait_events == NULL) {
  16178. mg_cry_ctx_internal(ctx,
  16179. "%s",
  16180. "Not enough memory for worker event array");
  16181. mg_free(ctx->worker_threadids);
  16182. free_context(ctx);
  16183. pthread_setspecific(sTlsKey, NULL);
  16184. return NULL;
  16185. }
  16186. ctx->client_socks =
  16187. (struct socket *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16188. sizeof(ctx->client_socks[0]),
  16189. ctx);
  16190. if (ctx->client_socks == NULL) {
  16191. mg_cry_ctx_internal(ctx,
  16192. "%s",
  16193. "Not enough memory for worker socket array");
  16194. mg_free(ctx->client_wait_events);
  16195. mg_free(ctx->worker_threadids);
  16196. free_context(ctx);
  16197. pthread_setspecific(sTlsKey, NULL);
  16198. return NULL;
  16199. }
  16200. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16201. ctx->client_wait_events[i] = event_create();
  16202. if (ctx->client_wait_events[i] == 0) {
  16203. mg_cry_ctx_internal(ctx, "Error creating worker event %i", i);
  16204. while (i > 0) {
  16205. i--;
  16206. event_destroy(ctx->client_wait_events[i]);
  16207. }
  16208. mg_free(ctx->client_socks);
  16209. mg_free(ctx->client_wait_events);
  16210. mg_free(ctx->worker_threadids);
  16211. free_context(ctx);
  16212. pthread_setspecific(sTlsKey, NULL);
  16213. return NULL;
  16214. }
  16215. }
  16216. #endif
  16217. #if defined(USE_TIMERS)
  16218. if (timers_init(ctx) != 0) {
  16219. mg_cry_ctx_internal(ctx, "%s", "Error creating timers");
  16220. free_context(ctx);
  16221. pthread_setspecific(sTlsKey, NULL);
  16222. return NULL;
  16223. }
  16224. #endif
  16225. /* Context has been created - init user libraries */
  16226. if (ctx->callbacks.init_context) {
  16227. ctx->callbacks.init_context(ctx);
  16228. }
  16229. ctx->callbacks.exit_context = exit_callback;
  16230. ctx->context_type = CONTEXT_SERVER; /* server context */
  16231. /* Start master (listening) thread */
  16232. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16233. /* Start worker threads */
  16234. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16235. /* worker_thread sets up the other fields */
  16236. ctx->worker_connections[i].phys_ctx = ctx;
  16237. if (mg_start_thread_with_id(worker_thread,
  16238. &ctx->worker_connections[i],
  16239. &ctx->worker_threadids[i])
  16240. != 0) {
  16241. /* thread was not created */
  16242. if (i > 0) {
  16243. mg_cry_ctx_internal(ctx,
  16244. "Cannot start worker thread %i: error %ld",
  16245. i + 1,
  16246. (long)ERRNO);
  16247. } else {
  16248. mg_cry_ctx_internal(ctx,
  16249. "Cannot create threads: error %ld",
  16250. (long)ERRNO);
  16251. free_context(ctx);
  16252. pthread_setspecific(sTlsKey, NULL);
  16253. return NULL;
  16254. }
  16255. break;
  16256. }
  16257. }
  16258. pthread_setspecific(sTlsKey, NULL);
  16259. return ctx;
  16260. }
  16261. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16262. /* Add an additional domain to an already running web server. */
  16263. int
  16264. mg_start_domain(struct mg_context *ctx, const char **options)
  16265. {
  16266. const char *name;
  16267. const char *value;
  16268. const char *default_value;
  16269. struct mg_domain_context *new_dom;
  16270. struct mg_domain_context *dom;
  16271. int idx, i;
  16272. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  16273. return -1;
  16274. }
  16275. new_dom = (struct mg_domain_context *)
  16276. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16277. if (!new_dom) {
  16278. /* Out of memory */
  16279. return -6;
  16280. }
  16281. /* Store options - TODO: unite duplicate code */
  16282. while (options && (name = *options++) != NULL) {
  16283. if ((idx = get_option_index(name)) == -1) {
  16284. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16285. mg_free(new_dom);
  16286. return -2;
  16287. } else if ((value = *options++) == NULL) {
  16288. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16289. mg_free(new_dom);
  16290. return -2;
  16291. }
  16292. if (new_dom->config[idx] != NULL) {
  16293. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16294. mg_free(new_dom->config[idx]);
  16295. }
  16296. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16297. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16298. }
  16299. /* Authentication domain is mandatory */
  16300. /* TODO: Maybe use a new option hostname? */
  16301. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16302. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  16303. mg_free(new_dom);
  16304. return -4;
  16305. }
  16306. /* Set default value if needed. Take the config value from
  16307. * ctx as a default value. */
  16308. for (i = 0; config_options[i].name != NULL; i++) {
  16309. default_value = ctx->dd.config[i];
  16310. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16311. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16312. }
  16313. }
  16314. new_dom->handlers = NULL;
  16315. new_dom->next = NULL;
  16316. new_dom->nonce_count = 0;
  16317. new_dom->auth_nonce_mask =
  16318. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16319. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16320. new_dom->shared_lua_websockets = NULL;
  16321. #endif
  16322. if (!init_ssl_ctx(ctx, new_dom)) {
  16323. /* Init SSL failed */
  16324. mg_free(new_dom);
  16325. return -3;
  16326. }
  16327. /* Add element to linked list. */
  16328. mg_lock_context(ctx);
  16329. idx = 0;
  16330. dom = &(ctx->dd);
  16331. for (;;) {
  16332. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16333. dom->config[AUTHENTICATION_DOMAIN])) {
  16334. /* Domain collision */
  16335. mg_cry_ctx_internal(ctx,
  16336. "domain %s already in use",
  16337. new_dom->config[AUTHENTICATION_DOMAIN]);
  16338. mg_free(new_dom);
  16339. return -5;
  16340. }
  16341. /* Count number of domains */
  16342. idx++;
  16343. if (dom->next == NULL) {
  16344. dom->next = new_dom;
  16345. break;
  16346. }
  16347. dom = dom->next;
  16348. }
  16349. mg_unlock_context(ctx);
  16350. /* Return domain number */
  16351. return idx;
  16352. }
  16353. #endif
  16354. /* Feature check API function */
  16355. unsigned
  16356. mg_check_feature(unsigned feature)
  16357. {
  16358. static const unsigned feature_set = 0
  16359. /* Set bits for available features according to API documentation.
  16360. * This bit mask is created at compile time, according to the active
  16361. * preprocessor defines. It is a single const value at runtime. */
  16362. #if !defined(NO_FILES)
  16363. | MG_FEATURES_FILES
  16364. #endif
  16365. #if !defined(NO_SSL)
  16366. | MG_FEATURES_SSL
  16367. #endif
  16368. #if !defined(NO_CGI)
  16369. | MG_FEATURES_CGI
  16370. #endif
  16371. #if defined(USE_IPV6)
  16372. | MG_FEATURES_IPV6
  16373. #endif
  16374. #if defined(USE_WEBSOCKET)
  16375. | MG_FEATURES_WEBSOCKET
  16376. #endif
  16377. #if defined(USE_LUA)
  16378. | MG_FEATURES_LUA
  16379. #endif
  16380. #if defined(USE_DUKTAPE)
  16381. | MG_FEATURES_SSJS
  16382. #endif
  16383. #if !defined(NO_CACHING)
  16384. | MG_FEATURES_CACHE
  16385. #endif
  16386. #if defined(USE_SERVER_STATS)
  16387. | MG_FEATURES_STATS
  16388. #endif
  16389. #if defined(USE_ZLIB)
  16390. | MG_FEATURES_COMPRESSION
  16391. #endif
  16392. /* Set some extra bits not defined in the API documentation.
  16393. * These bits may change without further notice. */
  16394. #if defined(MG_LEGACY_INTERFACE)
  16395. | 0x00008000u
  16396. #endif
  16397. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16398. | 0x00004000u
  16399. #endif
  16400. #if defined(MEMORY_DEBUGGING)
  16401. | 0x00001000u
  16402. #endif
  16403. #if defined(USE_TIMERS)
  16404. | 0x00020000u
  16405. #endif
  16406. #if !defined(NO_NONCE_CHECK)
  16407. | 0x00040000u
  16408. #endif
  16409. #if !defined(NO_POPEN)
  16410. | 0x00080000u
  16411. #endif
  16412. ;
  16413. return (feature & feature_set);
  16414. }
  16415. static size_t
  16416. mg_str_append(char **dst, char *end, const char *src)
  16417. {
  16418. size_t len = strlen(src);
  16419. if (*dst != end) {
  16420. /* Append src if enough space, or close dst. */
  16421. if ((size_t)(end - *dst) > len) {
  16422. strcpy(*dst, src);
  16423. *dst += len;
  16424. } else {
  16425. *dst = end;
  16426. }
  16427. }
  16428. return len;
  16429. }
  16430. /* Get system information. It can be printed or stored by the caller.
  16431. * Return the size of available information. */
  16432. int
  16433. mg_get_system_info(char *buffer, int buflen)
  16434. {
  16435. char *end, *append_eoobj = NULL, block[256];
  16436. size_t system_info_length = 0;
  16437. #if defined(_WIN32)
  16438. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16439. #else
  16440. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16441. #endif
  16442. if ((buffer == NULL) || (buflen < 1)) {
  16443. buflen = 0;
  16444. end = buffer;
  16445. } else {
  16446. *buffer = 0;
  16447. end = buffer + buflen;
  16448. }
  16449. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16450. /* has enough space to append eoobj */
  16451. append_eoobj = buffer;
  16452. end -= sizeof(eoobj) - 1;
  16453. }
  16454. system_info_length += mg_str_append(&buffer, end, "{");
  16455. /* Server version */
  16456. {
  16457. const char *version = mg_version();
  16458. mg_snprintf(NULL,
  16459. NULL,
  16460. block,
  16461. sizeof(block),
  16462. "%s\"version\" : \"%s\"",
  16463. eol,
  16464. version);
  16465. system_info_length += mg_str_append(&buffer, end, block);
  16466. }
  16467. /* System info */
  16468. {
  16469. #if defined(_WIN32)
  16470. DWORD dwVersion = 0;
  16471. DWORD dwMajorVersion = 0;
  16472. DWORD dwMinorVersion = 0;
  16473. SYSTEM_INFO si;
  16474. GetSystemInfo(&si);
  16475. #if defined(_MSC_VER)
  16476. #pragma warning(push)
  16477. /* GetVersion was declared deprecated */
  16478. #pragma warning(disable : 4996)
  16479. #endif
  16480. dwVersion = GetVersion();
  16481. #if defined(_MSC_VER)
  16482. #pragma warning(pop)
  16483. #endif
  16484. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16485. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16486. mg_snprintf(NULL,
  16487. NULL,
  16488. block,
  16489. sizeof(block),
  16490. ",%s\"os\" : \"Windows %u.%u\"",
  16491. eol,
  16492. (unsigned)dwMajorVersion,
  16493. (unsigned)dwMinorVersion);
  16494. system_info_length += mg_str_append(&buffer, end, block);
  16495. mg_snprintf(NULL,
  16496. NULL,
  16497. block,
  16498. sizeof(block),
  16499. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  16500. eol,
  16501. (unsigned)si.wProcessorArchitecture,
  16502. (unsigned)si.dwNumberOfProcessors,
  16503. (unsigned)si.dwActiveProcessorMask);
  16504. system_info_length += mg_str_append(&buffer, end, block);
  16505. #elif defined(__ZEPHYR__)
  16506. mg_snprintf(NULL,
  16507. NULL,
  16508. block,
  16509. sizeof(block),
  16510. ",%s\"os\" : \"%s %s\"",
  16511. eol,
  16512. "Zephyr OS",
  16513. ZEPHYR_VERSION);
  16514. system_info_length += mg_str_append(&buffer, end, block);
  16515. #else
  16516. struct utsname name;
  16517. memset(&name, 0, sizeof(name));
  16518. uname(&name);
  16519. mg_snprintf(NULL,
  16520. NULL,
  16521. block,
  16522. sizeof(block),
  16523. ",%s\"os\" : \"%s %s (%s) - %s\"",
  16524. eol,
  16525. name.sysname,
  16526. name.version,
  16527. name.release,
  16528. name.machine);
  16529. system_info_length += mg_str_append(&buffer, end, block);
  16530. #endif
  16531. }
  16532. /* Features */
  16533. {
  16534. mg_snprintf(NULL,
  16535. NULL,
  16536. block,
  16537. sizeof(block),
  16538. ",%s\"features\" : %lu"
  16539. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  16540. eol,
  16541. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16542. eol,
  16543. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16544. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16545. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16546. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16547. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16548. : "",
  16549. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16550. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16551. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16552. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  16553. system_info_length += mg_str_append(&buffer, end, block);
  16554. #if defined(USE_LUA)
  16555. mg_snprintf(NULL,
  16556. NULL,
  16557. block,
  16558. sizeof(block),
  16559. ",%s\"lua_version\" : \"%u (%s)\"",
  16560. eol,
  16561. (unsigned)LUA_VERSION_NUM,
  16562. LUA_RELEASE);
  16563. system_info_length += mg_str_append(&buffer, end, block);
  16564. #endif
  16565. #if defined(USE_DUKTAPE)
  16566. mg_snprintf(NULL,
  16567. NULL,
  16568. block,
  16569. sizeof(block),
  16570. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  16571. eol,
  16572. (unsigned)DUK_VERSION / 10000,
  16573. ((unsigned)DUK_VERSION / 100) % 100,
  16574. (unsigned)DUK_VERSION % 100);
  16575. system_info_length += mg_str_append(&buffer, end, block);
  16576. #endif
  16577. }
  16578. /* Build date */
  16579. {
  16580. #if defined(GCC_DIAGNOSTIC)
  16581. #if GCC_VERSION >= 40900
  16582. #pragma GCC diagnostic push
  16583. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  16584. #pragma GCC diagnostic ignored "-Wdate-time"
  16585. #endif
  16586. #endif
  16587. mg_snprintf(NULL,
  16588. NULL,
  16589. block,
  16590. sizeof(block),
  16591. ",%s\"build\" : \"%s\"",
  16592. eol,
  16593. __DATE__);
  16594. #if defined(GCC_DIAGNOSTIC)
  16595. #if GCC_VERSION >= 40900
  16596. #pragma GCC diagnostic pop
  16597. #endif
  16598. #endif
  16599. system_info_length += mg_str_append(&buffer, end, block);
  16600. }
  16601. /* Compiler information */
  16602. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16603. {
  16604. #if defined(_MSC_VER)
  16605. mg_snprintf(NULL,
  16606. NULL,
  16607. block,
  16608. sizeof(block),
  16609. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  16610. eol,
  16611. (unsigned)_MSC_VER,
  16612. (unsigned)_MSC_FULL_VER);
  16613. system_info_length += mg_str_append(&buffer, end, block);
  16614. #elif defined(__MINGW64__)
  16615. mg_snprintf(NULL,
  16616. NULL,
  16617. block,
  16618. sizeof(block),
  16619. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  16620. eol,
  16621. (unsigned)__MINGW64_VERSION_MAJOR,
  16622. (unsigned)__MINGW64_VERSION_MINOR);
  16623. system_info_length += mg_str_append(&buffer, end, block);
  16624. mg_snprintf(NULL,
  16625. NULL,
  16626. block,
  16627. sizeof(block),
  16628. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16629. eol,
  16630. (unsigned)__MINGW32_MAJOR_VERSION,
  16631. (unsigned)__MINGW32_MINOR_VERSION);
  16632. system_info_length += mg_str_append(&buffer, end, block);
  16633. #elif defined(__MINGW32__)
  16634. mg_snprintf(NULL,
  16635. NULL,
  16636. block,
  16637. sizeof(block),
  16638. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16639. eol,
  16640. (unsigned)__MINGW32_MAJOR_VERSION,
  16641. (unsigned)__MINGW32_MINOR_VERSION);
  16642. system_info_length += mg_str_append(&buffer, end, block);
  16643. #elif defined(__clang__)
  16644. mg_snprintf(NULL,
  16645. NULL,
  16646. block,
  16647. sizeof(block),
  16648. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  16649. eol,
  16650. __clang_major__,
  16651. __clang_minor__,
  16652. __clang_patchlevel__,
  16653. __clang_version__);
  16654. system_info_length += mg_str_append(&buffer, end, block);
  16655. #elif defined(__GNUC__)
  16656. mg_snprintf(NULL,
  16657. NULL,
  16658. block,
  16659. sizeof(block),
  16660. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  16661. eol,
  16662. (unsigned)__GNUC__,
  16663. (unsigned)__GNUC_MINOR__,
  16664. (unsigned)__GNUC_PATCHLEVEL__);
  16665. system_info_length += mg_str_append(&buffer, end, block);
  16666. #elif defined(__INTEL_COMPILER)
  16667. mg_snprintf(NULL,
  16668. NULL,
  16669. block,
  16670. sizeof(block),
  16671. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  16672. eol,
  16673. (unsigned)__INTEL_COMPILER);
  16674. system_info_length += mg_str_append(&buffer, end, block);
  16675. #elif defined(__BORLANDC__)
  16676. mg_snprintf(NULL,
  16677. NULL,
  16678. block,
  16679. sizeof(block),
  16680. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  16681. eol,
  16682. (unsigned)__BORLANDC__);
  16683. system_info_length += mg_str_append(&buffer, end, block);
  16684. #elif defined(__SUNPRO_C)
  16685. mg_snprintf(NULL,
  16686. NULL,
  16687. block,
  16688. sizeof(block),
  16689. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  16690. eol,
  16691. (unsigned)__SUNPRO_C);
  16692. system_info_length += mg_str_append(&buffer, end, block);
  16693. #else
  16694. mg_snprintf(NULL,
  16695. NULL,
  16696. block,
  16697. sizeof(block),
  16698. ",%s\"compiler\" : \"other\"",
  16699. eol);
  16700. system_info_length += mg_str_append(&buffer, end, block);
  16701. #endif
  16702. }
  16703. /* Determine 32/64 bit data mode.
  16704. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16705. {
  16706. mg_snprintf(NULL,
  16707. NULL,
  16708. block,
  16709. sizeof(block),
  16710. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16711. "char:%u/%u, "
  16712. "ptr:%u, size:%u, time:%u\"",
  16713. eol,
  16714. (unsigned)sizeof(short),
  16715. (unsigned)sizeof(int),
  16716. (unsigned)sizeof(long),
  16717. (unsigned)sizeof(long long),
  16718. (unsigned)sizeof(float),
  16719. (unsigned)sizeof(double),
  16720. (unsigned)sizeof(long double),
  16721. (unsigned)sizeof(char),
  16722. (unsigned)sizeof(wchar_t),
  16723. (unsigned)sizeof(void *),
  16724. (unsigned)sizeof(size_t),
  16725. (unsigned)sizeof(time_t));
  16726. system_info_length += mg_str_append(&buffer, end, block);
  16727. }
  16728. /* Terminate string */
  16729. if (append_eoobj) {
  16730. strcat(append_eoobj, eoobj);
  16731. }
  16732. system_info_length += sizeof(eoobj) - 1;
  16733. return (int)system_info_length;
  16734. }
  16735. /* Get context information. It can be printed or stored by the caller.
  16736. * Return the size of available information. */
  16737. int
  16738. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16739. {
  16740. #if defined(USE_SERVER_STATS)
  16741. char *end, *append_eoobj = NULL, block[256];
  16742. size_t context_info_length = 0;
  16743. #if defined(_WIN32)
  16744. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16745. #else
  16746. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16747. #endif
  16748. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16749. if ((buffer == NULL) || (buflen < 1)) {
  16750. buflen = 0;
  16751. end = buffer;
  16752. } else {
  16753. *buffer = 0;
  16754. end = buffer + buflen;
  16755. }
  16756. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16757. /* has enough space to append eoobj */
  16758. append_eoobj = buffer;
  16759. end -= sizeof(eoobj) - 1;
  16760. }
  16761. context_info_length += mg_str_append(&buffer, end, "{");
  16762. if (ms) { /* <-- should be always true */
  16763. /* Memory information */
  16764. mg_snprintf(NULL,
  16765. NULL,
  16766. block,
  16767. sizeof(block),
  16768. "%s\"memory\" : {%s"
  16769. "\"blocks\" : %i,%s"
  16770. "\"used\" : %" INT64_FMT ",%s"
  16771. "\"maxUsed\" : %" INT64_FMT "%s"
  16772. "}",
  16773. eol,
  16774. eol,
  16775. ms->blockCount,
  16776. eol,
  16777. ms->totalMemUsed,
  16778. eol,
  16779. ms->maxMemUsed,
  16780. eol);
  16781. context_info_length += mg_str_append(&buffer, end, block);
  16782. }
  16783. if (ctx) {
  16784. /* Declare all variables at begin of the block, to comply
  16785. * with old C standards. */
  16786. char start_time_str[64] = {0};
  16787. char now_str[64] = {0};
  16788. time_t start_time = ctx->start_time;
  16789. time_t now = time(NULL);
  16790. /* Connections information */
  16791. mg_snprintf(NULL,
  16792. NULL,
  16793. block,
  16794. sizeof(block),
  16795. ",%s\"connections\" : {%s"
  16796. "\"active\" : %i,%s"
  16797. "\"maxActive\" : %i,%s"
  16798. "\"total\" : %" INT64_FMT "%s"
  16799. "}",
  16800. eol,
  16801. eol,
  16802. ctx->active_connections,
  16803. eol,
  16804. ctx->max_connections,
  16805. eol,
  16806. ctx->total_connections,
  16807. eol);
  16808. context_info_length += mg_str_append(&buffer, end, block);
  16809. /* Requests information */
  16810. mg_snprintf(NULL,
  16811. NULL,
  16812. block,
  16813. sizeof(block),
  16814. ",%s\"requests\" : {%s"
  16815. "\"total\" : %" INT64_FMT "%s"
  16816. "}",
  16817. eol,
  16818. eol,
  16819. ctx->total_requests,
  16820. eol);
  16821. context_info_length += mg_str_append(&buffer, end, block);
  16822. /* Data information */
  16823. mg_snprintf(NULL,
  16824. NULL,
  16825. block,
  16826. sizeof(block),
  16827. ",%s\"data\" : {%s"
  16828. "\"read\" : %" INT64_FMT ",%s"
  16829. "\"written\" : %" INT64_FMT "%s"
  16830. "}",
  16831. eol,
  16832. eol,
  16833. ctx->total_data_read,
  16834. eol,
  16835. ctx->total_data_written,
  16836. eol);
  16837. context_info_length += mg_str_append(&buffer, end, block);
  16838. /* Execution time information */
  16839. gmt_time_string(start_time_str,
  16840. sizeof(start_time_str) - 1,
  16841. &start_time);
  16842. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16843. mg_snprintf(NULL,
  16844. NULL,
  16845. block,
  16846. sizeof(block),
  16847. ",%s\"time\" : {%s"
  16848. "\"uptime\" : %.0f,%s"
  16849. "\"start\" : \"%s\",%s"
  16850. "\"now\" : \"%s\"%s"
  16851. "}",
  16852. eol,
  16853. eol,
  16854. difftime(now, start_time),
  16855. eol,
  16856. start_time_str,
  16857. eol,
  16858. now_str,
  16859. eol);
  16860. context_info_length += mg_str_append(&buffer, end, block);
  16861. }
  16862. /* Terminate string */
  16863. if (append_eoobj) {
  16864. strcat(append_eoobj, eoobj);
  16865. }
  16866. context_info_length += sizeof(eoobj) - 1;
  16867. return (int)context_info_length;
  16868. #else
  16869. (void)ctx;
  16870. if ((buffer != NULL) && (buflen > 0)) {
  16871. *buffer = 0;
  16872. }
  16873. return 0;
  16874. #endif
  16875. }
  16876. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16877. /* Get connection information. It can be printed or stored by the caller.
  16878. * Return the size of available information. */
  16879. int
  16880. mg_get_connection_info(const struct mg_context *ctx,
  16881. int idx,
  16882. char *buffer,
  16883. int buflen)
  16884. {
  16885. const struct mg_connection *conn;
  16886. const struct mg_request_info *ri;
  16887. char *end, *append_eoobj = NULL, block[256];
  16888. size_t connection_info_length = 0;
  16889. int state = 0;
  16890. const char *state_str = "unknown";
  16891. #if defined(_WIN32)
  16892. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16893. #else
  16894. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16895. #endif
  16896. if ((buffer == NULL) || (buflen < 1)) {
  16897. buflen = 0;
  16898. end = buffer;
  16899. } else {
  16900. *buffer = 0;
  16901. end = buffer + buflen;
  16902. }
  16903. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16904. /* has enough space to append eoobj */
  16905. append_eoobj = buffer;
  16906. end -= sizeof(eoobj) - 1;
  16907. }
  16908. if ((ctx == NULL) || (idx < 0)) {
  16909. /* Parameter error */
  16910. return 0;
  16911. }
  16912. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16913. /* Out of range */
  16914. return 0;
  16915. }
  16916. /* Take connection [idx]. This connection is not locked in
  16917. * any way, so some other thread might use it. */
  16918. conn = (ctx->worker_connections) + idx;
  16919. /* Initialize output string */
  16920. connection_info_length += mg_str_append(&buffer, end, "{");
  16921. /* Init variables */
  16922. ri = &(conn->request_info);
  16923. #if defined(USE_SERVER_STATS)
  16924. state = conn->conn_state;
  16925. /* State as string */
  16926. switch (state) {
  16927. case 0:
  16928. state_str = "undefined";
  16929. break;
  16930. case 1:
  16931. state_str = "not used";
  16932. break;
  16933. case 2:
  16934. state_str = "init";
  16935. break;
  16936. case 3:
  16937. state_str = "ready";
  16938. break;
  16939. case 4:
  16940. state_str = "processing";
  16941. break;
  16942. case 5:
  16943. state_str = "processed";
  16944. break;
  16945. case 6:
  16946. state_str = "to close";
  16947. break;
  16948. case 7:
  16949. state_str = "closing";
  16950. break;
  16951. case 8:
  16952. state_str = "closed";
  16953. break;
  16954. case 9:
  16955. state_str = "done";
  16956. break;
  16957. }
  16958. #endif
  16959. /* Connection info */
  16960. if ((state >= 3) && (state < 9)) {
  16961. mg_snprintf(NULL,
  16962. NULL,
  16963. block,
  16964. sizeof(block),
  16965. "%s\"connection\" : {%s"
  16966. "\"remote\" : {%s"
  16967. "\"protocol\" : \"%s\",%s"
  16968. "\"addr\" : \"%s\",%s"
  16969. "\"port\" : %u%s"
  16970. "},%s"
  16971. "\"handled_requests\" : %u%s"
  16972. "}",
  16973. eol,
  16974. eol,
  16975. eol,
  16976. get_proto_name(conn),
  16977. eol,
  16978. ri->remote_addr,
  16979. eol,
  16980. ri->remote_port,
  16981. eol,
  16982. eol,
  16983. conn->handled_requests,
  16984. eol);
  16985. connection_info_length += mg_str_append(&buffer, end, block);
  16986. }
  16987. /* Request info */
  16988. if ((state >= 4) && (state < 6)) {
  16989. mg_snprintf(NULL,
  16990. NULL,
  16991. block,
  16992. sizeof(block),
  16993. "%s%s\"request_info\" : {%s"
  16994. "\"method\" : \"%s\",%s"
  16995. "\"uri\" : \"%s\",%s"
  16996. "\"query\" : %s%s%s%s"
  16997. "}",
  16998. (connection_info_length > 1 ? "," : ""),
  16999. eol,
  17000. eol,
  17001. ri->request_method,
  17002. eol,
  17003. ri->request_uri,
  17004. eol,
  17005. ri->query_string ? "\"" : "",
  17006. ri->query_string ? ri->query_string : "null",
  17007. ri->query_string ? "\"" : "",
  17008. eol);
  17009. connection_info_length += mg_str_append(&buffer, end, block);
  17010. }
  17011. /* Execution time information */
  17012. if ((state >= 2) && (state < 9)) {
  17013. char start_time_str[64] = {0};
  17014. char now_str[64] = {0};
  17015. time_t start_time = conn->conn_birth_time;
  17016. time_t now = time(NULL);
  17017. gmt_time_string(start_time_str,
  17018. sizeof(start_time_str) - 1,
  17019. &start_time);
  17020. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  17021. mg_snprintf(NULL,
  17022. NULL,
  17023. block,
  17024. sizeof(block),
  17025. "%s%s\"time\" : {%s"
  17026. "\"uptime\" : %.0f,%s"
  17027. "\"start\" : \"%s\",%s"
  17028. "\"now\" : \"%s\"%s"
  17029. "}",
  17030. (connection_info_length > 1 ? "," : ""),
  17031. eol,
  17032. eol,
  17033. difftime(now, start_time),
  17034. eol,
  17035. start_time_str,
  17036. eol,
  17037. now_str,
  17038. eol);
  17039. connection_info_length += mg_str_append(&buffer, end, block);
  17040. }
  17041. /* Remote user name */
  17042. if ((ri->remote_user) && (state < 9)) {
  17043. mg_snprintf(NULL,
  17044. NULL,
  17045. block,
  17046. sizeof(block),
  17047. "%s%s\"user\" : {%s"
  17048. "\"name\" : \"%s\",%s"
  17049. "}",
  17050. (connection_info_length > 1 ? "," : ""),
  17051. eol,
  17052. eol,
  17053. ri->remote_user,
  17054. eol);
  17055. connection_info_length += mg_str_append(&buffer, end, block);
  17056. }
  17057. /* Data block */
  17058. if (state >= 3) {
  17059. mg_snprintf(NULL,
  17060. NULL,
  17061. block,
  17062. sizeof(block),
  17063. "%s%s\"data\" : {%s"
  17064. "\"read\" : %" INT64_FMT ",%s"
  17065. "\"written\" : %" INT64_FMT "%s"
  17066. "}",
  17067. (connection_info_length > 1 ? "," : ""),
  17068. eol,
  17069. eol,
  17070. conn->consumed_content,
  17071. eol,
  17072. conn->num_bytes_sent,
  17073. eol);
  17074. connection_info_length += mg_str_append(&buffer, end, block);
  17075. }
  17076. /* State */
  17077. mg_snprintf(NULL,
  17078. NULL,
  17079. block,
  17080. sizeof(block),
  17081. "%s%s\"state\" : \"%s\"",
  17082. (connection_info_length > 1 ? "," : ""),
  17083. eol,
  17084. state_str);
  17085. connection_info_length += mg_str_append(&buffer, end, block);
  17086. /* Terminate string */
  17087. if (append_eoobj) {
  17088. strcat(append_eoobj, eoobj);
  17089. }
  17090. connection_info_length += sizeof(eoobj) - 1;
  17091. return (int)connection_info_length;
  17092. }
  17093. #endif
  17094. /* Initialize this library. This function does not need to be thread safe.
  17095. */
  17096. unsigned
  17097. mg_init_library(unsigned features)
  17098. {
  17099. #if !defined(NO_SSL)
  17100. char ebuf[128];
  17101. #endif
  17102. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17103. unsigned features_inited = features_to_init;
  17104. if (mg_init_library_called <= 0) {
  17105. /* Not initialized yet */
  17106. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17107. return 0;
  17108. }
  17109. }
  17110. mg_global_lock();
  17111. if (mg_init_library_called <= 0) {
  17112. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17113. /* Fatal error - abort start. However, this situation should
  17114. * never occur in practice. */
  17115. mg_global_unlock();
  17116. return 0;
  17117. }
  17118. #if defined(_WIN32)
  17119. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  17120. #else
  17121. pthread_mutexattr_init(&pthread_mutex_attr);
  17122. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17123. #endif
  17124. #if defined(USE_LUA)
  17125. lua_init_optional_libraries();
  17126. #endif
  17127. }
  17128. mg_global_unlock();
  17129. #if !defined(NO_SSL)
  17130. if (features_to_init & MG_FEATURES_SSL) {
  17131. if (!mg_ssl_initialized) {
  17132. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17133. mg_ssl_initialized = 1;
  17134. } else {
  17135. (void)ebuf;
  17136. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17137. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17138. }
  17139. } else {
  17140. /* ssl already initialized */
  17141. }
  17142. }
  17143. #endif
  17144. /* Start WinSock for Windows */
  17145. mg_global_lock();
  17146. if (mg_init_library_called <= 0) {
  17147. #if defined(_WIN32)
  17148. WSADATA data;
  17149. WSAStartup(MAKEWORD(2, 2), &data);
  17150. #endif /* _WIN32 */
  17151. mg_init_library_called = 1;
  17152. } else {
  17153. mg_init_library_called++;
  17154. }
  17155. mg_global_unlock();
  17156. return features_inited;
  17157. }
  17158. /* Un-initialize this library. */
  17159. unsigned
  17160. mg_exit_library(void)
  17161. {
  17162. if (mg_init_library_called <= 0) {
  17163. return 0;
  17164. }
  17165. mg_global_lock();
  17166. mg_init_library_called--;
  17167. if (mg_init_library_called == 0) {
  17168. #if defined(_WIN32)
  17169. (void)WSACleanup();
  17170. #endif /* _WIN32 */
  17171. #if !defined(NO_SSL)
  17172. if (mg_ssl_initialized) {
  17173. uninitialize_ssl();
  17174. mg_ssl_initialized = 0;
  17175. }
  17176. #endif
  17177. #if defined(_WIN32)
  17178. (void)pthread_mutex_destroy(&global_log_file_lock);
  17179. #else
  17180. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17181. #endif
  17182. (void)pthread_key_delete(sTlsKey);
  17183. #if defined(USE_LUA)
  17184. lua_exit_optional_libraries();
  17185. #endif
  17186. mg_global_unlock();
  17187. (void)pthread_mutex_destroy(&global_lock_mutex);
  17188. return 1;
  17189. }
  17190. mg_global_unlock();
  17191. return 1;
  17192. }
  17193. /* End of civetweb.c */