civetweb.c 502 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901
  1. /* Copyright (c) 2013-2017 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  76. #define mg_static_assert _Static_assert
  77. #elif defined(__cplusplus) && __cplusplus >= 201103L
  78. #define mg_static_assert static_assert
  79. #else
  80. char static_assert_replacement[1];
  81. #define mg_static_assert(cond, txt) \
  82. extern char static_assert_replacement[(cond) ? 1 : -1]
  83. #endif
  84. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  85. "int data type size check");
  86. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  87. "pointer data type size check");
  88. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  89. /* Alternative queue is well tested and should be the new default */
  90. #ifdef NO_ALTERNATIVE_QUEUE
  91. #ifdef ALTERNATIVE_QUEUE
  92. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  93. #endif
  94. #else
  95. #define ALTERNATIVE_QUEUE
  96. #endif
  97. /* DTL -- including winsock2.h works better if lean and mean */
  98. #ifndef WIN32_LEAN_AND_MEAN
  99. #define WIN32_LEAN_AND_MEAN
  100. #endif
  101. #if defined(__SYMBIAN32__)
  102. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  103. * Symbian is no longer maintained since 2014-01-01.
  104. * Recent versions of CivetWeb are no longer tested for Symbian.
  105. * It makes no sense, to support an abandoned operating system.
  106. * All remaining "#ifdef __SYMBIAN__" cases will be dropped from
  107. * the code sooner or later.
  108. */
  109. #pragma message \
  110. "Symbian is no longer maintained. CivetWeb will drop Symbian support."
  111. #define NO_SSL /* SSL is not supported */
  112. #define NO_CGI /* CGI is not supported */
  113. #define PATH_MAX FILENAME_MAX
  114. #endif /* __SYMBIAN32__ */
  115. #ifndef CIVETWEB_HEADER_INCLUDED
  116. /* Include the header file here, so the CivetWeb interface is defined for the
  117. * entire implementation, including the following forward definitions. */
  118. #include "civetweb.h"
  119. #endif
  120. #if !defined(DEBUG_TRACE)
  121. #if defined(DEBUG)
  122. static void DEBUG_TRACE_FUNC(const char *func,
  123. unsigned line,
  124. PRINTF_FORMAT_STRING(const char *fmt),
  125. ...) PRINTF_ARGS(3, 4);
  126. #define DEBUG_TRACE(fmt, ...) \
  127. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  128. #define NEED_DEBUG_TRACE_FUNC
  129. #else
  130. #define DEBUG_TRACE(fmt, ...) \
  131. do { \
  132. } while (0)
  133. #endif /* DEBUG */
  134. #endif /* DEBUG_TRACE */
  135. #if !defined(DEBUG_ASSERT)
  136. #if defined(DEBUG)
  137. #define DEBUG_ASSERT(cond) \
  138. do { \
  139. if (!(cond)) { \
  140. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  141. exit(2); /* Exit with error */ \
  142. } \
  143. } while (0)
  144. #else
  145. #define DEBUG_ASSERT(cond)
  146. #endif /* DEBUG */
  147. #endif
  148. #ifndef IGNORE_UNUSED_RESULT
  149. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  150. #endif
  151. #if defined(__GNUC__) || defined(__MINGW32__)
  152. /* GCC unused function attribute seems fundamentally broken.
  153. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  154. * OR UNUSED" for individual functions failed.
  155. * Either the compiler creates an "unused-function" warning if a
  156. * function is not marked with __attribute__((unused)).
  157. * On the other hand, if the function is marked with this attribute,
  158. * but is used, the compiler raises a completely idiotic
  159. * "used-but-marked-unused" warning - and
  160. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  161. * raises error: unknown option after "#pragma GCC diagnostic".
  162. * Disable this warning completely, until the GCC guys sober up
  163. * again.
  164. */
  165. #pragma GCC diagnostic ignored "-Wunused-function"
  166. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  167. #else
  168. #define FUNCTION_MAY_BE_UNUSED
  169. #endif
  170. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  171. #include <sys/types.h>
  172. #include <sys/stat.h>
  173. #include <errno.h>
  174. #include <signal.h>
  175. #include <fcntl.h>
  176. #endif /* !_WIN32_WCE */
  177. #ifdef __clang__
  178. /* When using -Weverything, clang does not accept it's own headers
  179. * in a release build configuration. Disable what is too much in
  180. * -Weverything. */
  181. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  182. #endif
  183. #if defined(__GNUC__) || defined(__MINGW32__)
  184. /* Who on earth came to the conclusion, using __DATE__ should rise
  185. * an "expansion of date or time macro is not reproducible"
  186. * warning. That's exactly what was intended by using this macro.
  187. * Just disable this nonsense warning. */
  188. /* And disabling them does not work either:
  189. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  190. * #pragma clang diagnostic ignored "-Wdate-time"
  191. * So we just have to disable ALL warnings for some lines
  192. * of code.
  193. * This seems to be a known GCC bug, not resolved since 2012:
  194. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  195. */
  196. #endif
  197. #ifdef __MACH__ /* Apple OSX section */
  198. #ifdef __clang__
  199. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  200. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  201. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  202. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  203. #endif
  204. #endif
  205. #define CLOCK_MONOTONIC (1)
  206. #define CLOCK_REALTIME (2)
  207. #include <sys/errno.h>
  208. #include <sys/time.h>
  209. #include <mach/clock.h>
  210. #include <mach/mach.h>
  211. #include <mach/mach_time.h>
  212. /* clock_gettime is not implemented on OSX prior to 10.12 */
  213. static int
  214. _civet_clock_gettime(int clk_id, struct timespec *t)
  215. {
  216. memset(t, 0, sizeof(*t));
  217. if (clk_id == CLOCK_REALTIME) {
  218. struct timeval now;
  219. int rv = gettimeofday(&now, NULL);
  220. if (rv) {
  221. return rv;
  222. }
  223. t->tv_sec = now.tv_sec;
  224. t->tv_nsec = now.tv_usec * 1000;
  225. return 0;
  226. } else if (clk_id == CLOCK_MONOTONIC) {
  227. static uint64_t clock_start_time = 0;
  228. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  229. uint64_t now = mach_absolute_time();
  230. if (clock_start_time == 0) {
  231. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  232. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  233. /* appease "unused variable" warning for release builds */
  234. (void)mach_status;
  235. clock_start_time = now;
  236. }
  237. now = (uint64_t)((double)(now - clock_start_time)
  238. * (double)timebase_ifo.numer
  239. / (double)timebase_ifo.denom);
  240. t->tv_sec = now / 1000000000;
  241. t->tv_nsec = now % 1000000000;
  242. return 0;
  243. }
  244. return -1; /* EINVAL - Clock ID is unknown */
  245. }
  246. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  247. #ifdef __CLOCK_AVAILABILITY
  248. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  249. * declared but it may be NULL at runtime. So we need to check before using
  250. * it. */
  251. static int
  252. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  253. {
  254. if (clock_gettime) {
  255. return clock_gettime(clk_id, t);
  256. }
  257. return _civet_clock_gettime(clk_id, t);
  258. }
  259. #define clock_gettime _civet_safe_clock_gettime
  260. #else
  261. #define clock_gettime _civet_clock_gettime
  262. #endif
  263. #endif
  264. #include <time.h>
  265. #include <stdlib.h>
  266. #include <stdarg.h>
  267. #include <string.h>
  268. #include <ctype.h>
  269. #include <limits.h>
  270. #include <stddef.h>
  271. #include <stdio.h>
  272. #include <stdint.h>
  273. #ifndef INT64_MAX
  274. #define INT64_MAX (9223372036854775807)
  275. #endif
  276. #ifndef MAX_WORKER_THREADS
  277. #define MAX_WORKER_THREADS (1024 * 64)
  278. #endif
  279. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  280. #define SOCKET_TIMEOUT_QUANTUM (2000)
  281. #endif
  282. #define SHUTDOWN_RD (0)
  283. #define SHUTDOWN_WR (1)
  284. #define SHUTDOWN_BOTH (2)
  285. mg_static_assert(MAX_WORKER_THREADS >= 1,
  286. "worker threads must be a positive number");
  287. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  288. "size_t data type size check");
  289. #if defined(_WIN32) \
  290. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  291. #include <windows.h>
  292. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  293. #include <ws2tcpip.h>
  294. typedef const char *SOCK_OPT_TYPE;
  295. #if !defined(PATH_MAX)
  296. #define W_PATH_MAX (MAX_PATH)
  297. /* at most three UTF-8 chars per wchar_t */
  298. #define PATH_MAX (W_PATH_MAX * 3)
  299. #else
  300. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  301. #endif
  302. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  303. #ifndef _IN_PORT_T
  304. #ifndef in_port_t
  305. #define in_port_t u_short
  306. #endif
  307. #endif
  308. #ifndef _WIN32_WCE
  309. #include <process.h>
  310. #include <direct.h>
  311. #include <io.h>
  312. #else /* _WIN32_WCE */
  313. #define NO_CGI /* WinCE has no pipes */
  314. #define NO_POPEN /* WinCE has no popen */
  315. typedef long off_t;
  316. #define errno ((int)(GetLastError()))
  317. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  318. #endif /* _WIN32_WCE */
  319. #define MAKEUQUAD(lo, hi) \
  320. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  321. #define RATE_DIFF (10000000) /* 100 nsecs */
  322. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  323. #define SYS2UNIX_TIME(lo, hi) \
  324. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  325. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  326. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  327. * Also use _strtoui64 on modern M$ compilers */
  328. #if defined(_MSC_VER)
  329. #if (_MSC_VER < 1300)
  330. #define STRX(x) #x
  331. #define STR(x) STRX(x)
  332. #define __func__ __FILE__ ":" STR(__LINE__)
  333. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  334. #define strtoll(x, y, z) (_atoi64(x))
  335. #else
  336. #define __func__ __FUNCTION__
  337. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  338. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  339. #endif
  340. #endif /* _MSC_VER */
  341. #define ERRNO ((int)(GetLastError()))
  342. #define NO_SOCKLEN_T
  343. #if defined(_WIN64) || defined(__MINGW64__)
  344. #define SSL_LIB "ssleay64.dll"
  345. #define CRYPTO_LIB "libeay64.dll"
  346. #else
  347. #define SSL_LIB "ssleay32.dll"
  348. #define CRYPTO_LIB "libeay32.dll"
  349. #endif
  350. #define O_NONBLOCK (0)
  351. #ifndef W_OK
  352. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  353. #endif
  354. #if !defined(EWOULDBLOCK)
  355. #define EWOULDBLOCK WSAEWOULDBLOCK
  356. #endif /* !EWOULDBLOCK */
  357. #define _POSIX_
  358. #define INT64_FMT "I64d"
  359. #define UINT64_FMT "I64u"
  360. #define WINCDECL __cdecl
  361. #define vsnprintf_impl _vsnprintf
  362. #define access _access
  363. #define mg_sleep(x) (Sleep(x))
  364. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  365. #ifndef popen
  366. #define popen(x, y) (_popen(x, y))
  367. #endif
  368. #ifndef pclose
  369. #define pclose(x) (_pclose(x))
  370. #endif
  371. #define close(x) (_close(x))
  372. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  373. #define RTLD_LAZY (0)
  374. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  375. #define fdopen(x, y) (_fdopen((x), (y)))
  376. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  377. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  378. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  379. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  380. #define sleep(x) (Sleep((x)*1000))
  381. #define rmdir(x) (_rmdir(x))
  382. #define timegm(x) (_mkgmtime(x))
  383. #if !defined(fileno)
  384. #define fileno(x) (_fileno(x))
  385. #endif /* !fileno MINGW #defines fileno */
  386. typedef HANDLE pthread_mutex_t;
  387. typedef DWORD pthread_key_t;
  388. typedef HANDLE pthread_t;
  389. typedef struct {
  390. CRITICAL_SECTION threadIdSec;
  391. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  392. } pthread_cond_t;
  393. #ifndef __clockid_t_defined
  394. typedef DWORD clockid_t;
  395. #endif
  396. #ifndef CLOCK_MONOTONIC
  397. #define CLOCK_MONOTONIC (1)
  398. #endif
  399. #ifndef CLOCK_REALTIME
  400. #define CLOCK_REALTIME (2)
  401. #endif
  402. #ifndef CLOCK_THREAD
  403. #define CLOCK_THREAD (3)
  404. #endif
  405. #ifndef CLOCK_PROCESS
  406. #define CLOCK_PROCESS (4)
  407. #endif
  408. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  409. #define _TIMESPEC_DEFINED
  410. #endif
  411. #ifndef _TIMESPEC_DEFINED
  412. struct timespec {
  413. time_t tv_sec; /* seconds */
  414. long tv_nsec; /* nanoseconds */
  415. };
  416. #endif
  417. #if !defined(WIN_PTHREADS_TIME_H)
  418. #define MUST_IMPLEMENT_CLOCK_GETTIME
  419. #endif
  420. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  421. #define clock_gettime mg_clock_gettime
  422. static int
  423. clock_gettime(clockid_t clk_id, struct timespec *tp)
  424. {
  425. FILETIME ft;
  426. ULARGE_INTEGER li, li2;
  427. BOOL ok = FALSE;
  428. double d;
  429. static double perfcnt_per_sec = 0.0;
  430. if (tp) {
  431. memset(tp, 0, sizeof(*tp));
  432. if (clk_id == CLOCK_REALTIME) {
  433. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  434. GetSystemTimeAsFileTime(&ft);
  435. li.LowPart = ft.dwLowDateTime;
  436. li.HighPart = ft.dwHighDateTime;
  437. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  438. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  439. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  440. ok = TRUE;
  441. /* END: CLOCK_REALTIME */
  442. } else if (clk_id == CLOCK_MONOTONIC) {
  443. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  444. if (perfcnt_per_sec == 0.0) {
  445. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  446. perfcnt_per_sec = 1.0 / li.QuadPart;
  447. }
  448. if (perfcnt_per_sec != 0.0) {
  449. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  450. d = li.QuadPart * perfcnt_per_sec;
  451. tp->tv_sec = (time_t)d;
  452. d -= tp->tv_sec;
  453. tp->tv_nsec = (long)(d * 1.0E9);
  454. ok = TRUE;
  455. }
  456. /* END: CLOCK_MONOTONIC */
  457. } else if (clk_id == CLOCK_THREAD) {
  458. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  459. FILETIME t_create, t_exit, t_kernel, t_user;
  460. if (GetThreadTimes(GetCurrentThread(),
  461. &t_create,
  462. &t_exit,
  463. &t_kernel,
  464. &t_user)) {
  465. li.LowPart = t_user.dwLowDateTime;
  466. li.HighPart = t_user.dwHighDateTime;
  467. li2.LowPart = t_kernel.dwLowDateTime;
  468. li2.HighPart = t_kernel.dwHighDateTime;
  469. li.QuadPart += li2.QuadPart;
  470. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  471. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  472. ok = TRUE;
  473. }
  474. /* END: CLOCK_THREAD */
  475. } else if (clk_id == CLOCK_PROCESS) {
  476. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  477. FILETIME t_create, t_exit, t_kernel, t_user;
  478. if (GetProcessTimes(GetCurrentProcess(),
  479. &t_create,
  480. &t_exit,
  481. &t_kernel,
  482. &t_user)) {
  483. li.LowPart = t_user.dwLowDateTime;
  484. li.HighPart = t_user.dwHighDateTime;
  485. li2.LowPart = t_kernel.dwLowDateTime;
  486. li2.HighPart = t_kernel.dwHighDateTime;
  487. li.QuadPart += li2.QuadPart;
  488. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  489. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  490. ok = TRUE;
  491. }
  492. /* END: CLOCK_PROCESS */
  493. } else {
  494. /* BEGIN: unknown clock */
  495. /* ok = FALSE; already set by init */
  496. /* END: unknown clock */
  497. }
  498. }
  499. return ok ? 0 : -1;
  500. }
  501. #endif
  502. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  503. static int pthread_mutex_lock(pthread_mutex_t *);
  504. static int pthread_mutex_unlock(pthread_mutex_t *);
  505. static void path_to_unicode(const struct mg_connection *conn,
  506. const char *path,
  507. wchar_t *wbuf,
  508. size_t wbuf_len);
  509. /* All file operations need to be rewritten to solve #246. */
  510. #include "file_ops.inl"
  511. struct mg_file;
  512. static const char *
  513. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  514. /* POSIX dirent interface */
  515. struct dirent {
  516. char d_name[PATH_MAX];
  517. };
  518. typedef struct DIR {
  519. HANDLE handle;
  520. WIN32_FIND_DATAW info;
  521. struct dirent result;
  522. } DIR;
  523. #if defined(_WIN32) && !defined(POLLIN)
  524. #ifndef HAVE_POLL
  525. struct pollfd {
  526. SOCKET fd;
  527. short events;
  528. short revents;
  529. };
  530. #define POLLIN (0x0300)
  531. #endif
  532. #endif
  533. /* Mark required libraries */
  534. #if defined(_MSC_VER)
  535. #pragma comment(lib, "Ws2_32.lib")
  536. #endif
  537. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  538. WINDOWS / UNIX include block */
  539. #include <sys/wait.h>
  540. #include <sys/socket.h>
  541. #include <sys/poll.h>
  542. #include <netinet/in.h>
  543. #include <arpa/inet.h>
  544. #include <sys/time.h>
  545. #include <sys/utsname.h>
  546. #include <stdint.h>
  547. #include <inttypes.h>
  548. #include <netdb.h>
  549. #include <netinet/tcp.h>
  550. typedef const void *SOCK_OPT_TYPE;
  551. #if defined(ANDROID)
  552. typedef unsigned short int in_port_t;
  553. #endif
  554. #include <pwd.h>
  555. #include <unistd.h>
  556. #include <grp.h>
  557. #include <dirent.h>
  558. #define vsnprintf_impl vsnprintf
  559. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  560. #include <dlfcn.h>
  561. #endif
  562. #include <pthread.h>
  563. #if defined(__MACH__)
  564. #define SSL_LIB "libssl.dylib"
  565. #define CRYPTO_LIB "libcrypto.dylib"
  566. #else
  567. #if !defined(SSL_LIB)
  568. #define SSL_LIB "libssl.so"
  569. #endif
  570. #if !defined(CRYPTO_LIB)
  571. #define CRYPTO_LIB "libcrypto.so"
  572. #endif
  573. #endif
  574. #ifndef O_BINARY
  575. #define O_BINARY (0)
  576. #endif /* O_BINARY */
  577. #define closesocket(a) (close(a))
  578. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  579. #define mg_remove(conn, x) (remove(x))
  580. #define mg_sleep(x) (usleep((x)*1000))
  581. #define mg_opendir(conn, x) (opendir(x))
  582. #define mg_closedir(x) (closedir(x))
  583. #define mg_readdir(x) (readdir(x))
  584. #define ERRNO (errno)
  585. #define INVALID_SOCKET (-1)
  586. #define INT64_FMT PRId64
  587. #define UINT64_FMT PRIu64
  588. typedef int SOCKET;
  589. #define WINCDECL
  590. #if defined(__hpux)
  591. /* HPUX 11 does not have monotonic, fall back to realtime */
  592. #ifndef CLOCK_MONOTONIC
  593. #define CLOCK_MONOTONIC CLOCK_REALTIME
  594. #endif
  595. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  596. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  597. * the prototypes use int* rather than socklen_t* which matches the
  598. * actual library expectation. When called with the wrong size arg
  599. * accept() returns a zero client inet addr and check_acl() always
  600. * fails. Since socklen_t is widely used below, just force replace
  601. * their typedef with int. - DTL
  602. */
  603. #define socklen_t int
  604. #endif /* hpux */
  605. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  606. WINDOWS / UNIX include block */
  607. /* va_copy should always be a macro, C99 and C++11 - DTL */
  608. #ifndef va_copy
  609. #define va_copy(x, y) ((x) = (y))
  610. #endif
  611. #ifdef _WIN32
  612. /* Create substitutes for POSIX functions in Win32. */
  613. #if defined(__MINGW32__)
  614. /* Show no warning in case system functions are not used. */
  615. #pragma GCC diagnostic push
  616. #pragma GCC diagnostic ignored "-Wunused-function"
  617. #endif
  618. static CRITICAL_SECTION global_log_file_lock;
  619. FUNCTION_MAY_BE_UNUSED
  620. static DWORD
  621. pthread_self(void)
  622. {
  623. return GetCurrentThreadId();
  624. }
  625. FUNCTION_MAY_BE_UNUSED
  626. static int
  627. pthread_key_create(
  628. pthread_key_t *key,
  629. void (*_ignored)(void *) /* destructor not supported for Windows */
  630. )
  631. {
  632. (void)_ignored;
  633. if ((key != 0)) {
  634. *key = TlsAlloc();
  635. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  636. }
  637. return -2;
  638. }
  639. FUNCTION_MAY_BE_UNUSED
  640. static int
  641. pthread_key_delete(pthread_key_t key)
  642. {
  643. return TlsFree(key) ? 0 : 1;
  644. }
  645. FUNCTION_MAY_BE_UNUSED
  646. static int
  647. pthread_setspecific(pthread_key_t key, void *value)
  648. {
  649. return TlsSetValue(key, value) ? 0 : 1;
  650. }
  651. FUNCTION_MAY_BE_UNUSED
  652. static void *
  653. pthread_getspecific(pthread_key_t key)
  654. {
  655. return TlsGetValue(key);
  656. }
  657. #if defined(__MINGW32__)
  658. /* Enable unused function warning again */
  659. #pragma GCC diagnostic pop
  660. #endif
  661. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  662. #else
  663. static pthread_mutexattr_t pthread_mutex_attr;
  664. #endif /* _WIN32 */
  665. #define PASSWORDS_FILE_NAME ".htpasswd"
  666. #define CGI_ENVIRONMENT_SIZE (4096)
  667. #define MAX_CGI_ENVIR_VARS (256)
  668. #define MG_BUF_LEN (8192)
  669. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  670. #if defined(_WIN32_WCE)
  671. /* Create substitutes for POSIX functions in Win32. */
  672. #if defined(__MINGW32__)
  673. /* Show no warning in case system functions are not used. */
  674. #pragma GCC diagnostic push
  675. #pragma GCC diagnostic ignored "-Wunused-function"
  676. #endif
  677. FUNCTION_MAY_BE_UNUSED
  678. static time_t
  679. time(time_t *ptime)
  680. {
  681. time_t t;
  682. SYSTEMTIME st;
  683. FILETIME ft;
  684. GetSystemTime(&st);
  685. SystemTimeToFileTime(&st, &ft);
  686. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  687. if (ptime != NULL) {
  688. *ptime = t;
  689. }
  690. return t;
  691. }
  692. FUNCTION_MAY_BE_UNUSED
  693. static struct tm *
  694. localtime_s(const time_t *ptime, struct tm *ptm)
  695. {
  696. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  697. FILETIME ft, lft;
  698. SYSTEMTIME st;
  699. TIME_ZONE_INFORMATION tzinfo;
  700. if (ptm == NULL) {
  701. return NULL;
  702. }
  703. *(int64_t *)&ft = t;
  704. FileTimeToLocalFileTime(&ft, &lft);
  705. FileTimeToSystemTime(&lft, &st);
  706. ptm->tm_year = st.wYear - 1900;
  707. ptm->tm_mon = st.wMonth - 1;
  708. ptm->tm_wday = st.wDayOfWeek;
  709. ptm->tm_mday = st.wDay;
  710. ptm->tm_hour = st.wHour;
  711. ptm->tm_min = st.wMinute;
  712. ptm->tm_sec = st.wSecond;
  713. ptm->tm_yday = 0; /* hope nobody uses this */
  714. ptm->tm_isdst =
  715. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  716. return ptm;
  717. }
  718. FUNCTION_MAY_BE_UNUSED
  719. static struct tm *
  720. gmtime_s(const time_t *ptime, struct tm *ptm)
  721. {
  722. /* FIXME(lsm): fix this. */
  723. return localtime_s(ptime, ptm);
  724. }
  725. static int mg_atomic_inc(volatile int *addr);
  726. static struct tm tm_array[MAX_WORKER_THREADS];
  727. static int tm_index = 0;
  728. FUNCTION_MAY_BE_UNUSED
  729. static struct tm *
  730. localtime(const time_t *ptime)
  731. {
  732. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  733. return localtime_s(ptime, tm_array + i);
  734. }
  735. FUNCTION_MAY_BE_UNUSED
  736. static struct tm *
  737. gmtime(const time_t *ptime)
  738. {
  739. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  740. return gmtime_s(ptime, tm_array + i);
  741. }
  742. FUNCTION_MAY_BE_UNUSED
  743. static size_t
  744. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  745. {
  746. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  747. * for WinCE"); */
  748. return 0;
  749. }
  750. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  751. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  752. #define remove(f) mg_remove(NULL, f)
  753. FUNCTION_MAY_BE_UNUSED
  754. static int
  755. rename(const char *a, const char *b)
  756. {
  757. wchar_t wa[W_PATH_MAX];
  758. wchar_t wb[W_PATH_MAX];
  759. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  760. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  761. return MoveFileW(wa, wb) ? 0 : -1;
  762. }
  763. struct stat {
  764. int64_t st_size;
  765. time_t st_mtime;
  766. };
  767. FUNCTION_MAY_BE_UNUSED
  768. static int
  769. stat(const char *name, struct stat *st)
  770. {
  771. wchar_t wbuf[W_PATH_MAX];
  772. WIN32_FILE_ATTRIBUTE_DATA attr;
  773. time_t creation_time, write_time;
  774. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  775. memset(&attr, 0, sizeof(attr));
  776. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  777. st->st_size =
  778. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  779. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  780. attr.ftLastWriteTime.dwHighDateTime);
  781. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  782. attr.ftCreationTime.dwHighDateTime);
  783. if (creation_time > write_time) {
  784. st->st_mtime = creation_time;
  785. } else {
  786. st->st_mtime = write_time;
  787. }
  788. return 0;
  789. }
  790. #define access(x, a) 1 /* not required anyway */
  791. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  792. /* Values from errno.h in Windows SDK (Visual Studio). */
  793. #define EEXIST 17
  794. #define EACCES 13
  795. #define ENOENT 2
  796. #if defined(__MINGW32__)
  797. /* Enable unused function warning again */
  798. #pragma GCC diagnostic pop
  799. #endif
  800. #endif /* defined(_WIN32_WCE) */
  801. #if defined(__GNUC__) || defined(__MINGW32__)
  802. /* Show no warning in case system functions are not used. */
  803. #define GCC_VERSION \
  804. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  805. #if GCC_VERSION >= 40500
  806. #pragma GCC diagnostic push
  807. #pragma GCC diagnostic ignored "-Wunused-function"
  808. #endif /* GCC_VERSION >= 40500 */
  809. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  810. #if defined(__clang__)
  811. /* Show no warning in case system functions are not used. */
  812. #pragma clang diagnostic push
  813. #pragma clang diagnostic ignored "-Wunused-function"
  814. #endif
  815. static pthread_mutex_t global_lock_mutex;
  816. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  817. /* Forward declaration for Windows */
  818. FUNCTION_MAY_BE_UNUSED
  819. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  820. FUNCTION_MAY_BE_UNUSED
  821. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  822. #endif
  823. FUNCTION_MAY_BE_UNUSED
  824. static void
  825. mg_global_lock(void)
  826. {
  827. (void)pthread_mutex_lock(&global_lock_mutex);
  828. }
  829. FUNCTION_MAY_BE_UNUSED
  830. static void
  831. mg_global_unlock(void)
  832. {
  833. (void)pthread_mutex_unlock(&global_lock_mutex);
  834. }
  835. FUNCTION_MAY_BE_UNUSED
  836. static int
  837. mg_atomic_inc(volatile int *addr)
  838. {
  839. int ret;
  840. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  841. /* Depending on the SDK, this function uses either
  842. * (volatile unsigned int *) or (volatile LONG *),
  843. * so whatever you use, the other SDK is likely to raise a warning. */
  844. ret = InterlockedIncrement((volatile long *)addr);
  845. #elif defined(__GNUC__) \
  846. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  847. && !defined(NO_ATOMICS)
  848. ret = __sync_add_and_fetch(addr, 1);
  849. #else
  850. mg_global_lock();
  851. ret = (++(*addr));
  852. mg_global_unlock();
  853. #endif
  854. return ret;
  855. }
  856. FUNCTION_MAY_BE_UNUSED
  857. static int
  858. mg_atomic_dec(volatile int *addr)
  859. {
  860. int ret;
  861. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  862. /* Depending on the SDK, this function uses either
  863. * (volatile unsigned int *) or (volatile LONG *),
  864. * so whatever you use, the other SDK is likely to raise a warning. */
  865. ret = InterlockedDecrement((volatile long *)addr);
  866. #elif defined(__GNUC__) \
  867. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  868. && !defined(NO_ATOMICS)
  869. ret = __sync_sub_and_fetch(addr, 1);
  870. #else
  871. mg_global_lock();
  872. ret = (--(*addr));
  873. mg_global_unlock();
  874. #endif
  875. return ret;
  876. }
  877. #if defined(USE_SERVER_STATS)
  878. static int64_t
  879. mg_atomic_add(volatile int64_t *addr, int64_t value)
  880. {
  881. int64_t ret;
  882. #if defined(_WIN64) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  883. ret = InterlockedAdd64(addr, value);
  884. #elif defined(__GNUC__) \
  885. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  886. && !defined(NO_ATOMICS)
  887. ret = __sync_add_and_fetch(addr, value);
  888. #else
  889. mg_global_lock();
  890. *addr += value;
  891. ret = (*addr);
  892. mg_global_unlock();
  893. #endif
  894. return ret;
  895. }
  896. #endif
  897. #if defined(__GNUC__)
  898. /* Show no warning in case system functions are not used. */
  899. #if GCC_VERSION >= 40500
  900. #pragma GCC diagnostic pop
  901. #endif /* GCC_VERSION >= 40500 */
  902. #endif /* defined(__GNUC__) */
  903. #if defined(__clang__)
  904. /* Show no warning in case system functions are not used. */
  905. #pragma clang diagnostic pop
  906. #endif
  907. #if defined(USE_SERVER_STATS)
  908. struct mg_memory_stat {
  909. volatile int64_t totalMemUsed;
  910. volatile int64_t maxMemUsed;
  911. volatile int blockCount;
  912. };
  913. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  914. static void *
  915. mg_malloc_ex(size_t size,
  916. struct mg_context *ctx,
  917. const char *file,
  918. unsigned line)
  919. {
  920. void *data = malloc(size + 2 * sizeof(uintptr_t));
  921. void *memory = 0;
  922. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  923. #if defined(MEMORY_DEBUGGING)
  924. char mallocStr[256];
  925. #else
  926. (void)file;
  927. (void)line;
  928. #endif
  929. if (data) {
  930. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  931. if (mmem > mstat->maxMemUsed) {
  932. /* could use atomic compare exchange, but this
  933. * seems overkill for statistics data */
  934. mstat->maxMemUsed = mmem;
  935. }
  936. mg_atomic_inc(&mstat->blockCount);
  937. ((uintptr_t *)data)[0] = size;
  938. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  939. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  940. }
  941. #if defined(MEMORY_DEBUGGING)
  942. sprintf(mallocStr,
  943. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  944. memory,
  945. (unsigned long)size,
  946. (unsigned long)mstat->totalMemUsed,
  947. (unsigned long)mstat->blockCount,
  948. file,
  949. line);
  950. #if defined(_WIN32)
  951. OutputDebugStringA(mallocStr);
  952. #else
  953. DEBUG_TRACE("%s", mallocStr);
  954. #endif
  955. #endif
  956. return memory;
  957. }
  958. static void *
  959. mg_calloc_ex(size_t count,
  960. size_t size,
  961. struct mg_context *ctx,
  962. const char *file,
  963. unsigned line)
  964. {
  965. void *data = mg_malloc_ex(size * count, ctx, file, line);
  966. if (data) {
  967. memset(data, 0, size * count);
  968. }
  969. return data;
  970. }
  971. static void
  972. mg_free_ex(void *memory, const char *file, unsigned line)
  973. {
  974. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  975. #if defined(MEMORY_DEBUGGING)
  976. char mallocStr[256];
  977. #else
  978. (void)file;
  979. (void)line;
  980. #endif
  981. if (memory) {
  982. uintptr_t size = ((uintptr_t *)data)[0];
  983. struct mg_memory_stat *mstat =
  984. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  985. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  986. mg_atomic_dec(&mstat->blockCount);
  987. #if defined(MEMORY_DEBUGGING)
  988. sprintf(mallocStr,
  989. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  990. memory,
  991. (unsigned long)size,
  992. (unsigned long)mstat->totalMemUsed,
  993. (unsigned long)mstat->blockCount,
  994. file,
  995. line);
  996. #if defined(_WIN32)
  997. OutputDebugStringA(mallocStr);
  998. #else
  999. DEBUG_TRACE("%s", mallocStr);
  1000. #endif
  1001. #endif
  1002. free(data);
  1003. }
  1004. }
  1005. static void *
  1006. mg_realloc_ex(void *memory,
  1007. size_t newsize,
  1008. struct mg_context *ctx,
  1009. const char *file,
  1010. unsigned line)
  1011. {
  1012. void *data;
  1013. void *_realloc;
  1014. uintptr_t oldsize;
  1015. #if defined(MEMORY_DEBUGGING)
  1016. char mallocStr[256];
  1017. #else
  1018. (void)file;
  1019. (void)line;
  1020. #endif
  1021. if (newsize) {
  1022. if (memory) {
  1023. /* Reallocate existing block */
  1024. struct mg_memory_stat *mstat;
  1025. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1026. oldsize = ((uintptr_t *)data)[0];
  1027. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1028. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1029. if (_realloc) {
  1030. data = _realloc;
  1031. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1032. #if defined(MEMORY_DEBUGGING)
  1033. sprintf(mallocStr,
  1034. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1035. memory,
  1036. (unsigned long)oldsize,
  1037. (unsigned long)mstat->totalMemUsed,
  1038. (unsigned long)mstat->blockCount,
  1039. file,
  1040. line);
  1041. #if defined(_WIN32)
  1042. OutputDebugStringA(mallocStr);
  1043. #else
  1044. DEBUG_TRACE("%s", mallocStr);
  1045. #endif
  1046. #endif
  1047. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1048. #if defined(MEMORY_DEBUGGING)
  1049. sprintf(mallocStr,
  1050. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1051. memory,
  1052. (unsigned long)newsize,
  1053. (unsigned long)mstat->totalMemUsed,
  1054. (unsigned long)mstat->blockCount,
  1055. file,
  1056. line);
  1057. #if defined(_WIN32)
  1058. OutputDebugStringA(mallocStr);
  1059. #else
  1060. DEBUG_TRACE("%s", mallocStr);
  1061. #endif
  1062. #endif
  1063. *(uintptr_t *)data = newsize;
  1064. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1065. } else {
  1066. #if defined(MEMORY_DEBUGGING)
  1067. #if defined(_WIN32)
  1068. OutputDebugStringA("MEM: realloc failed\n");
  1069. #else
  1070. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1071. #endif
  1072. #endif
  1073. return _realloc;
  1074. }
  1075. } else {
  1076. /* Allocate new block */
  1077. data = mg_malloc_ex(newsize, ctx, file, line);
  1078. }
  1079. } else {
  1080. /* Free existing block */
  1081. data = 0;
  1082. mg_free_ex(memory, file, line);
  1083. }
  1084. return data;
  1085. }
  1086. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1087. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1088. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1089. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1090. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1091. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1092. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1093. #else /* USE_SERVER_STATS */
  1094. static __inline void *
  1095. mg_malloc(size_t a)
  1096. {
  1097. return malloc(a);
  1098. }
  1099. static __inline void *
  1100. mg_calloc(size_t a, size_t b)
  1101. {
  1102. return calloc(a, b);
  1103. }
  1104. static __inline void *
  1105. mg_realloc(void *a, size_t b)
  1106. {
  1107. return realloc(a, b);
  1108. }
  1109. static __inline void
  1110. mg_free(void *a)
  1111. {
  1112. free(a);
  1113. }
  1114. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1115. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1116. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1117. #define mg_free_ctx(a, c) mg_free(a)
  1118. #endif /* USE_SERVER_STATS */
  1119. static void mg_vsnprintf(const struct mg_connection *conn,
  1120. int *truncated,
  1121. char *buf,
  1122. size_t buflen,
  1123. const char *fmt,
  1124. va_list ap);
  1125. static void mg_snprintf(const struct mg_connection *conn,
  1126. int *truncated,
  1127. char *buf,
  1128. size_t buflen,
  1129. PRINTF_FORMAT_STRING(const char *fmt),
  1130. ...) PRINTF_ARGS(5, 6);
  1131. /* This following lines are just meant as a reminder to use the mg-functions
  1132. * for memory management */
  1133. #ifdef malloc
  1134. #undef malloc
  1135. #endif
  1136. #ifdef calloc
  1137. #undef calloc
  1138. #endif
  1139. #ifdef realloc
  1140. #undef realloc
  1141. #endif
  1142. #ifdef free
  1143. #undef free
  1144. #endif
  1145. #ifdef snprintf
  1146. #undef snprintf
  1147. #endif
  1148. #ifdef vsnprintf
  1149. #undef vsnprintf
  1150. #endif
  1151. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1152. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1153. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1154. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1155. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1156. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  1157. * but this define only works well for Windows. */
  1158. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1159. #endif
  1160. /* mg_init_library counter */
  1161. static int mg_init_library_called = 0;
  1162. #if !defined(NO_SSL)
  1163. static int mg_ssl_initialized = 0;
  1164. #endif
  1165. static pthread_key_t sTlsKey; /* Thread local storage index */
  1166. static int thread_idx_max = 0;
  1167. struct mg_workerTLS {
  1168. int is_master;
  1169. unsigned long thread_idx;
  1170. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1171. HANDLE pthread_cond_helper_mutex;
  1172. struct mg_workerTLS *next_waiting_thread;
  1173. #endif
  1174. };
  1175. #if defined(__GNUC__) || defined(__MINGW32__)
  1176. /* Show no warning in case system functions are not used. */
  1177. #if GCC_VERSION >= 40500
  1178. #pragma GCC diagnostic push
  1179. #pragma GCC diagnostic ignored "-Wunused-function"
  1180. #endif /* GCC_VERSION >= 40500 */
  1181. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1182. #if defined(__clang__)
  1183. /* Show no warning in case system functions are not used. */
  1184. #pragma clang diagnostic push
  1185. #pragma clang diagnostic ignored "-Wunused-function"
  1186. #endif
  1187. /* Get a unique thread ID as unsigned long, independent from the data type
  1188. * of thread IDs defined by the operating system API.
  1189. * If two calls to mg_current_thread_id return the same value, they calls
  1190. * are done from the same thread. If they return different values, they are
  1191. * done from different threads. (Provided this function is used in the same
  1192. * process context and threads are not repeatedly created and deleted, but
  1193. * CivetWeb does not do that).
  1194. * This function must match the signature required for SSL id callbacks:
  1195. * CRYPTO_set_id_callback
  1196. */
  1197. FUNCTION_MAY_BE_UNUSED
  1198. static unsigned long
  1199. mg_current_thread_id(void)
  1200. {
  1201. #ifdef _WIN32
  1202. return GetCurrentThreadId();
  1203. #else
  1204. #ifdef __clang__
  1205. #pragma clang diagnostic push
  1206. #pragma clang diagnostic ignored "-Wunreachable-code"
  1207. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1208. * or not, so one of the two conditions will be unreachable by construction.
  1209. * Unfortunately the C standard does not define a way to check this at
  1210. * compile time, since the #if preprocessor conditions can not use the sizeof
  1211. * operator as an argument. */
  1212. #endif
  1213. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1214. /* This is the problematic case for CRYPTO_set_id_callback:
  1215. * The OS pthread_t can not be cast to unsigned long. */
  1216. struct mg_workerTLS *tls =
  1217. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1218. if (tls == NULL) {
  1219. /* SSL called from an unknown thread: Create some thread index.
  1220. */
  1221. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1222. tls->is_master = -2; /* -2 means "3rd party thread" */
  1223. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1224. pthread_setspecific(sTlsKey, tls);
  1225. }
  1226. return tls->thread_idx;
  1227. } else {
  1228. /* pthread_t may be any data type, so a simple cast to unsigned long
  1229. * can rise a warning/error, depending on the platform.
  1230. * Here memcpy is used as an anything-to-anything cast. */
  1231. unsigned long ret = 0;
  1232. pthread_t t = pthread_self();
  1233. memcpy(&ret, &t, sizeof(pthread_t));
  1234. return ret;
  1235. }
  1236. #ifdef __clang__
  1237. #pragma clang diagnostic pop
  1238. #endif
  1239. #endif
  1240. }
  1241. FUNCTION_MAY_BE_UNUSED
  1242. static uint64_t
  1243. mg_get_current_time_ns(void)
  1244. {
  1245. struct timespec tsnow;
  1246. clock_gettime(CLOCK_REALTIME, &tsnow);
  1247. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1248. }
  1249. #if defined(__GNUC__)
  1250. /* Show no warning in case system functions are not used. */
  1251. #if GCC_VERSION >= 40500
  1252. #pragma GCC diagnostic pop
  1253. #endif /* GCC_VERSION >= 40500 */
  1254. #endif /* defined(__GNUC__) */
  1255. #if defined(__clang__)
  1256. /* Show no warning in case system functions are not used. */
  1257. #pragma clang diagnostic pop
  1258. #endif
  1259. #if defined(NEED_DEBUG_TRACE_FUNC)
  1260. static void
  1261. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1262. {
  1263. va_list args;
  1264. uint64_t nsnow;
  1265. static uint64_t nslast;
  1266. struct timespec tsnow;
  1267. /* Get some operating system independent thread id */
  1268. unsigned long thread_id = mg_current_thread_id();
  1269. clock_gettime(CLOCK_REALTIME, &tsnow);
  1270. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1271. + ((uint64_t)tsnow.tv_nsec);
  1272. if (!nslast) {
  1273. nslast = nsnow;
  1274. }
  1275. flockfile(stdout);
  1276. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1277. (unsigned long)tsnow.tv_sec,
  1278. (unsigned long)tsnow.tv_nsec,
  1279. nsnow - nslast,
  1280. thread_id,
  1281. func,
  1282. line);
  1283. va_start(args, fmt);
  1284. vprintf(fmt, args);
  1285. va_end(args);
  1286. putchar('\n');
  1287. fflush(stdout);
  1288. funlockfile(stdout);
  1289. nslast = nsnow;
  1290. }
  1291. #endif /* NEED_DEBUG_TRACE_FUNC */
  1292. #define MD5_STATIC static
  1293. #include "md5.inl"
  1294. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1295. #ifdef NO_SOCKLEN_T
  1296. typedef int socklen_t;
  1297. #endif /* NO_SOCKLEN_T */
  1298. #define _DARWIN_UNLIMITED_SELECT
  1299. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1300. #if !defined(MSG_NOSIGNAL)
  1301. #define MSG_NOSIGNAL (0)
  1302. #endif
  1303. #if !defined(SOMAXCONN)
  1304. #define SOMAXCONN (100)
  1305. #endif
  1306. /* Size of the accepted socket queue */
  1307. #if !defined(MGSQLEN)
  1308. #define MGSQLEN (20)
  1309. #endif
  1310. #if defined(NO_SSL)
  1311. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1312. typedef struct SSL_CTX SSL_CTX;
  1313. #else
  1314. #if defined(NO_SSL_DL)
  1315. #include <openssl/ssl.h>
  1316. #include <openssl/err.h>
  1317. #include <openssl/crypto.h>
  1318. #include <openssl/x509.h>
  1319. #include <openssl/pem.h>
  1320. #include <openssl/engine.h>
  1321. #include <openssl/conf.h>
  1322. #include <openssl/dh.h>
  1323. #include <openssl/bn.h>
  1324. #include <openssl/opensslv.h>
  1325. #else
  1326. /* SSL loaded dynamically from DLL.
  1327. * I put the prototypes here to be independent from OpenSSL source
  1328. * installation. */
  1329. typedef struct ssl_st SSL;
  1330. typedef struct ssl_method_st SSL_METHOD;
  1331. typedef struct ssl_ctx_st SSL_CTX;
  1332. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1333. typedef struct x509_name X509_NAME;
  1334. typedef struct asn1_integer ASN1_INTEGER;
  1335. typedef struct bignum BIGNUM;
  1336. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1337. typedef struct evp_md EVP_MD;
  1338. typedef struct x509 X509;
  1339. #define SSL_CTRL_OPTIONS (32)
  1340. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1341. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1342. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1343. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1344. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1345. #define SSL_VERIFY_NONE (0)
  1346. #define SSL_VERIFY_PEER (1)
  1347. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1348. #define SSL_VERIFY_CLIENT_ONCE (4)
  1349. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1350. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1351. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1352. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1353. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1354. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1355. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1356. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1357. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1358. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1359. #define SSL_CB_HANDSHAKE_START (0x10)
  1360. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1361. #define SSL_ERROR_NONE (0)
  1362. #define SSL_ERROR_SSL (1)
  1363. #define SSL_ERROR_WANT_READ (2)
  1364. #define SSL_ERROR_WANT_WRITE (3)
  1365. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1366. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1367. #define SSL_ERROR_ZERO_RETURN (6)
  1368. #define SSL_ERROR_WANT_CONNECT (7)
  1369. #define SSL_ERROR_WANT_ACCEPT (8)
  1370. #define TLSEXT_TYPE_server_name (0)
  1371. #define TLSEXT_NAMETYPE_host_name (0)
  1372. #define SSL_TLSEXT_ERR_OK (0)
  1373. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1374. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1375. #define SSL_TLSEXT_ERR_NOACK (3)
  1376. struct ssl_func {
  1377. const char *name; /* SSL function name */
  1378. void (*ptr)(void); /* Function pointer */
  1379. };
  1380. #ifdef OPENSSL_API_1_1
  1381. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1382. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1383. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1384. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1385. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1386. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1387. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1388. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1389. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1390. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1391. #define OPENSSL_init_ssl \
  1392. (*(int (*)(uint64_t opts, \
  1393. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1394. #define SSL_CTX_use_PrivateKey_file \
  1395. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1396. #define SSL_CTX_use_certificate_file \
  1397. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1398. #define SSL_CTX_set_default_passwd_cb \
  1399. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1400. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1401. #define SSL_CTX_use_certificate_chain_file \
  1402. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1403. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1404. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1405. #define SSL_CTX_set_verify \
  1406. (*(void (*)(SSL_CTX *, \
  1407. int, \
  1408. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1409. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1410. #define SSL_CTX_load_verify_locations \
  1411. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1412. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1413. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1414. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1415. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1416. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1417. #define SSL_CIPHER_get_name \
  1418. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1419. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1420. #define SSL_CTX_set_session_id_context \
  1421. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1422. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1423. #define SSL_CTX_set_cipher_list \
  1424. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1425. #define SSL_CTX_set_options \
  1426. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1427. #define SSL_CTX_set_info_callback \
  1428. (*(void (*)(SSL_CTX * ctx, \
  1429. void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1430. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1431. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1432. #define SSL_CTX_callback_ctrl \
  1433. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1434. #define SSL_get_servername \
  1435. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1436. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1437. #define SSL_CTX_clear_options(ctx, op) \
  1438. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1439. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1440. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1441. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1442. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1443. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1444. SSL_CTX_callback_ctrl(ctx, \
  1445. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1446. (void (*)(void))cb)
  1447. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1448. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1449. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1450. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1451. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1452. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1453. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1454. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1455. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1456. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1457. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1458. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1459. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1460. #define X509_NAME_oneline \
  1461. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1462. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1463. #define EVP_get_digestbyname \
  1464. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1465. #define EVP_Digest \
  1466. (*(int (*)( \
  1467. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1468. crypto_sw[10].ptr)
  1469. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1470. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1471. #define ASN1_INTEGER_to_BN \
  1472. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1473. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1474. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1475. #define OPENSSL_free(a) CRYPTO_free(a)
  1476. /* init_ssl_ctx() function updates this array.
  1477. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1478. * of respective functions. The macros above (like SSL_connect()) are really
  1479. * just calling these functions indirectly via the pointer. */
  1480. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1481. {"SSL_accept", NULL},
  1482. {"SSL_connect", NULL},
  1483. {"SSL_read", NULL},
  1484. {"SSL_write", NULL},
  1485. {"SSL_get_error", NULL},
  1486. {"SSL_set_fd", NULL},
  1487. {"SSL_new", NULL},
  1488. {"SSL_CTX_new", NULL},
  1489. {"TLS_server_method", NULL},
  1490. {"OPENSSL_init_ssl", NULL},
  1491. {"SSL_CTX_use_PrivateKey_file", NULL},
  1492. {"SSL_CTX_use_certificate_file", NULL},
  1493. {"SSL_CTX_set_default_passwd_cb", NULL},
  1494. {"SSL_CTX_free", NULL},
  1495. {"SSL_CTX_use_certificate_chain_file", NULL},
  1496. {"TLS_client_method", NULL},
  1497. {"SSL_pending", NULL},
  1498. {"SSL_CTX_set_verify", NULL},
  1499. {"SSL_shutdown", NULL},
  1500. {"SSL_CTX_load_verify_locations", NULL},
  1501. {"SSL_CTX_set_default_verify_paths", NULL},
  1502. {"SSL_CTX_set_verify_depth", NULL},
  1503. {"SSL_get_peer_certificate", NULL},
  1504. {"SSL_get_version", NULL},
  1505. {"SSL_get_current_cipher", NULL},
  1506. {"SSL_CIPHER_get_name", NULL},
  1507. {"SSL_CTX_check_private_key", NULL},
  1508. {"SSL_CTX_set_session_id_context", NULL},
  1509. {"SSL_CTX_ctrl", NULL},
  1510. {"SSL_CTX_set_cipher_list", NULL},
  1511. {"SSL_CTX_set_options", NULL},
  1512. {"SSL_CTX_set_info_callback", NULL},
  1513. {"SSL_get_ex_data", NULL},
  1514. {"SSL_set_ex_data", NULL},
  1515. {"SSL_CTX_callback_ctrl", NULL},
  1516. {"SSL_get_servername", NULL},
  1517. {"SSL_set_SSL_CTX", NULL},
  1518. {NULL, NULL}};
  1519. /* Similar array as ssl_sw. These functions could be located in different
  1520. * lib. */
  1521. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1522. {"ERR_error_string", NULL},
  1523. {"ERR_remove_state", NULL},
  1524. {"CONF_modules_unload", NULL},
  1525. {"X509_free", NULL},
  1526. {"X509_get_subject_name", NULL},
  1527. {"X509_get_issuer_name", NULL},
  1528. {"X509_NAME_oneline", NULL},
  1529. {"X509_get_serialNumber", NULL},
  1530. {"EVP_get_digestbyname", NULL},
  1531. {"EVP_Digest", NULL},
  1532. {"i2d_X509", NULL},
  1533. {"BN_bn2hex", NULL},
  1534. {"ASN1_INTEGER_to_BN", NULL},
  1535. {"BN_free", NULL},
  1536. {"CRYPTO_free", NULL},
  1537. {NULL, NULL}};
  1538. #else
  1539. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1540. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1541. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1542. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1543. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1544. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1545. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1546. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1547. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1548. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1549. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1550. #define SSL_CTX_use_PrivateKey_file \
  1551. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1552. #define SSL_CTX_use_certificate_file \
  1553. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1554. #define SSL_CTX_set_default_passwd_cb \
  1555. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1556. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1557. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1558. #define SSL_CTX_use_certificate_chain_file \
  1559. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1560. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1561. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1562. #define SSL_CTX_set_verify \
  1563. (*(void (*)(SSL_CTX *, \
  1564. int, \
  1565. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1566. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1567. #define SSL_CTX_load_verify_locations \
  1568. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1569. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1570. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1571. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1572. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1573. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1574. #define SSL_CIPHER_get_name \
  1575. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1576. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1577. #define SSL_CTX_set_session_id_context \
  1578. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1579. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1580. #define SSL_CTX_set_cipher_list \
  1581. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1582. #define SSL_CTX_set_info_callback \
  1583. (*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1584. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1585. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1586. #define SSL_CTX_callback_ctrl \
  1587. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1588. #define SSL_get_servername \
  1589. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1590. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1591. #define SSL_CTX_set_options(ctx, op) \
  1592. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1593. #define SSL_CTX_clear_options(ctx, op) \
  1594. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1595. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1596. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1597. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1598. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1599. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1600. SSL_CTX_callback_ctrl(ctx, \
  1601. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1602. (void (*)(void))cb)
  1603. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1604. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1605. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1606. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1607. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1608. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1609. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1610. #define CRYPTO_set_locking_callback \
  1611. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1612. #define CRYPTO_set_id_callback \
  1613. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1614. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1615. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1616. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1617. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1618. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1619. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1620. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1621. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1622. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1623. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1624. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1625. #define X509_NAME_oneline \
  1626. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1627. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1628. #define i2c_ASN1_INTEGER \
  1629. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1630. #define EVP_get_digestbyname \
  1631. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1632. #define EVP_Digest \
  1633. (*(int (*)( \
  1634. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1635. crypto_sw[18].ptr)
  1636. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1637. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1638. #define ASN1_INTEGER_to_BN \
  1639. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1640. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1641. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1642. #define OPENSSL_free(a) CRYPTO_free(a)
  1643. /* init_ssl_ctx() function updates this array.
  1644. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1645. * of respective functions. The macros above (like SSL_connect()) are really
  1646. * just calling these functions indirectly via the pointer. */
  1647. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1648. {"SSL_accept", NULL},
  1649. {"SSL_connect", NULL},
  1650. {"SSL_read", NULL},
  1651. {"SSL_write", NULL},
  1652. {"SSL_get_error", NULL},
  1653. {"SSL_set_fd", NULL},
  1654. {"SSL_new", NULL},
  1655. {"SSL_CTX_new", NULL},
  1656. {"SSLv23_server_method", NULL},
  1657. {"SSL_library_init", NULL},
  1658. {"SSL_CTX_use_PrivateKey_file", NULL},
  1659. {"SSL_CTX_use_certificate_file", NULL},
  1660. {"SSL_CTX_set_default_passwd_cb", NULL},
  1661. {"SSL_CTX_free", NULL},
  1662. {"SSL_load_error_strings", NULL},
  1663. {"SSL_CTX_use_certificate_chain_file", NULL},
  1664. {"SSLv23_client_method", NULL},
  1665. {"SSL_pending", NULL},
  1666. {"SSL_CTX_set_verify", NULL},
  1667. {"SSL_shutdown", NULL},
  1668. {"SSL_CTX_load_verify_locations", NULL},
  1669. {"SSL_CTX_set_default_verify_paths", NULL},
  1670. {"SSL_CTX_set_verify_depth", NULL},
  1671. {"SSL_get_peer_certificate", NULL},
  1672. {"SSL_get_version", NULL},
  1673. {"SSL_get_current_cipher", NULL},
  1674. {"SSL_CIPHER_get_name", NULL},
  1675. {"SSL_CTX_check_private_key", NULL},
  1676. {"SSL_CTX_set_session_id_context", NULL},
  1677. {"SSL_CTX_ctrl", NULL},
  1678. {"SSL_CTX_set_cipher_list", NULL},
  1679. {"SSL_CTX_set_info_callback", NULL},
  1680. {"SSL_get_ex_data", NULL},
  1681. {"SSL_set_ex_data", NULL},
  1682. {"SSL_CTX_callback_ctrl", NULL},
  1683. {"SSL_get_servername", NULL},
  1684. {"SSL_set_SSL_CTX", NULL},
  1685. {NULL, NULL}};
  1686. /* Similar array as ssl_sw. These functions could be located in different
  1687. * lib. */
  1688. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1689. {"CRYPTO_set_locking_callback", NULL},
  1690. {"CRYPTO_set_id_callback", NULL},
  1691. {"ERR_get_error", NULL},
  1692. {"ERR_error_string", NULL},
  1693. {"ERR_remove_state", NULL},
  1694. {"ERR_free_strings", NULL},
  1695. {"ENGINE_cleanup", NULL},
  1696. {"CONF_modules_unload", NULL},
  1697. {"CRYPTO_cleanup_all_ex_data", NULL},
  1698. {"EVP_cleanup", NULL},
  1699. {"X509_free", NULL},
  1700. {"X509_get_subject_name", NULL},
  1701. {"X509_get_issuer_name", NULL},
  1702. {"X509_NAME_oneline", NULL},
  1703. {"X509_get_serialNumber", NULL},
  1704. {"i2c_ASN1_INTEGER", NULL},
  1705. {"EVP_get_digestbyname", NULL},
  1706. {"EVP_Digest", NULL},
  1707. {"i2d_X509", NULL},
  1708. {"BN_bn2hex", NULL},
  1709. {"ASN1_INTEGER_to_BN", NULL},
  1710. {"BN_free", NULL},
  1711. {"CRYPTO_free", NULL},
  1712. {NULL, NULL}};
  1713. #endif /* OPENSSL_API_1_1 */
  1714. #endif /* NO_SSL_DL */
  1715. #endif /* NO_SSL */
  1716. #if !defined(NO_CACHING)
  1717. static const char *month_names[] = {"Jan",
  1718. "Feb",
  1719. "Mar",
  1720. "Apr",
  1721. "May",
  1722. "Jun",
  1723. "Jul",
  1724. "Aug",
  1725. "Sep",
  1726. "Oct",
  1727. "Nov",
  1728. "Dec"};
  1729. #endif /* !NO_CACHING */
  1730. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1731. * the
  1732. * union u. */
  1733. union usa {
  1734. struct sockaddr sa;
  1735. struct sockaddr_in sin;
  1736. #if defined(USE_IPV6)
  1737. struct sockaddr_in6 sin6;
  1738. #endif
  1739. };
  1740. /* Describes a string (chunk of memory). */
  1741. struct vec {
  1742. const char *ptr;
  1743. size_t len;
  1744. };
  1745. struct mg_file_stat {
  1746. /* File properties filled by mg_stat: */
  1747. uint64_t size;
  1748. time_t last_modified;
  1749. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1750. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1751. * case we need a "Content-Eencoding: gzip" header */
  1752. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1753. };
  1754. struct mg_file_in_memory {
  1755. char *p;
  1756. uint32_t pos;
  1757. char mode;
  1758. };
  1759. struct mg_file_access {
  1760. /* File properties filled by mg_fopen: */
  1761. FILE *fp;
  1762. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1763. * support library. Use some struct mg_file_in_memory *mf; instead of
  1764. * membuf char pointer. */
  1765. const char *membuf;
  1766. };
  1767. struct mg_file {
  1768. struct mg_file_stat stat;
  1769. struct mg_file_access access;
  1770. };
  1771. #define STRUCT_FILE_INITIALIZER \
  1772. { \
  1773. { \
  1774. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1775. } \
  1776. , \
  1777. { \
  1778. (FILE *) NULL, (const char *)NULL \
  1779. } \
  1780. }
  1781. /* Describes listening socket, or socket which was accept()-ed by the master
  1782. * thread and queued for future handling by the worker thread. */
  1783. struct socket {
  1784. SOCKET sock; /* Listening socket */
  1785. union usa lsa; /* Local socket address */
  1786. union usa rsa; /* Remote socket address */
  1787. unsigned char is_ssl; /* Is port SSL-ed */
  1788. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1789. * port */
  1790. unsigned char in_use; /* Is valid */
  1791. };
  1792. /* Enum const for all options must be in sync with
  1793. * static struct mg_option config_options[]
  1794. * This is tested in the unit test (test/private.c)
  1795. * "Private Config Options"
  1796. */
  1797. enum {
  1798. LISTENING_PORTS,
  1799. NUM_THREADS,
  1800. RUN_AS_USER,
  1801. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1802. * socket option typedef TCP_NODELAY. */
  1803. MAX_REQUEST_SIZE,
  1804. LINGER_TIMEOUT,
  1805. #if defined(__linux__)
  1806. ALLOW_SENDFILE_CALL,
  1807. #endif
  1808. #if defined(_WIN32)
  1809. CASE_SENSITIVE_FILES,
  1810. #endif
  1811. THROTTLE,
  1812. ACCESS_LOG_FILE,
  1813. ERROR_LOG_FILE,
  1814. ENABLE_KEEP_ALIVE,
  1815. REQUEST_TIMEOUT,
  1816. KEEP_ALIVE_TIMEOUT,
  1817. #if defined(USE_WEBSOCKET)
  1818. WEBSOCKET_TIMEOUT,
  1819. ENABLE_WEBSOCKET_PING_PONG,
  1820. #endif
  1821. DECODE_URL,
  1822. #if defined(USE_LUA)
  1823. LUA_BACKGROUND_SCRIPT,
  1824. LUA_BACKGROUND_SCRIPT_PARAMS,
  1825. #endif
  1826. DOCUMENT_ROOT,
  1827. CGI_EXTENSIONS,
  1828. CGI_ENVIRONMENT,
  1829. PUT_DELETE_PASSWORDS_FILE,
  1830. CGI_INTERPRETER,
  1831. PROTECT_URI,
  1832. AUTHENTICATION_DOMAIN,
  1833. ENABLE_AUTH_DOMAIN_CHECK,
  1834. SSI_EXTENSIONS,
  1835. ENABLE_DIRECTORY_LISTING,
  1836. GLOBAL_PASSWORDS_FILE,
  1837. INDEX_FILES,
  1838. ACCESS_CONTROL_LIST,
  1839. EXTRA_MIME_TYPES,
  1840. SSL_CERTIFICATE,
  1841. SSL_CERTIFICATE_CHAIN,
  1842. URL_REWRITE_PATTERN,
  1843. HIDE_FILES,
  1844. SSL_DO_VERIFY_PEER,
  1845. SSL_CA_PATH,
  1846. SSL_CA_FILE,
  1847. SSL_VERIFY_DEPTH,
  1848. SSL_DEFAULT_VERIFY_PATHS,
  1849. SSL_CIPHER_LIST,
  1850. SSL_PROTOCOL_VERSION,
  1851. SSL_SHORT_TRUST,
  1852. #if defined(USE_LUA)
  1853. LUA_PRELOAD_FILE,
  1854. LUA_SCRIPT_EXTENSIONS,
  1855. LUA_SERVER_PAGE_EXTENSIONS,
  1856. #endif
  1857. #if defined(USE_DUKTAPE)
  1858. DUKTAPE_SCRIPT_EXTENSIONS,
  1859. #endif
  1860. #if defined(USE_WEBSOCKET)
  1861. WEBSOCKET_ROOT,
  1862. #endif
  1863. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1864. LUA_WEBSOCKET_EXTENSIONS,
  1865. #endif
  1866. ACCESS_CONTROL_ALLOW_ORIGIN,
  1867. ACCESS_CONTROL_ALLOW_METHODS,
  1868. ACCESS_CONTROL_ALLOW_HEADERS,
  1869. ERROR_PAGES,
  1870. #if !defined(NO_CACHING)
  1871. STATIC_FILE_MAX_AGE,
  1872. #endif
  1873. #if !defined(NO_SSL)
  1874. STRICT_HTTPS_MAX_AGE,
  1875. #endif
  1876. ADDITIONAL_HEADER,
  1877. ALLOW_INDEX_SCRIPT_SUB_RES,
  1878. NUM_OPTIONS
  1879. };
  1880. /* Config option name, config types, default value.
  1881. * Must be in the same order as the enum const above.
  1882. */
  1883. static struct mg_option config_options[] = {
  1884. /* Once for each server */
  1885. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1886. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1887. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1888. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1889. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1890. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1891. #if defined(__linux__)
  1892. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1893. #endif
  1894. #if defined(_WIN32)
  1895. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1896. #endif
  1897. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1898. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1899. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1900. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1901. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1902. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1903. #if defined(USE_WEBSOCKET)
  1904. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1905. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1906. #endif
  1907. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1908. #if defined(USE_LUA)
  1909. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1910. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1911. #endif
  1912. /* Once for each domain */
  1913. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1914. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1915. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1916. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1917. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1918. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1919. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1920. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1921. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1922. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1923. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1924. {"index_files",
  1925. MG_CONFIG_TYPE_STRING_LIST,
  1926. #ifdef USE_LUA
  1927. "index.xhtml,index.html,index.htm,"
  1928. "index.lp,index.lsp,index.lua,index.cgi,"
  1929. "index.shtml,index.php"},
  1930. #else
  1931. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1932. #endif
  1933. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1934. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1935. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1936. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1937. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1938. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1939. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1940. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1941. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1942. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1943. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1944. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1945. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  1946. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1947. #if defined(USE_LUA)
  1948. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1949. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1950. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1951. #endif
  1952. #if defined(USE_DUKTAPE)
  1953. /* The support for duktape is still in alpha version state.
  1954. * The name of this config option might change. */
  1955. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1956. #endif
  1957. #if defined(USE_WEBSOCKET)
  1958. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1959. #endif
  1960. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1961. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1962. #endif
  1963. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1964. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1965. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1966. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1967. #if !defined(NO_CACHING)
  1968. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1969. #endif
  1970. #if !defined(NO_SSL)
  1971. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1972. #endif
  1973. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1974. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1975. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1976. /* Check if the config_options and the corresponding enum have compatible
  1977. * sizes. */
  1978. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1979. == (NUM_OPTIONS + 1),
  1980. "config_options and enum not sync");
  1981. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1982. struct mg_handler_info {
  1983. /* Name/Pattern of the URI. */
  1984. char *uri;
  1985. size_t uri_len;
  1986. /* handler type */
  1987. int handler_type;
  1988. /* Handler for http/https or authorization requests. */
  1989. mg_request_handler handler;
  1990. /* Handler for ws/wss (websocket) requests. */
  1991. mg_websocket_connect_handler connect_handler;
  1992. mg_websocket_ready_handler ready_handler;
  1993. mg_websocket_data_handler data_handler;
  1994. mg_websocket_close_handler close_handler;
  1995. /* accepted subprotocols for ws/wss requests. */
  1996. struct mg_websocket_subprotocols *subprotocols;
  1997. /* Handler for authorization requests */
  1998. mg_authorization_handler auth_handler;
  1999. /* User supplied argument for the handler function. */
  2000. void *cbdata;
  2001. /* next handler in a linked list */
  2002. struct mg_handler_info *next;
  2003. };
  2004. enum {
  2005. CONTEXT_INVALID,
  2006. CONTEXT_SERVER,
  2007. CONTEXT_HTTP_CLIENT,
  2008. CONTEXT_WS_CLIENT
  2009. };
  2010. struct mg_domain_context {
  2011. SSL_CTX *ssl_ctx; /* SSL context */
  2012. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2013. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2014. /* Server nonce */
  2015. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2016. unsigned long nonce_count; /* Used nonces, used for authentication */
  2017. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2018. /* linked list of shared lua websockets */
  2019. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2020. #endif
  2021. /* Linked list of domains */
  2022. struct mg_domain_context *next;
  2023. };
  2024. struct mg_context {
  2025. /* Part 1 - Physical context:
  2026. * This holds threads, ports, timeouts, ...
  2027. * set for the entire server, independent from the
  2028. * addressed hostname.
  2029. */
  2030. /* Connection related */
  2031. int context_type; /* See CONTEXT_* above */
  2032. struct socket *listening_sockets;
  2033. struct pollfd *listening_socket_fds;
  2034. unsigned int num_listening_sockets;
  2035. struct mg_connection *worker_connections; /* The connection struct, pre-
  2036. * allocated for each worker */
  2037. #if defined(USE_SERVER_STATS)
  2038. int active_connections;
  2039. int max_connections;
  2040. int64_t total_connections;
  2041. int64_t total_requests;
  2042. int64_t total_data_read;
  2043. int64_t total_data_written;
  2044. #endif
  2045. /* Thread related */
  2046. volatile int stop_flag; /* Should we stop event loop */
  2047. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2048. pthread_t masterthreadid; /* The master thread ID */
  2049. unsigned int
  2050. cfg_worker_threads; /* The number of configured worker threads. */
  2051. pthread_t *worker_threadids; /* The worker thread IDs */
  2052. /* Connection to thread dispatching */
  2053. #ifdef ALTERNATIVE_QUEUE
  2054. struct socket *client_socks;
  2055. void **client_wait_events;
  2056. #else
  2057. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2058. volatile int sq_head; /* Head of the socket queue */
  2059. volatile int sq_tail; /* Tail of the socket queue */
  2060. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2061. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2062. #endif
  2063. /* Memory related */
  2064. unsigned int max_request_size; /* The max request size */
  2065. #if defined(USE_SERVER_STATS)
  2066. struct mg_memory_stat ctx_memory;
  2067. #endif
  2068. /* Operating system related */
  2069. char *systemName; /* What operating system is running */
  2070. time_t start_time; /* Server start time, used for authentication
  2071. * and for diagnstics. */
  2072. #if defined(USE_TIMERS)
  2073. struct ttimers *timers;
  2074. #endif
  2075. /* Lua specific: Background operations and shared websockets */
  2076. #if defined(USE_LUA)
  2077. void *lua_background_state;
  2078. #endif
  2079. /* Server nonce */
  2080. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2081. /* Server callbacks */
  2082. struct mg_callbacks callbacks; /* User-defined callback function */
  2083. void *user_data; /* User-defined data */
  2084. /* Part 2 - Logical domain:
  2085. * This holds hostname, TLS certificate, document root, ...
  2086. * set for a domain hosted at the server.
  2087. * There may be multiple domains hosted at one physical server.
  2088. * The default domain "dd" is the first element of a list of
  2089. * domains.
  2090. */
  2091. struct mg_domain_context dd; /* default domain */
  2092. };
  2093. #if defined(USE_SERVER_STATS)
  2094. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2095. static struct mg_memory_stat *
  2096. get_memory_stat(struct mg_context *ctx)
  2097. {
  2098. if (ctx) {
  2099. return &(ctx->ctx_memory);
  2100. }
  2101. return &mg_common_memory;
  2102. }
  2103. #endif
  2104. enum {
  2105. CONNECTION_TYPE_INVALID,
  2106. CONNECTION_TYPE_REQUEST,
  2107. CONNECTION_TYPE_RESPONSE
  2108. };
  2109. struct mg_connection {
  2110. int connection_type; /* see CONNECTION_TYPE_* above */
  2111. struct mg_request_info request_info;
  2112. struct mg_response_info response_info;
  2113. struct mg_context *phys_ctx;
  2114. struct mg_domain_context *dom_ctx;
  2115. #if defined(USE_SERVER_STATS)
  2116. int conn_state; /* 0 = undef, numerical value may change in different
  2117. * versions. For the current definition, see
  2118. * mg_get_connection_info_impl */
  2119. #endif
  2120. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2121. SSL *ssl; /* SSL descriptor */
  2122. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2123. struct socket client; /* Connected client */
  2124. time_t conn_birth_time; /* Time (wall clock) when connection was
  2125. * established */
  2126. struct timespec req_time; /* Time (since system start) when the request
  2127. * was received */
  2128. int64_t num_bytes_sent; /* Total bytes sent to client */
  2129. int64_t content_len; /* Content-Length header value */
  2130. int64_t consumed_content; /* How many bytes of content have been read */
  2131. int is_chunked; /* Transfer-Encoding is chunked:
  2132. * 0 = not chunked,
  2133. * 1 = chunked, do data read yet,
  2134. * 2 = chunked, some data read,
  2135. * 3 = chunked, all data read
  2136. */
  2137. size_t chunk_remainder; /* Unread data from the last chunk */
  2138. char *buf; /* Buffer for received data */
  2139. char *path_info; /* PATH_INFO part of the URL */
  2140. int must_close; /* 1 if connection must be closed */
  2141. int accept_gzip; /* 1 if gzip encoding is accepted */
  2142. int in_error_handler; /* 1 if in handler for user defined error
  2143. * pages */
  2144. #if defined(USE_WEBSOCKET)
  2145. int in_websocket_handling; /* 1 if in read_websocket */
  2146. #endif
  2147. int handled_requests; /* Number of requests handled by this connection
  2148. */
  2149. int buf_size; /* Buffer size */
  2150. int request_len; /* Size of the request + headers in a buffer */
  2151. int data_len; /* Total size of data in a buffer */
  2152. int status_code; /* HTTP reply status code, e.g. 200 */
  2153. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2154. * throttle */
  2155. time_t last_throttle_time; /* Last time throttled data was sent */
  2156. int64_t last_throttle_bytes; /* Bytes sent this second */
  2157. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2158. * atomic transmissions for websockets */
  2159. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2160. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2161. #endif
  2162. int thread_index; /* Thread index within ctx */
  2163. };
  2164. /* Directory entry */
  2165. struct de {
  2166. struct mg_connection *conn;
  2167. char *file_name;
  2168. struct mg_file_stat file;
  2169. };
  2170. #if defined(USE_WEBSOCKET)
  2171. static int is_websocket_protocol(const struct mg_connection *conn);
  2172. #else
  2173. #define is_websocket_protocol(conn) (0)
  2174. #endif
  2175. #define mg_cry_internal(conn, fmt, ...) \
  2176. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2177. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2178. const char *func,
  2179. unsigned line,
  2180. const char *fmt,
  2181. ...) PRINTF_ARGS(4, 5);
  2182. #if !defined(NO_THREAD_NAME)
  2183. #if defined(_WIN32) && defined(_MSC_VER)
  2184. /* Set the thread name for debugging purposes in Visual Studio
  2185. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2186. */
  2187. #pragma pack(push, 8)
  2188. typedef struct tagTHREADNAME_INFO {
  2189. DWORD dwType; /* Must be 0x1000. */
  2190. LPCSTR szName; /* Pointer to name (in user addr space). */
  2191. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2192. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2193. } THREADNAME_INFO;
  2194. #pragma pack(pop)
  2195. #elif defined(__linux__)
  2196. #include <sys/prctl.h>
  2197. #include <sys/sendfile.h>
  2198. #ifdef ALTERNATIVE_QUEUE
  2199. #include <sys/eventfd.h>
  2200. #endif /* ALTERNATIVE_QUEUE */
  2201. #if defined(ALTERNATIVE_QUEUE)
  2202. #ifdef __clang__
  2203. #pragma clang diagnostic push
  2204. #pragma clang diagnostic ignored "-Wunreachable-code"
  2205. /* For every system, "(sizeof(int) == sizeof(void *))" is either always
  2206. * true or always false. One of the two branches is unreachable in any case.
  2207. * Unfortunately the C standard does not define a way to check this at
  2208. * compile time, since the #if preprocessor conditions can not use the sizeof
  2209. * operator as an argument. */
  2210. #endif
  2211. #if defined(__GNUC__) || defined(__MINGW32__)
  2212. /* GCC does not realize one branch is unreachable, so it raises some
  2213. * pointer cast warning within the unreachable branch.
  2214. */
  2215. #pragma GCC diagnostic push
  2216. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
  2217. #pragma GCC diagnostic ignored "-Wpointer-to-int-cast"
  2218. #endif
  2219. static void *
  2220. event_create(void)
  2221. {
  2222. int evhdl = eventfd(0, EFD_CLOEXEC);
  2223. int *ret;
  2224. if (evhdl == -1) {
  2225. /* Linux uses -1 on error, Windows NULL. */
  2226. /* However, Linux does not return 0 on success either. */
  2227. return 0;
  2228. }
  2229. if (sizeof(int) == sizeof(void *)) {
  2230. ret = (void *)evhdl;
  2231. } else {
  2232. ret = (int *)mg_malloc(sizeof(int));
  2233. if (ret) {
  2234. *ret = evhdl;
  2235. } else {
  2236. (void)close(evhdl);
  2237. }
  2238. }
  2239. return (void *)ret;
  2240. }
  2241. static int
  2242. event_wait(void *eventhdl)
  2243. {
  2244. uint64_t u;
  2245. int evhdl, s;
  2246. if (sizeof(int) == sizeof(void *)) {
  2247. evhdl = (int)eventhdl;
  2248. } else {
  2249. if (!eventhdl) {
  2250. /* error */
  2251. return 0;
  2252. }
  2253. evhdl = *(int *)eventhdl;
  2254. }
  2255. s = (int)read(evhdl, &u, sizeof(u));
  2256. if (s != sizeof(uint64_t)) {
  2257. /* error */
  2258. return 0;
  2259. }
  2260. (void)u; /* the value is not required */
  2261. return 1;
  2262. }
  2263. static int
  2264. event_signal(void *eventhdl)
  2265. {
  2266. uint64_t u = 1;
  2267. int evhdl, s;
  2268. if (sizeof(int) == sizeof(void *)) {
  2269. evhdl = (int)eventhdl;
  2270. } else {
  2271. if (!eventhdl) {
  2272. /* error */
  2273. return 0;
  2274. }
  2275. evhdl = *(int *)eventhdl;
  2276. }
  2277. s = (int)write(evhdl, &u, sizeof(u));
  2278. if (s != sizeof(uint64_t)) {
  2279. /* error */
  2280. return 0;
  2281. }
  2282. return 1;
  2283. }
  2284. static void
  2285. event_destroy(void *eventhdl)
  2286. {
  2287. int evhdl;
  2288. if (sizeof(int) == sizeof(void *)) {
  2289. evhdl = (int)eventhdl;
  2290. close(evhdl);
  2291. } else {
  2292. if (!eventhdl) {
  2293. /* error */
  2294. return;
  2295. }
  2296. evhdl = *(int *)eventhdl;
  2297. close(evhdl);
  2298. mg_free(eventhdl);
  2299. }
  2300. }
  2301. #if defined(__GNUC__) || defined(__MINGW32__)
  2302. #pragma GCC diagnostic pop
  2303. #endif
  2304. #ifdef __clang__
  2305. #pragma clang diagnostic pop
  2306. #endif
  2307. #endif
  2308. #endif
  2309. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2310. struct posix_event {
  2311. pthread_mutex_t mutex;
  2312. pthread_cond_t cond;
  2313. };
  2314. static void *
  2315. event_create(void)
  2316. {
  2317. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2318. if (ret == 0) {
  2319. /* out of memory */
  2320. return 0;
  2321. }
  2322. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2323. /* pthread mutex not available */
  2324. mg_free(ret);
  2325. return 0;
  2326. }
  2327. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2328. /* pthread cond not available */
  2329. pthread_mutex_destroy(&(ret->mutex));
  2330. mg_free(ret);
  2331. return 0;
  2332. }
  2333. return (void *)ret;
  2334. }
  2335. static int
  2336. event_wait(void *eventhdl)
  2337. {
  2338. struct posix_event *ev = (struct posix_event *)eventhdl;
  2339. pthread_mutex_lock(&(ev->mutex));
  2340. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2341. pthread_mutex_unlock(&(ev->mutex));
  2342. return 1;
  2343. }
  2344. static int
  2345. event_signal(void *eventhdl)
  2346. {
  2347. struct posix_event *ev = (struct posix_event *)eventhdl;
  2348. pthread_mutex_lock(&(ev->mutex));
  2349. pthread_cond_signal(&(ev->cond));
  2350. pthread_mutex_unlock(&(ev->mutex));
  2351. return 1;
  2352. }
  2353. static void
  2354. event_destroy(void *eventhdl)
  2355. {
  2356. struct posix_event *ev = (struct posix_event *)eventhdl;
  2357. pthread_cond_destroy(&(ev->cond));
  2358. pthread_mutex_destroy(&(ev->mutex));
  2359. mg_free(ev);
  2360. }
  2361. #endif
  2362. static void
  2363. mg_set_thread_name(const char *name)
  2364. {
  2365. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2366. mg_snprintf(
  2367. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2368. #if defined(_WIN32)
  2369. #if defined(_MSC_VER)
  2370. /* Windows and Visual Studio Compiler */
  2371. __try
  2372. {
  2373. THREADNAME_INFO info;
  2374. info.dwType = 0x1000;
  2375. info.szName = threadName;
  2376. info.dwThreadID = ~0U;
  2377. info.dwFlags = 0;
  2378. RaiseException(0x406D1388,
  2379. 0,
  2380. sizeof(info) / sizeof(ULONG_PTR),
  2381. (ULONG_PTR *)&info);
  2382. }
  2383. __except(EXCEPTION_EXECUTE_HANDLER)
  2384. {
  2385. }
  2386. #elif defined(__MINGW32__)
  2387. /* No option known to set thread name for MinGW */
  2388. #endif
  2389. #elif defined(__GLIBC__) \
  2390. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2391. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2392. (void)pthread_setname_np(pthread_self(), threadName);
  2393. #elif defined(__linux__)
  2394. /* on linux we can use the old prctl function */
  2395. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2396. #endif
  2397. }
  2398. #else /* !defined(NO_THREAD_NAME) */
  2399. void
  2400. mg_set_thread_name(const char *threadName)
  2401. {
  2402. }
  2403. #endif
  2404. #if defined(MG_LEGACY_INTERFACE)
  2405. const char **
  2406. mg_get_valid_option_names(void)
  2407. {
  2408. /* This function is deprecated. Use mg_get_valid_options instead. */
  2409. static const char *
  2410. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2411. int i;
  2412. for (i = 0; config_options[i].name != NULL; i++) {
  2413. data[i * 2] = config_options[i].name;
  2414. data[i * 2 + 1] = config_options[i].default_value;
  2415. }
  2416. return data;
  2417. }
  2418. #endif
  2419. const struct mg_option *
  2420. mg_get_valid_options(void)
  2421. {
  2422. return config_options;
  2423. }
  2424. /* Do not open file (used in is_file_in_memory) */
  2425. #define MG_FOPEN_MODE_NONE (0)
  2426. /* Open file for read only access */
  2427. #define MG_FOPEN_MODE_READ (1)
  2428. /* Open file for writing, create and overwrite */
  2429. #define MG_FOPEN_MODE_WRITE (2)
  2430. /* Open file for writing, create and append */
  2431. #define MG_FOPEN_MODE_APPEND (4)
  2432. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2433. * output filep and return 1, otherwise return 0 and don't modify anything.
  2434. */
  2435. static int
  2436. open_file_in_memory(const struct mg_connection *conn,
  2437. const char *path,
  2438. struct mg_file *filep,
  2439. int mode)
  2440. {
  2441. #if defined(MG_USE_OPEN_FILE)
  2442. size_t size = 0;
  2443. const char *buf = NULL;
  2444. if (!conn) {
  2445. return 0;
  2446. }
  2447. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2448. return 0;
  2449. }
  2450. if (conn->phys_ctx->callbacks.open_file) {
  2451. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2452. if (buf != NULL) {
  2453. if (filep == NULL) {
  2454. /* This is a file in memory, but we cannot store the
  2455. * properties
  2456. * now.
  2457. * Called from "is_file_in_memory" function. */
  2458. return 1;
  2459. }
  2460. /* NOTE: override filep->size only on success. Otherwise, it
  2461. * might
  2462. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2463. filep->access.membuf = buf;
  2464. filep->access.fp = NULL;
  2465. /* Size was set by the callback */
  2466. filep->stat.size = size;
  2467. /* Assume the data may change during runtime by setting
  2468. * last_modified = now */
  2469. filep->stat.last_modified = time(NULL);
  2470. filep->stat.is_directory = 0;
  2471. filep->stat.is_gzipped = 0;
  2472. }
  2473. }
  2474. return (buf != NULL);
  2475. #else
  2476. (void)conn;
  2477. (void)path;
  2478. (void)filep;
  2479. (void)mode;
  2480. return 0;
  2481. #endif
  2482. }
  2483. static int
  2484. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2485. {
  2486. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2487. }
  2488. static int
  2489. is_file_opened(const struct mg_file_access *fileacc)
  2490. {
  2491. if (!fileacc) {
  2492. return 0;
  2493. }
  2494. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2495. }
  2496. static int mg_stat(const struct mg_connection *conn,
  2497. const char *path,
  2498. struct mg_file_stat *filep);
  2499. /* mg_fopen will open a file either in memory or on the disk.
  2500. * The input parameter path is a string in UTF-8 encoding.
  2501. * The input parameter mode is MG_FOPEN_MODE_*
  2502. * On success, either fp or membuf will be set in the output
  2503. * struct file. All status members will also be set.
  2504. * The function returns 1 on success, 0 on error. */
  2505. static int
  2506. mg_fopen(const struct mg_connection *conn,
  2507. const char *path,
  2508. int mode,
  2509. struct mg_file *filep)
  2510. {
  2511. int found;
  2512. if (!filep) {
  2513. return 0;
  2514. }
  2515. filep->access.fp = NULL;
  2516. filep->access.membuf = NULL;
  2517. if (!is_file_in_memory(conn, path)) {
  2518. /* filep is initialized in mg_stat: all fields with memset to,
  2519. * some fields like size and modification date with values */
  2520. found = mg_stat(conn, path, &(filep->stat));
  2521. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2522. /* file does not exist and will not be created */
  2523. return 0;
  2524. }
  2525. #ifdef _WIN32
  2526. {
  2527. wchar_t wbuf[W_PATH_MAX];
  2528. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2529. switch (mode) {
  2530. case MG_FOPEN_MODE_READ:
  2531. filep->access.fp = _wfopen(wbuf, L"rb");
  2532. break;
  2533. case MG_FOPEN_MODE_WRITE:
  2534. filep->access.fp = _wfopen(wbuf, L"wb");
  2535. break;
  2536. case MG_FOPEN_MODE_APPEND:
  2537. filep->access.fp = _wfopen(wbuf, L"ab");
  2538. break;
  2539. }
  2540. }
  2541. #else
  2542. /* Linux et al already use unicode. No need to convert. */
  2543. switch (mode) {
  2544. case MG_FOPEN_MODE_READ:
  2545. filep->access.fp = fopen(path, "r");
  2546. break;
  2547. case MG_FOPEN_MODE_WRITE:
  2548. filep->access.fp = fopen(path, "w");
  2549. break;
  2550. case MG_FOPEN_MODE_APPEND:
  2551. filep->access.fp = fopen(path, "a");
  2552. break;
  2553. }
  2554. #endif
  2555. if (!found) {
  2556. /* File did not exist before fopen was called.
  2557. * Maybe it has been created now. Get stat info
  2558. * like creation time now. */
  2559. found = mg_stat(conn, path, &(filep->stat));
  2560. (void)found;
  2561. }
  2562. /* file is on disk */
  2563. return (filep->access.fp != NULL);
  2564. } else {
  2565. /* is_file_in_memory returned true */
  2566. if (open_file_in_memory(conn, path, filep, mode)) {
  2567. /* file is in memory */
  2568. return (filep->access.membuf != NULL);
  2569. }
  2570. }
  2571. /* Open failed */
  2572. return 0;
  2573. }
  2574. /* return 0 on success, just like fclose */
  2575. static int
  2576. mg_fclose(struct mg_file_access *fileacc)
  2577. {
  2578. int ret = -1;
  2579. if (fileacc != NULL) {
  2580. if (fileacc->fp != NULL) {
  2581. ret = fclose(fileacc->fp);
  2582. } else if (fileacc->membuf != NULL) {
  2583. ret = 0;
  2584. }
  2585. /* reset all members of fileacc */
  2586. memset(fileacc, 0, sizeof(*fileacc));
  2587. }
  2588. return ret;
  2589. }
  2590. static void
  2591. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2592. {
  2593. for (; *src != '\0' && n > 1; n--) {
  2594. *dst++ = *src++;
  2595. }
  2596. *dst = '\0';
  2597. }
  2598. static int
  2599. lowercase(const char *s)
  2600. {
  2601. return tolower(*(const unsigned char *)s);
  2602. }
  2603. int
  2604. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2605. {
  2606. int diff = 0;
  2607. if (len > 0) {
  2608. do {
  2609. diff = lowercase(s1++) - lowercase(s2++);
  2610. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2611. }
  2612. return diff;
  2613. }
  2614. int
  2615. mg_strcasecmp(const char *s1, const char *s2)
  2616. {
  2617. int diff;
  2618. do {
  2619. diff = lowercase(s1++) - lowercase(s2++);
  2620. } while (diff == 0 && s1[-1] != '\0');
  2621. return diff;
  2622. }
  2623. static char *
  2624. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2625. {
  2626. char *p;
  2627. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2628. * defined */
  2629. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2630. mg_strlcpy(p, ptr, len + 1);
  2631. }
  2632. return p;
  2633. }
  2634. static char *
  2635. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2636. {
  2637. return mg_strndup_ctx(str, strlen(str), ctx);
  2638. }
  2639. static char *
  2640. mg_strdup(const char *str)
  2641. {
  2642. return mg_strndup_ctx(str, strlen(str), NULL);
  2643. }
  2644. static const char *
  2645. mg_strcasestr(const char *big_str, const char *small_str)
  2646. {
  2647. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2648. if (big_len >= small_len) {
  2649. for (i = 0; i <= (big_len - small_len); i++) {
  2650. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2651. return big_str + i;
  2652. }
  2653. }
  2654. }
  2655. return NULL;
  2656. }
  2657. /* Return null terminated string of given maximum length.
  2658. * Report errors if length is exceeded. */
  2659. static void
  2660. mg_vsnprintf(const struct mg_connection *conn,
  2661. int *truncated,
  2662. char *buf,
  2663. size_t buflen,
  2664. const char *fmt,
  2665. va_list ap)
  2666. {
  2667. int n, ok;
  2668. if (buflen == 0) {
  2669. if (truncated) {
  2670. *truncated = 1;
  2671. }
  2672. return;
  2673. }
  2674. #ifdef __clang__
  2675. #pragma clang diagnostic push
  2676. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2677. /* Using fmt as a non-literal is intended here, since it is mostly called
  2678. * indirectly by mg_snprintf */
  2679. #endif
  2680. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2681. ok = (n >= 0) && ((size_t)n < buflen);
  2682. #ifdef __clang__
  2683. #pragma clang diagnostic pop
  2684. #endif
  2685. if (ok) {
  2686. if (truncated) {
  2687. *truncated = 0;
  2688. }
  2689. } else {
  2690. if (truncated) {
  2691. *truncated = 1;
  2692. }
  2693. mg_cry_internal(conn,
  2694. "truncating vsnprintf buffer: [%.*s]",
  2695. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2696. buf);
  2697. n = (int)buflen - 1;
  2698. }
  2699. buf[n] = '\0';
  2700. }
  2701. static void
  2702. mg_snprintf(const struct mg_connection *conn,
  2703. int *truncated,
  2704. char *buf,
  2705. size_t buflen,
  2706. const char *fmt,
  2707. ...)
  2708. {
  2709. va_list ap;
  2710. va_start(ap, fmt);
  2711. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2712. va_end(ap);
  2713. }
  2714. static int
  2715. get_option_index(const char *name)
  2716. {
  2717. int i;
  2718. for (i = 0; config_options[i].name != NULL; i++) {
  2719. if (strcmp(config_options[i].name, name) == 0) {
  2720. return i;
  2721. }
  2722. }
  2723. return -1;
  2724. }
  2725. const char *
  2726. mg_get_option(const struct mg_context *ctx, const char *name)
  2727. {
  2728. int i;
  2729. if ((i = get_option_index(name)) == -1) {
  2730. return NULL;
  2731. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2732. return "";
  2733. } else {
  2734. return ctx->dd.config[i];
  2735. }
  2736. }
  2737. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2738. struct mg_context *
  2739. mg_get_context(const struct mg_connection *conn)
  2740. {
  2741. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2742. }
  2743. void *
  2744. mg_get_user_data(const struct mg_context *ctx)
  2745. {
  2746. return (ctx == NULL) ? NULL : ctx->user_data;
  2747. }
  2748. void
  2749. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2750. {
  2751. if (conn != NULL) {
  2752. conn->request_info.conn_data = data;
  2753. }
  2754. }
  2755. void *
  2756. mg_get_user_connection_data(const struct mg_connection *conn)
  2757. {
  2758. if (conn != NULL) {
  2759. return conn->request_info.conn_data;
  2760. }
  2761. return NULL;
  2762. }
  2763. #if defined(MG_LEGACY_INTERFACE)
  2764. /* Deprecated: Use mg_get_server_ports instead. */
  2765. size_t
  2766. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2767. {
  2768. size_t i;
  2769. if (!ctx) {
  2770. return 0;
  2771. }
  2772. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2773. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2774. ports[i] =
  2775. #if defined(USE_IPV6)
  2776. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2777. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2778. :
  2779. #endif
  2780. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2781. }
  2782. return i;
  2783. }
  2784. #endif
  2785. int
  2786. mg_get_server_ports(const struct mg_context *ctx,
  2787. int size,
  2788. struct mg_server_ports *ports)
  2789. {
  2790. int i, cnt = 0;
  2791. if (size <= 0) {
  2792. return -1;
  2793. }
  2794. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2795. if (!ctx) {
  2796. return -1;
  2797. }
  2798. if (!ctx->listening_sockets) {
  2799. return -1;
  2800. }
  2801. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2802. ports[cnt].port =
  2803. #if defined(USE_IPV6)
  2804. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2805. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2806. :
  2807. #endif
  2808. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2809. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2810. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2811. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2812. /* IPv4 */
  2813. ports[cnt].protocol = 1;
  2814. cnt++;
  2815. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2816. /* IPv6 */
  2817. ports[cnt].protocol = 3;
  2818. cnt++;
  2819. }
  2820. }
  2821. return cnt;
  2822. }
  2823. static void
  2824. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2825. {
  2826. buf[0] = '\0';
  2827. if (!usa) {
  2828. return;
  2829. }
  2830. if (usa->sa.sa_family == AF_INET) {
  2831. getnameinfo(&usa->sa,
  2832. sizeof(usa->sin),
  2833. buf,
  2834. (unsigned)len,
  2835. NULL,
  2836. 0,
  2837. NI_NUMERICHOST);
  2838. }
  2839. #if defined(USE_IPV6)
  2840. else if (usa->sa.sa_family == AF_INET6) {
  2841. getnameinfo(&usa->sa,
  2842. sizeof(usa->sin6),
  2843. buf,
  2844. (unsigned)len,
  2845. NULL,
  2846. 0,
  2847. NI_NUMERICHOST);
  2848. }
  2849. #endif
  2850. }
  2851. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2852. * included in all responses other than 100, 101, 5xx. */
  2853. static void
  2854. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2855. {
  2856. #ifndef REENTRANT_TIME
  2857. struct tm *tm;
  2858. tm = ((t != NULL) ? gmtime(t) : NULL);
  2859. if (tm != NULL) {
  2860. #else
  2861. struct tm _tm;
  2862. struct tm *tm = &_tm;
  2863. if (t != NULL) {
  2864. gmtime_r(t, tm);
  2865. #endif
  2866. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2867. } else {
  2868. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2869. buf[buf_len - 1] = '\0';
  2870. }
  2871. }
  2872. /* difftime for struct timespec. Return value is in seconds. */
  2873. static double
  2874. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2875. {
  2876. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2877. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2878. }
  2879. /* Print error message to the opened error log stream. */
  2880. static void
  2881. mg_cry_internal_impl(const struct mg_connection *conn,
  2882. const char *func,
  2883. unsigned line,
  2884. const char *fmt,
  2885. va_list ap)
  2886. {
  2887. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2888. struct mg_file fi;
  2889. time_t timestamp;
  2890. /* Unused, in the RELEASE build */
  2891. (void)func;
  2892. (void)line;
  2893. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2894. buf[sizeof(buf) - 1] = 0;
  2895. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2896. if (!conn) {
  2897. puts(buf);
  2898. return;
  2899. }
  2900. /* Do not lock when getting the callback value, here and below.
  2901. * I suppose this is fine, since function cannot disappear in the
  2902. * same way string option can. */
  2903. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2904. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2905. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2906. if (mg_fopen(conn,
  2907. conn->dom_ctx->config[ERROR_LOG_FILE],
  2908. MG_FOPEN_MODE_APPEND,
  2909. &fi) == 0) {
  2910. fi.access.fp = NULL;
  2911. }
  2912. } else {
  2913. fi.access.fp = NULL;
  2914. }
  2915. if (fi.access.fp != NULL) {
  2916. flockfile(fi.access.fp);
  2917. timestamp = time(NULL);
  2918. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2919. fprintf(fi.access.fp,
  2920. "[%010lu] [error] [client %s] ",
  2921. (unsigned long)timestamp,
  2922. src_addr);
  2923. if (conn->request_info.request_method != NULL) {
  2924. fprintf(fi.access.fp,
  2925. "%s %s: ",
  2926. conn->request_info.request_method,
  2927. conn->request_info.request_uri
  2928. ? conn->request_info.request_uri
  2929. : "");
  2930. }
  2931. fprintf(fi.access.fp, "%s", buf);
  2932. fputc('\n', fi.access.fp);
  2933. fflush(fi.access.fp);
  2934. funlockfile(fi.access.fp);
  2935. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2936. * mg_cry here anyway ;-) */
  2937. }
  2938. }
  2939. }
  2940. static void
  2941. mg_cry_internal_wrap(const struct mg_connection *conn,
  2942. const char *func,
  2943. unsigned line,
  2944. const char *fmt,
  2945. ...)
  2946. {
  2947. va_list ap;
  2948. va_start(ap, fmt);
  2949. mg_cry_internal_impl(conn, func, line, fmt, ap);
  2950. va_end(ap);
  2951. }
  2952. void
  2953. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2954. {
  2955. va_list ap;
  2956. va_start(ap, fmt);
  2957. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  2958. va_end(ap);
  2959. }
  2960. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  2961. /* Return fake connection structure. Used for logging, if connection
  2962. * is not applicable at the moment of logging. */
  2963. static struct mg_connection *
  2964. fc(struct mg_context *ctx)
  2965. {
  2966. static struct mg_connection fake_connection;
  2967. fake_connection.phys_ctx = ctx;
  2968. fake_connection.dom_ctx = &(ctx->dd);
  2969. return &fake_connection;
  2970. }
  2971. const char *
  2972. mg_version(void)
  2973. {
  2974. return CIVETWEB_VERSION;
  2975. }
  2976. const struct mg_request_info *
  2977. mg_get_request_info(const struct mg_connection *conn)
  2978. {
  2979. if (!conn) {
  2980. return NULL;
  2981. }
  2982. #if 1 /* TODO: deal with legacy */
  2983. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2984. static char txt[16];
  2985. sprintf(txt, "%03i", conn->response_info.status_code);
  2986. ((struct mg_connection *)conn)->request_info.local_uri =
  2987. ((struct mg_connection *)conn)->request_info.request_uri =
  2988. txt; /* TODO: not thread safe */
  2989. ((struct mg_connection *)conn)->request_info.num_headers =
  2990. conn->response_info.num_headers;
  2991. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2992. conn->response_info.http_headers,
  2993. sizeof(conn->response_info.http_headers));
  2994. } else
  2995. #endif
  2996. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2997. return NULL;
  2998. }
  2999. return &conn->request_info;
  3000. }
  3001. const struct mg_response_info *
  3002. mg_get_response_info(const struct mg_connection *conn)
  3003. {
  3004. if (!conn) {
  3005. return NULL;
  3006. }
  3007. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3008. return NULL;
  3009. }
  3010. return &conn->response_info;
  3011. }
  3012. static const char *
  3013. get_proto_name(const struct mg_connection *conn)
  3014. {
  3015. #ifdef __clang__
  3016. #pragma clang diagnostic push
  3017. #pragma clang diagnostic ignored "-Wunreachable-code"
  3018. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3019. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3020. * unreachable, but splitting into four different #ifdef clauses here is more
  3021. * complicated.
  3022. */
  3023. #endif
  3024. const struct mg_request_info *ri = &conn->request_info;
  3025. const char *proto =
  3026. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3027. : (ri->is_ssl ? "https" : "http"));
  3028. return proto;
  3029. #ifdef __clang__
  3030. #pragma clang diagnostic pop
  3031. #endif
  3032. }
  3033. int
  3034. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3035. {
  3036. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3037. return -1;
  3038. } else {
  3039. int truncated = 0;
  3040. const struct mg_request_info *ri = &conn->request_info;
  3041. const char *proto = get_proto_name(conn);
  3042. if (ri->local_uri == NULL) {
  3043. return -1;
  3044. }
  3045. if ((ri->request_uri != NULL)
  3046. && strcmp(ri->local_uri, ri->request_uri)) {
  3047. mg_snprintf(conn,
  3048. &truncated,
  3049. buf,
  3050. buflen,
  3051. "%s://%s",
  3052. proto,
  3053. ri->request_uri);
  3054. if (truncated) {
  3055. return -1;
  3056. }
  3057. return 0;
  3058. } else {
  3059. #if defined(USE_IPV6)
  3060. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3061. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3062. : htons(conn->client.lsa.sin.sin_port);
  3063. #else
  3064. int port = htons(conn->client.lsa.sin.sin_port);
  3065. #endif
  3066. int def_port = ri->is_ssl ? 443 : 80;
  3067. int auth_domain_check_enabled =
  3068. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3069. && (!mg_strcasecmp(
  3070. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  3071. "yes"));
  3072. const char *server_domain =
  3073. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3074. char portstr[16];
  3075. char server_ip[48];
  3076. if (port != def_port) {
  3077. sprintf(portstr, ":%u", (unsigned)port);
  3078. } else {
  3079. portstr[0] = 0;
  3080. }
  3081. if (!auth_domain_check_enabled || !server_domain) {
  3082. sockaddr_to_string(server_ip,
  3083. sizeof(server_ip),
  3084. &conn->client.lsa);
  3085. server_domain = server_ip;
  3086. }
  3087. mg_snprintf(conn,
  3088. &truncated,
  3089. buf,
  3090. buflen,
  3091. "%s://%s%s%s",
  3092. proto,
  3093. server_domain,
  3094. portstr,
  3095. ri->local_uri);
  3096. if (truncated) {
  3097. return -1;
  3098. }
  3099. return 0;
  3100. }
  3101. }
  3102. }
  3103. /* Skip the characters until one of the delimiters characters found.
  3104. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3105. * Advance pointer to buffer to the next word. Return found 0-terminated
  3106. * word.
  3107. * Delimiters can be quoted with quotechar. */
  3108. static char *
  3109. skip_quoted(char **buf,
  3110. const char *delimiters,
  3111. const char *whitespace,
  3112. char quotechar)
  3113. {
  3114. char *p, *begin_word, *end_word, *end_whitespace;
  3115. begin_word = *buf;
  3116. end_word = begin_word + strcspn(begin_word, delimiters);
  3117. /* Check for quotechar */
  3118. if (end_word > begin_word) {
  3119. p = end_word - 1;
  3120. while (*p == quotechar) {
  3121. /* While the delimiter is quoted, look for the next delimiter.
  3122. */
  3123. /* This happens, e.g., in calls from parse_auth_header,
  3124. * if the user name contains a " character. */
  3125. /* If there is anything beyond end_word, copy it. */
  3126. if (*end_word != '\0') {
  3127. size_t end_off = strcspn(end_word + 1, delimiters);
  3128. memmove(p, end_word, end_off + 1);
  3129. p += end_off; /* p must correspond to end_word - 1 */
  3130. end_word += end_off + 1;
  3131. } else {
  3132. *p = '\0';
  3133. break;
  3134. }
  3135. }
  3136. for (p++; p < end_word; p++) {
  3137. *p = '\0';
  3138. }
  3139. }
  3140. if (*end_word == '\0') {
  3141. *buf = end_word;
  3142. } else {
  3143. #if defined(__GNUC__) || defined(__MINGW32__)
  3144. /* Disable spurious conversion warning for GCC */
  3145. #if GCC_VERSION >= 40500
  3146. #pragma GCC diagnostic push
  3147. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3148. #endif /* GCC_VERSION >= 40500 */
  3149. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3150. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3151. #if defined(__GNUC__) || defined(__MINGW32__)
  3152. #if GCC_VERSION >= 40500
  3153. #pragma GCC diagnostic pop
  3154. #endif /* GCC_VERSION >= 40500 */
  3155. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3156. for (p = end_word; p < end_whitespace; p++) {
  3157. *p = '\0';
  3158. }
  3159. *buf = end_whitespace;
  3160. }
  3161. return begin_word;
  3162. }
  3163. /* Return HTTP header value, or NULL if not found. */
  3164. static const char *
  3165. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3166. {
  3167. int i;
  3168. for (i = 0; i < num_hdr; i++) {
  3169. if (!mg_strcasecmp(name, hdr[i].name)) {
  3170. return hdr[i].value;
  3171. }
  3172. }
  3173. return NULL;
  3174. }
  3175. #if defined(USE_WEBSOCKET)
  3176. /* Retrieve requested HTTP header multiple values, and return the number of
  3177. * found occurrences */
  3178. static int
  3179. get_req_headers(const struct mg_request_info *ri,
  3180. const char *name,
  3181. const char **output,
  3182. int output_max_size)
  3183. {
  3184. int i;
  3185. int cnt = 0;
  3186. if (ri) {
  3187. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3188. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3189. output[cnt++] = ri->http_headers[i].value;
  3190. }
  3191. }
  3192. }
  3193. return cnt;
  3194. }
  3195. #endif
  3196. const char *
  3197. mg_get_header(const struct mg_connection *conn, const char *name)
  3198. {
  3199. if (!conn) {
  3200. return NULL;
  3201. }
  3202. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3203. return get_header(conn->request_info.http_headers,
  3204. conn->request_info.num_headers,
  3205. name);
  3206. }
  3207. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3208. return get_header(conn->response_info.http_headers,
  3209. conn->response_info.num_headers,
  3210. name);
  3211. }
  3212. return NULL;
  3213. }
  3214. static const char *
  3215. get_http_version(const struct mg_connection *conn)
  3216. {
  3217. if (!conn) {
  3218. return NULL;
  3219. }
  3220. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3221. return conn->request_info.http_version;
  3222. }
  3223. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3224. return conn->response_info.http_version;
  3225. }
  3226. return NULL;
  3227. }
  3228. /* A helper function for traversing a comma separated list of values.
  3229. * It returns a list pointer shifted to the next value, or NULL if the end
  3230. * of the list found.
  3231. * Value is stored in val vector. If value has form "x=y", then eq_val
  3232. * vector is initialized to point to the "y" part, and val vector length
  3233. * is adjusted to point only to "x". */
  3234. static const char *
  3235. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3236. {
  3237. int end;
  3238. reparse:
  3239. if (val == NULL || list == NULL || *list == '\0') {
  3240. /* End of the list */
  3241. return NULL;
  3242. }
  3243. /* Skip over leading LWS */
  3244. while (*list == ' ' || *list == '\t')
  3245. list++;
  3246. val->ptr = list;
  3247. if ((list = strchr(val->ptr, ',')) != NULL) {
  3248. /* Comma found. Store length and shift the list ptr */
  3249. val->len = ((size_t)(list - val->ptr));
  3250. list++;
  3251. } else {
  3252. /* This value is the last one */
  3253. list = val->ptr + strlen(val->ptr);
  3254. val->len = ((size_t)(list - val->ptr));
  3255. }
  3256. /* Adjust length for trailing LWS */
  3257. end = (int)val->len - 1;
  3258. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3259. end--;
  3260. val->len = (size_t)(end + 1);
  3261. if (val->len == 0) {
  3262. /* Ignore any empty entries. */
  3263. goto reparse;
  3264. }
  3265. if (eq_val != NULL) {
  3266. /* Value has form "x=y", adjust pointers and lengths
  3267. * so that val points to "x", and eq_val points to "y". */
  3268. eq_val->len = 0;
  3269. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3270. if (eq_val->ptr != NULL) {
  3271. eq_val->ptr++; /* Skip over '=' character */
  3272. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3273. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3274. }
  3275. }
  3276. return list;
  3277. }
  3278. /* A helper function for checking if a comma separated list of values
  3279. * contains
  3280. * the given option (case insensitvely).
  3281. * 'header' can be NULL, in which case false is returned. */
  3282. static int
  3283. header_has_option(const char *header, const char *option)
  3284. {
  3285. struct vec opt_vec;
  3286. struct vec eq_vec;
  3287. DEBUG_ASSERT(option != NULL);
  3288. DEBUG_ASSERT(option[0] != '\0');
  3289. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3290. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3291. return 1;
  3292. }
  3293. return 0;
  3294. }
  3295. /* Perform case-insensitive match of string against pattern */
  3296. static int
  3297. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3298. {
  3299. const char *or_str;
  3300. size_t i;
  3301. int j, len, res;
  3302. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3303. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3304. return (res > 0) ? res : match_prefix(or_str + 1,
  3305. (size_t)((pattern + pattern_len)
  3306. - (or_str + 1)),
  3307. str);
  3308. }
  3309. for (i = 0, j = 0; (i < pattern_len); i++, j++) {
  3310. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3311. continue;
  3312. } else if (pattern[i] == '$') {
  3313. return (str[j] == '\0') ? j : -1;
  3314. } else if (pattern[i] == '*') {
  3315. i++;
  3316. if (pattern[i] == '*') {
  3317. i++;
  3318. len = (int)strlen(str + j);
  3319. } else {
  3320. len = (int)strcspn(str + j, "/");
  3321. }
  3322. if (i == pattern_len) {
  3323. return j + len;
  3324. }
  3325. do {
  3326. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3327. } while (res == -1 && len-- > 0);
  3328. return (res == -1) ? -1 : j + res + len;
  3329. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3330. return -1;
  3331. }
  3332. }
  3333. return j;
  3334. }
  3335. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3336. * This function must tolerate situations when connection info is not
  3337. * set up, for example if request parsing failed. */
  3338. static int
  3339. should_keep_alive(const struct mg_connection *conn)
  3340. {
  3341. const char *http_version;
  3342. const char *header;
  3343. /* First satisfy needs of the server */
  3344. if ((conn == NULL) || conn->must_close) {
  3345. /* Close, if civetweb framework needs to close */
  3346. return 0;
  3347. }
  3348. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3349. /* Close, if keep alive is not enabled */
  3350. return 0;
  3351. }
  3352. /* Check explicit wish of the client */
  3353. header = mg_get_header(conn, "Connection");
  3354. if (header) {
  3355. /* If there is a connection header from the client, obey */
  3356. if (header_has_option(header, "keep-alive")) {
  3357. return 1;
  3358. }
  3359. return 0;
  3360. }
  3361. /* Use default of the standard */
  3362. http_version = get_http_version(conn);
  3363. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3364. /* HTTP 1.1 default is keep alive */
  3365. return 1;
  3366. }
  3367. /* HTTP 1.0 (and earlier) default is to close the connection */
  3368. return 0;
  3369. }
  3370. static int
  3371. should_decode_url(const struct mg_connection *conn)
  3372. {
  3373. if (!conn || !conn->dom_ctx) {
  3374. return 0;
  3375. }
  3376. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3377. }
  3378. static const char *
  3379. suggest_connection_header(const struct mg_connection *conn)
  3380. {
  3381. return should_keep_alive(conn) ? "keep-alive" : "close";
  3382. }
  3383. static int
  3384. send_no_cache_header(struct mg_connection *conn)
  3385. {
  3386. /* Send all current and obsolete cache opt-out directives. */
  3387. return mg_printf(conn,
  3388. "Cache-Control: no-cache, no-store, "
  3389. "must-revalidate, private, max-age=0\r\n"
  3390. "Pragma: no-cache\r\n"
  3391. "Expires: 0\r\n");
  3392. }
  3393. static int
  3394. send_static_cache_header(struct mg_connection *conn)
  3395. {
  3396. #if !defined(NO_CACHING)
  3397. /* Read the server config to check how long a file may be cached.
  3398. * The configuration is in seconds. */
  3399. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3400. if (max_age <= 0) {
  3401. /* 0 means "do not cache". All values <0 are reserved
  3402. * and may be used differently in the future. */
  3403. /* If a file should not be cached, do not only send
  3404. * max-age=0, but also pragmas and Expires headers. */
  3405. return send_no_cache_header(conn);
  3406. }
  3407. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3408. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3409. /* See also https://www.mnot.net/cache_docs/ */
  3410. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3411. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3412. * leap
  3413. * year to 31622400 seconds. For the moment, we just send whatever has
  3414. * been configured, still the behavior for >1 year should be considered
  3415. * as undefined. */
  3416. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3417. #else /* NO_CACHING */
  3418. return send_no_cache_header(conn);
  3419. #endif /* !NO_CACHING */
  3420. }
  3421. static int
  3422. send_additional_header(struct mg_connection *conn)
  3423. {
  3424. int i = 0;
  3425. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3426. #if !defined(NO_SSL)
  3427. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3428. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3429. if (max_age >= 0) {
  3430. i += mg_printf(conn,
  3431. "Strict-Transport-Security: max-age=%u\r\n",
  3432. (unsigned)max_age);
  3433. }
  3434. }
  3435. #endif
  3436. if (header && header[0]) {
  3437. i += mg_printf(conn, "%s\r\n", header);
  3438. }
  3439. return i;
  3440. }
  3441. static void handle_file_based_request(struct mg_connection *conn,
  3442. const char *path,
  3443. struct mg_file *filep);
  3444. const char *
  3445. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3446. {
  3447. /* See IANA HTTP status code assignment:
  3448. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3449. */
  3450. switch (response_code) {
  3451. /* RFC2616 Section 10.1 - Informational 1xx */
  3452. case 100:
  3453. return "Continue"; /* RFC2616 Section 10.1.1 */
  3454. case 101:
  3455. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3456. case 102:
  3457. return "Processing"; /* RFC2518 Section 10.1 */
  3458. /* RFC2616 Section 10.2 - Successful 2xx */
  3459. case 200:
  3460. return "OK"; /* RFC2616 Section 10.2.1 */
  3461. case 201:
  3462. return "Created"; /* RFC2616 Section 10.2.2 */
  3463. case 202:
  3464. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3465. case 203:
  3466. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3467. case 204:
  3468. return "No Content"; /* RFC2616 Section 10.2.5 */
  3469. case 205:
  3470. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3471. case 206:
  3472. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3473. case 207:
  3474. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3475. */
  3476. case 208:
  3477. return "Already Reported"; /* RFC5842 Section 7.1 */
  3478. case 226:
  3479. return "IM used"; /* RFC3229 Section 10.4.1 */
  3480. /* RFC2616 Section 10.3 - Redirection 3xx */
  3481. case 300:
  3482. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3483. case 301:
  3484. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3485. case 302:
  3486. return "Found"; /* RFC2616 Section 10.3.3 */
  3487. case 303:
  3488. return "See Other"; /* RFC2616 Section 10.3.4 */
  3489. case 304:
  3490. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3491. case 305:
  3492. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3493. case 307:
  3494. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3495. case 308:
  3496. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3497. /* RFC2616 Section 10.4 - Client Error 4xx */
  3498. case 400:
  3499. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3500. case 401:
  3501. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3502. case 402:
  3503. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3504. case 403:
  3505. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3506. case 404:
  3507. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3508. case 405:
  3509. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3510. case 406:
  3511. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3512. case 407:
  3513. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3514. case 408:
  3515. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3516. case 409:
  3517. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3518. case 410:
  3519. return "Gone"; /* RFC2616 Section 10.4.11 */
  3520. case 411:
  3521. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3522. case 412:
  3523. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3524. case 413:
  3525. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3526. case 414:
  3527. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3528. case 415:
  3529. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3530. case 416:
  3531. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3532. */
  3533. case 417:
  3534. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3535. case 421:
  3536. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3537. case 422:
  3538. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3539. * Section 11.2 */
  3540. case 423:
  3541. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3542. case 424:
  3543. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3544. * Section 11.4 */
  3545. case 426:
  3546. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3547. case 428:
  3548. return "Precondition Required"; /* RFC 6585, Section 3 */
  3549. case 429:
  3550. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3551. case 431:
  3552. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3553. case 451:
  3554. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3555. * Section 3 */
  3556. /* RFC2616 Section 10.5 - Server Error 5xx */
  3557. case 500:
  3558. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3559. case 501:
  3560. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3561. case 502:
  3562. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3563. case 503:
  3564. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3565. case 504:
  3566. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3567. case 505:
  3568. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3569. case 506:
  3570. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3571. case 507:
  3572. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3573. * Section 11.5 */
  3574. case 508:
  3575. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3576. case 510:
  3577. return "Not Extended"; /* RFC 2774, Section 7 */
  3578. case 511:
  3579. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3580. /* Other status codes, not shown in the IANA HTTP status code
  3581. * assignment.
  3582. * E.g., "de facto" standards due to common use, ... */
  3583. case 418:
  3584. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3585. case 419:
  3586. return "Authentication Timeout"; /* common use */
  3587. case 420:
  3588. return "Enhance Your Calm"; /* common use */
  3589. case 440:
  3590. return "Login Timeout"; /* common use */
  3591. case 509:
  3592. return "Bandwidth Limit Exceeded"; /* common use */
  3593. default:
  3594. /* This error code is unknown. This should not happen. */
  3595. if (conn) {
  3596. mg_cry_internal(conn,
  3597. "Unknown HTTP response code: %u",
  3598. response_code);
  3599. }
  3600. /* Return at least a category according to RFC 2616 Section 10. */
  3601. if (response_code >= 100 && response_code < 200) {
  3602. /* Unknown informational status code */
  3603. return "Information";
  3604. }
  3605. if (response_code >= 200 && response_code < 300) {
  3606. /* Unknown success code */
  3607. return "Success";
  3608. }
  3609. if (response_code >= 300 && response_code < 400) {
  3610. /* Unknown redirection code */
  3611. return "Redirection";
  3612. }
  3613. if (response_code >= 400 && response_code < 500) {
  3614. /* Unknown request error code */
  3615. return "Client Error";
  3616. }
  3617. if (response_code >= 500 && response_code < 600) {
  3618. /* Unknown server error code */
  3619. return "Server Error";
  3620. }
  3621. /* Response code not even within reasonable range */
  3622. return "";
  3623. }
  3624. }
  3625. static void
  3626. mg_send_http_error_impl(struct mg_connection *conn,
  3627. int status,
  3628. const char *fmt,
  3629. va_list args)
  3630. {
  3631. char errmsg_buf[MG_BUF_LEN];
  3632. char path_buf[PATH_MAX];
  3633. va_list ap;
  3634. int len, i, page_handler_found, scope, truncated, has_body;
  3635. char date[64];
  3636. time_t curtime = time(NULL);
  3637. const char *error_handler = NULL;
  3638. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3639. const char *error_page_file_ext, *tstr;
  3640. int handled_by_callback = 0;
  3641. const char *status_text = mg_get_response_code_text(conn, status);
  3642. if (conn == NULL) {
  3643. return;
  3644. }
  3645. /* Set status (for log) */
  3646. conn->status_code = status;
  3647. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3648. has_body = ((status > 199) && (status != 204) && (status != 304));
  3649. /* Prepare message in buf, if required */
  3650. if ((has_body && (fmt != NULL))
  3651. || (!conn->in_error_handler
  3652. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3653. /* Store error message in errmsg_buf */
  3654. va_copy(ap, args);
  3655. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3656. va_end(ap);
  3657. /* In a debug build, print all html errors */
  3658. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3659. }
  3660. /* If there is a http_error callback, call it.
  3661. * But don't do it recursively, if callback calls mg_send_http_error again.
  3662. */
  3663. if (!conn->in_error_handler
  3664. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3665. /* Mark in_error_handler to avoid recursion and call user callback. */
  3666. conn->in_error_handler = 1;
  3667. handled_by_callback =
  3668. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3669. == 0);
  3670. conn->in_error_handler = 0;
  3671. }
  3672. if (!handled_by_callback) {
  3673. /* Check for recursion */
  3674. if (conn->in_error_handler) {
  3675. DEBUG_TRACE(
  3676. "Recursion when handling error %u - fall back to default",
  3677. status);
  3678. } else {
  3679. /* Send user defined error pages, if defined */
  3680. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3681. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3682. page_handler_found = 0;
  3683. if (error_handler != NULL) {
  3684. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3685. switch (scope) {
  3686. case 1: /* Handler for specific error, e.g. 404 error */
  3687. mg_snprintf(conn,
  3688. &truncated,
  3689. path_buf,
  3690. sizeof(path_buf) - 32,
  3691. "%serror%03u.",
  3692. error_handler,
  3693. status);
  3694. break;
  3695. case 2: /* Handler for error group, e.g., 5xx error
  3696. * handler
  3697. * for all server errors (500-599) */
  3698. mg_snprintf(conn,
  3699. &truncated,
  3700. path_buf,
  3701. sizeof(path_buf) - 32,
  3702. "%serror%01uxx.",
  3703. error_handler,
  3704. status / 100);
  3705. break;
  3706. default: /* Handler for all errors */
  3707. mg_snprintf(conn,
  3708. &truncated,
  3709. path_buf,
  3710. sizeof(path_buf) - 32,
  3711. "%serror.",
  3712. error_handler);
  3713. break;
  3714. }
  3715. /* String truncation in buf may only occur if
  3716. * error_handler is too long. This string is
  3717. * from the config, not from a client. */
  3718. (void)truncated;
  3719. len = (int)strlen(path_buf);
  3720. tstr = strchr(error_page_file_ext, '.');
  3721. while (tstr) {
  3722. for (i = 1;
  3723. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3724. i++)
  3725. path_buf[len + i - 1] = tstr[i];
  3726. path_buf[len + i - 1] = 0;
  3727. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3728. DEBUG_TRACE("Check error page %s - found",
  3729. path_buf);
  3730. page_handler_found = 1;
  3731. break;
  3732. }
  3733. DEBUG_TRACE("Check error page %s - not found",
  3734. path_buf);
  3735. tstr = strchr(tstr + i, '.');
  3736. }
  3737. }
  3738. }
  3739. if (page_handler_found) {
  3740. conn->in_error_handler = 1;
  3741. handle_file_based_request(conn, path_buf, &error_page_file);
  3742. conn->in_error_handler = 0;
  3743. return;
  3744. }
  3745. }
  3746. /* No custom error page. Send default error page. */
  3747. gmt_time_string(date, sizeof(date), &curtime);
  3748. conn->must_close = 1;
  3749. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3750. send_no_cache_header(conn);
  3751. send_additional_header(conn);
  3752. if (has_body) {
  3753. mg_printf(conn,
  3754. "%s",
  3755. "Content-Type: text/plain; charset=utf-8\r\n");
  3756. }
  3757. mg_printf(conn,
  3758. "Date: %s\r\n"
  3759. "Connection: close\r\n\r\n",
  3760. date);
  3761. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3762. if (has_body) {
  3763. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3764. if (fmt != NULL) {
  3765. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3766. }
  3767. } else {
  3768. /* No body allowed. Close the connection. */
  3769. DEBUG_TRACE("Error %i", status);
  3770. }
  3771. }
  3772. }
  3773. void
  3774. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3775. {
  3776. va_list ap;
  3777. va_start(ap, fmt);
  3778. mg_send_http_error_impl(conn, status, fmt, ap);
  3779. va_end(ap);
  3780. }
  3781. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3782. /* Create substitutes for POSIX functions in Win32. */
  3783. #if defined(__MINGW32__)
  3784. /* Show no warning in case system functions are not used. */
  3785. #pragma GCC diagnostic push
  3786. #pragma GCC diagnostic ignored "-Wunused-function"
  3787. #endif
  3788. FUNCTION_MAY_BE_UNUSED
  3789. static int
  3790. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3791. {
  3792. (void)unused;
  3793. *mutex = CreateMutex(NULL, FALSE, NULL);
  3794. return (*mutex == NULL) ? -1 : 0;
  3795. }
  3796. FUNCTION_MAY_BE_UNUSED
  3797. static int
  3798. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3799. {
  3800. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3801. }
  3802. FUNCTION_MAY_BE_UNUSED
  3803. static int
  3804. pthread_mutex_lock(pthread_mutex_t *mutex)
  3805. {
  3806. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  3807. : -1;
  3808. }
  3809. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3810. FUNCTION_MAY_BE_UNUSED
  3811. static int
  3812. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3813. {
  3814. switch (WaitForSingleObject(*mutex, 0)) {
  3815. case WAIT_OBJECT_0:
  3816. return 0;
  3817. case WAIT_TIMEOUT:
  3818. return -2; /* EBUSY */
  3819. }
  3820. return -1;
  3821. }
  3822. #endif
  3823. FUNCTION_MAY_BE_UNUSED
  3824. static int
  3825. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3826. {
  3827. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3828. }
  3829. FUNCTION_MAY_BE_UNUSED
  3830. static int
  3831. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3832. {
  3833. (void)unused;
  3834. InitializeCriticalSection(&cv->threadIdSec);
  3835. cv->waiting_thread = NULL;
  3836. return 0;
  3837. }
  3838. FUNCTION_MAY_BE_UNUSED
  3839. static int
  3840. pthread_cond_timedwait(pthread_cond_t *cv,
  3841. pthread_mutex_t *mutex,
  3842. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  3843. {
  3844. struct mg_workerTLS **ptls,
  3845. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3846. int ok;
  3847. int64_t nsnow, nswaitabs, nswaitrel;
  3848. DWORD mswaitrel;
  3849. EnterCriticalSection(&cv->threadIdSec);
  3850. /* Add this thread to cv's waiting list */
  3851. ptls = &cv->waiting_thread;
  3852. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3853. ;
  3854. tls->next_waiting_thread = NULL;
  3855. *ptls = tls;
  3856. LeaveCriticalSection(&cv->threadIdSec);
  3857. if (abstime) {
  3858. nsnow = mg_get_current_time_ns();
  3859. nswaitabs =
  3860. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3861. nswaitrel = nswaitabs - nsnow;
  3862. if (nswaitrel < 0) {
  3863. nswaitrel = 0;
  3864. }
  3865. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3866. } else {
  3867. mswaitrel = (DWORD)INFINITE;
  3868. }
  3869. pthread_mutex_unlock(mutex);
  3870. ok = (WAIT_OBJECT_0
  3871. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3872. if (!ok) {
  3873. ok = 1;
  3874. EnterCriticalSection(&cv->threadIdSec);
  3875. ptls = &cv->waiting_thread;
  3876. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3877. if (*ptls == tls) {
  3878. *ptls = tls->next_waiting_thread;
  3879. ok = 0;
  3880. break;
  3881. }
  3882. }
  3883. LeaveCriticalSection(&cv->threadIdSec);
  3884. if (ok) {
  3885. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  3886. (DWORD)INFINITE);
  3887. }
  3888. }
  3889. /* This thread has been removed from cv's waiting list */
  3890. pthread_mutex_lock(mutex);
  3891. return ok ? 0 : -1;
  3892. }
  3893. FUNCTION_MAY_BE_UNUSED
  3894. static int
  3895. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3896. {
  3897. return pthread_cond_timedwait(cv, mutex, NULL);
  3898. }
  3899. FUNCTION_MAY_BE_UNUSED
  3900. static int
  3901. pthread_cond_signal(pthread_cond_t *cv)
  3902. {
  3903. HANDLE wkup = NULL;
  3904. BOOL ok = FALSE;
  3905. EnterCriticalSection(&cv->threadIdSec);
  3906. if (cv->waiting_thread) {
  3907. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3908. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3909. ok = SetEvent(wkup);
  3910. DEBUG_ASSERT(ok);
  3911. }
  3912. LeaveCriticalSection(&cv->threadIdSec);
  3913. return ok ? 0 : 1;
  3914. }
  3915. FUNCTION_MAY_BE_UNUSED
  3916. static int
  3917. pthread_cond_broadcast(pthread_cond_t *cv)
  3918. {
  3919. EnterCriticalSection(&cv->threadIdSec);
  3920. while (cv->waiting_thread) {
  3921. pthread_cond_signal(cv);
  3922. }
  3923. LeaveCriticalSection(&cv->threadIdSec);
  3924. return 0;
  3925. }
  3926. FUNCTION_MAY_BE_UNUSED
  3927. static int
  3928. pthread_cond_destroy(pthread_cond_t *cv)
  3929. {
  3930. EnterCriticalSection(&cv->threadIdSec);
  3931. DEBUG_ASSERT(cv->waiting_thread == NULL);
  3932. LeaveCriticalSection(&cv->threadIdSec);
  3933. DeleteCriticalSection(&cv->threadIdSec);
  3934. return 0;
  3935. }
  3936. #ifdef ALTERNATIVE_QUEUE
  3937. FUNCTION_MAY_BE_UNUSED
  3938. static void *
  3939. event_create(void)
  3940. {
  3941. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3942. }
  3943. FUNCTION_MAY_BE_UNUSED
  3944. static int
  3945. event_wait(void *eventhdl)
  3946. {
  3947. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  3948. return (res == WAIT_OBJECT_0);
  3949. }
  3950. FUNCTION_MAY_BE_UNUSED
  3951. static int
  3952. event_signal(void *eventhdl)
  3953. {
  3954. return (int)SetEvent((HANDLE)eventhdl);
  3955. }
  3956. FUNCTION_MAY_BE_UNUSED
  3957. static void
  3958. event_destroy(void *eventhdl)
  3959. {
  3960. CloseHandle((HANDLE)eventhdl);
  3961. }
  3962. #endif
  3963. #if defined(__MINGW32__)
  3964. /* Enable unused function warning again */
  3965. #pragma GCC diagnostic pop
  3966. #endif
  3967. /* For Windows, change all slashes to backslashes in path names. */
  3968. static void
  3969. change_slashes_to_backslashes(char *path)
  3970. {
  3971. int i;
  3972. for (i = 0; path[i] != '\0'; i++) {
  3973. if (path[i] == '/') {
  3974. path[i] = '\\';
  3975. }
  3976. /* remove double backslash (check i > 0 to preserve UNC paths,
  3977. * like \\server\file.txt) */
  3978. if ((path[i] == '\\') && (i > 0)) {
  3979. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  3980. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3981. }
  3982. }
  3983. }
  3984. }
  3985. static int
  3986. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3987. {
  3988. int diff;
  3989. do {
  3990. diff = tolower(*s1) - tolower(*s2);
  3991. s1++;
  3992. s2++;
  3993. } while ((diff == 0) && (s1[-1] != '\0'));
  3994. return diff;
  3995. }
  3996. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3997. * wbuf and wbuf_len is a target buffer and its length. */
  3998. static void
  3999. path_to_unicode(const struct mg_connection *conn,
  4000. const char *path,
  4001. wchar_t *wbuf,
  4002. size_t wbuf_len)
  4003. {
  4004. char buf[PATH_MAX], buf2[PATH_MAX];
  4005. wchar_t wbuf2[W_PATH_MAX + 1];
  4006. DWORD long_len, err;
  4007. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4008. mg_strlcpy(buf, path, sizeof(buf));
  4009. change_slashes_to_backslashes(buf);
  4010. /* Convert to Unicode and back. If doubly-converted string does not
  4011. * match the original, something is fishy, reject. */
  4012. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4013. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4014. WideCharToMultiByte(
  4015. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4016. if (strcmp(buf, buf2) != 0) {
  4017. wbuf[0] = L'\0';
  4018. }
  4019. /* Windows file systems are not case sensitive, but you can still use
  4020. * uppercase and lowercase letters (on all modern file systems).
  4021. * The server can check if the URI uses the same upper/lowercase
  4022. * letters an the file system, effectively making Windows servers
  4023. * case sensitive (like Linux servers are). It is still not possible
  4024. * to use two files with the same name in different cases on Windows
  4025. * (like /a and /A) - this would be possible in Linux.
  4026. * As a default, Windows is not case sensitive, but the case sensitive
  4027. * file name check can be activated by an additional configuration. */
  4028. if (conn) {
  4029. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4030. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4031. "yes")) {
  4032. /* Use case sensitive compare function */
  4033. fcompare = wcscmp;
  4034. }
  4035. }
  4036. (void)conn; /* conn is currently unused */
  4037. #if !defined(_WIN32_WCE)
  4038. /* Only accept a full file path, not a Windows short (8.3) path. */
  4039. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4040. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4041. if (long_len == 0) {
  4042. err = GetLastError();
  4043. if (err == ERROR_FILE_NOT_FOUND) {
  4044. /* File does not exist. This is not always a problem here. */
  4045. return;
  4046. }
  4047. }
  4048. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4049. /* Short name is used. */
  4050. wbuf[0] = L'\0';
  4051. }
  4052. #else
  4053. (void)long_len;
  4054. (void)wbuf2;
  4055. (void)err;
  4056. if (strchr(path, '~')) {
  4057. wbuf[0] = L'\0';
  4058. }
  4059. #endif
  4060. }
  4061. /* Windows happily opens files with some garbage at the end of file name.
  4062. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4063. * "a.cgi", despite one would expect an error back.
  4064. * This function returns non-0 if path ends with some garbage. */
  4065. static int
  4066. path_cannot_disclose_cgi(const char *path)
  4067. {
  4068. static const char *allowed_last_characters = "_-";
  4069. int last = path[strlen(path) - 1];
  4070. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  4071. }
  4072. static int
  4073. mg_stat(const struct mg_connection *conn,
  4074. const char *path,
  4075. struct mg_file_stat *filep)
  4076. {
  4077. wchar_t wbuf[W_PATH_MAX];
  4078. WIN32_FILE_ATTRIBUTE_DATA info;
  4079. time_t creation_time;
  4080. if (!filep) {
  4081. return 0;
  4082. }
  4083. memset(filep, 0, sizeof(*filep));
  4084. if (conn && is_file_in_memory(conn, path)) {
  4085. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4086. * memset */
  4087. /* Quick fix (for 1.9.x): */
  4088. /* mg_stat must fill all fields, also for files in memory */
  4089. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4090. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4091. filep->size = tmp_file.stat.size;
  4092. filep->location = 2;
  4093. /* TODO: for 1.10: restructure how files in memory are handled */
  4094. /* The "file in memory" feature is a candidate for deletion.
  4095. * Please join the discussion at
  4096. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4097. */
  4098. filep->last_modified = time(NULL); /* TODO */
  4099. /* last_modified = now ... assumes the file may change during
  4100. * runtime,
  4101. * so every mg_fopen call may return different data */
  4102. /* last_modified = conn->phys_ctx.start_time;
  4103. * May be used it the data does not change during runtime. This
  4104. * allows
  4105. * browser caching. Since we do not know, we have to assume the file
  4106. * in memory may change. */
  4107. return 1;
  4108. }
  4109. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4110. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  4111. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4112. filep->last_modified =
  4113. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4114. info.ftLastWriteTime.dwHighDateTime);
  4115. /* On Windows, the file creation time can be higher than the
  4116. * modification time, e.g. when a file is copied.
  4117. * Since the Last-Modified timestamp is used for caching
  4118. * it should be based on the most recent timestamp. */
  4119. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4120. info.ftCreationTime.dwHighDateTime);
  4121. if (creation_time > filep->last_modified) {
  4122. filep->last_modified = creation_time;
  4123. }
  4124. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4125. /* If file name is fishy, reset the file structure and return
  4126. * error.
  4127. * Note it is important to reset, not just return the error, cause
  4128. * functions like is_file_opened() check the struct. */
  4129. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  4130. memset(filep, 0, sizeof(*filep));
  4131. return 0;
  4132. }
  4133. return 1;
  4134. }
  4135. return 0;
  4136. }
  4137. static int
  4138. mg_remove(const struct mg_connection *conn, const char *path)
  4139. {
  4140. wchar_t wbuf[W_PATH_MAX];
  4141. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4142. return DeleteFileW(wbuf) ? 0 : -1;
  4143. }
  4144. static int
  4145. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4146. {
  4147. wchar_t wbuf[W_PATH_MAX];
  4148. (void)mode;
  4149. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4150. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4151. }
  4152. /* Create substitutes for POSIX functions in Win32. */
  4153. #if defined(__MINGW32__)
  4154. /* Show no warning in case system functions are not used. */
  4155. #pragma GCC diagnostic push
  4156. #pragma GCC diagnostic ignored "-Wunused-function"
  4157. #endif
  4158. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4159. FUNCTION_MAY_BE_UNUSED
  4160. static DIR *
  4161. mg_opendir(const struct mg_connection *conn, const char *name)
  4162. {
  4163. DIR *dir = NULL;
  4164. wchar_t wpath[W_PATH_MAX];
  4165. DWORD attrs;
  4166. if (name == NULL) {
  4167. SetLastError(ERROR_BAD_ARGUMENTS);
  4168. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4169. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4170. } else {
  4171. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4172. attrs = GetFileAttributesW(wpath);
  4173. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4174. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4175. (void)wcscat(wpath, L"\\*");
  4176. dir->handle = FindFirstFileW(wpath, &dir->info);
  4177. dir->result.d_name[0] = '\0';
  4178. } else {
  4179. mg_free(dir);
  4180. dir = NULL;
  4181. }
  4182. }
  4183. return dir;
  4184. }
  4185. FUNCTION_MAY_BE_UNUSED
  4186. static int
  4187. mg_closedir(DIR *dir)
  4188. {
  4189. int result = 0;
  4190. if (dir != NULL) {
  4191. if (dir->handle != INVALID_HANDLE_VALUE)
  4192. result = FindClose(dir->handle) ? 0 : -1;
  4193. mg_free(dir);
  4194. } else {
  4195. result = -1;
  4196. SetLastError(ERROR_BAD_ARGUMENTS);
  4197. }
  4198. return result;
  4199. }
  4200. FUNCTION_MAY_BE_UNUSED
  4201. static struct dirent *
  4202. mg_readdir(DIR *dir)
  4203. {
  4204. struct dirent *result = 0;
  4205. if (dir) {
  4206. if (dir->handle != INVALID_HANDLE_VALUE) {
  4207. result = &dir->result;
  4208. (void)WideCharToMultiByte(CP_UTF8,
  4209. 0,
  4210. dir->info.cFileName,
  4211. -1,
  4212. result->d_name,
  4213. sizeof(result->d_name),
  4214. NULL,
  4215. NULL);
  4216. if (!FindNextFileW(dir->handle, &dir->info)) {
  4217. (void)FindClose(dir->handle);
  4218. dir->handle = INVALID_HANDLE_VALUE;
  4219. }
  4220. } else {
  4221. SetLastError(ERROR_FILE_NOT_FOUND);
  4222. }
  4223. } else {
  4224. SetLastError(ERROR_BAD_ARGUMENTS);
  4225. }
  4226. return result;
  4227. }
  4228. #ifndef HAVE_POLL
  4229. FUNCTION_MAY_BE_UNUSED
  4230. static int
  4231. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4232. {
  4233. struct timeval tv;
  4234. fd_set set;
  4235. unsigned int i;
  4236. int result;
  4237. SOCKET maxfd = 0;
  4238. memset(&tv, 0, sizeof(tv));
  4239. tv.tv_sec = milliseconds / 1000;
  4240. tv.tv_usec = (milliseconds % 1000) * 1000;
  4241. FD_ZERO(&set);
  4242. for (i = 0; i < n; i++) {
  4243. FD_SET((SOCKET)pfd[i].fd, &set);
  4244. pfd[i].revents = 0;
  4245. if (pfd[i].fd > maxfd) {
  4246. maxfd = pfd[i].fd;
  4247. }
  4248. }
  4249. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  4250. for (i = 0; i < n; i++) {
  4251. if (FD_ISSET(pfd[i].fd, &set)) {
  4252. pfd[i].revents = POLLIN;
  4253. }
  4254. }
  4255. }
  4256. /* We should subtract the time used in select from remaining
  4257. * "milliseconds", in particular if called from mg_poll with a
  4258. * timeout quantum.
  4259. * Unfortunately, the remaining time is not stored in "tv" in all
  4260. * implementations, so the result in "tv" must be considered undefined.
  4261. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4262. return result;
  4263. }
  4264. #endif /* HAVE_POLL */
  4265. #if defined(__MINGW32__)
  4266. /* Enable unused function warning again */
  4267. #pragma GCC diagnostic pop
  4268. #endif
  4269. static void
  4270. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4271. {
  4272. (void)conn; /* Unused. */
  4273. #if defined(_WIN32_WCE)
  4274. (void)sock;
  4275. #else
  4276. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4277. #endif
  4278. }
  4279. int
  4280. mg_start_thread(mg_thread_func_t f, void *p)
  4281. {
  4282. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4283. /* Compile-time option to control stack size, e.g.
  4284. * -DUSE_STACK_SIZE=16384
  4285. */
  4286. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4287. == ((uintptr_t)(-1L)))
  4288. ? -1
  4289. : 0);
  4290. #else
  4291. return (
  4292. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4293. ? -1
  4294. : 0);
  4295. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4296. }
  4297. /* Start a thread storing the thread context. */
  4298. static int
  4299. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4300. void *p,
  4301. pthread_t *threadidptr)
  4302. {
  4303. uintptr_t uip;
  4304. HANDLE threadhandle;
  4305. int result = -1;
  4306. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4307. threadhandle = (HANDLE)uip;
  4308. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4309. *threadidptr = threadhandle;
  4310. result = 0;
  4311. }
  4312. return result;
  4313. }
  4314. /* Wait for a thread to finish. */
  4315. static int
  4316. mg_join_thread(pthread_t threadid)
  4317. {
  4318. int result;
  4319. DWORD dwevent;
  4320. result = -1;
  4321. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4322. if (dwevent == WAIT_FAILED) {
  4323. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4324. } else {
  4325. if (dwevent == WAIT_OBJECT_0) {
  4326. CloseHandle(threadid);
  4327. result = 0;
  4328. }
  4329. }
  4330. return result;
  4331. }
  4332. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4333. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4334. /* Create substitutes for POSIX functions in Win32. */
  4335. #if defined(__MINGW32__)
  4336. /* Show no warning in case system functions are not used. */
  4337. #pragma GCC diagnostic push
  4338. #pragma GCC diagnostic ignored "-Wunused-function"
  4339. #endif
  4340. FUNCTION_MAY_BE_UNUSED
  4341. static HANDLE
  4342. dlopen(const char *dll_name, int flags)
  4343. {
  4344. wchar_t wbuf[W_PATH_MAX];
  4345. (void)flags;
  4346. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4347. return LoadLibraryW(wbuf);
  4348. }
  4349. FUNCTION_MAY_BE_UNUSED
  4350. static int
  4351. dlclose(void *handle)
  4352. {
  4353. int result;
  4354. if (FreeLibrary((HMODULE)handle) != 0) {
  4355. result = 0;
  4356. } else {
  4357. result = -1;
  4358. }
  4359. return result;
  4360. }
  4361. #if defined(__MINGW32__)
  4362. /* Enable unused function warning again */
  4363. #pragma GCC diagnostic pop
  4364. #endif
  4365. #endif
  4366. #if !defined(NO_CGI)
  4367. #define SIGKILL (0)
  4368. static int
  4369. kill(pid_t pid, int sig_num)
  4370. {
  4371. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4372. (void)CloseHandle((HANDLE)pid);
  4373. return 0;
  4374. }
  4375. static void
  4376. trim_trailing_whitespaces(char *s)
  4377. {
  4378. char *e = s + strlen(s) - 1;
  4379. while ((e > s) && isspace(*(unsigned char *)e)) {
  4380. *e-- = '\0';
  4381. }
  4382. }
  4383. static pid_t
  4384. spawn_process(struct mg_connection *conn,
  4385. const char *prog,
  4386. char *envblk,
  4387. char *envp[],
  4388. int fdin[2],
  4389. int fdout[2],
  4390. int fderr[2],
  4391. const char *dir)
  4392. {
  4393. HANDLE me;
  4394. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4395. cmdline[PATH_MAX], buf[PATH_MAX];
  4396. int truncated;
  4397. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4398. STARTUPINFOA si;
  4399. PROCESS_INFORMATION pi = {0};
  4400. (void)envp;
  4401. memset(&si, 0, sizeof(si));
  4402. si.cb = sizeof(si);
  4403. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4404. si.wShowWindow = SW_HIDE;
  4405. me = GetCurrentProcess();
  4406. DuplicateHandle(me,
  4407. (HANDLE)_get_osfhandle(fdin[0]),
  4408. me,
  4409. &si.hStdInput,
  4410. 0,
  4411. TRUE,
  4412. DUPLICATE_SAME_ACCESS);
  4413. DuplicateHandle(me,
  4414. (HANDLE)_get_osfhandle(fdout[1]),
  4415. me,
  4416. &si.hStdOutput,
  4417. 0,
  4418. TRUE,
  4419. DUPLICATE_SAME_ACCESS);
  4420. DuplicateHandle(me,
  4421. (HANDLE)_get_osfhandle(fderr[1]),
  4422. me,
  4423. &si.hStdError,
  4424. 0,
  4425. TRUE,
  4426. DUPLICATE_SAME_ACCESS);
  4427. /* Mark handles that should not be inherited. See
  4428. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4429. */
  4430. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4431. HANDLE_FLAG_INHERIT,
  4432. 0);
  4433. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4434. HANDLE_FLAG_INHERIT,
  4435. 0);
  4436. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4437. HANDLE_FLAG_INHERIT,
  4438. 0);
  4439. /* If CGI file is a script, try to read the interpreter line */
  4440. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4441. if (interp == NULL) {
  4442. buf[0] = buf[1] = '\0';
  4443. /* Read the first line of the script into the buffer */
  4444. mg_snprintf(
  4445. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4446. if (truncated) {
  4447. pi.hProcess = (pid_t)-1;
  4448. goto spawn_cleanup;
  4449. }
  4450. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4451. p = (char *)file.access.membuf;
  4452. mg_fgets(buf, sizeof(buf), &file, &p);
  4453. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4454. buf[sizeof(buf) - 1] = '\0';
  4455. }
  4456. if ((buf[0] == '#') && (buf[1] == '!')) {
  4457. trim_trailing_whitespaces(buf + 2);
  4458. } else {
  4459. buf[2] = '\0';
  4460. }
  4461. interp = buf + 2;
  4462. }
  4463. if (interp[0] != '\0') {
  4464. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4465. interp = full_interp;
  4466. }
  4467. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4468. if (interp[0] != '\0') {
  4469. mg_snprintf(conn,
  4470. &truncated,
  4471. cmdline,
  4472. sizeof(cmdline),
  4473. "\"%s\" \"%s\\%s\"",
  4474. interp,
  4475. full_dir,
  4476. prog);
  4477. } else {
  4478. mg_snprintf(conn,
  4479. &truncated,
  4480. cmdline,
  4481. sizeof(cmdline),
  4482. "\"%s\\%s\"",
  4483. full_dir,
  4484. prog);
  4485. }
  4486. if (truncated) {
  4487. pi.hProcess = (pid_t)-1;
  4488. goto spawn_cleanup;
  4489. }
  4490. DEBUG_TRACE("Running [%s]", cmdline);
  4491. if (CreateProcessA(NULL,
  4492. cmdline,
  4493. NULL,
  4494. NULL,
  4495. TRUE,
  4496. CREATE_NEW_PROCESS_GROUP,
  4497. envblk,
  4498. NULL,
  4499. &si,
  4500. &pi) == 0) {
  4501. mg_cry_internal(
  4502. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4503. pi.hProcess = (pid_t)-1;
  4504. /* goto spawn_cleanup; */
  4505. }
  4506. spawn_cleanup:
  4507. (void)CloseHandle(si.hStdOutput);
  4508. (void)CloseHandle(si.hStdError);
  4509. (void)CloseHandle(si.hStdInput);
  4510. if (pi.hThread != NULL) {
  4511. (void)CloseHandle(pi.hThread);
  4512. }
  4513. return (pid_t)pi.hProcess;
  4514. }
  4515. #endif /* !NO_CGI */
  4516. static int
  4517. set_blocking_mode(SOCKET sock)
  4518. {
  4519. unsigned long non_blocking = 0;
  4520. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4521. }
  4522. static int
  4523. set_non_blocking_mode(SOCKET sock)
  4524. {
  4525. unsigned long non_blocking = 1;
  4526. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4527. }
  4528. #else
  4529. static int
  4530. mg_stat(const struct mg_connection *conn,
  4531. const char *path,
  4532. struct mg_file_stat *filep)
  4533. {
  4534. struct stat st;
  4535. if (!filep) {
  4536. return 0;
  4537. }
  4538. memset(filep, 0, sizeof(*filep));
  4539. if (conn && is_file_in_memory(conn, path)) {
  4540. /* Quick fix (for 1.9.x): */
  4541. /* mg_stat must fill all fields, also for files in memory */
  4542. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4543. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4544. filep->size = tmp_file.stat.size;
  4545. filep->last_modified = time(NULL);
  4546. filep->location = 2;
  4547. /* TODO: for 1.10: restructure how files in memory are handled */
  4548. return 1;
  4549. }
  4550. if (0 == stat(path, &st)) {
  4551. filep->size = (uint64_t)(st.st_size);
  4552. filep->last_modified = st.st_mtime;
  4553. filep->is_directory = S_ISDIR(st.st_mode);
  4554. return 1;
  4555. }
  4556. return 0;
  4557. }
  4558. static void
  4559. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4560. {
  4561. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4562. if (conn) {
  4563. mg_cry_internal(conn,
  4564. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4565. __func__,
  4566. strerror(ERRNO));
  4567. }
  4568. }
  4569. }
  4570. int
  4571. mg_start_thread(mg_thread_func_t func, void *param)
  4572. {
  4573. pthread_t thread_id;
  4574. pthread_attr_t attr;
  4575. int result;
  4576. (void)pthread_attr_init(&attr);
  4577. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4578. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4579. /* Compile-time option to control stack size,
  4580. * e.g. -DUSE_STACK_SIZE=16384 */
  4581. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4582. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4583. result = pthread_create(&thread_id, &attr, func, param);
  4584. pthread_attr_destroy(&attr);
  4585. return result;
  4586. }
  4587. /* Start a thread storing the thread context. */
  4588. static int
  4589. mg_start_thread_with_id(mg_thread_func_t func,
  4590. void *param,
  4591. pthread_t *threadidptr)
  4592. {
  4593. pthread_t thread_id;
  4594. pthread_attr_t attr;
  4595. int result;
  4596. (void)pthread_attr_init(&attr);
  4597. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4598. /* Compile-time option to control stack size,
  4599. * e.g. -DUSE_STACK_SIZE=16384 */
  4600. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4601. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4602. result = pthread_create(&thread_id, &attr, func, param);
  4603. pthread_attr_destroy(&attr);
  4604. if ((result == 0) && (threadidptr != NULL)) {
  4605. *threadidptr = thread_id;
  4606. }
  4607. return result;
  4608. }
  4609. /* Wait for a thread to finish. */
  4610. static int
  4611. mg_join_thread(pthread_t threadid)
  4612. {
  4613. int result;
  4614. result = pthread_join(threadid, NULL);
  4615. return result;
  4616. }
  4617. #ifndef NO_CGI
  4618. static pid_t
  4619. spawn_process(struct mg_connection *conn,
  4620. const char *prog,
  4621. char *envblk,
  4622. char *envp[],
  4623. int fdin[2],
  4624. int fdout[2],
  4625. int fderr[2],
  4626. const char *dir)
  4627. {
  4628. pid_t pid;
  4629. const char *interp;
  4630. (void)envblk;
  4631. if (conn == NULL) {
  4632. return 0;
  4633. }
  4634. if ((pid = fork()) == -1) {
  4635. /* Parent */
  4636. mg_send_http_error(conn,
  4637. 500,
  4638. "Error: Creating CGI process\nfork(): %s",
  4639. strerror(ERRNO));
  4640. } else if (pid == 0) {
  4641. /* Child */
  4642. if (chdir(dir) != 0) {
  4643. mg_cry_internal(
  4644. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4645. } else if (dup2(fdin[0], 0) == -1) {
  4646. mg_cry_internal(conn,
  4647. "%s: dup2(%d, 0): %s",
  4648. __func__,
  4649. fdin[0],
  4650. strerror(ERRNO));
  4651. } else if (dup2(fdout[1], 1) == -1) {
  4652. mg_cry_internal(conn,
  4653. "%s: dup2(%d, 1): %s",
  4654. __func__,
  4655. fdout[1],
  4656. strerror(ERRNO));
  4657. } else if (dup2(fderr[1], 2) == -1) {
  4658. mg_cry_internal(conn,
  4659. "%s: dup2(%d, 2): %s",
  4660. __func__,
  4661. fderr[1],
  4662. strerror(ERRNO));
  4663. } else {
  4664. /* Keep stderr and stdout in two different pipes.
  4665. * Stdout will be sent back to the client,
  4666. * stderr should go into a server error log. */
  4667. (void)close(fdin[0]);
  4668. (void)close(fdout[1]);
  4669. (void)close(fderr[1]);
  4670. /* Close write end fdin and read end fdout and fderr */
  4671. (void)close(fdin[1]);
  4672. (void)close(fdout[0]);
  4673. (void)close(fderr[0]);
  4674. /* After exec, all signal handlers are restored to their default
  4675. * values, with one exception of SIGCHLD. According to
  4676. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4677. * will leave unchanged after exec if it was set to be ignored.
  4678. * Restore it to default action. */
  4679. signal(SIGCHLD, SIG_DFL);
  4680. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4681. if (interp == NULL) {
  4682. (void)execle(prog, prog, NULL, envp);
  4683. mg_cry_internal(conn,
  4684. "%s: execle(%s): %s",
  4685. __func__,
  4686. prog,
  4687. strerror(ERRNO));
  4688. } else {
  4689. (void)execle(interp, interp, prog, NULL, envp);
  4690. mg_cry_internal(conn,
  4691. "%s: execle(%s %s): %s",
  4692. __func__,
  4693. interp,
  4694. prog,
  4695. strerror(ERRNO));
  4696. }
  4697. }
  4698. exit(EXIT_FAILURE);
  4699. }
  4700. return pid;
  4701. }
  4702. #endif /* !NO_CGI */
  4703. static int
  4704. set_non_blocking_mode(SOCKET sock)
  4705. {
  4706. int flags = fcntl(sock, F_GETFL, 0);
  4707. if (flags < 0) {
  4708. return -1;
  4709. }
  4710. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4711. return -1;
  4712. }
  4713. return 0;
  4714. }
  4715. static int
  4716. set_blocking_mode(SOCKET sock)
  4717. {
  4718. int flags = fcntl(sock, F_GETFL, 0);
  4719. if (flags < 0) {
  4720. return -1;
  4721. }
  4722. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4723. return -1;
  4724. }
  4725. return 0;
  4726. }
  4727. #endif /* _WIN32 / else */
  4728. /* End of initial operating system specific define block. */
  4729. /* Get a random number (independent of C rand function) */
  4730. static uint64_t
  4731. get_random(void)
  4732. {
  4733. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4734. static uint64_t lcg = 0; /* Linear congruential generator */
  4735. uint64_t now = mg_get_current_time_ns();
  4736. if (lfsr == 0) {
  4737. /* lfsr will be only 0 if has not been initialized,
  4738. * so this code is called only once. */
  4739. lfsr = mg_get_current_time_ns();
  4740. lcg = mg_get_current_time_ns();
  4741. } else {
  4742. /* Get the next step of both random number generators. */
  4743. lfsr = (lfsr >> 1)
  4744. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4745. << 63);
  4746. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4747. }
  4748. /* Combining two pseudo-random number generators and a high resolution
  4749. * part
  4750. * of the current server time will make it hard (impossible?) to guess
  4751. * the
  4752. * next number. */
  4753. return (lfsr ^ lcg ^ now);
  4754. }
  4755. static int
  4756. mg_poll(struct pollfd *pfd,
  4757. unsigned int n,
  4758. int milliseconds,
  4759. volatile int *stop_server)
  4760. {
  4761. /* Call poll, but only for a maximum time of a few seconds.
  4762. * This will allow to stop the server after some seconds, instead
  4763. * of having to wait for a long socket timeout. */
  4764. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4765. do {
  4766. int result;
  4767. if (*stop_server) {
  4768. /* Shut down signal */
  4769. return -2;
  4770. }
  4771. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4772. ms_now = milliseconds;
  4773. }
  4774. result = poll(pfd, n, ms_now);
  4775. if (result != 0) {
  4776. /* Poll returned either success (1) or error (-1).
  4777. * Forward both to the caller. */
  4778. return result;
  4779. }
  4780. /* Poll returned timeout (0). */
  4781. if (milliseconds > 0) {
  4782. milliseconds -= ms_now;
  4783. }
  4784. } while (milliseconds != 0);
  4785. /* timeout: return 0 */
  4786. return 0;
  4787. }
  4788. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4789. * descriptor.
  4790. * Return value:
  4791. * >=0 .. number of bytes successfully written
  4792. * -1 .. timeout
  4793. * -2 .. error
  4794. */
  4795. static int
  4796. push_inner(struct mg_context *ctx,
  4797. FILE *fp,
  4798. SOCKET sock,
  4799. SSL *ssl,
  4800. const char *buf,
  4801. int len,
  4802. double timeout)
  4803. {
  4804. uint64_t start = 0, now = 0, timeout_ns = 0;
  4805. int n, err;
  4806. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4807. #ifdef _WIN32
  4808. typedef int len_t;
  4809. #else
  4810. typedef size_t len_t;
  4811. #endif
  4812. if (timeout > 0) {
  4813. now = mg_get_current_time_ns();
  4814. start = now;
  4815. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4816. }
  4817. if (ctx == NULL) {
  4818. return -2;
  4819. }
  4820. #ifdef NO_SSL
  4821. if (ssl) {
  4822. return -2;
  4823. }
  4824. #endif
  4825. /* Try to read until it succeeds, fails, times out, or the server
  4826. * shuts down. */
  4827. for (;;) {
  4828. #ifndef NO_SSL
  4829. if (ssl != NULL) {
  4830. n = SSL_write(ssl, buf, len);
  4831. if (n <= 0) {
  4832. err = SSL_get_error(ssl, n);
  4833. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4834. err = ERRNO;
  4835. } else if ((err == SSL_ERROR_WANT_READ)
  4836. || (err == SSL_ERROR_WANT_WRITE)) {
  4837. n = 0;
  4838. } else {
  4839. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4840. return -2;
  4841. }
  4842. } else {
  4843. err = 0;
  4844. }
  4845. } else
  4846. #endif
  4847. if (fp != NULL) {
  4848. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4849. if (ferror(fp)) {
  4850. n = -1;
  4851. err = ERRNO;
  4852. } else {
  4853. err = 0;
  4854. }
  4855. } else {
  4856. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4857. err = (n < 0) ? ERRNO : 0;
  4858. #ifdef _WIN32
  4859. if (err == WSAEWOULDBLOCK) {
  4860. err = 0;
  4861. n = 0;
  4862. }
  4863. #else
  4864. if (err == EWOULDBLOCK) {
  4865. err = 0;
  4866. n = 0;
  4867. }
  4868. #endif
  4869. if (n < 0) {
  4870. /* shutdown of the socket at client side */
  4871. return -2;
  4872. }
  4873. }
  4874. if (ctx->stop_flag) {
  4875. return -2;
  4876. }
  4877. if ((n > 0) || ((n == 0) && (len == 0))) {
  4878. /* some data has been read, or no data was requested */
  4879. return n;
  4880. }
  4881. if (n < 0) {
  4882. /* socket error - check errno */
  4883. DEBUG_TRACE("send() failed, error %d", err);
  4884. /* TODO (mid): error handling depending on the error code.
  4885. * These codes are different between Windows and Linux.
  4886. * Currently there is no problem with failing send calls,
  4887. * if there is a reproducible situation, it should be
  4888. * investigated in detail.
  4889. */
  4890. return -2;
  4891. }
  4892. /* Only in case n=0 (timeout), repeat calling the write function */
  4893. /* If send failed, wait before retry */
  4894. if (fp != NULL) {
  4895. /* For files, just wait a fixed time,
  4896. * maybe an average disk seek time. */
  4897. mg_sleep(ms_wait > 10 ? 10 : ms_wait);
  4898. } else {
  4899. /* For sockets, wait for the socket using select */
  4900. fd_set wfds;
  4901. struct timeval tv;
  4902. int sret;
  4903. #if defined(__GNUC__) || defined(__MINGW32__)
  4904. /* GCC seems to have a flaw with it's own socket macros:
  4905. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  4906. */
  4907. #pragma GCC diagnostic push
  4908. #pragma GCC diagnostic ignored "-Wsign-conversion"
  4909. #endif
  4910. FD_ZERO(&wfds);
  4911. FD_SET(sock, &wfds);
  4912. tv.tv_sec = (time_t)(ms_wait / 1000);
  4913. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  4914. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  4915. #if defined(__GNUC__) || defined(__MINGW32__)
  4916. #pragma GCC diagnostic pop
  4917. #endif
  4918. if (sret > 0) {
  4919. /* We got ready to write. Don't check the timeout
  4920. * but directly go back to write again. */
  4921. continue;
  4922. }
  4923. }
  4924. if (timeout > 0) {
  4925. now = mg_get_current_time_ns();
  4926. if ((now - start) > timeout_ns) {
  4927. /* Timeout */
  4928. break;
  4929. }
  4930. }
  4931. }
  4932. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4933. used */
  4934. return -1;
  4935. }
  4936. static int64_t
  4937. push_all(struct mg_context *ctx,
  4938. FILE *fp,
  4939. SOCKET sock,
  4940. SSL *ssl,
  4941. const char *buf,
  4942. int64_t len)
  4943. {
  4944. double timeout = -1.0;
  4945. int64_t n, nwritten = 0;
  4946. if (ctx == NULL) {
  4947. return -1;
  4948. }
  4949. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  4950. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  4951. }
  4952. while ((len > 0) && (ctx->stop_flag == 0)) {
  4953. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4954. if (n < 0) {
  4955. if (nwritten == 0) {
  4956. nwritten = n; /* Propagate the error */
  4957. }
  4958. break;
  4959. } else if (n == 0) {
  4960. break; /* No more data to write */
  4961. } else {
  4962. nwritten += n;
  4963. len -= n;
  4964. }
  4965. }
  4966. return nwritten;
  4967. }
  4968. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4969. * Return value:
  4970. * >=0 .. number of bytes successfully read
  4971. * -1 .. timeout
  4972. * -2 .. error
  4973. */
  4974. static int
  4975. pull_inner(FILE *fp,
  4976. struct mg_connection *conn,
  4977. char *buf,
  4978. int len,
  4979. double timeout)
  4980. {
  4981. int nread, err = 0;
  4982. #ifdef _WIN32
  4983. typedef int len_t;
  4984. #else
  4985. typedef size_t len_t;
  4986. #endif
  4987. #ifndef NO_SSL
  4988. int ssl_pending;
  4989. #endif
  4990. /* We need an additional wait loop around this, because in some cases
  4991. * with TLSwe may get data from the socket but not from SSL_read.
  4992. * In this case we need to repeat at least once.
  4993. */
  4994. if (fp != NULL) {
  4995. #if !defined(_WIN32_WCE)
  4996. /* Use read() instead of fread(), because if we're reading from the
  4997. * CGI pipe, fread() may block until IO buffer is filled up. We
  4998. * cannot afford to block and must pass all read bytes immediately
  4999. * to the client. */
  5000. nread = (int)read(fileno(fp), buf, (size_t)len);
  5001. #else
  5002. /* WinCE does not support CGI pipes */
  5003. nread = (int)fread(buf, 1, (size_t)len, fp);
  5004. #endif
  5005. err = (nread < 0) ? ERRNO : 0;
  5006. if ((nread == 0) && (len > 0)) {
  5007. /* Should get data, but got EOL */
  5008. return -2;
  5009. }
  5010. #ifndef NO_SSL
  5011. } else if ((conn->ssl != NULL)
  5012. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5013. /* We already know there is no more data buffered in conn->buf
  5014. * but there is more available in the SSL layer. So don't poll
  5015. * conn->client.sock yet. */
  5016. if (ssl_pending > len) {
  5017. ssl_pending = len;
  5018. }
  5019. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5020. if (nread <= 0) {
  5021. err = SSL_get_error(conn->ssl, nread);
  5022. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5023. err = ERRNO;
  5024. } else if ((err == SSL_ERROR_WANT_READ)
  5025. || (err == SSL_ERROR_WANT_WRITE)) {
  5026. nread = 0;
  5027. } else {
  5028. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5029. return -1;
  5030. }
  5031. } else {
  5032. err = 0;
  5033. }
  5034. } else if (conn->ssl != NULL) {
  5035. struct pollfd pfd[1];
  5036. int pollres;
  5037. pfd[0].fd = conn->client.sock;
  5038. pfd[0].events = POLLIN;
  5039. pollres = mg_poll(pfd,
  5040. 1,
  5041. (int)(timeout * 1000.0),
  5042. &(conn->phys_ctx->stop_flag));
  5043. if (conn->phys_ctx->stop_flag) {
  5044. return -2;
  5045. }
  5046. if (pollres > 0) {
  5047. nread = SSL_read(conn->ssl, buf, len);
  5048. if (nread <= 0) {
  5049. err = SSL_get_error(conn->ssl, nread);
  5050. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5051. err = ERRNO;
  5052. } else if ((err == SSL_ERROR_WANT_READ)
  5053. || (err == SSL_ERROR_WANT_WRITE)) {
  5054. nread = 0;
  5055. } else {
  5056. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5057. return -2;
  5058. }
  5059. } else {
  5060. err = 0;
  5061. }
  5062. } else if (pollres < 0) {
  5063. /* Error */
  5064. return -2;
  5065. } else {
  5066. /* pollres = 0 means timeout */
  5067. nread = 0;
  5068. }
  5069. #endif
  5070. } else {
  5071. struct pollfd pfd[1];
  5072. int pollres;
  5073. pfd[0].fd = conn->client.sock;
  5074. pfd[0].events = POLLIN;
  5075. pollres = mg_poll(pfd,
  5076. 1,
  5077. (int)(timeout * 1000.0),
  5078. &(conn->phys_ctx->stop_flag));
  5079. if (conn->phys_ctx->stop_flag) {
  5080. return -2;
  5081. }
  5082. if (pollres > 0) {
  5083. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5084. err = (nread < 0) ? ERRNO : 0;
  5085. if (nread <= 0) {
  5086. /* shutdown of the socket at client side */
  5087. return -2;
  5088. }
  5089. } else if (pollres < 0) {
  5090. /* error callint poll */
  5091. return -2;
  5092. } else {
  5093. /* pollres = 0 means timeout */
  5094. nread = 0;
  5095. }
  5096. }
  5097. if (conn->phys_ctx->stop_flag) {
  5098. return -2;
  5099. }
  5100. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5101. /* some data has been read, or no data was requested */
  5102. return nread;
  5103. }
  5104. if (nread < 0) {
  5105. /* socket error - check errno */
  5106. #ifdef _WIN32
  5107. if (err == WSAEWOULDBLOCK) {
  5108. /* TODO (low): check if this is still required */
  5109. /* standard case if called from close_socket_gracefully */
  5110. return -2;
  5111. } else if (err == WSAETIMEDOUT) {
  5112. /* TODO (low): check if this is still required */
  5113. /* timeout is handled by the while loop */
  5114. return 0;
  5115. } else if (err == WSAECONNABORTED) {
  5116. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5117. return -2;
  5118. } else {
  5119. DEBUG_TRACE("recv() failed, error %d", err);
  5120. return -2;
  5121. }
  5122. #else
  5123. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5124. * if the timeout is reached and if the socket was set to non-
  5125. * blocking in close_socket_gracefully, so we can not distinguish
  5126. * here. We have to wait for the timeout in both cases for now.
  5127. */
  5128. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5129. /* TODO (low): check if this is still required */
  5130. /* EAGAIN/EWOULDBLOCK:
  5131. * standard case if called from close_socket_gracefully
  5132. * => should return -1 */
  5133. /* or timeout occurred
  5134. * => the code must stay in the while loop */
  5135. /* EINTR can be generated on a socket with a timeout set even
  5136. * when SA_RESTART is effective for all relevant signals
  5137. * (see signal(7)).
  5138. * => stay in the while loop */
  5139. } else {
  5140. DEBUG_TRACE("recv() failed, error %d", err);
  5141. return -2;
  5142. }
  5143. #endif
  5144. }
  5145. /* Timeout occurred, but no data available. */
  5146. return -1;
  5147. }
  5148. static int
  5149. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5150. {
  5151. int n, nread = 0;
  5152. double timeout = -1.0;
  5153. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5154. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5155. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5156. }
  5157. if (timeout >= 0.0) {
  5158. start_time = mg_get_current_time_ns();
  5159. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5160. }
  5161. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5162. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5163. if (n == -2) {
  5164. if (nread == 0) {
  5165. nread = -1; /* Propagate the error */
  5166. }
  5167. break;
  5168. } else if (n == -1) {
  5169. /* timeout */
  5170. if (timeout >= 0.0) {
  5171. now = mg_get_current_time_ns();
  5172. if ((now - start_time) <= timeout_ns) {
  5173. continue;
  5174. }
  5175. }
  5176. break;
  5177. } else if (n == 0) {
  5178. break; /* No more data to read */
  5179. } else {
  5180. conn->consumed_content += n;
  5181. nread += n;
  5182. len -= n;
  5183. }
  5184. }
  5185. return nread;
  5186. }
  5187. static void
  5188. discard_unread_request_data(struct mg_connection *conn)
  5189. {
  5190. char buf[MG_BUF_LEN];
  5191. size_t to_read;
  5192. int nread;
  5193. if (conn == NULL) {
  5194. return;
  5195. }
  5196. to_read = sizeof(buf);
  5197. if (conn->is_chunked) {
  5198. /* Chunked encoding: 3=chunk read completely
  5199. * completely */
  5200. while (conn->is_chunked != 3) {
  5201. nread = mg_read(conn, buf, to_read);
  5202. if (nread <= 0) {
  5203. break;
  5204. }
  5205. }
  5206. } else {
  5207. /* Not chunked: content length is known */
  5208. while (conn->consumed_content < conn->content_len) {
  5209. if (to_read
  5210. > (size_t)(conn->content_len - conn->consumed_content)) {
  5211. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5212. }
  5213. nread = mg_read(conn, buf, to_read);
  5214. if (nread <= 0) {
  5215. break;
  5216. }
  5217. }
  5218. }
  5219. }
  5220. static int
  5221. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5222. {
  5223. int64_t n, buffered_len, nread;
  5224. int64_t len64 =
  5225. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5226. * int, we may not read more
  5227. * bytes */
  5228. const char *body;
  5229. if (conn == NULL) {
  5230. return 0;
  5231. }
  5232. /* If Content-Length is not set for a request with body data
  5233. * (e.g., a PUT or POST request), we do not know in advance
  5234. * how much data should be read. */
  5235. if (conn->consumed_content == 0) {
  5236. if (conn->is_chunked == 1) {
  5237. conn->content_len = len64;
  5238. conn->is_chunked = 2;
  5239. } else if (conn->content_len == -1) {
  5240. /* The body data is completed when the connection
  5241. * is closed. */
  5242. conn->content_len = INT64_MAX;
  5243. conn->must_close = 1;
  5244. }
  5245. }
  5246. nread = 0;
  5247. if (conn->consumed_content < conn->content_len) {
  5248. /* Adjust number of bytes to read. */
  5249. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5250. if (left_to_read < len64) {
  5251. /* Do not read more than the total content length of the
  5252. * request.
  5253. */
  5254. len64 = left_to_read;
  5255. }
  5256. /* Return buffered data */
  5257. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5258. - conn->consumed_content;
  5259. if (buffered_len > 0) {
  5260. if (len64 < buffered_len) {
  5261. buffered_len = len64;
  5262. }
  5263. body = conn->buf + conn->request_len + conn->consumed_content;
  5264. memcpy(buf, body, (size_t)buffered_len);
  5265. len64 -= buffered_len;
  5266. conn->consumed_content += buffered_len;
  5267. nread += buffered_len;
  5268. buf = (char *)buf + buffered_len;
  5269. }
  5270. /* We have returned all buffered data. Read new data from the remote
  5271. * socket.
  5272. */
  5273. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5274. nread += n;
  5275. } else {
  5276. nread = ((nread > 0) ? nread : n);
  5277. }
  5278. }
  5279. return (int)nread;
  5280. }
  5281. static char
  5282. mg_getc(struct mg_connection *conn)
  5283. {
  5284. char c;
  5285. if (conn == NULL) {
  5286. return 0;
  5287. }
  5288. if (mg_read_inner(conn, &c, 1) <= 0) {
  5289. return (char)0;
  5290. }
  5291. return c;
  5292. }
  5293. int
  5294. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5295. {
  5296. if (len > INT_MAX) {
  5297. len = INT_MAX;
  5298. }
  5299. if (conn == NULL) {
  5300. return 0;
  5301. }
  5302. if (conn->is_chunked) {
  5303. size_t all_read = 0;
  5304. while (len > 0) {
  5305. if (conn->is_chunked == 3) {
  5306. /* No more data left to read */
  5307. return 0;
  5308. }
  5309. if (conn->chunk_remainder) {
  5310. /* copy from the remainder of the last received chunk */
  5311. long read_ret;
  5312. size_t read_now =
  5313. ((conn->chunk_remainder > len) ? (len)
  5314. : (conn->chunk_remainder));
  5315. conn->content_len += (int)read_now;
  5316. read_ret =
  5317. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5318. if (read_ret < 1) {
  5319. /* read error */
  5320. return -1;
  5321. }
  5322. all_read += (size_t)read_ret;
  5323. conn->chunk_remainder -= (size_t)read_ret;
  5324. len -= (size_t)read_ret;
  5325. if (conn->chunk_remainder == 0) {
  5326. /* Add data bytes in the current chunk have been read,
  5327. * so we are expecting \r\n now. */
  5328. char x1, x2;
  5329. conn->content_len += 2;
  5330. x1 = mg_getc(conn);
  5331. x2 = mg_getc(conn);
  5332. if ((x1 != '\r') || (x2 != '\n')) {
  5333. /* Protocol violation */
  5334. return -1;
  5335. }
  5336. }
  5337. } else {
  5338. /* fetch a new chunk */
  5339. int i = 0;
  5340. char lenbuf[64];
  5341. char *end = 0;
  5342. unsigned long chunkSize = 0;
  5343. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5344. conn->content_len++;
  5345. lenbuf[i] = mg_getc(conn);
  5346. if ((i > 0) && (lenbuf[i] == '\r')
  5347. && (lenbuf[i - 1] != '\r')) {
  5348. continue;
  5349. }
  5350. if ((i > 1) && (lenbuf[i] == '\n')
  5351. && (lenbuf[i - 1] == '\r')) {
  5352. lenbuf[i + 1] = 0;
  5353. chunkSize = strtoul(lenbuf, &end, 16);
  5354. if (chunkSize == 0) {
  5355. /* regular end of content */
  5356. conn->is_chunked = 3;
  5357. }
  5358. break;
  5359. }
  5360. if (!isxdigit(lenbuf[i])) {
  5361. /* illegal character for chunk length */
  5362. return -1;
  5363. }
  5364. }
  5365. if ((end == NULL) || (*end != '\r')) {
  5366. /* chunksize not set correctly */
  5367. return -1;
  5368. }
  5369. if (chunkSize == 0) {
  5370. break;
  5371. }
  5372. conn->chunk_remainder = chunkSize;
  5373. }
  5374. }
  5375. return (int)all_read;
  5376. }
  5377. return mg_read_inner(conn, buf, len);
  5378. }
  5379. int
  5380. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5381. {
  5382. time_t now;
  5383. int64_t n, total, allowed;
  5384. if (conn == NULL) {
  5385. return 0;
  5386. }
  5387. if (conn->throttle > 0) {
  5388. if ((now = time(NULL)) != conn->last_throttle_time) {
  5389. conn->last_throttle_time = now;
  5390. conn->last_throttle_bytes = 0;
  5391. }
  5392. allowed = conn->throttle - conn->last_throttle_bytes;
  5393. if (allowed > (int64_t)len) {
  5394. allowed = (int64_t)len;
  5395. }
  5396. if ((total = push_all(conn->phys_ctx,
  5397. NULL,
  5398. conn->client.sock,
  5399. conn->ssl,
  5400. (const char *)buf,
  5401. (int64_t)allowed)) == allowed) {
  5402. buf = (const char *)buf + total;
  5403. conn->last_throttle_bytes += total;
  5404. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5405. allowed = (conn->throttle > ((int64_t)len - total))
  5406. ? (int64_t)len - total
  5407. : conn->throttle;
  5408. if ((n = push_all(conn->phys_ctx,
  5409. NULL,
  5410. conn->client.sock,
  5411. conn->ssl,
  5412. (const char *)buf,
  5413. (int64_t)allowed)) != allowed) {
  5414. break;
  5415. }
  5416. sleep(1);
  5417. conn->last_throttle_bytes = allowed;
  5418. conn->last_throttle_time = time(NULL);
  5419. buf = (const char *)buf + n;
  5420. total += n;
  5421. }
  5422. }
  5423. } else {
  5424. total = push_all(conn->phys_ctx,
  5425. NULL,
  5426. conn->client.sock,
  5427. conn->ssl,
  5428. (const char *)buf,
  5429. (int64_t)len);
  5430. }
  5431. if (total > 0) {
  5432. conn->num_bytes_sent += total;
  5433. }
  5434. return (int)total;
  5435. }
  5436. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5437. int
  5438. mg_send_chunk(struct mg_connection *conn,
  5439. const char *chunk,
  5440. unsigned int chunk_len)
  5441. {
  5442. char lenbuf[16];
  5443. size_t lenbuf_len;
  5444. int ret;
  5445. int t;
  5446. /* First store the length information in a text buffer. */
  5447. sprintf(lenbuf, "%x\r\n", chunk_len);
  5448. lenbuf_len = strlen(lenbuf);
  5449. /* Then send length information, chunk and terminating \r\n. */
  5450. ret = mg_write(conn, lenbuf, lenbuf_len);
  5451. if (ret != (int)lenbuf_len) {
  5452. return -1;
  5453. }
  5454. t = ret;
  5455. ret = mg_write(conn, chunk, chunk_len);
  5456. if (ret != (int)chunk_len) {
  5457. return -1;
  5458. }
  5459. t += ret;
  5460. ret = mg_write(conn, "\r\n", 2);
  5461. if (ret != 2) {
  5462. return -1;
  5463. }
  5464. t += ret;
  5465. return t;
  5466. }
  5467. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5468. static int
  5469. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5470. {
  5471. va_list ap_copy;
  5472. size_t size = MG_BUF_LEN / 4;
  5473. int len = -1;
  5474. *buf = NULL;
  5475. while (len < 0) {
  5476. if (*buf) {
  5477. mg_free(*buf);
  5478. }
  5479. size *= 4;
  5480. *buf = (char *)mg_malloc(size);
  5481. if (!*buf) {
  5482. break;
  5483. }
  5484. va_copy(ap_copy, ap);
  5485. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5486. va_end(ap_copy);
  5487. (*buf)[size - 1] = 0;
  5488. }
  5489. return len;
  5490. }
  5491. /* Print message to buffer. If buffer is large enough to hold the message,
  5492. * return buffer. If buffer is to small, allocate large enough buffer on
  5493. * heap,
  5494. * and return allocated buffer. */
  5495. static int
  5496. alloc_vprintf(char **out_buf,
  5497. char *prealloc_buf,
  5498. size_t prealloc_size,
  5499. const char *fmt,
  5500. va_list ap)
  5501. {
  5502. va_list ap_copy;
  5503. int len;
  5504. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5505. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5506. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5507. * Therefore, we make two passes: on first pass, get required message
  5508. * length.
  5509. * On second pass, actually print the message. */
  5510. va_copy(ap_copy, ap);
  5511. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5512. va_end(ap_copy);
  5513. if (len < 0) {
  5514. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5515. * Switch to alternative code path that uses incremental
  5516. * allocations.
  5517. */
  5518. va_copy(ap_copy, ap);
  5519. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5520. va_end(ap_copy);
  5521. } else if ((size_t)(len) >= prealloc_size) {
  5522. /* The pre-allocated buffer not large enough. */
  5523. /* Allocate a new buffer. */
  5524. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5525. if (!*out_buf) {
  5526. /* Allocation failed. Return -1 as "out of memory" error. */
  5527. return -1;
  5528. }
  5529. /* Buffer allocation successful. Store the string there. */
  5530. va_copy(ap_copy, ap);
  5531. IGNORE_UNUSED_RESULT(
  5532. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5533. va_end(ap_copy);
  5534. } else {
  5535. /* The pre-allocated buffer is large enough.
  5536. * Use it to store the string and return the address. */
  5537. va_copy(ap_copy, ap);
  5538. IGNORE_UNUSED_RESULT(
  5539. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5540. va_end(ap_copy);
  5541. *out_buf = prealloc_buf;
  5542. }
  5543. return len;
  5544. }
  5545. static int
  5546. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5547. {
  5548. char mem[MG_BUF_LEN];
  5549. char *buf = NULL;
  5550. int len;
  5551. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5552. len = mg_write(conn, buf, (size_t)len);
  5553. }
  5554. if ((buf != mem) && (buf != NULL)) {
  5555. mg_free(buf);
  5556. }
  5557. return len;
  5558. }
  5559. int
  5560. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5561. {
  5562. va_list ap;
  5563. int result;
  5564. va_start(ap, fmt);
  5565. result = mg_vprintf(conn, fmt, ap);
  5566. va_end(ap);
  5567. return result;
  5568. }
  5569. int
  5570. mg_url_decode(const char *src,
  5571. int src_len,
  5572. char *dst,
  5573. int dst_len,
  5574. int is_form_url_encoded)
  5575. {
  5576. int i, j, a, b;
  5577. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5578. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5579. if ((i < src_len - 2) && (src[i] == '%')
  5580. && isxdigit(*(const unsigned char *)(src + i + 1))
  5581. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5582. a = tolower(*(const unsigned char *)(src + i + 1));
  5583. b = tolower(*(const unsigned char *)(src + i + 2));
  5584. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5585. i += 2;
  5586. } else if (is_form_url_encoded && (src[i] == '+')) {
  5587. dst[j] = ' ';
  5588. } else {
  5589. dst[j] = src[i];
  5590. }
  5591. }
  5592. dst[j] = '\0'; /* Null-terminate the destination */
  5593. return (i >= src_len) ? j : -1;
  5594. }
  5595. int
  5596. mg_get_var(const char *data,
  5597. size_t data_len,
  5598. const char *name,
  5599. char *dst,
  5600. size_t dst_len)
  5601. {
  5602. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5603. }
  5604. int
  5605. mg_get_var2(const char *data,
  5606. size_t data_len,
  5607. const char *name,
  5608. char *dst,
  5609. size_t dst_len,
  5610. size_t occurrence)
  5611. {
  5612. const char *p, *e, *s;
  5613. size_t name_len;
  5614. int len;
  5615. if ((dst == NULL) || (dst_len == 0)) {
  5616. len = -2;
  5617. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5618. len = -1;
  5619. dst[0] = '\0';
  5620. } else {
  5621. name_len = strlen(name);
  5622. e = data + data_len;
  5623. len = -1;
  5624. dst[0] = '\0';
  5625. /* data is "var1=val1&var2=val2...". Find variable first */
  5626. for (p = data; p + name_len < e; p++) {
  5627. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5628. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5629. /* Point p to variable value */
  5630. p += name_len + 1;
  5631. /* Point s to the end of the value */
  5632. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5633. if (s == NULL) {
  5634. s = e;
  5635. }
  5636. DEBUG_ASSERT(s >= p);
  5637. if (s < p) {
  5638. return -3;
  5639. }
  5640. /* Decode variable into destination buffer */
  5641. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5642. /* Redirect error code from -1 to -2 (destination buffer too
  5643. * small). */
  5644. if (len == -1) {
  5645. len = -2;
  5646. }
  5647. break;
  5648. }
  5649. }
  5650. }
  5651. return len;
  5652. }
  5653. /* HCP24: some changes to compare hole var_name */
  5654. int
  5655. mg_get_cookie(const char *cookie_header,
  5656. const char *var_name,
  5657. char *dst,
  5658. size_t dst_size)
  5659. {
  5660. const char *s, *p, *end;
  5661. int name_len, len = -1;
  5662. if ((dst == NULL) || (dst_size == 0)) {
  5663. return -2;
  5664. }
  5665. dst[0] = '\0';
  5666. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5667. return -1;
  5668. }
  5669. name_len = (int)strlen(var_name);
  5670. end = s + strlen(s);
  5671. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5672. if (s[name_len] == '=') {
  5673. /* HCP24: now check is it a substring or a full cookie name */
  5674. if ((s == cookie_header) || (s[-1] == ' ')) {
  5675. s += name_len + 1;
  5676. if ((p = strchr(s, ' ')) == NULL) {
  5677. p = end;
  5678. }
  5679. if (p[-1] == ';') {
  5680. p--;
  5681. }
  5682. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5683. s++;
  5684. p--;
  5685. }
  5686. if ((size_t)(p - s) < dst_size) {
  5687. len = (int)(p - s);
  5688. mg_strlcpy(dst, s, (size_t)len + 1);
  5689. } else {
  5690. len = -3;
  5691. }
  5692. break;
  5693. }
  5694. }
  5695. }
  5696. return len;
  5697. }
  5698. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5699. static void
  5700. base64_encode(const unsigned char *src, int src_len, char *dst)
  5701. {
  5702. static const char *b64 =
  5703. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5704. int i, j, a, b, c;
  5705. for (i = j = 0; i < src_len; i += 3) {
  5706. a = src[i];
  5707. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5708. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5709. dst[j++] = b64[a >> 2];
  5710. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5711. if (i + 1 < src_len) {
  5712. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5713. }
  5714. if (i + 2 < src_len) {
  5715. dst[j++] = b64[c & 63];
  5716. }
  5717. }
  5718. while (j % 4 != 0) {
  5719. dst[j++] = '=';
  5720. }
  5721. dst[j++] = '\0';
  5722. }
  5723. #endif
  5724. #if defined(USE_LUA)
  5725. static unsigned char
  5726. b64reverse(char letter)
  5727. {
  5728. if ((letter >= 'A') && (letter <= 'Z')) {
  5729. return letter - 'A';
  5730. }
  5731. if ((letter >= 'a') && (letter <= 'z')) {
  5732. return letter - 'a' + 26;
  5733. }
  5734. if ((letter >= '0') && (letter <= '9')) {
  5735. return letter - '0' + 52;
  5736. }
  5737. if (letter == '+') {
  5738. return 62;
  5739. }
  5740. if (letter == '/') {
  5741. return 63;
  5742. }
  5743. if (letter == '=') {
  5744. return 255; /* normal end */
  5745. }
  5746. return 254; /* error */
  5747. }
  5748. static int
  5749. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5750. {
  5751. int i;
  5752. unsigned char a, b, c, d;
  5753. *dst_len = 0;
  5754. for (i = 0; i < src_len; i += 4) {
  5755. a = b64reverse(src[i]);
  5756. if (a >= 254) {
  5757. return i;
  5758. }
  5759. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5760. if (b >= 254) {
  5761. return i + 1;
  5762. }
  5763. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5764. if (c == 254) {
  5765. return i + 2;
  5766. }
  5767. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5768. if (d == 254) {
  5769. return i + 3;
  5770. }
  5771. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5772. if (c != 255) {
  5773. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5774. if (d != 255) {
  5775. dst[(*dst_len)++] = (c << 6) + d;
  5776. }
  5777. }
  5778. }
  5779. return -1;
  5780. }
  5781. #endif
  5782. static int
  5783. is_put_or_delete_method(const struct mg_connection *conn)
  5784. {
  5785. if (conn) {
  5786. const char *s = conn->request_info.request_method;
  5787. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5788. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5789. }
  5790. return 0;
  5791. }
  5792. #if !defined(NO_FILES)
  5793. static int
  5794. extention_matches_script(
  5795. struct mg_connection *conn, /* in: request (must be valid) */
  5796. const char *filename /* in: filename (must be valid) */
  5797. )
  5798. {
  5799. #if !defined(NO_CGI)
  5800. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  5801. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  5802. filename) > 0) {
  5803. return 1;
  5804. }
  5805. #endif
  5806. #if defined(USE_LUA)
  5807. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  5808. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5809. filename) > 0) {
  5810. return 1;
  5811. }
  5812. #endif
  5813. #if defined(USE_DUKTAPE)
  5814. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5815. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5816. filename) > 0) {
  5817. return 1;
  5818. }
  5819. #endif
  5820. /* filename and conn could be unused, if all preocessor conditions
  5821. * are false (no script language supported). */
  5822. (void)filename;
  5823. (void)conn;
  5824. return 0;
  5825. }
  5826. /* For given directory path, substitute it to valid index file.
  5827. * Return 1 if index file has been found, 0 if not found.
  5828. * If the file is found, it's stats is returned in stp. */
  5829. static int
  5830. substitute_index_file(struct mg_connection *conn,
  5831. char *path,
  5832. size_t path_len,
  5833. struct mg_file_stat *filestat)
  5834. {
  5835. const char *list = conn->dom_ctx->config[INDEX_FILES];
  5836. struct vec filename_vec;
  5837. size_t n = strlen(path);
  5838. int found = 0;
  5839. /* The 'path' given to us points to the directory. Remove all trailing
  5840. * directory separator characters from the end of the path, and
  5841. * then append single directory separator character. */
  5842. while ((n > 0) && (path[n - 1] == '/')) {
  5843. n--;
  5844. }
  5845. path[n] = '/';
  5846. /* Traverse index files list. For each entry, append it to the given
  5847. * path and see if the file exists. If it exists, break the loop */
  5848. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5849. /* Ignore too long entries that may overflow path buffer */
  5850. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  5851. continue;
  5852. }
  5853. /* Prepare full path to the index file */
  5854. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5855. /* Does it exist? */
  5856. if (mg_stat(conn, path, filestat)) {
  5857. /* Yes it does, break the loop */
  5858. found = 1;
  5859. break;
  5860. }
  5861. }
  5862. /* If no index file exists, restore directory path */
  5863. if (!found) {
  5864. path[n] = '\0';
  5865. }
  5866. return found;
  5867. }
  5868. #endif
  5869. static void
  5870. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  5871. char *filename, /* out: filename */
  5872. size_t filename_buf_len, /* in: size of filename buffer */
  5873. struct mg_file_stat *filestat, /* out: file status structure */
  5874. int *is_found, /* out: file found (directly) */
  5875. int *is_script_resource, /* out: handled by a script? */
  5876. int *is_websocket_request, /* out: websocket connetion? */
  5877. int *is_put_or_delete_request /* out: put/delete a file? */
  5878. )
  5879. {
  5880. char const *accept_encoding;
  5881. #if !defined(NO_FILES)
  5882. const char *uri = conn->request_info.local_uri;
  5883. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  5884. const char *rewrite;
  5885. struct vec a, b;
  5886. int match_len;
  5887. char gz_path[PATH_MAX];
  5888. int truncated;
  5889. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5890. char *tmp_str;
  5891. size_t tmp_str_len, sep_pos;
  5892. int allow_substitute_script_subresources;
  5893. #endif
  5894. #else
  5895. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5896. #endif
  5897. /* Step 1: Set all initially unknown outputs to zero */
  5898. memset(filestat, 0, sizeof(*filestat));
  5899. *filename = 0;
  5900. *is_found = 0;
  5901. *is_script_resource = 0;
  5902. /* Step 2: Check if the request attempts to modify the file system */
  5903. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5904. /* Step 3: Check if it is a websocket request, and modify the document
  5905. * root if required */
  5906. #if defined(USE_WEBSOCKET)
  5907. *is_websocket_request = is_websocket_protocol(conn);
  5908. #if !defined(NO_FILES)
  5909. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  5910. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  5911. }
  5912. #endif /* !NO_FILES */
  5913. #else /* USE_WEBSOCKET */
  5914. *is_websocket_request = 0;
  5915. #endif /* USE_WEBSOCKET */
  5916. /* Step 4: Check if gzip encoded response is allowed */
  5917. conn->accept_gzip = 0;
  5918. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5919. if (strstr(accept_encoding, "gzip") != NULL) {
  5920. conn->accept_gzip = 1;
  5921. }
  5922. }
  5923. #if !defined(NO_FILES)
  5924. /* Step 5: If there is no root directory, don't look for files. */
  5925. /* Note that root == NULL is a regular use case here. This occurs,
  5926. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5927. * config is not required. */
  5928. if (root == NULL) {
  5929. /* all file related outputs have already been set to 0, just return
  5930. */
  5931. return;
  5932. }
  5933. /* Step 6: Determine the local file path from the root path and the
  5934. * request uri. */
  5935. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5936. * part of the path one byte on the right. */
  5937. mg_snprintf(
  5938. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5939. if (truncated) {
  5940. goto interpret_cleanup;
  5941. }
  5942. /* Step 7: URI rewriting */
  5943. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  5944. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5945. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5946. mg_snprintf(conn,
  5947. &truncated,
  5948. filename,
  5949. filename_buf_len - 1,
  5950. "%.*s%s",
  5951. (int)b.len,
  5952. b.ptr,
  5953. uri + match_len);
  5954. break;
  5955. }
  5956. }
  5957. if (truncated) {
  5958. goto interpret_cleanup;
  5959. }
  5960. /* Step 8: Check if the file exists at the server */
  5961. /* Local file path and name, corresponding to requested URI
  5962. * is now stored in "filename" variable. */
  5963. if (mg_stat(conn, filename, filestat)) {
  5964. int uri_len = (int)strlen(uri);
  5965. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  5966. /* 8.1: File exists. */
  5967. *is_found = 1;
  5968. /* 8.2: Check if it is a script type. */
  5969. if (extention_matches_script(conn, filename)) {
  5970. /* The request addresses a CGI resource, Lua script or
  5971. * server-side javascript.
  5972. * The URI corresponds to the script itself (like
  5973. * /path/script.cgi), and there is no additional resource
  5974. * path (like /path/script.cgi/something).
  5975. * Requests that modify (replace or delete) a resource, like
  5976. * PUT and DELETE requests, should replace/delete the script
  5977. * file.
  5978. * Requests that read or write from/to a resource, like GET and
  5979. * POST requests, should call the script and return the
  5980. * generated response. */
  5981. *is_script_resource = (!*is_put_or_delete_request);
  5982. }
  5983. /* 8.3: If the request target is a directory, there could be
  5984. * a substitute file (index.html, index.cgi, ...). */
  5985. if (filestat->is_directory && is_uri_end_slash) {
  5986. /* Use a local copy here, since substitute_index_file will
  5987. * change the content of the file status */
  5988. struct mg_file_stat tmp_filestat;
  5989. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5990. if (substitute_index_file(
  5991. conn, filename, filename_buf_len, &tmp_filestat)) {
  5992. /* Substitute file found. Copy stat to the output, then
  5993. * check if the file is a script file */
  5994. *filestat = tmp_filestat;
  5995. if (extention_matches_script(conn, filename)) {
  5996. /* Substitute file is a script file */
  5997. *is_script_resource = 1;
  5998. } else {
  5999. /* Substitute file is a regular file */
  6000. *is_script_resource = 0;
  6001. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6002. }
  6003. }
  6004. /* If there is no substitute file, the server could return
  6005. * a directory listing in a later step */
  6006. }
  6007. return;
  6008. }
  6009. /* Step 9: Check for zipped files: */
  6010. /* If we can't find the actual file, look for the file
  6011. * with the same name but a .gz extension. If we find it,
  6012. * use that and set the gzipped flag in the file struct
  6013. * to indicate that the response need to have the content-
  6014. * encoding: gzip header.
  6015. * We can only do this if the browser declares support. */
  6016. if (conn->accept_gzip) {
  6017. mg_snprintf(
  6018. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6019. if (truncated) {
  6020. goto interpret_cleanup;
  6021. }
  6022. if (mg_stat(conn, gz_path, filestat)) {
  6023. if (filestat) {
  6024. filestat->is_gzipped = 1;
  6025. *is_found = 1;
  6026. }
  6027. /* Currently gz files can not be scripts. */
  6028. return;
  6029. }
  6030. }
  6031. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6032. /* Step 10: Script resources may handle sub-resources */
  6033. /* Support PATH_INFO for CGI scripts. */
  6034. tmp_str_len = strlen(filename);
  6035. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6036. if (!tmp_str) {
  6037. /* Out of memory */
  6038. goto interpret_cleanup;
  6039. }
  6040. memcpy(tmp_str, filename, tmp_str_len + 1);
  6041. /* Check config, if index scripts may have sub-resources */
  6042. allow_substitute_script_subresources =
  6043. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6044. "yes");
  6045. sep_pos = tmp_str_len;
  6046. while (sep_pos > 0) {
  6047. sep_pos--;
  6048. if (tmp_str[sep_pos] == '/') {
  6049. int is_script = 0, does_exist = 0;
  6050. tmp_str[sep_pos] = 0;
  6051. if (tmp_str[0]) {
  6052. is_script = extention_matches_script(conn, tmp_str);
  6053. does_exist = mg_stat(conn, tmp_str, filestat);
  6054. }
  6055. if (does_exist && is_script) {
  6056. filename[sep_pos] = 0;
  6057. memmove(filename + sep_pos + 2,
  6058. filename + sep_pos + 1,
  6059. strlen(filename + sep_pos + 1) + 1);
  6060. conn->path_info = filename + sep_pos + 1;
  6061. filename[sep_pos + 1] = '/';
  6062. *is_script_resource = 1;
  6063. *is_found = 1;
  6064. break;
  6065. }
  6066. if (allow_substitute_script_subresources) {
  6067. if (substitute_index_file(
  6068. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6069. /* some intermediate directory has an index file */
  6070. if (extention_matches_script(conn, tmp_str)) {
  6071. char *tmp_str2;
  6072. DEBUG_TRACE("Substitute script %s serving path %s",
  6073. tmp_str,
  6074. filename);
  6075. /* this index file is a script */
  6076. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6077. conn->phys_ctx);
  6078. mg_snprintf(conn,
  6079. &truncated,
  6080. filename,
  6081. filename_buf_len,
  6082. "%s//%s",
  6083. tmp_str,
  6084. tmp_str2);
  6085. mg_free(tmp_str2);
  6086. if (truncated) {
  6087. mg_free(tmp_str);
  6088. goto interpret_cleanup;
  6089. }
  6090. sep_pos = strlen(tmp_str);
  6091. filename[sep_pos] = 0;
  6092. conn->path_info = filename + sep_pos + 1;
  6093. *is_script_resource = 1;
  6094. *is_found = 1;
  6095. break;
  6096. } else {
  6097. DEBUG_TRACE("Substitute file %s serving path %s",
  6098. tmp_str,
  6099. filename);
  6100. /* non-script files will not have sub-resources */
  6101. filename[sep_pos] = 0;
  6102. conn->path_info = 0;
  6103. *is_script_resource = 0;
  6104. *is_found = 0;
  6105. break;
  6106. }
  6107. }
  6108. }
  6109. tmp_str[sep_pos] = '/';
  6110. }
  6111. }
  6112. mg_free(tmp_str);
  6113. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6114. #endif /* !defined(NO_FILES) */
  6115. return;
  6116. #if !defined(NO_FILES)
  6117. /* Reset all outputs */
  6118. interpret_cleanup:
  6119. memset(filestat, 0, sizeof(*filestat));
  6120. *filename = 0;
  6121. *is_found = 0;
  6122. *is_script_resource = 0;
  6123. *is_websocket_request = 0;
  6124. *is_put_or_delete_request = 0;
  6125. #endif /* !defined(NO_FILES) */
  6126. }
  6127. /* Check whether full request is buffered. Return:
  6128. * -1 if request or response is malformed
  6129. * 0 if request or response is not yet fully buffered
  6130. * >0 actual request length, including last \r\n\r\n */
  6131. static int
  6132. get_http_header_len(const char *buf, int buflen)
  6133. {
  6134. int i;
  6135. for (i = 0; i < buflen; i++) {
  6136. /* Do an unsigned comparison in some conditions below */
  6137. const unsigned char c = ((const unsigned char *)buf)[i];
  6138. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6139. && !isprint(c)) {
  6140. /* abort scan as soon as one malformed character is found */
  6141. return -1;
  6142. }
  6143. if (i < buflen - 1) {
  6144. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6145. /* Two newline, no carriage return - not standard compliant,
  6146. * but
  6147. * it
  6148. * should be accepted */
  6149. return i + 2;
  6150. }
  6151. }
  6152. if (i < buflen - 3) {
  6153. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6154. && (buf[i + 3] == '\n')) {
  6155. /* Two \r\n - standard compliant */
  6156. return i + 4;
  6157. }
  6158. }
  6159. }
  6160. return 0;
  6161. }
  6162. #if !defined(NO_CACHING)
  6163. /* Convert month to the month number. Return -1 on error, or month number */
  6164. static int
  6165. get_month_index(const char *s)
  6166. {
  6167. size_t i;
  6168. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6169. if (!strcmp(s, month_names[i])) {
  6170. return (int)i;
  6171. }
  6172. }
  6173. return -1;
  6174. }
  6175. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6176. static time_t
  6177. parse_date_string(const char *datetime)
  6178. {
  6179. char month_str[32] = {0};
  6180. int second, minute, hour, day, month, year;
  6181. time_t result = (time_t)0;
  6182. struct tm tm;
  6183. if ((sscanf(datetime,
  6184. "%d/%3s/%d %d:%d:%d",
  6185. &day,
  6186. month_str,
  6187. &year,
  6188. &hour,
  6189. &minute,
  6190. &second) == 6) || (sscanf(datetime,
  6191. "%d %3s %d %d:%d:%d",
  6192. &day,
  6193. month_str,
  6194. &year,
  6195. &hour,
  6196. &minute,
  6197. &second) == 6)
  6198. || (sscanf(datetime,
  6199. "%*3s, %d %3s %d %d:%d:%d",
  6200. &day,
  6201. month_str,
  6202. &year,
  6203. &hour,
  6204. &minute,
  6205. &second) == 6) || (sscanf(datetime,
  6206. "%d-%3s-%d %d:%d:%d",
  6207. &day,
  6208. month_str,
  6209. &year,
  6210. &hour,
  6211. &minute,
  6212. &second) == 6)) {
  6213. month = get_month_index(month_str);
  6214. if ((month >= 0) && (year >= 1970)) {
  6215. memset(&tm, 0, sizeof(tm));
  6216. tm.tm_year = year - 1900;
  6217. tm.tm_mon = month;
  6218. tm.tm_mday = day;
  6219. tm.tm_hour = hour;
  6220. tm.tm_min = minute;
  6221. tm.tm_sec = second;
  6222. result = timegm(&tm);
  6223. }
  6224. }
  6225. return result;
  6226. }
  6227. #endif /* !NO_CACHING */
  6228. /* Protect against directory disclosure attack by removing '..',
  6229. * excessive '/' and '\' characters */
  6230. static void
  6231. remove_double_dots_and_double_slashes(char *s)
  6232. {
  6233. char *p = s;
  6234. while ((s[0] == '.') && (s[1] == '.')) {
  6235. s++;
  6236. }
  6237. while (*s != '\0') {
  6238. *p++ = *s++;
  6239. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6240. /* Skip all following slashes, backslashes and double-dots */
  6241. while (s[0] != '\0') {
  6242. if ((s[0] == '/') || (s[0] == '\\')) {
  6243. s++;
  6244. } else if ((s[0] == '.') && (s[1] == '.')) {
  6245. s += 2;
  6246. } else {
  6247. break;
  6248. }
  6249. }
  6250. }
  6251. }
  6252. *p = '\0';
  6253. }
  6254. static const struct {
  6255. const char *extension;
  6256. size_t ext_len;
  6257. const char *mime_type;
  6258. } builtin_mime_types[] = {
  6259. /* IANA registered MIME types
  6260. * (http://www.iana.org/assignments/media-types)
  6261. * application types */
  6262. {".doc", 4, "application/msword"},
  6263. {".eps", 4, "application/postscript"},
  6264. {".exe", 4, "application/octet-stream"},
  6265. {".js", 3, "application/javascript"},
  6266. {".json", 5, "application/json"},
  6267. {".pdf", 4, "application/pdf"},
  6268. {".ps", 3, "application/postscript"},
  6269. {".rtf", 4, "application/rtf"},
  6270. {".xhtml", 6, "application/xhtml+xml"},
  6271. {".xsl", 4, "application/xml"},
  6272. {".xslt", 5, "application/xml"},
  6273. /* fonts */
  6274. {".ttf", 4, "application/font-sfnt"},
  6275. {".cff", 4, "application/font-sfnt"},
  6276. {".otf", 4, "application/font-sfnt"},
  6277. {".aat", 4, "application/font-sfnt"},
  6278. {".sil", 4, "application/font-sfnt"},
  6279. {".pfr", 4, "application/font-tdpfr"},
  6280. {".woff", 5, "application/font-woff"},
  6281. /* audio */
  6282. {".mp3", 4, "audio/mpeg"},
  6283. {".oga", 4, "audio/ogg"},
  6284. {".ogg", 4, "audio/ogg"},
  6285. /* image */
  6286. {".gif", 4, "image/gif"},
  6287. {".ief", 4, "image/ief"},
  6288. {".jpeg", 5, "image/jpeg"},
  6289. {".jpg", 4, "image/jpeg"},
  6290. {".jpm", 4, "image/jpm"},
  6291. {".jpx", 4, "image/jpx"},
  6292. {".png", 4, "image/png"},
  6293. {".svg", 4, "image/svg+xml"},
  6294. {".tif", 4, "image/tiff"},
  6295. {".tiff", 5, "image/tiff"},
  6296. /* model */
  6297. {".wrl", 4, "model/vrml"},
  6298. /* text */
  6299. {".css", 4, "text/css"},
  6300. {".csv", 4, "text/csv"},
  6301. {".htm", 4, "text/html"},
  6302. {".html", 5, "text/html"},
  6303. {".sgm", 4, "text/sgml"},
  6304. {".shtm", 5, "text/html"},
  6305. {".shtml", 6, "text/html"},
  6306. {".txt", 4, "text/plain"},
  6307. {".xml", 4, "text/xml"},
  6308. /* video */
  6309. {".mov", 4, "video/quicktime"},
  6310. {".mp4", 4, "video/mp4"},
  6311. {".mpeg", 5, "video/mpeg"},
  6312. {".mpg", 4, "video/mpeg"},
  6313. {".ogv", 4, "video/ogg"},
  6314. {".qt", 3, "video/quicktime"},
  6315. /* not registered types
  6316. * (http://reference.sitepoint.com/html/mime-types-full,
  6317. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6318. {".arj", 4, "application/x-arj-compressed"},
  6319. {".gz", 3, "application/x-gunzip"},
  6320. {".rar", 4, "application/x-arj-compressed"},
  6321. {".swf", 4, "application/x-shockwave-flash"},
  6322. {".tar", 4, "application/x-tar"},
  6323. {".tgz", 4, "application/x-tar-gz"},
  6324. {".torrent", 8, "application/x-bittorrent"},
  6325. {".ppt", 4, "application/x-mspowerpoint"},
  6326. {".xls", 4, "application/x-msexcel"},
  6327. {".zip", 4, "application/x-zip-compressed"},
  6328. {".aac",
  6329. 4,
  6330. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6331. {".aif", 4, "audio/x-aif"},
  6332. {".m3u", 4, "audio/x-mpegurl"},
  6333. {".mid", 4, "audio/x-midi"},
  6334. {".ra", 3, "audio/x-pn-realaudio"},
  6335. {".ram", 4, "audio/x-pn-realaudio"},
  6336. {".wav", 4, "audio/x-wav"},
  6337. {".bmp", 4, "image/bmp"},
  6338. {".ico", 4, "image/x-icon"},
  6339. {".pct", 4, "image/x-pct"},
  6340. {".pict", 5, "image/pict"},
  6341. {".rgb", 4, "image/x-rgb"},
  6342. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6343. {".asf", 4, "video/x-ms-asf"},
  6344. {".avi", 4, "video/x-msvideo"},
  6345. {".m4v", 4, "video/x-m4v"},
  6346. {NULL, 0, NULL}};
  6347. const char *
  6348. mg_get_builtin_mime_type(const char *path)
  6349. {
  6350. const char *ext;
  6351. size_t i, path_len;
  6352. path_len = strlen(path);
  6353. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6354. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6355. if ((path_len > builtin_mime_types[i].ext_len)
  6356. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6357. return builtin_mime_types[i].mime_type;
  6358. }
  6359. }
  6360. return "text/plain";
  6361. }
  6362. /* Look at the "path" extension and figure what mime type it has.
  6363. * Store mime type in the vector. */
  6364. static void
  6365. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6366. {
  6367. struct vec ext_vec, mime_vec;
  6368. const char *list, *ext;
  6369. size_t path_len;
  6370. path_len = strlen(path);
  6371. if ((conn == NULL) || (vec == NULL)) {
  6372. if (vec != NULL) {
  6373. memset(vec, '\0', sizeof(struct vec));
  6374. }
  6375. return;
  6376. }
  6377. /* Scan user-defined mime types first, in case user wants to
  6378. * override default mime types. */
  6379. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6380. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6381. /* ext now points to the path suffix */
  6382. ext = path + path_len - ext_vec.len;
  6383. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6384. *vec = mime_vec;
  6385. return;
  6386. }
  6387. }
  6388. vec->ptr = mg_get_builtin_mime_type(path);
  6389. vec->len = strlen(vec->ptr);
  6390. }
  6391. /* Stringify binary data. Output buffer must be twice as big as input,
  6392. * because each byte takes 2 bytes in string representation */
  6393. static void
  6394. bin2str(char *to, const unsigned char *p, size_t len)
  6395. {
  6396. static const char *hex = "0123456789abcdef";
  6397. for (; len--; p++) {
  6398. *to++ = hex[p[0] >> 4];
  6399. *to++ = hex[p[0] & 0x0f];
  6400. }
  6401. *to = '\0';
  6402. }
  6403. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6404. */
  6405. char *
  6406. mg_md5(char buf[33], ...)
  6407. {
  6408. md5_byte_t hash[16];
  6409. const char *p;
  6410. va_list ap;
  6411. md5_state_t ctx;
  6412. md5_init(&ctx);
  6413. va_start(ap, buf);
  6414. while ((p = va_arg(ap, const char *)) != NULL) {
  6415. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6416. }
  6417. va_end(ap);
  6418. md5_finish(&ctx, hash);
  6419. bin2str(buf, hash, sizeof(hash));
  6420. return buf;
  6421. }
  6422. /* Check the user's password, return 1 if OK */
  6423. static int
  6424. check_password(const char *method,
  6425. const char *ha1,
  6426. const char *uri,
  6427. const char *nonce,
  6428. const char *nc,
  6429. const char *cnonce,
  6430. const char *qop,
  6431. const char *response)
  6432. {
  6433. char ha2[32 + 1], expected_response[32 + 1];
  6434. /* Some of the parameters may be NULL */
  6435. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6436. || (qop == NULL) || (response == NULL)) {
  6437. return 0;
  6438. }
  6439. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6440. if (strlen(response) != 32) {
  6441. return 0;
  6442. }
  6443. mg_md5(ha2, method, ":", uri, NULL);
  6444. mg_md5(expected_response,
  6445. ha1,
  6446. ":",
  6447. nonce,
  6448. ":",
  6449. nc,
  6450. ":",
  6451. cnonce,
  6452. ":",
  6453. qop,
  6454. ":",
  6455. ha2,
  6456. NULL);
  6457. return mg_strcasecmp(response, expected_response) == 0;
  6458. }
  6459. /* Use the global passwords file, if specified by auth_gpass option,
  6460. * or search for .htpasswd in the requested directory. */
  6461. static void
  6462. open_auth_file(struct mg_connection *conn,
  6463. const char *path,
  6464. struct mg_file *filep)
  6465. {
  6466. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6467. char name[PATH_MAX];
  6468. const char *p, *e,
  6469. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6470. int truncated;
  6471. if (gpass != NULL) {
  6472. /* Use global passwords file */
  6473. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6474. #ifdef DEBUG
  6475. /* Use mg_cry_internal here, since gpass has been configured. */
  6476. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6477. #endif
  6478. }
  6479. /* Important: using local struct mg_file to test path for
  6480. * is_directory flag. If filep is used, mg_stat() makes it
  6481. * appear as if auth file was opened.
  6482. * TODO(mid): Check if this is still required after rewriting
  6483. * mg_stat */
  6484. } else if (mg_stat(conn, path, &filep->stat)
  6485. && filep->stat.is_directory) {
  6486. mg_snprintf(conn,
  6487. &truncated,
  6488. name,
  6489. sizeof(name),
  6490. "%s/%s",
  6491. path,
  6492. PASSWORDS_FILE_NAME);
  6493. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6494. #ifdef DEBUG
  6495. /* Don't use mg_cry_internal here, but only a trace, since this
  6496. * is
  6497. * a typical case. It will occur for every directory
  6498. * without a password file. */
  6499. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6500. #endif
  6501. }
  6502. } else {
  6503. /* Try to find .htpasswd in requested directory. */
  6504. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6505. if (e[0] == '/') {
  6506. break;
  6507. }
  6508. }
  6509. mg_snprintf(conn,
  6510. &truncated,
  6511. name,
  6512. sizeof(name),
  6513. "%.*s/%s",
  6514. (int)(e - p),
  6515. p,
  6516. PASSWORDS_FILE_NAME);
  6517. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6518. #ifdef DEBUG
  6519. /* Don't use mg_cry_internal here, but only a trace, since this
  6520. * is
  6521. * a typical case. It will occur for every directory
  6522. * without a password file. */
  6523. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6524. #endif
  6525. }
  6526. }
  6527. }
  6528. }
  6529. /* Parsed Authorization header */
  6530. struct ah {
  6531. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6532. };
  6533. /* Return 1 on success. Always initializes the ah structure. */
  6534. static int
  6535. parse_auth_header(struct mg_connection *conn,
  6536. char *buf,
  6537. size_t buf_size,
  6538. struct ah *ah)
  6539. {
  6540. char *name, *value, *s;
  6541. const char *auth_header;
  6542. uint64_t nonce;
  6543. if (!ah || !conn) {
  6544. return 0;
  6545. }
  6546. (void)memset(ah, 0, sizeof(*ah));
  6547. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6548. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6549. return 0;
  6550. }
  6551. /* Make modifiable copy of the auth header */
  6552. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6553. s = buf;
  6554. /* Parse authorization header */
  6555. for (;;) {
  6556. /* Gobble initial spaces */
  6557. while (isspace(*(unsigned char *)s)) {
  6558. s++;
  6559. }
  6560. name = skip_quoted(&s, "=", " ", 0);
  6561. /* Value is either quote-delimited, or ends at first comma or space.
  6562. */
  6563. if (s[0] == '\"') {
  6564. s++;
  6565. value = skip_quoted(&s, "\"", " ", '\\');
  6566. if (s[0] == ',') {
  6567. s++;
  6568. }
  6569. } else {
  6570. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6571. * spaces */
  6572. }
  6573. if (*name == '\0') {
  6574. break;
  6575. }
  6576. if (!strcmp(name, "username")) {
  6577. ah->user = value;
  6578. } else if (!strcmp(name, "cnonce")) {
  6579. ah->cnonce = value;
  6580. } else if (!strcmp(name, "response")) {
  6581. ah->response = value;
  6582. } else if (!strcmp(name, "uri")) {
  6583. ah->uri = value;
  6584. } else if (!strcmp(name, "qop")) {
  6585. ah->qop = value;
  6586. } else if (!strcmp(name, "nc")) {
  6587. ah->nc = value;
  6588. } else if (!strcmp(name, "nonce")) {
  6589. ah->nonce = value;
  6590. }
  6591. }
  6592. #ifndef NO_NONCE_CHECK
  6593. /* Read the nonce from the response. */
  6594. if (ah->nonce == NULL) {
  6595. return 0;
  6596. }
  6597. s = NULL;
  6598. nonce = strtoull(ah->nonce, &s, 10);
  6599. if ((s == NULL) || (*s != 0)) {
  6600. return 0;
  6601. }
  6602. /* Convert the nonce from the client to a number. */
  6603. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6604. /* The converted number corresponds to the time the nounce has been
  6605. * created. This should not be earlier than the server start. */
  6606. /* Server side nonce check is valuable in all situations but one:
  6607. * if the server restarts frequently, but the client should not see
  6608. * that, so the server should accept nonces from previous starts. */
  6609. /* However, the reasonable default is to not accept a nonce from a
  6610. * previous start, so if anyone changed the access rights between
  6611. * two restarts, a new login is required. */
  6612. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6613. /* nonce is from a previous start of the server and no longer valid
  6614. * (replay attack?) */
  6615. return 0;
  6616. }
  6617. /* Check if the nonce is too high, so it has not (yet) been used by the
  6618. * server. */
  6619. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6620. + conn->dom_ctx->nonce_count)) {
  6621. return 0;
  6622. }
  6623. #else
  6624. (void)nonce;
  6625. #endif
  6626. /* CGI needs it as REMOTE_USER */
  6627. if (ah->user != NULL) {
  6628. conn->request_info.remote_user =
  6629. mg_strdup_ctx(ah->user, conn->phys_ctx);
  6630. } else {
  6631. return 0;
  6632. }
  6633. return 1;
  6634. }
  6635. static const char *
  6636. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6637. {
  6638. const char *eof;
  6639. size_t len;
  6640. const char *memend;
  6641. if (!filep) {
  6642. return NULL;
  6643. }
  6644. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6645. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6646. /* Search for \n from p till the end of stream */
  6647. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6648. if (eof != NULL) {
  6649. eof += 1; /* Include \n */
  6650. } else {
  6651. eof = memend; /* Copy remaining data */
  6652. }
  6653. len =
  6654. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6655. memcpy(buf, *p, len);
  6656. buf[len] = '\0';
  6657. *p += len;
  6658. return len ? eof : NULL;
  6659. } else if (filep->access.fp != NULL) {
  6660. return fgets(buf, (int)size, filep->access.fp);
  6661. } else {
  6662. return NULL;
  6663. }
  6664. }
  6665. /* Define the initial recursion depth for procesesing htpasswd files that
  6666. * include other htpasswd
  6667. * (or even the same) files. It is not difficult to provide a file or files
  6668. * s.t. they force civetweb
  6669. * to infinitely recurse and then crash.
  6670. */
  6671. #define INITIAL_DEPTH 9
  6672. #if INITIAL_DEPTH <= 0
  6673. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6674. #endif
  6675. struct read_auth_file_struct {
  6676. struct mg_connection *conn;
  6677. struct ah ah;
  6678. const char *domain;
  6679. char buf[256 + 256 + 40];
  6680. const char *f_user;
  6681. const char *f_domain;
  6682. const char *f_ha1;
  6683. };
  6684. static int
  6685. read_auth_file(struct mg_file *filep,
  6686. struct read_auth_file_struct *workdata,
  6687. int depth)
  6688. {
  6689. char *p;
  6690. int is_authorized = 0;
  6691. struct mg_file fp;
  6692. size_t l;
  6693. if (!filep || !workdata || (0 == depth)) {
  6694. return 0;
  6695. }
  6696. /* Loop over passwords file */
  6697. p = (char *)filep->access.membuf;
  6698. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6699. l = strlen(workdata->buf);
  6700. while (l > 0) {
  6701. if (isspace(workdata->buf[l - 1])
  6702. || iscntrl(workdata->buf[l - 1])) {
  6703. l--;
  6704. workdata->buf[l] = 0;
  6705. } else
  6706. break;
  6707. }
  6708. if (l < 1) {
  6709. continue;
  6710. }
  6711. workdata->f_user = workdata->buf;
  6712. if (workdata->f_user[0] == ':') {
  6713. /* user names may not contain a ':' and may not be empty,
  6714. * so lines starting with ':' may be used for a special purpose
  6715. */
  6716. if (workdata->f_user[1] == '#') {
  6717. /* :# is a comment */
  6718. continue;
  6719. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6720. if (mg_fopen(workdata->conn,
  6721. workdata->f_user + 9,
  6722. MG_FOPEN_MODE_READ,
  6723. &fp)) {
  6724. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6725. (void)mg_fclose(
  6726. &fp.access); /* ignore error on read only file */
  6727. /* No need to continue processing files once we have a
  6728. * match, since nothing will reset it back
  6729. * to 0.
  6730. */
  6731. if (is_authorized) {
  6732. return is_authorized;
  6733. }
  6734. } else {
  6735. mg_cry_internal(workdata->conn,
  6736. "%s: cannot open authorization file: %s",
  6737. __func__,
  6738. workdata->buf);
  6739. }
  6740. continue;
  6741. }
  6742. /* everything is invalid for the moment (might change in the
  6743. * future) */
  6744. mg_cry_internal(workdata->conn,
  6745. "%s: syntax error in authorization file: %s",
  6746. __func__,
  6747. workdata->buf);
  6748. continue;
  6749. }
  6750. workdata->f_domain = strchr(workdata->f_user, ':');
  6751. if (workdata->f_domain == NULL) {
  6752. mg_cry_internal(workdata->conn,
  6753. "%s: syntax error in authorization file: %s",
  6754. __func__,
  6755. workdata->buf);
  6756. continue;
  6757. }
  6758. *(char *)(workdata->f_domain) = 0;
  6759. (workdata->f_domain)++;
  6760. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6761. if (workdata->f_ha1 == NULL) {
  6762. mg_cry_internal(workdata->conn,
  6763. "%s: syntax error in authorization file: %s",
  6764. __func__,
  6765. workdata->buf);
  6766. continue;
  6767. }
  6768. *(char *)(workdata->f_ha1) = 0;
  6769. (workdata->f_ha1)++;
  6770. if (!strcmp(workdata->ah.user, workdata->f_user)
  6771. && !strcmp(workdata->domain, workdata->f_domain)) {
  6772. return check_password(workdata->conn->request_info.request_method,
  6773. workdata->f_ha1,
  6774. workdata->ah.uri,
  6775. workdata->ah.nonce,
  6776. workdata->ah.nc,
  6777. workdata->ah.cnonce,
  6778. workdata->ah.qop,
  6779. workdata->ah.response);
  6780. }
  6781. }
  6782. return is_authorized;
  6783. }
  6784. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6785. static int
  6786. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  6787. {
  6788. struct read_auth_file_struct workdata;
  6789. char buf[MG_BUF_LEN];
  6790. if (!conn || !conn->dom_ctx) {
  6791. return 0;
  6792. }
  6793. memset(&workdata, 0, sizeof(workdata));
  6794. workdata.conn = conn;
  6795. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6796. return 0;
  6797. }
  6798. if (realm) {
  6799. workdata.domain = realm;
  6800. } else {
  6801. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  6802. }
  6803. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6804. }
  6805. /* Public function to check http digest authentication header */
  6806. int
  6807. mg_check_digest_access_authentication(struct mg_connection *conn,
  6808. const char *realm,
  6809. const char *filename)
  6810. {
  6811. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6812. int auth;
  6813. if (!conn || !filename) {
  6814. return -1;
  6815. }
  6816. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  6817. return -2;
  6818. }
  6819. auth = authorize(conn, &file, realm);
  6820. mg_fclose(&file.access);
  6821. return auth;
  6822. }
  6823. /* Return 1 if request is authorised, 0 otherwise. */
  6824. static int
  6825. check_authorization(struct mg_connection *conn, const char *path)
  6826. {
  6827. char fname[PATH_MAX];
  6828. struct vec uri_vec, filename_vec;
  6829. const char *list;
  6830. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6831. int authorized = 1, truncated;
  6832. if (!conn || !conn->dom_ctx) {
  6833. return 0;
  6834. }
  6835. list = conn->dom_ctx->config[PROTECT_URI];
  6836. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6837. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6838. mg_snprintf(conn,
  6839. &truncated,
  6840. fname,
  6841. sizeof(fname),
  6842. "%.*s",
  6843. (int)filename_vec.len,
  6844. filename_vec.ptr);
  6845. if (truncated
  6846. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6847. mg_cry_internal(conn,
  6848. "%s: cannot open %s: %s",
  6849. __func__,
  6850. fname,
  6851. strerror(errno));
  6852. }
  6853. break;
  6854. }
  6855. }
  6856. if (!is_file_opened(&file.access)) {
  6857. open_auth_file(conn, path, &file);
  6858. }
  6859. if (is_file_opened(&file.access)) {
  6860. authorized = authorize(conn, &file, NULL);
  6861. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6862. }
  6863. return authorized;
  6864. }
  6865. /* Internal function. Assumes conn is valid */
  6866. static void
  6867. send_authorization_request(struct mg_connection *conn, const char *realm)
  6868. {
  6869. char date[64];
  6870. time_t curtime = time(NULL);
  6871. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  6872. if (!realm) {
  6873. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  6874. }
  6875. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  6876. nonce += conn->dom_ctx->nonce_count;
  6877. ++conn->dom_ctx->nonce_count;
  6878. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  6879. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6880. conn->status_code = 401;
  6881. conn->must_close = 1;
  6882. gmt_time_string(date, sizeof(date), &curtime);
  6883. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6884. send_no_cache_header(conn);
  6885. send_additional_header(conn);
  6886. mg_printf(conn,
  6887. "Date: %s\r\n"
  6888. "Connection: %s\r\n"
  6889. "Content-Length: 0\r\n"
  6890. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6891. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6892. date,
  6893. suggest_connection_header(conn),
  6894. realm,
  6895. nonce);
  6896. }
  6897. /* Interface function. Parameters are provided by the user, so do
  6898. * at least some basic checks.
  6899. */
  6900. int
  6901. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  6902. const char *realm)
  6903. {
  6904. if (conn && conn->dom_ctx) {
  6905. send_authorization_request(conn, realm);
  6906. return 0;
  6907. }
  6908. return -1;
  6909. }
  6910. #if !defined(NO_FILES)
  6911. static int
  6912. is_authorized_for_put(struct mg_connection *conn)
  6913. {
  6914. if (conn) {
  6915. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6916. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6917. int ret = 0;
  6918. if (passfile != NULL
  6919. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6920. ret = authorize(conn, &file, NULL);
  6921. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6922. }
  6923. return ret;
  6924. }
  6925. return 0;
  6926. }
  6927. #endif
  6928. int
  6929. mg_modify_passwords_file(const char *fname,
  6930. const char *domain,
  6931. const char *user,
  6932. const char *pass)
  6933. {
  6934. int found, i;
  6935. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6936. FILE *fp, *fp2;
  6937. found = 0;
  6938. fp = fp2 = NULL;
  6939. /* Regard empty password as no password - remove user record. */
  6940. if ((pass != NULL) && (pass[0] == '\0')) {
  6941. pass = NULL;
  6942. }
  6943. /* Other arguments must not be empty */
  6944. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  6945. return 0;
  6946. }
  6947. /* Using the given file format, user name and domain must not contain
  6948. * ':'
  6949. */
  6950. if (strchr(user, ':') != NULL) {
  6951. return 0;
  6952. }
  6953. if (strchr(domain, ':') != NULL) {
  6954. return 0;
  6955. }
  6956. /* Do not allow control characters like newline in user name and domain.
  6957. * Do not allow excessively long names either. */
  6958. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  6959. if (iscntrl(user[i])) {
  6960. return 0;
  6961. }
  6962. }
  6963. if (user[i]) {
  6964. return 0;
  6965. }
  6966. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  6967. if (iscntrl(domain[i])) {
  6968. return 0;
  6969. }
  6970. }
  6971. if (domain[i]) {
  6972. return 0;
  6973. }
  6974. /* The maximum length of the path to the password file is limited */
  6975. if ((strlen(fname) + 4) >= PATH_MAX) {
  6976. return 0;
  6977. }
  6978. /* Create a temporary file name. Length has been checked before. */
  6979. strcpy(tmp, fname);
  6980. strcat(tmp, ".tmp");
  6981. /* Create the file if does not exist */
  6982. /* Use of fopen here is OK, since fname is only ASCII */
  6983. if ((fp = fopen(fname, "a+")) != NULL) {
  6984. (void)fclose(fp);
  6985. }
  6986. /* Open the given file and temporary file */
  6987. if ((fp = fopen(fname, "r")) == NULL) {
  6988. return 0;
  6989. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6990. fclose(fp);
  6991. return 0;
  6992. }
  6993. /* Copy the stuff to temporary file */
  6994. while (fgets(line, sizeof(line), fp) != NULL) {
  6995. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6996. continue;
  6997. }
  6998. u[255] = 0;
  6999. d[255] = 0;
  7000. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7001. found++;
  7002. if (pass != NULL) {
  7003. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7004. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7005. }
  7006. } else {
  7007. fprintf(fp2, "%s", line);
  7008. }
  7009. }
  7010. /* If new user, just add it */
  7011. if (!found && (pass != NULL)) {
  7012. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7013. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7014. }
  7015. /* Close files */
  7016. fclose(fp);
  7017. fclose(fp2);
  7018. /* Put the temp file in place of real file */
  7019. IGNORE_UNUSED_RESULT(remove(fname));
  7020. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7021. return 1;
  7022. }
  7023. static int
  7024. is_valid_port(unsigned long port)
  7025. {
  7026. return (port <= 0xffff);
  7027. }
  7028. static int
  7029. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7030. {
  7031. struct addrinfo hints, *res, *ressave;
  7032. int func_ret = 0;
  7033. int gai_ret;
  7034. memset(&hints, 0, sizeof(struct addrinfo));
  7035. hints.ai_family = af;
  7036. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7037. if (gai_ret != 0) {
  7038. /* gai_strerror could be used to convert gai_ret to a string */
  7039. /* POSIX return values: see
  7040. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7041. */
  7042. /* Windows return values: see
  7043. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7044. */
  7045. return 0;
  7046. }
  7047. ressave = res;
  7048. while (res) {
  7049. if (dstlen >= (size_t)res->ai_addrlen) {
  7050. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7051. func_ret = 1;
  7052. }
  7053. res = res->ai_next;
  7054. }
  7055. freeaddrinfo(ressave);
  7056. return func_ret;
  7057. }
  7058. static int
  7059. connect_socket(struct mg_context *ctx /* may be NULL */,
  7060. const char *host,
  7061. int port,
  7062. int use_ssl,
  7063. char *ebuf,
  7064. size_t ebuf_len,
  7065. SOCKET *sock /* output: socket, must not be NULL */,
  7066. union usa *sa /* output: socket address, must not be NULL */
  7067. )
  7068. {
  7069. int ip_ver = 0;
  7070. int conn_ret = -1;
  7071. *sock = INVALID_SOCKET;
  7072. memset(sa, 0, sizeof(*sa));
  7073. if (ebuf_len > 0) {
  7074. *ebuf = 0;
  7075. }
  7076. if (host == NULL) {
  7077. mg_snprintf(NULL,
  7078. NULL, /* No truncation check for ebuf */
  7079. ebuf,
  7080. ebuf_len,
  7081. "%s",
  7082. "NULL host");
  7083. return 0;
  7084. }
  7085. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7086. mg_snprintf(NULL,
  7087. NULL, /* No truncation check for ebuf */
  7088. ebuf,
  7089. ebuf_len,
  7090. "%s",
  7091. "invalid port");
  7092. return 0;
  7093. }
  7094. #if !defined(NO_SSL)
  7095. #if !defined(NO_SSL_DL)
  7096. #ifdef OPENSSL_API_1_1
  7097. if (use_ssl && (TLS_client_method == NULL)) {
  7098. mg_snprintf(NULL,
  7099. NULL, /* No truncation check for ebuf */
  7100. ebuf,
  7101. ebuf_len,
  7102. "%s",
  7103. "SSL is not initialized");
  7104. return 0;
  7105. }
  7106. #else
  7107. if (use_ssl && (SSLv23_client_method == NULL)) {
  7108. mg_snprintf(NULL,
  7109. NULL, /* No truncation check for ebuf */
  7110. ebuf,
  7111. ebuf_len,
  7112. "%s",
  7113. "SSL is not initialized");
  7114. return 0;
  7115. }
  7116. #endif /* OPENSSL_API_1_1 */
  7117. #else
  7118. (void)use_ssl;
  7119. #endif /* NO_SSL_DL */
  7120. #else
  7121. (void)use_ssl;
  7122. #endif /* !defined(NO_SSL) */
  7123. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7124. sa->sin.sin_family = AF_INET;
  7125. sa->sin.sin_port = htons((uint16_t)port);
  7126. ip_ver = 4;
  7127. #ifdef USE_IPV6
  7128. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7129. sa->sin6.sin6_family = AF_INET6;
  7130. sa->sin6.sin6_port = htons((uint16_t)port);
  7131. ip_ver = 6;
  7132. } else if (host[0] == '[') {
  7133. /* While getaddrinfo on Windows will work with [::1],
  7134. * getaddrinfo on Linux only works with ::1 (without []). */
  7135. size_t l = strlen(host + 1);
  7136. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7137. if (h) {
  7138. h[l - 1] = 0;
  7139. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7140. sa->sin6.sin6_family = AF_INET6;
  7141. sa->sin6.sin6_port = htons((uint16_t)port);
  7142. ip_ver = 6;
  7143. }
  7144. mg_free(h);
  7145. }
  7146. #endif
  7147. }
  7148. if (ip_ver == 0) {
  7149. mg_snprintf(NULL,
  7150. NULL, /* No truncation check for ebuf */
  7151. ebuf,
  7152. ebuf_len,
  7153. "%s",
  7154. "host not found");
  7155. return 0;
  7156. }
  7157. if (ip_ver == 4) {
  7158. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7159. }
  7160. #ifdef USE_IPV6
  7161. else if (ip_ver == 6) {
  7162. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7163. }
  7164. #endif
  7165. if (*sock == INVALID_SOCKET) {
  7166. mg_snprintf(NULL,
  7167. NULL, /* No truncation check for ebuf */
  7168. ebuf,
  7169. ebuf_len,
  7170. "socket(): %s",
  7171. strerror(ERRNO));
  7172. return 0;
  7173. }
  7174. if (0 != set_non_blocking_mode(*sock)) {
  7175. mg_snprintf(NULL,
  7176. NULL, /* No truncation check for ebuf */
  7177. ebuf,
  7178. ebuf_len,
  7179. "Cannot set socket to non-blocking: %s",
  7180. strerror(ERRNO));
  7181. closesocket(*sock);
  7182. *sock = INVALID_SOCKET;
  7183. return 0;
  7184. }
  7185. set_close_on_exec(*sock, fc(ctx));
  7186. if (ip_ver == 4) {
  7187. /* connected with IPv4 */
  7188. conn_ret = connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin));
  7189. }
  7190. #ifdef USE_IPV6
  7191. else if (ip_ver == 6) {
  7192. /* connected with IPv6 */
  7193. conn_ret =
  7194. connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6));
  7195. }
  7196. #endif
  7197. if (conn_ret != 0) {
  7198. fd_set fdset;
  7199. struct timeval timeout;
  7200. int sockerr = -1;
  7201. #if defined(_WIN32)
  7202. int len = (int)sizeof(sockerr);
  7203. #else
  7204. socklen_t len = (socklen_t)sizeof(sockerr);
  7205. #endif
  7206. FD_ZERO(&fdset);
  7207. FD_SET(*sock, &fdset);
  7208. timeout.tv_sec = 10; /* 10 second timeout */
  7209. timeout.tv_usec = 0;
  7210. if (select((int)(*sock) + 1, NULL, &fdset, NULL, &timeout) != 1) {
  7211. /* Not connected */
  7212. mg_snprintf(NULL,
  7213. NULL, /* No truncation check for ebuf */
  7214. ebuf,
  7215. ebuf_len,
  7216. "connect(%s:%d): timeout",
  7217. host,
  7218. port);
  7219. closesocket(*sock);
  7220. *sock = INVALID_SOCKET;
  7221. return 0;
  7222. }
  7223. #if defined(_WIN32)
  7224. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)&sockerr, &len);
  7225. #else
  7226. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &len);
  7227. #endif
  7228. if (sockerr != 0) {
  7229. /* Not connected */
  7230. mg_snprintf(NULL,
  7231. NULL, /* No truncation check for ebuf */
  7232. ebuf,
  7233. ebuf_len,
  7234. "connect(%s:%d): error %s",
  7235. host,
  7236. port,
  7237. strerror(sockerr));
  7238. closesocket(*sock);
  7239. *sock = INVALID_SOCKET;
  7240. return 0;
  7241. }
  7242. }
  7243. return 1;
  7244. }
  7245. int
  7246. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7247. {
  7248. static const char *dont_escape = "._-$,;~()";
  7249. static const char *hex = "0123456789abcdef";
  7250. char *pos = dst;
  7251. const char *end = dst + dst_len - 1;
  7252. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7253. if (isalnum(*(const unsigned char *)src)
  7254. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7255. *pos = *src;
  7256. } else if (pos + 2 < end) {
  7257. pos[0] = '%';
  7258. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7259. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7260. pos += 2;
  7261. } else {
  7262. break;
  7263. }
  7264. }
  7265. *pos = '\0';
  7266. return (*src == '\0') ? (int)(pos - dst) : -1;
  7267. }
  7268. /* Return 0 on success, non-zero if an error occurs. */
  7269. static int
  7270. print_dir_entry(struct de *de)
  7271. {
  7272. size_t hrefsize;
  7273. char *href;
  7274. char size[64], mod[64];
  7275. #ifdef REENTRANT_TIME
  7276. struct tm _tm;
  7277. struct tm *tm = &_tm;
  7278. #else
  7279. struct tm *tm;
  7280. #endif
  7281. hrefsize = PATH_MAX * 3; /* worst case */
  7282. href = (char *)mg_malloc(hrefsize);
  7283. if (href == NULL) {
  7284. return -1;
  7285. }
  7286. if (de->file.is_directory) {
  7287. mg_snprintf(de->conn,
  7288. NULL, /* Buffer is big enough */
  7289. size,
  7290. sizeof(size),
  7291. "%s",
  7292. "[DIRECTORY]");
  7293. } else {
  7294. /* We use (signed) cast below because MSVC 6 compiler cannot
  7295. * convert unsigned __int64 to double. Sigh. */
  7296. if (de->file.size < 1024) {
  7297. mg_snprintf(de->conn,
  7298. NULL, /* Buffer is big enough */
  7299. size,
  7300. sizeof(size),
  7301. "%d",
  7302. (int)de->file.size);
  7303. } else if (de->file.size < 0x100000) {
  7304. mg_snprintf(de->conn,
  7305. NULL, /* Buffer is big enough */
  7306. size,
  7307. sizeof(size),
  7308. "%.1fk",
  7309. (double)de->file.size / 1024.0);
  7310. } else if (de->file.size < 0x40000000) {
  7311. mg_snprintf(de->conn,
  7312. NULL, /* Buffer is big enough */
  7313. size,
  7314. sizeof(size),
  7315. "%.1fM",
  7316. (double)de->file.size / 1048576);
  7317. } else {
  7318. mg_snprintf(de->conn,
  7319. NULL, /* Buffer is big enough */
  7320. size,
  7321. sizeof(size),
  7322. "%.1fG",
  7323. (double)de->file.size / 1073741824);
  7324. }
  7325. }
  7326. /* Note: mg_snprintf will not cause a buffer overflow above.
  7327. * So, string truncation checks are not required here. */
  7328. #ifdef REENTRANT_TIME
  7329. localtime_r(&de->file.last_modified, tm);
  7330. #else
  7331. tm = localtime(&de->file.last_modified);
  7332. #endif
  7333. if (tm != NULL) {
  7334. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7335. } else {
  7336. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7337. mod[sizeof(mod) - 1] = '\0';
  7338. }
  7339. mg_url_encode(de->file_name, href, hrefsize);
  7340. mg_printf(de->conn,
  7341. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7342. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7343. de->conn->request_info.local_uri,
  7344. href,
  7345. de->file.is_directory ? "/" : "",
  7346. de->file_name,
  7347. de->file.is_directory ? "/" : "",
  7348. mod,
  7349. size);
  7350. mg_free(href);
  7351. return 0;
  7352. }
  7353. /* This function is called from send_directory() and used for
  7354. * sorting directory entries by size, or name, or modification time.
  7355. * On windows, __cdecl specification is needed in case if project is built
  7356. * with __stdcall convention. qsort always requires __cdels callback. */
  7357. static int WINCDECL
  7358. compare_dir_entries(const void *p1, const void *p2)
  7359. {
  7360. if (p1 && p2) {
  7361. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7362. const char *query_string = a->conn->request_info.query_string;
  7363. int cmp_result = 0;
  7364. if (query_string == NULL) {
  7365. query_string = "na";
  7366. }
  7367. if (a->file.is_directory && !b->file.is_directory) {
  7368. return -1; /* Always put directories on top */
  7369. } else if (!a->file.is_directory && b->file.is_directory) {
  7370. return 1; /* Always put directories on top */
  7371. } else if (*query_string == 'n') {
  7372. cmp_result = strcmp(a->file_name, b->file_name);
  7373. } else if (*query_string == 's') {
  7374. cmp_result = (a->file.size == b->file.size)
  7375. ? 0
  7376. : ((a->file.size > b->file.size) ? 1 : -1);
  7377. } else if (*query_string == 'd') {
  7378. cmp_result =
  7379. (a->file.last_modified == b->file.last_modified)
  7380. ? 0
  7381. : ((a->file.last_modified > b->file.last_modified) ? 1
  7382. : -1);
  7383. }
  7384. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7385. }
  7386. return 0;
  7387. }
  7388. static int
  7389. must_hide_file(struct mg_connection *conn, const char *path)
  7390. {
  7391. if (conn && conn->dom_ctx) {
  7392. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7393. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7394. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7395. || ((pattern != NULL)
  7396. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7397. }
  7398. return 0;
  7399. }
  7400. static int
  7401. scan_directory(struct mg_connection *conn,
  7402. const char *dir,
  7403. void *data,
  7404. int (*cb)(struct de *, void *))
  7405. {
  7406. char path[PATH_MAX];
  7407. struct dirent *dp;
  7408. DIR *dirp;
  7409. struct de de;
  7410. int truncated;
  7411. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7412. return 0;
  7413. } else {
  7414. de.conn = conn;
  7415. while ((dp = mg_readdir(dirp)) != NULL) {
  7416. /* Do not show current dir and hidden files */
  7417. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7418. || must_hide_file(conn, dp->d_name)) {
  7419. continue;
  7420. }
  7421. mg_snprintf(
  7422. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7423. /* If we don't memset stat structure to zero, mtime will have
  7424. * garbage and strftime() will segfault later on in
  7425. * print_dir_entry(). memset is required only if mg_stat()
  7426. * fails. For more details, see
  7427. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7428. memset(&de.file, 0, sizeof(de.file));
  7429. if (truncated) {
  7430. /* If the path is not complete, skip processing. */
  7431. continue;
  7432. }
  7433. if (!mg_stat(conn, path, &de.file)) {
  7434. mg_cry_internal(conn,
  7435. "%s: mg_stat(%s) failed: %s",
  7436. __func__,
  7437. path,
  7438. strerror(ERRNO));
  7439. }
  7440. de.file_name = dp->d_name;
  7441. cb(&de, data);
  7442. }
  7443. (void)mg_closedir(dirp);
  7444. }
  7445. return 1;
  7446. }
  7447. #if !defined(NO_FILES)
  7448. static int
  7449. remove_directory(struct mg_connection *conn, const char *dir)
  7450. {
  7451. char path[PATH_MAX];
  7452. struct dirent *dp;
  7453. DIR *dirp;
  7454. struct de de;
  7455. int truncated;
  7456. int ok = 1;
  7457. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7458. return 0;
  7459. } else {
  7460. de.conn = conn;
  7461. while ((dp = mg_readdir(dirp)) != NULL) {
  7462. /* Do not show current dir (but show hidden files as they will
  7463. * also be removed) */
  7464. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7465. continue;
  7466. }
  7467. mg_snprintf(
  7468. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7469. /* If we don't memset stat structure to zero, mtime will have
  7470. * garbage and strftime() will segfault later on in
  7471. * print_dir_entry(). memset is required only if mg_stat()
  7472. * fails. For more details, see
  7473. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7474. memset(&de.file, 0, sizeof(de.file));
  7475. if (truncated) {
  7476. /* Do not delete anything shorter */
  7477. ok = 0;
  7478. continue;
  7479. }
  7480. if (!mg_stat(conn, path, &de.file)) {
  7481. mg_cry_internal(conn,
  7482. "%s: mg_stat(%s) failed: %s",
  7483. __func__,
  7484. path,
  7485. strerror(ERRNO));
  7486. ok = 0;
  7487. }
  7488. if (de.file.is_directory) {
  7489. if (remove_directory(conn, path) == 0) {
  7490. ok = 0;
  7491. }
  7492. } else {
  7493. /* This will fail file is the file is in memory */
  7494. if (mg_remove(conn, path) == 0) {
  7495. ok = 0;
  7496. }
  7497. }
  7498. }
  7499. (void)mg_closedir(dirp);
  7500. IGNORE_UNUSED_RESULT(rmdir(dir));
  7501. }
  7502. return ok;
  7503. }
  7504. #endif
  7505. struct dir_scan_data {
  7506. struct de *entries;
  7507. unsigned int num_entries;
  7508. unsigned int arr_size;
  7509. };
  7510. /* Behaves like realloc(), but frees original pointer on failure */
  7511. static void *
  7512. realloc2(void *ptr, size_t size)
  7513. {
  7514. void *new_ptr = mg_realloc(ptr, size);
  7515. if (new_ptr == NULL) {
  7516. mg_free(ptr);
  7517. }
  7518. return new_ptr;
  7519. }
  7520. static int
  7521. dir_scan_callback(struct de *de, void *data)
  7522. {
  7523. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7524. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7525. dsd->arr_size *= 2;
  7526. dsd->entries =
  7527. (struct de *)realloc2(dsd->entries,
  7528. dsd->arr_size * sizeof(dsd->entries[0]));
  7529. }
  7530. if (dsd->entries == NULL) {
  7531. /* TODO(lsm, low): propagate an error to the caller */
  7532. dsd->num_entries = 0;
  7533. } else {
  7534. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7535. dsd->entries[dsd->num_entries].file = de->file;
  7536. dsd->entries[dsd->num_entries].conn = de->conn;
  7537. dsd->num_entries++;
  7538. }
  7539. return 0;
  7540. }
  7541. static void
  7542. handle_directory_request(struct mg_connection *conn, const char *dir)
  7543. {
  7544. unsigned int i;
  7545. int sort_direction;
  7546. struct dir_scan_data data = {NULL, 0, 128};
  7547. char date[64];
  7548. time_t curtime = time(NULL);
  7549. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7550. mg_send_http_error(conn,
  7551. 500,
  7552. "Error: Cannot open directory\nopendir(%s): %s",
  7553. dir,
  7554. strerror(ERRNO));
  7555. return;
  7556. }
  7557. gmt_time_string(date, sizeof(date), &curtime);
  7558. if (!conn) {
  7559. return;
  7560. }
  7561. sort_direction = ((conn->request_info.query_string != NULL)
  7562. && (conn->request_info.query_string[1] == 'd'))
  7563. ? 'a'
  7564. : 'd';
  7565. conn->must_close = 1;
  7566. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7567. send_static_cache_header(conn);
  7568. send_additional_header(conn);
  7569. mg_printf(conn,
  7570. "Date: %s\r\n"
  7571. "Connection: close\r\n"
  7572. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7573. date);
  7574. mg_printf(conn,
  7575. "<html><head><title>Index of %s</title>"
  7576. "<style>th {text-align: left;}</style></head>"
  7577. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7578. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7579. "<th><a href=\"?d%c\">Modified</a></th>"
  7580. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7581. "<tr><td colspan=\"3\"><hr></td></tr>",
  7582. conn->request_info.local_uri,
  7583. conn->request_info.local_uri,
  7584. sort_direction,
  7585. sort_direction,
  7586. sort_direction);
  7587. /* Print first entry - link to a parent directory */
  7588. mg_printf(conn,
  7589. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7590. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7591. conn->request_info.local_uri,
  7592. "..",
  7593. "Parent directory",
  7594. "-",
  7595. "-");
  7596. /* Sort and print directory entries */
  7597. if (data.entries != NULL) {
  7598. qsort(data.entries,
  7599. (size_t)data.num_entries,
  7600. sizeof(data.entries[0]),
  7601. compare_dir_entries);
  7602. for (i = 0; i < data.num_entries; i++) {
  7603. print_dir_entry(&data.entries[i]);
  7604. mg_free(data.entries[i].file_name);
  7605. }
  7606. mg_free(data.entries);
  7607. }
  7608. mg_printf(conn, "%s", "</table></body></html>");
  7609. conn->status_code = 200;
  7610. }
  7611. /* Send len bytes from the opened file to the client. */
  7612. static void
  7613. send_file_data(struct mg_connection *conn,
  7614. struct mg_file *filep,
  7615. int64_t offset,
  7616. int64_t len)
  7617. {
  7618. char buf[MG_BUF_LEN];
  7619. int to_read, num_read, num_written;
  7620. int64_t size;
  7621. if (!filep || !conn) {
  7622. return;
  7623. }
  7624. /* Sanity check the offset */
  7625. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7626. : (int64_t)(filep->stat.size);
  7627. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7628. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7629. /* file stored in memory */
  7630. if (len > size - offset) {
  7631. len = size - offset;
  7632. }
  7633. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7634. } else if (len > 0 && filep->access.fp != NULL) {
  7635. /* file stored on disk */
  7636. #if defined(__linux__)
  7637. /* sendfile is only available for Linux */
  7638. if ((conn->ssl == 0) && (conn->throttle == 0)
  7639. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  7640. "yes"))) {
  7641. off_t sf_offs = (off_t)offset;
  7642. ssize_t sf_sent;
  7643. int sf_file = fileno(filep->access.fp);
  7644. int loop_cnt = 0;
  7645. do {
  7646. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7647. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7648. size_t sf_tosend =
  7649. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7650. sf_sent =
  7651. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7652. if (sf_sent > 0) {
  7653. len -= sf_sent;
  7654. offset += sf_sent;
  7655. } else if (loop_cnt == 0) {
  7656. /* This file can not be sent using sendfile.
  7657. * This might be the case for pseudo-files in the
  7658. * /sys/ and /proc/ file system.
  7659. * Use the regular user mode copy code instead. */
  7660. break;
  7661. } else if (sf_sent == 0) {
  7662. /* No error, but 0 bytes sent. May be EOF? */
  7663. return;
  7664. }
  7665. loop_cnt++;
  7666. } while ((len > 0) && (sf_sent >= 0));
  7667. if (sf_sent > 0) {
  7668. return; /* OK */
  7669. }
  7670. /* sf_sent<0 means error, thus fall back to the classic way */
  7671. /* This is always the case, if sf_file is not a "normal" file,
  7672. * e.g., for sending data from the output of a CGI process. */
  7673. offset = (int64_t)sf_offs;
  7674. }
  7675. #endif
  7676. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7677. mg_cry_internal(conn,
  7678. "%s: fseeko() failed: %s",
  7679. __func__,
  7680. strerror(ERRNO));
  7681. mg_send_http_error(
  7682. conn,
  7683. 500,
  7684. "%s",
  7685. "Error: Unable to access file at requested position.");
  7686. } else {
  7687. while (len > 0) {
  7688. /* Calculate how much to read from the file in the buffer */
  7689. to_read = sizeof(buf);
  7690. if ((int64_t)to_read > len) {
  7691. to_read = (int)len;
  7692. }
  7693. /* Read from file, exit the loop on error */
  7694. if ((num_read =
  7695. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7696. <= 0) {
  7697. break;
  7698. }
  7699. /* Send read bytes to the client, exit the loop on error */
  7700. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7701. != num_read) {
  7702. break;
  7703. }
  7704. /* Both read and were successful, adjust counters */
  7705. len -= num_written;
  7706. }
  7707. }
  7708. }
  7709. }
  7710. static int
  7711. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7712. {
  7713. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7714. }
  7715. static void
  7716. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7717. {
  7718. if ((filestat != NULL) && (buf != NULL)) {
  7719. mg_snprintf(NULL,
  7720. NULL, /* All calls to construct_etag use 64 byte buffer */
  7721. buf,
  7722. buf_len,
  7723. "\"%lx.%" INT64_FMT "\"",
  7724. (unsigned long)filestat->last_modified,
  7725. filestat->size);
  7726. }
  7727. }
  7728. static void
  7729. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7730. {
  7731. if (filep != NULL && filep->fp != NULL) {
  7732. #ifdef _WIN32
  7733. (void)conn; /* Unused. */
  7734. #else
  7735. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7736. mg_cry_internal(conn,
  7737. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7738. __func__,
  7739. strerror(ERRNO));
  7740. }
  7741. #endif
  7742. }
  7743. }
  7744. static void
  7745. handle_static_file_request(struct mg_connection *conn,
  7746. const char *path,
  7747. struct mg_file *filep,
  7748. const char *mime_type,
  7749. const char *additional_headers)
  7750. {
  7751. char date[64], lm[64], etag[64];
  7752. char range[128]; /* large enough, so there will be no overflow */
  7753. const char *msg = "OK", *hdr;
  7754. time_t curtime = time(NULL);
  7755. int64_t cl, r1, r2;
  7756. struct vec mime_vec;
  7757. int n, truncated;
  7758. char gz_path[PATH_MAX];
  7759. const char *encoding = "";
  7760. const char *cors1, *cors2, *cors3;
  7761. int allow_on_the_fly_compression;
  7762. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  7763. return;
  7764. }
  7765. if (mime_type == NULL) {
  7766. get_mime_type(conn, path, &mime_vec);
  7767. } else {
  7768. mime_vec.ptr = mime_type;
  7769. mime_vec.len = strlen(mime_type);
  7770. }
  7771. if (filep->stat.size > INT64_MAX) {
  7772. mg_send_http_error(conn,
  7773. 500,
  7774. "Error: File size is too large to send\n%" INT64_FMT,
  7775. filep->stat.size);
  7776. return;
  7777. }
  7778. cl = (int64_t)filep->stat.size;
  7779. conn->status_code = 200;
  7780. range[0] = '\0';
  7781. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7782. * it's important to rewrite the filename after resolving
  7783. * the mime type from it, to preserve the actual file's type */
  7784. allow_on_the_fly_compression = conn->accept_gzip;
  7785. if (filep->stat.is_gzipped) {
  7786. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7787. if (truncated) {
  7788. mg_send_http_error(conn,
  7789. 500,
  7790. "Error: Path of zipped file too long (%s)",
  7791. path);
  7792. return;
  7793. }
  7794. path = gz_path;
  7795. encoding = "Content-Encoding: gzip\r\n";
  7796. /* File is already compressed. No "on the fly" compression. */
  7797. allow_on_the_fly_compression = 0;
  7798. }
  7799. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7800. mg_send_http_error(conn,
  7801. 500,
  7802. "Error: Cannot open file\nfopen(%s): %s",
  7803. path,
  7804. strerror(ERRNO));
  7805. return;
  7806. }
  7807. fclose_on_exec(&filep->access, conn);
  7808. /* If Range: header specified, act accordingly */
  7809. r1 = r2 = 0;
  7810. hdr = mg_get_header(conn, "Range");
  7811. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7812. && (r1 >= 0) && (r2 >= 0)) {
  7813. /* actually, range requests don't play well with a pre-gzipped
  7814. * file (since the range is specified in the uncompressed space) */
  7815. if (filep->stat.is_gzipped) {
  7816. mg_send_http_error(
  7817. conn,
  7818. 416, /* 416 = Range Not Satisfiable */
  7819. "%s",
  7820. "Error: Range requests in gzipped files are not supported");
  7821. (void)mg_fclose(
  7822. &filep->access); /* ignore error on read only file */
  7823. return;
  7824. }
  7825. conn->status_code = 206;
  7826. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7827. mg_snprintf(conn,
  7828. NULL, /* range buffer is big enough */
  7829. range,
  7830. sizeof(range),
  7831. "Content-Range: bytes "
  7832. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7833. r1,
  7834. r1 + cl - 1,
  7835. filep->stat.size);
  7836. msg = "Partial Content";
  7837. /* Do not compress ranges. */
  7838. allow_on_the_fly_compression = 0;
  7839. }
  7840. hdr = mg_get_header(conn, "Origin");
  7841. if (hdr) {
  7842. /* Cross-origin resource sharing (CORS), see
  7843. * http://www.html5rocks.com/en/tutorials/cors/,
  7844. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  7845. * -
  7846. * preflight is not supported for files. */
  7847. cors1 = "Access-Control-Allow-Origin: ";
  7848. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7849. cors3 = "\r\n";
  7850. } else {
  7851. cors1 = cors2 = cors3 = "";
  7852. }
  7853. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  7854. * according to
  7855. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7856. gmt_time_string(date, sizeof(date), &curtime);
  7857. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7858. construct_etag(etag, sizeof(etag), &filep->stat);
  7859. /* On the fly compression allowed */
  7860. if (allow_on_the_fly_compression) {
  7861. ;
  7862. /* TODO: add interface to compression module */
  7863. /* e.g., def from https://zlib.net/zlib_how.html */
  7864. /* Check license (zlib has a permissive license, but */
  7865. /* is still not MIT) and use dynamic binding like */
  7866. /* done with OpenSSL */
  7867. /* See #199 (https://github.com/civetweb/civetweb/issues/199) */
  7868. }
  7869. /* Send header */
  7870. (void)mg_printf(conn,
  7871. "HTTP/1.1 %d %s\r\n"
  7872. "%s%s%s"
  7873. "Date: %s\r\n",
  7874. conn->status_code,
  7875. msg,
  7876. cors1,
  7877. cors2,
  7878. cors3,
  7879. date);
  7880. send_static_cache_header(conn);
  7881. send_additional_header(conn);
  7882. (void)mg_printf(conn,
  7883. "Last-Modified: %s\r\n"
  7884. "Etag: %s\r\n"
  7885. "Content-Type: %.*s\r\n"
  7886. "Content-Length: %" INT64_FMT "\r\n"
  7887. "Connection: %s\r\n"
  7888. "Accept-Ranges: bytes\r\n"
  7889. "%s%s",
  7890. lm,
  7891. etag,
  7892. (int)mime_vec.len,
  7893. mime_vec.ptr,
  7894. cl,
  7895. suggest_connection_header(conn),
  7896. range,
  7897. encoding);
  7898. /* The previous code must not add any header starting with X- to make
  7899. * sure no one of the additional_headers is included twice */
  7900. if (additional_headers != NULL) {
  7901. (void)mg_printf(conn,
  7902. "%.*s\r\n\r\n",
  7903. (int)strlen(additional_headers),
  7904. additional_headers);
  7905. } else {
  7906. (void)mg_printf(conn, "\r\n");
  7907. }
  7908. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7909. send_file_data(conn, filep, r1, cl);
  7910. }
  7911. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7912. }
  7913. #if !defined(NO_CACHING)
  7914. /* Return True if we should reply 304 Not Modified. */
  7915. static int
  7916. is_not_modified(const struct mg_connection *conn,
  7917. const struct mg_file_stat *filestat)
  7918. {
  7919. char etag[64];
  7920. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7921. const char *inm = mg_get_header(conn, "If-None-Match");
  7922. construct_etag(etag, sizeof(etag), filestat);
  7923. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  7924. || ((ims != NULL)
  7925. && (filestat->last_modified <= parse_date_string(ims)));
  7926. }
  7927. static void
  7928. handle_not_modified_static_file_request(struct mg_connection *conn,
  7929. struct mg_file *filep)
  7930. {
  7931. char date[64], lm[64], etag[64];
  7932. time_t curtime = time(NULL);
  7933. if ((conn == NULL) || (filep == NULL)) {
  7934. return;
  7935. }
  7936. conn->status_code = 304;
  7937. gmt_time_string(date, sizeof(date), &curtime);
  7938. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7939. construct_etag(etag, sizeof(etag), &filep->stat);
  7940. (void)mg_printf(conn,
  7941. "HTTP/1.1 %d %s\r\n"
  7942. "Date: %s\r\n",
  7943. conn->status_code,
  7944. mg_get_response_code_text(conn, conn->status_code),
  7945. date);
  7946. send_static_cache_header(conn);
  7947. send_additional_header(conn);
  7948. (void)mg_printf(conn,
  7949. "Last-Modified: %s\r\n"
  7950. "Etag: %s\r\n"
  7951. "Connection: %s\r\n"
  7952. "\r\n",
  7953. lm,
  7954. etag,
  7955. suggest_connection_header(conn));
  7956. }
  7957. #endif
  7958. void
  7959. mg_send_file(struct mg_connection *conn, const char *path)
  7960. {
  7961. mg_send_mime_file(conn, path, NULL);
  7962. }
  7963. void
  7964. mg_send_mime_file(struct mg_connection *conn,
  7965. const char *path,
  7966. const char *mime_type)
  7967. {
  7968. mg_send_mime_file2(conn, path, mime_type, NULL);
  7969. }
  7970. void
  7971. mg_send_mime_file2(struct mg_connection *conn,
  7972. const char *path,
  7973. const char *mime_type,
  7974. const char *additional_headers)
  7975. {
  7976. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7977. if (!conn) {
  7978. /* No conn */
  7979. return;
  7980. }
  7981. if (mg_stat(conn, path, &file.stat)) {
  7982. #if !defined(NO_CACHING)
  7983. if (is_not_modified(conn, &file.stat)) {
  7984. /* Send 304 "Not Modified" - this must not send any body data */
  7985. handle_not_modified_static_file_request(conn, &file);
  7986. } else
  7987. #endif /* NO_CACHING */
  7988. if (file.stat.is_directory) {
  7989. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  7990. "yes")) {
  7991. handle_directory_request(conn, path);
  7992. } else {
  7993. mg_send_http_error(conn,
  7994. 403,
  7995. "%s",
  7996. "Error: Directory listing denied");
  7997. }
  7998. } else {
  7999. handle_static_file_request(
  8000. conn, path, &file, mime_type, additional_headers);
  8001. }
  8002. } else {
  8003. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8004. }
  8005. }
  8006. /* For a given PUT path, create all intermediate subdirectories.
  8007. * Return 0 if the path itself is a directory.
  8008. * Return 1 if the path leads to a file.
  8009. * Return -1 for if the path is too long.
  8010. * Return -2 if path can not be created.
  8011. */
  8012. static int
  8013. put_dir(struct mg_connection *conn, const char *path)
  8014. {
  8015. char buf[PATH_MAX];
  8016. const char *s, *p;
  8017. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8018. size_t len;
  8019. int res = 1;
  8020. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8021. len = (size_t)(p - path);
  8022. if (len >= sizeof(buf)) {
  8023. /* path too long */
  8024. res = -1;
  8025. break;
  8026. }
  8027. memcpy(buf, path, len);
  8028. buf[len] = '\0';
  8029. /* Try to create intermediate directory */
  8030. DEBUG_TRACE("mkdir(%s)", buf);
  8031. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8032. /* path does not exixt and can not be created */
  8033. res = -2;
  8034. break;
  8035. }
  8036. /* Is path itself a directory? */
  8037. if (p[1] == '\0') {
  8038. res = 0;
  8039. }
  8040. }
  8041. return res;
  8042. }
  8043. static void
  8044. remove_bad_file(const struct mg_connection *conn, const char *path)
  8045. {
  8046. int r = mg_remove(conn, path);
  8047. if (r != 0) {
  8048. mg_cry_internal(conn,
  8049. "%s: Cannot remove invalid file %s",
  8050. __func__,
  8051. path);
  8052. }
  8053. }
  8054. long long
  8055. mg_store_body(struct mg_connection *conn, const char *path)
  8056. {
  8057. char buf[MG_BUF_LEN];
  8058. long long len = 0;
  8059. int ret, n;
  8060. struct mg_file fi;
  8061. if (conn->consumed_content != 0) {
  8062. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8063. return -11;
  8064. }
  8065. ret = put_dir(conn, path);
  8066. if (ret < 0) {
  8067. /* -1 for path too long,
  8068. * -2 for path can not be created. */
  8069. return ret;
  8070. }
  8071. if (ret != 1) {
  8072. /* Return 0 means, path itself is a directory. */
  8073. return 0;
  8074. }
  8075. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8076. return -12;
  8077. }
  8078. ret = mg_read(conn, buf, sizeof(buf));
  8079. while (ret > 0) {
  8080. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8081. if (n != ret) {
  8082. (void)mg_fclose(
  8083. &fi.access); /* File is bad and will be removed anyway. */
  8084. remove_bad_file(conn, path);
  8085. return -13;
  8086. }
  8087. len += ret;
  8088. ret = mg_read(conn, buf, sizeof(buf));
  8089. }
  8090. /* File is open for writing. If fclose fails, there was probably an
  8091. * error flushing the buffer to disk, so the file on disk might be
  8092. * broken. Delete it and return an error to the caller. */
  8093. if (mg_fclose(&fi.access) != 0) {
  8094. remove_bad_file(conn, path);
  8095. return -14;
  8096. }
  8097. return len;
  8098. }
  8099. /* Parse a buffer:
  8100. * Forward the string pointer till the end of a word, then
  8101. * terminate it and forward till the begin of the next word.
  8102. */
  8103. static int
  8104. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8105. {
  8106. /* Forward until a space is found - use isgraph here */
  8107. /* See http://www.cplusplus.com/reference/cctype/ */
  8108. while (isgraph(**ppw)) {
  8109. (*ppw)++;
  8110. }
  8111. /* Check end of word */
  8112. if (eol) {
  8113. /* must be a end of line */
  8114. if ((**ppw != '\r') && (**ppw != '\n')) {
  8115. return -1;
  8116. }
  8117. } else {
  8118. /* must be a end of a word, but not a line */
  8119. if (**ppw != ' ') {
  8120. return -1;
  8121. }
  8122. }
  8123. /* Terminate and forward to the next word */
  8124. do {
  8125. **ppw = 0;
  8126. (*ppw)++;
  8127. } while ((**ppw) && isspace(**ppw));
  8128. /* Check after term */
  8129. if (!eol) {
  8130. /* if it's not the end of line, there must be a next word */
  8131. if (!isgraph(**ppw)) {
  8132. return -1;
  8133. }
  8134. }
  8135. /* ok */
  8136. return 1;
  8137. }
  8138. /* Parse HTTP headers from the given buffer, advance buf pointer
  8139. * to the point where parsing stopped.
  8140. * All parameters must be valid pointers (not NULL).
  8141. * Return <0 on error. */
  8142. static int
  8143. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8144. {
  8145. int i;
  8146. int num_headers = 0;
  8147. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8148. char *dp = *buf;
  8149. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8150. dp++;
  8151. }
  8152. if (dp == *buf) {
  8153. /* End of headers reached. */
  8154. break;
  8155. }
  8156. if (*dp != ':') {
  8157. /* This is not a valid field. */
  8158. return -1;
  8159. }
  8160. /* End of header key (*dp == ':') */
  8161. /* Truncate here and set the key name */
  8162. *dp = 0;
  8163. hdr[i].name = *buf;
  8164. do {
  8165. dp++;
  8166. } while (*dp == ' ');
  8167. /* The rest of the line is the value */
  8168. hdr[i].value = dp;
  8169. *buf = dp + strcspn(dp, "\r\n");
  8170. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8171. *buf = NULL;
  8172. }
  8173. num_headers = i + 1;
  8174. if (*buf) {
  8175. (*buf)[0] = 0;
  8176. (*buf)[1] = 0;
  8177. *buf += 2;
  8178. } else {
  8179. *buf = dp;
  8180. break;
  8181. }
  8182. if ((*buf)[0] == '\r') {
  8183. /* This is the end of the header */
  8184. break;
  8185. }
  8186. }
  8187. return num_headers;
  8188. }
  8189. struct mg_http_method_info {
  8190. const char *name;
  8191. int request_has_body;
  8192. int response_has_body;
  8193. int is_safe;
  8194. int is_idempotent;
  8195. int is_cacheable;
  8196. };
  8197. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8198. static struct mg_http_method_info http_methods[] = {
  8199. /* HTTP (RFC 2616) */
  8200. {"GET", 0, 1, 1, 1, 1},
  8201. {"POST", 1, 1, 0, 0, 0},
  8202. {"PUT", 1, 0, 0, 1, 0},
  8203. {"DELETE", 0, 0, 0, 1, 0},
  8204. {"HEAD", 0, 0, 1, 1, 1},
  8205. {"OPTIONS", 0, 0, 1, 1, 0},
  8206. {"CONNECT", 1, 1, 0, 0, 0},
  8207. /* TRACE method (RFC 2616) is not supported for security reasons */
  8208. /* PATCH method (RFC 5789) */
  8209. {"PATCH", 1, 0, 0, 0, 0},
  8210. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8211. /* WEBDAV (RFC 2518) */
  8212. {"PROPFIND", 0, 1, 1, 1, 0},
  8213. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8214. * Some PROPFIND results MAY be cached, with care,
  8215. * as there is no cache validation mechanism for
  8216. * most properties. This method is both safe and
  8217. * idempotent (see Section 9.1 of [RFC2616]). */
  8218. {"MKCOL", 0, 0, 0, 1, 0},
  8219. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8220. * When MKCOL is invoked without a request body,
  8221. * the newly created collection SHOULD have no
  8222. * members. A MKCOL request message may contain
  8223. * a message body. The precise behavior of a MKCOL
  8224. * request when the body is present is undefined,
  8225. * ... ==> We do not support MKCOL with body data.
  8226. * This method is idempotent, but not safe (see
  8227. * Section 9.1 of [RFC2616]). Responses to this
  8228. * method MUST NOT be cached. */
  8229. /* Unsupported WEBDAV Methods: */
  8230. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8231. /* + 11 methods from RFC 3253 */
  8232. /* ORDERPATCH (RFC 3648) */
  8233. /* ACL (RFC 3744) */
  8234. /* SEARCH (RFC 5323) */
  8235. /* + MicroSoft extensions
  8236. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8237. /* REPORT method (RFC 3253) */
  8238. {"REPORT", 1, 1, 1, 1, 1},
  8239. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8240. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8241. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8242. * to be useful for REST in case a "GET request with body" is
  8243. * required. */
  8244. {NULL, 0, 0, 0, 0, 0}
  8245. /* end of list */
  8246. };
  8247. static const struct mg_http_method_info *
  8248. get_http_method_info(const char *method)
  8249. {
  8250. /* Check if the method is known to the server. The list of all known
  8251. * HTTP methods can be found here at
  8252. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8253. */
  8254. const struct mg_http_method_info *m = http_methods;
  8255. while (m->name) {
  8256. if (!strcmp(m->name, method)) {
  8257. return m;
  8258. }
  8259. m++;
  8260. }
  8261. return NULL;
  8262. }
  8263. static int
  8264. is_valid_http_method(const char *method)
  8265. {
  8266. return (get_http_method_info(method) != NULL);
  8267. }
  8268. /* Parse HTTP request, fill in mg_request_info structure.
  8269. * This function modifies the buffer by NUL-terminating
  8270. * HTTP request components, header names and header values.
  8271. * Parameters:
  8272. * buf (in/out): pointer to the HTTP header to parse and split
  8273. * len (in): length of HTTP header buffer
  8274. * re (out): parsed header as mg_request_info
  8275. * buf and ri must be valid pointers (not NULL), len>0.
  8276. * Returns <0 on error. */
  8277. static int
  8278. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8279. {
  8280. int request_length;
  8281. int init_skip = 0;
  8282. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8283. * remote_port */
  8284. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8285. NULL;
  8286. ri->num_headers = 0;
  8287. /* RFC says that all initial whitespaces should be ingored */
  8288. /* This included all leading \r and \n (isspace) */
  8289. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8290. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8291. buf++;
  8292. len--;
  8293. init_skip++;
  8294. }
  8295. if (len == 0) {
  8296. /* Incomplete request */
  8297. return 0;
  8298. }
  8299. /* Control characters are not allowed, including zero */
  8300. if (iscntrl(*(unsigned char *)buf)) {
  8301. return -1;
  8302. }
  8303. /* Find end of HTTP header */
  8304. request_length = get_http_header_len(buf, len);
  8305. if (request_length <= 0) {
  8306. return request_length;
  8307. }
  8308. buf[request_length - 1] = '\0';
  8309. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8310. return -1;
  8311. }
  8312. /* The first word has to be the HTTP method */
  8313. ri->request_method = buf;
  8314. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8315. return -1;
  8316. }
  8317. /* Check for a valid http method */
  8318. if (!is_valid_http_method(ri->request_method)) {
  8319. return -1;
  8320. }
  8321. /* The second word is the URI */
  8322. ri->request_uri = buf;
  8323. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8324. return -1;
  8325. }
  8326. /* Next would be the HTTP version */
  8327. ri->http_version = buf;
  8328. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8329. return -1;
  8330. }
  8331. /* Check for a valid HTTP version key */
  8332. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8333. /* Invalid request */
  8334. return -1;
  8335. }
  8336. ri->http_version += 5;
  8337. /* Parse all HTTP headers */
  8338. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8339. if (ri->num_headers < 0) {
  8340. /* Error while parsing headers */
  8341. return -1;
  8342. }
  8343. return request_length + init_skip;
  8344. }
  8345. static int
  8346. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8347. {
  8348. int response_length;
  8349. int init_skip = 0;
  8350. char *tmp, *tmp2;
  8351. long l;
  8352. /* Initialize elements. */
  8353. ri->http_version = ri->status_text = NULL;
  8354. ri->num_headers = ri->status_code = 0;
  8355. /* RFC says that all initial whitespaces should be ingored */
  8356. /* This included all leading \r and \n (isspace) */
  8357. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8358. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8359. buf++;
  8360. len--;
  8361. init_skip++;
  8362. }
  8363. if (len == 0) {
  8364. /* Incomplete request */
  8365. return 0;
  8366. }
  8367. /* Control characters are not allowed, including zero */
  8368. if (iscntrl(*(unsigned char *)buf)) {
  8369. return -1;
  8370. }
  8371. /* Find end of HTTP header */
  8372. response_length = get_http_header_len(buf, len);
  8373. if (response_length <= 0) {
  8374. return response_length;
  8375. }
  8376. buf[response_length - 1] = '\0';
  8377. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8378. return -1;
  8379. }
  8380. /* The first word is the HTTP version */
  8381. /* Check for a valid HTTP version key */
  8382. if (strncmp(buf, "HTTP/", 5) != 0) {
  8383. /* Invalid request */
  8384. return -1;
  8385. }
  8386. buf += 5;
  8387. if (!isgraph(buf[0])) {
  8388. /* Invalid request */
  8389. return -1;
  8390. }
  8391. ri->http_version = buf;
  8392. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8393. return -1;
  8394. }
  8395. /* The second word is the status as a number */
  8396. tmp = buf;
  8397. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8398. return -1;
  8399. }
  8400. l = strtol(tmp, &tmp2, 10);
  8401. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8402. /* Everything else but a 3 digit code is invalid */
  8403. return -1;
  8404. }
  8405. ri->status_code = (int)l;
  8406. /* The rest of the line is the status text */
  8407. ri->status_text = buf;
  8408. /* Find end of status text */
  8409. /* isgraph or isspace = isprint */
  8410. while (isprint(*buf)) {
  8411. buf++;
  8412. }
  8413. if ((*buf != '\r') && (*buf != '\n')) {
  8414. return -1;
  8415. }
  8416. /* Terminate string and forward buf to next line */
  8417. do {
  8418. *buf = 0;
  8419. buf++;
  8420. } while ((*buf) && isspace(*buf));
  8421. /* Parse all HTTP headers */
  8422. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8423. if (ri->num_headers < 0) {
  8424. /* Error while parsing headers */
  8425. return -1;
  8426. }
  8427. return response_length + init_skip;
  8428. }
  8429. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8430. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8431. * buffer (which marks the end of HTTP request). Buffer buf may already
  8432. * have some data. The length of the data is stored in nread.
  8433. * Upon every read operation, increase nread by the number of bytes read. */
  8434. static int
  8435. read_message(FILE *fp,
  8436. struct mg_connection *conn,
  8437. char *buf,
  8438. int bufsiz,
  8439. int *nread)
  8440. {
  8441. int request_len, n = 0;
  8442. struct timespec last_action_time;
  8443. double request_timeout;
  8444. if (!conn) {
  8445. return 0;
  8446. }
  8447. memset(&last_action_time, 0, sizeof(last_action_time));
  8448. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8449. /* value of request_timeout is in seconds, config in milliseconds */
  8450. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8451. } else {
  8452. request_timeout = -1.0;
  8453. }
  8454. if (conn->handled_requests > 0) {
  8455. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8456. request_timeout =
  8457. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8458. }
  8459. }
  8460. request_len = get_http_header_len(buf, *nread);
  8461. /* first time reading from this connection */
  8462. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8463. while (request_len == 0) {
  8464. /* Full request not yet received */
  8465. if (conn->phys_ctx->stop_flag != 0) {
  8466. /* Server is to be stopped. */
  8467. return -1;
  8468. }
  8469. if (*nread >= bufsiz) {
  8470. /* Request too long */
  8471. return -2;
  8472. }
  8473. n = pull_inner(
  8474. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8475. if (n == -2) {
  8476. /* Receive error */
  8477. return -1;
  8478. }
  8479. if (n > 0) {
  8480. *nread += n;
  8481. request_len = get_http_header_len(buf, *nread);
  8482. } else {
  8483. request_len = 0;
  8484. }
  8485. if ((request_len == 0) && (request_timeout >= 0)) {
  8486. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8487. > request_timeout) {
  8488. /* Timeout */
  8489. return -1;
  8490. }
  8491. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8492. }
  8493. }
  8494. return request_len;
  8495. }
  8496. #if !defined(NO_CGI) || !defined(NO_FILES)
  8497. static int
  8498. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8499. {
  8500. const char *expect, *body;
  8501. char buf[MG_BUF_LEN];
  8502. int to_read, nread, success = 0;
  8503. int64_t buffered_len;
  8504. double timeout = -1.0;
  8505. if (!conn) {
  8506. return 0;
  8507. }
  8508. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8509. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8510. }
  8511. expect = mg_get_header(conn, "Expect");
  8512. DEBUG_ASSERT(fp != NULL);
  8513. if (!fp) {
  8514. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8515. return 0;
  8516. }
  8517. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8518. /* Content length is not specified by the client. */
  8519. mg_send_http_error(conn,
  8520. 411,
  8521. "%s",
  8522. "Error: Client did not specify content length");
  8523. } else if ((expect != NULL)
  8524. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8525. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8526. */
  8527. mg_send_http_error(conn,
  8528. 417,
  8529. "Error: Can not fulfill expectation %s",
  8530. expect);
  8531. } else {
  8532. if (expect != NULL) {
  8533. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8534. conn->status_code = 100;
  8535. } else {
  8536. conn->status_code = 200;
  8537. }
  8538. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8539. - conn->consumed_content;
  8540. DEBUG_ASSERT(buffered_len >= 0);
  8541. DEBUG_ASSERT(conn->consumed_content == 0);
  8542. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8543. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8544. return 0;
  8545. }
  8546. if (buffered_len > 0) {
  8547. if ((int64_t)buffered_len > conn->content_len) {
  8548. buffered_len = (int)conn->content_len;
  8549. }
  8550. body = conn->buf + conn->request_len + conn->consumed_content;
  8551. push_all(
  8552. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8553. conn->consumed_content += buffered_len;
  8554. }
  8555. nread = 0;
  8556. while (conn->consumed_content < conn->content_len) {
  8557. to_read = sizeof(buf);
  8558. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8559. to_read = (int)(conn->content_len - conn->consumed_content);
  8560. }
  8561. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8562. if (nread == -2) {
  8563. /* error */
  8564. break;
  8565. }
  8566. if (nread > 0) {
  8567. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  8568. != nread) {
  8569. break;
  8570. }
  8571. }
  8572. conn->consumed_content += nread;
  8573. }
  8574. if (conn->consumed_content == conn->content_len) {
  8575. success = (nread >= 0);
  8576. }
  8577. /* Each error code path in this function must send an error */
  8578. if (!success) {
  8579. /* NOTE: Maybe some data has already been sent. */
  8580. /* TODO (low): If some data has been sent, a correct error
  8581. * reply can no longer be sent, so just close the connection */
  8582. mg_send_http_error(conn, 500, "%s", "");
  8583. }
  8584. }
  8585. return success;
  8586. }
  8587. #endif
  8588. #if !defined(NO_CGI)
  8589. /* This structure helps to create an environment for the spawned CGI
  8590. * program.
  8591. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8592. * last element must be NULL.
  8593. * However, on Windows there is a requirement that all these
  8594. * VARIABLE=VALUE\0
  8595. * strings must reside in a contiguous buffer. The end of the buffer is
  8596. * marked by two '\0' characters.
  8597. * We satisfy both worlds: we create an envp array (which is vars), all
  8598. * entries are actually pointers inside buf. */
  8599. struct cgi_environment {
  8600. struct mg_connection *conn;
  8601. /* Data block */
  8602. char *buf; /* Environment buffer */
  8603. size_t buflen; /* Space available in buf */
  8604. size_t bufused; /* Space taken in buf */
  8605. /* Index block */
  8606. char **var; /* char **envp */
  8607. size_t varlen; /* Number of variables available in var */
  8608. size_t varused; /* Number of variables stored in var */
  8609. };
  8610. static void addenv(struct cgi_environment *env,
  8611. PRINTF_FORMAT_STRING(const char *fmt),
  8612. ...) PRINTF_ARGS(2, 3);
  8613. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8614. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8615. static void
  8616. addenv(struct cgi_environment *env, const char *fmt, ...)
  8617. {
  8618. size_t n, space;
  8619. int truncated = 0;
  8620. char *added;
  8621. va_list ap;
  8622. /* Calculate how much space is left in the buffer */
  8623. space = (env->buflen - env->bufused);
  8624. /* Calculate an estimate for the required space */
  8625. n = strlen(fmt) + 2 + 128;
  8626. do {
  8627. if (space <= n) {
  8628. /* Allocate new buffer */
  8629. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  8630. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  8631. if (!added) {
  8632. /* Out of memory */
  8633. mg_cry_internal(
  8634. env->conn,
  8635. "%s: Cannot allocate memory for CGI variable [%s]",
  8636. __func__,
  8637. fmt);
  8638. return;
  8639. }
  8640. env->buf = added;
  8641. env->buflen = n;
  8642. space = (env->buflen - env->bufused);
  8643. }
  8644. /* Make a pointer to the free space int the buffer */
  8645. added = env->buf + env->bufused;
  8646. /* Copy VARIABLE=VALUE\0 string into the free space */
  8647. va_start(ap, fmt);
  8648. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  8649. va_end(ap);
  8650. /* Do not add truncated strings to the environment */
  8651. if (truncated) {
  8652. /* Reallocate the buffer */
  8653. space = 0;
  8654. n = 1;
  8655. }
  8656. } while (truncated);
  8657. /* Calculate number of bytes added to the environment */
  8658. n = strlen(added) + 1;
  8659. env->bufused += n;
  8660. /* Now update the variable index */
  8661. space = (env->varlen - env->varused);
  8662. if (space < 2) {
  8663. mg_cry_internal(env->conn,
  8664. "%s: Cannot register CGI variable [%s]",
  8665. __func__,
  8666. fmt);
  8667. return;
  8668. }
  8669. /* Append a pointer to the added string into the envp array */
  8670. env->var[env->varused] = added;
  8671. env->varused++;
  8672. }
  8673. /* Return 0 on success, non-zero if an error occurs. */
  8674. static int
  8675. prepare_cgi_environment(struct mg_connection *conn,
  8676. const char *prog,
  8677. struct cgi_environment *env)
  8678. {
  8679. const char *s;
  8680. struct vec var_vec;
  8681. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8682. int i, truncated, uri_len;
  8683. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8684. return -1;
  8685. }
  8686. env->conn = conn;
  8687. env->buflen = CGI_ENVIRONMENT_SIZE;
  8688. env->bufused = 0;
  8689. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  8690. if (env->buf == NULL) {
  8691. mg_cry_internal(conn,
  8692. "%s: Not enough memory for environmental buffer",
  8693. __func__);
  8694. return -1;
  8695. }
  8696. env->varlen = MAX_CGI_ENVIR_VARS;
  8697. env->varused = 0;
  8698. env->var =
  8699. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  8700. if (env->var == NULL) {
  8701. mg_cry_internal(conn,
  8702. "%s: Not enough memory for environmental variables",
  8703. __func__);
  8704. mg_free(env->buf);
  8705. return -1;
  8706. }
  8707. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  8708. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8709. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8710. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  8711. /* Prepare the environment block */
  8712. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8713. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8714. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8715. #if defined(USE_IPV6)
  8716. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8717. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8718. } else
  8719. #endif
  8720. {
  8721. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8722. }
  8723. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8724. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8725. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8726. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8727. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8728. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8729. /* SCRIPT_NAME */
  8730. uri_len = (int)strlen(conn->request_info.local_uri);
  8731. if (conn->path_info == NULL) {
  8732. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8733. /* URI: /path_to_script/script.cgi */
  8734. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8735. } else {
  8736. /* URI: /path_to_script/ ... using index.cgi */
  8737. const char *index_file = strrchr(prog, '/');
  8738. if (index_file) {
  8739. addenv(env,
  8740. "SCRIPT_NAME=%s%s",
  8741. conn->request_info.local_uri,
  8742. index_file + 1);
  8743. }
  8744. }
  8745. } else {
  8746. /* URI: /path_to_script/script.cgi/path_info */
  8747. addenv(env,
  8748. "SCRIPT_NAME=%.*s",
  8749. uri_len - (int)strlen(conn->path_info),
  8750. conn->request_info.local_uri);
  8751. }
  8752. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8753. if (conn->path_info == NULL) {
  8754. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8755. } else {
  8756. addenv(env,
  8757. "PATH_TRANSLATED=%s%s",
  8758. conn->dom_ctx->config[DOCUMENT_ROOT],
  8759. conn->path_info);
  8760. }
  8761. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8762. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8763. addenv(env, "CONTENT_TYPE=%s", s);
  8764. }
  8765. if (conn->request_info.query_string != NULL) {
  8766. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8767. }
  8768. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8769. addenv(env, "CONTENT_LENGTH=%s", s);
  8770. }
  8771. if ((s = getenv("PATH")) != NULL) {
  8772. addenv(env, "PATH=%s", s);
  8773. }
  8774. if (conn->path_info != NULL) {
  8775. addenv(env, "PATH_INFO=%s", conn->path_info);
  8776. }
  8777. if (conn->status_code > 0) {
  8778. /* CGI error handler should show the status code */
  8779. addenv(env, "STATUS=%d", conn->status_code);
  8780. }
  8781. #if defined(_WIN32)
  8782. if ((s = getenv("COMSPEC")) != NULL) {
  8783. addenv(env, "COMSPEC=%s", s);
  8784. }
  8785. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8786. addenv(env, "SYSTEMROOT=%s", s);
  8787. }
  8788. if ((s = getenv("SystemDrive")) != NULL) {
  8789. addenv(env, "SystemDrive=%s", s);
  8790. }
  8791. if ((s = getenv("ProgramFiles")) != NULL) {
  8792. addenv(env, "ProgramFiles=%s", s);
  8793. }
  8794. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8795. addenv(env, "ProgramFiles(x86)=%s", s);
  8796. }
  8797. #else
  8798. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8799. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8800. }
  8801. #endif /* _WIN32 */
  8802. if ((s = getenv("PERLLIB")) != NULL) {
  8803. addenv(env, "PERLLIB=%s", s);
  8804. }
  8805. if (conn->request_info.remote_user != NULL) {
  8806. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8807. addenv(env, "%s", "AUTH_TYPE=Digest");
  8808. }
  8809. /* Add all headers as HTTP_* variables */
  8810. for (i = 0; i < conn->request_info.num_headers; i++) {
  8811. (void)mg_snprintf(conn,
  8812. &truncated,
  8813. http_var_name,
  8814. sizeof(http_var_name),
  8815. "HTTP_%s",
  8816. conn->request_info.http_headers[i].name);
  8817. if (truncated) {
  8818. mg_cry_internal(conn,
  8819. "%s: HTTP header variable too long [%s]",
  8820. __func__,
  8821. conn->request_info.http_headers[i].name);
  8822. continue;
  8823. }
  8824. /* Convert variable name into uppercase, and change - to _ */
  8825. for (p = http_var_name; *p != '\0'; p++) {
  8826. if (*p == '-') {
  8827. *p = '_';
  8828. }
  8829. *p = (char)toupper(*(unsigned char *)p);
  8830. }
  8831. addenv(env,
  8832. "%s=%s",
  8833. http_var_name,
  8834. conn->request_info.http_headers[i].value);
  8835. }
  8836. /* Add user-specified variables */
  8837. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  8838. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  8839. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  8840. }
  8841. env->var[env->varused] = NULL;
  8842. env->buf[env->bufused] = '\0';
  8843. return 0;
  8844. }
  8845. static void
  8846. handle_cgi_request(struct mg_connection *conn, const char *prog)
  8847. {
  8848. char *buf;
  8849. size_t buflen;
  8850. int headers_len, data_len, i, truncated;
  8851. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  8852. const char *status, *status_text, *connection_state;
  8853. char *pbuf, dir[PATH_MAX], *p;
  8854. struct mg_request_info ri;
  8855. struct cgi_environment blk;
  8856. FILE *in = NULL, *out = NULL, *err = NULL;
  8857. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  8858. pid_t pid = (pid_t)-1;
  8859. if (conn == NULL) {
  8860. return;
  8861. }
  8862. buf = NULL;
  8863. buflen = 16384;
  8864. i = prepare_cgi_environment(conn, prog, &blk);
  8865. if (i != 0) {
  8866. blk.buf = NULL;
  8867. blk.var = NULL;
  8868. goto done;
  8869. }
  8870. /* CGI must be executed in its own directory. 'dir' must point to the
  8871. * directory containing executable program, 'p' must point to the
  8872. * executable program name relative to 'dir'. */
  8873. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  8874. if (truncated) {
  8875. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  8876. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  8877. goto done;
  8878. }
  8879. if ((p = strrchr(dir, '/')) != NULL) {
  8880. *p++ = '\0';
  8881. } else {
  8882. dir[0] = '.';
  8883. dir[1] = '\0';
  8884. p = (char *)prog;
  8885. }
  8886. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  8887. status = strerror(ERRNO);
  8888. mg_cry_internal(
  8889. conn,
  8890. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  8891. prog,
  8892. status);
  8893. mg_send_http_error(conn,
  8894. 500,
  8895. "Error: Cannot create CGI pipe: %s",
  8896. status);
  8897. goto done;
  8898. }
  8899. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  8900. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  8901. if (pid == (pid_t)-1) {
  8902. status = strerror(ERRNO);
  8903. mg_cry_internal(
  8904. conn,
  8905. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  8906. prog,
  8907. status);
  8908. mg_send_http_error(conn,
  8909. 500,
  8910. "Error: Cannot spawn CGI process [%s]: %s",
  8911. prog,
  8912. status);
  8913. goto done;
  8914. }
  8915. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  8916. */
  8917. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  8918. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  8919. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  8920. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  8921. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  8922. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  8923. /* Parent closes only one side of the pipes.
  8924. * If we don't mark them as closed, close() attempt before
  8925. * return from this function throws an exception on Windows.
  8926. * Windows does not like when closed descriptor is closed again. */
  8927. (void)close(fdin[0]);
  8928. (void)close(fdout[1]);
  8929. (void)close(fderr[1]);
  8930. fdin[0] = fdout[1] = fderr[1] = -1;
  8931. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  8932. status = strerror(ERRNO);
  8933. mg_cry_internal(conn,
  8934. "Error: CGI program \"%s\": Can not open stdin: %s",
  8935. prog,
  8936. status);
  8937. mg_send_http_error(conn,
  8938. 500,
  8939. "Error: CGI can not open fdin\nfopen: %s",
  8940. status);
  8941. goto done;
  8942. }
  8943. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  8944. status = strerror(ERRNO);
  8945. mg_cry_internal(conn,
  8946. "Error: CGI program \"%s\": Can not open stdout: %s",
  8947. prog,
  8948. status);
  8949. mg_send_http_error(conn,
  8950. 500,
  8951. "Error: CGI can not open fdout\nfopen: %s",
  8952. status);
  8953. goto done;
  8954. }
  8955. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  8956. status = strerror(ERRNO);
  8957. mg_cry_internal(conn,
  8958. "Error: CGI program \"%s\": Can not open stderr: %s",
  8959. prog,
  8960. status);
  8961. mg_send_http_error(conn,
  8962. 500,
  8963. "Error: CGI can not open fdout\nfopen: %s",
  8964. status);
  8965. goto done;
  8966. }
  8967. setbuf(in, NULL);
  8968. setbuf(out, NULL);
  8969. setbuf(err, NULL);
  8970. fout.access.fp = out;
  8971. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  8972. DEBUG_TRACE("CGI: send body data (%lli)\n",
  8973. (signed long long)conn->request_info.content_length);
  8974. /* This is a POST/PUT request, or another request with body data. */
  8975. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  8976. /* Error sending the body data */
  8977. mg_cry_internal(
  8978. conn,
  8979. "Error: CGI program \"%s\": Forward body data failed",
  8980. prog);
  8981. goto done;
  8982. }
  8983. }
  8984. /* Close so child gets an EOF. */
  8985. fclose(in);
  8986. in = NULL;
  8987. fdin[1] = -1;
  8988. /* Now read CGI reply into a buffer. We need to set correct
  8989. * status code, thus we need to see all HTTP headers first.
  8990. * Do not send anything back to client, until we buffer in all
  8991. * HTTP headers. */
  8992. data_len = 0;
  8993. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  8994. if (buf == NULL) {
  8995. mg_send_http_error(conn,
  8996. 500,
  8997. "Error: Not enough memory for CGI buffer (%u bytes)",
  8998. (unsigned int)buflen);
  8999. mg_cry_internal(
  9000. conn,
  9001. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9002. "bytes)",
  9003. prog,
  9004. (unsigned int)buflen);
  9005. goto done;
  9006. }
  9007. DEBUG_TRACE("CGI: %s", "wait for response");
  9008. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9009. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9010. if (headers_len <= 0) {
  9011. /* Could not parse the CGI response. Check if some error message on
  9012. * stderr. */
  9013. i = pull_all(err, conn, buf, (int)buflen);
  9014. if (i > 0) {
  9015. mg_cry_internal(conn,
  9016. "Error: CGI program \"%s\" sent error "
  9017. "message: [%.*s]",
  9018. prog,
  9019. i,
  9020. buf);
  9021. mg_send_http_error(conn,
  9022. 500,
  9023. "Error: CGI program \"%s\" sent error "
  9024. "message: [%.*s]",
  9025. prog,
  9026. i,
  9027. buf);
  9028. } else {
  9029. mg_cry_internal(conn,
  9030. "Error: CGI program sent malformed or too big "
  9031. "(>%u bytes) HTTP headers: [%.*s]",
  9032. (unsigned)buflen,
  9033. data_len,
  9034. buf);
  9035. mg_send_http_error(conn,
  9036. 500,
  9037. "Error: CGI program sent malformed or too big "
  9038. "(>%u bytes) HTTP headers: [%.*s]",
  9039. (unsigned)buflen,
  9040. data_len,
  9041. buf);
  9042. }
  9043. goto done;
  9044. }
  9045. pbuf = buf;
  9046. buf[headers_len - 1] = '\0';
  9047. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9048. /* Make up and send the status line */
  9049. status_text = "OK";
  9050. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9051. != NULL) {
  9052. conn->status_code = atoi(status);
  9053. status_text = status;
  9054. while (isdigit(*(const unsigned char *)status_text)
  9055. || *status_text == ' ') {
  9056. status_text++;
  9057. }
  9058. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9059. != NULL) {
  9060. conn->status_code = 302;
  9061. } else {
  9062. conn->status_code = 200;
  9063. }
  9064. connection_state =
  9065. get_header(ri.http_headers, ri.num_headers, "Connection");
  9066. if (!header_has_option(connection_state, "keep-alive")) {
  9067. conn->must_close = 1;
  9068. }
  9069. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9070. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9071. /* Send headers */
  9072. for (i = 0; i < ri.num_headers; i++) {
  9073. mg_printf(conn,
  9074. "%s: %s\r\n",
  9075. ri.http_headers[i].name,
  9076. ri.http_headers[i].value);
  9077. }
  9078. mg_write(conn, "\r\n", 2);
  9079. /* Send chunk of data that may have been read after the headers */
  9080. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9081. /* Read the rest of CGI output and send to the client */
  9082. send_file_data(conn, &fout, 0, INT64_MAX);
  9083. DEBUG_TRACE("CGI: %s", "all data sent");
  9084. done:
  9085. mg_free(blk.var);
  9086. mg_free(blk.buf);
  9087. if (pid != (pid_t)-1) {
  9088. kill(pid, SIGKILL);
  9089. #if !defined(_WIN32)
  9090. {
  9091. int st;
  9092. while (waitpid(pid, &st, 0) != -1)
  9093. ; /* clean zombies */
  9094. }
  9095. #endif
  9096. }
  9097. if (fdin[0] != -1) {
  9098. close(fdin[0]);
  9099. }
  9100. if (fdout[1] != -1) {
  9101. close(fdout[1]);
  9102. }
  9103. if (in != NULL) {
  9104. fclose(in);
  9105. } else if (fdin[1] != -1) {
  9106. close(fdin[1]);
  9107. }
  9108. if (out != NULL) {
  9109. fclose(out);
  9110. } else if (fdout[0] != -1) {
  9111. close(fdout[0]);
  9112. }
  9113. if (err != NULL) {
  9114. fclose(err);
  9115. } else if (fderr[0] != -1) {
  9116. close(fderr[0]);
  9117. }
  9118. if (buf != NULL) {
  9119. mg_free(buf);
  9120. }
  9121. }
  9122. #endif /* !NO_CGI */
  9123. #if !defined(NO_FILES)
  9124. static void
  9125. mkcol(struct mg_connection *conn, const char *path)
  9126. {
  9127. int rc, body_len;
  9128. struct de de;
  9129. char date[64];
  9130. time_t curtime = time(NULL);
  9131. if (conn == NULL) {
  9132. return;
  9133. }
  9134. /* TODO (mid): Check the mg_send_http_error situations in this function
  9135. */
  9136. memset(&de.file, 0, sizeof(de.file));
  9137. if (!mg_stat(conn, path, &de.file)) {
  9138. mg_cry_internal(conn,
  9139. "%s: mg_stat(%s) failed: %s",
  9140. __func__,
  9141. path,
  9142. strerror(ERRNO));
  9143. }
  9144. if (de.file.last_modified) {
  9145. /* TODO (mid): This check does not seem to make any sense ! */
  9146. /* TODO (mid): Add a webdav unit test first, before changing
  9147. * anything here. */
  9148. mg_send_http_error(
  9149. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9150. return;
  9151. }
  9152. body_len = conn->data_len - conn->request_len;
  9153. if (body_len > 0) {
  9154. mg_send_http_error(
  9155. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9156. return;
  9157. }
  9158. rc = mg_mkdir(conn, path, 0755);
  9159. if (rc == 0) {
  9160. conn->status_code = 201;
  9161. gmt_time_string(date, sizeof(date), &curtime);
  9162. mg_printf(conn,
  9163. "HTTP/1.1 %d Created\r\n"
  9164. "Date: %s\r\n",
  9165. conn->status_code,
  9166. date);
  9167. send_static_cache_header(conn);
  9168. send_additional_header(conn);
  9169. mg_printf(conn,
  9170. "Content-Length: 0\r\n"
  9171. "Connection: %s\r\n\r\n",
  9172. suggest_connection_header(conn));
  9173. } else if (rc == -1) {
  9174. if (errno == EEXIST) {
  9175. mg_send_http_error(
  9176. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9177. } else if (errno == EACCES) {
  9178. mg_send_http_error(
  9179. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9180. } else if (errno == ENOENT) {
  9181. mg_send_http_error(
  9182. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9183. } else {
  9184. mg_send_http_error(
  9185. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9186. }
  9187. }
  9188. }
  9189. static void
  9190. put_file(struct mg_connection *conn, const char *path)
  9191. {
  9192. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9193. const char *range;
  9194. int64_t r1, r2;
  9195. int rc;
  9196. char date[64];
  9197. time_t curtime = time(NULL);
  9198. if (conn == NULL) {
  9199. return;
  9200. }
  9201. if (mg_stat(conn, path, &file.stat)) {
  9202. /* File already exists */
  9203. conn->status_code = 200;
  9204. if (file.stat.is_directory) {
  9205. /* This is an already existing directory,
  9206. * so there is nothing to do for the server. */
  9207. rc = 0;
  9208. } else {
  9209. /* File exists and is not a directory. */
  9210. /* Can it be replaced? */
  9211. if (file.access.membuf != NULL) {
  9212. /* This is an "in-memory" file, that can not be replaced */
  9213. mg_send_http_error(conn,
  9214. 405,
  9215. "Error: Put not possible\nReplacing %s "
  9216. "is not supported",
  9217. path);
  9218. return;
  9219. }
  9220. /* Check if the server may write this file */
  9221. if (access(path, W_OK) == 0) {
  9222. /* Access granted */
  9223. conn->status_code = 200;
  9224. rc = 1;
  9225. } else {
  9226. mg_send_http_error(
  9227. conn,
  9228. 403,
  9229. "Error: Put not possible\nReplacing %s is not allowed",
  9230. path);
  9231. return;
  9232. }
  9233. }
  9234. } else {
  9235. /* File should be created */
  9236. conn->status_code = 201;
  9237. rc = put_dir(conn, path);
  9238. }
  9239. if (rc == 0) {
  9240. /* put_dir returns 0 if path is a directory */
  9241. gmt_time_string(date, sizeof(date), &curtime);
  9242. mg_printf(conn,
  9243. "HTTP/1.1 %d %s\r\n",
  9244. conn->status_code,
  9245. mg_get_response_code_text(NULL, conn->status_code));
  9246. send_no_cache_header(conn);
  9247. send_additional_header(conn);
  9248. mg_printf(conn,
  9249. "Date: %s\r\n"
  9250. "Content-Length: 0\r\n"
  9251. "Connection: %s\r\n\r\n",
  9252. date,
  9253. suggest_connection_header(conn));
  9254. /* Request to create a directory has been fulfilled successfully.
  9255. * No need to put a file. */
  9256. return;
  9257. }
  9258. if (rc == -1) {
  9259. /* put_dir returns -1 if the path is too long */
  9260. mg_send_http_error(conn,
  9261. 414,
  9262. "Error: Path too long\nput_dir(%s): %s",
  9263. path,
  9264. strerror(ERRNO));
  9265. return;
  9266. }
  9267. if (rc == -2) {
  9268. /* put_dir returns -2 if the directory can not be created */
  9269. mg_send_http_error(conn,
  9270. 500,
  9271. "Error: Can not create directory\nput_dir(%s): %s",
  9272. path,
  9273. strerror(ERRNO));
  9274. return;
  9275. }
  9276. /* A file should be created or overwritten. */
  9277. /* Currently CivetWeb does not nead read+write access. */
  9278. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9279. || file.access.fp == NULL) {
  9280. (void)mg_fclose(&file.access);
  9281. mg_send_http_error(conn,
  9282. 500,
  9283. "Error: Can not create file\nfopen(%s): %s",
  9284. path,
  9285. strerror(ERRNO));
  9286. return;
  9287. }
  9288. fclose_on_exec(&file.access, conn);
  9289. range = mg_get_header(conn, "Content-Range");
  9290. r1 = r2 = 0;
  9291. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9292. conn->status_code = 206; /* Partial content */
  9293. fseeko(file.access.fp, r1, SEEK_SET);
  9294. }
  9295. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9296. /* forward_body_data failed.
  9297. * The error code has already been sent to the client,
  9298. * and conn->status_code is already set. */
  9299. (void)mg_fclose(&file.access);
  9300. return;
  9301. }
  9302. if (mg_fclose(&file.access) != 0) {
  9303. /* fclose failed. This might have different reasons, but a likely
  9304. * one is "no space on disk", http 507. */
  9305. conn->status_code = 507;
  9306. }
  9307. gmt_time_string(date, sizeof(date), &curtime);
  9308. mg_printf(conn,
  9309. "HTTP/1.1 %d %s\r\n",
  9310. conn->status_code,
  9311. mg_get_response_code_text(NULL, conn->status_code));
  9312. send_no_cache_header(conn);
  9313. send_additional_header(conn);
  9314. mg_printf(conn,
  9315. "Date: %s\r\n"
  9316. "Content-Length: 0\r\n"
  9317. "Connection: %s\r\n\r\n",
  9318. date,
  9319. suggest_connection_header(conn));
  9320. }
  9321. static void
  9322. delete_file(struct mg_connection *conn, const char *path)
  9323. {
  9324. struct de de;
  9325. memset(&de.file, 0, sizeof(de.file));
  9326. if (!mg_stat(conn, path, &de.file)) {
  9327. /* mg_stat returns 0 if the file does not exist */
  9328. mg_send_http_error(conn,
  9329. 404,
  9330. "Error: Cannot delete file\nFile %s not found",
  9331. path);
  9332. return;
  9333. }
  9334. #if 0 /* Ignore if a file in memory is inside a folder */
  9335. if (de.access.membuf != NULL) {
  9336. /* the file is cached in memory */
  9337. mg_send_http_error(
  9338. conn,
  9339. 405,
  9340. "Error: Delete not possible\nDeleting %s is not supported",
  9341. path);
  9342. return;
  9343. }
  9344. #endif
  9345. if (de.file.is_directory) {
  9346. if (remove_directory(conn, path)) {
  9347. /* Delete is successful: Return 204 without content. */
  9348. mg_send_http_error(conn, 204, "%s", "");
  9349. } else {
  9350. /* Delete is not successful: Return 500 (Server error). */
  9351. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9352. }
  9353. return;
  9354. }
  9355. /* This is an existing file (not a directory).
  9356. * Check if write permission is granted. */
  9357. if (access(path, W_OK) != 0) {
  9358. /* File is read only */
  9359. mg_send_http_error(
  9360. conn,
  9361. 403,
  9362. "Error: Delete not possible\nDeleting %s is not allowed",
  9363. path);
  9364. return;
  9365. }
  9366. /* Try to delete it. */
  9367. if (mg_remove(conn, path) == 0) {
  9368. /* Delete was successful: Return 204 without content. */
  9369. mg_send_http_error(conn, 204, "%s", "");
  9370. } else {
  9371. /* Delete not successful (file locked). */
  9372. mg_send_http_error(conn,
  9373. 423,
  9374. "Error: Cannot delete file\nremove(%s): %s",
  9375. path,
  9376. strerror(ERRNO));
  9377. }
  9378. }
  9379. #endif /* !NO_FILES */
  9380. static void
  9381. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9382. static void
  9383. do_ssi_include(struct mg_connection *conn,
  9384. const char *ssi,
  9385. char *tag,
  9386. int include_level)
  9387. {
  9388. char file_name[MG_BUF_LEN], path[512], *p;
  9389. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9390. size_t len;
  9391. int truncated = 0;
  9392. if (conn == NULL) {
  9393. return;
  9394. }
  9395. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9396. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9397. * always < MG_BUF_LEN. */
  9398. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9399. /* File name is relative to the webserver root */
  9400. file_name[511] = 0;
  9401. (void)mg_snprintf(conn,
  9402. &truncated,
  9403. path,
  9404. sizeof(path),
  9405. "%s/%s",
  9406. conn->dom_ctx->config[DOCUMENT_ROOT],
  9407. file_name);
  9408. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9409. /* File name is relative to the webserver working directory
  9410. * or it is absolute system path */
  9411. file_name[511] = 0;
  9412. (void)
  9413. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9414. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9415. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9416. /* File name is relative to the currect document */
  9417. file_name[511] = 0;
  9418. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9419. if (!truncated) {
  9420. if ((p = strrchr(path, '/')) != NULL) {
  9421. p[1] = '\0';
  9422. }
  9423. len = strlen(path);
  9424. (void)mg_snprintf(conn,
  9425. &truncated,
  9426. path + len,
  9427. sizeof(path) - len,
  9428. "%s",
  9429. file_name);
  9430. }
  9431. } else {
  9432. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9433. return;
  9434. }
  9435. if (truncated) {
  9436. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9437. return;
  9438. }
  9439. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9440. mg_cry_internal(conn,
  9441. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9442. tag,
  9443. path,
  9444. strerror(ERRNO));
  9445. } else {
  9446. fclose_on_exec(&file.access, conn);
  9447. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9448. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9449. path) > 0) {
  9450. send_ssi_file(conn, path, &file, include_level + 1);
  9451. } else {
  9452. send_file_data(conn, &file, 0, INT64_MAX);
  9453. }
  9454. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9455. }
  9456. }
  9457. #if !defined(NO_POPEN)
  9458. static void
  9459. do_ssi_exec(struct mg_connection *conn, char *tag)
  9460. {
  9461. char cmd[1024] = "";
  9462. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9463. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9464. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  9465. } else {
  9466. cmd[1023] = 0;
  9467. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9468. mg_cry_internal(conn,
  9469. "Cannot SSI #exec: [%s]: %s",
  9470. cmd,
  9471. strerror(ERRNO));
  9472. } else {
  9473. send_file_data(conn, &file, 0, INT64_MAX);
  9474. pclose(file.access.fp);
  9475. }
  9476. }
  9477. }
  9478. #endif /* !NO_POPEN */
  9479. static int
  9480. mg_fgetc(struct mg_file *filep, int offset)
  9481. {
  9482. if (filep == NULL) {
  9483. return EOF;
  9484. }
  9485. if ((filep->access.membuf != NULL) && (offset >= 0)
  9486. && (((unsigned int)(offset)) < filep->stat.size)) {
  9487. return ((const unsigned char *)filep->access.membuf)[offset];
  9488. } else if (filep->access.fp != NULL) {
  9489. return fgetc(filep->access.fp);
  9490. } else {
  9491. return EOF;
  9492. }
  9493. }
  9494. static void
  9495. send_ssi_file(struct mg_connection *conn,
  9496. const char *path,
  9497. struct mg_file *filep,
  9498. int include_level)
  9499. {
  9500. char buf[MG_BUF_LEN];
  9501. int ch, offset, len, in_tag, in_ssi_tag;
  9502. if (include_level > 10) {
  9503. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  9504. return;
  9505. }
  9506. in_tag = in_ssi_tag = len = offset = 0;
  9507. /* Read file, byte by byte, and look for SSI include tags */
  9508. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9509. if (in_tag) {
  9510. /* We are in a tag, either SSI tag or html tag */
  9511. if (ch == '>') {
  9512. /* Tag is closing */
  9513. buf[len++] = '>';
  9514. if (in_ssi_tag) {
  9515. /* Handle SSI tag */
  9516. buf[len] = 0;
  9517. if (!memcmp(buf + 5, "include", 7)) {
  9518. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9519. #if !defined(NO_POPEN)
  9520. } else if (!memcmp(buf + 5, "exec", 4)) {
  9521. do_ssi_exec(conn, buf + 9);
  9522. #endif /* !NO_POPEN */
  9523. } else {
  9524. mg_cry_internal(conn,
  9525. "%s: unknown SSI "
  9526. "command: \"%s\"",
  9527. path,
  9528. buf);
  9529. }
  9530. len = 0;
  9531. in_ssi_tag = in_tag = 0;
  9532. } else {
  9533. /* Not an SSI tag */
  9534. /* Flush buffer */
  9535. (void)mg_write(conn, buf, (size_t)len);
  9536. len = 0;
  9537. in_tag = 0;
  9538. }
  9539. } else {
  9540. /* Tag is still open */
  9541. buf[len++] = (char)(ch & 0xff);
  9542. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9543. /* All SSI tags start with <!--# */
  9544. in_ssi_tag = 1;
  9545. }
  9546. if ((len + 2) > (int)sizeof(buf)) {
  9547. /* Tag to long for buffer */
  9548. mg_cry_internal(conn, "%s: tag is too large", path);
  9549. return;
  9550. }
  9551. }
  9552. } else {
  9553. /* We are not in a tag yet. */
  9554. if (ch == '<') {
  9555. /* Tag is opening */
  9556. in_tag = 1;
  9557. /* Flush current buffer */
  9558. (void)mg_write(conn, buf, (size_t)len);
  9559. /* Store the < */
  9560. len = 1;
  9561. buf[0] = '<';
  9562. } else {
  9563. /* No Tag */
  9564. /* Add data to buffer */
  9565. buf[len++] = (char)(ch & 0xff);
  9566. /* Flush if buffer is full */
  9567. if (len == (int)sizeof(buf)) {
  9568. mg_write(conn, buf, (size_t)len);
  9569. len = 0;
  9570. }
  9571. }
  9572. }
  9573. }
  9574. /* Send the rest of buffered data */
  9575. if (len > 0) {
  9576. mg_write(conn, buf, (size_t)len);
  9577. }
  9578. }
  9579. static void
  9580. handle_ssi_file_request(struct mg_connection *conn,
  9581. const char *path,
  9582. struct mg_file *filep)
  9583. {
  9584. char date[64];
  9585. time_t curtime = time(NULL);
  9586. const char *cors1, *cors2, *cors3;
  9587. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  9588. return;
  9589. }
  9590. if (mg_get_header(conn, "Origin")) {
  9591. /* Cross-origin resource sharing (CORS). */
  9592. cors1 = "Access-Control-Allow-Origin: ";
  9593. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9594. cors3 = "\r\n";
  9595. } else {
  9596. cors1 = cors2 = cors3 = "";
  9597. }
  9598. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9599. /* File exists (precondition for calling this function),
  9600. * but can not be opened by the server. */
  9601. mg_send_http_error(conn,
  9602. 500,
  9603. "Error: Cannot read file\nfopen(%s): %s",
  9604. path,
  9605. strerror(ERRNO));
  9606. } else {
  9607. conn->must_close = 1;
  9608. gmt_time_string(date, sizeof(date), &curtime);
  9609. fclose_on_exec(&filep->access, conn);
  9610. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  9611. send_no_cache_header(conn);
  9612. send_additional_header(conn);
  9613. mg_printf(conn,
  9614. "%s%s%s"
  9615. "Date: %s\r\n"
  9616. "Content-Type: text/html\r\n"
  9617. "Connection: %s\r\n\r\n",
  9618. cors1,
  9619. cors2,
  9620. cors3,
  9621. date,
  9622. suggest_connection_header(conn));
  9623. send_ssi_file(conn, path, filep, 0);
  9624. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  9625. }
  9626. }
  9627. #if !defined(NO_FILES)
  9628. static void
  9629. send_options(struct mg_connection *conn)
  9630. {
  9631. char date[64];
  9632. time_t curtime = time(NULL);
  9633. if (!conn) {
  9634. return;
  9635. }
  9636. conn->status_code = 200;
  9637. conn->must_close = 1;
  9638. gmt_time_string(date, sizeof(date), &curtime);
  9639. /* We do not set a "Cache-Control" header here, but leave the default.
  9640. * Since browsers do not send an OPTIONS request, we can not test the
  9641. * effect anyway. */
  9642. mg_printf(conn,
  9643. "HTTP/1.1 200 OK\r\n"
  9644. "Date: %s\r\n"
  9645. "Connection: %s\r\n"
  9646. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  9647. "PROPFIND, MKCOL\r\n"
  9648. "DAV: 1\r\n",
  9649. date,
  9650. suggest_connection_header(conn));
  9651. send_additional_header(conn);
  9652. mg_printf(conn, "\r\n");
  9653. }
  9654. /* Writes PROPFIND properties for a collection element */
  9655. static void
  9656. print_props(struct mg_connection *conn,
  9657. const char *uri,
  9658. struct mg_file_stat *filep)
  9659. {
  9660. char mtime[64];
  9661. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  9662. return;
  9663. }
  9664. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  9665. mg_printf(conn,
  9666. "<d:response>"
  9667. "<d:href>%s</d:href>"
  9668. "<d:propstat>"
  9669. "<d:prop>"
  9670. "<d:resourcetype>%s</d:resourcetype>"
  9671. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  9672. "<d:getlastmodified>%s</d:getlastmodified>"
  9673. "</d:prop>"
  9674. "<d:status>HTTP/1.1 200 OK</d:status>"
  9675. "</d:propstat>"
  9676. "</d:response>\n",
  9677. uri,
  9678. filep->is_directory ? "<d:collection/>" : "",
  9679. filep->size,
  9680. mtime);
  9681. }
  9682. static int
  9683. print_dav_dir_entry(struct de *de, void *data)
  9684. {
  9685. char href[PATH_MAX];
  9686. int truncated;
  9687. struct mg_connection *conn = (struct mg_connection *)data;
  9688. if (!de || !conn) {
  9689. return -1;
  9690. }
  9691. mg_snprintf(conn,
  9692. &truncated,
  9693. href,
  9694. sizeof(href),
  9695. "%s%s",
  9696. conn->request_info.local_uri,
  9697. de->file_name);
  9698. if (!truncated) {
  9699. size_t href_encoded_size;
  9700. char *href_encoded;
  9701. href_encoded_size = PATH_MAX * 3; /* worst case */
  9702. href_encoded = (char *)mg_malloc(href_encoded_size);
  9703. if (href_encoded == NULL) {
  9704. return -1;
  9705. }
  9706. mg_url_encode(href, href_encoded, href_encoded_size);
  9707. print_props(conn, href_encoded, &de->file);
  9708. mg_free(href_encoded);
  9709. }
  9710. return 0;
  9711. }
  9712. static void
  9713. handle_propfind(struct mg_connection *conn,
  9714. const char *path,
  9715. struct mg_file_stat *filep)
  9716. {
  9717. const char *depth = mg_get_header(conn, "Depth");
  9718. char date[64];
  9719. time_t curtime = time(NULL);
  9720. gmt_time_string(date, sizeof(date), &curtime);
  9721. if (!conn || !path || !filep || !conn->dom_ctx) {
  9722. return;
  9723. }
  9724. conn->must_close = 1;
  9725. conn->status_code = 207;
  9726. mg_printf(conn,
  9727. "HTTP/1.1 207 Multi-Status\r\n"
  9728. "Date: %s\r\n",
  9729. date);
  9730. send_static_cache_header(conn);
  9731. send_additional_header(conn);
  9732. mg_printf(conn,
  9733. "Connection: %s\r\n"
  9734. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9735. suggest_connection_header(conn));
  9736. mg_printf(conn,
  9737. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9738. "<d:multistatus xmlns:d='DAV:'>\n");
  9739. /* Print properties for the requested resource itself */
  9740. print_props(conn, conn->request_info.local_uri, filep);
  9741. /* If it is a directory, print directory entries too if Depth is not 0
  9742. */
  9743. if (filep && filep->is_directory
  9744. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9745. "yes")
  9746. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9747. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9748. }
  9749. mg_printf(conn, "%s\n", "</d:multistatus>");
  9750. }
  9751. #endif
  9752. void
  9753. mg_lock_connection(struct mg_connection *conn)
  9754. {
  9755. if (conn) {
  9756. (void)pthread_mutex_lock(&conn->mutex);
  9757. }
  9758. }
  9759. void
  9760. mg_unlock_connection(struct mg_connection *conn)
  9761. {
  9762. if (conn) {
  9763. (void)pthread_mutex_unlock(&conn->mutex);
  9764. }
  9765. }
  9766. void
  9767. mg_lock_context(struct mg_context *ctx)
  9768. {
  9769. if (ctx) {
  9770. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9771. }
  9772. }
  9773. void
  9774. mg_unlock_context(struct mg_context *ctx)
  9775. {
  9776. if (ctx) {
  9777. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9778. }
  9779. }
  9780. #if defined(USE_TIMERS)
  9781. #define TIMER_API static
  9782. #include "timer.inl"
  9783. #endif /* USE_TIMERS */
  9784. #ifdef USE_LUA
  9785. #include "mod_lua.inl"
  9786. #endif /* USE_LUA */
  9787. #ifdef USE_DUKTAPE
  9788. #include "mod_duktape.inl"
  9789. #endif /* USE_DUKTAPE */
  9790. #if defined(USE_WEBSOCKET)
  9791. #if !defined(NO_SSL_DL)
  9792. #define SHA_API static
  9793. #include "sha1.inl"
  9794. #endif
  9795. static int
  9796. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9797. {
  9798. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9799. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9800. SHA_CTX sha_ctx;
  9801. int truncated;
  9802. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9803. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9804. if (truncated) {
  9805. conn->must_close = 1;
  9806. return 0;
  9807. }
  9808. DEBUG_TRACE("%s", "Send websocket handshake");
  9809. SHA1_Init(&sha_ctx);
  9810. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9811. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9812. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9813. mg_printf(conn,
  9814. "HTTP/1.1 101 Switching Protocols\r\n"
  9815. "Upgrade: websocket\r\n"
  9816. "Connection: Upgrade\r\n"
  9817. "Sec-WebSocket-Accept: %s\r\n",
  9818. b64_sha);
  9819. if (conn->request_info.acceptedWebSocketSubprotocol) {
  9820. mg_printf(conn,
  9821. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  9822. conn->request_info.acceptedWebSocketSubprotocol);
  9823. } else {
  9824. mg_printf(conn, "%s", "\r\n");
  9825. }
  9826. return 1;
  9827. }
  9828. static void
  9829. read_websocket(struct mg_connection *conn,
  9830. mg_websocket_data_handler ws_data_handler,
  9831. void *callback_data)
  9832. {
  9833. /* Pointer to the beginning of the portion of the incoming websocket
  9834. * message queue.
  9835. * The original websocket upgrade request is never removed, so the queue
  9836. * begins after it. */
  9837. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  9838. int n, error, exit_by_callback;
  9839. /* body_len is the length of the entire queue in bytes
  9840. * len is the length of the current message
  9841. * data_len is the length of the current message's data payload
  9842. * header_len is the length of the current message's header */
  9843. size_t i, len, mask_len = 0, header_len, body_len;
  9844. uint64_t data_len = 0;
  9845. /* "The masking key is a 32-bit value chosen at random by the client."
  9846. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  9847. */
  9848. unsigned char mask[4];
  9849. /* data points to the place where the message is stored when passed to
  9850. * the
  9851. * websocket_data callback. This is either mem on the stack, or a
  9852. * dynamically allocated buffer if it is too large. */
  9853. unsigned char mem[4096];
  9854. unsigned char mop; /* mask flag and opcode */
  9855. double timeout = -1.0;
  9856. int enable_ping_pong =
  9857. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  9858. "yes");
  9859. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  9860. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  9861. }
  9862. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  9863. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9864. }
  9865. conn->in_websocket_handling = 1;
  9866. mg_set_thread_name("wsock");
  9867. /* Loop continuously, reading messages from the socket, invoking the
  9868. * callback, and waiting repeatedly until an error occurs. */
  9869. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  9870. header_len = 0;
  9871. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  9872. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  9873. len = buf[1] & 127;
  9874. mask_len = (buf[1] & 128) ? 4 : 0;
  9875. if ((len < 126) && (body_len >= mask_len)) {
  9876. /* inline 7-bit length field */
  9877. data_len = len;
  9878. header_len = 2 + mask_len;
  9879. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  9880. /* 16-bit length field */
  9881. header_len = 4 + mask_len;
  9882. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  9883. } else if (body_len >= (10 + mask_len)) {
  9884. /* 64-bit length field */
  9885. uint32_t l1, l2;
  9886. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  9887. memcpy(&l2, &buf[6], 4);
  9888. header_len = 10 + mask_len;
  9889. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  9890. if (data_len > (uint64_t)0x7FFF0000ul) {
  9891. /* no can do */
  9892. mg_cry_internal(
  9893. conn,
  9894. "%s",
  9895. "websocket out of memory; closing connection");
  9896. break;
  9897. }
  9898. }
  9899. }
  9900. if ((header_len > 0) && (body_len >= header_len)) {
  9901. /* Allocate space to hold websocket payload */
  9902. unsigned char *data = mem;
  9903. if ((size_t)data_len > (size_t)sizeof(mem)) {
  9904. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  9905. conn->phys_ctx);
  9906. if (data == NULL) {
  9907. /* Allocation failed, exit the loop and then close the
  9908. * connection */
  9909. mg_cry_internal(
  9910. conn,
  9911. "%s",
  9912. "websocket out of memory; closing connection");
  9913. break;
  9914. }
  9915. }
  9916. /* Copy the mask before we shift the queue and destroy it */
  9917. if (mask_len > 0) {
  9918. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  9919. } else {
  9920. memset(mask, 0, sizeof(mask));
  9921. }
  9922. /* Read frame payload from the first message in the queue into
  9923. * data and advance the queue by moving the memory in place. */
  9924. DEBUG_ASSERT(body_len >= header_len);
  9925. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  9926. mop = buf[0]; /* current mask and opcode */
  9927. /* Overflow case */
  9928. len = body_len - header_len;
  9929. memcpy(data, buf + header_len, len);
  9930. error = 0;
  9931. while ((uint64_t)len < data_len) {
  9932. n = pull_inner(NULL,
  9933. conn,
  9934. (char *)(data + len),
  9935. (int)(data_len - len),
  9936. timeout);
  9937. if (n <= -2) {
  9938. error = 1;
  9939. break;
  9940. } else if (n > 0) {
  9941. len += (size_t)n;
  9942. } else {
  9943. /* Timeout: should retry */
  9944. /* TODO: retry condition */
  9945. }
  9946. }
  9947. if (error) {
  9948. mg_cry_internal(
  9949. conn,
  9950. "%s",
  9951. "Websocket pull failed; closing connection");
  9952. if (data != mem) {
  9953. mg_free(data);
  9954. }
  9955. break;
  9956. }
  9957. conn->data_len = conn->request_len;
  9958. } else {
  9959. mop = buf[0]; /* current mask and opcode, overwritten by
  9960. * memmove() */
  9961. /* Length of the message being read at the front of the
  9962. * queue. Cast to 31 bit is OK, since we limited
  9963. * data_len before. */
  9964. len = (size_t)data_len + header_len;
  9965. /* Copy the data payload into the data pointer for the
  9966. * callback. Cast to 31 bit is OK, since we
  9967. * limited data_len */
  9968. memcpy(data, buf + header_len, (size_t)data_len);
  9969. /* Move the queue forward len bytes */
  9970. memmove(buf, buf + len, body_len - len);
  9971. /* Mark the queue as advanced */
  9972. conn->data_len -= (int)len;
  9973. }
  9974. /* Apply mask if necessary */
  9975. if (mask_len > 0) {
  9976. for (i = 0; i < (size_t)data_len; i++) {
  9977. data[i] ^= mask[i & 3];
  9978. }
  9979. }
  9980. exit_by_callback = 0;
  9981. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  9982. /* filter PONG messages */
  9983. DEBUG_TRACE("PONG from %s:%u",
  9984. conn->request_info.remote_addr,
  9985. conn->request_info.remote_port);
  9986. } else {
  9987. /* Exit the loop if callback signals to exit (server side),
  9988. * or "connection close" opcode received (client side). */
  9989. if ((ws_data_handler != NULL)
  9990. && !ws_data_handler(conn,
  9991. mop,
  9992. (char *)data,
  9993. (size_t)data_len,
  9994. callback_data)) {
  9995. exit_by_callback = 1;
  9996. }
  9997. }
  9998. /* It a buffer has been allocated, free it again */
  9999. if (data != mem) {
  10000. mg_free(data);
  10001. }
  10002. if (exit_by_callback
  10003. || ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  10004. /* Opcode == 8, connection close */
  10005. break;
  10006. }
  10007. /* Not breaking the loop, process next websocket frame. */
  10008. } else {
  10009. /* Read from the socket into the next available location in the
  10010. * message queue. */
  10011. n = pull_inner(NULL,
  10012. conn,
  10013. conn->buf + conn->data_len,
  10014. conn->buf_size - conn->data_len,
  10015. timeout);
  10016. if (n <= -2) {
  10017. /* Error, no bytes read */
  10018. break;
  10019. }
  10020. if (n > 0) {
  10021. conn->data_len += n;
  10022. } else {
  10023. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10024. if (enable_ping_pong) {
  10025. int ret;
  10026. /* Send Websocket PING message */
  10027. DEBUG_TRACE("PING to %s:%u",
  10028. conn->request_info.remote_addr,
  10029. conn->request_info.remote_port);
  10030. ret = mg_websocket_write(conn,
  10031. MG_WEBSOCKET_OPCODE_PING,
  10032. NULL,
  10033. 0);
  10034. if (ret <= 0) {
  10035. /* Error: send failed */
  10036. break;
  10037. }
  10038. }
  10039. }
  10040. /* Timeout: should retry */
  10041. /* TODO: get timeout def */
  10042. }
  10043. }
  10044. }
  10045. mg_set_thread_name("worker");
  10046. conn->in_websocket_handling = 0;
  10047. }
  10048. static int
  10049. mg_websocket_write_exec(struct mg_connection *conn,
  10050. int opcode,
  10051. const char *data,
  10052. size_t dataLen,
  10053. uint32_t masking_key)
  10054. {
  10055. unsigned char header[14];
  10056. size_t headerLen;
  10057. int retval;
  10058. #if defined(__GNUC__) || defined(__MINGW32__)
  10059. /* Disable spurious conversion warning for GCC */
  10060. #pragma GCC diagnostic push
  10061. #pragma GCC diagnostic ignored "-Wconversion"
  10062. #endif
  10063. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10064. #if defined(__GNUC__) || defined(__MINGW32__)
  10065. #pragma GCC diagnostic pop
  10066. #endif
  10067. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10068. if (dataLen < 126) {
  10069. /* inline 7-bit length field */
  10070. header[1] = (unsigned char)dataLen;
  10071. headerLen = 2;
  10072. } else if (dataLen <= 0xFFFF) {
  10073. /* 16-bit length field */
  10074. uint16_t len = htons((uint16_t)dataLen);
  10075. header[1] = 126;
  10076. memcpy(header + 2, &len, 2);
  10077. headerLen = 4;
  10078. } else {
  10079. /* 64-bit length field */
  10080. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10081. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10082. header[1] = 127;
  10083. memcpy(header + 2, &len1, 4);
  10084. memcpy(header + 6, &len2, 4);
  10085. headerLen = 10;
  10086. }
  10087. if (masking_key) {
  10088. /* add mask */
  10089. header[1] |= 0x80;
  10090. memcpy(header + headerLen, &masking_key, 4);
  10091. headerLen += 4;
  10092. }
  10093. /* Note that POSIX/Winsock's send() is threadsafe
  10094. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10095. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10096. * push(), although that is only a problem if the packet is large or
  10097. * outgoing buffer is full). */
  10098. /* TODO: Check if this lock should be moved to user land.
  10099. * Currently the server sets this lock for websockets, but
  10100. * not for any other connection. It must be set for every
  10101. * conn read/written by more than one thread, no matter if
  10102. * it is a websocket or regular connection. */
  10103. (void)mg_lock_connection(conn);
  10104. retval = mg_write(conn, header, headerLen);
  10105. if (retval != (int)headerLen) {
  10106. /* Did not send complete header */
  10107. retval = -1;
  10108. } else {
  10109. if (dataLen > 0) {
  10110. retval = mg_write(conn, data, dataLen);
  10111. }
  10112. /* if dataLen == 0, the header length (2) is returned */
  10113. }
  10114. /* TODO: Remove this unlock as well, when lock is removed. */
  10115. mg_unlock_connection(conn);
  10116. return retval;
  10117. }
  10118. int
  10119. mg_websocket_write(struct mg_connection *conn,
  10120. int opcode,
  10121. const char *data,
  10122. size_t dataLen)
  10123. {
  10124. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10125. }
  10126. static void
  10127. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10128. {
  10129. size_t i = 0;
  10130. i = 0;
  10131. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10132. /* Convert in 32 bit words, if data is 4 byte aligned */
  10133. while (i < (in_len - 3)) {
  10134. *(uint32_t *)(void *)(out + i) =
  10135. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10136. i += 4;
  10137. }
  10138. }
  10139. if (i != in_len) {
  10140. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10141. while (i < in_len) {
  10142. *(uint8_t *)(void *)(out + i) =
  10143. *(uint8_t *)(void *)(in + i)
  10144. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10145. i++;
  10146. }
  10147. }
  10148. }
  10149. int
  10150. mg_websocket_client_write(struct mg_connection *conn,
  10151. int opcode,
  10152. const char *data,
  10153. size_t dataLen)
  10154. {
  10155. int retval = -1;
  10156. char *masked_data =
  10157. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10158. uint32_t masking_key = 0;
  10159. if (masked_data == NULL) {
  10160. /* Return -1 in an error case */
  10161. mg_cry_internal(conn,
  10162. "%s",
  10163. "Cannot allocate buffer for masked websocket response: "
  10164. "Out of memory");
  10165. return -1;
  10166. }
  10167. do {
  10168. /* Get a masking key - but not 0 */
  10169. masking_key = (uint32_t)get_random();
  10170. } while (masking_key == 0);
  10171. mask_data(data, dataLen, masking_key, masked_data);
  10172. retval = mg_websocket_write_exec(
  10173. conn, opcode, masked_data, dataLen, masking_key);
  10174. mg_free(masked_data);
  10175. return retval;
  10176. }
  10177. static void
  10178. handle_websocket_request(struct mg_connection *conn,
  10179. const char *path,
  10180. int is_callback_resource,
  10181. struct mg_websocket_subprotocols *subprotocols,
  10182. mg_websocket_connect_handler ws_connect_handler,
  10183. mg_websocket_ready_handler ws_ready_handler,
  10184. mg_websocket_data_handler ws_data_handler,
  10185. mg_websocket_close_handler ws_close_handler,
  10186. void *cbData)
  10187. {
  10188. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10189. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10190. int lua_websock = 0;
  10191. #if !defined(USE_LUA)
  10192. (void)path;
  10193. #endif
  10194. /* Step 1: Check websocket protocol version. */
  10195. /* Step 1.1: Check Sec-WebSocket-Key. */
  10196. if (!websock_key) {
  10197. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10198. * requires a Sec-WebSocket-Key header.
  10199. */
  10200. /* It could be the hixie draft version
  10201. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10202. */
  10203. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10204. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10205. char key3[8];
  10206. if ((key1 != NULL) && (key2 != NULL)) {
  10207. /* This version uses 8 byte body data in a GET request */
  10208. conn->content_len = 8;
  10209. if (8 == mg_read(conn, key3, 8)) {
  10210. /* This is the hixie version */
  10211. mg_send_http_error(conn,
  10212. 426,
  10213. "%s",
  10214. "Protocol upgrade to RFC 6455 required");
  10215. return;
  10216. }
  10217. }
  10218. /* This is an unknown version */
  10219. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10220. return;
  10221. }
  10222. /* Step 1.2: Check websocket protocol version. */
  10223. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10224. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10225. /* Reject wrong versions */
  10226. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10227. return;
  10228. }
  10229. /* Step 1.3: Could check for "Host", but we do not really nead this
  10230. * value for anything, so just ignore it. */
  10231. /* Step 2: If a callback is responsible, call it. */
  10232. if (is_callback_resource) {
  10233. /* Step 2.1 check and select subprotocol */
  10234. const char *protocols[64]; // max 64 headers
  10235. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10236. "Sec-WebSocket-Protocol",
  10237. protocols,
  10238. 64);
  10239. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10240. int cnt = 0;
  10241. int idx;
  10242. unsigned long len;
  10243. const char *sep, *curSubProtocol,
  10244. *acceptedWebSocketSubprotocol = NULL;
  10245. /* look for matching subprotocol */
  10246. do {
  10247. const char *protocol = protocols[cnt];
  10248. do {
  10249. sep = strchr(protocol, ',');
  10250. curSubProtocol = protocol;
  10251. len = sep ? (unsigned long)(sep - protocol)
  10252. : (unsigned long)strlen(protocol);
  10253. while (sep && isspace(*++sep))
  10254. ; // ignore leading whitespaces
  10255. protocol = sep;
  10256. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10257. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10258. && (strncmp(curSubProtocol,
  10259. subprotocols->subprotocols[idx],
  10260. len) == 0)) {
  10261. acceptedWebSocketSubprotocol =
  10262. subprotocols->subprotocols[idx];
  10263. break;
  10264. }
  10265. }
  10266. } while (sep && !acceptedWebSocketSubprotocol);
  10267. } while (++cnt < nbSubprotocolHeader
  10268. && !acceptedWebSocketSubprotocol);
  10269. conn->request_info.acceptedWebSocketSubprotocol =
  10270. acceptedWebSocketSubprotocol;
  10271. } else if (nbSubprotocolHeader > 0) {
  10272. /* keep legacy behavior */
  10273. const char *protocol = protocols[0];
  10274. /* The protocol is a comma separated list of names. */
  10275. /* The server must only return one value from this list. */
  10276. /* First check if it is a list or just a single value. */
  10277. const char *sep = strrchr(protocol, ',');
  10278. if (sep == NULL) {
  10279. /* Just a single protocol -> accept it. */
  10280. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10281. } else {
  10282. /* Multiple protocols -> accept the last one. */
  10283. /* This is just a quick fix if the client offers multiple
  10284. * protocols. The handler should have a list of accepted
  10285. * protocols on his own
  10286. * and use it to select one protocol among those the client
  10287. * has
  10288. * offered.
  10289. */
  10290. while (isspace(*++sep)) {
  10291. ; /* ignore leading whitespaces */
  10292. }
  10293. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10294. }
  10295. }
  10296. if ((ws_connect_handler != NULL)
  10297. && (ws_connect_handler(conn, cbData) != 0)) {
  10298. /* C callback has returned non-zero, do not proceed with
  10299. * handshake.
  10300. */
  10301. /* Note that C callbacks are no longer called when Lua is
  10302. * responsible, so C can no longer filter callbacks for Lua. */
  10303. return;
  10304. }
  10305. }
  10306. #if defined(USE_LUA)
  10307. /* Step 3: No callback. Check if Lua is responsible. */
  10308. else {
  10309. /* Step 3.1: Check if Lua is responsible. */
  10310. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10311. lua_websock = match_prefix(
  10312. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10313. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10314. path);
  10315. }
  10316. if (lua_websock) {
  10317. /* Step 3.2: Lua is responsible: call it. */
  10318. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10319. if (!conn->lua_websocket_state) {
  10320. /* Lua rejected the new client */
  10321. return;
  10322. }
  10323. }
  10324. }
  10325. #endif
  10326. /* Step 4: Check if there is a responsible websocket handler. */
  10327. if (!is_callback_resource && !lua_websock) {
  10328. /* There is no callback, and Lua is not responsible either. */
  10329. /* Reply with a 404 Not Found. We are still at a standard
  10330. * HTTP request here, before the websocket handshake, so
  10331. * we can still send standard HTTP error replies. */
  10332. mg_send_http_error(conn, 404, "%s", "Not found");
  10333. return;
  10334. }
  10335. /* Step 5: The websocket connection has been accepted */
  10336. if (!send_websocket_handshake(conn, websock_key)) {
  10337. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10338. return;
  10339. }
  10340. /* Step 6: Call the ready handler */
  10341. if (is_callback_resource) {
  10342. if (ws_ready_handler != NULL) {
  10343. ws_ready_handler(conn, cbData);
  10344. }
  10345. #if defined(USE_LUA)
  10346. } else if (lua_websock) {
  10347. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10348. /* the ready handler returned false */
  10349. return;
  10350. }
  10351. #endif
  10352. }
  10353. /* Step 7: Enter the read loop */
  10354. if (is_callback_resource) {
  10355. read_websocket(conn, ws_data_handler, cbData);
  10356. #if defined(USE_LUA)
  10357. } else if (lua_websock) {
  10358. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10359. #endif
  10360. }
  10361. /* Step 8: Call the close handler */
  10362. if (ws_close_handler) {
  10363. ws_close_handler(conn, cbData);
  10364. }
  10365. }
  10366. static int
  10367. is_websocket_protocol(const struct mg_connection *conn)
  10368. {
  10369. const char *upgrade, *connection;
  10370. /* A websocket protocoll has the following HTTP headers:
  10371. *
  10372. * Connection: Upgrade
  10373. * Upgrade: Websocket
  10374. */
  10375. upgrade = mg_get_header(conn, "Upgrade");
  10376. if (upgrade == NULL) {
  10377. return 0; /* fail early, don't waste time checking other header
  10378. * fields
  10379. */
  10380. }
  10381. if (!mg_strcasestr(upgrade, "websocket")) {
  10382. return 0;
  10383. }
  10384. connection = mg_get_header(conn, "Connection");
  10385. if (connection == NULL) {
  10386. return 0;
  10387. }
  10388. if (!mg_strcasestr(connection, "upgrade")) {
  10389. return 0;
  10390. }
  10391. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10392. * "Sec-WebSocket-Version" are also required.
  10393. * Don't check them here, since even an unsupported websocket protocol
  10394. * request still IS a websocket request (in contrast to a standard HTTP
  10395. * request). It will fail later in handle_websocket_request.
  10396. */
  10397. return 1;
  10398. }
  10399. #endif /* !USE_WEBSOCKET */
  10400. static int
  10401. isbyte(int n)
  10402. {
  10403. return (n >= 0) && (n <= 255);
  10404. }
  10405. static int
  10406. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10407. {
  10408. int n, a, b, c, d, slash = 32, len = 0;
  10409. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10410. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10411. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10412. && (slash < 33)) {
  10413. len = n;
  10414. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10415. | (uint32_t)d;
  10416. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10417. }
  10418. return len;
  10419. }
  10420. static int
  10421. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10422. {
  10423. int throttle = 0;
  10424. struct vec vec, val;
  10425. uint32_t net, mask;
  10426. char mult;
  10427. double v;
  10428. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  10429. mult = ',';
  10430. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  10431. || (v < 0) || ((lowercase(&mult) != 'k')
  10432. && (lowercase(&mult) != 'm') && (mult != ','))) {
  10433. continue;
  10434. }
  10435. v *= (lowercase(&mult) == 'k')
  10436. ? 1024
  10437. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  10438. if (vec.len == 1 && vec.ptr[0] == '*') {
  10439. throttle = (int)v;
  10440. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  10441. if ((remote_ip & mask) == net) {
  10442. throttle = (int)v;
  10443. }
  10444. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  10445. throttle = (int)v;
  10446. }
  10447. }
  10448. return throttle;
  10449. }
  10450. static uint32_t
  10451. get_remote_ip(const struct mg_connection *conn)
  10452. {
  10453. if (!conn) {
  10454. return 0;
  10455. }
  10456. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  10457. }
  10458. /* The mg_upload function is superseeded by mg_handle_form_request. */
  10459. #include "handle_form.inl"
  10460. #if defined(MG_LEGACY_INTERFACE)
  10461. /* Implement the deprecated mg_upload function by calling the new
  10462. * mg_handle_form_request function. While mg_upload could only handle
  10463. * HTML forms sent as POST request in multipart/form-data format
  10464. * containing only file input elements, mg_handle_form_request can
  10465. * handle all form input elements and all standard request methods. */
  10466. struct mg_upload_user_data {
  10467. struct mg_connection *conn;
  10468. const char *destination_dir;
  10469. int num_uploaded_files;
  10470. };
  10471. /* Helper function for deprecated mg_upload. */
  10472. static int
  10473. mg_upload_field_found(const char *key,
  10474. const char *filename,
  10475. char *path,
  10476. size_t pathlen,
  10477. void *user_data)
  10478. {
  10479. int truncated = 0;
  10480. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10481. (void)key;
  10482. if (!filename) {
  10483. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  10484. return FORM_FIELD_STORAGE_ABORT;
  10485. }
  10486. mg_snprintf(fud->conn,
  10487. &truncated,
  10488. path,
  10489. pathlen - 1,
  10490. "%s/%s",
  10491. fud->destination_dir,
  10492. filename);
  10493. if (truncated) {
  10494. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  10495. return FORM_FIELD_STORAGE_ABORT;
  10496. }
  10497. return FORM_FIELD_STORAGE_STORE;
  10498. }
  10499. /* Helper function for deprecated mg_upload. */
  10500. static int
  10501. mg_upload_field_get(const char *key,
  10502. const char *value,
  10503. size_t value_size,
  10504. void *user_data)
  10505. {
  10506. /* Function should never be called */
  10507. (void)key;
  10508. (void)value;
  10509. (void)value_size;
  10510. (void)user_data;
  10511. return 0;
  10512. }
  10513. /* Helper function for deprecated mg_upload. */
  10514. static int
  10515. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  10516. {
  10517. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10518. (void)file_size;
  10519. fud->num_uploaded_files++;
  10520. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  10521. return 0;
  10522. }
  10523. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  10524. int
  10525. mg_upload(struct mg_connection *conn, const char *destination_dir)
  10526. {
  10527. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  10528. struct mg_form_data_handler fdh = {mg_upload_field_found,
  10529. mg_upload_field_get,
  10530. mg_upload_field_stored,
  10531. 0};
  10532. int ret;
  10533. fdh.user_data = (void *)&fud;
  10534. ret = mg_handle_form_request(conn, &fdh);
  10535. if (ret < 0) {
  10536. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  10537. }
  10538. return fud.num_uploaded_files;
  10539. }
  10540. #endif
  10541. static int
  10542. get_first_ssl_listener_index(const struct mg_context *ctx)
  10543. {
  10544. unsigned int i;
  10545. int idx = -1;
  10546. if (ctx) {
  10547. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  10548. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  10549. }
  10550. }
  10551. return idx;
  10552. }
  10553. /* Return host (without port) */
  10554. /* Use mg_free to free the result */
  10555. static const char *
  10556. alloc_get_host(struct mg_connection *conn)
  10557. {
  10558. char host[1025];
  10559. const char *host_header;
  10560. size_t hostlen;
  10561. host_header = get_header(conn->request_info.http_headers,
  10562. conn->request_info.num_headers,
  10563. "Host");
  10564. hostlen = sizeof(host);
  10565. if (host_header != NULL) {
  10566. char *pos;
  10567. mg_strlcpy(host, host_header, hostlen);
  10568. host[hostlen - 1] = '\0';
  10569. pos = strchr(host, ':');
  10570. if (pos != NULL) {
  10571. *pos = '\0';
  10572. }
  10573. if (conn->ssl) {
  10574. /* This is a HTTPS connection, maybe we have a hostname
  10575. * from SNI (set in ssl_servername_callback). */
  10576. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  10577. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  10578. /* We are not using the default domain */
  10579. if (mg_strcasecmp(host, sslhost)) {
  10580. /* Mismatch between SNI domain and HTTP domain */
  10581. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  10582. sslhost,
  10583. host);
  10584. return NULL;
  10585. }
  10586. }
  10587. DEBUG_TRACE("HTTPS Host: %s", host);
  10588. } else {
  10589. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  10590. while (dom) {
  10591. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  10592. /* Found matching domain */
  10593. DEBUG_TRACE("HTTP domain %s found",
  10594. dom->config[AUTHENTICATION_DOMAIN]);
  10595. /* TODO: Check if this is a HTTP or HTTPS domain */
  10596. conn->dom_ctx = dom;
  10597. break;
  10598. }
  10599. dom = dom->next;
  10600. }
  10601. DEBUG_TRACE("HTTP Host: %s", host);
  10602. }
  10603. } else {
  10604. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  10605. DEBUG_TRACE("IP: %s", host);
  10606. }
  10607. return mg_strdup_ctx(host, conn->phys_ctx);
  10608. }
  10609. static void
  10610. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  10611. {
  10612. conn->must_close = 1;
  10613. /* Send host, port, uri and (if it exists) ?query_string */
  10614. if (conn->host) {
  10615. mg_printf(conn,
  10616. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  10617. conn->host,
  10618. #if defined(USE_IPV6)
  10619. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  10620. == AF_INET6)
  10621. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  10622. .lsa.sin6.sin6_port)
  10623. :
  10624. #endif
  10625. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  10626. .lsa.sin.sin_port),
  10627. conn->request_info.local_uri,
  10628. (conn->request_info.query_string == NULL) ? "" : "?",
  10629. (conn->request_info.query_string == NULL)
  10630. ? ""
  10631. : conn->request_info.query_string);
  10632. }
  10633. }
  10634. static void
  10635. mg_set_handler_type(struct mg_context *phys_ctx,
  10636. struct mg_domain_context *dom_ctx,
  10637. const char *uri,
  10638. int handler_type,
  10639. int is_delete_request,
  10640. mg_request_handler handler,
  10641. struct mg_websocket_subprotocols *subprotocols,
  10642. mg_websocket_connect_handler connect_handler,
  10643. mg_websocket_ready_handler ready_handler,
  10644. mg_websocket_data_handler data_handler,
  10645. mg_websocket_close_handler close_handler,
  10646. mg_authorization_handler auth_handler,
  10647. void *cbdata)
  10648. {
  10649. struct mg_handler_info *tmp_rh, **lastref;
  10650. size_t urilen = strlen(uri);
  10651. if (handler_type == WEBSOCKET_HANDLER) {
  10652. DEBUG_ASSERT(handler == NULL);
  10653. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  10654. || ready_handler != NULL
  10655. || data_handler != NULL
  10656. || close_handler != NULL);
  10657. DEBUG_ASSERT(auth_handler == NULL);
  10658. if (handler != NULL) {
  10659. return;
  10660. }
  10661. if (!is_delete_request && (connect_handler == NULL)
  10662. && (ready_handler == NULL) && (data_handler == NULL)
  10663. && (close_handler == NULL)) {
  10664. return;
  10665. }
  10666. if (auth_handler != NULL) {
  10667. return;
  10668. }
  10669. } else if (handler_type == REQUEST_HANDLER) {
  10670. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  10671. && data_handler == NULL
  10672. && close_handler == NULL);
  10673. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  10674. DEBUG_ASSERT(auth_handler == NULL);
  10675. if ((connect_handler != NULL) || (ready_handler != NULL)
  10676. || (data_handler != NULL) || (close_handler != NULL)) {
  10677. return;
  10678. }
  10679. if (!is_delete_request && (handler == NULL)) {
  10680. return;
  10681. }
  10682. if (auth_handler != NULL) {
  10683. return;
  10684. }
  10685. } else { /* AUTH_HANDLER */
  10686. DEBUG_ASSERT(handler == NULL);
  10687. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  10688. && data_handler == NULL
  10689. && close_handler == NULL);
  10690. DEBUG_ASSERT(auth_handler != NULL);
  10691. if (handler != NULL) {
  10692. return;
  10693. }
  10694. if ((connect_handler != NULL) || (ready_handler != NULL)
  10695. || (data_handler != NULL) || (close_handler != NULL)) {
  10696. return;
  10697. }
  10698. if (!is_delete_request && (auth_handler == NULL)) {
  10699. return;
  10700. }
  10701. }
  10702. if (!phys_ctx || !dom_ctx) {
  10703. return;
  10704. }
  10705. mg_lock_context(phys_ctx);
  10706. /* first try to find an existing handler */
  10707. lastref = &(dom_ctx->handlers);
  10708. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  10709. if (tmp_rh->handler_type == handler_type) {
  10710. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10711. if (!is_delete_request) {
  10712. /* update existing handler */
  10713. if (handler_type == REQUEST_HANDLER) {
  10714. tmp_rh->handler = handler;
  10715. } else if (handler_type == WEBSOCKET_HANDLER) {
  10716. tmp_rh->subprotocols = subprotocols;
  10717. tmp_rh->connect_handler = connect_handler;
  10718. tmp_rh->ready_handler = ready_handler;
  10719. tmp_rh->data_handler = data_handler;
  10720. tmp_rh->close_handler = close_handler;
  10721. } else { /* AUTH_HANDLER */
  10722. tmp_rh->auth_handler = auth_handler;
  10723. }
  10724. tmp_rh->cbdata = cbdata;
  10725. } else {
  10726. /* remove existing handler */
  10727. *lastref = tmp_rh->next;
  10728. mg_free(tmp_rh->uri);
  10729. mg_free(tmp_rh);
  10730. }
  10731. mg_unlock_context(phys_ctx);
  10732. return;
  10733. }
  10734. }
  10735. lastref = &(tmp_rh->next);
  10736. }
  10737. if (is_delete_request) {
  10738. /* no handler to set, this was a remove request to a non-existing
  10739. * handler */
  10740. mg_unlock_context(phys_ctx);
  10741. return;
  10742. }
  10743. tmp_rh =
  10744. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  10745. 1,
  10746. phys_ctx);
  10747. if (tmp_rh == NULL) {
  10748. mg_unlock_context(phys_ctx);
  10749. mg_cry_internal(fc(phys_ctx),
  10750. "%s",
  10751. "Cannot create new request handler struct, OOM");
  10752. return;
  10753. }
  10754. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  10755. if (!tmp_rh->uri) {
  10756. mg_unlock_context(phys_ctx);
  10757. mg_free(tmp_rh);
  10758. mg_cry_internal(fc(phys_ctx),
  10759. "%s",
  10760. "Cannot create new request handler struct, OOM");
  10761. return;
  10762. }
  10763. tmp_rh->uri_len = urilen;
  10764. if (handler_type == REQUEST_HANDLER) {
  10765. tmp_rh->handler = handler;
  10766. } else if (handler_type == WEBSOCKET_HANDLER) {
  10767. tmp_rh->subprotocols = subprotocols;
  10768. tmp_rh->connect_handler = connect_handler;
  10769. tmp_rh->ready_handler = ready_handler;
  10770. tmp_rh->data_handler = data_handler;
  10771. tmp_rh->close_handler = close_handler;
  10772. } else { /* AUTH_HANDLER */
  10773. tmp_rh->auth_handler = auth_handler;
  10774. }
  10775. tmp_rh->cbdata = cbdata;
  10776. tmp_rh->handler_type = handler_type;
  10777. tmp_rh->next = NULL;
  10778. *lastref = tmp_rh;
  10779. mg_unlock_context(phys_ctx);
  10780. }
  10781. void
  10782. mg_set_request_handler(struct mg_context *ctx,
  10783. const char *uri,
  10784. mg_request_handler handler,
  10785. void *cbdata)
  10786. {
  10787. mg_set_handler_type(ctx,
  10788. &(ctx->dd),
  10789. uri,
  10790. REQUEST_HANDLER,
  10791. handler == NULL,
  10792. handler,
  10793. NULL,
  10794. NULL,
  10795. NULL,
  10796. NULL,
  10797. NULL,
  10798. NULL,
  10799. cbdata);
  10800. }
  10801. void
  10802. mg_set_websocket_handler(struct mg_context *ctx,
  10803. const char *uri,
  10804. mg_websocket_connect_handler connect_handler,
  10805. mg_websocket_ready_handler ready_handler,
  10806. mg_websocket_data_handler data_handler,
  10807. mg_websocket_close_handler close_handler,
  10808. void *cbdata)
  10809. {
  10810. mg_set_websocket_handler_with_subprotocols(ctx,
  10811. uri,
  10812. NULL,
  10813. connect_handler,
  10814. ready_handler,
  10815. data_handler,
  10816. close_handler,
  10817. cbdata);
  10818. }
  10819. void
  10820. mg_set_websocket_handler_with_subprotocols(
  10821. struct mg_context *ctx,
  10822. const char *uri,
  10823. struct mg_websocket_subprotocols *subprotocols,
  10824. mg_websocket_connect_handler connect_handler,
  10825. mg_websocket_ready_handler ready_handler,
  10826. mg_websocket_data_handler data_handler,
  10827. mg_websocket_close_handler close_handler,
  10828. void *cbdata)
  10829. {
  10830. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  10831. && (data_handler == NULL)
  10832. && (close_handler == NULL);
  10833. mg_set_handler_type(ctx,
  10834. &(ctx->dd),
  10835. uri,
  10836. WEBSOCKET_HANDLER,
  10837. is_delete_request,
  10838. NULL,
  10839. subprotocols,
  10840. connect_handler,
  10841. ready_handler,
  10842. data_handler,
  10843. close_handler,
  10844. NULL,
  10845. cbdata);
  10846. }
  10847. void
  10848. mg_set_auth_handler(struct mg_context *ctx,
  10849. const char *uri,
  10850. mg_request_handler handler,
  10851. void *cbdata)
  10852. {
  10853. mg_set_handler_type(ctx,
  10854. &(ctx->dd),
  10855. uri,
  10856. AUTH_HANDLER,
  10857. handler == NULL,
  10858. NULL,
  10859. NULL,
  10860. NULL,
  10861. NULL,
  10862. NULL,
  10863. NULL,
  10864. handler,
  10865. cbdata);
  10866. }
  10867. static int
  10868. get_request_handler(struct mg_connection *conn,
  10869. int handler_type,
  10870. mg_request_handler *handler,
  10871. struct mg_websocket_subprotocols **subprotocols,
  10872. mg_websocket_connect_handler *connect_handler,
  10873. mg_websocket_ready_handler *ready_handler,
  10874. mg_websocket_data_handler *data_handler,
  10875. mg_websocket_close_handler *close_handler,
  10876. mg_authorization_handler *auth_handler,
  10877. void **cbdata)
  10878. {
  10879. const struct mg_request_info *request_info = mg_get_request_info(conn);
  10880. if (request_info) {
  10881. const char *uri = request_info->local_uri;
  10882. size_t urilen = strlen(uri);
  10883. struct mg_handler_info *tmp_rh;
  10884. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  10885. return 0;
  10886. }
  10887. mg_lock_context(conn->phys_ctx);
  10888. /* first try for an exact match */
  10889. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  10890. tmp_rh = tmp_rh->next) {
  10891. if (tmp_rh->handler_type == handler_type) {
  10892. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10893. if (handler_type == WEBSOCKET_HANDLER) {
  10894. *subprotocols = tmp_rh->subprotocols;
  10895. *connect_handler = tmp_rh->connect_handler;
  10896. *ready_handler = tmp_rh->ready_handler;
  10897. *data_handler = tmp_rh->data_handler;
  10898. *close_handler = tmp_rh->close_handler;
  10899. } else if (handler_type == REQUEST_HANDLER) {
  10900. *handler = tmp_rh->handler;
  10901. } else { /* AUTH_HANDLER */
  10902. *auth_handler = tmp_rh->auth_handler;
  10903. }
  10904. *cbdata = tmp_rh->cbdata;
  10905. mg_unlock_context(conn->phys_ctx);
  10906. return 1;
  10907. }
  10908. }
  10909. }
  10910. /* next try for a partial match, we will accept uri/something */
  10911. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  10912. tmp_rh = tmp_rh->next) {
  10913. if (tmp_rh->handler_type == handler_type) {
  10914. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  10915. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  10916. if (handler_type == WEBSOCKET_HANDLER) {
  10917. *subprotocols = tmp_rh->subprotocols;
  10918. *connect_handler = tmp_rh->connect_handler;
  10919. *ready_handler = tmp_rh->ready_handler;
  10920. *data_handler = tmp_rh->data_handler;
  10921. *close_handler = tmp_rh->close_handler;
  10922. } else if (handler_type == REQUEST_HANDLER) {
  10923. *handler = tmp_rh->handler;
  10924. } else { /* AUTH_HANDLER */
  10925. *auth_handler = tmp_rh->auth_handler;
  10926. }
  10927. *cbdata = tmp_rh->cbdata;
  10928. mg_unlock_context(conn->phys_ctx);
  10929. return 1;
  10930. }
  10931. }
  10932. }
  10933. /* finally try for pattern match */
  10934. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  10935. tmp_rh = tmp_rh->next) {
  10936. if (tmp_rh->handler_type == handler_type) {
  10937. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  10938. if (handler_type == WEBSOCKET_HANDLER) {
  10939. *subprotocols = tmp_rh->subprotocols;
  10940. *connect_handler = tmp_rh->connect_handler;
  10941. *ready_handler = tmp_rh->ready_handler;
  10942. *data_handler = tmp_rh->data_handler;
  10943. *close_handler = tmp_rh->close_handler;
  10944. } else if (handler_type == REQUEST_HANDLER) {
  10945. *handler = tmp_rh->handler;
  10946. } else { /* AUTH_HANDLER */
  10947. *auth_handler = tmp_rh->auth_handler;
  10948. }
  10949. *cbdata = tmp_rh->cbdata;
  10950. mg_unlock_context(conn->phys_ctx);
  10951. return 1;
  10952. }
  10953. }
  10954. }
  10955. mg_unlock_context(conn->phys_ctx);
  10956. }
  10957. return 0; /* none found */
  10958. }
  10959. /* Check if the script file is in a path, allowed for script files.
  10960. * This can be used if uploading files is possible not only for the server
  10961. * admin, and the upload mechanism does not check the file extension.
  10962. */
  10963. static int
  10964. is_in_script_path(const struct mg_connection *conn, const char *path)
  10965. {
  10966. /* TODO (Feature): Add config value for allowed script path.
  10967. * Default: All allowed. */
  10968. (void)conn;
  10969. (void)path;
  10970. return 1;
  10971. }
  10972. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  10973. static int
  10974. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  10975. void *cbdata)
  10976. {
  10977. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10978. if (pcallbacks->websocket_connect) {
  10979. return pcallbacks->websocket_connect(conn);
  10980. }
  10981. /* No handler set - assume "OK" */
  10982. return 0;
  10983. }
  10984. static void
  10985. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  10986. {
  10987. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10988. if (pcallbacks->websocket_ready) {
  10989. pcallbacks->websocket_ready(conn);
  10990. }
  10991. }
  10992. static int
  10993. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  10994. int bits,
  10995. char *data,
  10996. size_t len,
  10997. void *cbdata)
  10998. {
  10999. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11000. if (pcallbacks->websocket_data) {
  11001. return pcallbacks->websocket_data(conn, bits, data, len);
  11002. }
  11003. /* No handler set - assume "OK" */
  11004. return 1;
  11005. }
  11006. #endif
  11007. /* This is the heart of the Civetweb's logic.
  11008. * This function is called when the request is read, parsed and validated,
  11009. * and Civetweb must decide what action to take: serve a file, or
  11010. * a directory, or call embedded function, etcetera. */
  11011. static void
  11012. handle_request(struct mg_connection *conn)
  11013. {
  11014. struct mg_request_info *ri = &conn->request_info;
  11015. char path[PATH_MAX];
  11016. int uri_len, ssl_index;
  11017. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11018. is_put_or_delete_request = 0, is_callback_resource = 0;
  11019. int i;
  11020. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11021. mg_request_handler callback_handler = NULL;
  11022. struct mg_websocket_subprotocols *subprotocols;
  11023. mg_websocket_connect_handler ws_connect_handler = NULL;
  11024. mg_websocket_ready_handler ws_ready_handler = NULL;
  11025. mg_websocket_data_handler ws_data_handler = NULL;
  11026. mg_websocket_close_handler ws_close_handler = NULL;
  11027. void *callback_data = NULL;
  11028. mg_authorization_handler auth_handler = NULL;
  11029. void *auth_callback_data = NULL;
  11030. int handler_type;
  11031. time_t curtime = time(NULL);
  11032. char date[64];
  11033. path[0] = 0;
  11034. /* 1. get the request url */
  11035. /* 1.1. split into url and query string */
  11036. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11037. != NULL) {
  11038. *((char *)conn->request_info.query_string++) = '\0';
  11039. }
  11040. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11041. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11042. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11043. if (ssl_index >= 0) {
  11044. redirect_to_https_port(conn, ssl_index);
  11045. } else {
  11046. /* A http to https forward port has been specified,
  11047. * but no https port to forward to. */
  11048. mg_send_http_error(conn,
  11049. 503,
  11050. "%s",
  11051. "Error: SSL forward not configured properly");
  11052. mg_cry_internal(conn,
  11053. "%s",
  11054. "Can not redirect to SSL, no SSL port available");
  11055. }
  11056. return;
  11057. }
  11058. uri_len = (int)strlen(ri->local_uri);
  11059. /* 1.3. decode url (if config says so) */
  11060. if (should_decode_url(conn)) {
  11061. mg_url_decode(
  11062. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11063. }
  11064. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11065. * not possible */
  11066. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11067. /* step 1. completed, the url is known now */
  11068. uri_len = (int)strlen(ri->local_uri);
  11069. DEBUG_TRACE("URL: %s", ri->local_uri);
  11070. /* 2. if this ip has limited speed, set it for this connection */
  11071. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11072. get_remote_ip(conn),
  11073. ri->local_uri);
  11074. /* 3. call a "handle everything" callback, if registered */
  11075. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11076. /* Note that since V1.7 the "begin_request" function is called
  11077. * before an authorization check. If an authorization check is
  11078. * required, use a request_handler instead. */
  11079. i = conn->phys_ctx->callbacks.begin_request(conn);
  11080. if (i > 0) {
  11081. /* callback already processed the request. Store the
  11082. return value as a status code for the access log. */
  11083. conn->status_code = i;
  11084. discard_unread_request_data(conn);
  11085. return;
  11086. } else if (i == 0) {
  11087. /* civetweb should process the request */
  11088. } else {
  11089. /* unspecified - may change with the next version */
  11090. return;
  11091. }
  11092. }
  11093. /* request not yet handled by a handler or redirect, so the request
  11094. * is processed here */
  11095. /* 4. Check for CORS preflight requests and handle them (if configured).
  11096. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11097. */
  11098. if (!strcmp(ri->request_method, "OPTIONS")) {
  11099. /* Send a response to CORS preflights only if
  11100. * access_control_allow_methods is not NULL and not an empty string.
  11101. * In this case, scripts can still handle CORS. */
  11102. const char *cors_meth_cfg =
  11103. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11104. const char *cors_orig_cfg =
  11105. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11106. const char *cors_origin =
  11107. get_header(ri->http_headers, ri->num_headers, "Origin");
  11108. const char *cors_acrm = get_header(ri->http_headers,
  11109. ri->num_headers,
  11110. "Access-Control-Request-Method");
  11111. /* Todo: check if cors_origin is in cors_orig_cfg.
  11112. * Or, let the client check this. */
  11113. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11114. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11115. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11116. /* This is a valid CORS preflight, and the server is configured
  11117. * to
  11118. * handle it automatically. */
  11119. const char *cors_acrh =
  11120. get_header(ri->http_headers,
  11121. ri->num_headers,
  11122. "Access-Control-Request-Headers");
  11123. gmt_time_string(date, sizeof(date), &curtime);
  11124. mg_printf(conn,
  11125. "HTTP/1.1 200 OK\r\n"
  11126. "Date: %s\r\n"
  11127. "Access-Control-Allow-Origin: %s\r\n"
  11128. "Access-Control-Allow-Methods: %s\r\n"
  11129. "Content-Length: 0\r\n"
  11130. "Connection: %s\r\n",
  11131. date,
  11132. cors_orig_cfg,
  11133. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11134. suggest_connection_header(conn));
  11135. if (cors_acrh != NULL) {
  11136. /* CORS request is asking for additional headers */
  11137. const char *cors_hdr_cfg =
  11138. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11139. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11140. /* Allow only if access_control_allow_headers is
  11141. * not NULL and not an empty string. If this
  11142. * configuration is set to *, allow everything.
  11143. * Otherwise this configuration must be a list
  11144. * of allowed HTTP header names. */
  11145. mg_printf(conn,
  11146. "Access-Control-Allow-Headers: %s\r\n",
  11147. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11148. : cors_hdr_cfg));
  11149. }
  11150. }
  11151. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11152. mg_printf(conn, "\r\n");
  11153. return;
  11154. }
  11155. }
  11156. /* 5. interpret the url to find out how the request must be handled
  11157. */
  11158. /* 5.1. first test, if the request targets the regular http(s)://
  11159. * protocol namespace or the websocket ws(s):// protocol namespace.
  11160. */
  11161. is_websocket_request = is_websocket_protocol(conn);
  11162. #if defined(USE_WEBSOCKET)
  11163. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11164. #else
  11165. handler_type = REQUEST_HANDLER;
  11166. #endif /* defined(USE_WEBSOCKET) */
  11167. /* 5.2. check if the request will be handled by a callback */
  11168. if (get_request_handler(conn,
  11169. handler_type,
  11170. &callback_handler,
  11171. &subprotocols,
  11172. &ws_connect_handler,
  11173. &ws_ready_handler,
  11174. &ws_data_handler,
  11175. &ws_close_handler,
  11176. NULL,
  11177. &callback_data)) {
  11178. /* 5.2.1. A callback will handle this request. All requests
  11179. * handled
  11180. * by a callback have to be considered as requests to a script
  11181. * resource. */
  11182. is_callback_resource = 1;
  11183. is_script_resource = 1;
  11184. is_put_or_delete_request = is_put_or_delete_method(conn);
  11185. } else {
  11186. no_callback_resource:
  11187. /* 5.2.2. No callback is responsible for this request. The URI
  11188. * addresses a file based resource (static content or Lua/cgi
  11189. * scripts in the file system). */
  11190. is_callback_resource = 0;
  11191. interpret_uri(conn,
  11192. path,
  11193. sizeof(path),
  11194. &file.stat,
  11195. &is_found,
  11196. &is_script_resource,
  11197. &is_websocket_request,
  11198. &is_put_or_delete_request);
  11199. }
  11200. /* 6. authorization check */
  11201. /* 6.1. a custom authorization handler is installed */
  11202. if (get_request_handler(conn,
  11203. AUTH_HANDLER,
  11204. NULL,
  11205. NULL,
  11206. NULL,
  11207. NULL,
  11208. NULL,
  11209. NULL,
  11210. &auth_handler,
  11211. &auth_callback_data)) {
  11212. if (!auth_handler(conn, auth_callback_data)) {
  11213. return;
  11214. }
  11215. } else if (is_put_or_delete_request && !is_script_resource
  11216. && !is_callback_resource) {
  11217. /* 6.2. this request is a PUT/DELETE to a real file */
  11218. /* 6.2.1. thus, the server must have real files */
  11219. #if defined(NO_FILES)
  11220. if (1) {
  11221. #else
  11222. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11223. #endif
  11224. /* This server does not have any real files, thus the
  11225. * PUT/DELETE methods are not valid. */
  11226. mg_send_http_error(conn,
  11227. 405,
  11228. "%s method not allowed",
  11229. conn->request_info.request_method);
  11230. return;
  11231. }
  11232. #if !defined(NO_FILES)
  11233. /* 6.2.2. Check if put authorization for static files is
  11234. * available.
  11235. */
  11236. if (!is_authorized_for_put(conn)) {
  11237. send_authorization_request(conn, NULL);
  11238. return;
  11239. }
  11240. #endif
  11241. } else {
  11242. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11243. * or it is a PUT or DELETE request to a resource that does not
  11244. * correspond to a file. Check authorization. */
  11245. if (!check_authorization(conn, path)) {
  11246. send_authorization_request(conn, NULL);
  11247. return;
  11248. }
  11249. }
  11250. /* request is authorized or does not need authorization */
  11251. /* 7. check if there are request handlers for this uri */
  11252. if (is_callback_resource) {
  11253. if (!is_websocket_request) {
  11254. i = callback_handler(conn, callback_data);
  11255. if (i > 0) {
  11256. /* Do nothing, callback has served the request. Store
  11257. * then return value as status code for the log and discard
  11258. * all data from the client not used by the callback. */
  11259. conn->status_code = i;
  11260. discard_unread_request_data(conn);
  11261. } else {
  11262. /* The handler did NOT handle the request. */
  11263. /* Some proper reactions would be:
  11264. * a) close the connections without sending anything
  11265. * b) send a 404 not found
  11266. * c) try if there is a file matching the URI
  11267. * It would be possible to do a, b or c in the callback
  11268. * implementation, and return 1 - we cannot do anything
  11269. * here, that is not possible in the callback.
  11270. *
  11271. * TODO: What would be the best reaction here?
  11272. * (Note: The reaction may change, if there is a better
  11273. *idea.)
  11274. */
  11275. /* For the moment, use option c: We look for a proper file,
  11276. * but since a file request is not always a script resource,
  11277. * the authorization check might be different. */
  11278. interpret_uri(conn,
  11279. path,
  11280. sizeof(path),
  11281. &file.stat,
  11282. &is_found,
  11283. &is_script_resource,
  11284. &is_websocket_request,
  11285. &is_put_or_delete_request);
  11286. callback_handler = NULL;
  11287. /* Here we are at a dead end:
  11288. * According to URI matching, a callback should be
  11289. * responsible for handling the request,
  11290. * we called it, but the callback declared itself
  11291. * not responsible.
  11292. * We use a goto here, to get out of this dead end,
  11293. * and continue with the default handling.
  11294. * A goto here is simpler and better to understand
  11295. * than some curious loop. */
  11296. goto no_callback_resource;
  11297. }
  11298. } else {
  11299. #if defined(USE_WEBSOCKET)
  11300. handle_websocket_request(conn,
  11301. path,
  11302. is_callback_resource,
  11303. subprotocols,
  11304. ws_connect_handler,
  11305. ws_ready_handler,
  11306. ws_data_handler,
  11307. ws_close_handler,
  11308. callback_data);
  11309. #endif
  11310. }
  11311. return;
  11312. }
  11313. /* 8. handle websocket requests */
  11314. #if defined(USE_WEBSOCKET)
  11315. if (is_websocket_request) {
  11316. if (is_script_resource) {
  11317. if (is_in_script_path(conn, path)) {
  11318. /* Websocket Lua script */
  11319. handle_websocket_request(conn,
  11320. path,
  11321. 0 /* Lua Script */,
  11322. NULL,
  11323. NULL,
  11324. NULL,
  11325. NULL,
  11326. NULL,
  11327. conn->phys_ctx->user_data);
  11328. } else {
  11329. /* Script was in an illegal path */
  11330. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11331. }
  11332. } else {
  11333. #if defined(MG_LEGACY_INTERFACE)
  11334. handle_websocket_request(
  11335. conn,
  11336. path,
  11337. !is_script_resource /* could be deprecated global callback */,
  11338. NULL,
  11339. deprecated_websocket_connect_wrapper,
  11340. deprecated_websocket_ready_wrapper,
  11341. deprecated_websocket_data_wrapper,
  11342. NULL,
  11343. conn->phys_ctx->user_data);
  11344. #else
  11345. mg_send_http_error(conn, 404, "%s", "Not found");
  11346. #endif
  11347. }
  11348. return;
  11349. } else
  11350. #endif
  11351. #if defined(NO_FILES)
  11352. /* 9a. In case the server uses only callbacks, this uri is
  11353. * unknown.
  11354. * Then, all request handling ends here. */
  11355. mg_send_http_error(conn, 404, "%s", "Not Found");
  11356. #else
  11357. /* 9b. This request is either for a static file or resource handled
  11358. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  11359. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11360. mg_send_http_error(conn, 404, "%s", "Not Found");
  11361. return;
  11362. }
  11363. /* 10. Request is handled by a script */
  11364. if (is_script_resource) {
  11365. handle_file_based_request(conn, path, &file);
  11366. return;
  11367. }
  11368. /* 11. Handle put/delete/mkcol requests */
  11369. if (is_put_or_delete_request) {
  11370. /* 11.1. PUT method */
  11371. if (!strcmp(ri->request_method, "PUT")) {
  11372. put_file(conn, path);
  11373. return;
  11374. }
  11375. /* 11.2. DELETE method */
  11376. if (!strcmp(ri->request_method, "DELETE")) {
  11377. delete_file(conn, path);
  11378. return;
  11379. }
  11380. /* 11.3. MKCOL method */
  11381. if (!strcmp(ri->request_method, "MKCOL")) {
  11382. mkcol(conn, path);
  11383. return;
  11384. }
  11385. /* 11.4. PATCH method
  11386. * This method is not supported for static resources,
  11387. * only for scripts (Lua, CGI) and callbacks. */
  11388. mg_send_http_error(conn,
  11389. 405,
  11390. "%s method not allowed",
  11391. conn->request_info.request_method);
  11392. return;
  11393. }
  11394. /* 11. File does not exist, or it was configured that it should be
  11395. * hidden */
  11396. if (!is_found || (must_hide_file(conn, path))) {
  11397. mg_send_http_error(conn, 404, "%s", "Not found");
  11398. return;
  11399. }
  11400. /* 12. Directory uris should end with a slash */
  11401. if (file.stat.is_directory && (uri_len > 0)
  11402. && (ri->local_uri[uri_len - 1] != '/')) {
  11403. gmt_time_string(date, sizeof(date), &curtime);
  11404. mg_printf(conn,
  11405. "HTTP/1.1 301 Moved Permanently\r\n"
  11406. "Location: %s/\r\n"
  11407. "Date: %s\r\n"
  11408. /* "Cache-Control: private\r\n" (= default) */
  11409. "Content-Length: 0\r\n"
  11410. "Connection: %s\r\n",
  11411. ri->request_uri,
  11412. date,
  11413. suggest_connection_header(conn));
  11414. send_additional_header(conn);
  11415. mg_printf(conn, "\r\n");
  11416. return;
  11417. }
  11418. /* 13. Handle other methods than GET/HEAD */
  11419. /* 13.1. Handle PROPFIND */
  11420. if (!strcmp(ri->request_method, "PROPFIND")) {
  11421. handle_propfind(conn, path, &file.stat);
  11422. return;
  11423. }
  11424. /* 13.2. Handle OPTIONS for files */
  11425. if (!strcmp(ri->request_method, "OPTIONS")) {
  11426. /* This standard handler is only used for real files.
  11427. * Scripts should support the OPTIONS method themselves, to allow a
  11428. * maximum flexibility.
  11429. * Lua and CGI scripts may fully support CORS this way (including
  11430. * preflights). */
  11431. send_options(conn);
  11432. return;
  11433. }
  11434. /* 13.3. everything but GET and HEAD (e.g. POST) */
  11435. if ((0 != strcmp(ri->request_method, "GET"))
  11436. && (0 != strcmp(ri->request_method, "HEAD"))) {
  11437. mg_send_http_error(conn,
  11438. 405,
  11439. "%s method not allowed",
  11440. conn->request_info.request_method);
  11441. return;
  11442. }
  11443. /* 14. directories */
  11444. if (file.stat.is_directory) {
  11445. /* Substitute files have already been handled above. */
  11446. /* Here we can either generate and send a directory listing,
  11447. * or send an "access denied" error. */
  11448. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11449. "yes")) {
  11450. handle_directory_request(conn, path);
  11451. } else {
  11452. mg_send_http_error(conn,
  11453. 403,
  11454. "%s",
  11455. "Error: Directory listing denied");
  11456. }
  11457. return;
  11458. }
  11459. handle_file_based_request(conn, path, &file);
  11460. #endif /* !defined(NO_FILES) */
  11461. #if 0
  11462. /* Perform redirect and auth checks before calling begin_request()
  11463. * handler.
  11464. * Otherwise, begin_request() would need to perform auth checks and
  11465. * redirects. */
  11466. #endif
  11467. }
  11468. static void
  11469. handle_file_based_request(struct mg_connection *conn,
  11470. const char *path,
  11471. struct mg_file *file)
  11472. {
  11473. if (!conn || !conn->dom_ctx) {
  11474. return;
  11475. }
  11476. if (0) {
  11477. #ifdef USE_LUA
  11478. } else if (match_prefix(
  11479. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  11480. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  11481. path) > 0) {
  11482. if (is_in_script_path(conn, path)) {
  11483. /* Lua server page: an SSI like page containing mostly plain
  11484. * html
  11485. * code
  11486. * plus some tags with server generated contents. */
  11487. handle_lsp_request(conn, path, file, NULL);
  11488. } else {
  11489. /* Script was in an illegal path */
  11490. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11491. }
  11492. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  11493. strlen(
  11494. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  11495. path) > 0) {
  11496. if (is_in_script_path(conn, path)) {
  11497. /* Lua in-server module script: a CGI like script used to
  11498. * generate
  11499. * the
  11500. * entire reply. */
  11501. mg_exec_lua_script(conn, path, NULL);
  11502. } else {
  11503. /* Script was in an illegal path */
  11504. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11505. }
  11506. #endif
  11507. #if defined(USE_DUKTAPE)
  11508. } else if (match_prefix(
  11509. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  11510. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  11511. path) > 0) {
  11512. if (is_in_script_path(conn, path)) {
  11513. /* Call duktape to generate the page */
  11514. mg_exec_duktape_script(conn, path);
  11515. } else {
  11516. /* Script was in an illegal path */
  11517. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11518. }
  11519. #endif
  11520. #if !defined(NO_CGI)
  11521. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  11522. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  11523. path) > 0) {
  11524. if (is_in_script_path(conn, path)) {
  11525. /* CGI scripts may support all HTTP methods */
  11526. handle_cgi_request(conn, path);
  11527. } else {
  11528. /* Script was in an illegal path */
  11529. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11530. }
  11531. #endif /* !NO_CGI */
  11532. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  11533. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  11534. path) > 0) {
  11535. if (is_in_script_path(conn, path)) {
  11536. handle_ssi_file_request(conn, path, file);
  11537. } else {
  11538. /* Script was in an illegal path */
  11539. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11540. }
  11541. #if !defined(NO_CACHING)
  11542. } else if ((!conn->in_error_handler)
  11543. && is_not_modified(conn, &file->stat)) {
  11544. /* Send 304 "Not Modified" - this must not send any body data */
  11545. handle_not_modified_static_file_request(conn, file);
  11546. #endif /* !NO_CACHING */
  11547. } else {
  11548. handle_static_file_request(conn, path, file, NULL, NULL);
  11549. }
  11550. }
  11551. static void
  11552. close_all_listening_sockets(struct mg_context *ctx)
  11553. {
  11554. unsigned int i;
  11555. if (!ctx) {
  11556. return;
  11557. }
  11558. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11559. closesocket(ctx->listening_sockets[i].sock);
  11560. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  11561. }
  11562. mg_free(ctx->listening_sockets);
  11563. ctx->listening_sockets = NULL;
  11564. mg_free(ctx->listening_socket_fds);
  11565. ctx->listening_socket_fds = NULL;
  11566. }
  11567. /* Valid listening port specification is: [ip_address:]port[s]
  11568. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  11569. * Examples for IPv6: [::]:80, [::1]:80,
  11570. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  11571. * see https://tools.ietf.org/html/rfc3513#section-2.2
  11572. * In order to bind to both, IPv4 and IPv6, you can either add
  11573. * both ports using 8080,[::]:8080, or the short form +8080.
  11574. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  11575. * one only accepting IPv4 the other only IPv6. +8080 creates
  11576. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  11577. * environment, they might work differently, or might not work
  11578. * at all - it must be tested what options work best in the
  11579. * relevant network environment.
  11580. */
  11581. static int
  11582. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  11583. {
  11584. unsigned int a, b, c, d, port;
  11585. int ch, len;
  11586. const char *cb;
  11587. #if defined(USE_IPV6)
  11588. char buf[100] = {0};
  11589. #endif
  11590. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  11591. * Also, all-zeroes in the socket address means binding to all addresses
  11592. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  11593. memset(so, 0, sizeof(*so));
  11594. so->lsa.sin.sin_family = AF_INET;
  11595. *ip_version = 0;
  11596. /* Initialize port and len as invalid. */
  11597. port = 0;
  11598. len = 0;
  11599. /* Test for different ways to format this string */
  11600. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  11601. == 5) {
  11602. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  11603. so->lsa.sin.sin_addr.s_addr =
  11604. htonl((a << 24) | (b << 16) | (c << 8) | d);
  11605. so->lsa.sin.sin_port = htons((uint16_t)port);
  11606. *ip_version = 4;
  11607. #if defined(USE_IPV6)
  11608. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  11609. && mg_inet_pton(
  11610. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  11611. /* IPv6 address, examples: see above */
  11612. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  11613. */
  11614. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11615. *ip_version = 6;
  11616. #endif
  11617. } else if ((vec->ptr[0] == '+')
  11618. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  11619. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  11620. /* Add 1 to len for the + character we skipped before */
  11621. len++;
  11622. #if defined(USE_IPV6)
  11623. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  11624. so->lsa.sin6.sin6_family = AF_INET6;
  11625. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11626. *ip_version = 4 + 6;
  11627. #else
  11628. /* Bind to IPv4 only, since IPv6 is not built in. */
  11629. so->lsa.sin.sin_port = htons((uint16_t)port);
  11630. *ip_version = 4;
  11631. #endif
  11632. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  11633. /* If only port is specified, bind to IPv4, INADDR_ANY */
  11634. so->lsa.sin.sin_port = htons((uint16_t)port);
  11635. *ip_version = 4;
  11636. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  11637. /* Could be a hostname */
  11638. /* Will only work for RFC 952 compliant hostnames,
  11639. * starting with a letter, containing only letters,
  11640. * digits and hyphen ('-'). Newer specs may allow
  11641. * more, but this is not guaranteed here, since it
  11642. * may interfere with rules for port option lists. */
  11643. *(char *)cb = 0; /* Use a const cast here and modify the string.
  11644. * We are going to restore the string later. */
  11645. if (mg_inet_pton(
  11646. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  11647. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11648. *ip_version = 4;
  11649. so->lsa.sin.sin_family = AF_INET;
  11650. so->lsa.sin.sin_port = htons((uint16_t)port);
  11651. len += (int)(cb - vec->ptr) + 1;
  11652. } else {
  11653. port = 0;
  11654. len = 0;
  11655. }
  11656. #if defined(USE_IPV6)
  11657. } else if (mg_inet_pton(AF_INET6,
  11658. vec->ptr,
  11659. &so->lsa.sin6,
  11660. sizeof(so->lsa.sin6))) {
  11661. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11662. *ip_version = 6;
  11663. so->lsa.sin6.sin6_family = AF_INET6;
  11664. so->lsa.sin.sin_port = htons((uint16_t)port);
  11665. len += (int)(cb - vec->ptr) + 1;
  11666. } else {
  11667. port = 0;
  11668. len = 0;
  11669. }
  11670. #endif
  11671. }
  11672. *(char *)cb = ':'; /* restore the string */
  11673. } else {
  11674. /* Parsing failure. */
  11675. }
  11676. /* sscanf and the option splitting code ensure the following condition
  11677. */
  11678. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  11679. *ip_version = 0;
  11680. return 0;
  11681. }
  11682. ch = vec->ptr[len]; /* Next character after the port number */
  11683. so->is_ssl = (ch == 's');
  11684. so->ssl_redir = (ch == 'r');
  11685. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  11686. if (is_valid_port(port)
  11687. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  11688. return 1;
  11689. }
  11690. /* Reset ip_version to 0 of there is an error */
  11691. *ip_version = 0;
  11692. return 0;
  11693. }
  11694. /* Is there any SSL port in use? */
  11695. static int
  11696. is_ssl_port_used(const char *ports)
  11697. {
  11698. if (ports) {
  11699. if (strchr(ports, 's')) {
  11700. return 1;
  11701. }
  11702. if (strchr(ports, 'r')) {
  11703. return 1;
  11704. }
  11705. }
  11706. return 0;
  11707. }
  11708. static int
  11709. set_ports_option(struct mg_context *phys_ctx)
  11710. {
  11711. const char *list;
  11712. int on = 1;
  11713. #if defined(USE_IPV6)
  11714. int off = 0;
  11715. #endif
  11716. struct vec vec;
  11717. struct socket so, *ptr;
  11718. struct pollfd *pfd;
  11719. union usa usa;
  11720. socklen_t len;
  11721. int ip_version;
  11722. int portsTotal = 0;
  11723. int portsOk = 0;
  11724. if (!phys_ctx) {
  11725. return 0;
  11726. }
  11727. memset(&so, 0, sizeof(so));
  11728. memset(&usa, 0, sizeof(usa));
  11729. len = sizeof(usa);
  11730. list = phys_ctx->dd.config[LISTENING_PORTS];
  11731. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11732. portsTotal++;
  11733. if (!parse_port_string(&vec, &so, &ip_version)) {
  11734. mg_cry_internal(
  11735. fc(phys_ctx),
  11736. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  11737. (int)vec.len,
  11738. vec.ptr,
  11739. portsTotal,
  11740. "[IP_ADDRESS:]PORT[s|r]");
  11741. continue;
  11742. }
  11743. #if !defined(NO_SSL)
  11744. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  11745. mg_cry_internal(fc(phys_ctx),
  11746. "Cannot add SSL socket (entry %i)",
  11747. portsTotal);
  11748. continue;
  11749. }
  11750. #endif
  11751. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  11752. == INVALID_SOCKET) {
  11753. mg_cry_internal(fc(phys_ctx),
  11754. "cannot create socket (entry %i)",
  11755. portsTotal);
  11756. continue;
  11757. }
  11758. #ifdef _WIN32
  11759. /* Windows SO_REUSEADDR lets many procs binds to a
  11760. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  11761. * if someone already has the socket -- DTL */
  11762. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  11763. * Windows might need a few seconds before
  11764. * the same port can be used again in the
  11765. * same process, so a short Sleep may be
  11766. * required between mg_stop and mg_start.
  11767. */
  11768. if (setsockopt(so.sock,
  11769. SOL_SOCKET,
  11770. SO_EXCLUSIVEADDRUSE,
  11771. (SOCK_OPT_TYPE)&on,
  11772. sizeof(on)) != 0) {
  11773. /* Set reuse option, but don't abort on errors. */
  11774. mg_cry_internal(
  11775. fc(phys_ctx),
  11776. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  11777. portsTotal);
  11778. }
  11779. #else
  11780. if (setsockopt(so.sock,
  11781. SOL_SOCKET,
  11782. SO_REUSEADDR,
  11783. (SOCK_OPT_TYPE)&on,
  11784. sizeof(on)) != 0) {
  11785. /* Set reuse option, but don't abort on errors. */
  11786. mg_cry_internal(fc(phys_ctx),
  11787. "cannot set socket option SO_REUSEADDR (entry %i)",
  11788. portsTotal);
  11789. }
  11790. #endif
  11791. if (ip_version > 4) {
  11792. #if defined(USE_IPV6)
  11793. if (ip_version == 6) {
  11794. if (so.lsa.sa.sa_family == AF_INET6
  11795. && setsockopt(so.sock,
  11796. IPPROTO_IPV6,
  11797. IPV6_V6ONLY,
  11798. (void *)&off,
  11799. sizeof(off)) != 0) {
  11800. /* Set IPv6 only option, but don't abort on errors. */
  11801. mg_cry_internal(
  11802. fc(phys_ctx),
  11803. "cannot set socket option IPV6_V6ONLY (entry %i)",
  11804. portsTotal);
  11805. }
  11806. }
  11807. #else
  11808. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  11809. closesocket(so.sock);
  11810. so.sock = INVALID_SOCKET;
  11811. continue;
  11812. #endif
  11813. }
  11814. if (so.lsa.sa.sa_family == AF_INET) {
  11815. len = sizeof(so.lsa.sin);
  11816. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11817. mg_cry_internal(fc(phys_ctx),
  11818. "cannot bind to %.*s: %d (%s)",
  11819. (int)vec.len,
  11820. vec.ptr,
  11821. (int)ERRNO,
  11822. strerror(errno));
  11823. closesocket(so.sock);
  11824. so.sock = INVALID_SOCKET;
  11825. continue;
  11826. }
  11827. }
  11828. #if defined(USE_IPV6)
  11829. else if (so.lsa.sa.sa_family == AF_INET6) {
  11830. len = sizeof(so.lsa.sin6);
  11831. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11832. mg_cry_internal(fc(phys_ctx),
  11833. "cannot bind to IPv6 %.*s: %d (%s)",
  11834. (int)vec.len,
  11835. vec.ptr,
  11836. (int)ERRNO,
  11837. strerror(errno));
  11838. closesocket(so.sock);
  11839. so.sock = INVALID_SOCKET;
  11840. continue;
  11841. }
  11842. }
  11843. #endif
  11844. else {
  11845. mg_cry_internal(
  11846. fc(phys_ctx),
  11847. "cannot bind: address family not supported (entry %i)",
  11848. portsTotal);
  11849. closesocket(so.sock);
  11850. so.sock = INVALID_SOCKET;
  11851. continue;
  11852. }
  11853. if (listen(so.sock, SOMAXCONN) != 0) {
  11854. mg_cry_internal(fc(phys_ctx),
  11855. "cannot listen to %.*s: %d (%s)",
  11856. (int)vec.len,
  11857. vec.ptr,
  11858. (int)ERRNO,
  11859. strerror(errno));
  11860. closesocket(so.sock);
  11861. so.sock = INVALID_SOCKET;
  11862. continue;
  11863. }
  11864. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  11865. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  11866. int err = (int)ERRNO;
  11867. mg_cry_internal(fc(phys_ctx),
  11868. "call to getsockname failed %.*s: %d (%s)",
  11869. (int)vec.len,
  11870. vec.ptr,
  11871. err,
  11872. strerror(errno));
  11873. closesocket(so.sock);
  11874. so.sock = INVALID_SOCKET;
  11875. continue;
  11876. }
  11877. /* Update lsa port in case of random free ports */
  11878. #if defined(USE_IPV6)
  11879. if (so.lsa.sa.sa_family == AF_INET6) {
  11880. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  11881. } else
  11882. #endif
  11883. {
  11884. so.lsa.sin.sin_port = usa.sin.sin_port;
  11885. }
  11886. if ((ptr = (struct socket *)
  11887. mg_realloc_ctx(phys_ctx->listening_sockets,
  11888. (phys_ctx->num_listening_sockets + 1)
  11889. * sizeof(phys_ctx->listening_sockets[0]),
  11890. phys_ctx)) == NULL) {
  11891. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  11892. closesocket(so.sock);
  11893. so.sock = INVALID_SOCKET;
  11894. continue;
  11895. }
  11896. if ((pfd = (struct pollfd *)
  11897. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  11898. (phys_ctx->num_listening_sockets + 1)
  11899. * sizeof(phys_ctx->listening_socket_fds[0]),
  11900. phys_ctx)) == NULL) {
  11901. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  11902. closesocket(so.sock);
  11903. so.sock = INVALID_SOCKET;
  11904. mg_free(ptr);
  11905. continue;
  11906. }
  11907. set_close_on_exec(so.sock, fc(phys_ctx));
  11908. phys_ctx->listening_sockets = ptr;
  11909. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  11910. phys_ctx->listening_socket_fds = pfd;
  11911. phys_ctx->num_listening_sockets++;
  11912. portsOk++;
  11913. }
  11914. if (portsOk != portsTotal) {
  11915. close_all_listening_sockets(phys_ctx);
  11916. portsOk = 0;
  11917. }
  11918. return portsOk;
  11919. }
  11920. static const char *
  11921. header_val(const struct mg_connection *conn, const char *header)
  11922. {
  11923. const char *header_value;
  11924. if ((header_value = mg_get_header(conn, header)) == NULL) {
  11925. return "-";
  11926. } else {
  11927. return header_value;
  11928. }
  11929. }
  11930. static void
  11931. log_access(const struct mg_connection *conn)
  11932. {
  11933. const struct mg_request_info *ri;
  11934. struct mg_file fi;
  11935. char date[64], src_addr[IP_ADDR_STR_LEN];
  11936. struct tm *tm;
  11937. const char *referer;
  11938. const char *user_agent;
  11939. char buf[4096];
  11940. if (!conn || !conn->dom_ctx) {
  11941. return;
  11942. }
  11943. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  11944. if (mg_fopen(conn,
  11945. conn->dom_ctx->config[ACCESS_LOG_FILE],
  11946. MG_FOPEN_MODE_APPEND,
  11947. &fi) == 0) {
  11948. fi.access.fp = NULL;
  11949. }
  11950. } else {
  11951. fi.access.fp = NULL;
  11952. }
  11953. /* Log is written to a file and/or a callback. If both are not set,
  11954. * executing the rest of the function is pointless. */
  11955. if ((fi.access.fp == NULL)
  11956. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  11957. return;
  11958. }
  11959. tm = localtime(&conn->conn_birth_time);
  11960. if (tm != NULL) {
  11961. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  11962. } else {
  11963. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  11964. date[sizeof(date) - 1] = '\0';
  11965. }
  11966. ri = &conn->request_info;
  11967. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  11968. referer = header_val(conn, "Referer");
  11969. user_agent = header_val(conn, "User-Agent");
  11970. mg_snprintf(conn,
  11971. NULL, /* Ignore truncation in access log */
  11972. buf,
  11973. sizeof(buf),
  11974. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  11975. src_addr,
  11976. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  11977. date,
  11978. ri->request_method ? ri->request_method : "-",
  11979. ri->request_uri ? ri->request_uri : "-",
  11980. ri->query_string ? "?" : "",
  11981. ri->query_string ? ri->query_string : "",
  11982. ri->http_version,
  11983. conn->status_code,
  11984. conn->num_bytes_sent,
  11985. referer,
  11986. user_agent);
  11987. if (conn->phys_ctx->callbacks.log_access) {
  11988. conn->phys_ctx->callbacks.log_access(conn, buf);
  11989. }
  11990. if (fi.access.fp) {
  11991. int ok = 1;
  11992. flockfile(fi.access.fp);
  11993. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  11994. ok = 0;
  11995. }
  11996. if (fflush(fi.access.fp) != 0) {
  11997. ok = 0;
  11998. }
  11999. funlockfile(fi.access.fp);
  12000. if (mg_fclose(&fi.access) != 0) {
  12001. ok = 0;
  12002. }
  12003. if (!ok) {
  12004. mg_cry_internal(conn,
  12005. "Error writing log file %s",
  12006. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12007. }
  12008. }
  12009. }
  12010. /* Verify given socket address against the ACL.
  12011. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12012. */
  12013. static int
  12014. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12015. {
  12016. int allowed, flag;
  12017. uint32_t net, mask;
  12018. struct vec vec;
  12019. if (phys_ctx) {
  12020. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12021. /* If any ACL is set, deny by default */
  12022. allowed = (list == NULL) ? '+' : '-';
  12023. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12024. flag = vec.ptr[0];
  12025. if ((flag != '+' && flag != '-')
  12026. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12027. mg_cry_internal(fc(phys_ctx),
  12028. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12029. __func__);
  12030. return -1;
  12031. }
  12032. if (net == (remote_ip & mask)) {
  12033. allowed = flag;
  12034. }
  12035. }
  12036. return allowed == '+';
  12037. }
  12038. return -1;
  12039. }
  12040. #if !defined(_WIN32)
  12041. static int
  12042. set_uid_option(struct mg_context *phys_ctx)
  12043. {
  12044. int success = 0;
  12045. if (phys_ctx) {
  12046. /* We are currently running as curr_uid. */
  12047. const uid_t curr_uid = getuid();
  12048. /* If set, we want to run as run_as_user. */
  12049. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12050. const struct passwd *to_pw = NULL;
  12051. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12052. /* run_as_user does not exist on the system. We can't proceed
  12053. * further. */
  12054. mg_cry_internal(fc(phys_ctx),
  12055. "%s: unknown user [%s]",
  12056. __func__,
  12057. run_as_user);
  12058. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12059. /* There was either no request to change user, or we're already
  12060. * running as run_as_user. Nothing else to do.
  12061. */
  12062. success = 1;
  12063. } else {
  12064. /* Valid change request. */
  12065. if (setgid(to_pw->pw_gid) == -1) {
  12066. mg_cry_internal(fc(phys_ctx),
  12067. "%s: setgid(%s): %s",
  12068. __func__,
  12069. run_as_user,
  12070. strerror(errno));
  12071. } else if (setgroups(0, NULL) == -1) {
  12072. mg_cry_internal(fc(phys_ctx),
  12073. "%s: setgroups(): %s",
  12074. __func__,
  12075. strerror(errno));
  12076. } else if (setuid(to_pw->pw_uid) == -1) {
  12077. mg_cry_internal(fc(phys_ctx),
  12078. "%s: setuid(%s): %s",
  12079. __func__,
  12080. run_as_user,
  12081. strerror(errno));
  12082. } else {
  12083. success = 1;
  12084. }
  12085. }
  12086. }
  12087. return success;
  12088. }
  12089. #endif /* !_WIN32 */
  12090. static void
  12091. tls_dtor(void *key)
  12092. {
  12093. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12094. /* key == pthread_getspecific(sTlsKey); */
  12095. if (tls) {
  12096. if (tls->is_master == 2) {
  12097. tls->is_master = -3; /* Mark memory as dead */
  12098. mg_free(tls);
  12099. }
  12100. }
  12101. pthread_setspecific(sTlsKey, NULL);
  12102. }
  12103. #if !defined(NO_SSL)
  12104. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12105. struct mg_domain_context *dom_ctx,
  12106. const char *pem,
  12107. const char *chain);
  12108. static const char *ssl_error(void);
  12109. static int
  12110. refresh_trust(struct mg_connection *conn)
  12111. {
  12112. static int reload_lock = 0;
  12113. static long int data_check = 0;
  12114. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12115. struct stat cert_buf;
  12116. long int t;
  12117. const char *pem;
  12118. const char *chain;
  12119. int should_verify_peer;
  12120. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12121. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12122. * refresh_trust still can not work. */
  12123. return 0;
  12124. }
  12125. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12126. if (chain == NULL) {
  12127. /* pem is not NULL here */
  12128. chain = pem;
  12129. }
  12130. if (*chain == 0) {
  12131. chain = NULL;
  12132. }
  12133. t = data_check;
  12134. if (stat(pem, &cert_buf) != -1) {
  12135. t = (long int)cert_buf.st_mtime;
  12136. }
  12137. if (data_check != t) {
  12138. data_check = t;
  12139. should_verify_peer = 0;
  12140. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12141. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12142. == 0) {
  12143. should_verify_peer = 1;
  12144. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12145. "optional") == 0) {
  12146. should_verify_peer = 1;
  12147. }
  12148. }
  12149. if (should_verify_peer) {
  12150. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12151. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12152. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12153. ca_file,
  12154. ca_path) != 1) {
  12155. mg_cry_internal(
  12156. fc(conn->phys_ctx),
  12157. "SSL_CTX_load_verify_locations error: %s "
  12158. "ssl_verify_peer requires setting "
  12159. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12160. "present in "
  12161. "the .conf file?",
  12162. ssl_error());
  12163. return 0;
  12164. }
  12165. }
  12166. if (1 == mg_atomic_inc(p_reload_lock)) {
  12167. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12168. == 0) {
  12169. return 0;
  12170. }
  12171. *p_reload_lock = 0;
  12172. }
  12173. }
  12174. /* lock while cert is reloading */
  12175. while (*p_reload_lock) {
  12176. sleep(1);
  12177. }
  12178. return 1;
  12179. }
  12180. #ifdef OPENSSL_API_1_1
  12181. #else
  12182. static pthread_mutex_t *ssl_mutexes;
  12183. #endif /* OPENSSL_API_1_1 */
  12184. static int
  12185. sslize(struct mg_connection *conn,
  12186. SSL_CTX *s,
  12187. int (*func)(SSL *),
  12188. volatile int *stop_server)
  12189. {
  12190. int ret, err;
  12191. int short_trust;
  12192. unsigned i;
  12193. if (!conn) {
  12194. return 0;
  12195. }
  12196. short_trust =
  12197. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  12198. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  12199. if (short_trust) {
  12200. int trust_ret = refresh_trust(conn);
  12201. if (!trust_ret) {
  12202. return trust_ret;
  12203. }
  12204. }
  12205. conn->ssl = SSL_new(s);
  12206. if (conn->ssl == NULL) {
  12207. return 0;
  12208. }
  12209. SSL_set_app_data(conn->ssl, (char *)conn);
  12210. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  12211. if (ret != 1) {
  12212. err = SSL_get_error(conn->ssl, ret);
  12213. (void)err; /* TODO: set some error message */
  12214. SSL_free(conn->ssl);
  12215. conn->ssl = NULL;
  12216. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12217. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12218. #ifndef OPENSSL_API_1_1
  12219. ERR_remove_state(0);
  12220. #endif
  12221. return 0;
  12222. }
  12223. /* SSL functions may fail and require to be called again:
  12224. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  12225. * Here "func" could be SSL_connect or SSL_accept. */
  12226. for (i = 16; i <= 1024; i *= 2) {
  12227. ret = func(conn->ssl);
  12228. if (ret != 1) {
  12229. err = SSL_get_error(conn->ssl, ret);
  12230. if ((err == SSL_ERROR_WANT_CONNECT)
  12231. || (err == SSL_ERROR_WANT_ACCEPT)
  12232. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  12233. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  12234. /* Need to retry the function call "later".
  12235. * See https://linux.die.net/man/3/ssl_get_error
  12236. * This is typical for non-blocking sockets. */
  12237. if (*stop_server) {
  12238. /* Don't wait if the server is going to be stopped. */
  12239. break;
  12240. }
  12241. mg_sleep(i);
  12242. } else if (err == SSL_ERROR_SYSCALL) {
  12243. /* This is an IO error. Look at errno. */
  12244. err = errno;
  12245. /* TODO: set some error message */
  12246. (void)err;
  12247. break;
  12248. } else {
  12249. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  12250. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  12251. break;
  12252. }
  12253. } else {
  12254. /* success */
  12255. break;
  12256. }
  12257. }
  12258. if (ret != 1) {
  12259. SSL_free(conn->ssl);
  12260. conn->ssl = NULL;
  12261. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12262. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12263. #ifndef OPENSSL_API_1_1
  12264. ERR_remove_state(0);
  12265. #endif
  12266. return 0;
  12267. }
  12268. return 1;
  12269. }
  12270. /* Return OpenSSL error message (from CRYPTO lib) */
  12271. static const char *
  12272. ssl_error(void)
  12273. {
  12274. unsigned long err;
  12275. err = ERR_get_error();
  12276. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  12277. }
  12278. static int
  12279. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  12280. {
  12281. int i;
  12282. const char hexdigit[] = "0123456789abcdef";
  12283. if ((memlen <= 0) || (buflen <= 0)) {
  12284. return 0;
  12285. }
  12286. if (buflen < (3 * memlen)) {
  12287. return 0;
  12288. }
  12289. for (i = 0; i < memlen; i++) {
  12290. if (i > 0) {
  12291. buf[3 * i - 1] = ' ';
  12292. }
  12293. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  12294. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  12295. }
  12296. buf[3 * memlen - 1] = 0;
  12297. return 1;
  12298. }
  12299. static void
  12300. ssl_get_client_cert_info(struct mg_connection *conn)
  12301. {
  12302. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  12303. if (cert) {
  12304. char str_subject[1024];
  12305. char str_issuer[1024];
  12306. char str_finger[1024];
  12307. unsigned char buf[256];
  12308. char *str_serial = NULL;
  12309. unsigned int ulen;
  12310. int ilen;
  12311. unsigned char *tmp_buf;
  12312. unsigned char *tmp_p;
  12313. /* Handle to algorithm used for fingerprint */
  12314. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  12315. /* Get Subject and issuer */
  12316. X509_NAME *subj = X509_get_subject_name(cert);
  12317. X509_NAME *iss = X509_get_issuer_name(cert);
  12318. /* Get serial number */
  12319. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  12320. /* Translate serial number to a hex string */
  12321. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  12322. str_serial = BN_bn2hex(serial_bn);
  12323. BN_free(serial_bn);
  12324. /* Translate subject and issuer to a string */
  12325. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  12326. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  12327. /* Calculate SHA1 fingerprint and store as a hex string */
  12328. ulen = 0;
  12329. /* ASN1_digest is deprecated. Do the calculation manually,
  12330. * using EVP_Digest. */
  12331. ilen = i2d_X509(cert, NULL);
  12332. tmp_buf = (ilen > 0)
  12333. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  12334. conn->phys_ctx)
  12335. : NULL;
  12336. if (tmp_buf) {
  12337. tmp_p = tmp_buf;
  12338. (void)i2d_X509(cert, &tmp_p);
  12339. if (!EVP_Digest(
  12340. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  12341. ulen = 0;
  12342. }
  12343. mg_free(tmp_buf);
  12344. }
  12345. if (!hexdump2string(
  12346. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  12347. *str_finger = 0;
  12348. }
  12349. conn->request_info.client_cert = (struct mg_client_cert *)
  12350. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  12351. if (conn->request_info.client_cert) {
  12352. conn->request_info.client_cert->peer_cert = (void *)cert;
  12353. conn->request_info.client_cert->subject =
  12354. mg_strdup_ctx(str_subject, conn->phys_ctx);
  12355. conn->request_info.client_cert->issuer =
  12356. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  12357. conn->request_info.client_cert->serial =
  12358. mg_strdup_ctx(str_serial, conn->phys_ctx);
  12359. conn->request_info.client_cert->finger =
  12360. mg_strdup_ctx(str_finger, conn->phys_ctx);
  12361. } else {
  12362. mg_cry_internal(conn,
  12363. "%s",
  12364. "Out of memory: Cannot allocate memory for client "
  12365. "certificate");
  12366. }
  12367. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  12368. * see https://linux.die.net/man/3/bn_bn2hex */
  12369. OPENSSL_free(str_serial);
  12370. }
  12371. }
  12372. #ifdef OPENSSL_API_1_1
  12373. #else
  12374. static void
  12375. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  12376. {
  12377. (void)line;
  12378. (void)file;
  12379. if (mode & 1) {
  12380. /* 1 is CRYPTO_LOCK */
  12381. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  12382. } else {
  12383. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  12384. }
  12385. }
  12386. #endif /* OPENSSL_API_1_1 */
  12387. #if !defined(NO_SSL_DL)
  12388. static void *
  12389. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  12390. {
  12391. union {
  12392. void *p;
  12393. void (*fp)(void);
  12394. } u;
  12395. void *dll_handle;
  12396. struct ssl_func *fp;
  12397. int ok;
  12398. int truncated = 0;
  12399. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  12400. mg_snprintf(NULL,
  12401. NULL, /* No truncation check for ebuf */
  12402. ebuf,
  12403. ebuf_len,
  12404. "%s: cannot load %s",
  12405. __func__,
  12406. dll_name);
  12407. return NULL;
  12408. }
  12409. ok = 1;
  12410. for (fp = sw; fp->name != NULL; fp++) {
  12411. #ifdef _WIN32
  12412. /* GetProcAddress() returns pointer to function */
  12413. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  12414. #else
  12415. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  12416. * pointers to function pointers. We need to use a union to make a
  12417. * cast. */
  12418. u.p = dlsym(dll_handle, fp->name);
  12419. #endif /* _WIN32 */
  12420. if (u.fp == NULL) {
  12421. if (ok) {
  12422. mg_snprintf(NULL,
  12423. &truncated,
  12424. ebuf,
  12425. ebuf_len,
  12426. "%s: %s: cannot find %s",
  12427. __func__,
  12428. dll_name,
  12429. fp->name);
  12430. ok = 0;
  12431. } else {
  12432. size_t cur_len = strlen(ebuf);
  12433. if (!truncated) {
  12434. mg_snprintf(NULL,
  12435. &truncated,
  12436. ebuf + cur_len,
  12437. ebuf_len - cur_len - 3,
  12438. ", %s",
  12439. fp->name);
  12440. if (truncated) {
  12441. /* If truncated, add "..." */
  12442. strcat(ebuf, "...");
  12443. }
  12444. }
  12445. }
  12446. /* Debug:
  12447. * printf("Missing function: %s\n", fp->name); */
  12448. } else {
  12449. fp->ptr = u.fp;
  12450. }
  12451. }
  12452. if (!ok) {
  12453. (void)dlclose(dll_handle);
  12454. return NULL;
  12455. }
  12456. return dll_handle;
  12457. }
  12458. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  12459. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  12460. #endif /* NO_SSL_DL */
  12461. #if defined(SSL_ALREADY_INITIALIZED)
  12462. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  12463. #else
  12464. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  12465. #endif
  12466. static int
  12467. initialize_ssl(char *ebuf, size_t ebuf_len)
  12468. {
  12469. #ifdef OPENSSL_API_1_1
  12470. if (ebuf_len > 0) {
  12471. ebuf[0] = 0;
  12472. }
  12473. #if !defined(NO_SSL_DL)
  12474. if (!cryptolib_dll_handle) {
  12475. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12476. if (!cryptolib_dll_handle) {
  12477. mg_snprintf(NULL,
  12478. NULL, /* No truncation check for ebuf */
  12479. ebuf,
  12480. ebuf_len,
  12481. "%s: error loading library %s",
  12482. __func__,
  12483. CRYPTO_LIB);
  12484. DEBUG_TRACE("%s", ebuf);
  12485. return 0;
  12486. }
  12487. }
  12488. #endif /* NO_SSL_DL */
  12489. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12490. return 1;
  12491. }
  12492. #else /* not OPENSSL_API_1_1 */
  12493. int i;
  12494. size_t size;
  12495. if (ebuf_len > 0) {
  12496. ebuf[0] = 0;
  12497. }
  12498. #if !defined(NO_SSL_DL)
  12499. if (!cryptolib_dll_handle) {
  12500. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12501. if (!cryptolib_dll_handle) {
  12502. mg_snprintf(NULL,
  12503. NULL, /* No truncation check for ebuf */
  12504. ebuf,
  12505. ebuf_len,
  12506. "%s: error loading library %s",
  12507. __func__,
  12508. CRYPTO_LIB);
  12509. DEBUG_TRACE("%s", ebuf);
  12510. return 0;
  12511. }
  12512. }
  12513. #endif /* NO_SSL_DL */
  12514. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12515. return 1;
  12516. }
  12517. /* Initialize locking callbacks, needed for thread safety.
  12518. * http://www.openssl.org/support/faq.html#PROG1
  12519. */
  12520. i = CRYPTO_num_locks();
  12521. if (i < 0) {
  12522. i = 0;
  12523. }
  12524. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  12525. if (size == 0) {
  12526. ssl_mutexes = NULL;
  12527. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  12528. mg_snprintf(NULL,
  12529. NULL, /* No truncation check for ebuf */
  12530. ebuf,
  12531. ebuf_len,
  12532. "%s: cannot allocate mutexes: %s",
  12533. __func__,
  12534. ssl_error());
  12535. DEBUG_TRACE("%s", ebuf);
  12536. return 0;
  12537. }
  12538. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12539. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  12540. }
  12541. CRYPTO_set_locking_callback(&ssl_locking_callback);
  12542. CRYPTO_set_id_callback(&mg_current_thread_id);
  12543. #endif /* OPENSSL_API_1_1 */
  12544. #if !defined(NO_SSL_DL)
  12545. if (!ssllib_dll_handle) {
  12546. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  12547. if (!ssllib_dll_handle) {
  12548. DEBUG_TRACE("%s", ebuf);
  12549. return 0;
  12550. }
  12551. }
  12552. #endif /* NO_SSL_DL */
  12553. #ifdef OPENSSL_API_1_1
  12554. /* Initialize SSL library */
  12555. OPENSSL_init_ssl(0, NULL);
  12556. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  12557. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  12558. NULL);
  12559. #else
  12560. /* Initialize SSL library */
  12561. SSL_library_init();
  12562. SSL_load_error_strings();
  12563. #endif
  12564. return 1;
  12565. }
  12566. static int
  12567. ssl_use_pem_file(struct mg_context *phys_ctx,
  12568. struct mg_domain_context *dom_ctx,
  12569. const char *pem,
  12570. const char *chain)
  12571. {
  12572. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  12573. mg_cry_internal(fc(phys_ctx),
  12574. "%s: cannot open certificate file %s: %s",
  12575. __func__,
  12576. pem,
  12577. ssl_error());
  12578. return 0;
  12579. }
  12580. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  12581. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  12582. mg_cry_internal(fc(phys_ctx),
  12583. "%s: cannot open private key file %s: %s",
  12584. __func__,
  12585. pem,
  12586. ssl_error());
  12587. return 0;
  12588. }
  12589. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  12590. mg_cry_internal(fc(phys_ctx),
  12591. "%s: certificate and private key do not match: %s",
  12592. __func__,
  12593. pem);
  12594. return 0;
  12595. }
  12596. /* In contrast to OpenSSL, wolfSSL does not support certificate
  12597. * chain files that contain private keys and certificates in
  12598. * SSL_CTX_use_certificate_chain_file.
  12599. * The CivetWeb-Server used pem-Files that contained both information.
  12600. * In order to make wolfSSL work, it is split in two files.
  12601. * One file that contains key and certificate used by the server and
  12602. * an optional chain file for the ssl stack.
  12603. */
  12604. if (chain) {
  12605. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  12606. mg_cry_internal(fc(phys_ctx),
  12607. "%s: cannot use certificate chain file %s: %s",
  12608. __func__,
  12609. pem,
  12610. ssl_error());
  12611. return 0;
  12612. }
  12613. }
  12614. return 1;
  12615. }
  12616. #ifdef OPENSSL_API_1_1
  12617. static unsigned long
  12618. ssl_get_protocol(int version_id)
  12619. {
  12620. long unsigned ret = SSL_OP_ALL;
  12621. if (version_id > 0)
  12622. ret |= SSL_OP_NO_SSLv2;
  12623. if (version_id > 1)
  12624. ret |= SSL_OP_NO_SSLv3;
  12625. if (version_id > 2)
  12626. ret |= SSL_OP_NO_TLSv1;
  12627. if (version_id > 3)
  12628. ret |= SSL_OP_NO_TLSv1_1;
  12629. return ret;
  12630. }
  12631. #else
  12632. static long
  12633. ssl_get_protocol(int version_id)
  12634. {
  12635. long ret = SSL_OP_ALL;
  12636. if (version_id > 0)
  12637. ret |= SSL_OP_NO_SSLv2;
  12638. if (version_id > 1)
  12639. ret |= SSL_OP_NO_SSLv3;
  12640. if (version_id > 2)
  12641. ret |= SSL_OP_NO_TLSv1;
  12642. if (version_id > 3)
  12643. ret |= SSL_OP_NO_TLSv1_1;
  12644. return ret;
  12645. }
  12646. #endif /* OPENSSL_API_1_1 */
  12647. /* SSL callback documentation:
  12648. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  12649. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  12650. * https://linux.die.net/man/3/ssl_set_info_callback */
  12651. /* Note: There is no "const" for the first argument in the documentation,
  12652. * however some (maybe most, but not all) headers of OpenSSL versions /
  12653. * OpenSSL compatibility layers have it. Having a different definition
  12654. * will cause a warning in C and an error in C++. With inconsitent
  12655. * definitions of this function, having a warning in one version or
  12656. * another is unavoidable. */
  12657. static void
  12658. ssl_info_callback(SSL *ssl, int what, int ret)
  12659. {
  12660. (void)ret;
  12661. if (what & SSL_CB_HANDSHAKE_START) {
  12662. SSL_get_app_data(ssl);
  12663. }
  12664. if (what & SSL_CB_HANDSHAKE_DONE) {
  12665. /* TODO: check for openSSL 1.1 */
  12666. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  12667. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  12668. }
  12669. }
  12670. static int
  12671. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  12672. {
  12673. struct mg_context *ctx = (struct mg_context *)arg;
  12674. struct mg_domain_context *dom =
  12675. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  12676. #if defined(__GNUC__) || defined(__MINGW32__)
  12677. #pragma GCC diagnostic push
  12678. #pragma GCC diagnostic ignored "-Wcast-align"
  12679. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  12680. /* We used an aligned pointer in SSL_set_app_data */
  12681. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  12682. #if defined(__GNUC__) || defined(__MINGW32__)
  12683. #pragma GCC diagnostic pop
  12684. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  12685. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  12686. (void)ad;
  12687. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  12688. DEBUG_TRACE("%s", "internal error - assertion failed");
  12689. return SSL_TLSEXT_ERR_NOACK;
  12690. }
  12691. /* Old clients (Win XP) will not support SNI. Then, there
  12692. * is no server name available in the request - we can
  12693. * only work with the default certificate.
  12694. * Multiple HTTPS hosts on one IP+port are only possible
  12695. * with a certificate containing all alternative names.
  12696. */
  12697. if ((servername == NULL) || (*servername == 0)) {
  12698. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  12699. conn->dom_ctx = &(ctx->dd);
  12700. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  12701. return SSL_TLSEXT_ERR_NOACK;
  12702. }
  12703. DEBUG_TRACE("TLS connection to host %s", servername);
  12704. while (dom) {
  12705. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  12706. /* Found matching domain */
  12707. DEBUG_TRACE("TLS domain %s found",
  12708. dom->config[AUTHENTICATION_DOMAIN]);
  12709. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  12710. conn->dom_ctx = dom;
  12711. return SSL_TLSEXT_ERR_OK;
  12712. }
  12713. dom = dom->next;
  12714. }
  12715. /* Default domain */
  12716. DEBUG_TRACE("TLS default domain %s used",
  12717. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  12718. conn->dom_ctx = &(ctx->dd);
  12719. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  12720. return SSL_TLSEXT_ERR_OK;
  12721. }
  12722. /* Setup SSL CTX as required by CivetWeb */
  12723. static int
  12724. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  12725. struct mg_domain_context *dom_ctx,
  12726. const char *pem,
  12727. const char *chain)
  12728. {
  12729. int callback_ret;
  12730. int should_verify_peer;
  12731. int peer_certificate_optional;
  12732. const char *ca_path;
  12733. const char *ca_file;
  12734. int use_default_verify_paths;
  12735. int verify_depth;
  12736. time_t now_rt = time(NULL);
  12737. struct timespec now_mt;
  12738. md5_byte_t ssl_context_id[16];
  12739. md5_state_t md5state;
  12740. int protocol_ver;
  12741. #ifdef OPENSSL_API_1_1
  12742. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  12743. mg_cry_internal(fc(phys_ctx),
  12744. "SSL_CTX_new (server) error: %s",
  12745. ssl_error());
  12746. return 0;
  12747. }
  12748. #else
  12749. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  12750. mg_cry_internal(fc(phys_ctx),
  12751. "SSL_CTX_new (server) error: %s",
  12752. ssl_error());
  12753. return 0;
  12754. }
  12755. #endif /* OPENSSL_API_1_1 */
  12756. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  12757. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  12758. | SSL_OP_NO_TLSv1_1);
  12759. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  12760. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  12761. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  12762. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  12763. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  12764. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  12765. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  12766. #if !defined(NO_SSL_DL)
  12767. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  12768. #endif /* NO_SSL_DL */
  12769. #ifdef __clang__
  12770. #pragma clang diagnostic push
  12771. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  12772. #endif
  12773. /* Depending on the OpenSSL version, the callback may be
  12774. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  12775. * yielding in an "incompatible-pointer-type" warning for the other
  12776. * version. It seems to be "unclear" what is correct:
  12777. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  12778. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  12779. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  12780. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  12781. * Disable this warning here.
  12782. * Alternative would be a version dependent ssl_info_callback and
  12783. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  12784. */
  12785. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  12786. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  12787. ssl_servername_callback);
  12788. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  12789. #ifdef __clang__
  12790. #pragma clang diagnostic pop
  12791. #endif
  12792. /* If a callback has been specified, call it. */
  12793. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  12794. ? 0
  12795. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  12796. phys_ctx->user_data));
  12797. /* If callback returns 0, civetweb sets up the SSL certificate.
  12798. * If it returns 1, civetweb assumes the calback already did this.
  12799. * If it returns -1, initializing ssl fails. */
  12800. if (callback_ret < 0) {
  12801. mg_cry_internal(fc(phys_ctx),
  12802. "SSL callback returned error: %i",
  12803. callback_ret);
  12804. return 0;
  12805. }
  12806. if (callback_ret > 0) {
  12807. /* Callback did everything. */
  12808. return 1;
  12809. }
  12810. /* Use some UID as session context ID. */
  12811. md5_init(&md5state);
  12812. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  12813. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  12814. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  12815. md5_append(&md5state,
  12816. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  12817. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  12818. md5_append(&md5state,
  12819. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  12820. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  12821. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  12822. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  12823. md5_finish(&md5state, ssl_context_id);
  12824. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  12825. (const unsigned char *)&ssl_context_id,
  12826. sizeof(ssl_context_id));
  12827. if (pem != NULL) {
  12828. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  12829. return 0;
  12830. }
  12831. }
  12832. /* Should we support client certificates? */
  12833. /* Default is "no". */
  12834. should_verify_peer = 0;
  12835. peer_certificate_optional = 0;
  12836. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12837. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  12838. /* Yes, they are mandatory */
  12839. should_verify_peer = 1;
  12840. peer_certificate_optional = 0;
  12841. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  12842. "optional") == 0) {
  12843. /* Yes, they are optional */
  12844. should_verify_peer = 1;
  12845. peer_certificate_optional = 1;
  12846. }
  12847. }
  12848. use_default_verify_paths =
  12849. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  12850. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  12851. == 0);
  12852. if (should_verify_peer) {
  12853. ca_path = dom_ctx->config[SSL_CA_PATH];
  12854. ca_file = dom_ctx->config[SSL_CA_FILE];
  12855. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  12856. != 1) {
  12857. mg_cry_internal(fc(phys_ctx),
  12858. "SSL_CTX_load_verify_locations error: %s "
  12859. "ssl_verify_peer requires setting "
  12860. "either ssl_ca_path or ssl_ca_file. "
  12861. "Is any of them present in the "
  12862. ".conf file?",
  12863. ssl_error());
  12864. return 0;
  12865. }
  12866. if (peer_certificate_optional) {
  12867. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  12868. } else {
  12869. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  12870. SSL_VERIFY_PEER
  12871. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  12872. NULL);
  12873. }
  12874. if (use_default_verify_paths
  12875. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  12876. mg_cry_internal(fc(phys_ctx),
  12877. "SSL_CTX_set_default_verify_paths error: %s",
  12878. ssl_error());
  12879. return 0;
  12880. }
  12881. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  12882. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  12883. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  12884. }
  12885. }
  12886. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  12887. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  12888. dom_ctx->config[SSL_CIPHER_LIST]) != 1) {
  12889. mg_cry_internal(fc(phys_ctx),
  12890. "SSL_CTX_set_cipher_list error: %s",
  12891. ssl_error());
  12892. }
  12893. }
  12894. return 1;
  12895. }
  12896. /* Check if SSL is required.
  12897. * If so, dynamically load SSL library
  12898. * and set up ctx->ssl_ctx pointer. */
  12899. static int
  12900. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  12901. {
  12902. void *ssl_ctx = 0;
  12903. int callback_ret;
  12904. const char *pem;
  12905. const char *chain;
  12906. char ebuf[128];
  12907. if (!phys_ctx) {
  12908. return 0;
  12909. }
  12910. if (!dom_ctx) {
  12911. dom_ctx = &(phys_ctx->dd);
  12912. }
  12913. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  12914. /* No SSL port is set. No need to setup SSL. */
  12915. return 1;
  12916. }
  12917. /* Check for external SSL_CTX */
  12918. callback_ret =
  12919. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  12920. ? 0
  12921. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  12922. phys_ctx->user_data));
  12923. if (callback_ret < 0) {
  12924. mg_cry_internal(fc(phys_ctx),
  12925. "external_ssl_ctx callback returned error: %i",
  12926. callback_ret);
  12927. return 0;
  12928. } else if (callback_ret > 0) {
  12929. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  12930. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12931. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  12932. return 0;
  12933. }
  12934. return 1;
  12935. }
  12936. /* else: external_ssl_ctx does not exist or returns 0,
  12937. * CivetWeb should continue initializing SSL */
  12938. /* If PEM file is not specified and the init_ssl callback
  12939. * is not specified, setup will fail. */
  12940. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  12941. && (phys_ctx->callbacks.init_ssl == NULL)) {
  12942. /* No certificate and no callback:
  12943. * Essential data to set up TLS is missing.
  12944. */
  12945. mg_cry_internal(fc(phys_ctx),
  12946. "Initializing SSL failed: -%s is not set",
  12947. config_options[SSL_CERTIFICATE].name);
  12948. return 0;
  12949. }
  12950. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12951. if (chain == NULL) {
  12952. chain = pem;
  12953. }
  12954. if ((chain != NULL) && (*chain == 0)) {
  12955. chain = NULL;
  12956. }
  12957. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12958. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  12959. return 0;
  12960. }
  12961. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  12962. }
  12963. static void
  12964. uninitialize_ssl(void)
  12965. {
  12966. #ifdef OPENSSL_API_1_1
  12967. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12968. /* Shutdown according to
  12969. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12970. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12971. */
  12972. CONF_modules_unload(1);
  12973. #else
  12974. int i;
  12975. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12976. /* Shutdown according to
  12977. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12978. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12979. */
  12980. CRYPTO_set_locking_callback(NULL);
  12981. CRYPTO_set_id_callback(NULL);
  12982. ENGINE_cleanup();
  12983. CONF_modules_unload(1);
  12984. ERR_free_strings();
  12985. EVP_cleanup();
  12986. CRYPTO_cleanup_all_ex_data();
  12987. ERR_remove_state(0);
  12988. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12989. pthread_mutex_destroy(&ssl_mutexes[i]);
  12990. }
  12991. mg_free(ssl_mutexes);
  12992. ssl_mutexes = NULL;
  12993. #endif /* OPENSSL_API_1_1 */
  12994. }
  12995. }
  12996. #endif /* !NO_SSL */
  12997. static int
  12998. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  12999. {
  13000. if (phys_ctx) {
  13001. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13002. const char *path;
  13003. if (!dom_ctx) {
  13004. dom_ctx = &(phys_ctx->dd);
  13005. }
  13006. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13007. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  13008. mg_cry_internal(fc(phys_ctx),
  13009. "Cannot open %s: %s",
  13010. path,
  13011. strerror(ERRNO));
  13012. return 0;
  13013. }
  13014. return 1;
  13015. }
  13016. return 0;
  13017. }
  13018. static int
  13019. set_acl_option(struct mg_context *phys_ctx)
  13020. {
  13021. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13022. }
  13023. static void
  13024. reset_per_request_attributes(struct mg_connection *conn)
  13025. {
  13026. if (!conn) {
  13027. return;
  13028. }
  13029. conn->connection_type =
  13030. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13031. conn->num_bytes_sent = conn->consumed_content = 0;
  13032. conn->path_info = NULL;
  13033. conn->status_code = -1;
  13034. conn->content_len = -1;
  13035. conn->is_chunked = 0;
  13036. conn->must_close = 0;
  13037. conn->request_len = 0;
  13038. conn->throttle = 0;
  13039. conn->data_len = 0;
  13040. conn->chunk_remainder = 0;
  13041. conn->accept_gzip = 0;
  13042. conn->response_info.content_length = conn->request_info.content_length = -1;
  13043. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13044. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13045. conn->response_info.status_text = NULL;
  13046. conn->response_info.status_code = 0;
  13047. conn->request_info.remote_user = NULL;
  13048. conn->request_info.request_method = NULL;
  13049. conn->request_info.request_uri = NULL;
  13050. conn->request_info.local_uri = NULL;
  13051. #if defined(MG_LEGACY_INTERFACE)
  13052. /* Legacy before split into local_uri and request_uri */
  13053. conn->request_info.uri = NULL;
  13054. #endif
  13055. }
  13056. #if 0
  13057. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13058. * Leave this function here (commented out) for reference until
  13059. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13060. * no longer required.
  13061. */
  13062. static int
  13063. set_sock_timeout(SOCKET sock, int milliseconds)
  13064. {
  13065. int r0 = 0, r1, r2;
  13066. #ifdef _WIN32
  13067. /* Windows specific */
  13068. DWORD tv = (DWORD)milliseconds;
  13069. #else
  13070. /* Linux, ... (not Windows) */
  13071. struct timeval tv;
  13072. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13073. * max. time waiting for the acknowledged of TCP data before the connection
  13074. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13075. * If this option is not set, the default timeout of 20-30 minutes is used.
  13076. */
  13077. /* #define TCP_USER_TIMEOUT (18) */
  13078. #if defined(TCP_USER_TIMEOUT)
  13079. unsigned int uto = (unsigned int)milliseconds;
  13080. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13081. #endif
  13082. memset(&tv, 0, sizeof(tv));
  13083. tv.tv_sec = milliseconds / 1000;
  13084. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13085. #endif /* _WIN32 */
  13086. r1 = setsockopt(
  13087. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13088. r2 = setsockopt(
  13089. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13090. return r0 || r1 || r2;
  13091. }
  13092. #endif
  13093. static int
  13094. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13095. {
  13096. if (setsockopt(sock,
  13097. IPPROTO_TCP,
  13098. TCP_NODELAY,
  13099. (SOCK_OPT_TYPE)&nodelay_on,
  13100. sizeof(nodelay_on)) != 0) {
  13101. /* Error */
  13102. return 1;
  13103. }
  13104. /* OK */
  13105. return 0;
  13106. }
  13107. static void
  13108. close_socket_gracefully(struct mg_connection *conn)
  13109. {
  13110. #if defined(_WIN32)
  13111. char buf[MG_BUF_LEN];
  13112. int n;
  13113. #endif
  13114. struct linger linger;
  13115. int error_code = 0;
  13116. int linger_timeout = -2;
  13117. socklen_t opt_len = sizeof(error_code);
  13118. if (!conn) {
  13119. return;
  13120. }
  13121. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13122. * "Note that enabling a nonzero timeout on a nonblocking socket
  13123. * is not recommended.", so set it to blocking now */
  13124. set_blocking_mode(conn->client.sock);
  13125. /* Send FIN to the client */
  13126. shutdown(conn->client.sock, SHUTDOWN_WR);
  13127. #if defined(_WIN32)
  13128. /* Read and discard pending incoming data. If we do not do that and
  13129. * close
  13130. * the socket, the data in the send buffer may be discarded. This
  13131. * behaviour is seen on Windows, when client keeps sending data
  13132. * when server decides to close the connection; then when client
  13133. * does recv() it gets no data back. */
  13134. do {
  13135. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13136. } while (n > 0);
  13137. #endif
  13138. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13139. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13140. }
  13141. /* Set linger option according to configuration */
  13142. if (linger_timeout >= 0) {
  13143. /* Set linger option to avoid socket hanging out after close. This
  13144. * prevent ephemeral port exhaust problem under high QPS. */
  13145. linger.l_onoff = 1;
  13146. #if defined(_MSC_VER)
  13147. #pragma warning(push)
  13148. #pragma warning(disable : 4244)
  13149. #endif
  13150. #if defined(__GNUC__) || defined(__MINGW32__)
  13151. #pragma GCC diagnostic push
  13152. #pragma GCC diagnostic ignored "-Wconversion"
  13153. #endif
  13154. /* Data type of linger structure elements may differ,
  13155. * so we don't know what cast we need here.
  13156. * Disable type conversion warnings. */
  13157. linger.l_linger = (linger_timeout + 999) / 1000;
  13158. #if defined(__GNUC__) || defined(__MINGW32__)
  13159. #pragma GCC diagnostic pop
  13160. #endif
  13161. #if defined(_MSC_VER)
  13162. #pragma warning(pop)
  13163. #endif
  13164. } else {
  13165. linger.l_onoff = 0;
  13166. linger.l_linger = 0;
  13167. }
  13168. if (linger_timeout < -1) {
  13169. /* Default: don't configure any linger */
  13170. } else if (getsockopt(conn->client.sock,
  13171. SOL_SOCKET,
  13172. SO_ERROR,
  13173. (char *)&error_code,
  13174. &opt_len) != 0) {
  13175. /* Cannot determine if socket is already closed. This should
  13176. * not occur and never did in a test. Log an error message
  13177. * and continue. */
  13178. mg_cry_internal(conn,
  13179. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  13180. __func__,
  13181. strerror(ERRNO));
  13182. } else if (error_code == ECONNRESET) {
  13183. /* Socket already closed by client/peer, close socket without linger
  13184. */
  13185. } else {
  13186. /* Set linger timeout */
  13187. if (setsockopt(conn->client.sock,
  13188. SOL_SOCKET,
  13189. SO_LINGER,
  13190. (char *)&linger,
  13191. sizeof(linger)) != 0) {
  13192. mg_cry_internal(
  13193. conn,
  13194. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  13195. __func__,
  13196. linger.l_onoff,
  13197. linger.l_linger,
  13198. strerror(ERRNO));
  13199. }
  13200. }
  13201. /* Now we know that our FIN is ACK-ed, safe to close */
  13202. closesocket(conn->client.sock);
  13203. conn->client.sock = INVALID_SOCKET;
  13204. }
  13205. static void
  13206. close_connection(struct mg_connection *conn)
  13207. {
  13208. #if defined(USE_SERVER_STATS)
  13209. conn->conn_state = 6; /* to close */
  13210. #endif
  13211. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13212. if (conn->lua_websocket_state) {
  13213. lua_websocket_close(conn, conn->lua_websocket_state);
  13214. conn->lua_websocket_state = NULL;
  13215. }
  13216. #endif
  13217. mg_lock_connection(conn);
  13218. /* Set close flag, so keep-alive loops will stop */
  13219. conn->must_close = 1;
  13220. /* call the connection_close callback if assigned */
  13221. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  13222. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13223. conn->phys_ctx->callbacks.connection_close(conn);
  13224. }
  13225. }
  13226. /* Reset user data, after close callback is called.
  13227. * Do not reuse it. If the user needs a destructor,
  13228. * it must be done in the connection_close callback. */
  13229. mg_set_user_connection_data(conn, NULL);
  13230. #if defined(USE_SERVER_STATS)
  13231. conn->conn_state = 7; /* closing */
  13232. #endif
  13233. #ifndef NO_SSL
  13234. if (conn->ssl != NULL) {
  13235. /* Run SSL_shutdown twice to ensure completely close SSL connection
  13236. */
  13237. SSL_shutdown(conn->ssl);
  13238. SSL_free(conn->ssl);
  13239. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  13240. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  13241. #ifndef OPENSSL_API_1_1
  13242. ERR_remove_state(0);
  13243. #endif
  13244. conn->ssl = NULL;
  13245. }
  13246. #endif
  13247. if (conn->client.sock != INVALID_SOCKET) {
  13248. close_socket_gracefully(conn);
  13249. conn->client.sock = INVALID_SOCKET;
  13250. }
  13251. if (conn->host) {
  13252. mg_free((void *)conn->host);
  13253. conn->host = NULL;
  13254. }
  13255. mg_unlock_connection(conn);
  13256. #if defined(USE_SERVER_STATS)
  13257. conn->conn_state = 8; /* closed */
  13258. #endif
  13259. }
  13260. void
  13261. mg_close_connection(struct mg_connection *conn)
  13262. {
  13263. #if defined(USE_WEBSOCKET)
  13264. struct mg_context *client_ctx = NULL;
  13265. #endif /* defined(USE_WEBSOCKET) */
  13266. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  13267. return;
  13268. }
  13269. #if defined(USE_WEBSOCKET)
  13270. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13271. if (conn->in_websocket_handling) {
  13272. /* Set close flag, so the server thread can exit. */
  13273. conn->must_close = 1;
  13274. return;
  13275. }
  13276. }
  13277. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  13278. unsigned int i;
  13279. /* ws/wss client */
  13280. client_ctx = conn->phys_ctx;
  13281. /* client context: loops must end */
  13282. client_ctx->stop_flag = 1;
  13283. conn->must_close = 1;
  13284. /* We need to get the client thread out of the select/recv call
  13285. * here. */
  13286. /* Since we use a sleep quantum of some seconds to check for recv
  13287. * timeouts, we will just wait a few seconds in mg_join_thread. */
  13288. /* join worker thread */
  13289. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  13290. if (client_ctx->worker_threadids[i] != 0) {
  13291. mg_join_thread(client_ctx->worker_threadids[i]);
  13292. }
  13293. }
  13294. }
  13295. #endif /* defined(USE_WEBSOCKET) */
  13296. close_connection(conn);
  13297. #ifndef NO_SSL
  13298. if (conn->client_ssl_ctx != NULL) {
  13299. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  13300. }
  13301. #endif
  13302. #if defined(USE_WEBSOCKET)
  13303. if (client_ctx != NULL) {
  13304. /* free context */
  13305. mg_free(client_ctx->worker_threadids);
  13306. mg_free(client_ctx);
  13307. (void)pthread_mutex_destroy(&conn->mutex);
  13308. mg_free(conn);
  13309. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  13310. mg_free(conn);
  13311. }
  13312. #else
  13313. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  13314. mg_free(conn);
  13315. }
  13316. #endif /* defined(USE_WEBSOCKET) */
  13317. }
  13318. /* Only for memory statistics */
  13319. static struct mg_context common_client_context;
  13320. static struct mg_connection *
  13321. mg_connect_client_impl(const struct mg_client_options *client_options,
  13322. int use_ssl,
  13323. char *ebuf,
  13324. size_t ebuf_len)
  13325. {
  13326. struct mg_connection *conn = NULL;
  13327. SOCKET sock;
  13328. union usa sa;
  13329. struct sockaddr *psa;
  13330. socklen_t len;
  13331. unsigned max_req_size =
  13332. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  13333. /* Size of structures, aligned to 8 bytes */
  13334. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  13335. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  13336. conn = (struct mg_connection *)mg_calloc_ctx(1,
  13337. conn_size + ctx_size
  13338. + max_req_size,
  13339. &common_client_context);
  13340. if (conn == NULL) {
  13341. mg_snprintf(NULL,
  13342. NULL, /* No truncation check for ebuf */
  13343. ebuf,
  13344. ebuf_len,
  13345. "calloc(): %s",
  13346. strerror(ERRNO));
  13347. return NULL;
  13348. }
  13349. #if defined(__GNUC__) || defined(__MINGW32__)
  13350. #pragma GCC diagnostic push
  13351. #pragma GCC diagnostic ignored "-Wcast-align"
  13352. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13353. /* conn_size is aligned to 8 bytes */
  13354. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  13355. #if defined(__GNUC__) || defined(__MINGW32__)
  13356. #pragma GCC diagnostic pop
  13357. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13358. conn->buf = (((char *)conn) + conn_size + ctx_size);
  13359. conn->buf_size = (int)max_req_size;
  13360. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  13361. conn->dom_ctx = &(conn->phys_ctx->dd);
  13362. if (!connect_socket(&common_client_context,
  13363. client_options->host,
  13364. client_options->port,
  13365. use_ssl,
  13366. ebuf,
  13367. ebuf_len,
  13368. &sock,
  13369. &sa)) {
  13370. /* ebuf is set by connect_socket,
  13371. * free all memory and return NULL; */
  13372. mg_free(conn);
  13373. return NULL;
  13374. }
  13375. #ifndef NO_SSL
  13376. #ifdef OPENSSL_API_1_1
  13377. if (use_ssl
  13378. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  13379. mg_snprintf(NULL,
  13380. NULL, /* No truncation check for ebuf */
  13381. ebuf,
  13382. ebuf_len,
  13383. "SSL_CTX_new error");
  13384. closesocket(sock);
  13385. mg_free(conn);
  13386. return NULL;
  13387. }
  13388. #else
  13389. if (use_ssl
  13390. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  13391. == NULL) {
  13392. mg_snprintf(NULL,
  13393. NULL, /* No truncation check for ebuf */
  13394. ebuf,
  13395. ebuf_len,
  13396. "SSL_CTX_new error");
  13397. closesocket(sock);
  13398. mg_free(conn);
  13399. return NULL;
  13400. }
  13401. #endif /* OPENSSL_API_1_1 */
  13402. #endif /* NO_SSL */
  13403. #ifdef USE_IPV6
  13404. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  13405. : sizeof(conn->client.rsa.sin6);
  13406. psa = (sa.sa.sa_family == AF_INET)
  13407. ? (struct sockaddr *)&(conn->client.rsa.sin)
  13408. : (struct sockaddr *)&(conn->client.rsa.sin6);
  13409. #else
  13410. len = sizeof(conn->client.rsa.sin);
  13411. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  13412. #endif
  13413. conn->client.sock = sock;
  13414. conn->client.lsa = sa;
  13415. if (getsockname(sock, psa, &len) != 0) {
  13416. mg_cry_internal(conn,
  13417. "%s: getsockname() failed: %s",
  13418. __func__,
  13419. strerror(ERRNO));
  13420. }
  13421. conn->client.is_ssl = use_ssl ? 1 : 0;
  13422. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13423. #ifndef NO_SSL
  13424. if (use_ssl) {
  13425. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  13426. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  13427. * SSL_CTX_set_verify call is needed to switch off server
  13428. * certificate checking, which is off by default in OpenSSL and
  13429. * on in yaSSL. */
  13430. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  13431. * SSL_VERIFY_PEER, verify_ssl_server); */
  13432. if (client_options->client_cert) {
  13433. if (!ssl_use_pem_file(&common_client_context,
  13434. &(common_client_context.dd),
  13435. client_options->client_cert,
  13436. NULL)) {
  13437. mg_snprintf(NULL,
  13438. NULL, /* No truncation check for ebuf */
  13439. ebuf,
  13440. ebuf_len,
  13441. "Can not use SSL client certificate");
  13442. SSL_CTX_free(conn->client_ssl_ctx);
  13443. closesocket(sock);
  13444. mg_free(conn);
  13445. return NULL;
  13446. }
  13447. }
  13448. if (client_options->server_cert) {
  13449. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  13450. client_options->server_cert,
  13451. NULL);
  13452. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  13453. } else {
  13454. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  13455. }
  13456. if (!sslize(conn,
  13457. conn->client_ssl_ctx,
  13458. SSL_connect,
  13459. &(conn->phys_ctx->stop_flag))) {
  13460. mg_snprintf(NULL,
  13461. NULL, /* No truncation check for ebuf */
  13462. ebuf,
  13463. ebuf_len,
  13464. "SSL connection error");
  13465. SSL_CTX_free(conn->client_ssl_ctx);
  13466. closesocket(sock);
  13467. mg_free(conn);
  13468. return NULL;
  13469. }
  13470. }
  13471. #endif
  13472. if (0 != set_non_blocking_mode(sock)) {
  13473. /* TODO: handle error */
  13474. ;
  13475. }
  13476. return conn;
  13477. }
  13478. CIVETWEB_API struct mg_connection *
  13479. mg_connect_client_secure(const struct mg_client_options *client_options,
  13480. char *error_buffer,
  13481. size_t error_buffer_size)
  13482. {
  13483. return mg_connect_client_impl(client_options,
  13484. 1,
  13485. error_buffer,
  13486. error_buffer_size);
  13487. }
  13488. struct mg_connection *
  13489. mg_connect_client(const char *host,
  13490. int port,
  13491. int use_ssl,
  13492. char *error_buffer,
  13493. size_t error_buffer_size)
  13494. {
  13495. struct mg_client_options opts;
  13496. memset(&opts, 0, sizeof(opts));
  13497. opts.host = host;
  13498. opts.port = port;
  13499. return mg_connect_client_impl(&opts,
  13500. use_ssl,
  13501. error_buffer,
  13502. error_buffer_size);
  13503. }
  13504. static const struct {
  13505. const char *proto;
  13506. size_t proto_len;
  13507. unsigned default_port;
  13508. } abs_uri_protocols[] = {{"http://", 7, 80},
  13509. {"https://", 8, 443},
  13510. {"ws://", 5, 80},
  13511. {"wss://", 6, 443},
  13512. {NULL, 0, 0}};
  13513. /* Check if the uri is valid.
  13514. * return 0 for invalid uri,
  13515. * return 1 for *,
  13516. * return 2 for relative uri,
  13517. * return 3 for absolute uri without port,
  13518. * return 4 for absolute uri with port */
  13519. static int
  13520. get_uri_type(const char *uri)
  13521. {
  13522. int i;
  13523. const char *hostend, *portbegin;
  13524. char *portend;
  13525. unsigned long port;
  13526. /* According to the HTTP standard
  13527. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  13528. * URI can be an asterisk (*) or should start with slash (relative uri),
  13529. * or it should start with the protocol (absolute uri). */
  13530. if ((uri[0] == '*') && (uri[1] == '\0')) {
  13531. /* asterisk */
  13532. return 1;
  13533. }
  13534. /* Valid URIs according to RFC 3986
  13535. * (https://www.ietf.org/rfc/rfc3986.txt)
  13536. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  13537. * and unreserved characters A-Z a-z 0-9 and -._~
  13538. * and % encoded symbols.
  13539. */
  13540. for (i = 0; uri[i] != 0; i++) {
  13541. if (uri[i] < 33) {
  13542. /* control characters and spaces are invalid */
  13543. return 0;
  13544. }
  13545. if (uri[i] > 126) {
  13546. /* non-ascii characters must be % encoded */
  13547. return 0;
  13548. } else {
  13549. switch (uri[i]) {
  13550. case '"': /* 34 */
  13551. case '<': /* 60 */
  13552. case '>': /* 62 */
  13553. case '\\': /* 92 */
  13554. case '^': /* 94 */
  13555. case '`': /* 96 */
  13556. case '{': /* 123 */
  13557. case '|': /* 124 */
  13558. case '}': /* 125 */
  13559. return 0;
  13560. default:
  13561. /* character is ok */
  13562. break;
  13563. }
  13564. }
  13565. }
  13566. /* A relative uri starts with a / character */
  13567. if (uri[0] == '/') {
  13568. /* relative uri */
  13569. return 2;
  13570. }
  13571. /* It could be an absolute uri: */
  13572. /* This function only checks if the uri is valid, not if it is
  13573. * addressing the current server. So civetweb can also be used
  13574. * as a proxy server. */
  13575. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13576. if (mg_strncasecmp(uri,
  13577. abs_uri_protocols[i].proto,
  13578. abs_uri_protocols[i].proto_len) == 0) {
  13579. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  13580. if (!hostend) {
  13581. return 0;
  13582. }
  13583. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  13584. if (!portbegin) {
  13585. return 3;
  13586. }
  13587. port = strtoul(portbegin + 1, &portend, 10);
  13588. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  13589. return 0;
  13590. }
  13591. return 4;
  13592. }
  13593. }
  13594. return 0;
  13595. }
  13596. /* Return NULL or the relative uri at the current server */
  13597. static const char *
  13598. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  13599. {
  13600. const char *server_domain;
  13601. size_t server_domain_len;
  13602. size_t request_domain_len = 0;
  13603. unsigned long port = 0;
  13604. int i, auth_domain_check_enabled;
  13605. const char *hostbegin = NULL;
  13606. const char *hostend = NULL;
  13607. const char *portbegin;
  13608. char *portend;
  13609. auth_domain_check_enabled =
  13610. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  13611. /* DNS is case insensitive, so use case insensitive string compare here
  13612. */
  13613. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13614. if (mg_strncasecmp(uri,
  13615. abs_uri_protocols[i].proto,
  13616. abs_uri_protocols[i].proto_len) == 0) {
  13617. hostbegin = uri + abs_uri_protocols[i].proto_len;
  13618. hostend = strchr(hostbegin, '/');
  13619. if (!hostend) {
  13620. return 0;
  13621. }
  13622. portbegin = strchr(hostbegin, ':');
  13623. if ((!portbegin) || (portbegin > hostend)) {
  13624. port = abs_uri_protocols[i].default_port;
  13625. request_domain_len = (size_t)(hostend - hostbegin);
  13626. } else {
  13627. port = strtoul(portbegin + 1, &portend, 10);
  13628. if ((portend != hostend) || (port <= 0)
  13629. || !is_valid_port(port)) {
  13630. return 0;
  13631. }
  13632. request_domain_len = (size_t)(portbegin - hostbegin);
  13633. }
  13634. /* protocol found, port set */
  13635. break;
  13636. }
  13637. }
  13638. if (!port) {
  13639. /* port remains 0 if the protocol is not found */
  13640. return 0;
  13641. }
  13642. /* Check if the request is directed to a different server. */
  13643. /* First check if the port is the same (IPv4 and IPv6). */
  13644. #if defined(USE_IPV6)
  13645. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  13646. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  13647. /* Request is directed to a different port */
  13648. return 0;
  13649. }
  13650. } else
  13651. #endif
  13652. {
  13653. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  13654. /* Request is directed to a different port */
  13655. return 0;
  13656. }
  13657. }
  13658. /* Finally check if the server corresponds to the authentication
  13659. * domain of the server (the server domain).
  13660. * Allow full matches (like http://mydomain.com/path/file.ext), and
  13661. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  13662. * but do not allow substrings (like
  13663. * http://notmydomain.com/path/file.ext
  13664. * or http://mydomain.com.fake/path/file.ext).
  13665. */
  13666. if (auth_domain_check_enabled) {
  13667. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  13668. server_domain_len = strlen(server_domain);
  13669. if (!server_domain_len) {
  13670. return 0;
  13671. }
  13672. if ((request_domain_len == server_domain_len)
  13673. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  13674. /* Request is directed to this server - full name match. */
  13675. } else {
  13676. if (request_domain_len < (server_domain_len + 2)) {
  13677. /* Request is directed to another server: The server name is
  13678. * longer
  13679. * than
  13680. * the request name. Drop this case here to avoid overflows
  13681. * in
  13682. * the
  13683. * following checks. */
  13684. return 0;
  13685. }
  13686. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  13687. /* Request is directed to another server: It could be a
  13688. * substring
  13689. * like notmyserver.com */
  13690. return 0;
  13691. }
  13692. if (0 != memcmp(server_domain,
  13693. hostbegin + request_domain_len - server_domain_len,
  13694. server_domain_len)) {
  13695. /* Request is directed to another server:
  13696. * The server name is different. */
  13697. return 0;
  13698. }
  13699. }
  13700. }
  13701. return hostend;
  13702. }
  13703. static int
  13704. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13705. {
  13706. if (ebuf_len > 0) {
  13707. ebuf[0] = '\0';
  13708. }
  13709. *err = 0;
  13710. reset_per_request_attributes(conn);
  13711. if (!conn) {
  13712. mg_snprintf(conn,
  13713. NULL, /* No truncation check for ebuf */
  13714. ebuf,
  13715. ebuf_len,
  13716. "%s",
  13717. "Internal error");
  13718. *err = 500;
  13719. return 0;
  13720. }
  13721. /* Set the time the request was received. This value should be used for
  13722. * timeouts. */
  13723. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  13724. conn->request_len =
  13725. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  13726. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  13727. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  13728. mg_snprintf(conn,
  13729. NULL, /* No truncation check for ebuf */
  13730. ebuf,
  13731. ebuf_len,
  13732. "%s",
  13733. "Invalid message size");
  13734. *err = 500;
  13735. return 0;
  13736. }
  13737. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  13738. mg_snprintf(conn,
  13739. NULL, /* No truncation check for ebuf */
  13740. ebuf,
  13741. ebuf_len,
  13742. "%s",
  13743. "Message too large");
  13744. *err = 413;
  13745. return 0;
  13746. }
  13747. if (conn->request_len <= 0) {
  13748. if (conn->data_len > 0) {
  13749. mg_snprintf(conn,
  13750. NULL, /* No truncation check for ebuf */
  13751. ebuf,
  13752. ebuf_len,
  13753. "%s",
  13754. "Malformed message");
  13755. *err = 400;
  13756. } else {
  13757. /* Server did not recv anything -> just close the connection */
  13758. conn->must_close = 1;
  13759. mg_snprintf(conn,
  13760. NULL, /* No truncation check for ebuf */
  13761. ebuf,
  13762. ebuf_len,
  13763. "%s",
  13764. "No data received");
  13765. *err = 0;
  13766. }
  13767. return 0;
  13768. }
  13769. return 1;
  13770. }
  13771. static int
  13772. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13773. {
  13774. const char *cl;
  13775. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13776. return 0;
  13777. }
  13778. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  13779. <= 0) {
  13780. mg_snprintf(conn,
  13781. NULL, /* No truncation check for ebuf */
  13782. ebuf,
  13783. ebuf_len,
  13784. "%s",
  13785. "Bad request");
  13786. *err = 400;
  13787. return 0;
  13788. }
  13789. /* Message is a valid request */
  13790. /* Is there a "host" ? */
  13791. conn->host = alloc_get_host(conn);
  13792. if (!conn->host) {
  13793. mg_snprintf(conn,
  13794. NULL, /* No truncation check for ebuf */
  13795. ebuf,
  13796. ebuf_len,
  13797. "%s",
  13798. "Bad request: Host mismatch");
  13799. *err = 400;
  13800. return 0;
  13801. }
  13802. /* Do we know the content length? */
  13803. if ((cl = get_header(conn->request_info.http_headers,
  13804. conn->request_info.num_headers,
  13805. "Content-Length")) != NULL) {
  13806. /* Request/response has content length set */
  13807. char *endptr = NULL;
  13808. conn->content_len = strtoll(cl, &endptr, 10);
  13809. if (endptr == cl) {
  13810. mg_snprintf(conn,
  13811. NULL, /* No truncation check for ebuf */
  13812. ebuf,
  13813. ebuf_len,
  13814. "%s",
  13815. "Bad request");
  13816. *err = 411;
  13817. return 0;
  13818. }
  13819. /* Publish the content length back to the request info. */
  13820. conn->request_info.content_length = conn->content_len;
  13821. } else if ((cl = get_header(conn->request_info.http_headers,
  13822. conn->request_info.num_headers,
  13823. "Transfer-Encoding")) != NULL
  13824. && !mg_strcasecmp(cl, "chunked")) {
  13825. conn->is_chunked = 1;
  13826. conn->content_len = -1; /* unknown content length */
  13827. } else if (get_http_method_info(conn->request_info.request_method)
  13828. ->request_has_body) {
  13829. /* POST or PUT request without content length set */
  13830. conn->content_len = -1; /* unknown content length */
  13831. } else {
  13832. /* Other request */
  13833. conn->content_len = 0; /* No content */
  13834. }
  13835. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  13836. return 1;
  13837. }
  13838. /* conn is assumed to be valid in this internal function */
  13839. static int
  13840. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13841. {
  13842. const char *cl;
  13843. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13844. return 0;
  13845. }
  13846. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  13847. <= 0) {
  13848. mg_snprintf(conn,
  13849. NULL, /* No truncation check for ebuf */
  13850. ebuf,
  13851. ebuf_len,
  13852. "%s",
  13853. "Bad response");
  13854. *err = 400;
  13855. return 0;
  13856. }
  13857. /* Message is a valid response */
  13858. /* Do we know the content length? */
  13859. if ((cl = get_header(conn->response_info.http_headers,
  13860. conn->response_info.num_headers,
  13861. "Content-Length")) != NULL) {
  13862. /* Request/response has content length set */
  13863. char *endptr = NULL;
  13864. conn->content_len = strtoll(cl, &endptr, 10);
  13865. if (endptr == cl) {
  13866. mg_snprintf(conn,
  13867. NULL, /* No truncation check for ebuf */
  13868. ebuf,
  13869. ebuf_len,
  13870. "%s",
  13871. "Bad request");
  13872. *err = 411;
  13873. return 0;
  13874. }
  13875. /* Publish the content length back to the response info. */
  13876. conn->response_info.content_length = conn->content_len;
  13877. /* TODO: check if it is still used in response_info */
  13878. conn->request_info.content_length = conn->content_len;
  13879. } else if ((cl = get_header(conn->response_info.http_headers,
  13880. conn->response_info.num_headers,
  13881. "Transfer-Encoding")) != NULL
  13882. && !mg_strcasecmp(cl, "chunked")) {
  13883. conn->is_chunked = 1;
  13884. conn->content_len = -1; /* unknown content length */
  13885. } else {
  13886. conn->content_len = -1; /* unknown content length */
  13887. }
  13888. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  13889. return 1;
  13890. }
  13891. int
  13892. mg_get_response(struct mg_connection *conn,
  13893. char *ebuf,
  13894. size_t ebuf_len,
  13895. int timeout)
  13896. {
  13897. int err, ret;
  13898. char txt[32]; /* will not overflow */
  13899. char *save_timeout;
  13900. char *new_timeout;
  13901. if (ebuf_len > 0) {
  13902. ebuf[0] = '\0';
  13903. }
  13904. if (!conn) {
  13905. mg_snprintf(conn,
  13906. NULL, /* No truncation check for ebuf */
  13907. ebuf,
  13908. ebuf_len,
  13909. "%s",
  13910. "Parameter error");
  13911. return -1;
  13912. }
  13913. /* Implementation of API function for HTTP clients */
  13914. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  13915. if (timeout >= 0) {
  13916. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  13917. new_timeout = txt;
  13918. /* Not required for non-blocking sockets.
  13919. set_sock_timeout(conn->client.sock, timeout);
  13920. */
  13921. } else {
  13922. new_timeout = NULL;
  13923. }
  13924. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  13925. ret = get_response(conn, ebuf, ebuf_len, &err);
  13926. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  13927. #if defined(MG_LEGACY_INTERFACE)
  13928. /* TODO: 1) uri is deprecated;
  13929. * 2) here, ri.uri is the http response code */
  13930. conn->request_info.uri = conn->request_info.request_uri;
  13931. #endif
  13932. conn->request_info.local_uri = conn->request_info.request_uri;
  13933. /* TODO (mid): Define proper return values - maybe return length?
  13934. * For the first test use <0 for error and >0 for OK */
  13935. return (ret == 0) ? -1 : +1;
  13936. }
  13937. struct mg_connection *
  13938. mg_download(const char *host,
  13939. int port,
  13940. int use_ssl,
  13941. char *ebuf,
  13942. size_t ebuf_len,
  13943. const char *fmt,
  13944. ...)
  13945. {
  13946. struct mg_connection *conn;
  13947. va_list ap;
  13948. int i;
  13949. int reqerr;
  13950. if (ebuf_len > 0) {
  13951. ebuf[0] = '\0';
  13952. }
  13953. va_start(ap, fmt);
  13954. /* open a connection */
  13955. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  13956. if (conn != NULL) {
  13957. i = mg_vprintf(conn, fmt, ap);
  13958. if (i <= 0) {
  13959. mg_snprintf(conn,
  13960. NULL, /* No truncation check for ebuf */
  13961. ebuf,
  13962. ebuf_len,
  13963. "%s",
  13964. "Error sending request");
  13965. } else {
  13966. get_response(conn, ebuf, ebuf_len, &reqerr);
  13967. #if defined(MG_LEGACY_INTERFACE)
  13968. /* TODO: 1) uri is deprecated;
  13969. * 2) here, ri.uri is the http response code */
  13970. conn->request_info.uri = conn->request_info.request_uri;
  13971. #endif
  13972. conn->request_info.local_uri = conn->request_info.request_uri;
  13973. }
  13974. }
  13975. /* if an error occurred, close the connection */
  13976. if ((ebuf[0] != '\0') && (conn != NULL)) {
  13977. mg_close_connection(conn);
  13978. conn = NULL;
  13979. }
  13980. va_end(ap);
  13981. return conn;
  13982. }
  13983. struct websocket_client_thread_data {
  13984. struct mg_connection *conn;
  13985. mg_websocket_data_handler data_handler;
  13986. mg_websocket_close_handler close_handler;
  13987. void *callback_data;
  13988. };
  13989. #if defined(USE_WEBSOCKET)
  13990. #ifdef _WIN32
  13991. static unsigned __stdcall websocket_client_thread(void *data)
  13992. #else
  13993. static void *
  13994. websocket_client_thread(void *data)
  13995. #endif
  13996. {
  13997. struct websocket_client_thread_data *cdata =
  13998. (struct websocket_client_thread_data *)data;
  13999. #if !defined(_WIN32)
  14000. struct sigaction sa;
  14001. /* Ignore SIGPIPE */
  14002. memset(&sa, 0, sizeof(sa));
  14003. sa.sa_handler = SIG_IGN;
  14004. sigaction(SIGPIPE, &sa, NULL);
  14005. #endif
  14006. mg_set_thread_name("ws-clnt");
  14007. if (cdata->conn->phys_ctx) {
  14008. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14009. /* 3 indicates a websocket client thread */
  14010. /* TODO: check if conn->phys_ctx can be set */
  14011. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  14012. 3);
  14013. }
  14014. }
  14015. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14016. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14017. if (cdata->close_handler != NULL) {
  14018. cdata->close_handler(cdata->conn, cdata->callback_data);
  14019. }
  14020. /* The websocket_client context has only this thread. If it runs out,
  14021. set the stop_flag to 2 (= "stopped"). */
  14022. cdata->conn->phys_ctx->stop_flag = 2;
  14023. mg_free((void *)cdata);
  14024. #ifdef _WIN32
  14025. return 0;
  14026. #else
  14027. return NULL;
  14028. #endif
  14029. }
  14030. #endif
  14031. struct mg_connection *
  14032. mg_connect_websocket_client(const char *host,
  14033. int port,
  14034. int use_ssl,
  14035. char *error_buffer,
  14036. size_t error_buffer_size,
  14037. const char *path,
  14038. const char *origin,
  14039. mg_websocket_data_handler data_func,
  14040. mg_websocket_close_handler close_func,
  14041. void *user_data)
  14042. {
  14043. struct mg_connection *conn = NULL;
  14044. #if defined(USE_WEBSOCKET)
  14045. struct mg_context *newctx = NULL;
  14046. struct websocket_client_thread_data *thread_data;
  14047. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14048. static const char *handshake_req;
  14049. if (origin != NULL) {
  14050. handshake_req = "GET %s HTTP/1.1\r\n"
  14051. "Host: %s\r\n"
  14052. "Upgrade: websocket\r\n"
  14053. "Connection: Upgrade\r\n"
  14054. "Sec-WebSocket-Key: %s\r\n"
  14055. "Sec-WebSocket-Version: 13\r\n"
  14056. "Origin: %s\r\n"
  14057. "\r\n";
  14058. } else {
  14059. handshake_req = "GET %s HTTP/1.1\r\n"
  14060. "Host: %s\r\n"
  14061. "Upgrade: websocket\r\n"
  14062. "Connection: Upgrade\r\n"
  14063. "Sec-WebSocket-Key: %s\r\n"
  14064. "Sec-WebSocket-Version: 13\r\n"
  14065. "\r\n";
  14066. }
  14067. /* Establish the client connection and request upgrade */
  14068. conn = mg_download(host,
  14069. port,
  14070. use_ssl,
  14071. error_buffer,
  14072. error_buffer_size,
  14073. handshake_req,
  14074. path,
  14075. host,
  14076. magic,
  14077. origin);
  14078. /* Connection object will be null if something goes wrong */
  14079. if (conn == NULL) {
  14080. if (!*error_buffer) {
  14081. /* There should be already an error message */
  14082. mg_snprintf(conn,
  14083. NULL, /* No truncation check for ebuf */
  14084. error_buffer,
  14085. error_buffer_size,
  14086. "Unexpected error");
  14087. }
  14088. return NULL;
  14089. }
  14090. if (conn->response_info.status_code != 101) {
  14091. /* We sent an "upgrade" request. For a correct websocket
  14092. * protocol handshake, we expect a "101 Continue" response.
  14093. * Otherwise it is a protocol violation. Maybe the HTTP
  14094. * Server does not know websockets. */
  14095. if (!*error_buffer) {
  14096. /* set an error, if not yet set */
  14097. mg_snprintf(conn,
  14098. NULL, /* No truncation check for ebuf */
  14099. error_buffer,
  14100. error_buffer_size,
  14101. "Unexpected server reply");
  14102. }
  14103. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14104. mg_free(conn);
  14105. return NULL;
  14106. }
  14107. /* For client connections, mg_context is fake. Since we need to set a
  14108. * callback function, we need to create a copy and modify it. */
  14109. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  14110. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  14111. newctx->user_data = user_data;
  14112. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  14113. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  14114. newctx->worker_threadids =
  14115. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  14116. sizeof(pthread_t),
  14117. newctx);
  14118. conn->phys_ctx = newctx;
  14119. conn->dom_ctx = &(newctx->dd);
  14120. thread_data = (struct websocket_client_thread_data *)
  14121. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  14122. thread_data->conn = conn;
  14123. thread_data->data_handler = data_func;
  14124. thread_data->close_handler = close_func;
  14125. thread_data->callback_data = user_data;
  14126. /* Start a thread to read the websocket client connection
  14127. * This thread will automatically stop when mg_disconnect is
  14128. * called on the client connection */
  14129. if (mg_start_thread_with_id(websocket_client_thread,
  14130. (void *)thread_data,
  14131. newctx->worker_threadids) != 0) {
  14132. mg_free((void *)thread_data);
  14133. mg_free((void *)newctx->worker_threadids);
  14134. mg_free((void *)newctx);
  14135. mg_free((void *)conn);
  14136. conn = NULL;
  14137. DEBUG_TRACE("%s",
  14138. "Websocket client connect thread could not be started\r\n");
  14139. }
  14140. #else
  14141. /* Appease "unused parameter" warnings */
  14142. (void)host;
  14143. (void)port;
  14144. (void)use_ssl;
  14145. (void)error_buffer;
  14146. (void)error_buffer_size;
  14147. (void)path;
  14148. (void)origin;
  14149. (void)user_data;
  14150. (void)data_func;
  14151. (void)close_func;
  14152. #endif
  14153. return conn;
  14154. }
  14155. /* Prepare connection data structure */
  14156. static void
  14157. init_connection(struct mg_connection *conn)
  14158. {
  14159. /* Is keep alive allowed by the server */
  14160. int keep_alive_enabled =
  14161. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  14162. if (!keep_alive_enabled) {
  14163. conn->must_close = 1;
  14164. }
  14165. /* Important: on new connection, reset the receiving buffer. Credit
  14166. * goes to crule42. */
  14167. conn->data_len = 0;
  14168. conn->handled_requests = 0;
  14169. mg_set_user_connection_data(conn, NULL);
  14170. #if defined(USE_SERVER_STATS)
  14171. conn->conn_state = 2; /* init */
  14172. #endif
  14173. /* call the init_connection callback if assigned */
  14174. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  14175. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14176. void *conn_data = NULL;
  14177. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  14178. mg_set_user_connection_data(conn, conn_data);
  14179. }
  14180. }
  14181. }
  14182. /* Process a connection - may handle multiple requests
  14183. * using the same connection.
  14184. * Must be called with a valid connection (conn and
  14185. * conn->phys_ctx must be valid).
  14186. */
  14187. static void
  14188. process_new_connection(struct mg_connection *conn)
  14189. {
  14190. struct mg_request_info *ri = &conn->request_info;
  14191. int keep_alive, discard_len;
  14192. char ebuf[100];
  14193. const char *hostend;
  14194. int reqerr, uri_type;
  14195. #if defined(USE_SERVER_STATS)
  14196. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  14197. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  14198. if (mcon > (conn->phys_ctx->max_connections)) {
  14199. /* could use atomic compare exchange, but this
  14200. * seems overkill for statistics data */
  14201. conn->phys_ctx->max_connections = mcon;
  14202. }
  14203. #endif
  14204. init_connection(conn);
  14205. DEBUG_TRACE("Start processing connection from %s",
  14206. conn->request_info.remote_addr);
  14207. /* Loop over multiple requests sent using the same connection
  14208. * (while "keep alive"). */
  14209. do {
  14210. DEBUG_TRACE("calling get_request (%i times for this connection)",
  14211. conn->handled_requests + 1);
  14212. #if defined(USE_SERVER_STATS)
  14213. conn->conn_state = 3; /* ready */
  14214. #endif
  14215. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  14216. /* The request sent by the client could not be understood by
  14217. * the server, or it was incomplete or a timeout. Send an
  14218. * error message and close the connection. */
  14219. if (reqerr > 0) {
  14220. DEBUG_ASSERT(ebuf[0] != '\0');
  14221. mg_send_http_error(conn, reqerr, "%s", ebuf);
  14222. }
  14223. } else if (strcmp(ri->http_version, "1.0")
  14224. && strcmp(ri->http_version, "1.1")) {
  14225. mg_snprintf(conn,
  14226. NULL, /* No truncation check for ebuf */
  14227. ebuf,
  14228. sizeof(ebuf),
  14229. "Bad HTTP version: [%s]",
  14230. ri->http_version);
  14231. mg_send_http_error(conn, 505, "%s", ebuf);
  14232. }
  14233. if (ebuf[0] == '\0') {
  14234. uri_type = get_uri_type(conn->request_info.request_uri);
  14235. switch (uri_type) {
  14236. case 1:
  14237. /* Asterisk */
  14238. conn->request_info.local_uri = NULL;
  14239. break;
  14240. case 2:
  14241. /* relative uri */
  14242. conn->request_info.local_uri = conn->request_info.request_uri;
  14243. break;
  14244. case 3:
  14245. case 4:
  14246. /* absolute uri (with/without port) */
  14247. hostend = get_rel_url_at_current_server(
  14248. conn->request_info.request_uri, conn);
  14249. if (hostend) {
  14250. conn->request_info.local_uri = hostend;
  14251. } else {
  14252. conn->request_info.local_uri = NULL;
  14253. }
  14254. break;
  14255. default:
  14256. mg_snprintf(conn,
  14257. NULL, /* No truncation check for ebuf */
  14258. ebuf,
  14259. sizeof(ebuf),
  14260. "Invalid URI");
  14261. mg_send_http_error(conn, 400, "%s", ebuf);
  14262. conn->request_info.local_uri = NULL;
  14263. break;
  14264. }
  14265. #if defined(MG_LEGACY_INTERFACE)
  14266. /* Legacy before split into local_uri and request_uri */
  14267. conn->request_info.uri = conn->request_info.local_uri;
  14268. #endif
  14269. }
  14270. DEBUG_TRACE("http: %s, error: %s",
  14271. (ri->http_version ? ri->http_version : "none"),
  14272. (ebuf[0] ? ebuf : "none"));
  14273. if (ebuf[0] == '\0') {
  14274. if (conn->request_info.local_uri) {
  14275. /* handle request to local server */
  14276. #if defined(USE_SERVER_STATS)
  14277. conn->conn_state = 4; /* processing */
  14278. #endif
  14279. handle_request(conn);
  14280. #if defined(USE_SERVER_STATS)
  14281. conn->conn_state = 5; /* processed */
  14282. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  14283. conn->consumed_content);
  14284. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  14285. conn->num_bytes_sent);
  14286. #endif
  14287. DEBUG_TRACE("%s", "handle_request done");
  14288. if (conn->phys_ctx->callbacks.end_request != NULL) {
  14289. conn->phys_ctx->callbacks.end_request(conn,
  14290. conn->status_code);
  14291. DEBUG_TRACE("%s", "end_request callback done");
  14292. }
  14293. log_access(conn);
  14294. } else {
  14295. /* TODO: handle non-local request (PROXY) */
  14296. conn->must_close = 1;
  14297. }
  14298. } else {
  14299. conn->must_close = 1;
  14300. }
  14301. if (ri->remote_user != NULL) {
  14302. mg_free((void *)ri->remote_user);
  14303. /* Important! When having connections with and without auth
  14304. * would cause double free and then crash */
  14305. ri->remote_user = NULL;
  14306. }
  14307. /* NOTE(lsm): order is important here. should_keep_alive() call
  14308. * is using parsed request, which will be invalid after
  14309. * memmove's below.
  14310. * Therefore, memorize should_keep_alive() result now for later
  14311. * use in loop exit condition. */
  14312. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  14313. && (conn->content_len >= 0);
  14314. /* Discard all buffered data for this request */
  14315. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  14316. && ((conn->request_len + conn->content_len)
  14317. < (int64_t)conn->data_len))
  14318. ? (int)(conn->request_len + conn->content_len)
  14319. : conn->data_len;
  14320. DEBUG_ASSERT(discard_len >= 0);
  14321. if (discard_len < 0) {
  14322. DEBUG_TRACE("internal error: discard_len = %li",
  14323. (long int)discard_len);
  14324. break;
  14325. }
  14326. conn->data_len -= discard_len;
  14327. if (conn->data_len > 0) {
  14328. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  14329. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  14330. }
  14331. DEBUG_ASSERT(conn->data_len >= 0);
  14332. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  14333. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  14334. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  14335. (long int)conn->data_len,
  14336. (long int)conn->buf_size);
  14337. break;
  14338. }
  14339. conn->handled_requests++;
  14340. } while (keep_alive);
  14341. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  14342. conn->request_info.remote_addr,
  14343. difftime(time(NULL), conn->conn_birth_time));
  14344. close_connection(conn);
  14345. #if defined(USE_SERVER_STATS)
  14346. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  14347. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  14348. #endif
  14349. }
  14350. #if defined(ALTERNATIVE_QUEUE)
  14351. static void
  14352. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14353. {
  14354. unsigned int i;
  14355. while (!ctx->stop_flag) {
  14356. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14357. /* find a free worker slot and signal it */
  14358. if (ctx->client_socks[i].in_use == 0) {
  14359. ctx->client_socks[i] = *sp;
  14360. ctx->client_socks[i].in_use = 1;
  14361. event_signal(ctx->client_wait_events[i]);
  14362. return;
  14363. }
  14364. }
  14365. /* queue is full */
  14366. mg_sleep(1);
  14367. }
  14368. }
  14369. static int
  14370. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14371. {
  14372. DEBUG_TRACE("%s", "going idle");
  14373. ctx->client_socks[thread_index].in_use = 0;
  14374. event_wait(ctx->client_wait_events[thread_index]);
  14375. *sp = ctx->client_socks[thread_index];
  14376. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14377. return !ctx->stop_flag;
  14378. }
  14379. #else /* ALTERNATIVE_QUEUE */
  14380. /* Worker threads take accepted socket from the queue */
  14381. static int
  14382. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14383. {
  14384. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14385. (void)thread_index;
  14386. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14387. DEBUG_TRACE("%s", "going idle");
  14388. /* If the queue is empty, wait. We're idle at this point. */
  14389. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  14390. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  14391. }
  14392. /* If we're stopping, sq_head may be equal to sq_tail. */
  14393. if (ctx->sq_head > ctx->sq_tail) {
  14394. /* Copy socket from the queue and increment tail */
  14395. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  14396. ctx->sq_tail++;
  14397. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14398. /* Wrap pointers if needed */
  14399. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  14400. ctx->sq_tail -= QUEUE_SIZE(ctx);
  14401. ctx->sq_head -= QUEUE_SIZE(ctx);
  14402. }
  14403. }
  14404. (void)pthread_cond_signal(&ctx->sq_empty);
  14405. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14406. return !ctx->stop_flag;
  14407. #undef QUEUE_SIZE
  14408. }
  14409. /* Master thread adds accepted socket to a queue */
  14410. static void
  14411. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14412. {
  14413. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14414. if (!ctx) {
  14415. return;
  14416. }
  14417. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14418. /* If the queue is full, wait */
  14419. while ((ctx->stop_flag == 0)
  14420. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  14421. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  14422. }
  14423. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  14424. /* Copy socket to the queue and increment head */
  14425. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  14426. ctx->sq_head++;
  14427. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  14428. }
  14429. (void)pthread_cond_signal(&ctx->sq_full);
  14430. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14431. #undef QUEUE_SIZE
  14432. }
  14433. #endif /* ALTERNATIVE_QUEUE */
  14434. struct worker_thread_args {
  14435. struct mg_context *ctx;
  14436. int index;
  14437. };
  14438. static void *
  14439. worker_thread_run(struct worker_thread_args *thread_args)
  14440. {
  14441. struct mg_context *ctx = thread_args->ctx;
  14442. struct mg_connection *conn;
  14443. struct mg_workerTLS tls;
  14444. #if defined(MG_LEGACY_INTERFACE)
  14445. uint32_t addr;
  14446. #endif
  14447. mg_set_thread_name("worker");
  14448. tls.is_master = 0;
  14449. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14450. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14451. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14452. #endif
  14453. /* Initialize thread local storage before calling any callback */
  14454. pthread_setspecific(sTlsKey, &tls);
  14455. if (ctx->callbacks.init_thread) {
  14456. /* call init_thread for a worker thread (type 1) */
  14457. ctx->callbacks.init_thread(ctx, 1);
  14458. }
  14459. /* Connection structure has been pre-allocated */
  14460. if (((int)thread_args->index < 0)
  14461. || ((unsigned)thread_args->index
  14462. >= (unsigned)ctx->cfg_worker_threads)) {
  14463. mg_cry_internal(fc(ctx),
  14464. "Internal error: Invalid worker index %i",
  14465. (int)thread_args->index);
  14466. return NULL;
  14467. }
  14468. conn = ctx->worker_connections + thread_args->index;
  14469. /* Request buffers are not pre-allocated. They are private to the
  14470. * request and do not contain any state information that might be
  14471. * of interest to anyone observing a server status. */
  14472. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  14473. if (conn->buf == NULL) {
  14474. mg_cry_internal(fc(ctx),
  14475. "Out of memory: Cannot allocate buffer for worker %i",
  14476. (int)thread_args->index);
  14477. return NULL;
  14478. }
  14479. conn->buf_size = (int)ctx->max_request_size;
  14480. conn->phys_ctx = ctx;
  14481. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  14482. conn->host = NULL; /* until we have more information. */
  14483. conn->thread_index = thread_args->index;
  14484. conn->request_info.user_data = ctx->user_data;
  14485. /* Allocate a mutex for this connection to allow communication both
  14486. * within the request handler and from elsewhere in the application
  14487. */
  14488. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  14489. #if defined(USE_SERVER_STATS)
  14490. conn->conn_state = 1; /* not consumed */
  14491. #endif
  14492. #if defined(ALTERNATIVE_QUEUE)
  14493. while ((ctx->stop_flag == 0)
  14494. && consume_socket(ctx, &conn->client, conn->thread_index)) {
  14495. #else
  14496. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  14497. * signal sq_empty condvar to wake up the master waiting in
  14498. * produce_socket() */
  14499. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  14500. #endif
  14501. conn->conn_birth_time = time(NULL);
  14502. /* Fill in IP, port info early so even if SSL setup below fails,
  14503. * error handler would have the corresponding info.
  14504. * Thanks to Johannes Winkelmann for the patch.
  14505. */
  14506. #if defined(USE_IPV6)
  14507. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  14508. conn->request_info.remote_port =
  14509. ntohs(conn->client.rsa.sin6.sin6_port);
  14510. } else
  14511. #endif
  14512. {
  14513. conn->request_info.remote_port =
  14514. ntohs(conn->client.rsa.sin.sin_port);
  14515. }
  14516. sockaddr_to_string(conn->request_info.remote_addr,
  14517. sizeof(conn->request_info.remote_addr),
  14518. &conn->client.rsa);
  14519. DEBUG_TRACE("Start processing connection from %s",
  14520. conn->request_info.remote_addr);
  14521. conn->request_info.is_ssl = conn->client.is_ssl;
  14522. if (conn->client.is_ssl) {
  14523. #ifndef NO_SSL
  14524. /* HTTPS connection */
  14525. if (sslize(conn,
  14526. conn->dom_ctx->ssl_ctx,
  14527. SSL_accept,
  14528. &(conn->phys_ctx->stop_flag))) {
  14529. /* conn->dom_ctx is set in get_request */
  14530. /* Get SSL client certificate information (if set) */
  14531. ssl_get_client_cert_info(conn);
  14532. /* process HTTPS connection */
  14533. process_new_connection(conn);
  14534. /* Free client certificate info */
  14535. if (conn->request_info.client_cert) {
  14536. mg_free((void *)(conn->request_info.client_cert->subject));
  14537. mg_free((void *)(conn->request_info.client_cert->issuer));
  14538. mg_free((void *)(conn->request_info.client_cert->serial));
  14539. mg_free((void *)(conn->request_info.client_cert->finger));
  14540. /* Free certificate memory */
  14541. X509_free(
  14542. (X509 *)conn->request_info.client_cert->peer_cert);
  14543. conn->request_info.client_cert->peer_cert = 0;
  14544. conn->request_info.client_cert->subject = 0;
  14545. conn->request_info.client_cert->issuer = 0;
  14546. conn->request_info.client_cert->serial = 0;
  14547. conn->request_info.client_cert->finger = 0;
  14548. mg_free(conn->request_info.client_cert);
  14549. conn->request_info.client_cert = 0;
  14550. }
  14551. }
  14552. #endif
  14553. } else {
  14554. /* process HTTP connection */
  14555. process_new_connection(conn);
  14556. }
  14557. DEBUG_TRACE("%s", "Connection closed");
  14558. }
  14559. pthread_setspecific(sTlsKey, NULL);
  14560. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14561. CloseHandle(tls.pthread_cond_helper_mutex);
  14562. #endif
  14563. pthread_mutex_destroy(&conn->mutex);
  14564. /* Free the request buffer. */
  14565. conn->buf_size = 0;
  14566. mg_free(conn->buf);
  14567. conn->buf = NULL;
  14568. #if defined(USE_SERVER_STATS)
  14569. conn->conn_state = 9; /* done */
  14570. #endif
  14571. DEBUG_TRACE("%s", "exiting");
  14572. return NULL;
  14573. }
  14574. /* Threads have different return types on Windows and Unix. */
  14575. #ifdef _WIN32
  14576. static unsigned __stdcall worker_thread(void *thread_func_param)
  14577. {
  14578. struct worker_thread_args *pwta =
  14579. (struct worker_thread_args *)thread_func_param;
  14580. worker_thread_run(pwta);
  14581. mg_free(thread_func_param);
  14582. return 0;
  14583. }
  14584. #else
  14585. static void *
  14586. worker_thread(void *thread_func_param)
  14587. {
  14588. struct worker_thread_args *pwta =
  14589. (struct worker_thread_args *)thread_func_param;
  14590. struct sigaction sa;
  14591. /* Ignore SIGPIPE */
  14592. memset(&sa, 0, sizeof(sa));
  14593. sa.sa_handler = SIG_IGN;
  14594. sigaction(SIGPIPE, &sa, NULL);
  14595. worker_thread_run(pwta);
  14596. mg_free(thread_func_param);
  14597. return NULL;
  14598. }
  14599. #endif /* _WIN32 */
  14600. static void
  14601. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  14602. {
  14603. struct socket so;
  14604. char src_addr[IP_ADDR_STR_LEN];
  14605. socklen_t len = sizeof(so.rsa);
  14606. int on = 1;
  14607. if (!listener) {
  14608. return;
  14609. }
  14610. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  14611. == INVALID_SOCKET) {
  14612. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  14613. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  14614. mg_cry_internal(fc(ctx),
  14615. "%s: %s is not allowed to connect",
  14616. __func__,
  14617. src_addr);
  14618. closesocket(so.sock);
  14619. } else {
  14620. /* Put so socket structure into the queue */
  14621. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  14622. set_close_on_exec(so.sock, fc(ctx));
  14623. so.is_ssl = listener->is_ssl;
  14624. so.ssl_redir = listener->ssl_redir;
  14625. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  14626. mg_cry_internal(fc(ctx),
  14627. "%s: getsockname() failed: %s",
  14628. __func__,
  14629. strerror(ERRNO));
  14630. }
  14631. /* Set TCP keep-alive. This is needed because if HTTP-level
  14632. * keep-alive
  14633. * is enabled, and client resets the connection, server won't get
  14634. * TCP FIN or RST and will keep the connection open forever. With
  14635. * TCP keep-alive, next keep-alive handshake will figure out that
  14636. * the client is down and will close the server end.
  14637. * Thanks to Igor Klopov who suggested the patch. */
  14638. if (setsockopt(so.sock,
  14639. SOL_SOCKET,
  14640. SO_KEEPALIVE,
  14641. (SOCK_OPT_TYPE)&on,
  14642. sizeof(on)) != 0) {
  14643. mg_cry_internal(
  14644. fc(ctx),
  14645. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  14646. __func__,
  14647. strerror(ERRNO));
  14648. }
  14649. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  14650. * to effectively fill up the underlying IP packet payload and
  14651. * reduce the overhead of sending lots of small buffers. However
  14652. * this hurts the server's throughput (ie. operations per second)
  14653. * when HTTP 1.1 persistent connections are used and the responses
  14654. * are relatively small (eg. less than 1400 bytes).
  14655. */
  14656. if ((ctx != NULL) && (ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  14657. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  14658. if (set_tcp_nodelay(so.sock, 1) != 0) {
  14659. mg_cry_internal(
  14660. fc(ctx),
  14661. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  14662. __func__,
  14663. strerror(ERRNO));
  14664. }
  14665. }
  14666. /* We are using non-blocking sockets. Thus, the
  14667. * set_sock_timeout(so.sock, timeout);
  14668. * call is no longer required. */
  14669. /* The "non blocking" property should already be
  14670. * inherited from the parent socket. Set it for
  14671. * non-compliant socket implementations. */
  14672. set_non_blocking_mode(so.sock);
  14673. so.in_use = 0;
  14674. produce_socket(ctx, &so);
  14675. }
  14676. }
  14677. static void
  14678. master_thread_run(void *thread_func_param)
  14679. {
  14680. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  14681. struct mg_workerTLS tls;
  14682. struct pollfd *pfd;
  14683. unsigned int i;
  14684. unsigned int workerthreadcount;
  14685. if (!ctx) {
  14686. return;
  14687. }
  14688. mg_set_thread_name("master");
  14689. /* Increase priority of the master thread */
  14690. #if defined(_WIN32)
  14691. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  14692. #elif defined(USE_MASTER_THREAD_PRIORITY)
  14693. int min_prio = sched_get_priority_min(SCHED_RR);
  14694. int max_prio = sched_get_priority_max(SCHED_RR);
  14695. if ((min_prio >= 0) && (max_prio >= 0)
  14696. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  14697. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  14698. struct sched_param sched_param = {0};
  14699. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  14700. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  14701. }
  14702. #endif
  14703. /* Initialize thread local storage */
  14704. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14705. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14706. #endif
  14707. tls.is_master = 1;
  14708. pthread_setspecific(sTlsKey, &tls);
  14709. if (ctx->callbacks.init_thread) {
  14710. /* Callback for the master thread (type 0) */
  14711. ctx->callbacks.init_thread(ctx, 0);
  14712. }
  14713. /* Server starts *now* */
  14714. ctx->start_time = time(NULL);
  14715. /* Start the server */
  14716. pfd = ctx->listening_socket_fds;
  14717. while (ctx->stop_flag == 0) {
  14718. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14719. pfd[i].fd = ctx->listening_sockets[i].sock;
  14720. pfd[i].events = POLLIN;
  14721. }
  14722. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  14723. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14724. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  14725. * successful poll, and POLLIN is defined as
  14726. * (POLLRDNORM | POLLRDBAND)
  14727. * Therefore, we're checking pfd[i].revents & POLLIN, not
  14728. * pfd[i].revents == POLLIN. */
  14729. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  14730. accept_new_connection(&ctx->listening_sockets[i], ctx);
  14731. }
  14732. }
  14733. }
  14734. }
  14735. /* Here stop_flag is 1 - Initiate shutdown. */
  14736. DEBUG_TRACE("%s", "stopping workers");
  14737. /* Stop signal received: somebody called mg_stop. Quit. */
  14738. close_all_listening_sockets(ctx);
  14739. /* Wakeup workers that are waiting for connections to handle. */
  14740. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14741. #if defined(ALTERNATIVE_QUEUE)
  14742. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14743. event_signal(ctx->client_wait_events[i]);
  14744. /* Since we know all sockets, we can shutdown the connections. */
  14745. if (ctx->client_socks[i].in_use) {
  14746. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  14747. }
  14748. }
  14749. #else
  14750. pthread_cond_broadcast(&ctx->sq_full);
  14751. #endif
  14752. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14753. /* Join all worker threads to avoid leaking threads. */
  14754. workerthreadcount = ctx->cfg_worker_threads;
  14755. for (i = 0; i < workerthreadcount; i++) {
  14756. if (ctx->worker_threadids[i] != 0) {
  14757. mg_join_thread(ctx->worker_threadids[i]);
  14758. }
  14759. }
  14760. #if defined(USE_LUA)
  14761. /* Free Lua state of lua background task */
  14762. if (ctx->lua_background_state) {
  14763. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14764. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  14765. if (lua_istable(lstate, -1)) {
  14766. reg_boolean(lstate, "shutdown", 1);
  14767. lua_pop(lstate, 1);
  14768. mg_sleep(2);
  14769. }
  14770. lua_close(lstate);
  14771. ctx->lua_background_state = 0;
  14772. }
  14773. #endif
  14774. DEBUG_TRACE("%s", "exiting");
  14775. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14776. CloseHandle(tls.pthread_cond_helper_mutex);
  14777. #endif
  14778. pthread_setspecific(sTlsKey, NULL);
  14779. /* Signal mg_stop() that we're done.
  14780. * WARNING: This must be the very last thing this
  14781. * thread does, as ctx becomes invalid after this line. */
  14782. ctx->stop_flag = 2;
  14783. }
  14784. /* Threads have different return types on Windows and Unix. */
  14785. #ifdef _WIN32
  14786. static unsigned __stdcall master_thread(void *thread_func_param)
  14787. {
  14788. master_thread_run(thread_func_param);
  14789. return 0;
  14790. }
  14791. #else
  14792. static void *
  14793. master_thread(void *thread_func_param)
  14794. {
  14795. struct sigaction sa;
  14796. /* Ignore SIGPIPE */
  14797. memset(&sa, 0, sizeof(sa));
  14798. sa.sa_handler = SIG_IGN;
  14799. sigaction(SIGPIPE, &sa, NULL);
  14800. master_thread_run(thread_func_param);
  14801. return NULL;
  14802. }
  14803. #endif /* _WIN32 */
  14804. static void
  14805. free_context(struct mg_context *ctx)
  14806. {
  14807. int i;
  14808. struct mg_handler_info *tmp_rh;
  14809. if (ctx == NULL) {
  14810. return;
  14811. }
  14812. if (ctx->callbacks.exit_context) {
  14813. ctx->callbacks.exit_context(ctx);
  14814. }
  14815. /* All threads exited, no sync is needed. Destroy thread mutex and
  14816. * condvars
  14817. */
  14818. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  14819. #if defined(ALTERNATIVE_QUEUE)
  14820. mg_free(ctx->client_socks);
  14821. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14822. event_destroy(ctx->client_wait_events[i]);
  14823. }
  14824. mg_free(ctx->client_wait_events);
  14825. #else
  14826. (void)pthread_cond_destroy(&ctx->sq_empty);
  14827. (void)pthread_cond_destroy(&ctx->sq_full);
  14828. #endif
  14829. /* Destroy other context global data structures mutex */
  14830. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  14831. #if defined(USE_TIMERS)
  14832. timers_exit(ctx);
  14833. #endif
  14834. /* Deallocate config parameters */
  14835. for (i = 0; i < NUM_OPTIONS; i++) {
  14836. if (ctx->dd.config[i] != NULL) {
  14837. #if defined(_MSC_VER)
  14838. #pragma warning(suppress : 6001)
  14839. #endif
  14840. mg_free(ctx->dd.config[i]);
  14841. }
  14842. }
  14843. /* Deallocate request handlers */
  14844. while (ctx->dd.handlers) {
  14845. tmp_rh = ctx->dd.handlers;
  14846. ctx->dd.handlers = tmp_rh->next;
  14847. mg_free(tmp_rh->uri);
  14848. mg_free(tmp_rh);
  14849. }
  14850. #ifndef NO_SSL
  14851. /* Deallocate SSL context */
  14852. if (ctx->dd.ssl_ctx != NULL) {
  14853. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  14854. int callback_ret =
  14855. (ctx->callbacks.external_ssl_ctx == NULL)
  14856. ? 0
  14857. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  14858. if (callback_ret == 0) {
  14859. SSL_CTX_free(ctx->dd.ssl_ctx);
  14860. }
  14861. /* else: ignore error and ommit SSL_CTX_free in case
  14862. * callback_ret is 1 */
  14863. }
  14864. #endif /* !NO_SSL */
  14865. /* Deallocate worker thread ID array */
  14866. if (ctx->worker_threadids != NULL) {
  14867. mg_free(ctx->worker_threadids);
  14868. }
  14869. /* Deallocate worker thread ID array */
  14870. if (ctx->worker_connections != NULL) {
  14871. mg_free(ctx->worker_connections);
  14872. }
  14873. /* deallocate system name string */
  14874. mg_free(ctx->systemName);
  14875. /* Deallocate context itself */
  14876. mg_free(ctx);
  14877. }
  14878. void
  14879. mg_stop(struct mg_context *ctx)
  14880. {
  14881. pthread_t mt;
  14882. if (!ctx) {
  14883. return;
  14884. }
  14885. /* We don't use a lock here. Calling mg_stop with the same ctx from
  14886. * two threads is not allowed. */
  14887. mt = ctx->masterthreadid;
  14888. if (mt == 0) {
  14889. return;
  14890. }
  14891. ctx->masterthreadid = 0;
  14892. /* Set stop flag, so all threads know they have to exit. */
  14893. ctx->stop_flag = 1;
  14894. /* Wait until everything has stopped. */
  14895. while (ctx->stop_flag != 2) {
  14896. (void)mg_sleep(10);
  14897. }
  14898. mg_join_thread(mt);
  14899. free_context(ctx);
  14900. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14901. (void)WSACleanup();
  14902. #endif /* _WIN32 && !__SYMBIAN32__ */
  14903. }
  14904. static void
  14905. get_system_name(char **sysName)
  14906. {
  14907. #if defined(_WIN32)
  14908. #if !defined(__SYMBIAN32__)
  14909. #if defined(_WIN32_WCE)
  14910. *sysName = mg_strdup("WinCE");
  14911. #else
  14912. char name[128];
  14913. DWORD dwVersion = 0;
  14914. DWORD dwMajorVersion = 0;
  14915. DWORD dwMinorVersion = 0;
  14916. DWORD dwBuild = 0;
  14917. BOOL wowRet, isWoW = FALSE;
  14918. #ifdef _MSC_VER
  14919. #pragma warning(push)
  14920. /* GetVersion was declared deprecated */
  14921. #pragma warning(disable : 4996)
  14922. #endif
  14923. dwVersion = GetVersion();
  14924. #ifdef _MSC_VER
  14925. #pragma warning(pop)
  14926. #endif
  14927. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14928. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14929. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  14930. (void)dwBuild;
  14931. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  14932. sprintf(name,
  14933. "Windows %u.%u%s",
  14934. (unsigned)dwMajorVersion,
  14935. (unsigned)dwMinorVersion,
  14936. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  14937. *sysName = mg_strdup(name);
  14938. #endif
  14939. #else
  14940. *sysName = mg_strdup("Symbian");
  14941. #endif
  14942. #else
  14943. struct utsname name;
  14944. memset(&name, 0, sizeof(name));
  14945. uname(&name);
  14946. *sysName = mg_strdup(name.sysname);
  14947. #endif
  14948. }
  14949. struct mg_context *
  14950. mg_start(const struct mg_callbacks *callbacks,
  14951. void *user_data,
  14952. const char **options)
  14953. {
  14954. struct mg_context *ctx;
  14955. const char *name, *value, *default_value;
  14956. int idx, ok, workerthreadcount;
  14957. unsigned int i;
  14958. int itmp;
  14959. void (*exit_callback)(const struct mg_context *ctx) = 0;
  14960. struct mg_workerTLS tls;
  14961. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14962. WSADATA data;
  14963. WSAStartup(MAKEWORD(2, 2), &data);
  14964. #endif /* _WIN32 && !__SYMBIAN32__ */
  14965. /* Allocate context and initialize reasonable general case defaults. */
  14966. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  14967. return NULL;
  14968. }
  14969. /* Random number generator will initialize at the first call */
  14970. ctx->dd.auth_nonce_mask =
  14971. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  14972. if (mg_init_library_called == 0) {
  14973. /* Legacy INIT, if mg_start is called without mg_init_library.
  14974. * Note: This may cause a memory leak */
  14975. const char *ports_option =
  14976. config_options[LISTENING_PORTS].default_value;
  14977. if (options) {
  14978. const char **run_options = options;
  14979. const char *optname = config_options[LISTENING_PORTS].name;
  14980. /* Try to find the "listening_ports" option */
  14981. while (*run_options) {
  14982. if (!strcmp(*run_options, optname)) {
  14983. ports_option = run_options[1];
  14984. }
  14985. run_options += 2;
  14986. }
  14987. }
  14988. if (is_ssl_port_used(ports_option)) {
  14989. /* Initialize with SSL support */
  14990. mg_init_library(MG_FEATURES_TLS);
  14991. } else {
  14992. /* Initialize without SSL support */
  14993. mg_init_library(MG_FEATURES_DEFAULT);
  14994. }
  14995. }
  14996. tls.is_master = -1;
  14997. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14998. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14999. tls.pthread_cond_helper_mutex = NULL;
  15000. #endif
  15001. pthread_setspecific(sTlsKey, &tls);
  15002. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  15003. #if !defined(ALTERNATIVE_QUEUE)
  15004. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  15005. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  15006. #endif
  15007. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  15008. if (!ok) {
  15009. /* Fatal error - abort start. However, this situation should never
  15010. * occur in practice. */
  15011. mg_cry_internal(fc(ctx),
  15012. "%s",
  15013. "Cannot initialize thread synchronization objects");
  15014. mg_free(ctx);
  15015. pthread_setspecific(sTlsKey, NULL);
  15016. return NULL;
  15017. }
  15018. if (callbacks) {
  15019. ctx->callbacks = *callbacks;
  15020. exit_callback = callbacks->exit_context;
  15021. ctx->callbacks.exit_context = 0;
  15022. }
  15023. ctx->user_data = user_data;
  15024. ctx->dd.handlers = NULL;
  15025. ctx->dd.next = NULL;
  15026. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15027. ctx->dd.shared_lua_websockets = NULL;
  15028. #endif
  15029. /* Store options */
  15030. while (options && (name = *options++) != NULL) {
  15031. if ((idx = get_option_index(name)) == -1) {
  15032. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15033. free_context(ctx);
  15034. pthread_setspecific(sTlsKey, NULL);
  15035. return NULL;
  15036. } else if ((value = *options++) == NULL) {
  15037. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15038. free_context(ctx);
  15039. pthread_setspecific(sTlsKey, NULL);
  15040. return NULL;
  15041. }
  15042. if (ctx->dd.config[idx] != NULL) {
  15043. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15044. mg_free(ctx->dd.config[idx]);
  15045. }
  15046. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15047. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15048. }
  15049. /* Set default value if needed */
  15050. for (i = 0; config_options[i].name != NULL; i++) {
  15051. default_value = config_options[i].default_value;
  15052. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15053. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15054. }
  15055. }
  15056. /* Request size option */
  15057. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15058. if (itmp < 1024) {
  15059. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  15060. free_context(ctx);
  15061. pthread_setspecific(sTlsKey, NULL);
  15062. return NULL;
  15063. }
  15064. ctx->max_request_size = (unsigned)itmp;
  15065. /* Worker thread count option */
  15066. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15067. if (workerthreadcount > MAX_WORKER_THREADS) {
  15068. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  15069. free_context(ctx);
  15070. pthread_setspecific(sTlsKey, NULL);
  15071. return NULL;
  15072. }
  15073. if (workerthreadcount <= 0) {
  15074. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  15075. free_context(ctx);
  15076. pthread_setspecific(sTlsKey, NULL);
  15077. return NULL;
  15078. }
  15079. /* Document root */
  15080. #if defined(NO_FILES)
  15081. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  15082. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  15083. free_context(ctx);
  15084. pthread_setspecific(sTlsKey, NULL);
  15085. return NULL;
  15086. }
  15087. #endif
  15088. get_system_name(&ctx->systemName);
  15089. #if defined(USE_LUA)
  15090. /* If a Lua background script has been configured, start it. */
  15091. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  15092. char ebuf[256];
  15093. struct vec opt_vec;
  15094. struct vec eq_vec;
  15095. const char *sparams;
  15096. lua_State *state = (void *)mg_prepare_lua_context_script(
  15097. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  15098. if (!state) {
  15099. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  15100. free_context(ctx);
  15101. pthread_setspecific(sTlsKey, NULL);
  15102. return NULL;
  15103. }
  15104. ctx->lua_background_state = (void *)state;
  15105. lua_newtable(state);
  15106. reg_boolean(state, "shutdown", 0);
  15107. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  15108. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  15109. reg_llstring(
  15110. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  15111. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  15112. break;
  15113. }
  15114. lua_setglobal(state, LUABACKGROUNDPARAMS);
  15115. } else {
  15116. ctx->lua_background_state = 0;
  15117. }
  15118. #endif
  15119. /* NOTE(lsm): order is important here. SSL certificates must
  15120. * be initialized before listening ports. UID must be set last. */
  15121. if (!set_gpass_option(ctx, NULL) ||
  15122. #if !defined(NO_SSL)
  15123. !init_ssl_ctx(ctx, NULL) ||
  15124. #endif
  15125. !set_ports_option(ctx) ||
  15126. #if !defined(_WIN32)
  15127. !set_uid_option(ctx) ||
  15128. #endif
  15129. !set_acl_option(ctx)) {
  15130. free_context(ctx);
  15131. pthread_setspecific(sTlsKey, NULL);
  15132. return NULL;
  15133. }
  15134. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  15135. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15136. sizeof(pthread_t),
  15137. ctx);
  15138. if (ctx->worker_threadids == NULL) {
  15139. mg_cry_internal(fc(ctx),
  15140. "%s",
  15141. "Not enough memory for worker thread ID array");
  15142. free_context(ctx);
  15143. pthread_setspecific(sTlsKey, NULL);
  15144. return NULL;
  15145. }
  15146. ctx->worker_connections =
  15147. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15148. sizeof(struct mg_connection),
  15149. ctx);
  15150. if (ctx->worker_connections == NULL) {
  15151. mg_cry_internal(fc(ctx),
  15152. "%s",
  15153. "Not enough memory for worker thread connection array");
  15154. free_context(ctx);
  15155. pthread_setspecific(sTlsKey, NULL);
  15156. return NULL;
  15157. }
  15158. #if defined(ALTERNATIVE_QUEUE)
  15159. ctx->client_wait_events =
  15160. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  15161. ctx->cfg_worker_threads,
  15162. ctx);
  15163. if (ctx->client_wait_events == NULL) {
  15164. mg_cry_internal(fc(ctx),
  15165. "%s",
  15166. "Not enough memory for worker event array");
  15167. mg_free(ctx->worker_threadids);
  15168. free_context(ctx);
  15169. pthread_setspecific(sTlsKey, NULL);
  15170. return NULL;
  15171. }
  15172. ctx->client_socks =
  15173. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  15174. ctx->cfg_worker_threads,
  15175. ctx);
  15176. if (ctx->client_wait_events == NULL) {
  15177. mg_cry_internal(fc(ctx),
  15178. "%s",
  15179. "Not enough memory for worker socket array");
  15180. mg_free(ctx->client_socks);
  15181. mg_free(ctx->worker_threadids);
  15182. free_context(ctx);
  15183. pthread_setspecific(sTlsKey, NULL);
  15184. return NULL;
  15185. }
  15186. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15187. ctx->client_wait_events[i] = event_create();
  15188. if (ctx->client_wait_events[i] == 0) {
  15189. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  15190. while (i > 0) {
  15191. i--;
  15192. event_destroy(ctx->client_wait_events[i]);
  15193. }
  15194. mg_free(ctx->client_socks);
  15195. mg_free(ctx->worker_threadids);
  15196. free_context(ctx);
  15197. pthread_setspecific(sTlsKey, NULL);
  15198. return NULL;
  15199. }
  15200. }
  15201. #endif
  15202. #if defined(USE_TIMERS)
  15203. if (timers_init(ctx) != 0) {
  15204. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  15205. free_context(ctx);
  15206. pthread_setspecific(sTlsKey, NULL);
  15207. return NULL;
  15208. }
  15209. #endif
  15210. /* Context has been created - init user libraries */
  15211. if (ctx->callbacks.init_context) {
  15212. ctx->callbacks.init_context(ctx);
  15213. }
  15214. ctx->callbacks.exit_context = exit_callback;
  15215. ctx->context_type = CONTEXT_SERVER; /* server context */
  15216. /* Start master (listening) thread */
  15217. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  15218. /* Start worker threads */
  15219. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15220. struct worker_thread_args *wta = (struct worker_thread_args *)
  15221. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  15222. if (wta) {
  15223. wta->ctx = ctx;
  15224. wta->index = (int)i;
  15225. }
  15226. if ((wta == NULL)
  15227. || (mg_start_thread_with_id(worker_thread,
  15228. wta,
  15229. &ctx->worker_threadids[i]) != 0)) {
  15230. /* thread was not created */
  15231. if (wta != NULL) {
  15232. mg_free(wta);
  15233. }
  15234. if (i > 0) {
  15235. mg_cry_internal(fc(ctx),
  15236. "Cannot start worker thread %i: error %ld",
  15237. i + 1,
  15238. (long)ERRNO);
  15239. } else {
  15240. mg_cry_internal(fc(ctx),
  15241. "Cannot create threads: error %ld",
  15242. (long)ERRNO);
  15243. free_context(ctx);
  15244. pthread_setspecific(sTlsKey, NULL);
  15245. return NULL;
  15246. }
  15247. break;
  15248. }
  15249. }
  15250. pthread_setspecific(sTlsKey, NULL);
  15251. return ctx;
  15252. }
  15253. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15254. /* Add an additional domain to an already running web server. */
  15255. int
  15256. mg_start_domain(struct mg_context *ctx, const char **options)
  15257. {
  15258. const char *name;
  15259. const char *value;
  15260. const char *default_value;
  15261. struct mg_domain_context *new_dom;
  15262. struct mg_domain_context *dom;
  15263. int idx, i;
  15264. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  15265. return -1;
  15266. }
  15267. new_dom = (struct mg_domain_context *)
  15268. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  15269. if (!new_dom) {
  15270. /* Out of memory */
  15271. return -6;
  15272. }
  15273. /* Store options - TODO: unite duplicate code */
  15274. while (options && (name = *options++) != NULL) {
  15275. if ((idx = get_option_index(name)) == -1) {
  15276. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15277. mg_free(new_dom);
  15278. return -2;
  15279. } else if ((value = *options++) == NULL) {
  15280. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15281. mg_free(new_dom);
  15282. return -2;
  15283. }
  15284. if (new_dom->config[idx] != NULL) {
  15285. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15286. mg_free(new_dom->config[idx]);
  15287. }
  15288. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  15289. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15290. }
  15291. /* Authentication domain is mandatory */
  15292. /* TODO: Maybe use a new option hostname? */
  15293. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  15294. return -4;
  15295. }
  15296. /* Set default value if needed. Take the config value from
  15297. * ctx as a default value. */
  15298. for (i = 0; config_options[i].name != NULL; i++) {
  15299. default_value = ctx->dd.config[i];
  15300. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  15301. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  15302. }
  15303. }
  15304. new_dom->handlers = NULL;
  15305. new_dom->next = NULL;
  15306. new_dom->nonce_count = 0;
  15307. new_dom->auth_nonce_mask =
  15308. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  15309. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15310. new_dom->shared_lua_websockets = NULL;
  15311. #endif
  15312. if (!init_ssl_ctx(ctx, new_dom)) {
  15313. /* Init SSL failed */
  15314. mg_free(new_dom);
  15315. return -3;
  15316. }
  15317. /* Add element to linked list. */
  15318. mg_lock_context(ctx);
  15319. idx = 0;
  15320. dom = &(ctx->dd);
  15321. for (;;) {
  15322. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  15323. dom->config[AUTHENTICATION_DOMAIN])) {
  15324. /* Domain collision */
  15325. mg_cry_internal(fc(ctx),
  15326. "domain %s already in use",
  15327. new_dom->config[AUTHENTICATION_DOMAIN]);
  15328. mg_free(new_dom);
  15329. return -5;
  15330. }
  15331. /* Count number of domains */
  15332. idx++;
  15333. if (dom->next == NULL) {
  15334. dom->next = new_dom;
  15335. break;
  15336. }
  15337. dom = dom->next;
  15338. }
  15339. mg_unlock_context(ctx);
  15340. /* Return domain number */
  15341. return idx;
  15342. }
  15343. #endif
  15344. /* Feature check API function */
  15345. unsigned
  15346. mg_check_feature(unsigned feature)
  15347. {
  15348. static const unsigned feature_set = 0
  15349. /* Set bits for available features according to API documentation.
  15350. * This bit mask is created at compile time, according to the active
  15351. * preprocessor defines. It is a single const value at runtime. */
  15352. #if !defined(NO_FILES)
  15353. | MG_FEATURES_FILES
  15354. #endif
  15355. #if !defined(NO_SSL)
  15356. | MG_FEATURES_SSL
  15357. #endif
  15358. #if !defined(NO_CGI)
  15359. | MG_FEATURES_CGI
  15360. #endif
  15361. #if defined(USE_IPV6)
  15362. | MG_FEATURES_IPV6
  15363. #endif
  15364. #if defined(USE_WEBSOCKET)
  15365. | MG_FEATURES_WEBSOCKET
  15366. #endif
  15367. #if defined(USE_LUA)
  15368. | MG_FEATURES_LUA
  15369. #endif
  15370. #if defined(USE_DUKTAPE)
  15371. | MG_FEATURES_SSJS
  15372. #endif
  15373. #if !defined(NO_CACHING)
  15374. | MG_FEATURES_CACHE
  15375. #endif
  15376. #if defined(USE_SERVER_STATS)
  15377. | MG_FEATURES_STATS
  15378. #endif
  15379. /* Set some extra bits not defined in the API documentation.
  15380. * These bits may change without further notice. */
  15381. #if defined(MG_LEGACY_INTERFACE)
  15382. | 0x8000u
  15383. #endif
  15384. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15385. | 0x4000u
  15386. #endif
  15387. #if defined(MEMORY_DEBUGGING)
  15388. | 0x1000u
  15389. #endif
  15390. #if defined(USE_TIMERS)
  15391. | 0x0200u
  15392. #endif
  15393. #if !defined(NO_NONCE_CHECK)
  15394. | 0x0400u
  15395. #endif
  15396. #if !defined(NO_POPEN)
  15397. | 0x0800u
  15398. #endif
  15399. ;
  15400. return (feature & feature_set);
  15401. }
  15402. /* strcat with additional NULL check to avoid clang scan-build warning. */
  15403. #define strcat0(a, b) \
  15404. { \
  15405. if ((a != NULL) && (b != NULL)) { \
  15406. strcat(a, b); \
  15407. } \
  15408. }
  15409. /* Get system information. It can be printed or stored by the caller.
  15410. * Return the size of available information. */
  15411. static int
  15412. mg_get_system_info_impl(char *buffer, int buflen)
  15413. {
  15414. char block[256];
  15415. int system_info_length = 0;
  15416. #if defined(_WIN32)
  15417. const char *eol = "\r\n";
  15418. #else
  15419. const char *eol = "\n";
  15420. #endif
  15421. const char *eoobj = "}";
  15422. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15423. if ((buffer == NULL) || (buflen < 1)) {
  15424. buflen = 0;
  15425. } else {
  15426. *buffer = 0;
  15427. }
  15428. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15429. system_info_length += (int)strlen(block);
  15430. if (system_info_length < buflen) {
  15431. strcat0(buffer, block);
  15432. }
  15433. /* Server version */
  15434. {
  15435. const char *version = mg_version();
  15436. mg_snprintf(NULL,
  15437. NULL,
  15438. block,
  15439. sizeof(block),
  15440. "\"version\" : \"%s\",%s",
  15441. version,
  15442. eol);
  15443. system_info_length += (int)strlen(block);
  15444. if (system_info_length < buflen) {
  15445. strcat0(buffer, block);
  15446. }
  15447. }
  15448. /* System info */
  15449. {
  15450. #if defined(_WIN32)
  15451. #if !defined(__SYMBIAN32__)
  15452. DWORD dwVersion = 0;
  15453. DWORD dwMajorVersion = 0;
  15454. DWORD dwMinorVersion = 0;
  15455. SYSTEM_INFO si;
  15456. GetSystemInfo(&si);
  15457. #ifdef _MSC_VER
  15458. #pragma warning(push)
  15459. /* GetVersion was declared deprecated */
  15460. #pragma warning(disable : 4996)
  15461. #endif
  15462. dwVersion = GetVersion();
  15463. #ifdef _MSC_VER
  15464. #pragma warning(pop)
  15465. #endif
  15466. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15467. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15468. mg_snprintf(NULL,
  15469. NULL,
  15470. block,
  15471. sizeof(block),
  15472. "\"os\" : \"Windows %u.%u\",%s",
  15473. (unsigned)dwMajorVersion,
  15474. (unsigned)dwMinorVersion,
  15475. eol);
  15476. system_info_length += (int)strlen(block);
  15477. if (system_info_length < buflen) {
  15478. strcat0(buffer, block);
  15479. }
  15480. mg_snprintf(NULL,
  15481. NULL,
  15482. block,
  15483. sizeof(block),
  15484. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  15485. (unsigned)si.wProcessorArchitecture,
  15486. (unsigned)si.dwNumberOfProcessors,
  15487. (unsigned)si.dwActiveProcessorMask,
  15488. eol);
  15489. system_info_length += (int)strlen(block);
  15490. if (system_info_length < buflen) {
  15491. strcat0(buffer, block);
  15492. }
  15493. #else
  15494. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  15495. system_info_length += (int)strlen(block);
  15496. if (system_info_length < buflen) {
  15497. strcat0(buffer, block);
  15498. }
  15499. #endif
  15500. #else
  15501. struct utsname name;
  15502. memset(&name, 0, sizeof(name));
  15503. uname(&name);
  15504. mg_snprintf(NULL,
  15505. NULL,
  15506. block,
  15507. sizeof(block),
  15508. "\"os\" : \"%s %s (%s) - %s\",%s",
  15509. name.sysname,
  15510. name.version,
  15511. name.release,
  15512. name.machine,
  15513. eol);
  15514. system_info_length += (int)strlen(block);
  15515. if (system_info_length < buflen) {
  15516. strcat0(buffer, block);
  15517. }
  15518. #endif
  15519. }
  15520. /* Features */
  15521. {
  15522. mg_snprintf(NULL,
  15523. NULL,
  15524. block,
  15525. sizeof(block),
  15526. "\"features\" : %lu,%s"
  15527. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  15528. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  15529. eol,
  15530. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  15531. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  15532. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  15533. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  15534. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  15535. : "",
  15536. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  15537. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  15538. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  15539. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  15540. eol);
  15541. system_info_length += (int)strlen(block);
  15542. if (system_info_length < buflen) {
  15543. strcat0(buffer, block);
  15544. }
  15545. #ifdef USE_LUA
  15546. mg_snprintf(NULL,
  15547. NULL,
  15548. block,
  15549. sizeof(block),
  15550. "\"lua_version\" : \"%u (%s)\",%s",
  15551. (unsigned)LUA_VERSION_NUM,
  15552. LUA_RELEASE,
  15553. eol);
  15554. system_info_length += (int)strlen(block);
  15555. if (system_info_length < buflen) {
  15556. strcat0(buffer, block);
  15557. }
  15558. #endif
  15559. #if defined(USE_DUKTAPE)
  15560. mg_snprintf(NULL,
  15561. NULL,
  15562. block,
  15563. sizeof(block),
  15564. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  15565. (unsigned)DUK_VERSION / 10000,
  15566. ((unsigned)DUK_VERSION / 100) % 100,
  15567. (unsigned)DUK_VERSION % 100,
  15568. eol);
  15569. system_info_length += (int)strlen(block);
  15570. if (system_info_length < buflen) {
  15571. strcat0(buffer, block);
  15572. }
  15573. #endif
  15574. }
  15575. /* Build date */
  15576. {
  15577. #if defined(__GNUC__)
  15578. #pragma GCC diagnostic push
  15579. /* Disable bogus compiler warning -Wdate-time */
  15580. /* TODO: The obvious flags do not know:
  15581. * #pragma GCC diagnostic ignored "-Wdate-time"
  15582. * If someone knows other flags, please tell me. See also #561.
  15583. */
  15584. #endif
  15585. mg_snprintf(NULL,
  15586. NULL,
  15587. block,
  15588. sizeof(block),
  15589. "\"build\" : \"%s\",%s",
  15590. __DATE__,
  15591. eol);
  15592. #if defined(__GNUC__)
  15593. #pragma GCC diagnostic pop
  15594. #endif
  15595. system_info_length += (int)strlen(block);
  15596. if (system_info_length < buflen) {
  15597. strcat0(buffer, block);
  15598. }
  15599. }
  15600. /* Compiler information */
  15601. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  15602. {
  15603. #if defined(_MSC_VER)
  15604. mg_snprintf(NULL,
  15605. NULL,
  15606. block,
  15607. sizeof(block),
  15608. "\"compiler\" : \"MSC: %u (%u)\",%s",
  15609. (unsigned)_MSC_VER,
  15610. (unsigned)_MSC_FULL_VER,
  15611. eol);
  15612. system_info_length += (int)strlen(block);
  15613. if (system_info_length < buflen) {
  15614. strcat0(buffer, block);
  15615. }
  15616. #elif defined(__MINGW64__)
  15617. mg_snprintf(NULL,
  15618. NULL,
  15619. block,
  15620. sizeof(block),
  15621. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  15622. (unsigned)__MINGW64_VERSION_MAJOR,
  15623. (unsigned)__MINGW64_VERSION_MINOR,
  15624. eol);
  15625. system_info_length += (int)strlen(block);
  15626. if (system_info_length < buflen) {
  15627. strcat0(buffer, block);
  15628. }
  15629. mg_snprintf(NULL,
  15630. NULL,
  15631. block,
  15632. sizeof(block),
  15633. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15634. (unsigned)__MINGW32_MAJOR_VERSION,
  15635. (unsigned)__MINGW32_MINOR_VERSION,
  15636. eol);
  15637. system_info_length += (int)strlen(block);
  15638. if (system_info_length < buflen) {
  15639. strcat0(buffer, block);
  15640. }
  15641. #elif defined(__MINGW32__)
  15642. mg_snprintf(NULL,
  15643. NULL,
  15644. block,
  15645. sizeof(block),
  15646. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15647. (unsigned)__MINGW32_MAJOR_VERSION,
  15648. (unsigned)__MINGW32_MINOR_VERSION,
  15649. eol);
  15650. system_info_length += (int)strlen(block);
  15651. if (system_info_length < buflen) {
  15652. strcat0(buffer, block);
  15653. }
  15654. #elif defined(__clang__)
  15655. mg_snprintf(NULL,
  15656. NULL,
  15657. block,
  15658. sizeof(block),
  15659. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  15660. __clang_major__,
  15661. __clang_minor__,
  15662. __clang_patchlevel__,
  15663. __clang_version__,
  15664. eol);
  15665. system_info_length += (int)strlen(block);
  15666. if (system_info_length < buflen) {
  15667. strcat0(buffer, block);
  15668. }
  15669. #elif defined(__GNUC__)
  15670. mg_snprintf(NULL,
  15671. NULL,
  15672. block,
  15673. sizeof(block),
  15674. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  15675. (unsigned)__GNUC__,
  15676. (unsigned)__GNUC_MINOR__,
  15677. (unsigned)__GNUC_PATCHLEVEL__,
  15678. eol);
  15679. system_info_length += (int)strlen(block);
  15680. if (system_info_length < buflen) {
  15681. strcat0(buffer, block);
  15682. }
  15683. #elif defined(__INTEL_COMPILER)
  15684. mg_snprintf(NULL,
  15685. NULL,
  15686. block,
  15687. sizeof(block),
  15688. "\"compiler\" : \"Intel C/C++: %u\",%s",
  15689. (unsigned)__INTEL_COMPILER,
  15690. eol);
  15691. system_info_length += (int)strlen(block);
  15692. if (system_info_length < buflen) {
  15693. strcat0(buffer, block);
  15694. }
  15695. #elif defined(__BORLANDC__)
  15696. mg_snprintf(NULL,
  15697. NULL,
  15698. block,
  15699. sizeof(block),
  15700. "\"compiler\" : \"Borland C: 0x%x\",%s",
  15701. (unsigned)__BORLANDC__,
  15702. eol);
  15703. system_info_length += (int)strlen(block);
  15704. if (system_info_length < buflen) {
  15705. strcat0(buffer, block);
  15706. }
  15707. #elif defined(__SUNPRO_C)
  15708. mg_snprintf(NULL,
  15709. NULL,
  15710. block,
  15711. sizeof(block),
  15712. "\"compiler\" : \"Solaris: 0x%x\",%s",
  15713. (unsigned)__SUNPRO_C,
  15714. eol);
  15715. system_info_length += (int)strlen(block);
  15716. if (system_info_length < buflen) {
  15717. strcat0(buffer, block);
  15718. }
  15719. #else
  15720. mg_snprintf(NULL,
  15721. NULL,
  15722. block,
  15723. sizeof(block),
  15724. "\"compiler\" : \"other\",%s",
  15725. eol);
  15726. system_info_length += (int)strlen(block);
  15727. if (system_info_length < buflen) {
  15728. strcat0(buffer, block);
  15729. }
  15730. #endif
  15731. }
  15732. /* Determine 32/64 bit data mode.
  15733. * see https://en.wikipedia.org/wiki/64-bit_computing */
  15734. {
  15735. mg_snprintf(NULL,
  15736. NULL,
  15737. block,
  15738. sizeof(block),
  15739. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  15740. "char:%u/%u, "
  15741. "ptr:%u, size:%u, time:%u\"%s",
  15742. (unsigned)sizeof(short),
  15743. (unsigned)sizeof(int),
  15744. (unsigned)sizeof(long),
  15745. (unsigned)sizeof(long long),
  15746. (unsigned)sizeof(float),
  15747. (unsigned)sizeof(double),
  15748. (unsigned)sizeof(long double),
  15749. (unsigned)sizeof(char),
  15750. (unsigned)sizeof(wchar_t),
  15751. (unsigned)sizeof(void *),
  15752. (unsigned)sizeof(size_t),
  15753. (unsigned)sizeof(time_t),
  15754. eol);
  15755. system_info_length += (int)strlen(block);
  15756. if (system_info_length < buflen) {
  15757. strcat0(buffer, block);
  15758. }
  15759. }
  15760. /* Terminate string */
  15761. if ((buflen > 0) && buffer && buffer[0]) {
  15762. if (system_info_length < buflen) {
  15763. strcat0(buffer, eoobj);
  15764. strcat0(buffer, eol);
  15765. }
  15766. }
  15767. system_info_length += reserved_len;
  15768. return system_info_length;
  15769. }
  15770. #if defined(USE_SERVER_STATS)
  15771. /* Get context information. It can be printed or stored by the caller.
  15772. * Return the size of available information. */
  15773. static int
  15774. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  15775. {
  15776. char block[256];
  15777. int context_info_length = 0;
  15778. #if defined(_WIN32)
  15779. const char *eol = "\r\n";
  15780. #else
  15781. const char *eol = "\n";
  15782. #endif
  15783. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  15784. const char *eoobj = "}";
  15785. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15786. if ((buffer == NULL) || (buflen < 1)) {
  15787. buflen = 0;
  15788. } else {
  15789. *buffer = 0;
  15790. }
  15791. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15792. context_info_length += (int)strlen(block);
  15793. if (context_info_length < buflen) {
  15794. strcat0(buffer, block);
  15795. }
  15796. /* Memory information */
  15797. if (ms) {
  15798. mg_snprintf(NULL,
  15799. NULL,
  15800. block,
  15801. sizeof(block),
  15802. "\"memory\" : {%s"
  15803. "\"blocks\" : %i,%s"
  15804. "\"used\" : %" INT64_FMT ",%s"
  15805. "\"maxUsed\" : %" INT64_FMT "%s"
  15806. "}%s%s",
  15807. eol,
  15808. ms->blockCount,
  15809. eol,
  15810. ms->totalMemUsed,
  15811. eol,
  15812. ms->maxMemUsed,
  15813. eol,
  15814. (ctx ? "," : ""),
  15815. eol);
  15816. context_info_length += (int)strlen(block);
  15817. if (context_info_length + reserved_len < buflen) {
  15818. strcat0(buffer, block);
  15819. }
  15820. }
  15821. /* Connections information */
  15822. if (ctx) {
  15823. mg_snprintf(NULL,
  15824. NULL,
  15825. block,
  15826. sizeof(block),
  15827. "\"connections\" : {%s"
  15828. "\"active\" : %i,%s"
  15829. "\"maxActive\" : %i,%s"
  15830. "\"total\" : %" INT64_FMT "%s"
  15831. "},%s",
  15832. eol,
  15833. ctx->active_connections,
  15834. eol,
  15835. ctx->max_connections,
  15836. eol,
  15837. ctx->total_connections,
  15838. eol,
  15839. eol);
  15840. context_info_length += (int)strlen(block);
  15841. if (context_info_length + reserved_len < buflen) {
  15842. strcat0(buffer, block);
  15843. }
  15844. }
  15845. /* Requests information */
  15846. if (ctx) {
  15847. mg_snprintf(NULL,
  15848. NULL,
  15849. block,
  15850. sizeof(block),
  15851. "\"requests\" : {%s"
  15852. "\"total\" : %" INT64_FMT "%s"
  15853. "},%s",
  15854. eol,
  15855. ctx->total_requests,
  15856. eol,
  15857. eol);
  15858. context_info_length += (int)strlen(block);
  15859. if (context_info_length + reserved_len < buflen) {
  15860. strcat0(buffer, block);
  15861. }
  15862. }
  15863. /* Data information */
  15864. if (ctx) {
  15865. mg_snprintf(NULL,
  15866. NULL,
  15867. block,
  15868. sizeof(block),
  15869. "\"data\" : {%s"
  15870. "\"read\" : %" INT64_FMT "%s,"
  15871. "\"written\" : %" INT64_FMT "%s"
  15872. "},%s",
  15873. eol,
  15874. ctx->total_data_read,
  15875. eol,
  15876. ctx->total_data_written,
  15877. eol,
  15878. eol);
  15879. context_info_length += (int)strlen(block);
  15880. if (context_info_length + reserved_len < buflen) {
  15881. strcat0(buffer, block);
  15882. }
  15883. }
  15884. /* Execution time information */
  15885. if (ctx) {
  15886. char start_time_str[64] = {0};
  15887. char now_str[64] = {0};
  15888. time_t start_time = ctx->start_time;
  15889. time_t now = time(NULL);
  15890. gmt_time_string(start_time_str,
  15891. sizeof(start_time_str) - 1,
  15892. &start_time);
  15893. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15894. mg_snprintf(NULL,
  15895. NULL,
  15896. block,
  15897. sizeof(block),
  15898. "\"time\" : {%s"
  15899. "\"uptime\" : %.0f,%s"
  15900. "\"start\" : \"%s\",%s"
  15901. "\"now\" : \"%s\"%s"
  15902. "}%s",
  15903. eol,
  15904. difftime(now, start_time),
  15905. eol,
  15906. start_time_str,
  15907. eol,
  15908. now_str,
  15909. eol,
  15910. eol);
  15911. context_info_length += (int)strlen(block);
  15912. if (context_info_length + reserved_len < buflen) {
  15913. strcat0(buffer, block);
  15914. }
  15915. }
  15916. /* Terminate string */
  15917. if ((buflen > 0) && buffer && buffer[0]) {
  15918. if (context_info_length < buflen) {
  15919. strcat0(buffer, eoobj);
  15920. strcat0(buffer, eol);
  15921. }
  15922. }
  15923. context_info_length += reserved_len;
  15924. return context_info_length;
  15925. }
  15926. #endif
  15927. #ifdef MG_EXPERIMENTAL_INTERFACES
  15928. /* Get connection information. It can be printed or stored by the caller.
  15929. * Return the size of available information. */
  15930. static int
  15931. mg_get_connection_info_impl(const struct mg_context *ctx,
  15932. int idx,
  15933. char *buffer,
  15934. int buflen)
  15935. {
  15936. const struct mg_connection *conn;
  15937. const struct mg_request_info *ri;
  15938. char block[256];
  15939. int connection_info_length = 0;
  15940. int state = 0;
  15941. const char *state_str = "unknown";
  15942. #if defined(_WIN32)
  15943. const char *eol = "\r\n";
  15944. #else
  15945. const char *eol = "\n";
  15946. #endif
  15947. const char *eoobj = "}";
  15948. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15949. if ((buffer == NULL) || (buflen < 1)) {
  15950. buflen = 0;
  15951. } else {
  15952. *buffer = 0;
  15953. }
  15954. if ((ctx == NULL) || (idx < 0)) {
  15955. /* Parameter error */
  15956. return 0;
  15957. }
  15958. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  15959. /* Out of range */
  15960. return 0;
  15961. }
  15962. /* Take connection [idx]. This connection is not locked in
  15963. * any way, so some other thread might use it. */
  15964. conn = (ctx->worker_connections) + idx;
  15965. /* Initialize output string */
  15966. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15967. connection_info_length += (int)strlen(block);
  15968. if (connection_info_length < buflen) {
  15969. strcat0(buffer, block);
  15970. }
  15971. /* Init variables */
  15972. ri = &(conn->request_info);
  15973. #if defined(USE_SERVER_STATS)
  15974. state = conn->conn_state;
  15975. /* State as string */
  15976. switch (state) {
  15977. case 0:
  15978. state_str = "undefined";
  15979. break;
  15980. case 1:
  15981. state_str = "not used";
  15982. break;
  15983. case 2:
  15984. state_str = "init";
  15985. break;
  15986. case 3:
  15987. state_str = "ready";
  15988. break;
  15989. case 4:
  15990. state_str = "processing";
  15991. break;
  15992. case 5:
  15993. state_str = "processed";
  15994. break;
  15995. case 6:
  15996. state_str = "to close";
  15997. break;
  15998. case 7:
  15999. state_str = "closing";
  16000. break;
  16001. case 8:
  16002. state_str = "closed";
  16003. break;
  16004. case 9:
  16005. state_str = "done";
  16006. break;
  16007. }
  16008. #endif
  16009. /* Connection info */
  16010. if ((state >= 3) && (state < 9)) {
  16011. mg_snprintf(NULL,
  16012. NULL,
  16013. block,
  16014. sizeof(block),
  16015. "\"connection\" : {%s"
  16016. "\"remote\" : {%s"
  16017. "\"protocol\" : \"%s\",%s"
  16018. "\"addr\" : \"%s\",%s"
  16019. "\"port\" : %u%s"
  16020. "},%s"
  16021. "\"handled_requests\" : %u%s"
  16022. "},%s",
  16023. eol,
  16024. eol,
  16025. get_proto_name(conn),
  16026. eol,
  16027. ri->remote_addr,
  16028. eol,
  16029. ri->remote_port,
  16030. eol,
  16031. eol,
  16032. conn->handled_requests,
  16033. eol,
  16034. eol);
  16035. connection_info_length += (int)strlen(block);
  16036. if (connection_info_length + reserved_len < buflen) {
  16037. strcat0(buffer, block);
  16038. }
  16039. }
  16040. /* Request info */
  16041. if ((state >= 4) && (state < 6)) {
  16042. mg_snprintf(NULL,
  16043. NULL,
  16044. block,
  16045. sizeof(block),
  16046. "\"request_info\" : {%s"
  16047. "\"method\" : \"%s\",%s"
  16048. "\"uri\" : \"%s\",%s"
  16049. "\"query\" : %s%s%s%s"
  16050. "},%s",
  16051. eol,
  16052. ri->request_method,
  16053. eol,
  16054. ri->request_uri,
  16055. eol,
  16056. ri->query_string ? "\"" : "",
  16057. ri->query_string ? ri->query_string : "null",
  16058. ri->query_string ? "\"" : "",
  16059. eol,
  16060. eol);
  16061. connection_info_length += (int)strlen(block);
  16062. if (connection_info_length + reserved_len < buflen) {
  16063. strcat0(buffer, block);
  16064. }
  16065. }
  16066. /* Execution time information */
  16067. if ((state >= 2) && (state < 9)) {
  16068. char start_time_str[64] = {0};
  16069. char now_str[64] = {0};
  16070. time_t start_time = conn->conn_birth_time;
  16071. time_t now = time(NULL);
  16072. gmt_time_string(start_time_str,
  16073. sizeof(start_time_str) - 1,
  16074. &start_time);
  16075. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16076. mg_snprintf(NULL,
  16077. NULL,
  16078. block,
  16079. sizeof(block),
  16080. "\"time\" : {%s"
  16081. "\"uptime\" : %.0f,%s"
  16082. "\"start\" : \"%s\",%s"
  16083. "\"now\" : \"%s\"%s"
  16084. "},%s",
  16085. eol,
  16086. difftime(now, start_time),
  16087. eol,
  16088. start_time_str,
  16089. eol,
  16090. now_str,
  16091. eol,
  16092. eol);
  16093. connection_info_length += (int)strlen(block);
  16094. if (connection_info_length + reserved_len < buflen) {
  16095. strcat0(buffer, block);
  16096. }
  16097. }
  16098. /* Remote user name */
  16099. if ((ri->remote_user) && (state < 9)) {
  16100. mg_snprintf(NULL,
  16101. NULL,
  16102. block,
  16103. sizeof(block),
  16104. "\"user\" : {%s"
  16105. "\"name\" : \"%s\",%s"
  16106. "},%s",
  16107. eol,
  16108. ri->remote_user,
  16109. eol,
  16110. eol);
  16111. connection_info_length += (int)strlen(block);
  16112. if (connection_info_length + reserved_len < buflen) {
  16113. strcat0(buffer, block);
  16114. }
  16115. }
  16116. /* Data block */
  16117. if (state >= 3) {
  16118. mg_snprintf(NULL,
  16119. NULL,
  16120. block,
  16121. sizeof(block),
  16122. "\"data\" : {%s"
  16123. "\"read\" : %" INT64_FMT ",%s"
  16124. "\"written\" : %" INT64_FMT "%s"
  16125. "},%s",
  16126. eol,
  16127. conn->consumed_content,
  16128. eol,
  16129. conn->num_bytes_sent,
  16130. eol,
  16131. eol);
  16132. connection_info_length += (int)strlen(block);
  16133. if (connection_info_length + reserved_len < buflen) {
  16134. strcat0(buffer, block);
  16135. }
  16136. }
  16137. /* State */
  16138. mg_snprintf(NULL,
  16139. NULL,
  16140. block,
  16141. sizeof(block),
  16142. "\"state\" : \"%s\"%s",
  16143. state_str,
  16144. eol);
  16145. connection_info_length += (int)strlen(block);
  16146. if (connection_info_length + reserved_len < buflen) {
  16147. strcat0(buffer, block);
  16148. }
  16149. /* Terminate string */
  16150. if ((buflen > 0) && buffer && buffer[0]) {
  16151. if (connection_info_length < buflen) {
  16152. strcat0(buffer, eoobj);
  16153. strcat0(buffer, eol);
  16154. }
  16155. }
  16156. connection_info_length += reserved_len;
  16157. return connection_info_length;
  16158. }
  16159. #endif
  16160. /* Get system information. It can be printed or stored by the caller.
  16161. * Return the size of available information. */
  16162. int
  16163. mg_get_system_info(char *buffer, int buflen)
  16164. {
  16165. if ((buffer == NULL) || (buflen < 1)) {
  16166. return mg_get_system_info_impl(NULL, 0);
  16167. } else {
  16168. /* Reset buffer, so we can always use strcat. */
  16169. buffer[0] = 0;
  16170. return mg_get_system_info_impl(buffer, buflen);
  16171. }
  16172. }
  16173. /* Get context information. It can be printed or stored by the caller.
  16174. * Return the size of available information. */
  16175. int
  16176. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16177. {
  16178. #if defined(USE_SERVER_STATS)
  16179. if ((buffer == NULL) || (buflen < 1)) {
  16180. return mg_get_context_info_impl(ctx, NULL, 0);
  16181. } else {
  16182. /* Reset buffer, so we can always use strcat. */
  16183. buffer[0] = 0;
  16184. return mg_get_context_info_impl(ctx, buffer, buflen);
  16185. }
  16186. #else
  16187. (void)ctx;
  16188. if ((buffer != NULL) && (buflen > 0)) {
  16189. buffer[0] = 0;
  16190. }
  16191. return 0;
  16192. #endif
  16193. }
  16194. #ifdef MG_EXPERIMENTAL_INTERFACES
  16195. int
  16196. mg_get_connection_info(const struct mg_context *ctx,
  16197. int idx,
  16198. char *buffer,
  16199. int buflen)
  16200. {
  16201. if ((buffer == NULL) || (buflen < 1)) {
  16202. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  16203. } else {
  16204. /* Reset buffer, so we can always use strcat. */
  16205. buffer[0] = 0;
  16206. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  16207. }
  16208. }
  16209. #endif
  16210. /* Initialize this library. This function does not need to be thread safe.
  16211. */
  16212. unsigned
  16213. mg_init_library(unsigned features)
  16214. {
  16215. #if !defined(NO_SSL)
  16216. char ebuf[128];
  16217. #endif
  16218. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  16219. unsigned features_inited = features_to_init;
  16220. if (mg_init_library_called <= 0) {
  16221. /* Not initialized yet */
  16222. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  16223. return 0;
  16224. }
  16225. }
  16226. mg_global_lock();
  16227. if (mg_init_library_called <= 0) {
  16228. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  16229. /* Fatal error - abort start. However, this situation should
  16230. * never occur in practice. */
  16231. mg_global_unlock();
  16232. return 0;
  16233. }
  16234. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16235. InitializeCriticalSection(&global_log_file_lock);
  16236. #endif /* _WIN32 && !__SYMBIAN32__ */
  16237. #if !defined(_WIN32)
  16238. pthread_mutexattr_init(&pthread_mutex_attr);
  16239. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  16240. #endif
  16241. #if defined(USE_LUA)
  16242. lua_init_optional_libraries();
  16243. #endif
  16244. }
  16245. mg_global_unlock();
  16246. #if !defined(NO_SSL)
  16247. if (features_to_init & MG_FEATURES_SSL) {
  16248. if (!mg_ssl_initialized) {
  16249. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  16250. mg_ssl_initialized = 1;
  16251. } else {
  16252. (void)ebuf;
  16253. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  16254. features_inited &= ~(2u);
  16255. }
  16256. } else {
  16257. /* ssl already initialized */
  16258. }
  16259. }
  16260. #endif
  16261. /* Start WinSock for Windows */
  16262. mg_global_lock();
  16263. if (mg_init_library_called <= 0) {
  16264. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16265. WSADATA data;
  16266. WSAStartup(MAKEWORD(2, 2), &data);
  16267. #endif /* _WIN32 && !__SYMBIAN32__ */
  16268. mg_init_library_called = 1;
  16269. } else {
  16270. mg_init_library_called++;
  16271. }
  16272. mg_global_unlock();
  16273. return features_inited;
  16274. }
  16275. /* Un-initialize this library. */
  16276. unsigned
  16277. mg_exit_library(void)
  16278. {
  16279. if (mg_init_library_called <= 0) {
  16280. return 0;
  16281. }
  16282. mg_global_lock();
  16283. mg_init_library_called--;
  16284. if (mg_init_library_called == 0) {
  16285. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16286. (void)WSACleanup();
  16287. #endif /* _WIN32 && !__SYMBIAN32__ */
  16288. #if !defined(NO_SSL)
  16289. if (mg_ssl_initialized) {
  16290. uninitialize_ssl();
  16291. mg_ssl_initialized = 0;
  16292. }
  16293. #endif
  16294. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16295. (void)DeleteCriticalSection(&global_log_file_lock);
  16296. #endif /* _WIN32 && !__SYMBIAN32__ */
  16297. #if !defined(_WIN32)
  16298. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  16299. #endif
  16300. (void)pthread_key_delete(sTlsKey);
  16301. #if defined(USE_LUA)
  16302. lua_exit_optional_libraries();
  16303. #endif
  16304. mg_global_unlock();
  16305. (void)pthread_mutex_destroy(&global_lock_mutex);
  16306. return 1;
  16307. }
  16308. mg_global_unlock();
  16309. return 1;
  16310. }
  16311. /* End of civetweb.c */