civetweb.c 526 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710
  1. /* Copyright (c) 2013-2018 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0501
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Alternative queue is well tested and should be the new default */
  123. #if defined(NO_ALTERNATIVE_QUEUE)
  124. #if defined(ALTERNATIVE_QUEUE)
  125. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  126. #endif
  127. #else
  128. #define ALTERNATIVE_QUEUE
  129. #endif
  130. /* DTL -- including winsock2.h works better if lean and mean */
  131. #if !defined(WIN32_LEAN_AND_MEAN)
  132. #define WIN32_LEAN_AND_MEAN
  133. #endif
  134. #if defined(__SYMBIAN32__)
  135. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  136. * Symbian is no longer maintained since 2014-01-01.
  137. * Recent versions of CivetWeb are no longer tested for Symbian.
  138. * It makes no sense, to support an abandoned operating system.
  139. */
  140. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  141. #define NO_SSL /* SSL is not supported */
  142. #define NO_CGI /* CGI is not supported */
  143. #define PATH_MAX FILENAME_MAX
  144. #endif /* __SYMBIAN32__ */
  145. #if !defined(CIVETWEB_HEADER_INCLUDED)
  146. /* Include the header file here, so the CivetWeb interface is defined for the
  147. * entire implementation, including the following forward definitions. */
  148. #include "civetweb.h"
  149. #endif
  150. #if !defined(DEBUG_TRACE)
  151. #if defined(DEBUG)
  152. static void DEBUG_TRACE_FUNC(const char *func,
  153. unsigned line,
  154. PRINTF_FORMAT_STRING(const char *fmt),
  155. ...) PRINTF_ARGS(3, 4);
  156. #define DEBUG_TRACE(fmt, ...) \
  157. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  158. #define NEED_DEBUG_TRACE_FUNC
  159. #else
  160. #define DEBUG_TRACE(fmt, ...) \
  161. do { \
  162. } while (0)
  163. #endif /* DEBUG */
  164. #endif /* DEBUG_TRACE */
  165. #if !defined(DEBUG_ASSERT)
  166. #if defined(DEBUG)
  167. #define DEBUG_ASSERT(cond) \
  168. do { \
  169. if (!(cond)) { \
  170. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  171. exit(2); /* Exit with error */ \
  172. } \
  173. } while (0)
  174. #else
  175. #define DEBUG_ASSERT(cond)
  176. #endif /* DEBUG */
  177. #endif
  178. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  179. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  180. __attribute__((no_instrument_function));
  181. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  182. __attribute__((no_instrument_function));
  183. void
  184. __cyg_profile_func_enter(void *this_fn, void *call_site)
  185. {
  186. if ((void *)this_fn != (void *)printf) {
  187. printf("E %p %p\n", this_fn, call_site);
  188. }
  189. }
  190. void
  191. __cyg_profile_func_exit(void *this_fn, void *call_site)
  192. {
  193. if ((void *)this_fn != (void *)printf) {
  194. printf("X %p %p\n", this_fn, call_site);
  195. }
  196. }
  197. #endif
  198. #if !defined(IGNORE_UNUSED_RESULT)
  199. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  200. #endif
  201. #if defined(__GNUC__) || defined(__MINGW32__)
  202. /* GCC unused function attribute seems fundamentally broken.
  203. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  204. * OR UNUSED" for individual functions failed.
  205. * Either the compiler creates an "unused-function" warning if a
  206. * function is not marked with __attribute__((unused)).
  207. * On the other hand, if the function is marked with this attribute,
  208. * but is used, the compiler raises a completely idiotic
  209. * "used-but-marked-unused" warning - and
  210. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  211. * raises error: unknown option after "#pragma GCC diagnostic".
  212. * Disable this warning completely, until the GCC guys sober up
  213. * again.
  214. */
  215. #pragma GCC diagnostic ignored "-Wunused-function"
  216. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  217. #else
  218. #define FUNCTION_MAY_BE_UNUSED
  219. #endif
  220. /* Some ANSI #includes are not available on Windows CE */
  221. #if !defined(_WIN32_WCE)
  222. #include <errno.h>
  223. #include <fcntl.h>
  224. #include <signal.h>
  225. #include <sys/stat.h>
  226. #include <sys/types.h>
  227. #endif /* !_WIN32_WCE */
  228. #if defined(__clang__)
  229. /* When using -Weverything, clang does not accept it's own headers
  230. * in a release build configuration. Disable what is too much in
  231. * -Weverything. */
  232. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  233. #endif
  234. #if defined(__GNUC__) || defined(__MINGW32__)
  235. /* Who on earth came to the conclusion, using __DATE__ should rise
  236. * an "expansion of date or time macro is not reproducible"
  237. * warning. That's exactly what was intended by using this macro.
  238. * Just disable this nonsense warning. */
  239. /* And disabling them does not work either:
  240. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  241. * #pragma clang diagnostic ignored "-Wdate-time"
  242. * So we just have to disable ALL warnings for some lines
  243. * of code.
  244. * This seems to be a known GCC bug, not resolved since 2012:
  245. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  246. */
  247. #endif
  248. #if defined(__MACH__) /* Apple OSX section */
  249. #if defined(__clang__)
  250. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  251. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  252. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  253. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  254. #endif
  255. #endif
  256. #define CLOCK_MONOTONIC (1)
  257. #define CLOCK_REALTIME (2)
  258. #include <mach/clock.h>
  259. #include <mach/mach.h>
  260. #include <mach/mach_time.h>
  261. #include <sys/errno.h>
  262. #include <sys/time.h>
  263. /* clock_gettime is not implemented on OSX prior to 10.12 */
  264. static int
  265. _civet_clock_gettime(int clk_id, struct timespec *t)
  266. {
  267. memset(t, 0, sizeof(*t));
  268. if (clk_id == CLOCK_REALTIME) {
  269. struct timeval now;
  270. int rv = gettimeofday(&now, NULL);
  271. if (rv) {
  272. return rv;
  273. }
  274. t->tv_sec = now.tv_sec;
  275. t->tv_nsec = now.tv_usec * 1000;
  276. return 0;
  277. } else if (clk_id == CLOCK_MONOTONIC) {
  278. static uint64_t clock_start_time = 0;
  279. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  280. uint64_t now = mach_absolute_time();
  281. if (clock_start_time == 0) {
  282. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  283. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  284. /* appease "unused variable" warning for release builds */
  285. (void)mach_status;
  286. clock_start_time = now;
  287. }
  288. now = (uint64_t)((double)(now - clock_start_time)
  289. * (double)timebase_ifo.numer
  290. / (double)timebase_ifo.denom);
  291. t->tv_sec = now / 1000000000;
  292. t->tv_nsec = now % 1000000000;
  293. return 0;
  294. }
  295. return -1; /* EINVAL - Clock ID is unknown */
  296. }
  297. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  298. #if defined(__CLOCK_AVAILABILITY)
  299. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  300. * declared but it may be NULL at runtime. So we need to check before using
  301. * it. */
  302. static int
  303. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  304. {
  305. if (clock_gettime) {
  306. return clock_gettime(clk_id, t);
  307. }
  308. return _civet_clock_gettime(clk_id, t);
  309. }
  310. #define clock_gettime _civet_safe_clock_gettime
  311. #else
  312. #define clock_gettime _civet_clock_gettime
  313. #endif
  314. #endif
  315. #include <ctype.h>
  316. #include <limits.h>
  317. #include <stdarg.h>
  318. #include <stddef.h>
  319. #include <stdint.h>
  320. #include <stdio.h>
  321. #include <stdlib.h>
  322. #include <string.h>
  323. #include <time.h>
  324. /********************************************************************/
  325. /* CivetWeb configuration defines */
  326. /********************************************************************/
  327. /* Maximum number of threads that can be configured.
  328. * The number of threads actually created depends on the "num_threads"
  329. * configuration parameter, but this is the upper limit. */
  330. #if !defined(MAX_WORKER_THREADS)
  331. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  332. #endif
  333. /* Timeout interval for select/poll calls.
  334. * The timeouts depend on "*_timeout_ms" configuration values, but long
  335. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  336. * This reduces the time required to stop the server. */
  337. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  338. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  339. #endif
  340. /* Do not try to compress files smaller than this limit. */
  341. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  342. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  343. #endif
  344. #if !defined(PASSWORDS_FILE_NAME)
  345. #define PASSWORDS_FILE_NAME ".htpasswd"
  346. #endif
  347. /* Initial buffer size for all CGI environment variables. In case there is
  348. * not enough space, another block is allocated. */
  349. #if !defined(CGI_ENVIRONMENT_SIZE)
  350. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  351. #endif
  352. /* Maximum number of environment variables. */
  353. #if !defined(MAX_CGI_ENVIR_VARS)
  354. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  355. #endif
  356. /* General purpose buffer size. */
  357. #if !defined(MG_BUF_LEN) /* in bytes */
  358. #define MG_BUF_LEN (1024 * 8)
  359. #endif
  360. /* Size of the accepted socket queue (in case the old queue implementation
  361. * is used). */
  362. #if !defined(MGSQLEN)
  363. #define MGSQLEN (20) /* count */
  364. #endif
  365. /********************************************************************/
  366. /* Helper makros */
  367. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  368. /* Standard defines */
  369. #if !defined(INT64_MAX)
  370. #define INT64_MAX (9223372036854775807)
  371. #endif
  372. #define SHUTDOWN_RD (0)
  373. #define SHUTDOWN_WR (1)
  374. #define SHUTDOWN_BOTH (2)
  375. mg_static_assert(MAX_WORKER_THREADS >= 1,
  376. "worker threads must be a positive number");
  377. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  378. "size_t data type size check");
  379. #if defined(_WIN32) /* WINDOWS include block */
  380. #include <windows.h>
  381. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  382. #include <ws2tcpip.h>
  383. typedef const char *SOCK_OPT_TYPE;
  384. #if !defined(PATH_MAX)
  385. #define W_PATH_MAX (MAX_PATH)
  386. /* at most three UTF-8 chars per wchar_t */
  387. #define PATH_MAX (W_PATH_MAX * 3)
  388. #else
  389. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  390. #endif
  391. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  392. #if !defined(_IN_PORT_T)
  393. #if !defined(in_port_t)
  394. #define in_port_t u_short
  395. #endif
  396. #endif
  397. #if !defined(_WIN32_WCE)
  398. #include <direct.h>
  399. #include <io.h>
  400. #include <process.h>
  401. #else /* _WIN32_WCE */
  402. #define NO_CGI /* WinCE has no pipes */
  403. #define NO_POPEN /* WinCE has no popen */
  404. typedef long off_t;
  405. #define errno ((int)(GetLastError()))
  406. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  407. #endif /* _WIN32_WCE */
  408. #define MAKEUQUAD(lo, hi) \
  409. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  410. #define RATE_DIFF (10000000) /* 100 nsecs */
  411. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  412. #define SYS2UNIX_TIME(lo, hi) \
  413. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  414. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  415. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  416. * Also use _strtoui64 on modern M$ compilers */
  417. #if defined(_MSC_VER)
  418. #if (_MSC_VER < 1300)
  419. #define STRX(x) #x
  420. #define STR(x) STRX(x)
  421. #define __func__ __FILE__ ":" STR(__LINE__)
  422. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  423. #define strtoll(x, y, z) (_atoi64(x))
  424. #else
  425. #define __func__ __FUNCTION__
  426. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  427. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  428. #endif
  429. #endif /* _MSC_VER */
  430. #define ERRNO ((int)(GetLastError()))
  431. #define NO_SOCKLEN_T
  432. #if defined(_WIN64) || defined(__MINGW64__)
  433. #if !defined(SSL_LIB)
  434. #define SSL_LIB "ssleay64.dll"
  435. #endif
  436. #if !defined(CRYPTO_LIB)
  437. #define CRYPTO_LIB "libeay64.dll"
  438. #endif
  439. #else
  440. #if !defined(SSL_LIB)
  441. #define SSL_LIB "ssleay32.dll"
  442. #endif
  443. #if !defined(CRYPTO_LIB)
  444. #define CRYPTO_LIB "libeay32.dll"
  445. #endif
  446. #endif
  447. #define O_NONBLOCK (0)
  448. #if !defined(W_OK)
  449. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  450. #endif
  451. #define _POSIX_
  452. #define INT64_FMT "I64d"
  453. #define UINT64_FMT "I64u"
  454. #define WINCDECL __cdecl
  455. #define vsnprintf_impl _vsnprintf
  456. #define access _access
  457. #define mg_sleep(x) (Sleep(x))
  458. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  459. #if !defined(popen)
  460. #define popen(x, y) (_popen(x, y))
  461. #endif
  462. #if !defined(pclose)
  463. #define pclose(x) (_pclose(x))
  464. #endif
  465. #define close(x) (_close(x))
  466. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  467. #define RTLD_LAZY (0)
  468. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  469. #define fdopen(x, y) (_fdopen((x), (y)))
  470. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  471. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  472. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  473. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  474. #define sleep(x) (Sleep((x)*1000))
  475. #define rmdir(x) (_rmdir(x))
  476. #if defined(_WIN64) || !defined(__MINGW32__)
  477. /* Only MinGW 32 bit is missing this function */
  478. #define timegm(x) (_mkgmtime(x))
  479. #else
  480. time_t timegm(struct tm *tm);
  481. #define NEED_TIMEGM
  482. #endif
  483. #if !defined(fileno)
  484. #define fileno(x) (_fileno(x))
  485. #endif /* !fileno MINGW #defines fileno */
  486. typedef struct {
  487. CRITICAL_SECTION sec; /* Immovable */
  488. } pthread_mutex_t;
  489. typedef DWORD pthread_key_t;
  490. typedef HANDLE pthread_t;
  491. typedef struct {
  492. pthread_mutex_t threadIdSec;
  493. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  494. } pthread_cond_t;
  495. #if !defined(__clockid_t_defined)
  496. typedef DWORD clockid_t;
  497. #endif
  498. #if !defined(CLOCK_MONOTONIC)
  499. #define CLOCK_MONOTONIC (1)
  500. #endif
  501. #if !defined(CLOCK_REALTIME)
  502. #define CLOCK_REALTIME (2)
  503. #endif
  504. #if !defined(CLOCK_THREAD)
  505. #define CLOCK_THREAD (3)
  506. #endif
  507. #if !defined(CLOCK_PROCESS)
  508. #define CLOCK_PROCESS (4)
  509. #endif
  510. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  511. #define _TIMESPEC_DEFINED
  512. #endif
  513. #if !defined(_TIMESPEC_DEFINED)
  514. struct timespec {
  515. time_t tv_sec; /* seconds */
  516. long tv_nsec; /* nanoseconds */
  517. };
  518. #endif
  519. #if !defined(WIN_PTHREADS_TIME_H)
  520. #define MUST_IMPLEMENT_CLOCK_GETTIME
  521. #endif
  522. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  523. #define clock_gettime mg_clock_gettime
  524. static int
  525. clock_gettime(clockid_t clk_id, struct timespec *tp)
  526. {
  527. FILETIME ft;
  528. ULARGE_INTEGER li, li2;
  529. BOOL ok = FALSE;
  530. double d;
  531. static double perfcnt_per_sec = 0.0;
  532. static BOOL initialized = FALSE;
  533. if (!initialized) {
  534. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  535. perfcnt_per_sec = 1.0 / li.QuadPart;
  536. initialized = TRUE;
  537. }
  538. if (tp) {
  539. memset(tp, 0, sizeof(*tp));
  540. if (clk_id == CLOCK_REALTIME) {
  541. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  542. GetSystemTimeAsFileTime(&ft);
  543. li.LowPart = ft.dwLowDateTime;
  544. li.HighPart = ft.dwHighDateTime;
  545. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  546. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  547. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  548. ok = TRUE;
  549. /* END: CLOCK_REALTIME */
  550. } else if (clk_id == CLOCK_MONOTONIC) {
  551. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  552. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  553. d = li.QuadPart * perfcnt_per_sec;
  554. tp->tv_sec = (time_t)d;
  555. d -= (double)tp->tv_sec;
  556. tp->tv_nsec = (long)(d * 1.0E9);
  557. ok = TRUE;
  558. /* END: CLOCK_MONOTONIC */
  559. } else if (clk_id == CLOCK_THREAD) {
  560. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  561. FILETIME t_create, t_exit, t_kernel, t_user;
  562. if (GetThreadTimes(GetCurrentThread(),
  563. &t_create,
  564. &t_exit,
  565. &t_kernel,
  566. &t_user)) {
  567. li.LowPart = t_user.dwLowDateTime;
  568. li.HighPart = t_user.dwHighDateTime;
  569. li2.LowPart = t_kernel.dwLowDateTime;
  570. li2.HighPart = t_kernel.dwHighDateTime;
  571. li.QuadPart += li2.QuadPart;
  572. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  573. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  574. ok = TRUE;
  575. }
  576. /* END: CLOCK_THREAD */
  577. } else if (clk_id == CLOCK_PROCESS) {
  578. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  579. FILETIME t_create, t_exit, t_kernel, t_user;
  580. if (GetProcessTimes(GetCurrentProcess(),
  581. &t_create,
  582. &t_exit,
  583. &t_kernel,
  584. &t_user)) {
  585. li.LowPart = t_user.dwLowDateTime;
  586. li.HighPart = t_user.dwHighDateTime;
  587. li2.LowPart = t_kernel.dwLowDateTime;
  588. li2.HighPart = t_kernel.dwHighDateTime;
  589. li.QuadPart += li2.QuadPart;
  590. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  591. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  592. ok = TRUE;
  593. }
  594. /* END: CLOCK_PROCESS */
  595. } else {
  596. /* BEGIN: unknown clock */
  597. /* ok = FALSE; already set by init */
  598. /* END: unknown clock */
  599. }
  600. }
  601. return ok ? 0 : -1;
  602. }
  603. #endif
  604. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  605. static int pthread_mutex_lock(pthread_mutex_t *);
  606. static int pthread_mutex_unlock(pthread_mutex_t *);
  607. static void path_to_unicode(const struct mg_connection *conn,
  608. const char *path,
  609. wchar_t *wbuf,
  610. size_t wbuf_len);
  611. /* All file operations need to be rewritten to solve #246. */
  612. struct mg_file;
  613. static const char *
  614. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  615. /* POSIX dirent interface */
  616. struct dirent {
  617. char d_name[PATH_MAX];
  618. };
  619. typedef struct DIR {
  620. HANDLE handle;
  621. WIN32_FIND_DATAW info;
  622. struct dirent result;
  623. } DIR;
  624. #if defined(HAVE_POLL)
  625. #define mg_pollfd pollfd
  626. #else
  627. struct mg_pollfd {
  628. SOCKET fd;
  629. short events;
  630. short revents;
  631. };
  632. #endif
  633. /* Mark required libraries */
  634. #if defined(_MSC_VER)
  635. #pragma comment(lib, "Ws2_32.lib")
  636. #endif
  637. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  638. #include <arpa/inet.h>
  639. #include <inttypes.h>
  640. #include <netdb.h>
  641. #include <netinet/in.h>
  642. #include <netinet/tcp.h>
  643. #include <stdint.h>
  644. #include <sys/poll.h>
  645. #include <sys/socket.h>
  646. #include <sys/time.h>
  647. #include <sys/utsname.h>
  648. #include <sys/wait.h>
  649. typedef const void *SOCK_OPT_TYPE;
  650. #if defined(ANDROID)
  651. typedef unsigned short int in_port_t;
  652. #endif
  653. #include <dirent.h>
  654. #include <grp.h>
  655. #include <pwd.h>
  656. #include <unistd.h>
  657. #define vsnprintf_impl vsnprintf
  658. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  659. #include <dlfcn.h>
  660. #endif
  661. #include <pthread.h>
  662. #if defined(__MACH__)
  663. #define SSL_LIB "libssl.dylib"
  664. #define CRYPTO_LIB "libcrypto.dylib"
  665. #else
  666. #if !defined(SSL_LIB)
  667. #define SSL_LIB "libssl.so"
  668. #endif
  669. #if !defined(CRYPTO_LIB)
  670. #define CRYPTO_LIB "libcrypto.so"
  671. #endif
  672. #endif
  673. #if !defined(O_BINARY)
  674. #define O_BINARY (0)
  675. #endif /* O_BINARY */
  676. #define closesocket(a) (close(a))
  677. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  678. #define mg_remove(conn, x) (remove(x))
  679. #define mg_sleep(x) (usleep((x)*1000))
  680. #define mg_opendir(conn, x) (opendir(x))
  681. #define mg_closedir(x) (closedir(x))
  682. #define mg_readdir(x) (readdir(x))
  683. #define ERRNO (errno)
  684. #define INVALID_SOCKET (-1)
  685. #define INT64_FMT PRId64
  686. #define UINT64_FMT PRIu64
  687. typedef int SOCKET;
  688. #define WINCDECL
  689. #if defined(__hpux)
  690. /* HPUX 11 does not have monotonic, fall back to realtime */
  691. #if !defined(CLOCK_MONOTONIC)
  692. #define CLOCK_MONOTONIC CLOCK_REALTIME
  693. #endif
  694. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  695. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  696. * the prototypes use int* rather than socklen_t* which matches the
  697. * actual library expectation. When called with the wrong size arg
  698. * accept() returns a zero client inet addr and check_acl() always
  699. * fails. Since socklen_t is widely used below, just force replace
  700. * their typedef with int. - DTL
  701. */
  702. #define socklen_t int
  703. #endif /* hpux */
  704. #define mg_pollfd pollfd
  705. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  706. /* Maximum queue length for pending connections. This value is passed as
  707. * parameter to the "listen" socket call. */
  708. #if !defined(SOMAXCONN)
  709. /* This symbol may be defined in winsock2.h so this must after that include */
  710. #define SOMAXCONN (100) /* in pending connections (count) */
  711. #endif
  712. /* In case our C library is missing "timegm", provide an implementation */
  713. #if defined(NEED_TIMEGM)
  714. static inline int
  715. is_leap(int y)
  716. {
  717. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  718. }
  719. static inline int
  720. count_leap(int y)
  721. {
  722. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  723. }
  724. time_t
  725. timegm(struct tm *tm)
  726. {
  727. static const unsigned short ydays[] = {
  728. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  729. int year = tm->tm_year + 1900;
  730. int mon = tm->tm_mon;
  731. int mday = tm->tm_mday - 1;
  732. int hour = tm->tm_hour;
  733. int min = tm->tm_min;
  734. int sec = tm->tm_sec;
  735. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  736. || (mday >= ydays[mon + 1] - ydays[mon]
  737. + (mon == 1 && is_leap(year) ? 1 : 0))
  738. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  739. return -1;
  740. time_t res = year - 1970;
  741. res *= 365;
  742. res += mday;
  743. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  744. res += count_leap(year);
  745. res *= 24;
  746. res += hour;
  747. res *= 60;
  748. res += min;
  749. res *= 60;
  750. res += sec;
  751. return res;
  752. }
  753. #endif /* NEED_TIMEGM */
  754. /* va_copy should always be a macro, C99 and C++11 - DTL */
  755. #if !defined(va_copy)
  756. #define va_copy(x, y) ((x) = (y))
  757. #endif
  758. #if defined(_WIN32)
  759. /* Create substitutes for POSIX functions in Win32. */
  760. #if defined(GCC_DIAGNOSTIC)
  761. /* Show no warning in case system functions are not used. */
  762. #pragma GCC diagnostic push
  763. #pragma GCC diagnostic ignored "-Wunused-function"
  764. #endif
  765. static pthread_mutex_t global_log_file_lock;
  766. FUNCTION_MAY_BE_UNUSED
  767. static DWORD
  768. pthread_self(void)
  769. {
  770. return GetCurrentThreadId();
  771. }
  772. FUNCTION_MAY_BE_UNUSED
  773. static int
  774. pthread_key_create(
  775. pthread_key_t *key,
  776. void (*_ignored)(void *) /* destructor not supported for Windows */
  777. )
  778. {
  779. (void)_ignored;
  780. if ((key != 0)) {
  781. *key = TlsAlloc();
  782. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  783. }
  784. return -2;
  785. }
  786. FUNCTION_MAY_BE_UNUSED
  787. static int
  788. pthread_key_delete(pthread_key_t key)
  789. {
  790. return TlsFree(key) ? 0 : 1;
  791. }
  792. FUNCTION_MAY_BE_UNUSED
  793. static int
  794. pthread_setspecific(pthread_key_t key, void *value)
  795. {
  796. return TlsSetValue(key, value) ? 0 : 1;
  797. }
  798. FUNCTION_MAY_BE_UNUSED
  799. static void *
  800. pthread_getspecific(pthread_key_t key)
  801. {
  802. return TlsGetValue(key);
  803. }
  804. #if defined(GCC_DIAGNOSTIC)
  805. /* Enable unused function warning again */
  806. #pragma GCC diagnostic pop
  807. #endif
  808. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  809. #else
  810. static pthread_mutexattr_t pthread_mutex_attr;
  811. #endif /* _WIN32 */
  812. #if defined(_WIN32_WCE)
  813. /* Create substitutes for POSIX functions in Win32. */
  814. #if defined(GCC_DIAGNOSTIC)
  815. /* Show no warning in case system functions are not used. */
  816. #pragma GCC diagnostic push
  817. #pragma GCC diagnostic ignored "-Wunused-function"
  818. #endif
  819. FUNCTION_MAY_BE_UNUSED
  820. static time_t
  821. time(time_t *ptime)
  822. {
  823. time_t t;
  824. SYSTEMTIME st;
  825. FILETIME ft;
  826. GetSystemTime(&st);
  827. SystemTimeToFileTime(&st, &ft);
  828. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  829. if (ptime != NULL) {
  830. *ptime = t;
  831. }
  832. return t;
  833. }
  834. FUNCTION_MAY_BE_UNUSED
  835. static struct tm *
  836. localtime_s(const time_t *ptime, struct tm *ptm)
  837. {
  838. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  839. FILETIME ft, lft;
  840. SYSTEMTIME st;
  841. TIME_ZONE_INFORMATION tzinfo;
  842. if (ptm == NULL) {
  843. return NULL;
  844. }
  845. *(int64_t *)&ft = t;
  846. FileTimeToLocalFileTime(&ft, &lft);
  847. FileTimeToSystemTime(&lft, &st);
  848. ptm->tm_year = st.wYear - 1900;
  849. ptm->tm_mon = st.wMonth - 1;
  850. ptm->tm_wday = st.wDayOfWeek;
  851. ptm->tm_mday = st.wDay;
  852. ptm->tm_hour = st.wHour;
  853. ptm->tm_min = st.wMinute;
  854. ptm->tm_sec = st.wSecond;
  855. ptm->tm_yday = 0; /* hope nobody uses this */
  856. ptm->tm_isdst =
  857. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  858. return ptm;
  859. }
  860. FUNCTION_MAY_BE_UNUSED
  861. static struct tm *
  862. gmtime_s(const time_t *ptime, struct tm *ptm)
  863. {
  864. /* FIXME(lsm): fix this. */
  865. return localtime_s(ptime, ptm);
  866. }
  867. static int mg_atomic_inc(volatile int *addr);
  868. static struct tm tm_array[MAX_WORKER_THREADS];
  869. static int tm_index = 0;
  870. FUNCTION_MAY_BE_UNUSED
  871. static struct tm *
  872. localtime(const time_t *ptime)
  873. {
  874. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  875. return localtime_s(ptime, tm_array + i);
  876. }
  877. FUNCTION_MAY_BE_UNUSED
  878. static struct tm *
  879. gmtime(const time_t *ptime)
  880. {
  881. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  882. return gmtime_s(ptime, tm_array + i);
  883. }
  884. FUNCTION_MAY_BE_UNUSED
  885. static size_t
  886. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  887. {
  888. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  889. * for WinCE"); */
  890. return 0;
  891. }
  892. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  893. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  894. #define remove(f) mg_remove(NULL, f)
  895. FUNCTION_MAY_BE_UNUSED
  896. static int
  897. rename(const char *a, const char *b)
  898. {
  899. wchar_t wa[W_PATH_MAX];
  900. wchar_t wb[W_PATH_MAX];
  901. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  902. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  903. return MoveFileW(wa, wb) ? 0 : -1;
  904. }
  905. struct stat {
  906. int64_t st_size;
  907. time_t st_mtime;
  908. };
  909. FUNCTION_MAY_BE_UNUSED
  910. static int
  911. stat(const char *name, struct stat *st)
  912. {
  913. wchar_t wbuf[W_PATH_MAX];
  914. WIN32_FILE_ATTRIBUTE_DATA attr;
  915. time_t creation_time, write_time;
  916. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  917. memset(&attr, 0, sizeof(attr));
  918. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  919. st->st_size =
  920. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  921. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  922. attr.ftLastWriteTime.dwHighDateTime);
  923. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  924. attr.ftCreationTime.dwHighDateTime);
  925. if (creation_time > write_time) {
  926. st->st_mtime = creation_time;
  927. } else {
  928. st->st_mtime = write_time;
  929. }
  930. return 0;
  931. }
  932. #define access(x, a) 1 /* not required anyway */
  933. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  934. /* Values from errno.h in Windows SDK (Visual Studio). */
  935. #define EEXIST 17
  936. #define EACCES 13
  937. #define ENOENT 2
  938. #if defined(GCC_DIAGNOSTIC)
  939. /* Enable unused function warning again */
  940. #pragma GCC diagnostic pop
  941. #endif
  942. #endif /* defined(_WIN32_WCE) */
  943. #if defined(GCC_DIAGNOSTIC)
  944. /* Show no warning in case system functions are not used. */
  945. #pragma GCC diagnostic push
  946. #pragma GCC diagnostic ignored "-Wunused-function"
  947. #endif /* defined(GCC_DIAGNOSTIC) */
  948. #if defined(__clang__)
  949. /* Show no warning in case system functions are not used. */
  950. #pragma clang diagnostic push
  951. #pragma clang diagnostic ignored "-Wunused-function"
  952. #endif
  953. static pthread_mutex_t global_lock_mutex;
  954. FUNCTION_MAY_BE_UNUSED
  955. static void
  956. mg_global_lock(void)
  957. {
  958. (void)pthread_mutex_lock(&global_lock_mutex);
  959. }
  960. FUNCTION_MAY_BE_UNUSED
  961. static void
  962. mg_global_unlock(void)
  963. {
  964. (void)pthread_mutex_unlock(&global_lock_mutex);
  965. }
  966. FUNCTION_MAY_BE_UNUSED
  967. static int
  968. mg_atomic_inc(volatile int *addr)
  969. {
  970. int ret;
  971. #if defined(_WIN32) && !defined(NO_ATOMICS)
  972. /* Depending on the SDK, this function uses either
  973. * (volatile unsigned int *) or (volatile LONG *),
  974. * so whatever you use, the other SDK is likely to raise a warning. */
  975. ret = InterlockedIncrement((volatile long *)addr);
  976. #elif defined(__GNUC__) \
  977. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  978. && !defined(NO_ATOMICS)
  979. ret = __sync_add_and_fetch(addr, 1);
  980. #else
  981. mg_global_lock();
  982. ret = (++(*addr));
  983. mg_global_unlock();
  984. #endif
  985. return ret;
  986. }
  987. FUNCTION_MAY_BE_UNUSED
  988. static int
  989. mg_atomic_dec(volatile int *addr)
  990. {
  991. int ret;
  992. #if defined(_WIN32) && !defined(NO_ATOMICS)
  993. /* Depending on the SDK, this function uses either
  994. * (volatile unsigned int *) or (volatile LONG *),
  995. * so whatever you use, the other SDK is likely to raise a warning. */
  996. ret = InterlockedDecrement((volatile long *)addr);
  997. #elif defined(__GNUC__) \
  998. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  999. && !defined(NO_ATOMICS)
  1000. ret = __sync_sub_and_fetch(addr, 1);
  1001. #else
  1002. mg_global_lock();
  1003. ret = (--(*addr));
  1004. mg_global_unlock();
  1005. #endif
  1006. return ret;
  1007. }
  1008. #if defined(USE_SERVER_STATS)
  1009. static int64_t
  1010. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1011. {
  1012. int64_t ret;
  1013. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1014. ret = InterlockedAdd64(addr, value);
  1015. #elif defined(__GNUC__) \
  1016. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1017. && !defined(NO_ATOMICS)
  1018. ret = __sync_add_and_fetch(addr, value);
  1019. #else
  1020. mg_global_lock();
  1021. *addr += value;
  1022. ret = (*addr);
  1023. mg_global_unlock();
  1024. #endif
  1025. return ret;
  1026. }
  1027. #endif
  1028. #if defined(GCC_DIAGNOSTIC)
  1029. /* Show no warning in case system functions are not used. */
  1030. #pragma GCC diagnostic pop
  1031. #endif /* defined(GCC_DIAGNOSTIC) */
  1032. #if defined(__clang__)
  1033. /* Show no warning in case system functions are not used. */
  1034. #pragma clang diagnostic pop
  1035. #endif
  1036. #if defined(USE_SERVER_STATS)
  1037. struct mg_memory_stat {
  1038. volatile int64_t totalMemUsed;
  1039. volatile int64_t maxMemUsed;
  1040. volatile int blockCount;
  1041. };
  1042. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1043. static void *
  1044. mg_malloc_ex(size_t size,
  1045. struct mg_context *ctx,
  1046. const char *file,
  1047. unsigned line)
  1048. {
  1049. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1050. void *memory = 0;
  1051. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1052. #if defined(MEMORY_DEBUGGING)
  1053. char mallocStr[256];
  1054. #else
  1055. (void)file;
  1056. (void)line;
  1057. #endif
  1058. if (data) {
  1059. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1060. if (mmem > mstat->maxMemUsed) {
  1061. /* could use atomic compare exchange, but this
  1062. * seems overkill for statistics data */
  1063. mstat->maxMemUsed = mmem;
  1064. }
  1065. mg_atomic_inc(&mstat->blockCount);
  1066. ((uintptr_t *)data)[0] = size;
  1067. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1068. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1069. }
  1070. #if defined(MEMORY_DEBUGGING)
  1071. sprintf(mallocStr,
  1072. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1073. memory,
  1074. (unsigned long)size,
  1075. (unsigned long)mstat->totalMemUsed,
  1076. (unsigned long)mstat->blockCount,
  1077. file,
  1078. line);
  1079. #if defined(_WIN32)
  1080. OutputDebugStringA(mallocStr);
  1081. #else
  1082. DEBUG_TRACE("%s", mallocStr);
  1083. #endif
  1084. #endif
  1085. return memory;
  1086. }
  1087. static void *
  1088. mg_calloc_ex(size_t count,
  1089. size_t size,
  1090. struct mg_context *ctx,
  1091. const char *file,
  1092. unsigned line)
  1093. {
  1094. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1095. if (data) {
  1096. memset(data, 0, size * count);
  1097. }
  1098. return data;
  1099. }
  1100. static void
  1101. mg_free_ex(void *memory, const char *file, unsigned line)
  1102. {
  1103. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1104. #if defined(MEMORY_DEBUGGING)
  1105. char mallocStr[256];
  1106. #else
  1107. (void)file;
  1108. (void)line;
  1109. #endif
  1110. if (memory) {
  1111. uintptr_t size = ((uintptr_t *)data)[0];
  1112. struct mg_memory_stat *mstat =
  1113. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1114. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1115. mg_atomic_dec(&mstat->blockCount);
  1116. #if defined(MEMORY_DEBUGGING)
  1117. sprintf(mallocStr,
  1118. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1119. memory,
  1120. (unsigned long)size,
  1121. (unsigned long)mstat->totalMemUsed,
  1122. (unsigned long)mstat->blockCount,
  1123. file,
  1124. line);
  1125. #if defined(_WIN32)
  1126. OutputDebugStringA(mallocStr);
  1127. #else
  1128. DEBUG_TRACE("%s", mallocStr);
  1129. #endif
  1130. #endif
  1131. free(data);
  1132. }
  1133. }
  1134. static void *
  1135. mg_realloc_ex(void *memory,
  1136. size_t newsize,
  1137. struct mg_context *ctx,
  1138. const char *file,
  1139. unsigned line)
  1140. {
  1141. void *data;
  1142. void *_realloc;
  1143. uintptr_t oldsize;
  1144. #if defined(MEMORY_DEBUGGING)
  1145. char mallocStr[256];
  1146. #else
  1147. (void)file;
  1148. (void)line;
  1149. #endif
  1150. if (newsize) {
  1151. if (memory) {
  1152. /* Reallocate existing block */
  1153. struct mg_memory_stat *mstat;
  1154. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1155. oldsize = ((uintptr_t *)data)[0];
  1156. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1157. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1158. if (_realloc) {
  1159. data = _realloc;
  1160. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1161. #if defined(MEMORY_DEBUGGING)
  1162. sprintf(mallocStr,
  1163. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1164. memory,
  1165. (unsigned long)oldsize,
  1166. (unsigned long)mstat->totalMemUsed,
  1167. (unsigned long)mstat->blockCount,
  1168. file,
  1169. line);
  1170. #if defined(_WIN32)
  1171. OutputDebugStringA(mallocStr);
  1172. #else
  1173. DEBUG_TRACE("%s", mallocStr);
  1174. #endif
  1175. #endif
  1176. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1177. #if defined(MEMORY_DEBUGGING)
  1178. sprintf(mallocStr,
  1179. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1180. memory,
  1181. (unsigned long)newsize,
  1182. (unsigned long)mstat->totalMemUsed,
  1183. (unsigned long)mstat->blockCount,
  1184. file,
  1185. line);
  1186. #if defined(_WIN32)
  1187. OutputDebugStringA(mallocStr);
  1188. #else
  1189. DEBUG_TRACE("%s", mallocStr);
  1190. #endif
  1191. #endif
  1192. *(uintptr_t *)data = newsize;
  1193. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1194. } else {
  1195. #if defined(MEMORY_DEBUGGING)
  1196. #if defined(_WIN32)
  1197. OutputDebugStringA("MEM: realloc failed\n");
  1198. #else
  1199. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1200. #endif
  1201. #endif
  1202. return _realloc;
  1203. }
  1204. } else {
  1205. /* Allocate new block */
  1206. data = mg_malloc_ex(newsize, ctx, file, line);
  1207. }
  1208. } else {
  1209. /* Free existing block */
  1210. data = 0;
  1211. mg_free_ex(memory, file, line);
  1212. }
  1213. return data;
  1214. }
  1215. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1216. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1217. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1218. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1219. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1220. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1221. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1222. #else /* USE_SERVER_STATS */
  1223. static __inline void *
  1224. mg_malloc(size_t a)
  1225. {
  1226. return malloc(a);
  1227. }
  1228. static __inline void *
  1229. mg_calloc(size_t a, size_t b)
  1230. {
  1231. return calloc(a, b);
  1232. }
  1233. static __inline void *
  1234. mg_realloc(void *a, size_t b)
  1235. {
  1236. return realloc(a, b);
  1237. }
  1238. static __inline void
  1239. mg_free(void *a)
  1240. {
  1241. free(a);
  1242. }
  1243. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1244. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1245. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1246. #define mg_free_ctx(a, c) mg_free(a)
  1247. #endif /* USE_SERVER_STATS */
  1248. static void mg_vsnprintf(const struct mg_connection *conn,
  1249. int *truncated,
  1250. char *buf,
  1251. size_t buflen,
  1252. const char *fmt,
  1253. va_list ap);
  1254. static void mg_snprintf(const struct mg_connection *conn,
  1255. int *truncated,
  1256. char *buf,
  1257. size_t buflen,
  1258. PRINTF_FORMAT_STRING(const char *fmt),
  1259. ...) PRINTF_ARGS(5, 6);
  1260. /* This following lines are just meant as a reminder to use the mg-functions
  1261. * for memory management */
  1262. #if defined(malloc)
  1263. #undef malloc
  1264. #endif
  1265. #if defined(calloc)
  1266. #undef calloc
  1267. #endif
  1268. #if defined(realloc)
  1269. #undef realloc
  1270. #endif
  1271. #if defined(free)
  1272. #undef free
  1273. #endif
  1274. #if defined(snprintf)
  1275. #undef snprintf
  1276. #endif
  1277. #if defined(vsnprintf)
  1278. #undef vsnprintf
  1279. #endif
  1280. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1281. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1282. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1283. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1284. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1285. #if defined(_WIN32)
  1286. /* vsnprintf must not be used in any system,
  1287. * but this define only works well for Windows. */
  1288. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1289. #endif
  1290. /* mg_init_library counter */
  1291. static int mg_init_library_called = 0;
  1292. #if !defined(NO_SSL)
  1293. static int mg_ssl_initialized = 0;
  1294. #endif
  1295. static pthread_key_t sTlsKey; /* Thread local storage index */
  1296. static int thread_idx_max = 0;
  1297. #if defined(MG_LEGACY_INTERFACE)
  1298. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1299. #endif
  1300. struct mg_workerTLS {
  1301. int is_master;
  1302. unsigned long thread_idx;
  1303. void *user_ptr;
  1304. #if defined(_WIN32)
  1305. HANDLE pthread_cond_helper_mutex;
  1306. struct mg_workerTLS *next_waiting_thread;
  1307. #endif
  1308. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1309. char txtbuf[4];
  1310. #endif
  1311. };
  1312. #if defined(GCC_DIAGNOSTIC)
  1313. /* Show no warning in case system functions are not used. */
  1314. #pragma GCC diagnostic push
  1315. #pragma GCC diagnostic ignored "-Wunused-function"
  1316. #endif /* defined(GCC_DIAGNOSTIC) */
  1317. #if defined(__clang__)
  1318. /* Show no warning in case system functions are not used. */
  1319. #pragma clang diagnostic push
  1320. #pragma clang diagnostic ignored "-Wunused-function"
  1321. #endif
  1322. /* Get a unique thread ID as unsigned long, independent from the data type
  1323. * of thread IDs defined by the operating system API.
  1324. * If two calls to mg_current_thread_id return the same value, they calls
  1325. * are done from the same thread. If they return different values, they are
  1326. * done from different threads. (Provided this function is used in the same
  1327. * process context and threads are not repeatedly created and deleted, but
  1328. * CivetWeb does not do that).
  1329. * This function must match the signature required for SSL id callbacks:
  1330. * CRYPTO_set_id_callback
  1331. */
  1332. FUNCTION_MAY_BE_UNUSED
  1333. static unsigned long
  1334. mg_current_thread_id(void)
  1335. {
  1336. #if defined(_WIN32)
  1337. return GetCurrentThreadId();
  1338. #else
  1339. #if defined(__clang__)
  1340. #pragma clang diagnostic push
  1341. #pragma clang diagnostic ignored "-Wunreachable-code"
  1342. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1343. * or not, so one of the two conditions will be unreachable by construction.
  1344. * Unfortunately the C standard does not define a way to check this at
  1345. * compile time, since the #if preprocessor conditions can not use the sizeof
  1346. * operator as an argument. */
  1347. #endif
  1348. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1349. /* This is the problematic case for CRYPTO_set_id_callback:
  1350. * The OS pthread_t can not be cast to unsigned long. */
  1351. struct mg_workerTLS *tls =
  1352. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1353. if (tls == NULL) {
  1354. /* SSL called from an unknown thread: Create some thread index.
  1355. */
  1356. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1357. tls->is_master = -2; /* -2 means "3rd party thread" */
  1358. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1359. pthread_setspecific(sTlsKey, tls);
  1360. }
  1361. return tls->thread_idx;
  1362. } else {
  1363. /* pthread_t may be any data type, so a simple cast to unsigned long
  1364. * can rise a warning/error, depending on the platform.
  1365. * Here memcpy is used as an anything-to-anything cast. */
  1366. unsigned long ret = 0;
  1367. pthread_t t = pthread_self();
  1368. memcpy(&ret, &t, sizeof(pthread_t));
  1369. return ret;
  1370. }
  1371. #if defined(__clang__)
  1372. #pragma clang diagnostic pop
  1373. #endif
  1374. #endif
  1375. }
  1376. FUNCTION_MAY_BE_UNUSED
  1377. static uint64_t
  1378. mg_get_current_time_ns(void)
  1379. {
  1380. struct timespec tsnow;
  1381. clock_gettime(CLOCK_REALTIME, &tsnow);
  1382. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1383. }
  1384. #if defined(GCC_DIAGNOSTIC)
  1385. /* Show no warning in case system functions are not used. */
  1386. #pragma GCC diagnostic pop
  1387. #endif /* defined(GCC_DIAGNOSTIC) */
  1388. #if defined(__clang__)
  1389. /* Show no warning in case system functions are not used. */
  1390. #pragma clang diagnostic pop
  1391. #endif
  1392. #if defined(NEED_DEBUG_TRACE_FUNC)
  1393. static void
  1394. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1395. {
  1396. va_list args;
  1397. uint64_t nsnow;
  1398. static uint64_t nslast;
  1399. struct timespec tsnow;
  1400. /* Get some operating system independent thread id */
  1401. unsigned long thread_id = mg_current_thread_id();
  1402. clock_gettime(CLOCK_REALTIME, &tsnow);
  1403. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1404. + ((uint64_t)tsnow.tv_nsec);
  1405. if (!nslast) {
  1406. nslast = nsnow;
  1407. }
  1408. flockfile(stdout);
  1409. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1410. (unsigned long)tsnow.tv_sec,
  1411. (unsigned long)tsnow.tv_nsec,
  1412. nsnow - nslast,
  1413. thread_id,
  1414. func,
  1415. line);
  1416. va_start(args, fmt);
  1417. vprintf(fmt, args);
  1418. va_end(args);
  1419. putchar('\n');
  1420. fflush(stdout);
  1421. funlockfile(stdout);
  1422. nslast = nsnow;
  1423. }
  1424. #endif /* NEED_DEBUG_TRACE_FUNC */
  1425. #define MD5_STATIC static
  1426. #include "md5.inl"
  1427. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1428. #if defined(NO_SOCKLEN_T)
  1429. typedef int socklen_t;
  1430. #endif /* NO_SOCKLEN_T */
  1431. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1432. #if !defined(MSG_NOSIGNAL)
  1433. #define MSG_NOSIGNAL (0)
  1434. #endif
  1435. #if defined(NO_SSL)
  1436. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1437. typedef struct SSL_CTX SSL_CTX;
  1438. #else
  1439. #if defined(NO_SSL_DL)
  1440. #include <openssl/bn.h>
  1441. #include <openssl/conf.h>
  1442. #include <openssl/crypto.h>
  1443. #include <openssl/dh.h>
  1444. #include <openssl/engine.h>
  1445. #include <openssl/err.h>
  1446. #include <openssl/opensslv.h>
  1447. #include <openssl/pem.h>
  1448. #include <openssl/ssl.h>
  1449. #include <openssl/tls1.h>
  1450. #include <openssl/x509.h>
  1451. #if defined(WOLFSSL_VERSION)
  1452. /* Additional defines for WolfSSL, see
  1453. * https://github.com/civetweb/civetweb/issues/583 */
  1454. #include "wolfssl_extras.inl"
  1455. #endif
  1456. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1457. /* If OpenSSL headers are included, automatically select the API version */
  1458. #if !defined(OPENSSL_API_1_1)
  1459. #define OPENSSL_API_1_1
  1460. #endif
  1461. #define OPENSSL_REMOVE_THREAD_STATE()
  1462. #else
  1463. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1464. #endif
  1465. #else
  1466. /* SSL loaded dynamically from DLL.
  1467. * I put the prototypes here to be independent from OpenSSL source
  1468. * installation. */
  1469. typedef struct ssl_st SSL;
  1470. typedef struct ssl_method_st SSL_METHOD;
  1471. typedef struct ssl_ctx_st SSL_CTX;
  1472. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1473. typedef struct x509_name X509_NAME;
  1474. typedef struct asn1_integer ASN1_INTEGER;
  1475. typedef struct bignum BIGNUM;
  1476. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1477. typedef struct evp_md EVP_MD;
  1478. typedef struct x509 X509;
  1479. #define SSL_CTRL_OPTIONS (32)
  1480. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1481. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1482. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1483. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1484. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1485. #define SSL_VERIFY_NONE (0)
  1486. #define SSL_VERIFY_PEER (1)
  1487. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1488. #define SSL_VERIFY_CLIENT_ONCE (4)
  1489. #define SSL_OP_ALL (0x80000BFFul)
  1490. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1491. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1492. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1493. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1494. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1495. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1496. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1497. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1498. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1499. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1500. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1501. #define SSL_CB_HANDSHAKE_START (0x10)
  1502. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1503. #define SSL_ERROR_NONE (0)
  1504. #define SSL_ERROR_SSL (1)
  1505. #define SSL_ERROR_WANT_READ (2)
  1506. #define SSL_ERROR_WANT_WRITE (3)
  1507. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1508. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1509. #define SSL_ERROR_ZERO_RETURN (6)
  1510. #define SSL_ERROR_WANT_CONNECT (7)
  1511. #define SSL_ERROR_WANT_ACCEPT (8)
  1512. #define TLSEXT_TYPE_server_name (0)
  1513. #define TLSEXT_NAMETYPE_host_name (0)
  1514. #define SSL_TLSEXT_ERR_OK (0)
  1515. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1516. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1517. #define SSL_TLSEXT_ERR_NOACK (3)
  1518. struct ssl_func {
  1519. const char *name; /* SSL function name */
  1520. void (*ptr)(void); /* Function pointer */
  1521. };
  1522. #if defined(OPENSSL_API_1_1)
  1523. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1524. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1525. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1526. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1527. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1528. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1529. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1530. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1531. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1532. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1533. #define OPENSSL_init_ssl \
  1534. (*(int (*)(uint64_t opts, \
  1535. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1536. .ptr)
  1537. #define SSL_CTX_use_PrivateKey_file \
  1538. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1539. #define SSL_CTX_use_certificate_file \
  1540. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1541. #define SSL_CTX_set_default_passwd_cb \
  1542. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1543. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1544. #define SSL_CTX_use_certificate_chain_file \
  1545. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1546. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1547. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1548. #define SSL_CTX_set_verify \
  1549. (*(void (*)(SSL_CTX *, \
  1550. int, \
  1551. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1552. .ptr)
  1553. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1554. #define SSL_CTX_load_verify_locations \
  1555. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1556. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1557. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1558. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1559. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1560. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1561. #define SSL_CIPHER_get_name \
  1562. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1563. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1564. #define SSL_CTX_set_session_id_context \
  1565. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1566. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1567. #define SSL_CTX_set_cipher_list \
  1568. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1569. #define SSL_CTX_set_options \
  1570. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1571. #define SSL_CTX_set_info_callback \
  1572. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1573. ssl_sw[32] \
  1574. .ptr)
  1575. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1576. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1577. #define SSL_CTX_callback_ctrl \
  1578. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1579. #define SSL_get_servername \
  1580. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1581. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1582. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1583. #define SSL_CTX_clear_options(ctx, op) \
  1584. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1585. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1586. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1587. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1588. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1589. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1590. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1591. SSL_CTX_callback_ctrl(ctx, \
  1592. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1593. (void (*)(void))cb)
  1594. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1595. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1596. #define SSL_set_tlsext_host_name(ctx, arg) \
  1597. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1598. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1599. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1600. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1601. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1602. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1603. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1604. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1605. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1606. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1607. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1608. #define X509_NAME_oneline \
  1609. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1610. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1611. #define EVP_get_digestbyname \
  1612. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1613. #define EVP_Digest \
  1614. (*(int (*)( \
  1615. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1616. crypto_sw[9] \
  1617. .ptr)
  1618. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1619. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1620. #define ASN1_INTEGER_to_BN \
  1621. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1622. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1623. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1624. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1625. #define OPENSSL_free(a) CRYPTO_free(a)
  1626. #define OPENSSL_REMOVE_THREAD_STATE()
  1627. /* init_ssl_ctx() function updates this array.
  1628. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1629. * of respective functions. The macros above (like SSL_connect()) are really
  1630. * just calling these functions indirectly via the pointer. */
  1631. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1632. {"SSL_accept", NULL},
  1633. {"SSL_connect", NULL},
  1634. {"SSL_read", NULL},
  1635. {"SSL_write", NULL},
  1636. {"SSL_get_error", NULL},
  1637. {"SSL_set_fd", NULL},
  1638. {"SSL_new", NULL},
  1639. {"SSL_CTX_new", NULL},
  1640. {"TLS_server_method", NULL},
  1641. {"OPENSSL_init_ssl", NULL},
  1642. {"SSL_CTX_use_PrivateKey_file", NULL},
  1643. {"SSL_CTX_use_certificate_file", NULL},
  1644. {"SSL_CTX_set_default_passwd_cb", NULL},
  1645. {"SSL_CTX_free", NULL},
  1646. {"SSL_CTX_use_certificate_chain_file", NULL},
  1647. {"TLS_client_method", NULL},
  1648. {"SSL_pending", NULL},
  1649. {"SSL_CTX_set_verify", NULL},
  1650. {"SSL_shutdown", NULL},
  1651. {"SSL_CTX_load_verify_locations", NULL},
  1652. {"SSL_CTX_set_default_verify_paths", NULL},
  1653. {"SSL_CTX_set_verify_depth", NULL},
  1654. {"SSL_get_peer_certificate", NULL},
  1655. {"SSL_get_version", NULL},
  1656. {"SSL_get_current_cipher", NULL},
  1657. {"SSL_CIPHER_get_name", NULL},
  1658. {"SSL_CTX_check_private_key", NULL},
  1659. {"SSL_CTX_set_session_id_context", NULL},
  1660. {"SSL_CTX_ctrl", NULL},
  1661. {"SSL_CTX_set_cipher_list", NULL},
  1662. {"SSL_CTX_set_options", NULL},
  1663. {"SSL_CTX_set_info_callback", NULL},
  1664. {"SSL_get_ex_data", NULL},
  1665. {"SSL_set_ex_data", NULL},
  1666. {"SSL_CTX_callback_ctrl", NULL},
  1667. {"SSL_get_servername", NULL},
  1668. {"SSL_set_SSL_CTX", NULL},
  1669. {"SSL_ctrl", NULL},
  1670. {NULL, NULL}};
  1671. /* Similar array as ssl_sw. These functions could be located in different
  1672. * lib. */
  1673. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1674. {"ERR_error_string", NULL},
  1675. {"CONF_modules_unload", NULL},
  1676. {"X509_free", NULL},
  1677. {"X509_get_subject_name", NULL},
  1678. {"X509_get_issuer_name", NULL},
  1679. {"X509_NAME_oneline", NULL},
  1680. {"X509_get_serialNumber", NULL},
  1681. {"EVP_get_digestbyname", NULL},
  1682. {"EVP_Digest", NULL},
  1683. {"i2d_X509", NULL},
  1684. {"BN_bn2hex", NULL},
  1685. {"ASN1_INTEGER_to_BN", NULL},
  1686. {"BN_free", NULL},
  1687. {"CRYPTO_free", NULL},
  1688. {"ERR_clear_error", NULL},
  1689. {NULL, NULL}};
  1690. #else
  1691. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1692. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1693. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1694. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1695. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1696. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1697. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1698. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1699. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1700. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1701. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1702. #define SSL_CTX_use_PrivateKey_file \
  1703. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1704. #define SSL_CTX_use_certificate_file \
  1705. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1706. #define SSL_CTX_set_default_passwd_cb \
  1707. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1708. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1709. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1710. #define SSL_CTX_use_certificate_chain_file \
  1711. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1712. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1713. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1714. #define SSL_CTX_set_verify \
  1715. (*(void (*)(SSL_CTX *, \
  1716. int, \
  1717. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1718. .ptr)
  1719. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1720. #define SSL_CTX_load_verify_locations \
  1721. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1722. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1723. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1724. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1725. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1726. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1727. #define SSL_CIPHER_get_name \
  1728. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1729. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1730. #define SSL_CTX_set_session_id_context \
  1731. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1732. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1733. #define SSL_CTX_set_cipher_list \
  1734. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1735. #define SSL_CTX_set_info_callback \
  1736. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1737. .ptr)
  1738. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1739. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1740. #define SSL_CTX_callback_ctrl \
  1741. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1742. #define SSL_get_servername \
  1743. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1744. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1745. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1746. #define SSL_CTX_set_options(ctx, op) \
  1747. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1748. #define SSL_CTX_clear_options(ctx, op) \
  1749. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1750. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1751. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1752. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1753. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1754. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1755. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1756. SSL_CTX_callback_ctrl(ctx, \
  1757. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1758. (void (*)(void))cb)
  1759. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1760. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1761. #define SSL_set_tlsext_host_name(ctx, arg) \
  1762. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1763. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1764. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1765. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1766. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1767. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1768. #define CRYPTO_set_locking_callback \
  1769. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1770. #define CRYPTO_set_id_callback \
  1771. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1772. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1773. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1774. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1775. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1776. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1777. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1778. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1779. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1780. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1781. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1782. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1783. #define X509_NAME_oneline \
  1784. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1785. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1786. #define i2c_ASN1_INTEGER \
  1787. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1788. #define EVP_get_digestbyname \
  1789. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1790. #define EVP_Digest \
  1791. (*(int (*)( \
  1792. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1793. crypto_sw[18] \
  1794. .ptr)
  1795. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1796. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1797. #define ASN1_INTEGER_to_BN \
  1798. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1799. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1800. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1801. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1802. #define OPENSSL_free(a) CRYPTO_free(a)
  1803. /* use here ERR_remove_state,
  1804. * while on some platforms function is not included into library due to
  1805. * deprication */
  1806. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1807. /* init_ssl_ctx() function updates this array.
  1808. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1809. * of respective functions. The macros above (like SSL_connect()) are really
  1810. * just calling these functions indirectly via the pointer. */
  1811. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1812. {"SSL_accept", NULL},
  1813. {"SSL_connect", NULL},
  1814. {"SSL_read", NULL},
  1815. {"SSL_write", NULL},
  1816. {"SSL_get_error", NULL},
  1817. {"SSL_set_fd", NULL},
  1818. {"SSL_new", NULL},
  1819. {"SSL_CTX_new", NULL},
  1820. {"SSLv23_server_method", NULL},
  1821. {"SSL_library_init", NULL},
  1822. {"SSL_CTX_use_PrivateKey_file", NULL},
  1823. {"SSL_CTX_use_certificate_file", NULL},
  1824. {"SSL_CTX_set_default_passwd_cb", NULL},
  1825. {"SSL_CTX_free", NULL},
  1826. {"SSL_load_error_strings", NULL},
  1827. {"SSL_CTX_use_certificate_chain_file", NULL},
  1828. {"SSLv23_client_method", NULL},
  1829. {"SSL_pending", NULL},
  1830. {"SSL_CTX_set_verify", NULL},
  1831. {"SSL_shutdown", NULL},
  1832. {"SSL_CTX_load_verify_locations", NULL},
  1833. {"SSL_CTX_set_default_verify_paths", NULL},
  1834. {"SSL_CTX_set_verify_depth", NULL},
  1835. {"SSL_get_peer_certificate", NULL},
  1836. {"SSL_get_version", NULL},
  1837. {"SSL_get_current_cipher", NULL},
  1838. {"SSL_CIPHER_get_name", NULL},
  1839. {"SSL_CTX_check_private_key", NULL},
  1840. {"SSL_CTX_set_session_id_context", NULL},
  1841. {"SSL_CTX_ctrl", NULL},
  1842. {"SSL_CTX_set_cipher_list", NULL},
  1843. {"SSL_CTX_set_info_callback", NULL},
  1844. {"SSL_get_ex_data", NULL},
  1845. {"SSL_set_ex_data", NULL},
  1846. {"SSL_CTX_callback_ctrl", NULL},
  1847. {"SSL_get_servername", NULL},
  1848. {"SSL_set_SSL_CTX", NULL},
  1849. {"SSL_ctrl", NULL},
  1850. {NULL, NULL}};
  1851. /* Similar array as ssl_sw. These functions could be located in different
  1852. * lib. */
  1853. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1854. {"CRYPTO_set_locking_callback", NULL},
  1855. {"CRYPTO_set_id_callback", NULL},
  1856. {"ERR_get_error", NULL},
  1857. {"ERR_error_string", NULL},
  1858. {"ERR_remove_state", NULL},
  1859. {"ERR_free_strings", NULL},
  1860. {"ENGINE_cleanup", NULL},
  1861. {"CONF_modules_unload", NULL},
  1862. {"CRYPTO_cleanup_all_ex_data", NULL},
  1863. {"EVP_cleanup", NULL},
  1864. {"X509_free", NULL},
  1865. {"X509_get_subject_name", NULL},
  1866. {"X509_get_issuer_name", NULL},
  1867. {"X509_NAME_oneline", NULL},
  1868. {"X509_get_serialNumber", NULL},
  1869. {"i2c_ASN1_INTEGER", NULL},
  1870. {"EVP_get_digestbyname", NULL},
  1871. {"EVP_Digest", NULL},
  1872. {"i2d_X509", NULL},
  1873. {"BN_bn2hex", NULL},
  1874. {"ASN1_INTEGER_to_BN", NULL},
  1875. {"BN_free", NULL},
  1876. {"CRYPTO_free", NULL},
  1877. {"ERR_clear_error", NULL},
  1878. {NULL, NULL}};
  1879. #endif /* OPENSSL_API_1_1 */
  1880. #endif /* NO_SSL_DL */
  1881. #endif /* NO_SSL */
  1882. #if !defined(NO_CACHING)
  1883. static const char month_names[][4] = {"Jan",
  1884. "Feb",
  1885. "Mar",
  1886. "Apr",
  1887. "May",
  1888. "Jun",
  1889. "Jul",
  1890. "Aug",
  1891. "Sep",
  1892. "Oct",
  1893. "Nov",
  1894. "Dec"};
  1895. #endif /* !NO_CACHING */
  1896. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1897. * the
  1898. * union u. */
  1899. union usa {
  1900. struct sockaddr sa;
  1901. struct sockaddr_in sin;
  1902. #if defined(USE_IPV6)
  1903. struct sockaddr_in6 sin6;
  1904. #endif
  1905. };
  1906. /* Describes a string (chunk of memory). */
  1907. struct vec {
  1908. const char *ptr;
  1909. size_t len;
  1910. };
  1911. struct mg_file_stat {
  1912. /* File properties filled by mg_stat: */
  1913. uint64_t size;
  1914. time_t last_modified;
  1915. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1916. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1917. * case we need a "Content-Eencoding: gzip" header */
  1918. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1919. };
  1920. struct mg_file_in_memory {
  1921. char *p;
  1922. uint32_t pos;
  1923. char mode;
  1924. };
  1925. struct mg_file_access {
  1926. /* File properties filled by mg_fopen: */
  1927. FILE *fp;
  1928. #if defined(MG_USE_OPEN_FILE)
  1929. /* TODO (low): Remove obsolete "file in memory" implementation.
  1930. * In an "early 2017" discussion at Google groups
  1931. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1932. * we decided to get rid of this feature (after some fade-out
  1933. * phase). */
  1934. const char *membuf;
  1935. #endif
  1936. };
  1937. struct mg_file {
  1938. struct mg_file_stat stat;
  1939. struct mg_file_access access;
  1940. };
  1941. #if defined(MG_USE_OPEN_FILE)
  1942. #define STRUCT_FILE_INITIALIZER \
  1943. { \
  1944. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1945. { \
  1946. (FILE *)NULL, (const char *)NULL \
  1947. } \
  1948. }
  1949. #else
  1950. #define STRUCT_FILE_INITIALIZER \
  1951. { \
  1952. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1953. { \
  1954. (FILE *)NULL \
  1955. } \
  1956. }
  1957. #endif
  1958. /* Describes listening socket, or socket which was accept()-ed by the master
  1959. * thread and queued for future handling by the worker thread. */
  1960. struct socket {
  1961. SOCKET sock; /* Listening socket */
  1962. union usa lsa; /* Local socket address */
  1963. union usa rsa; /* Remote socket address */
  1964. unsigned char is_ssl; /* Is port SSL-ed */
  1965. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1966. * port */
  1967. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1968. };
  1969. /* Enum const for all options must be in sync with
  1970. * static struct mg_option config_options[]
  1971. * This is tested in the unit test (test/private.c)
  1972. * "Private Config Options"
  1973. */
  1974. enum {
  1975. /* Once for each server */
  1976. LISTENING_PORTS,
  1977. NUM_THREADS,
  1978. RUN_AS_USER,
  1979. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1980. * socket option typedef TCP_NODELAY. */
  1981. MAX_REQUEST_SIZE,
  1982. LINGER_TIMEOUT,
  1983. #if defined(__linux__)
  1984. ALLOW_SENDFILE_CALL,
  1985. #endif
  1986. #if defined(_WIN32)
  1987. CASE_SENSITIVE_FILES,
  1988. #endif
  1989. THROTTLE,
  1990. ACCESS_LOG_FILE,
  1991. ERROR_LOG_FILE,
  1992. ENABLE_KEEP_ALIVE,
  1993. REQUEST_TIMEOUT,
  1994. KEEP_ALIVE_TIMEOUT,
  1995. #if defined(USE_WEBSOCKET)
  1996. WEBSOCKET_TIMEOUT,
  1997. ENABLE_WEBSOCKET_PING_PONG,
  1998. #endif
  1999. DECODE_URL,
  2000. #if defined(USE_LUA)
  2001. LUA_BACKGROUND_SCRIPT,
  2002. LUA_BACKGROUND_SCRIPT_PARAMS,
  2003. #endif
  2004. #if defined(USE_TIMERS)
  2005. CGI_TIMEOUT,
  2006. #endif
  2007. /* Once for each domain */
  2008. DOCUMENT_ROOT,
  2009. CGI_EXTENSIONS,
  2010. CGI_ENVIRONMENT,
  2011. PUT_DELETE_PASSWORDS_FILE,
  2012. CGI_INTERPRETER,
  2013. PROTECT_URI,
  2014. AUTHENTICATION_DOMAIN,
  2015. ENABLE_AUTH_DOMAIN_CHECK,
  2016. SSI_EXTENSIONS,
  2017. ENABLE_DIRECTORY_LISTING,
  2018. GLOBAL_PASSWORDS_FILE,
  2019. INDEX_FILES,
  2020. ACCESS_CONTROL_LIST,
  2021. EXTRA_MIME_TYPES,
  2022. SSL_CERTIFICATE,
  2023. SSL_CERTIFICATE_CHAIN,
  2024. URL_REWRITE_PATTERN,
  2025. HIDE_FILES,
  2026. SSL_DO_VERIFY_PEER,
  2027. SSL_CA_PATH,
  2028. SSL_CA_FILE,
  2029. SSL_VERIFY_DEPTH,
  2030. SSL_DEFAULT_VERIFY_PATHS,
  2031. SSL_CIPHER_LIST,
  2032. SSL_PROTOCOL_VERSION,
  2033. SSL_SHORT_TRUST,
  2034. #if defined(USE_LUA)
  2035. LUA_PRELOAD_FILE,
  2036. LUA_SCRIPT_EXTENSIONS,
  2037. LUA_SERVER_PAGE_EXTENSIONS,
  2038. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2039. LUA_DEBUG_PARAMS,
  2040. #endif
  2041. #endif
  2042. #if defined(USE_DUKTAPE)
  2043. DUKTAPE_SCRIPT_EXTENSIONS,
  2044. #endif
  2045. #if defined(USE_WEBSOCKET)
  2046. WEBSOCKET_ROOT,
  2047. #endif
  2048. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2049. LUA_WEBSOCKET_EXTENSIONS,
  2050. #endif
  2051. ACCESS_CONTROL_ALLOW_ORIGIN,
  2052. ACCESS_CONTROL_ALLOW_METHODS,
  2053. ACCESS_CONTROL_ALLOW_HEADERS,
  2054. ERROR_PAGES,
  2055. #if !defined(NO_CACHING)
  2056. STATIC_FILE_MAX_AGE,
  2057. #endif
  2058. #if !defined(NO_SSL)
  2059. STRICT_HTTPS_MAX_AGE,
  2060. #endif
  2061. ADDITIONAL_HEADER,
  2062. ALLOW_INDEX_SCRIPT_SUB_RES,
  2063. #if defined(DAEMONIZE)
  2064. ENABLE_DAEMONIZE,
  2065. #endif
  2066. NUM_OPTIONS
  2067. };
  2068. /* Config option name, config types, default value.
  2069. * Must be in the same order as the enum const above.
  2070. */
  2071. static const struct mg_option config_options[] = {
  2072. /* Once for each server */
  2073. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2074. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2075. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2076. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2077. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2078. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2079. #if defined(__linux__)
  2080. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2081. #endif
  2082. #if defined(_WIN32)
  2083. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2084. #endif
  2085. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2086. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2087. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2088. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2089. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2090. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2091. #if defined(USE_WEBSOCKET)
  2092. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2093. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2094. #endif
  2095. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2096. #if defined(USE_LUA)
  2097. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2098. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2099. #endif
  2100. #if defined(USE_TIMERS)
  2101. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2102. #endif
  2103. /* Once for each domain */
  2104. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2105. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2106. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2107. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2108. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2109. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2110. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2111. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2112. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2113. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2114. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2115. {"index_files",
  2116. MG_CONFIG_TYPE_STRING_LIST,
  2117. #if defined(USE_LUA)
  2118. "index.xhtml,index.html,index.htm,"
  2119. "index.lp,index.lsp,index.lua,index.cgi,"
  2120. "index.shtml,index.php"},
  2121. #else
  2122. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2123. #endif
  2124. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2125. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2126. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2127. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2128. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2129. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2130. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2131. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2132. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2133. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2134. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2135. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2136. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2137. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2138. #if defined(USE_LUA)
  2139. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2140. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2141. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2142. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2143. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2144. #endif
  2145. #endif
  2146. #if defined(USE_DUKTAPE)
  2147. /* The support for duktape is still in alpha version state.
  2148. * The name of this config option might change. */
  2149. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2150. #endif
  2151. #if defined(USE_WEBSOCKET)
  2152. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2153. #endif
  2154. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2155. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2156. #endif
  2157. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2158. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2159. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2160. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2161. #if !defined(NO_CACHING)
  2162. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2163. #endif
  2164. #if !defined(NO_SSL)
  2165. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2166. #endif
  2167. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2168. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2169. #if defined(DAEMONIZE)
  2170. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2171. #endif
  2172. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2173. /* Check if the config_options and the corresponding enum have compatible
  2174. * sizes. */
  2175. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2176. == (NUM_OPTIONS + 1),
  2177. "config_options and enum not sync");
  2178. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2179. struct mg_handler_info {
  2180. /* Name/Pattern of the URI. */
  2181. char *uri;
  2182. size_t uri_len;
  2183. /* handler type */
  2184. int handler_type;
  2185. /* Handler for http/https or authorization requests. */
  2186. mg_request_handler handler;
  2187. unsigned int refcount;
  2188. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2189. pthread_cond_t
  2190. refcount_cond; /* Signaled when handler refcount is decremented */
  2191. /* Handler for ws/wss (websocket) requests. */
  2192. mg_websocket_connect_handler connect_handler;
  2193. mg_websocket_ready_handler ready_handler;
  2194. mg_websocket_data_handler data_handler;
  2195. mg_websocket_close_handler close_handler;
  2196. /* accepted subprotocols for ws/wss requests. */
  2197. struct mg_websocket_subprotocols *subprotocols;
  2198. /* Handler for authorization requests */
  2199. mg_authorization_handler auth_handler;
  2200. /* User supplied argument for the handler function. */
  2201. void *cbdata;
  2202. /* next handler in a linked list */
  2203. struct mg_handler_info *next;
  2204. };
  2205. enum {
  2206. CONTEXT_INVALID,
  2207. CONTEXT_SERVER,
  2208. CONTEXT_HTTP_CLIENT,
  2209. CONTEXT_WS_CLIENT
  2210. };
  2211. struct mg_domain_context {
  2212. SSL_CTX *ssl_ctx; /* SSL context */
  2213. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2214. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2215. /* Server nonce */
  2216. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2217. unsigned long nonce_count; /* Used nonces, used for authentication */
  2218. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2219. /* linked list of shared lua websockets */
  2220. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2221. #endif
  2222. /* Linked list of domains */
  2223. struct mg_domain_context *next;
  2224. };
  2225. struct mg_context {
  2226. /* Part 1 - Physical context:
  2227. * This holds threads, ports, timeouts, ...
  2228. * set for the entire server, independent from the
  2229. * addressed hostname.
  2230. */
  2231. /* Connection related */
  2232. int context_type; /* See CONTEXT_* above */
  2233. struct socket *listening_sockets;
  2234. struct mg_pollfd *listening_socket_fds;
  2235. unsigned int num_listening_sockets;
  2236. struct mg_connection *worker_connections; /* The connection struct, pre-
  2237. * allocated for each worker */
  2238. #if defined(USE_SERVER_STATS)
  2239. int active_connections;
  2240. int max_connections;
  2241. int64_t total_connections;
  2242. int64_t total_requests;
  2243. int64_t total_data_read;
  2244. int64_t total_data_written;
  2245. #endif
  2246. /* Thread related */
  2247. volatile int stop_flag; /* Should we stop event loop */
  2248. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2249. pthread_t masterthreadid; /* The master thread ID */
  2250. unsigned int
  2251. cfg_worker_threads; /* The number of configured worker threads. */
  2252. pthread_t *worker_threadids; /* The worker thread IDs */
  2253. /* Connection to thread dispatching */
  2254. #if defined(ALTERNATIVE_QUEUE)
  2255. struct socket *client_socks;
  2256. void **client_wait_events;
  2257. #else
  2258. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2259. volatile int sq_head; /* Head of the socket queue */
  2260. volatile int sq_tail; /* Tail of the socket queue */
  2261. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2262. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2263. #endif
  2264. /* Memory related */
  2265. unsigned int max_request_size; /* The max request size */
  2266. #if defined(USE_SERVER_STATS)
  2267. struct mg_memory_stat ctx_memory;
  2268. #endif
  2269. /* Operating system related */
  2270. char *systemName; /* What operating system is running */
  2271. time_t start_time; /* Server start time, used for authentication
  2272. * and for diagnstics. */
  2273. #if defined(USE_TIMERS)
  2274. struct ttimers *timers;
  2275. #endif
  2276. /* Lua specific: Background operations and shared websockets */
  2277. #if defined(USE_LUA)
  2278. void *lua_background_state;
  2279. #endif
  2280. /* Server nonce */
  2281. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2282. /* Server callbacks */
  2283. struct mg_callbacks callbacks; /* User-defined callback function */
  2284. void *user_data; /* User-defined data */
  2285. /* Part 2 - Logical domain:
  2286. * This holds hostname, TLS certificate, document root, ...
  2287. * set for a domain hosted at the server.
  2288. * There may be multiple domains hosted at one physical server.
  2289. * The default domain "dd" is the first element of a list of
  2290. * domains.
  2291. */
  2292. struct mg_domain_context dd; /* default domain */
  2293. };
  2294. #if defined(USE_SERVER_STATS)
  2295. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2296. static struct mg_memory_stat *
  2297. get_memory_stat(struct mg_context *ctx)
  2298. {
  2299. if (ctx) {
  2300. return &(ctx->ctx_memory);
  2301. }
  2302. return &mg_common_memory;
  2303. }
  2304. #endif
  2305. enum {
  2306. CONNECTION_TYPE_INVALID,
  2307. CONNECTION_TYPE_REQUEST,
  2308. CONNECTION_TYPE_RESPONSE
  2309. };
  2310. struct mg_connection {
  2311. int connection_type; /* see CONNECTION_TYPE_* above */
  2312. struct mg_request_info request_info;
  2313. struct mg_response_info response_info;
  2314. struct mg_context *phys_ctx;
  2315. struct mg_domain_context *dom_ctx;
  2316. #if defined(USE_SERVER_STATS)
  2317. int conn_state; /* 0 = undef, numerical value may change in different
  2318. * versions. For the current definition, see
  2319. * mg_get_connection_info_impl */
  2320. #endif
  2321. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2322. SSL *ssl; /* SSL descriptor */
  2323. struct socket client; /* Connected client */
  2324. time_t conn_birth_time; /* Time (wall clock) when connection was
  2325. * established */
  2326. struct timespec req_time; /* Time (since system start) when the request
  2327. * was received */
  2328. int64_t num_bytes_sent; /* Total bytes sent to client */
  2329. int64_t content_len; /* How many bytes of content can be read
  2330. * !is_chunked: Content-Length header value
  2331. * or -1 (until connection closed,
  2332. * not allowed for a request)
  2333. * is_chunked: >= 0, appended gradually
  2334. */
  2335. int64_t consumed_content; /* How many bytes of content have been read */
  2336. int is_chunked; /* Transfer-Encoding is chunked:
  2337. * 0 = not chunked,
  2338. * 1 = chunked, not yet, or some data read,
  2339. * 2 = chunked, has error,
  2340. * 3 = chunked, all data read except trailer,
  2341. * 4 = chunked, all data read
  2342. */
  2343. char *buf; /* Buffer for received data */
  2344. char *path_info; /* PATH_INFO part of the URL */
  2345. int must_close; /* 1 if connection must be closed */
  2346. int accept_gzip; /* 1 if gzip encoding is accepted */
  2347. int in_error_handler; /* 1 if in handler for user defined error
  2348. * pages */
  2349. #if defined(USE_WEBSOCKET)
  2350. int in_websocket_handling; /* 1 if in read_websocket */
  2351. #endif
  2352. int handled_requests; /* Number of requests handled by this connection
  2353. */
  2354. int buf_size; /* Buffer size */
  2355. int request_len; /* Size of the request + headers in a buffer */
  2356. int data_len; /* Total size of data in a buffer */
  2357. int status_code; /* HTTP reply status code, e.g. 200 */
  2358. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2359. * throttle */
  2360. time_t last_throttle_time; /* Last time throttled data was sent */
  2361. int last_throttle_bytes; /* Bytes sent this second */
  2362. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2363. * atomic transmissions for websockets */
  2364. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2365. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2366. #endif
  2367. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2368. * for quick access */
  2369. };
  2370. /* Directory entry */
  2371. struct de {
  2372. struct mg_connection *conn;
  2373. char *file_name;
  2374. struct mg_file_stat file;
  2375. };
  2376. #if defined(USE_WEBSOCKET)
  2377. static int is_websocket_protocol(const struct mg_connection *conn);
  2378. #else
  2379. #define is_websocket_protocol(conn) (0)
  2380. #endif
  2381. #define mg_cry_internal(conn, fmt, ...) \
  2382. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2383. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2384. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2385. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2386. struct mg_context *ctx,
  2387. const char *func,
  2388. unsigned line,
  2389. const char *fmt,
  2390. ...) PRINTF_ARGS(5, 6);
  2391. #if !defined(NO_THREAD_NAME)
  2392. #if defined(_WIN32) && defined(_MSC_VER)
  2393. /* Set the thread name for debugging purposes in Visual Studio
  2394. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2395. */
  2396. #pragma pack(push, 8)
  2397. typedef struct tagTHREADNAME_INFO {
  2398. DWORD dwType; /* Must be 0x1000. */
  2399. LPCSTR szName; /* Pointer to name (in user addr space). */
  2400. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2401. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2402. } THREADNAME_INFO;
  2403. #pragma pack(pop)
  2404. #elif defined(__linux__)
  2405. #include <sys/prctl.h>
  2406. #include <sys/sendfile.h>
  2407. #if defined(ALTERNATIVE_QUEUE)
  2408. #include <sys/eventfd.h>
  2409. #endif /* ALTERNATIVE_QUEUE */
  2410. #if defined(ALTERNATIVE_QUEUE)
  2411. static void *
  2412. event_create(void)
  2413. {
  2414. int evhdl = eventfd(0, EFD_CLOEXEC);
  2415. int *ret;
  2416. if (evhdl == -1) {
  2417. /* Linux uses -1 on error, Windows NULL. */
  2418. /* However, Linux does not return 0 on success either. */
  2419. return 0;
  2420. }
  2421. ret = (int *)mg_malloc(sizeof(int));
  2422. if (ret) {
  2423. *ret = evhdl;
  2424. } else {
  2425. (void)close(evhdl);
  2426. }
  2427. return (void *)ret;
  2428. }
  2429. static int
  2430. event_wait(void *eventhdl)
  2431. {
  2432. uint64_t u;
  2433. int evhdl, s;
  2434. if (!eventhdl) {
  2435. /* error */
  2436. return 0;
  2437. }
  2438. evhdl = *(int *)eventhdl;
  2439. s = (int)read(evhdl, &u, sizeof(u));
  2440. if (s != sizeof(u)) {
  2441. /* error */
  2442. return 0;
  2443. }
  2444. (void)u; /* the value is not required */
  2445. return 1;
  2446. }
  2447. static int
  2448. event_signal(void *eventhdl)
  2449. {
  2450. uint64_t u = 1;
  2451. int evhdl, s;
  2452. if (!eventhdl) {
  2453. /* error */
  2454. return 0;
  2455. }
  2456. evhdl = *(int *)eventhdl;
  2457. s = (int)write(evhdl, &u, sizeof(u));
  2458. if (s != sizeof(u)) {
  2459. /* error */
  2460. return 0;
  2461. }
  2462. return 1;
  2463. }
  2464. static void
  2465. event_destroy(void *eventhdl)
  2466. {
  2467. int evhdl;
  2468. if (!eventhdl) {
  2469. /* error */
  2470. return;
  2471. }
  2472. evhdl = *(int *)eventhdl;
  2473. close(evhdl);
  2474. mg_free(eventhdl);
  2475. }
  2476. #endif
  2477. #endif
  2478. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2479. struct posix_event {
  2480. pthread_mutex_t mutex;
  2481. pthread_cond_t cond;
  2482. int signaled;
  2483. };
  2484. static void *
  2485. event_create(void)
  2486. {
  2487. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2488. if (ret == 0) {
  2489. /* out of memory */
  2490. return 0;
  2491. }
  2492. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2493. /* pthread mutex not available */
  2494. mg_free(ret);
  2495. return 0;
  2496. }
  2497. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2498. /* pthread cond not available */
  2499. pthread_mutex_destroy(&(ret->mutex));
  2500. mg_free(ret);
  2501. return 0;
  2502. }
  2503. ret->signaled = 0;
  2504. return (void *)ret;
  2505. }
  2506. static int
  2507. event_wait(void *eventhdl)
  2508. {
  2509. struct posix_event *ev = (struct posix_event *)eventhdl;
  2510. pthread_mutex_lock(&(ev->mutex));
  2511. while (!ev->signaled) {
  2512. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2513. }
  2514. ev->signaled = 0;
  2515. pthread_mutex_unlock(&(ev->mutex));
  2516. return 1;
  2517. }
  2518. static int
  2519. event_signal(void *eventhdl)
  2520. {
  2521. struct posix_event *ev = (struct posix_event *)eventhdl;
  2522. pthread_mutex_lock(&(ev->mutex));
  2523. pthread_cond_signal(&(ev->cond));
  2524. ev->signaled = 1;
  2525. pthread_mutex_unlock(&(ev->mutex));
  2526. return 1;
  2527. }
  2528. static void
  2529. event_destroy(void *eventhdl)
  2530. {
  2531. struct posix_event *ev = (struct posix_event *)eventhdl;
  2532. pthread_cond_destroy(&(ev->cond));
  2533. pthread_mutex_destroy(&(ev->mutex));
  2534. mg_free(ev);
  2535. }
  2536. #endif
  2537. static void
  2538. mg_set_thread_name(const char *name)
  2539. {
  2540. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2541. mg_snprintf(
  2542. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2543. #if defined(_WIN32)
  2544. #if defined(_MSC_VER)
  2545. /* Windows and Visual Studio Compiler */
  2546. __try {
  2547. THREADNAME_INFO info;
  2548. info.dwType = 0x1000;
  2549. info.szName = threadName;
  2550. info.dwThreadID = ~0U;
  2551. info.dwFlags = 0;
  2552. RaiseException(0x406D1388,
  2553. 0,
  2554. sizeof(info) / sizeof(ULONG_PTR),
  2555. (ULONG_PTR *)&info);
  2556. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2557. }
  2558. #elif defined(__MINGW32__)
  2559. /* No option known to set thread name for MinGW */
  2560. #endif
  2561. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2562. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2563. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2564. #if defined(__MACH__)
  2565. /* OS X only current thread name can be changed */
  2566. (void)pthread_setname_np(threadName);
  2567. #else
  2568. (void)pthread_setname_np(pthread_self(), threadName);
  2569. #endif
  2570. #elif defined(__linux__)
  2571. /* on linux we can use the old prctl function */
  2572. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2573. #endif
  2574. }
  2575. #else /* !defined(NO_THREAD_NAME) */
  2576. void
  2577. mg_set_thread_name(const char *threadName)
  2578. {
  2579. }
  2580. #endif
  2581. #if defined(MG_LEGACY_INTERFACE)
  2582. const char **
  2583. mg_get_valid_option_names(void)
  2584. {
  2585. /* This function is deprecated. Use mg_get_valid_options instead. */
  2586. static const char
  2587. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2588. int i;
  2589. for (i = 0; config_options[i].name != NULL; i++) {
  2590. data[i * 2] = config_options[i].name;
  2591. data[i * 2 + 1] = config_options[i].default_value;
  2592. }
  2593. return data;
  2594. }
  2595. #endif
  2596. const struct mg_option *
  2597. mg_get_valid_options(void)
  2598. {
  2599. return config_options;
  2600. }
  2601. /* Do not open file (used in is_file_in_memory) */
  2602. #define MG_FOPEN_MODE_NONE (0)
  2603. /* Open file for read only access */
  2604. #define MG_FOPEN_MODE_READ (1)
  2605. /* Open file for writing, create and overwrite */
  2606. #define MG_FOPEN_MODE_WRITE (2)
  2607. /* Open file for writing, create and append */
  2608. #define MG_FOPEN_MODE_APPEND (4)
  2609. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2610. * output filep and return 1, otherwise return 0 and don't modify anything.
  2611. */
  2612. static int
  2613. open_file_in_memory(const struct mg_connection *conn,
  2614. const char *path,
  2615. struct mg_file *filep,
  2616. int mode)
  2617. {
  2618. #if defined(MG_USE_OPEN_FILE)
  2619. size_t size = 0;
  2620. const char *buf = NULL;
  2621. if (!conn) {
  2622. return 0;
  2623. }
  2624. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2625. return 0;
  2626. }
  2627. if (conn->phys_ctx->callbacks.open_file) {
  2628. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2629. if (buf != NULL) {
  2630. if (filep == NULL) {
  2631. /* This is a file in memory, but we cannot store the
  2632. * properties
  2633. * now.
  2634. * Called from "is_file_in_memory" function. */
  2635. return 1;
  2636. }
  2637. /* NOTE: override filep->size only on success. Otherwise, it
  2638. * might
  2639. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2640. filep->access.membuf = buf;
  2641. filep->access.fp = NULL;
  2642. /* Size was set by the callback */
  2643. filep->stat.size = size;
  2644. /* Assume the data may change during runtime by setting
  2645. * last_modified = now */
  2646. filep->stat.last_modified = time(NULL);
  2647. filep->stat.is_directory = 0;
  2648. filep->stat.is_gzipped = 0;
  2649. }
  2650. }
  2651. return (buf != NULL);
  2652. #else
  2653. (void)conn;
  2654. (void)path;
  2655. (void)filep;
  2656. (void)mode;
  2657. return 0;
  2658. #endif
  2659. }
  2660. static int
  2661. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2662. {
  2663. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2664. }
  2665. static int
  2666. is_file_opened(const struct mg_file_access *fileacc)
  2667. {
  2668. if (!fileacc) {
  2669. return 0;
  2670. }
  2671. #if defined(MG_USE_OPEN_FILE)
  2672. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2673. #else
  2674. return (fileacc->fp != NULL);
  2675. #endif
  2676. }
  2677. static int mg_stat(const struct mg_connection *conn,
  2678. const char *path,
  2679. struct mg_file_stat *filep);
  2680. /* mg_fopen will open a file either in memory or on the disk.
  2681. * The input parameter path is a string in UTF-8 encoding.
  2682. * The input parameter mode is MG_FOPEN_MODE_*
  2683. * On success, either fp or membuf will be set in the output
  2684. * struct file. All status members will also be set.
  2685. * The function returns 1 on success, 0 on error. */
  2686. static int
  2687. mg_fopen(const struct mg_connection *conn,
  2688. const char *path,
  2689. int mode,
  2690. struct mg_file *filep)
  2691. {
  2692. int found;
  2693. if (!filep) {
  2694. return 0;
  2695. }
  2696. filep->access.fp = NULL;
  2697. #if defined(MG_USE_OPEN_FILE)
  2698. filep->access.membuf = NULL;
  2699. #endif
  2700. if (!is_file_in_memory(conn, path)) {
  2701. /* filep is initialized in mg_stat: all fields with memset to,
  2702. * some fields like size and modification date with values */
  2703. found = mg_stat(conn, path, &(filep->stat));
  2704. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2705. /* file does not exist and will not be created */
  2706. return 0;
  2707. }
  2708. #if defined(_WIN32)
  2709. {
  2710. wchar_t wbuf[W_PATH_MAX];
  2711. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2712. switch (mode) {
  2713. case MG_FOPEN_MODE_READ:
  2714. filep->access.fp = _wfopen(wbuf, L"rb");
  2715. break;
  2716. case MG_FOPEN_MODE_WRITE:
  2717. filep->access.fp = _wfopen(wbuf, L"wb");
  2718. break;
  2719. case MG_FOPEN_MODE_APPEND:
  2720. filep->access.fp = _wfopen(wbuf, L"ab");
  2721. break;
  2722. }
  2723. }
  2724. #else
  2725. /* Linux et al already use unicode. No need to convert. */
  2726. switch (mode) {
  2727. case MG_FOPEN_MODE_READ:
  2728. filep->access.fp = fopen(path, "r");
  2729. break;
  2730. case MG_FOPEN_MODE_WRITE:
  2731. filep->access.fp = fopen(path, "w");
  2732. break;
  2733. case MG_FOPEN_MODE_APPEND:
  2734. filep->access.fp = fopen(path, "a");
  2735. break;
  2736. }
  2737. #endif
  2738. if (!found) {
  2739. /* File did not exist before fopen was called.
  2740. * Maybe it has been created now. Get stat info
  2741. * like creation time now. */
  2742. found = mg_stat(conn, path, &(filep->stat));
  2743. (void)found;
  2744. }
  2745. /* file is on disk */
  2746. return (filep->access.fp != NULL);
  2747. } else {
  2748. #if defined(MG_USE_OPEN_FILE)
  2749. /* is_file_in_memory returned true */
  2750. if (open_file_in_memory(conn, path, filep, mode)) {
  2751. /* file is in memory */
  2752. return (filep->access.membuf != NULL);
  2753. }
  2754. #endif
  2755. }
  2756. /* Open failed */
  2757. return 0;
  2758. }
  2759. /* return 0 on success, just like fclose */
  2760. static int
  2761. mg_fclose(struct mg_file_access *fileacc)
  2762. {
  2763. int ret = -1;
  2764. if (fileacc != NULL) {
  2765. if (fileacc->fp != NULL) {
  2766. ret = fclose(fileacc->fp);
  2767. #if defined(MG_USE_OPEN_FILE)
  2768. } else if (fileacc->membuf != NULL) {
  2769. ret = 0;
  2770. #endif
  2771. }
  2772. /* reset all members of fileacc */
  2773. memset(fileacc, 0, sizeof(*fileacc));
  2774. }
  2775. return ret;
  2776. }
  2777. static void
  2778. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2779. {
  2780. for (; *src != '\0' && n > 1; n--) {
  2781. *dst++ = *src++;
  2782. }
  2783. *dst = '\0';
  2784. }
  2785. static int
  2786. lowercase(const char *s)
  2787. {
  2788. return tolower((unsigned char)*s);
  2789. }
  2790. int
  2791. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2792. {
  2793. int diff = 0;
  2794. if (len > 0) {
  2795. do {
  2796. diff = lowercase(s1++) - lowercase(s2++);
  2797. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2798. }
  2799. return diff;
  2800. }
  2801. int
  2802. mg_strcasecmp(const char *s1, const char *s2)
  2803. {
  2804. int diff;
  2805. do {
  2806. diff = lowercase(s1++) - lowercase(s2++);
  2807. } while (diff == 0 && s1[-1] != '\0');
  2808. return diff;
  2809. }
  2810. static char *
  2811. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2812. {
  2813. char *p;
  2814. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2815. * defined */
  2816. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2817. mg_strlcpy(p, ptr, len + 1);
  2818. }
  2819. return p;
  2820. }
  2821. static char *
  2822. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2823. {
  2824. return mg_strndup_ctx(str, strlen(str), ctx);
  2825. }
  2826. static char *
  2827. mg_strdup(const char *str)
  2828. {
  2829. return mg_strndup_ctx(str, strlen(str), NULL);
  2830. }
  2831. static const char *
  2832. mg_strcasestr(const char *big_str, const char *small_str)
  2833. {
  2834. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2835. if (big_len >= small_len) {
  2836. for (i = 0; i <= (big_len - small_len); i++) {
  2837. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2838. return big_str + i;
  2839. }
  2840. }
  2841. }
  2842. return NULL;
  2843. }
  2844. /* Return null terminated string of given maximum length.
  2845. * Report errors if length is exceeded. */
  2846. static void
  2847. mg_vsnprintf(const struct mg_connection *conn,
  2848. int *truncated,
  2849. char *buf,
  2850. size_t buflen,
  2851. const char *fmt,
  2852. va_list ap)
  2853. {
  2854. int n, ok;
  2855. if (buflen == 0) {
  2856. if (truncated) {
  2857. *truncated = 1;
  2858. }
  2859. return;
  2860. }
  2861. #if defined(__clang__)
  2862. #pragma clang diagnostic push
  2863. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2864. /* Using fmt as a non-literal is intended here, since it is mostly called
  2865. * indirectly by mg_snprintf */
  2866. #endif
  2867. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2868. ok = (n >= 0) && ((size_t)n < buflen);
  2869. #if defined(__clang__)
  2870. #pragma clang diagnostic pop
  2871. #endif
  2872. if (ok) {
  2873. if (truncated) {
  2874. *truncated = 0;
  2875. }
  2876. } else {
  2877. if (truncated) {
  2878. *truncated = 1;
  2879. }
  2880. mg_cry_internal(conn,
  2881. "truncating vsnprintf buffer: [%.*s]",
  2882. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2883. buf);
  2884. n = (int)buflen - 1;
  2885. }
  2886. buf[n] = '\0';
  2887. }
  2888. static void
  2889. mg_snprintf(const struct mg_connection *conn,
  2890. int *truncated,
  2891. char *buf,
  2892. size_t buflen,
  2893. const char *fmt,
  2894. ...)
  2895. {
  2896. va_list ap;
  2897. va_start(ap, fmt);
  2898. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2899. va_end(ap);
  2900. }
  2901. static int
  2902. get_option_index(const char *name)
  2903. {
  2904. int i;
  2905. for (i = 0; config_options[i].name != NULL; i++) {
  2906. if (strcmp(config_options[i].name, name) == 0) {
  2907. return i;
  2908. }
  2909. }
  2910. return -1;
  2911. }
  2912. const char *
  2913. mg_get_option(const struct mg_context *ctx, const char *name)
  2914. {
  2915. int i;
  2916. if ((i = get_option_index(name)) == -1) {
  2917. return NULL;
  2918. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2919. return "";
  2920. } else {
  2921. return ctx->dd.config[i];
  2922. }
  2923. }
  2924. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2925. struct mg_context *
  2926. mg_get_context(const struct mg_connection *conn)
  2927. {
  2928. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2929. }
  2930. void *
  2931. mg_get_user_data(const struct mg_context *ctx)
  2932. {
  2933. return (ctx == NULL) ? NULL : ctx->user_data;
  2934. }
  2935. void *
  2936. mg_get_thread_pointer(const struct mg_connection *conn)
  2937. {
  2938. /* both methods should return the same pointer */
  2939. if (conn) {
  2940. /* quick access, in case conn is known */
  2941. return conn->tls_user_ptr;
  2942. } else {
  2943. /* otherwise get pointer from thread local storage (TLS) */
  2944. struct mg_workerTLS *tls =
  2945. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2946. return tls->user_ptr;
  2947. }
  2948. }
  2949. void
  2950. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2951. {
  2952. if (conn != NULL) {
  2953. conn->request_info.conn_data = data;
  2954. }
  2955. }
  2956. void *
  2957. mg_get_user_connection_data(const struct mg_connection *conn)
  2958. {
  2959. if (conn != NULL) {
  2960. return conn->request_info.conn_data;
  2961. }
  2962. return NULL;
  2963. }
  2964. #if defined(MG_LEGACY_INTERFACE)
  2965. /* Deprecated: Use mg_get_server_ports instead. */
  2966. size_t
  2967. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2968. {
  2969. size_t i;
  2970. if (!ctx) {
  2971. return 0;
  2972. }
  2973. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2974. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2975. ports[i] =
  2976. #if defined(USE_IPV6)
  2977. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2978. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2979. :
  2980. #endif
  2981. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2982. }
  2983. return i;
  2984. }
  2985. #endif
  2986. int
  2987. mg_get_server_ports(const struct mg_context *ctx,
  2988. int size,
  2989. struct mg_server_port *ports)
  2990. {
  2991. int i, cnt = 0;
  2992. if (size <= 0) {
  2993. return -1;
  2994. }
  2995. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2996. if (!ctx) {
  2997. return -1;
  2998. }
  2999. if (!ctx->listening_sockets) {
  3000. return -1;
  3001. }
  3002. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3003. ports[cnt].port =
  3004. #if defined(USE_IPV6)
  3005. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3006. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3007. :
  3008. #endif
  3009. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3010. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3011. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3012. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3013. /* IPv4 */
  3014. ports[cnt].protocol = 1;
  3015. cnt++;
  3016. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3017. /* IPv6 */
  3018. ports[cnt].protocol = 3;
  3019. cnt++;
  3020. }
  3021. }
  3022. return cnt;
  3023. }
  3024. static void
  3025. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3026. {
  3027. buf[0] = '\0';
  3028. if (!usa) {
  3029. return;
  3030. }
  3031. if (usa->sa.sa_family == AF_INET) {
  3032. getnameinfo(&usa->sa,
  3033. sizeof(usa->sin),
  3034. buf,
  3035. (unsigned)len,
  3036. NULL,
  3037. 0,
  3038. NI_NUMERICHOST);
  3039. }
  3040. #if defined(USE_IPV6)
  3041. else if (usa->sa.sa_family == AF_INET6) {
  3042. getnameinfo(&usa->sa,
  3043. sizeof(usa->sin6),
  3044. buf,
  3045. (unsigned)len,
  3046. NULL,
  3047. 0,
  3048. NI_NUMERICHOST);
  3049. }
  3050. #endif
  3051. }
  3052. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3053. * included in all responses other than 100, 101, 5xx. */
  3054. static void
  3055. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3056. {
  3057. #if !defined(REENTRANT_TIME)
  3058. struct tm *tm;
  3059. tm = ((t != NULL) ? gmtime(t) : NULL);
  3060. if (tm != NULL) {
  3061. #else
  3062. struct tm _tm;
  3063. struct tm *tm = &_tm;
  3064. if (t != NULL) {
  3065. gmtime_r(t, tm);
  3066. #endif
  3067. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3068. } else {
  3069. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3070. buf[buf_len - 1] = '\0';
  3071. }
  3072. }
  3073. /* difftime for struct timespec. Return value is in seconds. */
  3074. static double
  3075. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3076. {
  3077. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3078. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3079. }
  3080. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3081. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3082. const char *func,
  3083. unsigned line,
  3084. const char *fmt,
  3085. va_list ap);
  3086. #include "external_mg_cry_internal_impl.inl"
  3087. #else
  3088. /* Print error message to the opened error log stream. */
  3089. static void
  3090. mg_cry_internal_impl(const struct mg_connection *conn,
  3091. const char *func,
  3092. unsigned line,
  3093. const char *fmt,
  3094. va_list ap)
  3095. {
  3096. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3097. struct mg_file fi;
  3098. time_t timestamp;
  3099. /* Unused, in the RELEASE build */
  3100. (void)func;
  3101. (void)line;
  3102. #if defined(GCC_DIAGNOSTIC)
  3103. #pragma GCC diagnostic push
  3104. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3105. #endif
  3106. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3107. #if defined(GCC_DIAGNOSTIC)
  3108. #pragma GCC diagnostic pop
  3109. #endif
  3110. buf[sizeof(buf) - 1] = 0;
  3111. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3112. if (!conn) {
  3113. puts(buf);
  3114. return;
  3115. }
  3116. /* Do not lock when getting the callback value, here and below.
  3117. * I suppose this is fine, since function cannot disappear in the
  3118. * same way string option can. */
  3119. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3120. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3121. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3122. if (mg_fopen(conn,
  3123. conn->dom_ctx->config[ERROR_LOG_FILE],
  3124. MG_FOPEN_MODE_APPEND,
  3125. &fi)
  3126. == 0) {
  3127. fi.access.fp = NULL;
  3128. }
  3129. } else {
  3130. fi.access.fp = NULL;
  3131. }
  3132. if (fi.access.fp != NULL) {
  3133. flockfile(fi.access.fp);
  3134. timestamp = time(NULL);
  3135. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3136. fprintf(fi.access.fp,
  3137. "[%010lu] [error] [client %s] ",
  3138. (unsigned long)timestamp,
  3139. src_addr);
  3140. if (conn->request_info.request_method != NULL) {
  3141. fprintf(fi.access.fp,
  3142. "%s %s: ",
  3143. conn->request_info.request_method,
  3144. conn->request_info.request_uri
  3145. ? conn->request_info.request_uri
  3146. : "");
  3147. }
  3148. fprintf(fi.access.fp, "%s", buf);
  3149. fputc('\n', fi.access.fp);
  3150. fflush(fi.access.fp);
  3151. funlockfile(fi.access.fp);
  3152. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3153. * mg_cry here anyway ;-) */
  3154. }
  3155. }
  3156. }
  3157. #endif /* Externally provided function */
  3158. /* Construct fake connection structure. Used for logging, if connection
  3159. * is not applicable at the moment of logging. */
  3160. static struct mg_connection *
  3161. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3162. {
  3163. static const struct mg_connection conn_zero = {0};
  3164. *fc = conn_zero;
  3165. fc->phys_ctx = ctx;
  3166. fc->dom_ctx = &(ctx->dd);
  3167. return fc;
  3168. }
  3169. static void
  3170. mg_cry_internal_wrap(const struct mg_connection *conn,
  3171. struct mg_context *ctx,
  3172. const char *func,
  3173. unsigned line,
  3174. const char *fmt,
  3175. ...)
  3176. {
  3177. va_list ap;
  3178. va_start(ap, fmt);
  3179. if (!conn && ctx) {
  3180. struct mg_connection fc;
  3181. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3182. } else {
  3183. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3184. }
  3185. va_end(ap);
  3186. }
  3187. void
  3188. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3189. {
  3190. va_list ap;
  3191. va_start(ap, fmt);
  3192. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3193. va_end(ap);
  3194. }
  3195. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3196. const char *
  3197. mg_version(void)
  3198. {
  3199. return CIVETWEB_VERSION;
  3200. }
  3201. const struct mg_request_info *
  3202. mg_get_request_info(const struct mg_connection *conn)
  3203. {
  3204. if (!conn) {
  3205. return NULL;
  3206. }
  3207. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3208. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3209. char txt[16];
  3210. struct mg_workerTLS *tls =
  3211. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3212. sprintf(txt, "%03i", conn->response_info.status_code);
  3213. if (strlen(txt) == 3) {
  3214. memcpy(tls->txtbuf, txt, 4);
  3215. } else {
  3216. strcpy(tls->txtbuf, "ERR");
  3217. }
  3218. ((struct mg_connection *)conn)->request_info.local_uri =
  3219. ((struct mg_connection *)conn)->request_info.request_uri =
  3220. tls->txtbuf; /* use thread safe buffer */
  3221. ((struct mg_connection *)conn)->request_info.num_headers =
  3222. conn->response_info.num_headers;
  3223. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3224. conn->response_info.http_headers,
  3225. sizeof(conn->response_info.http_headers));
  3226. } else
  3227. #endif
  3228. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3229. return NULL;
  3230. }
  3231. return &conn->request_info;
  3232. }
  3233. const struct mg_response_info *
  3234. mg_get_response_info(const struct mg_connection *conn)
  3235. {
  3236. if (!conn) {
  3237. return NULL;
  3238. }
  3239. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3240. return NULL;
  3241. }
  3242. return &conn->response_info;
  3243. }
  3244. static const char *
  3245. get_proto_name(const struct mg_connection *conn)
  3246. {
  3247. #if defined(__clang__)
  3248. #pragma clang diagnostic push
  3249. #pragma clang diagnostic ignored "-Wunreachable-code"
  3250. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3251. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3252. * unreachable, but splitting into four different #ifdef clauses here is more
  3253. * complicated.
  3254. */
  3255. #endif
  3256. const struct mg_request_info *ri = &conn->request_info;
  3257. const char *proto =
  3258. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3259. : (ri->is_ssl ? "https" : "http"));
  3260. return proto;
  3261. #if defined(__clang__)
  3262. #pragma clang diagnostic pop
  3263. #endif
  3264. }
  3265. int
  3266. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3267. {
  3268. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3269. return -1;
  3270. } else {
  3271. int truncated = 0;
  3272. const struct mg_request_info *ri = &conn->request_info;
  3273. const char *proto = get_proto_name(conn);
  3274. if (ri->local_uri == NULL) {
  3275. return -1;
  3276. }
  3277. if ((ri->request_uri != NULL)
  3278. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3279. /* The request uri is different from the local uri.
  3280. * This is usually if an absolute URI, including server
  3281. * name has been provided. */
  3282. mg_snprintf(conn,
  3283. &truncated,
  3284. buf,
  3285. buflen,
  3286. "%s://%s",
  3287. proto,
  3288. ri->request_uri);
  3289. if (truncated) {
  3290. return -1;
  3291. }
  3292. return 0;
  3293. } else {
  3294. /* The common case is a relative URI, so we have to
  3295. * construct an absolute URI from server name and port */
  3296. #if defined(USE_IPV6)
  3297. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3298. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3299. : htons(conn->client.lsa.sin.sin_port);
  3300. #else
  3301. int port = htons(conn->client.lsa.sin.sin_port);
  3302. #endif
  3303. int def_port = ri->is_ssl ? 443 : 80;
  3304. int auth_domain_check_enabled =
  3305. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3306. && (!mg_strcasecmp(
  3307. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3308. const char *server_domain =
  3309. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3310. char portstr[16];
  3311. char server_ip[48];
  3312. if (port != def_port) {
  3313. sprintf(portstr, ":%u", (unsigned)port);
  3314. } else {
  3315. portstr[0] = 0;
  3316. }
  3317. if (!auth_domain_check_enabled || !server_domain) {
  3318. sockaddr_to_string(server_ip,
  3319. sizeof(server_ip),
  3320. &conn->client.lsa);
  3321. server_domain = server_ip;
  3322. }
  3323. mg_snprintf(conn,
  3324. &truncated,
  3325. buf,
  3326. buflen,
  3327. "%s://%s%s%s",
  3328. proto,
  3329. server_domain,
  3330. portstr,
  3331. ri->local_uri);
  3332. if (truncated) {
  3333. return -1;
  3334. }
  3335. return 0;
  3336. }
  3337. }
  3338. }
  3339. /* Skip the characters until one of the delimiters characters found.
  3340. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3341. * Advance pointer to buffer to the next word. Return found 0-terminated
  3342. * word.
  3343. * Delimiters can be quoted with quotechar. */
  3344. static char *
  3345. skip_quoted(char **buf,
  3346. const char *delimiters,
  3347. const char *whitespace,
  3348. char quotechar)
  3349. {
  3350. char *p, *begin_word, *end_word, *end_whitespace;
  3351. begin_word = *buf;
  3352. end_word = begin_word + strcspn(begin_word, delimiters);
  3353. /* Check for quotechar */
  3354. if (end_word > begin_word) {
  3355. p = end_word - 1;
  3356. while (*p == quotechar) {
  3357. /* While the delimiter is quoted, look for the next delimiter.
  3358. */
  3359. /* This happens, e.g., in calls from parse_auth_header,
  3360. * if the user name contains a " character. */
  3361. /* If there is anything beyond end_word, copy it. */
  3362. if (*end_word != '\0') {
  3363. size_t end_off = strcspn(end_word + 1, delimiters);
  3364. memmove(p, end_word, end_off + 1);
  3365. p += end_off; /* p must correspond to end_word - 1 */
  3366. end_word += end_off + 1;
  3367. } else {
  3368. *p = '\0';
  3369. break;
  3370. }
  3371. }
  3372. for (p++; p < end_word; p++) {
  3373. *p = '\0';
  3374. }
  3375. }
  3376. if (*end_word == '\0') {
  3377. *buf = end_word;
  3378. } else {
  3379. #if defined(GCC_DIAGNOSTIC)
  3380. /* Disable spurious conversion warning for GCC */
  3381. #pragma GCC diagnostic push
  3382. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3383. #endif /* defined(GCC_DIAGNOSTIC) */
  3384. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3385. #if defined(GCC_DIAGNOSTIC)
  3386. #pragma GCC diagnostic pop
  3387. #endif /* defined(GCC_DIAGNOSTIC) */
  3388. for (p = end_word; p < end_whitespace; p++) {
  3389. *p = '\0';
  3390. }
  3391. *buf = end_whitespace;
  3392. }
  3393. return begin_word;
  3394. }
  3395. /* Return HTTP header value, or NULL if not found. */
  3396. static const char *
  3397. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3398. {
  3399. int i;
  3400. for (i = 0; i < num_hdr; i++) {
  3401. if (!mg_strcasecmp(name, hdr[i].name)) {
  3402. return hdr[i].value;
  3403. }
  3404. }
  3405. return NULL;
  3406. }
  3407. #if defined(USE_WEBSOCKET)
  3408. /* Retrieve requested HTTP header multiple values, and return the number of
  3409. * found occurrences */
  3410. static int
  3411. get_req_headers(const struct mg_request_info *ri,
  3412. const char *name,
  3413. const char **output,
  3414. int output_max_size)
  3415. {
  3416. int i;
  3417. int cnt = 0;
  3418. if (ri) {
  3419. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3420. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3421. output[cnt++] = ri->http_headers[i].value;
  3422. }
  3423. }
  3424. }
  3425. return cnt;
  3426. }
  3427. #endif
  3428. const char *
  3429. mg_get_header(const struct mg_connection *conn, const char *name)
  3430. {
  3431. if (!conn) {
  3432. return NULL;
  3433. }
  3434. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3435. return get_header(conn->request_info.http_headers,
  3436. conn->request_info.num_headers,
  3437. name);
  3438. }
  3439. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3440. return get_header(conn->response_info.http_headers,
  3441. conn->response_info.num_headers,
  3442. name);
  3443. }
  3444. return NULL;
  3445. }
  3446. static const char *
  3447. get_http_version(const struct mg_connection *conn)
  3448. {
  3449. if (!conn) {
  3450. return NULL;
  3451. }
  3452. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3453. return conn->request_info.http_version;
  3454. }
  3455. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3456. return conn->response_info.http_version;
  3457. }
  3458. return NULL;
  3459. }
  3460. /* A helper function for traversing a comma separated list of values.
  3461. * It returns a list pointer shifted to the next value, or NULL if the end
  3462. * of the list found.
  3463. * Value is stored in val vector. If value has form "x=y", then eq_val
  3464. * vector is initialized to point to the "y" part, and val vector length
  3465. * is adjusted to point only to "x". */
  3466. static const char *
  3467. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3468. {
  3469. int end;
  3470. reparse:
  3471. if (val == NULL || list == NULL || *list == '\0') {
  3472. /* End of the list */
  3473. return NULL;
  3474. }
  3475. /* Skip over leading LWS */
  3476. while (*list == ' ' || *list == '\t')
  3477. list++;
  3478. val->ptr = list;
  3479. if ((list = strchr(val->ptr, ',')) != NULL) {
  3480. /* Comma found. Store length and shift the list ptr */
  3481. val->len = ((size_t)(list - val->ptr));
  3482. list++;
  3483. } else {
  3484. /* This value is the last one */
  3485. list = val->ptr + strlen(val->ptr);
  3486. val->len = ((size_t)(list - val->ptr));
  3487. }
  3488. /* Adjust length for trailing LWS */
  3489. end = (int)val->len - 1;
  3490. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3491. end--;
  3492. val->len = (size_t)(end) + (size_t)(1);
  3493. if (val->len == 0) {
  3494. /* Ignore any empty entries. */
  3495. goto reparse;
  3496. }
  3497. if (eq_val != NULL) {
  3498. /* Value has form "x=y", adjust pointers and lengths
  3499. * so that val points to "x", and eq_val points to "y". */
  3500. eq_val->len = 0;
  3501. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3502. if (eq_val->ptr != NULL) {
  3503. eq_val->ptr++; /* Skip over '=' character */
  3504. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3505. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3506. }
  3507. }
  3508. return list;
  3509. }
  3510. /* A helper function for checking if a comma separated list of values
  3511. * contains
  3512. * the given option (case insensitvely).
  3513. * 'header' can be NULL, in which case false is returned. */
  3514. static int
  3515. header_has_option(const char *header, const char *option)
  3516. {
  3517. struct vec opt_vec;
  3518. struct vec eq_vec;
  3519. DEBUG_ASSERT(option != NULL);
  3520. DEBUG_ASSERT(option[0] != '\0');
  3521. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3522. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3523. return 1;
  3524. }
  3525. return 0;
  3526. }
  3527. /* Perform case-insensitive match of string against pattern */
  3528. static ptrdiff_t
  3529. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3530. {
  3531. const char *or_str;
  3532. ptrdiff_t i, j, len, res;
  3533. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3534. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3535. return (res > 0) ? res
  3536. : match_prefix(or_str + 1,
  3537. (size_t)((pattern + pattern_len)
  3538. - (or_str + 1)),
  3539. str);
  3540. }
  3541. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3542. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3543. continue;
  3544. } else if (pattern[i] == '$') {
  3545. return (str[j] == '\0') ? j : -1;
  3546. } else if (pattern[i] == '*') {
  3547. i++;
  3548. if (pattern[i] == '*') {
  3549. i++;
  3550. len = strlen(str + j);
  3551. } else {
  3552. len = strcspn(str + j, "/");
  3553. }
  3554. if (i == (ptrdiff_t)pattern_len) {
  3555. return j + len;
  3556. }
  3557. do {
  3558. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3559. } while (res == -1 && len-- > 0);
  3560. return (res == -1) ? -1 : j + res + len;
  3561. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3562. return -1;
  3563. }
  3564. }
  3565. return (ptrdiff_t)j;
  3566. }
  3567. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3568. * This function must tolerate situations when connection info is not
  3569. * set up, for example if request parsing failed. */
  3570. static int
  3571. should_keep_alive(const struct mg_connection *conn)
  3572. {
  3573. const char *http_version;
  3574. const char *header;
  3575. /* First satisfy needs of the server */
  3576. if ((conn == NULL) || conn->must_close) {
  3577. /* Close, if civetweb framework needs to close */
  3578. return 0;
  3579. }
  3580. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3581. /* Close, if keep alive is not enabled */
  3582. return 0;
  3583. }
  3584. /* Check explicit wish of the client */
  3585. header = mg_get_header(conn, "Connection");
  3586. if (header) {
  3587. /* If there is a connection header from the client, obey */
  3588. if (header_has_option(header, "keep-alive")) {
  3589. return 1;
  3590. }
  3591. return 0;
  3592. }
  3593. /* Use default of the standard */
  3594. http_version = get_http_version(conn);
  3595. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3596. /* HTTP 1.1 default is keep alive */
  3597. return 1;
  3598. }
  3599. /* HTTP 1.0 (and earlier) default is to close the connection */
  3600. return 0;
  3601. }
  3602. static int
  3603. should_decode_url(const struct mg_connection *conn)
  3604. {
  3605. if (!conn || !conn->dom_ctx) {
  3606. return 0;
  3607. }
  3608. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3609. }
  3610. static const char *
  3611. suggest_connection_header(const struct mg_connection *conn)
  3612. {
  3613. return should_keep_alive(conn) ? "keep-alive" : "close";
  3614. }
  3615. static int
  3616. send_no_cache_header(struct mg_connection *conn)
  3617. {
  3618. /* Send all current and obsolete cache opt-out directives. */
  3619. return mg_printf(conn,
  3620. "Cache-Control: no-cache, no-store, "
  3621. "must-revalidate, private, max-age=0\r\n"
  3622. "Pragma: no-cache\r\n"
  3623. "Expires: 0\r\n");
  3624. }
  3625. static int
  3626. send_static_cache_header(struct mg_connection *conn)
  3627. {
  3628. #if !defined(NO_CACHING)
  3629. /* Read the server config to check how long a file may be cached.
  3630. * The configuration is in seconds. */
  3631. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3632. if (max_age <= 0) {
  3633. /* 0 means "do not cache". All values <0 are reserved
  3634. * and may be used differently in the future. */
  3635. /* If a file should not be cached, do not only send
  3636. * max-age=0, but also pragmas and Expires headers. */
  3637. return send_no_cache_header(conn);
  3638. }
  3639. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3640. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3641. /* See also https://www.mnot.net/cache_docs/ */
  3642. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3643. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3644. * leap
  3645. * year to 31622400 seconds. For the moment, we just send whatever has
  3646. * been configured, still the behavior for >1 year should be considered
  3647. * as undefined. */
  3648. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3649. #else /* NO_CACHING */
  3650. return send_no_cache_header(conn);
  3651. #endif /* !NO_CACHING */
  3652. }
  3653. static int
  3654. send_additional_header(struct mg_connection *conn)
  3655. {
  3656. int i = 0;
  3657. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3658. #if !defined(NO_SSL)
  3659. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3660. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3661. if (max_age >= 0) {
  3662. i += mg_printf(conn,
  3663. "Strict-Transport-Security: max-age=%u\r\n",
  3664. (unsigned)max_age);
  3665. }
  3666. }
  3667. #endif
  3668. if (header && header[0]) {
  3669. i += mg_printf(conn, "%s\r\n", header);
  3670. }
  3671. return i;
  3672. }
  3673. static void handle_file_based_request(struct mg_connection *conn,
  3674. const char *path,
  3675. struct mg_file *filep);
  3676. const char *
  3677. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3678. {
  3679. /* See IANA HTTP status code assignment:
  3680. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3681. */
  3682. switch (response_code) {
  3683. /* RFC2616 Section 10.1 - Informational 1xx */
  3684. case 100:
  3685. return "Continue"; /* RFC2616 Section 10.1.1 */
  3686. case 101:
  3687. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3688. case 102:
  3689. return "Processing"; /* RFC2518 Section 10.1 */
  3690. /* RFC2616 Section 10.2 - Successful 2xx */
  3691. case 200:
  3692. return "OK"; /* RFC2616 Section 10.2.1 */
  3693. case 201:
  3694. return "Created"; /* RFC2616 Section 10.2.2 */
  3695. case 202:
  3696. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3697. case 203:
  3698. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3699. case 204:
  3700. return "No Content"; /* RFC2616 Section 10.2.5 */
  3701. case 205:
  3702. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3703. case 206:
  3704. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3705. case 207:
  3706. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3707. */
  3708. case 208:
  3709. return "Already Reported"; /* RFC5842 Section 7.1 */
  3710. case 226:
  3711. return "IM used"; /* RFC3229 Section 10.4.1 */
  3712. /* RFC2616 Section 10.3 - Redirection 3xx */
  3713. case 300:
  3714. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3715. case 301:
  3716. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3717. case 302:
  3718. return "Found"; /* RFC2616 Section 10.3.3 */
  3719. case 303:
  3720. return "See Other"; /* RFC2616 Section 10.3.4 */
  3721. case 304:
  3722. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3723. case 305:
  3724. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3725. case 307:
  3726. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3727. case 308:
  3728. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3729. /* RFC2616 Section 10.4 - Client Error 4xx */
  3730. case 400:
  3731. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3732. case 401:
  3733. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3734. case 402:
  3735. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3736. case 403:
  3737. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3738. case 404:
  3739. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3740. case 405:
  3741. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3742. case 406:
  3743. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3744. case 407:
  3745. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3746. case 408:
  3747. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3748. case 409:
  3749. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3750. case 410:
  3751. return "Gone"; /* RFC2616 Section 10.4.11 */
  3752. case 411:
  3753. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3754. case 412:
  3755. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3756. case 413:
  3757. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3758. case 414:
  3759. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3760. case 415:
  3761. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3762. case 416:
  3763. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3764. */
  3765. case 417:
  3766. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3767. case 421:
  3768. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3769. case 422:
  3770. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3771. * Section 11.2 */
  3772. case 423:
  3773. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3774. case 424:
  3775. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3776. * Section 11.4 */
  3777. case 426:
  3778. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3779. case 428:
  3780. return "Precondition Required"; /* RFC 6585, Section 3 */
  3781. case 429:
  3782. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3783. case 431:
  3784. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3785. case 451:
  3786. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3787. * Section 3 */
  3788. /* RFC2616 Section 10.5 - Server Error 5xx */
  3789. case 500:
  3790. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3791. case 501:
  3792. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3793. case 502:
  3794. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3795. case 503:
  3796. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3797. case 504:
  3798. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3799. case 505:
  3800. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3801. case 506:
  3802. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3803. case 507:
  3804. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3805. * Section 11.5 */
  3806. case 508:
  3807. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3808. case 510:
  3809. return "Not Extended"; /* RFC 2774, Section 7 */
  3810. case 511:
  3811. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3812. /* Other status codes, not shown in the IANA HTTP status code
  3813. * assignment.
  3814. * E.g., "de facto" standards due to common use, ... */
  3815. case 418:
  3816. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3817. case 419:
  3818. return "Authentication Timeout"; /* common use */
  3819. case 420:
  3820. return "Enhance Your Calm"; /* common use */
  3821. case 440:
  3822. return "Login Timeout"; /* common use */
  3823. case 509:
  3824. return "Bandwidth Limit Exceeded"; /* common use */
  3825. default:
  3826. /* This error code is unknown. This should not happen. */
  3827. if (conn) {
  3828. mg_cry_internal(conn,
  3829. "Unknown HTTP response code: %u",
  3830. response_code);
  3831. }
  3832. /* Return at least a category according to RFC 2616 Section 10. */
  3833. if (response_code >= 100 && response_code < 200) {
  3834. /* Unknown informational status code */
  3835. return "Information";
  3836. }
  3837. if (response_code >= 200 && response_code < 300) {
  3838. /* Unknown success code */
  3839. return "Success";
  3840. }
  3841. if (response_code >= 300 && response_code < 400) {
  3842. /* Unknown redirection code */
  3843. return "Redirection";
  3844. }
  3845. if (response_code >= 400 && response_code < 500) {
  3846. /* Unknown request error code */
  3847. return "Client Error";
  3848. }
  3849. if (response_code >= 500 && response_code < 600) {
  3850. /* Unknown server error code */
  3851. return "Server Error";
  3852. }
  3853. /* Response code not even within reasonable range */
  3854. return "";
  3855. }
  3856. }
  3857. static int
  3858. mg_send_http_error_impl(struct mg_connection *conn,
  3859. int status,
  3860. const char *fmt,
  3861. va_list args)
  3862. {
  3863. char errmsg_buf[MG_BUF_LEN];
  3864. char path_buf[PATH_MAX];
  3865. va_list ap;
  3866. int len, i, page_handler_found, scope, truncated, has_body;
  3867. char date[64];
  3868. time_t curtime = time(NULL);
  3869. const char *error_handler = NULL;
  3870. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3871. const char *error_page_file_ext, *tstr;
  3872. int handled_by_callback = 0;
  3873. const char *status_text = mg_get_response_code_text(conn, status);
  3874. if ((conn == NULL) || (fmt == NULL)) {
  3875. return -2;
  3876. }
  3877. /* Set status (for log) */
  3878. conn->status_code = status;
  3879. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3880. has_body = ((status > 199) && (status != 204) && (status != 304));
  3881. /* Prepare message in buf, if required */
  3882. if (has_body
  3883. || (!conn->in_error_handler
  3884. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3885. /* Store error message in errmsg_buf */
  3886. va_copy(ap, args);
  3887. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3888. va_end(ap);
  3889. /* In a debug build, print all html errors */
  3890. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3891. }
  3892. /* If there is a http_error callback, call it.
  3893. * But don't do it recursively, if callback calls mg_send_http_error again.
  3894. */
  3895. if (!conn->in_error_handler
  3896. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3897. /* Mark in_error_handler to avoid recursion and call user callback. */
  3898. conn->in_error_handler = 1;
  3899. handled_by_callback =
  3900. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3901. == 0);
  3902. conn->in_error_handler = 0;
  3903. }
  3904. if (!handled_by_callback) {
  3905. /* Check for recursion */
  3906. if (conn->in_error_handler) {
  3907. DEBUG_TRACE(
  3908. "Recursion when handling error %u - fall back to default",
  3909. status);
  3910. } else {
  3911. /* Send user defined error pages, if defined */
  3912. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3913. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3914. page_handler_found = 0;
  3915. if (error_handler != NULL) {
  3916. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3917. switch (scope) {
  3918. case 1: /* Handler for specific error, e.g. 404 error */
  3919. mg_snprintf(conn,
  3920. &truncated,
  3921. path_buf,
  3922. sizeof(path_buf) - 32,
  3923. "%serror%03u.",
  3924. error_handler,
  3925. status);
  3926. break;
  3927. case 2: /* Handler for error group, e.g., 5xx error
  3928. * handler
  3929. * for all server errors (500-599) */
  3930. mg_snprintf(conn,
  3931. &truncated,
  3932. path_buf,
  3933. sizeof(path_buf) - 32,
  3934. "%serror%01uxx.",
  3935. error_handler,
  3936. status / 100);
  3937. break;
  3938. default: /* Handler for all errors */
  3939. mg_snprintf(conn,
  3940. &truncated,
  3941. path_buf,
  3942. sizeof(path_buf) - 32,
  3943. "%serror.",
  3944. error_handler);
  3945. break;
  3946. }
  3947. /* String truncation in buf may only occur if
  3948. * error_handler is too long. This string is
  3949. * from the config, not from a client. */
  3950. (void)truncated;
  3951. len = (int)strlen(path_buf);
  3952. tstr = strchr(error_page_file_ext, '.');
  3953. while (tstr) {
  3954. for (i = 1;
  3955. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3956. i++) {
  3957. /* buffer overrun is not possible here, since
  3958. * (i < 32) && (len < sizeof(path_buf) - 32)
  3959. * ==> (i + len) < sizeof(path_buf) */
  3960. path_buf[len + i - 1] = tstr[i];
  3961. }
  3962. /* buffer overrun is not possible here, since
  3963. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3964. * ==> (i + len) <= sizeof(path_buf) */
  3965. path_buf[len + i - 1] = 0;
  3966. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3967. DEBUG_TRACE("Check error page %s - found",
  3968. path_buf);
  3969. page_handler_found = 1;
  3970. break;
  3971. }
  3972. DEBUG_TRACE("Check error page %s - not found",
  3973. path_buf);
  3974. tstr = strchr(tstr + i, '.');
  3975. }
  3976. }
  3977. }
  3978. if (page_handler_found) {
  3979. conn->in_error_handler = 1;
  3980. handle_file_based_request(conn, path_buf, &error_page_file);
  3981. conn->in_error_handler = 0;
  3982. return 0;
  3983. }
  3984. }
  3985. /* No custom error page. Send default error page. */
  3986. gmt_time_string(date, sizeof(date), &curtime);
  3987. conn->must_close = 1;
  3988. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3989. send_no_cache_header(conn);
  3990. send_additional_header(conn);
  3991. if (has_body) {
  3992. mg_printf(conn,
  3993. "%s",
  3994. "Content-Type: text/plain; charset=utf-8\r\n");
  3995. }
  3996. mg_printf(conn,
  3997. "Date: %s\r\n"
  3998. "Connection: close\r\n\r\n",
  3999. date);
  4000. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4001. if (has_body) {
  4002. /* For other errors, send a generic error message. */
  4003. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4004. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4005. } else {
  4006. /* No body allowed. Close the connection. */
  4007. DEBUG_TRACE("Error %i", status);
  4008. }
  4009. }
  4010. return 0;
  4011. }
  4012. int
  4013. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4014. {
  4015. va_list ap;
  4016. int ret;
  4017. va_start(ap, fmt);
  4018. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4019. va_end(ap);
  4020. return ret;
  4021. }
  4022. int
  4023. mg_send_http_ok(struct mg_connection *conn,
  4024. const char *mime_type,
  4025. long long content_length)
  4026. {
  4027. char date[64];
  4028. time_t curtime = time(NULL);
  4029. if ((mime_type == NULL) || (*mime_type == 0)) {
  4030. /* Parameter error */
  4031. return -2;
  4032. }
  4033. gmt_time_string(date, sizeof(date), &curtime);
  4034. mg_printf(conn,
  4035. "HTTP/1.1 200 OK\r\n"
  4036. "Content-Type: %s\r\n"
  4037. "Date: %s\r\n"
  4038. "Connection: %s\r\n",
  4039. mime_type,
  4040. date,
  4041. suggest_connection_header(conn));
  4042. send_no_cache_header(conn);
  4043. send_additional_header(conn);
  4044. if (content_length < 0) {
  4045. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4046. } else {
  4047. mg_printf(conn,
  4048. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4049. (uint64_t)content_length);
  4050. }
  4051. return 0;
  4052. }
  4053. int
  4054. mg_send_http_redirect(struct mg_connection *conn,
  4055. const char *target_url,
  4056. int redirect_code)
  4057. {
  4058. /* Send a 30x redirect response.
  4059. *
  4060. * Redirect types (status codes):
  4061. *
  4062. * Status | Perm/Temp | Method | Version
  4063. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4064. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4065. * 303 | temporary | always use GET | HTTP/1.1
  4066. * 307 | temporary | always keep method | HTTP/1.1
  4067. * 308 | permanent | always keep method | HTTP/1.1
  4068. */
  4069. const char *redirect_text;
  4070. int ret;
  4071. size_t content_len = 0;
  4072. char reply[MG_BUF_LEN];
  4073. /* In case redirect_code=0, use 307. */
  4074. if (redirect_code == 0) {
  4075. redirect_code = 307;
  4076. }
  4077. /* In case redirect_code is none of the above, return error. */
  4078. if ((redirect_code != 301) && (redirect_code != 302)
  4079. && (redirect_code != 303) && (redirect_code != 307)
  4080. && (redirect_code != 308)) {
  4081. /* Parameter error */
  4082. return -2;
  4083. }
  4084. /* Get proper text for response code */
  4085. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4086. /* If target_url is not defined, redirect to "/". */
  4087. if ((target_url == NULL) || (*target_url == 0)) {
  4088. target_url = "/";
  4089. }
  4090. #if defined(MG_SEND_REDIRECT_BODY)
  4091. /* TODO: condition name? */
  4092. /* Prepare a response body with a hyperlink.
  4093. *
  4094. * According to RFC2616 (and RFC1945 before):
  4095. * Unless the request method was HEAD, the entity of the
  4096. * response SHOULD contain a short hypertext note with a hyperlink to
  4097. * the new URI(s).
  4098. *
  4099. * However, this response body is not useful in M2M communication.
  4100. * Probably the original reason in the RFC was, clients not supporting
  4101. * a 30x HTTP redirect could still show the HTML page and let the user
  4102. * press the link. Since current browsers support 30x HTTP, the additional
  4103. * HTML body does not seem to make sense anymore.
  4104. *
  4105. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4106. * but it only notes:
  4107. * The server's response payload usually contains a short
  4108. * hypertext note with a hyperlink to the new URI(s).
  4109. *
  4110. * Deactivated by default. If you need the 30x body, set the define.
  4111. */
  4112. mg_snprintf(
  4113. conn,
  4114. NULL /* ignore truncation */,
  4115. reply,
  4116. sizeof(reply),
  4117. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4118. redirect_text,
  4119. target_url,
  4120. target_url);
  4121. content_len = strlen(reply);
  4122. #else
  4123. reply[0] = 0;
  4124. #endif
  4125. /* Do not send any additional header. For all other options,
  4126. * including caching, there are suitable defaults. */
  4127. ret = mg_printf(conn,
  4128. "HTTP/1.1 %i %s\r\n"
  4129. "Location: %s\r\n"
  4130. "Content-Length: %u\r\n"
  4131. "Connection: %s\r\n\r\n",
  4132. redirect_code,
  4133. redirect_text,
  4134. target_url,
  4135. (unsigned int)content_len,
  4136. suggest_connection_header(conn));
  4137. /* Send response body */
  4138. if (ret > 0) {
  4139. /* ... unless it is a HEAD request */
  4140. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4141. ret = mg_write(conn, reply, content_len);
  4142. }
  4143. }
  4144. return (ret > 0) ? ret : -1;
  4145. }
  4146. #if defined(_WIN32)
  4147. /* Create substitutes for POSIX functions in Win32. */
  4148. #if defined(GCC_DIAGNOSTIC)
  4149. /* Show no warning in case system functions are not used. */
  4150. #pragma GCC diagnostic push
  4151. #pragma GCC diagnostic ignored "-Wunused-function"
  4152. #endif
  4153. static int
  4154. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4155. {
  4156. (void)unused;
  4157. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4158. InitializeCriticalSection(&mutex->sec);
  4159. return 0;
  4160. }
  4161. static int
  4162. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4163. {
  4164. DeleteCriticalSection(&mutex->sec);
  4165. return 0;
  4166. }
  4167. static int
  4168. pthread_mutex_lock(pthread_mutex_t *mutex)
  4169. {
  4170. EnterCriticalSection(&mutex->sec);
  4171. return 0;
  4172. }
  4173. static int
  4174. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4175. {
  4176. LeaveCriticalSection(&mutex->sec);
  4177. return 0;
  4178. }
  4179. FUNCTION_MAY_BE_UNUSED
  4180. static int
  4181. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4182. {
  4183. (void)unused;
  4184. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4185. cv->waiting_thread = NULL;
  4186. return 0;
  4187. }
  4188. FUNCTION_MAY_BE_UNUSED
  4189. static int
  4190. pthread_cond_timedwait(pthread_cond_t *cv,
  4191. pthread_mutex_t *mutex,
  4192. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4193. {
  4194. struct mg_workerTLS **ptls,
  4195. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4196. int ok;
  4197. int64_t nsnow, nswaitabs, nswaitrel;
  4198. DWORD mswaitrel;
  4199. pthread_mutex_lock(&cv->threadIdSec);
  4200. /* Add this thread to cv's waiting list */
  4201. ptls = &cv->waiting_thread;
  4202. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4203. ;
  4204. tls->next_waiting_thread = NULL;
  4205. *ptls = tls;
  4206. pthread_mutex_unlock(&cv->threadIdSec);
  4207. if (abstime) {
  4208. nsnow = mg_get_current_time_ns();
  4209. nswaitabs =
  4210. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4211. nswaitrel = nswaitabs - nsnow;
  4212. if (nswaitrel < 0) {
  4213. nswaitrel = 0;
  4214. }
  4215. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4216. } else {
  4217. mswaitrel = (DWORD)INFINITE;
  4218. }
  4219. pthread_mutex_unlock(mutex);
  4220. ok = (WAIT_OBJECT_0
  4221. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4222. if (!ok) {
  4223. ok = 1;
  4224. pthread_mutex_lock(&cv->threadIdSec);
  4225. ptls = &cv->waiting_thread;
  4226. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4227. if (*ptls == tls) {
  4228. *ptls = tls->next_waiting_thread;
  4229. ok = 0;
  4230. break;
  4231. }
  4232. }
  4233. pthread_mutex_unlock(&cv->threadIdSec);
  4234. if (ok) {
  4235. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4236. (DWORD)INFINITE);
  4237. }
  4238. }
  4239. /* This thread has been removed from cv's waiting list */
  4240. pthread_mutex_lock(mutex);
  4241. return ok ? 0 : -1;
  4242. }
  4243. FUNCTION_MAY_BE_UNUSED
  4244. static int
  4245. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4246. {
  4247. return pthread_cond_timedwait(cv, mutex, NULL);
  4248. }
  4249. FUNCTION_MAY_BE_UNUSED
  4250. static int
  4251. pthread_cond_signal(pthread_cond_t *cv)
  4252. {
  4253. HANDLE wkup = NULL;
  4254. BOOL ok = FALSE;
  4255. pthread_mutex_lock(&cv->threadIdSec);
  4256. if (cv->waiting_thread) {
  4257. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4258. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4259. ok = SetEvent(wkup);
  4260. DEBUG_ASSERT(ok);
  4261. }
  4262. pthread_mutex_unlock(&cv->threadIdSec);
  4263. return ok ? 0 : 1;
  4264. }
  4265. FUNCTION_MAY_BE_UNUSED
  4266. static int
  4267. pthread_cond_broadcast(pthread_cond_t *cv)
  4268. {
  4269. pthread_mutex_lock(&cv->threadIdSec);
  4270. while (cv->waiting_thread) {
  4271. pthread_cond_signal(cv);
  4272. }
  4273. pthread_mutex_unlock(&cv->threadIdSec);
  4274. return 0;
  4275. }
  4276. FUNCTION_MAY_BE_UNUSED
  4277. static int
  4278. pthread_cond_destroy(pthread_cond_t *cv)
  4279. {
  4280. pthread_mutex_lock(&cv->threadIdSec);
  4281. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4282. pthread_mutex_unlock(&cv->threadIdSec);
  4283. pthread_mutex_destroy(&cv->threadIdSec);
  4284. return 0;
  4285. }
  4286. #if defined(ALTERNATIVE_QUEUE)
  4287. FUNCTION_MAY_BE_UNUSED
  4288. static void *
  4289. event_create(void)
  4290. {
  4291. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4292. }
  4293. FUNCTION_MAY_BE_UNUSED
  4294. static int
  4295. event_wait(void *eventhdl)
  4296. {
  4297. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4298. return (res == WAIT_OBJECT_0);
  4299. }
  4300. FUNCTION_MAY_BE_UNUSED
  4301. static int
  4302. event_signal(void *eventhdl)
  4303. {
  4304. return (int)SetEvent((HANDLE)eventhdl);
  4305. }
  4306. FUNCTION_MAY_BE_UNUSED
  4307. static void
  4308. event_destroy(void *eventhdl)
  4309. {
  4310. CloseHandle((HANDLE)eventhdl);
  4311. }
  4312. #endif
  4313. #if defined(GCC_DIAGNOSTIC)
  4314. /* Enable unused function warning again */
  4315. #pragma GCC diagnostic pop
  4316. #endif
  4317. /* For Windows, change all slashes to backslashes in path names. */
  4318. static void
  4319. change_slashes_to_backslashes(char *path)
  4320. {
  4321. int i;
  4322. for (i = 0; path[i] != '\0'; i++) {
  4323. if (path[i] == '/') {
  4324. path[i] = '\\';
  4325. }
  4326. /* remove double backslash (check i > 0 to preserve UNC paths,
  4327. * like \\server\file.txt) */
  4328. if ((path[i] == '\\') && (i > 0)) {
  4329. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4330. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4331. }
  4332. }
  4333. }
  4334. }
  4335. static int
  4336. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4337. {
  4338. int diff;
  4339. do {
  4340. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4341. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4342. s1++;
  4343. s2++;
  4344. } while ((diff == 0) && (s1[-1] != L'\0'));
  4345. return diff;
  4346. }
  4347. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4348. * wbuf and wbuf_len is a target buffer and its length. */
  4349. static void
  4350. path_to_unicode(const struct mg_connection *conn,
  4351. const char *path,
  4352. wchar_t *wbuf,
  4353. size_t wbuf_len)
  4354. {
  4355. char buf[PATH_MAX], buf2[PATH_MAX];
  4356. wchar_t wbuf2[W_PATH_MAX + 1];
  4357. DWORD long_len, err;
  4358. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4359. mg_strlcpy(buf, path, sizeof(buf));
  4360. change_slashes_to_backslashes(buf);
  4361. /* Convert to Unicode and back. If doubly-converted string does not
  4362. * match the original, something is fishy, reject. */
  4363. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4364. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4365. WideCharToMultiByte(
  4366. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4367. if (strcmp(buf, buf2) != 0) {
  4368. wbuf[0] = L'\0';
  4369. }
  4370. /* Windows file systems are not case sensitive, but you can still use
  4371. * uppercase and lowercase letters (on all modern file systems).
  4372. * The server can check if the URI uses the same upper/lowercase
  4373. * letters an the file system, effectively making Windows servers
  4374. * case sensitive (like Linux servers are). It is still not possible
  4375. * to use two files with the same name in different cases on Windows
  4376. * (like /a and /A) - this would be possible in Linux.
  4377. * As a default, Windows is not case sensitive, but the case sensitive
  4378. * file name check can be activated by an additional configuration. */
  4379. if (conn) {
  4380. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4381. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4382. "yes")) {
  4383. /* Use case sensitive compare function */
  4384. fcompare = wcscmp;
  4385. }
  4386. }
  4387. (void)conn; /* conn is currently unused */
  4388. #if !defined(_WIN32_WCE)
  4389. /* Only accept a full file path, not a Windows short (8.3) path. */
  4390. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4391. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4392. if (long_len == 0) {
  4393. err = GetLastError();
  4394. if (err == ERROR_FILE_NOT_FOUND) {
  4395. /* File does not exist. This is not always a problem here. */
  4396. return;
  4397. }
  4398. }
  4399. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4400. /* Short name is used. */
  4401. wbuf[0] = L'\0';
  4402. }
  4403. #else
  4404. (void)long_len;
  4405. (void)wbuf2;
  4406. (void)err;
  4407. if (strchr(path, '~')) {
  4408. wbuf[0] = L'\0';
  4409. }
  4410. #endif
  4411. }
  4412. static int
  4413. mg_stat(const struct mg_connection *conn,
  4414. const char *path,
  4415. struct mg_file_stat *filep)
  4416. {
  4417. wchar_t wbuf[W_PATH_MAX];
  4418. WIN32_FILE_ATTRIBUTE_DATA info;
  4419. time_t creation_time;
  4420. size_t len;
  4421. if (!filep) {
  4422. return 0;
  4423. }
  4424. memset(filep, 0, sizeof(*filep));
  4425. if (conn && is_file_in_memory(conn, path)) {
  4426. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4427. * memset */
  4428. /* Quick fix (for 1.9.x): */
  4429. /* mg_stat must fill all fields, also for files in memory */
  4430. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4431. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4432. filep->size = tmp_file.stat.size;
  4433. filep->location = 2;
  4434. /* TODO: for 1.10: restructure how files in memory are handled */
  4435. /* The "file in memory" feature is a candidate for deletion.
  4436. * Please join the discussion at
  4437. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4438. */
  4439. filep->last_modified = time(NULL); /* TODO */
  4440. /* last_modified = now ... assumes the file may change during
  4441. * runtime,
  4442. * so every mg_fopen call may return different data */
  4443. /* last_modified = conn->phys_ctx.start_time;
  4444. * May be used it the data does not change during runtime. This
  4445. * allows
  4446. * browser caching. Since we do not know, we have to assume the file
  4447. * in memory may change. */
  4448. return 1;
  4449. }
  4450. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4451. /* Windows happily opens files with some garbage at the end of file name.
  4452. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4453. * "a.cgi", despite one would expect an error back. */
  4454. len = strlen(path);
  4455. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4456. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4457. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4458. filep->last_modified =
  4459. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4460. info.ftLastWriteTime.dwHighDateTime);
  4461. /* On Windows, the file creation time can be higher than the
  4462. * modification time, e.g. when a file is copied.
  4463. * Since the Last-Modified timestamp is used for caching
  4464. * it should be based on the most recent timestamp. */
  4465. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4466. info.ftCreationTime.dwHighDateTime);
  4467. if (creation_time > filep->last_modified) {
  4468. filep->last_modified = creation_time;
  4469. }
  4470. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4471. return 1;
  4472. }
  4473. return 0;
  4474. }
  4475. static int
  4476. mg_remove(const struct mg_connection *conn, const char *path)
  4477. {
  4478. wchar_t wbuf[W_PATH_MAX];
  4479. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4480. return DeleteFileW(wbuf) ? 0 : -1;
  4481. }
  4482. static int
  4483. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4484. {
  4485. wchar_t wbuf[W_PATH_MAX];
  4486. (void)mode;
  4487. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4488. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4489. }
  4490. /* Create substitutes for POSIX functions in Win32. */
  4491. #if defined(GCC_DIAGNOSTIC)
  4492. /* Show no warning in case system functions are not used. */
  4493. #pragma GCC diagnostic push
  4494. #pragma GCC diagnostic ignored "-Wunused-function"
  4495. #endif
  4496. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4497. FUNCTION_MAY_BE_UNUSED
  4498. static DIR *
  4499. mg_opendir(const struct mg_connection *conn, const char *name)
  4500. {
  4501. DIR *dir = NULL;
  4502. wchar_t wpath[W_PATH_MAX];
  4503. DWORD attrs;
  4504. if (name == NULL) {
  4505. SetLastError(ERROR_BAD_ARGUMENTS);
  4506. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4507. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4508. } else {
  4509. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4510. attrs = GetFileAttributesW(wpath);
  4511. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4512. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4513. (void)wcscat(wpath, L"\\*");
  4514. dir->handle = FindFirstFileW(wpath, &dir->info);
  4515. dir->result.d_name[0] = '\0';
  4516. } else {
  4517. mg_free(dir);
  4518. dir = NULL;
  4519. }
  4520. }
  4521. return dir;
  4522. }
  4523. FUNCTION_MAY_BE_UNUSED
  4524. static int
  4525. mg_closedir(DIR *dir)
  4526. {
  4527. int result = 0;
  4528. if (dir != NULL) {
  4529. if (dir->handle != INVALID_HANDLE_VALUE)
  4530. result = FindClose(dir->handle) ? 0 : -1;
  4531. mg_free(dir);
  4532. } else {
  4533. result = -1;
  4534. SetLastError(ERROR_BAD_ARGUMENTS);
  4535. }
  4536. return result;
  4537. }
  4538. FUNCTION_MAY_BE_UNUSED
  4539. static struct dirent *
  4540. mg_readdir(DIR *dir)
  4541. {
  4542. struct dirent *result = 0;
  4543. if (dir) {
  4544. if (dir->handle != INVALID_HANDLE_VALUE) {
  4545. result = &dir->result;
  4546. (void)WideCharToMultiByte(CP_UTF8,
  4547. 0,
  4548. dir->info.cFileName,
  4549. -1,
  4550. result->d_name,
  4551. sizeof(result->d_name),
  4552. NULL,
  4553. NULL);
  4554. if (!FindNextFileW(dir->handle, &dir->info)) {
  4555. (void)FindClose(dir->handle);
  4556. dir->handle = INVALID_HANDLE_VALUE;
  4557. }
  4558. } else {
  4559. SetLastError(ERROR_FILE_NOT_FOUND);
  4560. }
  4561. } else {
  4562. SetLastError(ERROR_BAD_ARGUMENTS);
  4563. }
  4564. return result;
  4565. }
  4566. #if !defined(HAVE_POLL)
  4567. #undef POLLIN
  4568. #undef POLLPRI
  4569. #undef POLLOUT
  4570. #define POLLIN (1) /* Data ready - read will not block. */
  4571. #define POLLPRI (2) /* Priority data ready. */
  4572. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4573. FUNCTION_MAY_BE_UNUSED
  4574. static int
  4575. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4576. {
  4577. struct timeval tv;
  4578. fd_set rset;
  4579. fd_set wset;
  4580. unsigned int i;
  4581. int result;
  4582. SOCKET maxfd = 0;
  4583. memset(&tv, 0, sizeof(tv));
  4584. tv.tv_sec = milliseconds / 1000;
  4585. tv.tv_usec = (milliseconds % 1000) * 1000;
  4586. FD_ZERO(&rset);
  4587. FD_ZERO(&wset);
  4588. for (i = 0; i < n; i++) {
  4589. if (pfd[i].events & POLLIN) {
  4590. FD_SET(pfd[i].fd, &rset);
  4591. }
  4592. if (pfd[i].events & POLLOUT) {
  4593. FD_SET(pfd[i].fd, &wset);
  4594. }
  4595. pfd[i].revents = 0;
  4596. if (pfd[i].fd > maxfd) {
  4597. maxfd = pfd[i].fd;
  4598. }
  4599. }
  4600. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4601. for (i = 0; i < n; i++) {
  4602. if (FD_ISSET(pfd[i].fd, &rset)) {
  4603. pfd[i].revents |= POLLIN;
  4604. }
  4605. if (FD_ISSET(pfd[i].fd, &wset)) {
  4606. pfd[i].revents |= POLLOUT;
  4607. }
  4608. }
  4609. }
  4610. /* We should subtract the time used in select from remaining
  4611. * "milliseconds", in particular if called from mg_poll with a
  4612. * timeout quantum.
  4613. * Unfortunately, the remaining time is not stored in "tv" in all
  4614. * implementations, so the result in "tv" must be considered undefined.
  4615. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4616. return result;
  4617. }
  4618. #endif /* HAVE_POLL */
  4619. #if defined(GCC_DIAGNOSTIC)
  4620. /* Enable unused function warning again */
  4621. #pragma GCC diagnostic pop
  4622. #endif
  4623. static void
  4624. set_close_on_exec(SOCKET sock,
  4625. const struct mg_connection *conn /* may be null */,
  4626. struct mg_context *ctx /* may be null */)
  4627. {
  4628. (void)conn; /* Unused. */
  4629. (void)ctx;
  4630. #if defined(_WIN32_WCE)
  4631. (void)sock;
  4632. #else
  4633. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4634. #endif
  4635. }
  4636. int
  4637. mg_start_thread(mg_thread_func_t f, void *p)
  4638. {
  4639. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4640. /* Compile-time option to control stack size, e.g.
  4641. * -DUSE_STACK_SIZE=16384
  4642. */
  4643. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4644. == ((uintptr_t)(-1L)))
  4645. ? -1
  4646. : 0);
  4647. #else
  4648. return (
  4649. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4650. ? -1
  4651. : 0);
  4652. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4653. }
  4654. /* Start a thread storing the thread context. */
  4655. static int
  4656. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4657. void *p,
  4658. pthread_t *threadidptr)
  4659. {
  4660. uintptr_t uip;
  4661. HANDLE threadhandle;
  4662. int result = -1;
  4663. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4664. threadhandle = (HANDLE)uip;
  4665. if ((uip != 0) && (threadidptr != NULL)) {
  4666. *threadidptr = threadhandle;
  4667. result = 0;
  4668. }
  4669. return result;
  4670. }
  4671. /* Wait for a thread to finish. */
  4672. static int
  4673. mg_join_thread(pthread_t threadid)
  4674. {
  4675. int result;
  4676. DWORD dwevent;
  4677. result = -1;
  4678. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4679. if (dwevent == WAIT_FAILED) {
  4680. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4681. } else {
  4682. if (dwevent == WAIT_OBJECT_0) {
  4683. CloseHandle(threadid);
  4684. result = 0;
  4685. }
  4686. }
  4687. return result;
  4688. }
  4689. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4690. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4691. /* Create substitutes for POSIX functions in Win32. */
  4692. #if defined(GCC_DIAGNOSTIC)
  4693. /* Show no warning in case system functions are not used. */
  4694. #pragma GCC diagnostic push
  4695. #pragma GCC diagnostic ignored "-Wunused-function"
  4696. #endif
  4697. FUNCTION_MAY_BE_UNUSED
  4698. static HANDLE
  4699. dlopen(const char *dll_name, int flags)
  4700. {
  4701. wchar_t wbuf[W_PATH_MAX];
  4702. (void)flags;
  4703. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4704. return LoadLibraryW(wbuf);
  4705. }
  4706. FUNCTION_MAY_BE_UNUSED
  4707. static int
  4708. dlclose(void *handle)
  4709. {
  4710. int result;
  4711. if (FreeLibrary((HMODULE)handle) != 0) {
  4712. result = 0;
  4713. } else {
  4714. result = -1;
  4715. }
  4716. return result;
  4717. }
  4718. #if defined(GCC_DIAGNOSTIC)
  4719. /* Enable unused function warning again */
  4720. #pragma GCC diagnostic pop
  4721. #endif
  4722. #endif
  4723. #if !defined(NO_CGI)
  4724. #define SIGKILL (0)
  4725. static int
  4726. kill(pid_t pid, int sig_num)
  4727. {
  4728. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4729. (void)CloseHandle((HANDLE)pid);
  4730. return 0;
  4731. }
  4732. #if !defined(WNOHANG)
  4733. #define WNOHANG (1)
  4734. #endif
  4735. static pid_t
  4736. waitpid(pid_t pid, int *status, int flags)
  4737. {
  4738. DWORD timeout = INFINITE;
  4739. DWORD waitres;
  4740. (void)status; /* Currently not used by any client here */
  4741. if ((flags | WNOHANG) == WNOHANG) {
  4742. timeout = 0;
  4743. }
  4744. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4745. if (waitres == WAIT_OBJECT_0) {
  4746. return pid;
  4747. }
  4748. if (waitres == WAIT_TIMEOUT) {
  4749. return 0;
  4750. }
  4751. return (pid_t)-1;
  4752. }
  4753. static void
  4754. trim_trailing_whitespaces(char *s)
  4755. {
  4756. char *e = s + strlen(s);
  4757. while ((e > s) && isspace((unsigned char)e[-1])) {
  4758. *(--e) = '\0';
  4759. }
  4760. }
  4761. static pid_t
  4762. spawn_process(struct mg_connection *conn,
  4763. const char *prog,
  4764. char *envblk,
  4765. char *envp[],
  4766. int fdin[2],
  4767. int fdout[2],
  4768. int fderr[2],
  4769. const char *dir)
  4770. {
  4771. HANDLE me;
  4772. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4773. cmdline[PATH_MAX], buf[PATH_MAX];
  4774. int truncated;
  4775. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4776. STARTUPINFOA si;
  4777. PROCESS_INFORMATION pi = {0};
  4778. (void)envp;
  4779. memset(&si, 0, sizeof(si));
  4780. si.cb = sizeof(si);
  4781. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4782. si.wShowWindow = SW_HIDE;
  4783. me = GetCurrentProcess();
  4784. DuplicateHandle(me,
  4785. (HANDLE)_get_osfhandle(fdin[0]),
  4786. me,
  4787. &si.hStdInput,
  4788. 0,
  4789. TRUE,
  4790. DUPLICATE_SAME_ACCESS);
  4791. DuplicateHandle(me,
  4792. (HANDLE)_get_osfhandle(fdout[1]),
  4793. me,
  4794. &si.hStdOutput,
  4795. 0,
  4796. TRUE,
  4797. DUPLICATE_SAME_ACCESS);
  4798. DuplicateHandle(me,
  4799. (HANDLE)_get_osfhandle(fderr[1]),
  4800. me,
  4801. &si.hStdError,
  4802. 0,
  4803. TRUE,
  4804. DUPLICATE_SAME_ACCESS);
  4805. /* Mark handles that should not be inherited. See
  4806. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4807. */
  4808. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4809. HANDLE_FLAG_INHERIT,
  4810. 0);
  4811. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4812. HANDLE_FLAG_INHERIT,
  4813. 0);
  4814. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4815. HANDLE_FLAG_INHERIT,
  4816. 0);
  4817. /* If CGI file is a script, try to read the interpreter line */
  4818. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4819. if (interp == NULL) {
  4820. buf[0] = buf[1] = '\0';
  4821. /* Read the first line of the script into the buffer */
  4822. mg_snprintf(
  4823. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4824. if (truncated) {
  4825. pi.hProcess = (pid_t)-1;
  4826. goto spawn_cleanup;
  4827. }
  4828. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4829. #if defined(MG_USE_OPEN_FILE)
  4830. p = (char *)file.access.membuf;
  4831. #else
  4832. p = (char *)NULL;
  4833. #endif
  4834. mg_fgets(buf, sizeof(buf), &file, &p);
  4835. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4836. buf[sizeof(buf) - 1] = '\0';
  4837. }
  4838. if ((buf[0] == '#') && (buf[1] == '!')) {
  4839. trim_trailing_whitespaces(buf + 2);
  4840. } else {
  4841. buf[2] = '\0';
  4842. }
  4843. interp = buf + 2;
  4844. }
  4845. if (interp[0] != '\0') {
  4846. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4847. interp = full_interp;
  4848. }
  4849. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4850. if (interp[0] != '\0') {
  4851. mg_snprintf(conn,
  4852. &truncated,
  4853. cmdline,
  4854. sizeof(cmdline),
  4855. "\"%s\" \"%s\\%s\"",
  4856. interp,
  4857. full_dir,
  4858. prog);
  4859. } else {
  4860. mg_snprintf(conn,
  4861. &truncated,
  4862. cmdline,
  4863. sizeof(cmdline),
  4864. "\"%s\\%s\"",
  4865. full_dir,
  4866. prog);
  4867. }
  4868. if (truncated) {
  4869. pi.hProcess = (pid_t)-1;
  4870. goto spawn_cleanup;
  4871. }
  4872. DEBUG_TRACE("Running [%s]", cmdline);
  4873. if (CreateProcessA(NULL,
  4874. cmdline,
  4875. NULL,
  4876. NULL,
  4877. TRUE,
  4878. CREATE_NEW_PROCESS_GROUP,
  4879. envblk,
  4880. NULL,
  4881. &si,
  4882. &pi)
  4883. == 0) {
  4884. mg_cry_internal(
  4885. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4886. pi.hProcess = (pid_t)-1;
  4887. /* goto spawn_cleanup; */
  4888. }
  4889. spawn_cleanup:
  4890. (void)CloseHandle(si.hStdOutput);
  4891. (void)CloseHandle(si.hStdError);
  4892. (void)CloseHandle(si.hStdInput);
  4893. if (pi.hThread != NULL) {
  4894. (void)CloseHandle(pi.hThread);
  4895. }
  4896. return (pid_t)pi.hProcess;
  4897. }
  4898. #endif /* !NO_CGI */
  4899. static int
  4900. set_blocking_mode(SOCKET sock)
  4901. {
  4902. unsigned long non_blocking = 0;
  4903. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4904. }
  4905. static int
  4906. set_non_blocking_mode(SOCKET sock)
  4907. {
  4908. unsigned long non_blocking = 1;
  4909. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4910. }
  4911. #else
  4912. static int
  4913. mg_stat(const struct mg_connection *conn,
  4914. const char *path,
  4915. struct mg_file_stat *filep)
  4916. {
  4917. struct stat st;
  4918. if (!filep) {
  4919. return 0;
  4920. }
  4921. memset(filep, 0, sizeof(*filep));
  4922. if (conn && is_file_in_memory(conn, path)) {
  4923. /* Quick fix (for 1.9.x): */
  4924. /* mg_stat must fill all fields, also for files in memory */
  4925. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4926. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4927. filep->size = tmp_file.stat.size;
  4928. filep->last_modified = time(NULL);
  4929. filep->location = 2;
  4930. /* TODO: remove legacy "files in memory" feature */
  4931. return 1;
  4932. }
  4933. if (0 == stat(path, &st)) {
  4934. filep->size = (uint64_t)(st.st_size);
  4935. filep->last_modified = st.st_mtime;
  4936. filep->is_directory = S_ISDIR(st.st_mode);
  4937. return 1;
  4938. }
  4939. return 0;
  4940. }
  4941. static void
  4942. set_close_on_exec(int fd,
  4943. const struct mg_connection *conn /* may be null */,
  4944. struct mg_context *ctx /* may be null */)
  4945. {
  4946. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4947. if (conn || ctx) {
  4948. struct mg_connection fc;
  4949. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4950. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4951. __func__,
  4952. strerror(ERRNO));
  4953. }
  4954. }
  4955. }
  4956. int
  4957. mg_start_thread(mg_thread_func_t func, void *param)
  4958. {
  4959. pthread_t thread_id;
  4960. pthread_attr_t attr;
  4961. int result;
  4962. (void)pthread_attr_init(&attr);
  4963. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4964. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4965. /* Compile-time option to control stack size,
  4966. * e.g. -DUSE_STACK_SIZE=16384 */
  4967. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4968. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4969. result = pthread_create(&thread_id, &attr, func, param);
  4970. pthread_attr_destroy(&attr);
  4971. return result;
  4972. }
  4973. /* Start a thread storing the thread context. */
  4974. static int
  4975. mg_start_thread_with_id(mg_thread_func_t func,
  4976. void *param,
  4977. pthread_t *threadidptr)
  4978. {
  4979. pthread_t thread_id;
  4980. pthread_attr_t attr;
  4981. int result;
  4982. (void)pthread_attr_init(&attr);
  4983. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4984. /* Compile-time option to control stack size,
  4985. * e.g. -DUSE_STACK_SIZE=16384 */
  4986. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4987. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4988. result = pthread_create(&thread_id, &attr, func, param);
  4989. pthread_attr_destroy(&attr);
  4990. if ((result == 0) && (threadidptr != NULL)) {
  4991. *threadidptr = thread_id;
  4992. }
  4993. return result;
  4994. }
  4995. /* Wait for a thread to finish. */
  4996. static int
  4997. mg_join_thread(pthread_t threadid)
  4998. {
  4999. int result;
  5000. result = pthread_join(threadid, NULL);
  5001. return result;
  5002. }
  5003. #if !defined(NO_CGI)
  5004. static pid_t
  5005. spawn_process(struct mg_connection *conn,
  5006. const char *prog,
  5007. char *envblk,
  5008. char *envp[],
  5009. int fdin[2],
  5010. int fdout[2],
  5011. int fderr[2],
  5012. const char *dir)
  5013. {
  5014. pid_t pid;
  5015. const char *interp;
  5016. (void)envblk;
  5017. if ((pid = fork()) == -1) {
  5018. /* Parent */
  5019. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5020. } else if (pid != 0) {
  5021. /* Make sure children close parent-side descriptors.
  5022. * The caller will close the child-side immediately. */
  5023. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5024. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5025. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5026. } else {
  5027. /* Child */
  5028. if (chdir(dir) != 0) {
  5029. mg_cry_internal(
  5030. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5031. } else if (dup2(fdin[0], 0) == -1) {
  5032. mg_cry_internal(conn,
  5033. "%s: dup2(%d, 0): %s",
  5034. __func__,
  5035. fdin[0],
  5036. strerror(ERRNO));
  5037. } else if (dup2(fdout[1], 1) == -1) {
  5038. mg_cry_internal(conn,
  5039. "%s: dup2(%d, 1): %s",
  5040. __func__,
  5041. fdout[1],
  5042. strerror(ERRNO));
  5043. } else if (dup2(fderr[1], 2) == -1) {
  5044. mg_cry_internal(conn,
  5045. "%s: dup2(%d, 2): %s",
  5046. __func__,
  5047. fderr[1],
  5048. strerror(ERRNO));
  5049. } else {
  5050. struct sigaction sa;
  5051. /* Keep stderr and stdout in two different pipes.
  5052. * Stdout will be sent back to the client,
  5053. * stderr should go into a server error log. */
  5054. (void)close(fdin[0]);
  5055. (void)close(fdout[1]);
  5056. (void)close(fderr[1]);
  5057. /* Close write end fdin and read end fdout and fderr */
  5058. (void)close(fdin[1]);
  5059. (void)close(fdout[0]);
  5060. (void)close(fderr[0]);
  5061. /* After exec, all signal handlers are restored to their default
  5062. * values, with one exception of SIGCHLD. According to
  5063. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5064. * will leave unchanged after exec if it was set to be ignored.
  5065. * Restore it to default action. */
  5066. memset(&sa, 0, sizeof(sa));
  5067. sa.sa_handler = SIG_DFL;
  5068. sigaction(SIGCHLD, &sa, NULL);
  5069. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5070. if (interp == NULL) {
  5071. (void)execle(prog, prog, NULL, envp);
  5072. mg_cry_internal(conn,
  5073. "%s: execle(%s): %s",
  5074. __func__,
  5075. prog,
  5076. strerror(ERRNO));
  5077. } else {
  5078. (void)execle(interp, interp, prog, NULL, envp);
  5079. mg_cry_internal(conn,
  5080. "%s: execle(%s %s): %s",
  5081. __func__,
  5082. interp,
  5083. prog,
  5084. strerror(ERRNO));
  5085. }
  5086. }
  5087. exit(EXIT_FAILURE);
  5088. }
  5089. return pid;
  5090. }
  5091. #endif /* !NO_CGI */
  5092. static int
  5093. set_non_blocking_mode(SOCKET sock)
  5094. {
  5095. int flags = fcntl(sock, F_GETFL, 0);
  5096. if (flags < 0) {
  5097. return -1;
  5098. }
  5099. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5100. return -1;
  5101. }
  5102. return 0;
  5103. }
  5104. static int
  5105. set_blocking_mode(SOCKET sock)
  5106. {
  5107. int flags = fcntl(sock, F_GETFL, 0);
  5108. if (flags < 0) {
  5109. return -1;
  5110. }
  5111. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5112. return -1;
  5113. }
  5114. return 0;
  5115. }
  5116. #endif /* _WIN32 / else */
  5117. /* End of initial operating system specific define block. */
  5118. /* Get a random number (independent of C rand function) */
  5119. static uint64_t
  5120. get_random(void)
  5121. {
  5122. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5123. static uint64_t lcg = 0; /* Linear congruential generator */
  5124. uint64_t now = mg_get_current_time_ns();
  5125. if (lfsr == 0) {
  5126. /* lfsr will be only 0 if has not been initialized,
  5127. * so this code is called only once. */
  5128. lfsr = mg_get_current_time_ns();
  5129. lcg = mg_get_current_time_ns();
  5130. } else {
  5131. /* Get the next step of both random number generators. */
  5132. lfsr = (lfsr >> 1)
  5133. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5134. << 63);
  5135. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5136. }
  5137. /* Combining two pseudo-random number generators and a high resolution
  5138. * part
  5139. * of the current server time will make it hard (impossible?) to guess
  5140. * the
  5141. * next number. */
  5142. return (lfsr ^ lcg ^ now);
  5143. }
  5144. static int
  5145. mg_poll(struct mg_pollfd *pfd,
  5146. unsigned int n,
  5147. int milliseconds,
  5148. volatile int *stop_server)
  5149. {
  5150. /* Call poll, but only for a maximum time of a few seconds.
  5151. * This will allow to stop the server after some seconds, instead
  5152. * of having to wait for a long socket timeout. */
  5153. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5154. do {
  5155. int result;
  5156. if (*stop_server) {
  5157. /* Shut down signal */
  5158. return -2;
  5159. }
  5160. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5161. ms_now = milliseconds;
  5162. }
  5163. result = poll(pfd, n, ms_now);
  5164. if (result != 0) {
  5165. /* Poll returned either success (1) or error (-1).
  5166. * Forward both to the caller. */
  5167. return result;
  5168. }
  5169. /* Poll returned timeout (0). */
  5170. if (milliseconds > 0) {
  5171. milliseconds -= ms_now;
  5172. }
  5173. } while (milliseconds != 0);
  5174. /* timeout: return 0 */
  5175. return 0;
  5176. }
  5177. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5178. * descriptor.
  5179. * Return value:
  5180. * >=0 .. number of bytes successfully written
  5181. * -1 .. timeout
  5182. * -2 .. error
  5183. */
  5184. static int
  5185. push_inner(struct mg_context *ctx,
  5186. FILE *fp,
  5187. SOCKET sock,
  5188. SSL *ssl,
  5189. const char *buf,
  5190. int len,
  5191. double timeout)
  5192. {
  5193. uint64_t start = 0, now = 0, timeout_ns = 0;
  5194. int n, err;
  5195. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5196. #if defined(_WIN32)
  5197. typedef int len_t;
  5198. #else
  5199. typedef size_t len_t;
  5200. #endif
  5201. if (timeout > 0) {
  5202. now = mg_get_current_time_ns();
  5203. start = now;
  5204. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5205. }
  5206. if (ctx == NULL) {
  5207. return -2;
  5208. }
  5209. #if defined(NO_SSL)
  5210. if (ssl) {
  5211. return -2;
  5212. }
  5213. #endif
  5214. /* Try to read until it succeeds, fails, times out, or the server
  5215. * shuts down. */
  5216. for (;;) {
  5217. #if !defined(NO_SSL)
  5218. if (ssl != NULL) {
  5219. n = SSL_write(ssl, buf, len);
  5220. if (n <= 0) {
  5221. err = SSL_get_error(ssl, n);
  5222. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5223. err = ERRNO;
  5224. } else if ((err == SSL_ERROR_WANT_READ)
  5225. || (err == SSL_ERROR_WANT_WRITE)) {
  5226. n = 0;
  5227. } else {
  5228. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5229. return -2;
  5230. }
  5231. } else {
  5232. err = 0;
  5233. }
  5234. } else
  5235. #endif
  5236. if (fp != NULL) {
  5237. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5238. if (ferror(fp)) {
  5239. n = -1;
  5240. err = ERRNO;
  5241. } else {
  5242. err = 0;
  5243. }
  5244. } else {
  5245. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5246. err = (n < 0) ? ERRNO : 0;
  5247. #if defined(_WIN32)
  5248. if (err == WSAEWOULDBLOCK) {
  5249. err = 0;
  5250. n = 0;
  5251. }
  5252. #else
  5253. if (err == EWOULDBLOCK) {
  5254. err = 0;
  5255. n = 0;
  5256. }
  5257. #endif
  5258. if (n < 0) {
  5259. /* shutdown of the socket at client side */
  5260. return -2;
  5261. }
  5262. }
  5263. if (ctx->stop_flag) {
  5264. return -2;
  5265. }
  5266. if ((n > 0) || ((n == 0) && (len == 0))) {
  5267. /* some data has been read, or no data was requested */
  5268. return n;
  5269. }
  5270. if (n < 0) {
  5271. /* socket error - check errno */
  5272. DEBUG_TRACE("send() failed, error %d", err);
  5273. /* TODO (mid): error handling depending on the error code.
  5274. * These codes are different between Windows and Linux.
  5275. * Currently there is no problem with failing send calls,
  5276. * if there is a reproducible situation, it should be
  5277. * investigated in detail.
  5278. */
  5279. return -2;
  5280. }
  5281. /* Only in case n=0 (timeout), repeat calling the write function */
  5282. /* If send failed, wait before retry */
  5283. if (fp != NULL) {
  5284. /* For files, just wait a fixed time.
  5285. * Maybe it helps, maybe not. */
  5286. mg_sleep(5);
  5287. } else {
  5288. /* For sockets, wait for the socket using poll */
  5289. struct mg_pollfd pfd[1];
  5290. int pollres;
  5291. pfd[0].fd = sock;
  5292. pfd[0].events = POLLOUT;
  5293. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5294. if (ctx->stop_flag) {
  5295. return -2;
  5296. }
  5297. if (pollres > 0) {
  5298. continue;
  5299. }
  5300. }
  5301. if (timeout > 0) {
  5302. now = mg_get_current_time_ns();
  5303. if ((now - start) > timeout_ns) {
  5304. /* Timeout */
  5305. break;
  5306. }
  5307. }
  5308. }
  5309. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5310. used */
  5311. return -1;
  5312. }
  5313. static int
  5314. push_all(struct mg_context *ctx,
  5315. FILE *fp,
  5316. SOCKET sock,
  5317. SSL *ssl,
  5318. const char *buf,
  5319. int len)
  5320. {
  5321. double timeout = -1.0;
  5322. int n, nwritten = 0;
  5323. if (ctx == NULL) {
  5324. return -1;
  5325. }
  5326. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5327. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5328. }
  5329. while ((len > 0) && (ctx->stop_flag == 0)) {
  5330. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5331. if (n < 0) {
  5332. if (nwritten == 0) {
  5333. nwritten = -1; /* Propagate the error */
  5334. }
  5335. break;
  5336. } else if (n == 0) {
  5337. break; /* No more data to write */
  5338. } else {
  5339. nwritten += n;
  5340. len -= n;
  5341. }
  5342. }
  5343. return nwritten;
  5344. }
  5345. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5346. * Return value:
  5347. * >=0 .. number of bytes successfully read
  5348. * -1 .. timeout
  5349. * -2 .. error
  5350. */
  5351. static int
  5352. pull_inner(FILE *fp,
  5353. struct mg_connection *conn,
  5354. char *buf,
  5355. int len,
  5356. double timeout)
  5357. {
  5358. int nread, err = 0;
  5359. #if defined(_WIN32)
  5360. typedef int len_t;
  5361. #else
  5362. typedef size_t len_t;
  5363. #endif
  5364. #if !defined(NO_SSL)
  5365. int ssl_pending;
  5366. #endif
  5367. /* We need an additional wait loop around this, because in some cases
  5368. * with TLSwe may get data from the socket but not from SSL_read.
  5369. * In this case we need to repeat at least once.
  5370. */
  5371. if (fp != NULL) {
  5372. #if !defined(_WIN32_WCE)
  5373. /* Use read() instead of fread(), because if we're reading from the
  5374. * CGI pipe, fread() may block until IO buffer is filled up. We
  5375. * cannot afford to block and must pass all read bytes immediately
  5376. * to the client. */
  5377. nread = (int)read(fileno(fp), buf, (size_t)len);
  5378. #else
  5379. /* WinCE does not support CGI pipes */
  5380. nread = (int)fread(buf, 1, (size_t)len, fp);
  5381. #endif
  5382. err = (nread < 0) ? ERRNO : 0;
  5383. if ((nread == 0) && (len > 0)) {
  5384. /* Should get data, but got EOL */
  5385. return -2;
  5386. }
  5387. #if !defined(NO_SSL)
  5388. } else if ((conn->ssl != NULL)
  5389. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5390. /* We already know there is no more data buffered in conn->buf
  5391. * but there is more available in the SSL layer. So don't poll
  5392. * conn->client.sock yet. */
  5393. if (ssl_pending > len) {
  5394. ssl_pending = len;
  5395. }
  5396. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5397. if (nread <= 0) {
  5398. err = SSL_get_error(conn->ssl, nread);
  5399. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5400. err = ERRNO;
  5401. } else if ((err == SSL_ERROR_WANT_READ)
  5402. || (err == SSL_ERROR_WANT_WRITE)) {
  5403. nread = 0;
  5404. } else {
  5405. /* All errors should return -2 */
  5406. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5407. return -2;
  5408. }
  5409. ERR_clear_error();
  5410. } else {
  5411. err = 0;
  5412. }
  5413. } else if (conn->ssl != NULL) {
  5414. struct mg_pollfd pfd[1];
  5415. int pollres;
  5416. pfd[0].fd = conn->client.sock;
  5417. pfd[0].events = POLLIN;
  5418. pollres = mg_poll(pfd,
  5419. 1,
  5420. (int)(timeout * 1000.0),
  5421. &(conn->phys_ctx->stop_flag));
  5422. if (conn->phys_ctx->stop_flag) {
  5423. return -2;
  5424. }
  5425. if (pollres > 0) {
  5426. nread = SSL_read(conn->ssl, buf, len);
  5427. if (nread <= 0) {
  5428. err = SSL_get_error(conn->ssl, nread);
  5429. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5430. err = ERRNO;
  5431. } else if ((err == SSL_ERROR_WANT_READ)
  5432. || (err == SSL_ERROR_WANT_WRITE)) {
  5433. nread = 0;
  5434. } else {
  5435. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5436. return -2;
  5437. }
  5438. } else {
  5439. err = 0;
  5440. }
  5441. ERR_clear_error();
  5442. } else if (pollres < 0) {
  5443. /* Error */
  5444. return -2;
  5445. } else {
  5446. /* pollres = 0 means timeout */
  5447. nread = 0;
  5448. }
  5449. #endif
  5450. } else {
  5451. struct mg_pollfd pfd[1];
  5452. int pollres;
  5453. pfd[0].fd = conn->client.sock;
  5454. pfd[0].events = POLLIN;
  5455. pollres = mg_poll(pfd,
  5456. 1,
  5457. (int)(timeout * 1000.0),
  5458. &(conn->phys_ctx->stop_flag));
  5459. if (conn->phys_ctx->stop_flag) {
  5460. return -2;
  5461. }
  5462. if (pollres > 0) {
  5463. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5464. err = (nread < 0) ? ERRNO : 0;
  5465. if (nread <= 0) {
  5466. /* shutdown of the socket at client side */
  5467. return -2;
  5468. }
  5469. } else if (pollres < 0) {
  5470. /* error callint poll */
  5471. return -2;
  5472. } else {
  5473. /* pollres = 0 means timeout */
  5474. nread = 0;
  5475. }
  5476. }
  5477. if (conn->phys_ctx->stop_flag) {
  5478. return -2;
  5479. }
  5480. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5481. /* some data has been read, or no data was requested */
  5482. return nread;
  5483. }
  5484. if (nread < 0) {
  5485. /* socket error - check errno */
  5486. #if defined(_WIN32)
  5487. if (err == WSAEWOULDBLOCK) {
  5488. /* TODO (low): check if this is still required */
  5489. /* standard case if called from close_socket_gracefully */
  5490. return -2;
  5491. } else if (err == WSAETIMEDOUT) {
  5492. /* TODO (low): check if this is still required */
  5493. /* timeout is handled by the while loop */
  5494. return 0;
  5495. } else if (err == WSAECONNABORTED) {
  5496. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5497. return -2;
  5498. } else {
  5499. DEBUG_TRACE("recv() failed, error %d", err);
  5500. return -2;
  5501. }
  5502. #else
  5503. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5504. * if the timeout is reached and if the socket was set to non-
  5505. * blocking in close_socket_gracefully, so we can not distinguish
  5506. * here. We have to wait for the timeout in both cases for now.
  5507. */
  5508. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5509. /* TODO (low): check if this is still required */
  5510. /* EAGAIN/EWOULDBLOCK:
  5511. * standard case if called from close_socket_gracefully
  5512. * => should return -1 */
  5513. /* or timeout occurred
  5514. * => the code must stay in the while loop */
  5515. /* EINTR can be generated on a socket with a timeout set even
  5516. * when SA_RESTART is effective for all relevant signals
  5517. * (see signal(7)).
  5518. * => stay in the while loop */
  5519. } else {
  5520. DEBUG_TRACE("recv() failed, error %d", err);
  5521. return -2;
  5522. }
  5523. #endif
  5524. }
  5525. /* Timeout occurred, but no data available. */
  5526. return -1;
  5527. }
  5528. static int
  5529. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5530. {
  5531. int n, nread = 0;
  5532. double timeout = -1.0;
  5533. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5534. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5535. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5536. }
  5537. if (timeout >= 0.0) {
  5538. start_time = mg_get_current_time_ns();
  5539. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5540. }
  5541. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5542. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5543. if (n == -2) {
  5544. if (nread == 0) {
  5545. nread = -1; /* Propagate the error */
  5546. }
  5547. break;
  5548. } else if (n == -1) {
  5549. /* timeout */
  5550. if (timeout >= 0.0) {
  5551. now = mg_get_current_time_ns();
  5552. if ((now - start_time) <= timeout_ns) {
  5553. continue;
  5554. }
  5555. }
  5556. break;
  5557. } else if (n == 0) {
  5558. break; /* No more data to read */
  5559. } else {
  5560. nread += n;
  5561. len -= n;
  5562. }
  5563. }
  5564. return nread;
  5565. }
  5566. static void
  5567. discard_unread_request_data(struct mg_connection *conn)
  5568. {
  5569. char buf[MG_BUF_LEN];
  5570. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5571. ;
  5572. }
  5573. static int
  5574. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5575. {
  5576. int64_t content_len, n, buffered_len, nread;
  5577. int64_t len64 =
  5578. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5579. * int, we may not read more
  5580. * bytes */
  5581. const char *body;
  5582. if (conn == NULL) {
  5583. return 0;
  5584. }
  5585. /* If Content-Length is not set for a response with body data,
  5586. * we do not know in advance how much data should be read. */
  5587. content_len = conn->content_len;
  5588. if (content_len < 0) {
  5589. /* The body data is completed when the connection is closed. */
  5590. content_len = INT64_MAX;
  5591. }
  5592. nread = 0;
  5593. if (conn->consumed_content < content_len) {
  5594. /* Adjust number of bytes to read. */
  5595. int64_t left_to_read = content_len - conn->consumed_content;
  5596. if (left_to_read < len64) {
  5597. /* Do not read more than the total content length of the
  5598. * request.
  5599. */
  5600. len64 = left_to_read;
  5601. }
  5602. /* Return buffered data */
  5603. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5604. - conn->consumed_content;
  5605. if (buffered_len > 0) {
  5606. if (len64 < buffered_len) {
  5607. buffered_len = len64;
  5608. }
  5609. body = conn->buf + conn->request_len + conn->consumed_content;
  5610. memcpy(buf, body, (size_t)buffered_len);
  5611. len64 -= buffered_len;
  5612. conn->consumed_content += buffered_len;
  5613. nread += buffered_len;
  5614. buf = (char *)buf + buffered_len;
  5615. }
  5616. /* We have returned all buffered data. Read new data from the remote
  5617. * socket.
  5618. */
  5619. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5620. conn->consumed_content += n;
  5621. nread += n;
  5622. } else {
  5623. nread = ((nread > 0) ? nread : n);
  5624. }
  5625. }
  5626. return (int)nread;
  5627. }
  5628. int
  5629. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5630. {
  5631. if (len > INT_MAX) {
  5632. len = INT_MAX;
  5633. }
  5634. if (conn == NULL) {
  5635. return 0;
  5636. }
  5637. if (conn->is_chunked) {
  5638. size_t all_read = 0;
  5639. while (len > 0) {
  5640. if (conn->is_chunked >= 3) {
  5641. /* No more data left to read */
  5642. return 0;
  5643. }
  5644. if (conn->is_chunked != 1) {
  5645. /* Has error */
  5646. return -1;
  5647. }
  5648. if (conn->consumed_content != conn->content_len) {
  5649. /* copy from the current chunk */
  5650. int read_ret = mg_read_inner(conn, (char *)buf + all_read,
  5651. len);
  5652. if (read_ret < 1) {
  5653. /* read error */
  5654. conn->is_chunked = 2;
  5655. return -1;
  5656. }
  5657. all_read += (size_t)read_ret;
  5658. len -= (size_t)read_ret;
  5659. if (conn->consumed_content == conn->content_len) {
  5660. /* Add data bytes in the current chunk have been read,
  5661. * so we are expecting \r\n now. */
  5662. char x[2];
  5663. conn->content_len += 2;
  5664. if ((mg_read_inner(conn, x, 2) != 2)
  5665. || (x[0] != '\r') || (x[1] != '\n')) {
  5666. /* Protocol violation */
  5667. conn->is_chunked = 2;
  5668. return -1;
  5669. }
  5670. }
  5671. } else {
  5672. /* fetch a new chunk */
  5673. size_t i;
  5674. char lenbuf[64];
  5675. char *end = NULL;
  5676. unsigned long chunkSize = 0;
  5677. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5678. conn->content_len++;
  5679. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5680. lenbuf[i] = 0;
  5681. }
  5682. if ((i > 0) && (lenbuf[i] == '\r')
  5683. && (lenbuf[i - 1] != '\r')) {
  5684. continue;
  5685. }
  5686. if ((i > 1) && (lenbuf[i] == '\n')
  5687. && (lenbuf[i - 1] == '\r')) {
  5688. lenbuf[i + 1] = 0;
  5689. chunkSize = strtoul(lenbuf, &end, 16);
  5690. if (chunkSize == 0) {
  5691. /* regular end of content */
  5692. conn->is_chunked = 3;
  5693. }
  5694. break;
  5695. }
  5696. if (!isxdigit((unsigned char)lenbuf[i])) {
  5697. /* illegal character for chunk length */
  5698. conn->is_chunked = 2;
  5699. return -1;
  5700. }
  5701. }
  5702. if ((end == NULL) || (*end != '\r')) {
  5703. /* chunksize not set correctly */
  5704. conn->is_chunked = 2;
  5705. return -1;
  5706. }
  5707. if (chunkSize == 0) {
  5708. /* try discarding trailer for keep-alive */
  5709. conn->content_len += 2;
  5710. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5711. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5712. conn->is_chunked = 4;
  5713. }
  5714. break;
  5715. }
  5716. /* append a new chunk */
  5717. conn->content_len += chunkSize;
  5718. }
  5719. }
  5720. return (int)all_read;
  5721. }
  5722. return mg_read_inner(conn, buf, len);
  5723. }
  5724. int
  5725. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5726. {
  5727. time_t now;
  5728. int n, total, allowed;
  5729. if (conn == NULL) {
  5730. return 0;
  5731. }
  5732. if (len > INT_MAX) {
  5733. return -1;
  5734. }
  5735. if (conn->throttle > 0) {
  5736. if ((now = time(NULL)) != conn->last_throttle_time) {
  5737. conn->last_throttle_time = now;
  5738. conn->last_throttle_bytes = 0;
  5739. }
  5740. allowed = conn->throttle - conn->last_throttle_bytes;
  5741. if (allowed > (int)len) {
  5742. allowed = (int)len;
  5743. }
  5744. if ((total = push_all(conn->phys_ctx,
  5745. NULL,
  5746. conn->client.sock,
  5747. conn->ssl,
  5748. (const char *)buf,
  5749. allowed))
  5750. == allowed) {
  5751. buf = (const char *)buf + total;
  5752. conn->last_throttle_bytes += total;
  5753. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5754. allowed = (conn->throttle > ((int)len - total))
  5755. ? (int)len - total
  5756. : conn->throttle;
  5757. if ((n = push_all(conn->phys_ctx,
  5758. NULL,
  5759. conn->client.sock,
  5760. conn->ssl,
  5761. (const char *)buf,
  5762. allowed))
  5763. != allowed) {
  5764. break;
  5765. }
  5766. sleep(1);
  5767. conn->last_throttle_bytes = allowed;
  5768. conn->last_throttle_time = time(NULL);
  5769. buf = (const char *)buf + n;
  5770. total += n;
  5771. }
  5772. }
  5773. } else {
  5774. total = push_all(conn->phys_ctx,
  5775. NULL,
  5776. conn->client.sock,
  5777. conn->ssl,
  5778. (const char *)buf,
  5779. (int)len);
  5780. }
  5781. if (total > 0) {
  5782. conn->num_bytes_sent += total;
  5783. }
  5784. return total;
  5785. }
  5786. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5787. int
  5788. mg_send_chunk(struct mg_connection *conn,
  5789. const char *chunk,
  5790. unsigned int chunk_len)
  5791. {
  5792. char lenbuf[16];
  5793. size_t lenbuf_len;
  5794. int ret;
  5795. int t;
  5796. /* First store the length information in a text buffer. */
  5797. sprintf(lenbuf, "%x\r\n", chunk_len);
  5798. lenbuf_len = strlen(lenbuf);
  5799. /* Then send length information, chunk and terminating \r\n. */
  5800. ret = mg_write(conn, lenbuf, lenbuf_len);
  5801. if (ret != (int)lenbuf_len) {
  5802. return -1;
  5803. }
  5804. t = ret;
  5805. ret = mg_write(conn, chunk, chunk_len);
  5806. if (ret != (int)chunk_len) {
  5807. return -1;
  5808. }
  5809. t += ret;
  5810. ret = mg_write(conn, "\r\n", 2);
  5811. if (ret != 2) {
  5812. return -1;
  5813. }
  5814. t += ret;
  5815. return t;
  5816. }
  5817. #if defined(GCC_DIAGNOSTIC)
  5818. /* This block forwards format strings to printf implementations,
  5819. * so we need to disable the format-nonliteral warning. */
  5820. #pragma GCC diagnostic push
  5821. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5822. #endif
  5823. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5824. static int
  5825. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5826. {
  5827. va_list ap_copy;
  5828. size_t size = MG_BUF_LEN / 4;
  5829. int len = -1;
  5830. *buf = NULL;
  5831. while (len < 0) {
  5832. if (*buf) {
  5833. mg_free(*buf);
  5834. }
  5835. size *= 4;
  5836. *buf = (char *)mg_malloc(size);
  5837. if (!*buf) {
  5838. break;
  5839. }
  5840. va_copy(ap_copy, ap);
  5841. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5842. va_end(ap_copy);
  5843. (*buf)[size - 1] = 0;
  5844. }
  5845. return len;
  5846. }
  5847. /* Print message to buffer. If buffer is large enough to hold the message,
  5848. * return buffer. If buffer is to small, allocate large enough buffer on
  5849. * heap,
  5850. * and return allocated buffer. */
  5851. static int
  5852. alloc_vprintf(char **out_buf,
  5853. char *prealloc_buf,
  5854. size_t prealloc_size,
  5855. const char *fmt,
  5856. va_list ap)
  5857. {
  5858. va_list ap_copy;
  5859. int len;
  5860. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5861. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5862. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5863. * Therefore, we make two passes: on first pass, get required message
  5864. * length.
  5865. * On second pass, actually print the message. */
  5866. va_copy(ap_copy, ap);
  5867. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5868. va_end(ap_copy);
  5869. if (len < 0) {
  5870. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5871. * Switch to alternative code path that uses incremental
  5872. * allocations.
  5873. */
  5874. va_copy(ap_copy, ap);
  5875. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5876. va_end(ap_copy);
  5877. } else if ((size_t)(len) >= prealloc_size) {
  5878. /* The pre-allocated buffer not large enough. */
  5879. /* Allocate a new buffer. */
  5880. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5881. if (!*out_buf) {
  5882. /* Allocation failed. Return -1 as "out of memory" error. */
  5883. return -1;
  5884. }
  5885. /* Buffer allocation successful. Store the string there. */
  5886. va_copy(ap_copy, ap);
  5887. IGNORE_UNUSED_RESULT(
  5888. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5889. va_end(ap_copy);
  5890. } else {
  5891. /* The pre-allocated buffer is large enough.
  5892. * Use it to store the string and return the address. */
  5893. va_copy(ap_copy, ap);
  5894. IGNORE_UNUSED_RESULT(
  5895. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5896. va_end(ap_copy);
  5897. *out_buf = prealloc_buf;
  5898. }
  5899. return len;
  5900. }
  5901. #if defined(GCC_DIAGNOSTIC)
  5902. /* Enable format-nonliteral warning again. */
  5903. #pragma GCC diagnostic pop
  5904. #endif
  5905. static int
  5906. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5907. {
  5908. char mem[MG_BUF_LEN];
  5909. char *buf = NULL;
  5910. int len;
  5911. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5912. len = mg_write(conn, buf, (size_t)len);
  5913. }
  5914. if (buf != mem) {
  5915. mg_free(buf);
  5916. }
  5917. return len;
  5918. }
  5919. int
  5920. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5921. {
  5922. va_list ap;
  5923. int result;
  5924. va_start(ap, fmt);
  5925. result = mg_vprintf(conn, fmt, ap);
  5926. va_end(ap);
  5927. return result;
  5928. }
  5929. int
  5930. mg_url_decode(const char *src,
  5931. int src_len,
  5932. char *dst,
  5933. int dst_len,
  5934. int is_form_url_encoded)
  5935. {
  5936. int i, j, a, b;
  5937. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5938. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5939. if ((i < src_len - 2) && (src[i] == '%')
  5940. && isxdigit((unsigned char)src[i + 1])
  5941. && isxdigit((unsigned char)src[i + 2])) {
  5942. a = tolower((unsigned char)src[i + 1]);
  5943. b = tolower((unsigned char)src[i + 2]);
  5944. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5945. i += 2;
  5946. } else if (is_form_url_encoded && (src[i] == '+')) {
  5947. dst[j] = ' ';
  5948. } else {
  5949. dst[j] = src[i];
  5950. }
  5951. }
  5952. dst[j] = '\0'; /* Null-terminate the destination */
  5953. return (i >= src_len) ? j : -1;
  5954. }
  5955. int
  5956. mg_get_var(const char *data,
  5957. size_t data_len,
  5958. const char *name,
  5959. char *dst,
  5960. size_t dst_len)
  5961. {
  5962. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5963. }
  5964. int
  5965. mg_get_var2(const char *data,
  5966. size_t data_len,
  5967. const char *name,
  5968. char *dst,
  5969. size_t dst_len,
  5970. size_t occurrence)
  5971. {
  5972. const char *p, *e, *s;
  5973. size_t name_len;
  5974. int len;
  5975. if ((dst == NULL) || (dst_len == 0)) {
  5976. len = -2;
  5977. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5978. len = -1;
  5979. dst[0] = '\0';
  5980. } else {
  5981. name_len = strlen(name);
  5982. e = data + data_len;
  5983. len = -1;
  5984. dst[0] = '\0';
  5985. /* data is "var1=val1&var2=val2...". Find variable first */
  5986. for (p = data; p + name_len < e; p++) {
  5987. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5988. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5989. /* Point p to variable value */
  5990. p += name_len + 1;
  5991. /* Point s to the end of the value */
  5992. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5993. if (s == NULL) {
  5994. s = e;
  5995. }
  5996. DEBUG_ASSERT(s >= p);
  5997. if (s < p) {
  5998. return -3;
  5999. }
  6000. /* Decode variable into destination buffer */
  6001. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6002. /* Redirect error code from -1 to -2 (destination buffer too
  6003. * small). */
  6004. if (len == -1) {
  6005. len = -2;
  6006. }
  6007. break;
  6008. }
  6009. }
  6010. }
  6011. return len;
  6012. }
  6013. /* HCP24: some changes to compare hole var_name */
  6014. int
  6015. mg_get_cookie(const char *cookie_header,
  6016. const char *var_name,
  6017. char *dst,
  6018. size_t dst_size)
  6019. {
  6020. const char *s, *p, *end;
  6021. int name_len, len = -1;
  6022. if ((dst == NULL) || (dst_size == 0)) {
  6023. return -2;
  6024. }
  6025. dst[0] = '\0';
  6026. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6027. return -1;
  6028. }
  6029. name_len = (int)strlen(var_name);
  6030. end = s + strlen(s);
  6031. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6032. if (s[name_len] == '=') {
  6033. /* HCP24: now check is it a substring or a full cookie name */
  6034. if ((s == cookie_header) || (s[-1] == ' ')) {
  6035. s += name_len + 1;
  6036. if ((p = strchr(s, ' ')) == NULL) {
  6037. p = end;
  6038. }
  6039. if (p[-1] == ';') {
  6040. p--;
  6041. }
  6042. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6043. s++;
  6044. p--;
  6045. }
  6046. if ((size_t)(p - s) < dst_size) {
  6047. len = (int)(p - s);
  6048. mg_strlcpy(dst, s, (size_t)len + 1);
  6049. } else {
  6050. len = -3;
  6051. }
  6052. break;
  6053. }
  6054. }
  6055. }
  6056. return len;
  6057. }
  6058. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6059. static void
  6060. base64_encode(const unsigned char *src, int src_len, char *dst)
  6061. {
  6062. static const char *b64 =
  6063. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6064. int i, j, a, b, c;
  6065. for (i = j = 0; i < src_len; i += 3) {
  6066. a = src[i];
  6067. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6068. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6069. dst[j++] = b64[a >> 2];
  6070. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6071. if (i + 1 < src_len) {
  6072. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6073. }
  6074. if (i + 2 < src_len) {
  6075. dst[j++] = b64[c & 63];
  6076. }
  6077. }
  6078. while (j % 4 != 0) {
  6079. dst[j++] = '=';
  6080. }
  6081. dst[j++] = '\0';
  6082. }
  6083. #endif
  6084. #if defined(USE_LUA)
  6085. static unsigned char
  6086. b64reverse(char letter)
  6087. {
  6088. if ((letter >= 'A') && (letter <= 'Z')) {
  6089. return letter - 'A';
  6090. }
  6091. if ((letter >= 'a') && (letter <= 'z')) {
  6092. return letter - 'a' + 26;
  6093. }
  6094. if ((letter >= '0') && (letter <= '9')) {
  6095. return letter - '0' + 52;
  6096. }
  6097. if (letter == '+') {
  6098. return 62;
  6099. }
  6100. if (letter == '/') {
  6101. return 63;
  6102. }
  6103. if (letter == '=') {
  6104. return 255; /* normal end */
  6105. }
  6106. return 254; /* error */
  6107. }
  6108. static int
  6109. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6110. {
  6111. int i;
  6112. unsigned char a, b, c, d;
  6113. *dst_len = 0;
  6114. for (i = 0; i < src_len; i += 4) {
  6115. a = b64reverse(src[i]);
  6116. if (a >= 254) {
  6117. return i;
  6118. }
  6119. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6120. if (b >= 254) {
  6121. return i + 1;
  6122. }
  6123. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6124. if (c == 254) {
  6125. return i + 2;
  6126. }
  6127. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6128. if (d == 254) {
  6129. return i + 3;
  6130. }
  6131. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6132. if (c != 255) {
  6133. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6134. if (d != 255) {
  6135. dst[(*dst_len)++] = (c << 6) + d;
  6136. }
  6137. }
  6138. }
  6139. return -1;
  6140. }
  6141. #endif
  6142. static int
  6143. is_put_or_delete_method(const struct mg_connection *conn)
  6144. {
  6145. if (conn) {
  6146. const char *s = conn->request_info.request_method;
  6147. return (s != NULL)
  6148. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6149. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6150. }
  6151. return 0;
  6152. }
  6153. #if !defined(NO_FILES)
  6154. static int
  6155. extention_matches_script(
  6156. struct mg_connection *conn, /* in: request (must be valid) */
  6157. const char *filename /* in: filename (must be valid) */
  6158. )
  6159. {
  6160. #if !defined(NO_CGI)
  6161. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6162. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6163. filename)
  6164. > 0) {
  6165. return 1;
  6166. }
  6167. #endif
  6168. #if defined(USE_LUA)
  6169. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6170. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6171. filename)
  6172. > 0) {
  6173. return 1;
  6174. }
  6175. #endif
  6176. #if defined(USE_DUKTAPE)
  6177. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6178. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6179. filename)
  6180. > 0) {
  6181. return 1;
  6182. }
  6183. #endif
  6184. /* filename and conn could be unused, if all preocessor conditions
  6185. * are false (no script language supported). */
  6186. (void)filename;
  6187. (void)conn;
  6188. return 0;
  6189. }
  6190. /* For given directory path, substitute it to valid index file.
  6191. * Return 1 if index file has been found, 0 if not found.
  6192. * If the file is found, it's stats is returned in stp. */
  6193. static int
  6194. substitute_index_file(struct mg_connection *conn,
  6195. char *path,
  6196. size_t path_len,
  6197. struct mg_file_stat *filestat)
  6198. {
  6199. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6200. struct vec filename_vec;
  6201. size_t n = strlen(path);
  6202. int found = 0;
  6203. /* The 'path' given to us points to the directory. Remove all trailing
  6204. * directory separator characters from the end of the path, and
  6205. * then append single directory separator character. */
  6206. while ((n > 0) && (path[n - 1] == '/')) {
  6207. n--;
  6208. }
  6209. path[n] = '/';
  6210. /* Traverse index files list. For each entry, append it to the given
  6211. * path and see if the file exists. If it exists, break the loop */
  6212. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6213. /* Ignore too long entries that may overflow path buffer */
  6214. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6215. continue;
  6216. }
  6217. /* Prepare full path to the index file */
  6218. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6219. /* Does it exist? */
  6220. if (mg_stat(conn, path, filestat)) {
  6221. /* Yes it does, break the loop */
  6222. found = 1;
  6223. break;
  6224. }
  6225. }
  6226. /* If no index file exists, restore directory path */
  6227. if (!found) {
  6228. path[n] = '\0';
  6229. }
  6230. return found;
  6231. }
  6232. #endif
  6233. static void
  6234. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6235. char *filename, /* out: filename */
  6236. size_t filename_buf_len, /* in: size of filename buffer */
  6237. struct mg_file_stat *filestat, /* out: file status structure */
  6238. int *is_found, /* out: file found (directly) */
  6239. int *is_script_resource, /* out: handled by a script? */
  6240. int *is_websocket_request, /* out: websocket connetion? */
  6241. int *is_put_or_delete_request /* out: put/delete a file? */
  6242. )
  6243. {
  6244. char const *accept_encoding;
  6245. #if !defined(NO_FILES)
  6246. const char *uri = conn->request_info.local_uri;
  6247. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6248. const char *rewrite;
  6249. struct vec a, b;
  6250. ptrdiff_t match_len;
  6251. char gz_path[PATH_MAX];
  6252. int truncated;
  6253. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6254. char *tmp_str;
  6255. size_t tmp_str_len, sep_pos;
  6256. int allow_substitute_script_subresources;
  6257. #endif
  6258. #else
  6259. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6260. #endif
  6261. /* Step 1: Set all initially unknown outputs to zero */
  6262. memset(filestat, 0, sizeof(*filestat));
  6263. *filename = 0;
  6264. *is_found = 0;
  6265. *is_script_resource = 0;
  6266. /* Step 2: Check if the request attempts to modify the file system */
  6267. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6268. /* Step 3: Check if it is a websocket request, and modify the document
  6269. * root if required */
  6270. #if defined(USE_WEBSOCKET)
  6271. *is_websocket_request = is_websocket_protocol(conn);
  6272. #if !defined(NO_FILES)
  6273. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6274. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6275. }
  6276. #endif /* !NO_FILES */
  6277. #else /* USE_WEBSOCKET */
  6278. *is_websocket_request = 0;
  6279. #endif /* USE_WEBSOCKET */
  6280. /* Step 4: Check if gzip encoded response is allowed */
  6281. conn->accept_gzip = 0;
  6282. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6283. if (strstr(accept_encoding, "gzip") != NULL) {
  6284. conn->accept_gzip = 1;
  6285. }
  6286. }
  6287. #if !defined(NO_FILES)
  6288. /* Step 5: If there is no root directory, don't look for files. */
  6289. /* Note that root == NULL is a regular use case here. This occurs,
  6290. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6291. * config is not required. */
  6292. if (root == NULL) {
  6293. /* all file related outputs have already been set to 0, just return
  6294. */
  6295. return;
  6296. }
  6297. /* Step 6: Determine the local file path from the root path and the
  6298. * request uri. */
  6299. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6300. * part of the path one byte on the right. */
  6301. mg_snprintf(
  6302. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6303. if (truncated) {
  6304. goto interpret_cleanup;
  6305. }
  6306. /* Step 7: URI rewriting */
  6307. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6308. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6309. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6310. mg_snprintf(conn,
  6311. &truncated,
  6312. filename,
  6313. filename_buf_len - 1,
  6314. "%.*s%s",
  6315. (int)b.len,
  6316. b.ptr,
  6317. uri + match_len);
  6318. break;
  6319. }
  6320. }
  6321. if (truncated) {
  6322. goto interpret_cleanup;
  6323. }
  6324. /* Step 8: Check if the file exists at the server */
  6325. /* Local file path and name, corresponding to requested URI
  6326. * is now stored in "filename" variable. */
  6327. if (mg_stat(conn, filename, filestat)) {
  6328. int uri_len = (int)strlen(uri);
  6329. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6330. /* 8.1: File exists. */
  6331. *is_found = 1;
  6332. /* 8.2: Check if it is a script type. */
  6333. if (extention_matches_script(conn, filename)) {
  6334. /* The request addresses a CGI resource, Lua script or
  6335. * server-side javascript.
  6336. * The URI corresponds to the script itself (like
  6337. * /path/script.cgi), and there is no additional resource
  6338. * path (like /path/script.cgi/something).
  6339. * Requests that modify (replace or delete) a resource, like
  6340. * PUT and DELETE requests, should replace/delete the script
  6341. * file.
  6342. * Requests that read or write from/to a resource, like GET and
  6343. * POST requests, should call the script and return the
  6344. * generated response. */
  6345. *is_script_resource = (!*is_put_or_delete_request);
  6346. }
  6347. /* 8.3: If the request target is a directory, there could be
  6348. * a substitute file (index.html, index.cgi, ...). */
  6349. if (filestat->is_directory && is_uri_end_slash) {
  6350. /* Use a local copy here, since substitute_index_file will
  6351. * change the content of the file status */
  6352. struct mg_file_stat tmp_filestat;
  6353. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6354. if (substitute_index_file(
  6355. conn, filename, filename_buf_len, &tmp_filestat)) {
  6356. /* Substitute file found. Copy stat to the output, then
  6357. * check if the file is a script file */
  6358. *filestat = tmp_filestat;
  6359. if (extention_matches_script(conn, filename)) {
  6360. /* Substitute file is a script file */
  6361. *is_script_resource = 1;
  6362. } else {
  6363. /* Substitute file is a regular file */
  6364. *is_script_resource = 0;
  6365. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6366. }
  6367. }
  6368. /* If there is no substitute file, the server could return
  6369. * a directory listing in a later step */
  6370. }
  6371. return;
  6372. }
  6373. /* Step 9: Check for zipped files: */
  6374. /* If we can't find the actual file, look for the file
  6375. * with the same name but a .gz extension. If we find it,
  6376. * use that and set the gzipped flag in the file struct
  6377. * to indicate that the response need to have the content-
  6378. * encoding: gzip header.
  6379. * We can only do this if the browser declares support. */
  6380. if (conn->accept_gzip) {
  6381. mg_snprintf(
  6382. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6383. if (truncated) {
  6384. goto interpret_cleanup;
  6385. }
  6386. if (mg_stat(conn, gz_path, filestat)) {
  6387. if (filestat) {
  6388. filestat->is_gzipped = 1;
  6389. *is_found = 1;
  6390. }
  6391. /* Currently gz files can not be scripts. */
  6392. return;
  6393. }
  6394. }
  6395. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6396. /* Step 10: Script resources may handle sub-resources */
  6397. /* Support PATH_INFO for CGI scripts. */
  6398. tmp_str_len = strlen(filename);
  6399. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6400. if (!tmp_str) {
  6401. /* Out of memory */
  6402. goto interpret_cleanup;
  6403. }
  6404. memcpy(tmp_str, filename, tmp_str_len + 1);
  6405. /* Check config, if index scripts may have sub-resources */
  6406. allow_substitute_script_subresources =
  6407. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6408. "yes");
  6409. sep_pos = tmp_str_len;
  6410. while (sep_pos > 0) {
  6411. sep_pos--;
  6412. if (tmp_str[sep_pos] == '/') {
  6413. int is_script = 0, does_exist = 0;
  6414. tmp_str[sep_pos] = 0;
  6415. if (tmp_str[0]) {
  6416. is_script = extention_matches_script(conn, tmp_str);
  6417. does_exist = mg_stat(conn, tmp_str, filestat);
  6418. }
  6419. if (does_exist && is_script) {
  6420. filename[sep_pos] = 0;
  6421. memmove(filename + sep_pos + 2,
  6422. filename + sep_pos + 1,
  6423. strlen(filename + sep_pos + 1) + 1);
  6424. conn->path_info = filename + sep_pos + 1;
  6425. filename[sep_pos + 1] = '/';
  6426. *is_script_resource = 1;
  6427. *is_found = 1;
  6428. break;
  6429. }
  6430. if (allow_substitute_script_subresources) {
  6431. if (substitute_index_file(
  6432. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6433. /* some intermediate directory has an index file */
  6434. if (extention_matches_script(conn, tmp_str)) {
  6435. char *tmp_str2;
  6436. DEBUG_TRACE("Substitute script %s serving path %s",
  6437. tmp_str,
  6438. filename);
  6439. /* this index file is a script */
  6440. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6441. conn->phys_ctx);
  6442. mg_snprintf(conn,
  6443. &truncated,
  6444. filename,
  6445. filename_buf_len,
  6446. "%s//%s",
  6447. tmp_str,
  6448. tmp_str2);
  6449. mg_free(tmp_str2);
  6450. if (truncated) {
  6451. mg_free(tmp_str);
  6452. goto interpret_cleanup;
  6453. }
  6454. sep_pos = strlen(tmp_str);
  6455. filename[sep_pos] = 0;
  6456. conn->path_info = filename + sep_pos + 1;
  6457. *is_script_resource = 1;
  6458. *is_found = 1;
  6459. break;
  6460. } else {
  6461. DEBUG_TRACE("Substitute file %s serving path %s",
  6462. tmp_str,
  6463. filename);
  6464. /* non-script files will not have sub-resources */
  6465. filename[sep_pos] = 0;
  6466. conn->path_info = 0;
  6467. *is_script_resource = 0;
  6468. *is_found = 0;
  6469. break;
  6470. }
  6471. }
  6472. }
  6473. tmp_str[sep_pos] = '/';
  6474. }
  6475. }
  6476. mg_free(tmp_str);
  6477. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6478. #endif /* !defined(NO_FILES) */
  6479. return;
  6480. #if !defined(NO_FILES)
  6481. /* Reset all outputs */
  6482. interpret_cleanup:
  6483. memset(filestat, 0, sizeof(*filestat));
  6484. *filename = 0;
  6485. *is_found = 0;
  6486. *is_script_resource = 0;
  6487. *is_websocket_request = 0;
  6488. *is_put_or_delete_request = 0;
  6489. #endif /* !defined(NO_FILES) */
  6490. }
  6491. /* Check whether full request is buffered. Return:
  6492. * -1 if request or response is malformed
  6493. * 0 if request or response is not yet fully buffered
  6494. * >0 actual request length, including last \r\n\r\n */
  6495. static int
  6496. get_http_header_len(const char *buf, int buflen)
  6497. {
  6498. int i;
  6499. for (i = 0; i < buflen; i++) {
  6500. /* Do an unsigned comparison in some conditions below */
  6501. const unsigned char c = (unsigned char)buf[i];
  6502. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6503. && !isprint(c)) {
  6504. /* abort scan as soon as one malformed character is found */
  6505. return -1;
  6506. }
  6507. if (i < buflen - 1) {
  6508. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6509. /* Two newline, no carriage return - not standard compliant,
  6510. * but
  6511. * it
  6512. * should be accepted */
  6513. return i + 2;
  6514. }
  6515. }
  6516. if (i < buflen - 3) {
  6517. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6518. && (buf[i + 3] == '\n')) {
  6519. /* Two \r\n - standard compliant */
  6520. return i + 4;
  6521. }
  6522. }
  6523. }
  6524. return 0;
  6525. }
  6526. #if !defined(NO_CACHING)
  6527. /* Convert month to the month number. Return -1 on error, or month number */
  6528. static int
  6529. get_month_index(const char *s)
  6530. {
  6531. size_t i;
  6532. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6533. if (!strcmp(s, month_names[i])) {
  6534. return (int)i;
  6535. }
  6536. }
  6537. return -1;
  6538. }
  6539. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6540. static time_t
  6541. parse_date_string(const char *datetime)
  6542. {
  6543. char month_str[32] = {0};
  6544. int second, minute, hour, day, month, year;
  6545. time_t result = (time_t)0;
  6546. struct tm tm;
  6547. if ((sscanf(datetime,
  6548. "%d/%3s/%d %d:%d:%d",
  6549. &day,
  6550. month_str,
  6551. &year,
  6552. &hour,
  6553. &minute,
  6554. &second)
  6555. == 6)
  6556. || (sscanf(datetime,
  6557. "%d %3s %d %d:%d:%d",
  6558. &day,
  6559. month_str,
  6560. &year,
  6561. &hour,
  6562. &minute,
  6563. &second)
  6564. == 6)
  6565. || (sscanf(datetime,
  6566. "%*3s, %d %3s %d %d:%d:%d",
  6567. &day,
  6568. month_str,
  6569. &year,
  6570. &hour,
  6571. &minute,
  6572. &second)
  6573. == 6)
  6574. || (sscanf(datetime,
  6575. "%d-%3s-%d %d:%d:%d",
  6576. &day,
  6577. month_str,
  6578. &year,
  6579. &hour,
  6580. &minute,
  6581. &second)
  6582. == 6)) {
  6583. month = get_month_index(month_str);
  6584. if ((month >= 0) && (year >= 1970)) {
  6585. memset(&tm, 0, sizeof(tm));
  6586. tm.tm_year = year - 1900;
  6587. tm.tm_mon = month;
  6588. tm.tm_mday = day;
  6589. tm.tm_hour = hour;
  6590. tm.tm_min = minute;
  6591. tm.tm_sec = second;
  6592. result = timegm(&tm);
  6593. }
  6594. }
  6595. return result;
  6596. }
  6597. #endif /* !NO_CACHING */
  6598. /* Protect against directory disclosure attack by removing '..',
  6599. * excessive '/' and '\' characters */
  6600. static void
  6601. remove_double_dots_and_double_slashes(char *s)
  6602. {
  6603. char *p = s;
  6604. while ((s[0] == '.') && (s[1] == '.')) {
  6605. s++;
  6606. }
  6607. while (*s != '\0') {
  6608. *p++ = *s++;
  6609. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6610. /* Skip all following slashes, backslashes and double-dots */
  6611. while (s[0] != '\0') {
  6612. if ((s[0] == '/') || (s[0] == '\\')) {
  6613. s++;
  6614. } else if ((s[0] == '.') && (s[1] == '.')) {
  6615. s += 2;
  6616. } else {
  6617. break;
  6618. }
  6619. }
  6620. }
  6621. }
  6622. *p = '\0';
  6623. }
  6624. static const struct {
  6625. const char *extension;
  6626. size_t ext_len;
  6627. const char *mime_type;
  6628. } builtin_mime_types[] = {
  6629. /* IANA registered MIME types
  6630. * (http://www.iana.org/assignments/media-types)
  6631. * application types */
  6632. {".doc", 4, "application/msword"},
  6633. {".eps", 4, "application/postscript"},
  6634. {".exe", 4, "application/octet-stream"},
  6635. {".js", 3, "application/javascript"},
  6636. {".json", 5, "application/json"},
  6637. {".pdf", 4, "application/pdf"},
  6638. {".ps", 3, "application/postscript"},
  6639. {".rtf", 4, "application/rtf"},
  6640. {".xhtml", 6, "application/xhtml+xml"},
  6641. {".xsl", 4, "application/xml"},
  6642. {".xslt", 5, "application/xml"},
  6643. /* fonts */
  6644. {".ttf", 4, "application/font-sfnt"},
  6645. {".cff", 4, "application/font-sfnt"},
  6646. {".otf", 4, "application/font-sfnt"},
  6647. {".aat", 4, "application/font-sfnt"},
  6648. {".sil", 4, "application/font-sfnt"},
  6649. {".pfr", 4, "application/font-tdpfr"},
  6650. {".woff", 5, "application/font-woff"},
  6651. /* audio */
  6652. {".mp3", 4, "audio/mpeg"},
  6653. {".oga", 4, "audio/ogg"},
  6654. {".ogg", 4, "audio/ogg"},
  6655. /* image */
  6656. {".gif", 4, "image/gif"},
  6657. {".ief", 4, "image/ief"},
  6658. {".jpeg", 5, "image/jpeg"},
  6659. {".jpg", 4, "image/jpeg"},
  6660. {".jpm", 4, "image/jpm"},
  6661. {".jpx", 4, "image/jpx"},
  6662. {".png", 4, "image/png"},
  6663. {".svg", 4, "image/svg+xml"},
  6664. {".tif", 4, "image/tiff"},
  6665. {".tiff", 5, "image/tiff"},
  6666. /* model */
  6667. {".wrl", 4, "model/vrml"},
  6668. /* text */
  6669. {".css", 4, "text/css"},
  6670. {".csv", 4, "text/csv"},
  6671. {".htm", 4, "text/html"},
  6672. {".html", 5, "text/html"},
  6673. {".sgm", 4, "text/sgml"},
  6674. {".shtm", 5, "text/html"},
  6675. {".shtml", 6, "text/html"},
  6676. {".txt", 4, "text/plain"},
  6677. {".xml", 4, "text/xml"},
  6678. /* video */
  6679. {".mov", 4, "video/quicktime"},
  6680. {".mp4", 4, "video/mp4"},
  6681. {".mpeg", 5, "video/mpeg"},
  6682. {".mpg", 4, "video/mpeg"},
  6683. {".ogv", 4, "video/ogg"},
  6684. {".qt", 3, "video/quicktime"},
  6685. /* not registered types
  6686. * (http://reference.sitepoint.com/html/mime-types-full,
  6687. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6688. {".arj", 4, "application/x-arj-compressed"},
  6689. {".gz", 3, "application/x-gunzip"},
  6690. {".rar", 4, "application/x-arj-compressed"},
  6691. {".swf", 4, "application/x-shockwave-flash"},
  6692. {".tar", 4, "application/x-tar"},
  6693. {".tgz", 4, "application/x-tar-gz"},
  6694. {".torrent", 8, "application/x-bittorrent"},
  6695. {".ppt", 4, "application/x-mspowerpoint"},
  6696. {".xls", 4, "application/x-msexcel"},
  6697. {".zip", 4, "application/x-zip-compressed"},
  6698. {".aac",
  6699. 4,
  6700. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6701. {".aif", 4, "audio/x-aif"},
  6702. {".m3u", 4, "audio/x-mpegurl"},
  6703. {".mid", 4, "audio/x-midi"},
  6704. {".ra", 3, "audio/x-pn-realaudio"},
  6705. {".ram", 4, "audio/x-pn-realaudio"},
  6706. {".wav", 4, "audio/x-wav"},
  6707. {".bmp", 4, "image/bmp"},
  6708. {".ico", 4, "image/x-icon"},
  6709. {".pct", 4, "image/x-pct"},
  6710. {".pict", 5, "image/pict"},
  6711. {".rgb", 4, "image/x-rgb"},
  6712. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6713. {".asf", 4, "video/x-ms-asf"},
  6714. {".avi", 4, "video/x-msvideo"},
  6715. {".m4v", 4, "video/x-m4v"},
  6716. {NULL, 0, NULL}};
  6717. const char *
  6718. mg_get_builtin_mime_type(const char *path)
  6719. {
  6720. const char *ext;
  6721. size_t i, path_len;
  6722. path_len = strlen(path);
  6723. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6724. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6725. if ((path_len > builtin_mime_types[i].ext_len)
  6726. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6727. return builtin_mime_types[i].mime_type;
  6728. }
  6729. }
  6730. return "text/plain";
  6731. }
  6732. /* Look at the "path" extension and figure what mime type it has.
  6733. * Store mime type in the vector. */
  6734. static void
  6735. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6736. {
  6737. struct vec ext_vec, mime_vec;
  6738. const char *list, *ext;
  6739. size_t path_len;
  6740. path_len = strlen(path);
  6741. if ((conn == NULL) || (vec == NULL)) {
  6742. if (vec != NULL) {
  6743. memset(vec, '\0', sizeof(struct vec));
  6744. }
  6745. return;
  6746. }
  6747. /* Scan user-defined mime types first, in case user wants to
  6748. * override default mime types. */
  6749. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6750. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6751. /* ext now points to the path suffix */
  6752. ext = path + path_len - ext_vec.len;
  6753. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6754. *vec = mime_vec;
  6755. return;
  6756. }
  6757. }
  6758. vec->ptr = mg_get_builtin_mime_type(path);
  6759. vec->len = strlen(vec->ptr);
  6760. }
  6761. /* Stringify binary data. Output buffer must be twice as big as input,
  6762. * because each byte takes 2 bytes in string representation */
  6763. static void
  6764. bin2str(char *to, const unsigned char *p, size_t len)
  6765. {
  6766. static const char *hex = "0123456789abcdef";
  6767. for (; len--; p++) {
  6768. *to++ = hex[p[0] >> 4];
  6769. *to++ = hex[p[0] & 0x0f];
  6770. }
  6771. *to = '\0';
  6772. }
  6773. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6774. */
  6775. char *
  6776. mg_md5(char buf[33], ...)
  6777. {
  6778. md5_byte_t hash[16];
  6779. const char *p;
  6780. va_list ap;
  6781. md5_state_t ctx;
  6782. md5_init(&ctx);
  6783. va_start(ap, buf);
  6784. while ((p = va_arg(ap, const char *)) != NULL) {
  6785. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6786. }
  6787. va_end(ap);
  6788. md5_finish(&ctx, hash);
  6789. bin2str(buf, hash, sizeof(hash));
  6790. return buf;
  6791. }
  6792. /* Check the user's password, return 1 if OK */
  6793. static int
  6794. check_password(const char *method,
  6795. const char *ha1,
  6796. const char *uri,
  6797. const char *nonce,
  6798. const char *nc,
  6799. const char *cnonce,
  6800. const char *qop,
  6801. const char *response)
  6802. {
  6803. char ha2[32 + 1], expected_response[32 + 1];
  6804. /* Some of the parameters may be NULL */
  6805. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6806. || (qop == NULL) || (response == NULL)) {
  6807. return 0;
  6808. }
  6809. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6810. if (strlen(response) != 32) {
  6811. return 0;
  6812. }
  6813. mg_md5(ha2, method, ":", uri, NULL);
  6814. mg_md5(expected_response,
  6815. ha1,
  6816. ":",
  6817. nonce,
  6818. ":",
  6819. nc,
  6820. ":",
  6821. cnonce,
  6822. ":",
  6823. qop,
  6824. ":",
  6825. ha2,
  6826. NULL);
  6827. return mg_strcasecmp(response, expected_response) == 0;
  6828. }
  6829. /* Use the global passwords file, if specified by auth_gpass option,
  6830. * or search for .htpasswd in the requested directory. */
  6831. static void
  6832. open_auth_file(struct mg_connection *conn,
  6833. const char *path,
  6834. struct mg_file *filep)
  6835. {
  6836. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6837. char name[PATH_MAX];
  6838. const char *p, *e,
  6839. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6840. int truncated;
  6841. if (gpass != NULL) {
  6842. /* Use global passwords file */
  6843. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6844. #if defined(DEBUG)
  6845. /* Use mg_cry_internal here, since gpass has been configured. */
  6846. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6847. #endif
  6848. }
  6849. /* Important: using local struct mg_file to test path for
  6850. * is_directory flag. If filep is used, mg_stat() makes it
  6851. * appear as if auth file was opened.
  6852. * TODO(mid): Check if this is still required after rewriting
  6853. * mg_stat */
  6854. } else if (mg_stat(conn, path, &filep->stat)
  6855. && filep->stat.is_directory) {
  6856. mg_snprintf(conn,
  6857. &truncated,
  6858. name,
  6859. sizeof(name),
  6860. "%s/%s",
  6861. path,
  6862. PASSWORDS_FILE_NAME);
  6863. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6864. #if defined(DEBUG)
  6865. /* Don't use mg_cry_internal here, but only a trace, since this
  6866. * is
  6867. * a typical case. It will occur for every directory
  6868. * without a password file. */
  6869. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6870. #endif
  6871. }
  6872. } else {
  6873. /* Try to find .htpasswd in requested directory. */
  6874. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6875. if (e[0] == '/') {
  6876. break;
  6877. }
  6878. }
  6879. mg_snprintf(conn,
  6880. &truncated,
  6881. name,
  6882. sizeof(name),
  6883. "%.*s/%s",
  6884. (int)(e - p),
  6885. p,
  6886. PASSWORDS_FILE_NAME);
  6887. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6888. #if defined(DEBUG)
  6889. /* Don't use mg_cry_internal here, but only a trace, since this
  6890. * is
  6891. * a typical case. It will occur for every directory
  6892. * without a password file. */
  6893. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6894. #endif
  6895. }
  6896. }
  6897. }
  6898. }
  6899. /* Parsed Authorization header */
  6900. struct ah {
  6901. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6902. };
  6903. /* Return 1 on success. Always initializes the ah structure. */
  6904. static int
  6905. parse_auth_header(struct mg_connection *conn,
  6906. char *buf,
  6907. size_t buf_size,
  6908. struct ah *ah)
  6909. {
  6910. char *name, *value, *s;
  6911. const char *auth_header;
  6912. uint64_t nonce;
  6913. if (!ah || !conn) {
  6914. return 0;
  6915. }
  6916. (void)memset(ah, 0, sizeof(*ah));
  6917. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6918. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6919. return 0;
  6920. }
  6921. /* Make modifiable copy of the auth header */
  6922. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6923. s = buf;
  6924. /* Parse authorization header */
  6925. for (;;) {
  6926. /* Gobble initial spaces */
  6927. while (isspace((unsigned char)*s)) {
  6928. s++;
  6929. }
  6930. name = skip_quoted(&s, "=", " ", 0);
  6931. /* Value is either quote-delimited, or ends at first comma or space.
  6932. */
  6933. if (s[0] == '\"') {
  6934. s++;
  6935. value = skip_quoted(&s, "\"", " ", '\\');
  6936. if (s[0] == ',') {
  6937. s++;
  6938. }
  6939. } else {
  6940. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6941. * spaces */
  6942. }
  6943. if (*name == '\0') {
  6944. break;
  6945. }
  6946. if (!strcmp(name, "username")) {
  6947. ah->user = value;
  6948. } else if (!strcmp(name, "cnonce")) {
  6949. ah->cnonce = value;
  6950. } else if (!strcmp(name, "response")) {
  6951. ah->response = value;
  6952. } else if (!strcmp(name, "uri")) {
  6953. ah->uri = value;
  6954. } else if (!strcmp(name, "qop")) {
  6955. ah->qop = value;
  6956. } else if (!strcmp(name, "nc")) {
  6957. ah->nc = value;
  6958. } else if (!strcmp(name, "nonce")) {
  6959. ah->nonce = value;
  6960. }
  6961. }
  6962. #if !defined(NO_NONCE_CHECK)
  6963. /* Read the nonce from the response. */
  6964. if (ah->nonce == NULL) {
  6965. return 0;
  6966. }
  6967. s = NULL;
  6968. nonce = strtoull(ah->nonce, &s, 10);
  6969. if ((s == NULL) || (*s != 0)) {
  6970. return 0;
  6971. }
  6972. /* Convert the nonce from the client to a number. */
  6973. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6974. /* The converted number corresponds to the time the nounce has been
  6975. * created. This should not be earlier than the server start. */
  6976. /* Server side nonce check is valuable in all situations but one:
  6977. * if the server restarts frequently, but the client should not see
  6978. * that, so the server should accept nonces from previous starts. */
  6979. /* However, the reasonable default is to not accept a nonce from a
  6980. * previous start, so if anyone changed the access rights between
  6981. * two restarts, a new login is required. */
  6982. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6983. /* nonce is from a previous start of the server and no longer valid
  6984. * (replay attack?) */
  6985. return 0;
  6986. }
  6987. /* Check if the nonce is too high, so it has not (yet) been used by the
  6988. * server. */
  6989. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6990. + conn->dom_ctx->nonce_count)) {
  6991. return 0;
  6992. }
  6993. #else
  6994. (void)nonce;
  6995. #endif
  6996. /* CGI needs it as REMOTE_USER */
  6997. if (ah->user != NULL) {
  6998. conn->request_info.remote_user =
  6999. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7000. } else {
  7001. return 0;
  7002. }
  7003. return 1;
  7004. }
  7005. static const char *
  7006. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7007. {
  7008. #if defined(MG_USE_OPEN_FILE)
  7009. const char *eof;
  7010. size_t len;
  7011. const char *memend;
  7012. #else
  7013. (void)p; /* parameter is unused */
  7014. #endif
  7015. if (!filep) {
  7016. return NULL;
  7017. }
  7018. #if defined(MG_USE_OPEN_FILE)
  7019. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7020. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7021. /* Search for \n from p till the end of stream */
  7022. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7023. if (eof != NULL) {
  7024. eof += 1; /* Include \n */
  7025. } else {
  7026. eof = memend; /* Copy remaining data */
  7027. }
  7028. len =
  7029. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7030. memcpy(buf, *p, len);
  7031. buf[len] = '\0';
  7032. *p += len;
  7033. return len ? eof : NULL;
  7034. } else /* filep->access.fp block below */
  7035. #endif
  7036. if (filep->access.fp != NULL) {
  7037. return fgets(buf, (int)size, filep->access.fp);
  7038. } else {
  7039. return NULL;
  7040. }
  7041. }
  7042. /* Define the initial recursion depth for procesesing htpasswd files that
  7043. * include other htpasswd
  7044. * (or even the same) files. It is not difficult to provide a file or files
  7045. * s.t. they force civetweb
  7046. * to infinitely recurse and then crash.
  7047. */
  7048. #define INITIAL_DEPTH 9
  7049. #if INITIAL_DEPTH <= 0
  7050. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7051. #endif
  7052. struct read_auth_file_struct {
  7053. struct mg_connection *conn;
  7054. struct ah ah;
  7055. const char *domain;
  7056. char buf[256 + 256 + 40];
  7057. const char *f_user;
  7058. const char *f_domain;
  7059. const char *f_ha1;
  7060. };
  7061. static int
  7062. read_auth_file(struct mg_file *filep,
  7063. struct read_auth_file_struct *workdata,
  7064. int depth)
  7065. {
  7066. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7067. int is_authorized = 0;
  7068. struct mg_file fp;
  7069. size_t l;
  7070. if (!filep || !workdata || (0 == depth)) {
  7071. return 0;
  7072. }
  7073. /* Loop over passwords file */
  7074. #if defined(MG_USE_OPEN_FILE)
  7075. p = (char *)filep->access.membuf;
  7076. #endif
  7077. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7078. l = strlen(workdata->buf);
  7079. while (l > 0) {
  7080. if (isspace((unsigned char)workdata->buf[l - 1])
  7081. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7082. l--;
  7083. workdata->buf[l] = 0;
  7084. } else
  7085. break;
  7086. }
  7087. if (l < 1) {
  7088. continue;
  7089. }
  7090. workdata->f_user = workdata->buf;
  7091. if (workdata->f_user[0] == ':') {
  7092. /* user names may not contain a ':' and may not be empty,
  7093. * so lines starting with ':' may be used for a special purpose
  7094. */
  7095. if (workdata->f_user[1] == '#') {
  7096. /* :# is a comment */
  7097. continue;
  7098. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7099. if (mg_fopen(workdata->conn,
  7100. workdata->f_user + 9,
  7101. MG_FOPEN_MODE_READ,
  7102. &fp)) {
  7103. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7104. (void)mg_fclose(
  7105. &fp.access); /* ignore error on read only file */
  7106. /* No need to continue processing files once we have a
  7107. * match, since nothing will reset it back
  7108. * to 0.
  7109. */
  7110. if (is_authorized) {
  7111. return is_authorized;
  7112. }
  7113. } else {
  7114. mg_cry_internal(workdata->conn,
  7115. "%s: cannot open authorization file: %s",
  7116. __func__,
  7117. workdata->buf);
  7118. }
  7119. continue;
  7120. }
  7121. /* everything is invalid for the moment (might change in the
  7122. * future) */
  7123. mg_cry_internal(workdata->conn,
  7124. "%s: syntax error in authorization file: %s",
  7125. __func__,
  7126. workdata->buf);
  7127. continue;
  7128. }
  7129. workdata->f_domain = strchr(workdata->f_user, ':');
  7130. if (workdata->f_domain == NULL) {
  7131. mg_cry_internal(workdata->conn,
  7132. "%s: syntax error in authorization file: %s",
  7133. __func__,
  7134. workdata->buf);
  7135. continue;
  7136. }
  7137. *(char *)(workdata->f_domain) = 0;
  7138. (workdata->f_domain)++;
  7139. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7140. if (workdata->f_ha1 == NULL) {
  7141. mg_cry_internal(workdata->conn,
  7142. "%s: syntax error in authorization file: %s",
  7143. __func__,
  7144. workdata->buf);
  7145. continue;
  7146. }
  7147. *(char *)(workdata->f_ha1) = 0;
  7148. (workdata->f_ha1)++;
  7149. if (!strcmp(workdata->ah.user, workdata->f_user)
  7150. && !strcmp(workdata->domain, workdata->f_domain)) {
  7151. return check_password(workdata->conn->request_info.request_method,
  7152. workdata->f_ha1,
  7153. workdata->ah.uri,
  7154. workdata->ah.nonce,
  7155. workdata->ah.nc,
  7156. workdata->ah.cnonce,
  7157. workdata->ah.qop,
  7158. workdata->ah.response);
  7159. }
  7160. }
  7161. return is_authorized;
  7162. }
  7163. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7164. static int
  7165. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7166. {
  7167. struct read_auth_file_struct workdata;
  7168. char buf[MG_BUF_LEN];
  7169. if (!conn || !conn->dom_ctx) {
  7170. return 0;
  7171. }
  7172. memset(&workdata, 0, sizeof(workdata));
  7173. workdata.conn = conn;
  7174. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7175. return 0;
  7176. }
  7177. if (realm) {
  7178. workdata.domain = realm;
  7179. } else {
  7180. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7181. }
  7182. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7183. }
  7184. /* Public function to check http digest authentication header */
  7185. int
  7186. mg_check_digest_access_authentication(struct mg_connection *conn,
  7187. const char *realm,
  7188. const char *filename)
  7189. {
  7190. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7191. int auth;
  7192. if (!conn || !filename) {
  7193. return -1;
  7194. }
  7195. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7196. return -2;
  7197. }
  7198. auth = authorize(conn, &file, realm);
  7199. mg_fclose(&file.access);
  7200. return auth;
  7201. }
  7202. /* Return 1 if request is authorised, 0 otherwise. */
  7203. static int
  7204. check_authorization(struct mg_connection *conn, const char *path)
  7205. {
  7206. char fname[PATH_MAX];
  7207. struct vec uri_vec, filename_vec;
  7208. const char *list;
  7209. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7210. int authorized = 1, truncated;
  7211. if (!conn || !conn->dom_ctx) {
  7212. return 0;
  7213. }
  7214. list = conn->dom_ctx->config[PROTECT_URI];
  7215. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7216. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7217. mg_snprintf(conn,
  7218. &truncated,
  7219. fname,
  7220. sizeof(fname),
  7221. "%.*s",
  7222. (int)filename_vec.len,
  7223. filename_vec.ptr);
  7224. if (truncated
  7225. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7226. mg_cry_internal(conn,
  7227. "%s: cannot open %s: %s",
  7228. __func__,
  7229. fname,
  7230. strerror(errno));
  7231. }
  7232. break;
  7233. }
  7234. }
  7235. if (!is_file_opened(&file.access)) {
  7236. open_auth_file(conn, path, &file);
  7237. }
  7238. if (is_file_opened(&file.access)) {
  7239. authorized = authorize(conn, &file, NULL);
  7240. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7241. }
  7242. return authorized;
  7243. }
  7244. /* Internal function. Assumes conn is valid */
  7245. static void
  7246. send_authorization_request(struct mg_connection *conn, const char *realm)
  7247. {
  7248. char date[64];
  7249. time_t curtime = time(NULL);
  7250. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7251. if (!realm) {
  7252. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7253. }
  7254. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7255. nonce += conn->dom_ctx->nonce_count;
  7256. ++conn->dom_ctx->nonce_count;
  7257. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7258. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7259. conn->status_code = 401;
  7260. conn->must_close = 1;
  7261. gmt_time_string(date, sizeof(date), &curtime);
  7262. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7263. send_no_cache_header(conn);
  7264. send_additional_header(conn);
  7265. mg_printf(conn,
  7266. "Date: %s\r\n"
  7267. "Connection: %s\r\n"
  7268. "Content-Length: 0\r\n"
  7269. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7270. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7271. date,
  7272. suggest_connection_header(conn),
  7273. realm,
  7274. nonce);
  7275. }
  7276. /* Interface function. Parameters are provided by the user, so do
  7277. * at least some basic checks.
  7278. */
  7279. int
  7280. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7281. const char *realm)
  7282. {
  7283. if (conn && conn->dom_ctx) {
  7284. send_authorization_request(conn, realm);
  7285. return 0;
  7286. }
  7287. return -1;
  7288. }
  7289. #if !defined(NO_FILES)
  7290. static int
  7291. is_authorized_for_put(struct mg_connection *conn)
  7292. {
  7293. if (conn) {
  7294. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7295. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7296. int ret = 0;
  7297. if (passfile != NULL
  7298. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7299. ret = authorize(conn, &file, NULL);
  7300. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7301. }
  7302. return ret;
  7303. }
  7304. return 0;
  7305. }
  7306. #endif
  7307. int
  7308. mg_modify_passwords_file(const char *fname,
  7309. const char *domain,
  7310. const char *user,
  7311. const char *pass)
  7312. {
  7313. int found, i;
  7314. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7315. FILE *fp, *fp2;
  7316. found = 0;
  7317. fp = fp2 = NULL;
  7318. /* Regard empty password as no password - remove user record. */
  7319. if ((pass != NULL) && (pass[0] == '\0')) {
  7320. pass = NULL;
  7321. }
  7322. /* Other arguments must not be empty */
  7323. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7324. return 0;
  7325. }
  7326. /* Using the given file format, user name and domain must not contain
  7327. * ':'
  7328. */
  7329. if (strchr(user, ':') != NULL) {
  7330. return 0;
  7331. }
  7332. if (strchr(domain, ':') != NULL) {
  7333. return 0;
  7334. }
  7335. /* Do not allow control characters like newline in user name and domain.
  7336. * Do not allow excessively long names either. */
  7337. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7338. if (iscntrl((unsigned char)user[i])) {
  7339. return 0;
  7340. }
  7341. }
  7342. if (user[i]) {
  7343. return 0;
  7344. }
  7345. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7346. if (iscntrl((unsigned char)domain[i])) {
  7347. return 0;
  7348. }
  7349. }
  7350. if (domain[i]) {
  7351. return 0;
  7352. }
  7353. /* The maximum length of the path to the password file is limited */
  7354. if ((strlen(fname) + 4) >= PATH_MAX) {
  7355. return 0;
  7356. }
  7357. /* Create a temporary file name. Length has been checked before. */
  7358. strcpy(tmp, fname);
  7359. strcat(tmp, ".tmp");
  7360. /* Create the file if does not exist */
  7361. /* Use of fopen here is OK, since fname is only ASCII */
  7362. if ((fp = fopen(fname, "a+")) != NULL) {
  7363. (void)fclose(fp);
  7364. }
  7365. /* Open the given file and temporary file */
  7366. if ((fp = fopen(fname, "r")) == NULL) {
  7367. return 0;
  7368. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7369. fclose(fp);
  7370. return 0;
  7371. }
  7372. /* Copy the stuff to temporary file */
  7373. while (fgets(line, sizeof(line), fp) != NULL) {
  7374. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7375. continue;
  7376. }
  7377. u[255] = 0;
  7378. d[255] = 0;
  7379. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7380. found++;
  7381. if (pass != NULL) {
  7382. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7383. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7384. }
  7385. } else {
  7386. fprintf(fp2, "%s", line);
  7387. }
  7388. }
  7389. /* If new user, just add it */
  7390. if (!found && (pass != NULL)) {
  7391. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7392. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7393. }
  7394. /* Close files */
  7395. fclose(fp);
  7396. fclose(fp2);
  7397. /* Put the temp file in place of real file */
  7398. IGNORE_UNUSED_RESULT(remove(fname));
  7399. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7400. return 1;
  7401. }
  7402. static int
  7403. is_valid_port(unsigned long port)
  7404. {
  7405. return (port <= 0xffff);
  7406. }
  7407. static int
  7408. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7409. {
  7410. struct addrinfo hints, *res, *ressave;
  7411. int func_ret = 0;
  7412. int gai_ret;
  7413. memset(&hints, 0, sizeof(struct addrinfo));
  7414. hints.ai_family = af;
  7415. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7416. if (gai_ret != 0) {
  7417. /* gai_strerror could be used to convert gai_ret to a string */
  7418. /* POSIX return values: see
  7419. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7420. */
  7421. /* Windows return values: see
  7422. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7423. */
  7424. return 0;
  7425. }
  7426. ressave = res;
  7427. while (res) {
  7428. if (dstlen >= (size_t)res->ai_addrlen) {
  7429. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7430. func_ret = 1;
  7431. }
  7432. res = res->ai_next;
  7433. }
  7434. freeaddrinfo(ressave);
  7435. return func_ret;
  7436. }
  7437. static int
  7438. connect_socket(struct mg_context *ctx /* may be NULL */,
  7439. const char *host,
  7440. int port,
  7441. int use_ssl,
  7442. char *ebuf,
  7443. size_t ebuf_len,
  7444. SOCKET *sock /* output: socket, must not be NULL */,
  7445. union usa *sa /* output: socket address, must not be NULL */
  7446. )
  7447. {
  7448. int ip_ver = 0;
  7449. int conn_ret = -1;
  7450. int sockerr = 0;
  7451. *sock = INVALID_SOCKET;
  7452. memset(sa, 0, sizeof(*sa));
  7453. if (ebuf_len > 0) {
  7454. *ebuf = 0;
  7455. }
  7456. if (host == NULL) {
  7457. mg_snprintf(NULL,
  7458. NULL, /* No truncation check for ebuf */
  7459. ebuf,
  7460. ebuf_len,
  7461. "%s",
  7462. "NULL host");
  7463. return 0;
  7464. }
  7465. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7466. mg_snprintf(NULL,
  7467. NULL, /* No truncation check for ebuf */
  7468. ebuf,
  7469. ebuf_len,
  7470. "%s",
  7471. "invalid port");
  7472. return 0;
  7473. }
  7474. #if !defined(NO_SSL)
  7475. #if !defined(NO_SSL_DL)
  7476. #if defined(OPENSSL_API_1_1)
  7477. if (use_ssl && (TLS_client_method == NULL)) {
  7478. mg_snprintf(NULL,
  7479. NULL, /* No truncation check for ebuf */
  7480. ebuf,
  7481. ebuf_len,
  7482. "%s",
  7483. "SSL is not initialized");
  7484. return 0;
  7485. }
  7486. #else
  7487. if (use_ssl && (SSLv23_client_method == NULL)) {
  7488. mg_snprintf(NULL,
  7489. NULL, /* No truncation check for ebuf */
  7490. ebuf,
  7491. ebuf_len,
  7492. "%s",
  7493. "SSL is not initialized");
  7494. return 0;
  7495. }
  7496. #endif /* OPENSSL_API_1_1 */
  7497. #else
  7498. (void)use_ssl;
  7499. #endif /* NO_SSL_DL */
  7500. #else
  7501. (void)use_ssl;
  7502. #endif /* !defined(NO_SSL) */
  7503. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7504. sa->sin.sin_family = AF_INET;
  7505. sa->sin.sin_port = htons((uint16_t)port);
  7506. ip_ver = 4;
  7507. #if defined(USE_IPV6)
  7508. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7509. sa->sin6.sin6_family = AF_INET6;
  7510. sa->sin6.sin6_port = htons((uint16_t)port);
  7511. ip_ver = 6;
  7512. } else if (host[0] == '[') {
  7513. /* While getaddrinfo on Windows will work with [::1],
  7514. * getaddrinfo on Linux only works with ::1 (without []). */
  7515. size_t l = strlen(host + 1);
  7516. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7517. if (h) {
  7518. h[l - 1] = 0;
  7519. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7520. sa->sin6.sin6_family = AF_INET6;
  7521. sa->sin6.sin6_port = htons((uint16_t)port);
  7522. ip_ver = 6;
  7523. }
  7524. mg_free(h);
  7525. }
  7526. #endif
  7527. }
  7528. if (ip_ver == 0) {
  7529. mg_snprintf(NULL,
  7530. NULL, /* No truncation check for ebuf */
  7531. ebuf,
  7532. ebuf_len,
  7533. "%s",
  7534. "host not found");
  7535. return 0;
  7536. }
  7537. if (ip_ver == 4) {
  7538. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7539. }
  7540. #if defined(USE_IPV6)
  7541. else if (ip_ver == 6) {
  7542. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7543. }
  7544. #endif
  7545. if (*sock == INVALID_SOCKET) {
  7546. mg_snprintf(NULL,
  7547. NULL, /* No truncation check for ebuf */
  7548. ebuf,
  7549. ebuf_len,
  7550. "socket(): %s",
  7551. strerror(ERRNO));
  7552. return 0;
  7553. }
  7554. if (0 != set_non_blocking_mode(*sock)) {
  7555. mg_snprintf(NULL,
  7556. NULL, /* No truncation check for ebuf */
  7557. ebuf,
  7558. ebuf_len,
  7559. "Cannot set socket to non-blocking: %s",
  7560. strerror(ERRNO));
  7561. closesocket(*sock);
  7562. *sock = INVALID_SOCKET;
  7563. return 0;
  7564. }
  7565. set_close_on_exec(*sock, NULL, ctx);
  7566. if (ip_ver == 4) {
  7567. /* connected with IPv4 */
  7568. conn_ret = connect(*sock,
  7569. (struct sockaddr *)((void *)&sa->sin),
  7570. sizeof(sa->sin));
  7571. }
  7572. #if defined(USE_IPV6)
  7573. else if (ip_ver == 6) {
  7574. /* connected with IPv6 */
  7575. conn_ret = connect(*sock,
  7576. (struct sockaddr *)((void *)&sa->sin6),
  7577. sizeof(sa->sin6));
  7578. }
  7579. #endif
  7580. if (conn_ret != 0) {
  7581. sockerr = ERRNO;
  7582. }
  7583. #if defined(_WIN32)
  7584. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7585. #else
  7586. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7587. #endif
  7588. /* Data for getsockopt */
  7589. void *psockerr = &sockerr;
  7590. int ret;
  7591. #if defined(_WIN32)
  7592. int len = (int)sizeof(sockerr);
  7593. #else
  7594. socklen_t len = (socklen_t)sizeof(sockerr);
  7595. #endif
  7596. /* Data for poll */
  7597. struct mg_pollfd pfd[1];
  7598. int pollres;
  7599. int ms_wait = 10000; /* 10 second timeout */
  7600. int nonstop = 0;
  7601. /* For a non-blocking socket, the connect sequence is:
  7602. * 1) call connect (will not block)
  7603. * 2) wait until the socket is ready for writing (select or poll)
  7604. * 3) check connection state with getsockopt
  7605. */
  7606. pfd[0].fd = *sock;
  7607. pfd[0].events = POLLOUT;
  7608. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7609. if (pollres != 1) {
  7610. /* Not connected */
  7611. mg_snprintf(NULL,
  7612. NULL, /* No truncation check for ebuf */
  7613. ebuf,
  7614. ebuf_len,
  7615. "connect(%s:%d): timeout",
  7616. host,
  7617. port);
  7618. closesocket(*sock);
  7619. *sock = INVALID_SOCKET;
  7620. return 0;
  7621. }
  7622. #if defined(_WIN32)
  7623. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7624. #else
  7625. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7626. #endif
  7627. if ((ret == 0) && (sockerr == 0)) {
  7628. conn_ret = 0;
  7629. }
  7630. }
  7631. if (conn_ret != 0) {
  7632. /* Not connected */
  7633. mg_snprintf(NULL,
  7634. NULL, /* No truncation check for ebuf */
  7635. ebuf,
  7636. ebuf_len,
  7637. "connect(%s:%d): error %s",
  7638. host,
  7639. port,
  7640. strerror(sockerr));
  7641. closesocket(*sock);
  7642. *sock = INVALID_SOCKET;
  7643. return 0;
  7644. }
  7645. return 1;
  7646. }
  7647. int
  7648. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7649. {
  7650. static const char *dont_escape = "._-$,;~()";
  7651. static const char *hex = "0123456789abcdef";
  7652. char *pos = dst;
  7653. const char *end = dst + dst_len - 1;
  7654. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7655. if (isalnum((unsigned char)*src)
  7656. || (strchr(dont_escape, *src) != NULL)) {
  7657. *pos = *src;
  7658. } else if (pos + 2 < end) {
  7659. pos[0] = '%';
  7660. pos[1] = hex[(unsigned char)*src >> 4];
  7661. pos[2] = hex[(unsigned char)*src & 0xf];
  7662. pos += 2;
  7663. } else {
  7664. break;
  7665. }
  7666. }
  7667. *pos = '\0';
  7668. return (*src == '\0') ? (int)(pos - dst) : -1;
  7669. }
  7670. /* Return 0 on success, non-zero if an error occurs. */
  7671. static int
  7672. print_dir_entry(struct de *de)
  7673. {
  7674. size_t namesize, escsize, i;
  7675. char *href, *esc, *p;
  7676. char size[64], mod[64];
  7677. #if defined(REENTRANT_TIME)
  7678. struct tm _tm;
  7679. struct tm *tm = &_tm;
  7680. #else
  7681. struct tm *tm;
  7682. #endif
  7683. /* Estimate worst case size for encoding and escaping */
  7684. namesize = strlen(de->file_name) + 1;
  7685. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7686. href = (char *)mg_malloc(namesize * 3 + escsize);
  7687. if (href == NULL) {
  7688. return -1;
  7689. }
  7690. mg_url_encode(de->file_name, href, namesize * 3);
  7691. esc = NULL;
  7692. if (escsize > 0) {
  7693. /* HTML escaping needed */
  7694. esc = href + namesize * 3;
  7695. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7696. mg_strlcpy(p, de->file_name + i, 2);
  7697. if (*p == '&') {
  7698. strcpy(p, "&amp;");
  7699. } else if (*p == '<') {
  7700. strcpy(p, "&lt;");
  7701. } else if (*p == '>') {
  7702. strcpy(p, "&gt;");
  7703. }
  7704. }
  7705. }
  7706. if (de->file.is_directory) {
  7707. mg_snprintf(de->conn,
  7708. NULL, /* Buffer is big enough */
  7709. size,
  7710. sizeof(size),
  7711. "%s",
  7712. "[DIRECTORY]");
  7713. } else {
  7714. /* We use (signed) cast below because MSVC 6 compiler cannot
  7715. * convert unsigned __int64 to double. Sigh. */
  7716. if (de->file.size < 1024) {
  7717. mg_snprintf(de->conn,
  7718. NULL, /* Buffer is big enough */
  7719. size,
  7720. sizeof(size),
  7721. "%d",
  7722. (int)de->file.size);
  7723. } else if (de->file.size < 0x100000) {
  7724. mg_snprintf(de->conn,
  7725. NULL, /* Buffer is big enough */
  7726. size,
  7727. sizeof(size),
  7728. "%.1fk",
  7729. (double)de->file.size / 1024.0);
  7730. } else if (de->file.size < 0x40000000) {
  7731. mg_snprintf(de->conn,
  7732. NULL, /* Buffer is big enough */
  7733. size,
  7734. sizeof(size),
  7735. "%.1fM",
  7736. (double)de->file.size / 1048576);
  7737. } else {
  7738. mg_snprintf(de->conn,
  7739. NULL, /* Buffer is big enough */
  7740. size,
  7741. sizeof(size),
  7742. "%.1fG",
  7743. (double)de->file.size / 1073741824);
  7744. }
  7745. }
  7746. /* Note: mg_snprintf will not cause a buffer overflow above.
  7747. * So, string truncation checks are not required here. */
  7748. #if defined(REENTRANT_TIME)
  7749. localtime_r(&de->file.last_modified, tm);
  7750. #else
  7751. tm = localtime(&de->file.last_modified);
  7752. #endif
  7753. if (tm != NULL) {
  7754. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7755. } else {
  7756. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7757. mod[sizeof(mod) - 1] = '\0';
  7758. }
  7759. mg_printf(de->conn,
  7760. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7761. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7762. href,
  7763. de->file.is_directory ? "/" : "",
  7764. esc ? esc : de->file_name,
  7765. de->file.is_directory ? "/" : "",
  7766. mod,
  7767. size);
  7768. mg_free(href);
  7769. return 0;
  7770. }
  7771. /* This function is called from send_directory() and used for
  7772. * sorting directory entries by size, or name, or modification time.
  7773. * On windows, __cdecl specification is needed in case if project is built
  7774. * with __stdcall convention. qsort always requires __cdels callback. */
  7775. static int WINCDECL
  7776. compare_dir_entries(const void *p1, const void *p2)
  7777. {
  7778. if (p1 && p2) {
  7779. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7780. const char *query_string = a->conn->request_info.query_string;
  7781. int cmp_result = 0;
  7782. if ((query_string == NULL) || (query_string[0] == '\0')) {
  7783. query_string = "n";
  7784. }
  7785. if (a->file.is_directory && !b->file.is_directory) {
  7786. return -1; /* Always put directories on top */
  7787. } else if (!a->file.is_directory && b->file.is_directory) {
  7788. return 1; /* Always put directories on top */
  7789. } else if (*query_string == 'n') {
  7790. cmp_result = strcmp(a->file_name, b->file_name);
  7791. } else if (*query_string == 's') {
  7792. cmp_result = (a->file.size == b->file.size)
  7793. ? 0
  7794. : ((a->file.size > b->file.size) ? 1 : -1);
  7795. } else if (*query_string == 'd') {
  7796. cmp_result =
  7797. (a->file.last_modified == b->file.last_modified)
  7798. ? 0
  7799. : ((a->file.last_modified > b->file.last_modified) ? 1
  7800. : -1);
  7801. }
  7802. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7803. }
  7804. return 0;
  7805. }
  7806. static int
  7807. must_hide_file(struct mg_connection *conn, const char *path)
  7808. {
  7809. if (conn && conn->dom_ctx) {
  7810. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7811. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7812. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7813. || ((pattern != NULL)
  7814. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7815. }
  7816. return 0;
  7817. }
  7818. static int
  7819. scan_directory(struct mg_connection *conn,
  7820. const char *dir,
  7821. void *data,
  7822. int (*cb)(struct de *, void *))
  7823. {
  7824. char path[PATH_MAX];
  7825. struct dirent *dp;
  7826. DIR *dirp;
  7827. struct de de;
  7828. int truncated;
  7829. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7830. return 0;
  7831. } else {
  7832. de.conn = conn;
  7833. while ((dp = mg_readdir(dirp)) != NULL) {
  7834. /* Do not show current dir and hidden files */
  7835. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7836. || must_hide_file(conn, dp->d_name)) {
  7837. continue;
  7838. }
  7839. mg_snprintf(
  7840. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7841. /* If we don't memset stat structure to zero, mtime will have
  7842. * garbage and strftime() will segfault later on in
  7843. * print_dir_entry(). memset is required only if mg_stat()
  7844. * fails. For more details, see
  7845. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7846. memset(&de.file, 0, sizeof(de.file));
  7847. if (truncated) {
  7848. /* If the path is not complete, skip processing. */
  7849. continue;
  7850. }
  7851. if (!mg_stat(conn, path, &de.file)) {
  7852. mg_cry_internal(conn,
  7853. "%s: mg_stat(%s) failed: %s",
  7854. __func__,
  7855. path,
  7856. strerror(ERRNO));
  7857. }
  7858. de.file_name = dp->d_name;
  7859. cb(&de, data);
  7860. }
  7861. (void)mg_closedir(dirp);
  7862. }
  7863. return 1;
  7864. }
  7865. #if !defined(NO_FILES)
  7866. static int
  7867. remove_directory(struct mg_connection *conn, const char *dir)
  7868. {
  7869. char path[PATH_MAX];
  7870. struct dirent *dp;
  7871. DIR *dirp;
  7872. struct de de;
  7873. int truncated;
  7874. int ok = 1;
  7875. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7876. return 0;
  7877. } else {
  7878. de.conn = conn;
  7879. while ((dp = mg_readdir(dirp)) != NULL) {
  7880. /* Do not show current dir (but show hidden files as they will
  7881. * also be removed) */
  7882. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7883. continue;
  7884. }
  7885. mg_snprintf(
  7886. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7887. /* If we don't memset stat structure to zero, mtime will have
  7888. * garbage and strftime() will segfault later on in
  7889. * print_dir_entry(). memset is required only if mg_stat()
  7890. * fails. For more details, see
  7891. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7892. memset(&de.file, 0, sizeof(de.file));
  7893. if (truncated) {
  7894. /* Do not delete anything shorter */
  7895. ok = 0;
  7896. continue;
  7897. }
  7898. if (!mg_stat(conn, path, &de.file)) {
  7899. mg_cry_internal(conn,
  7900. "%s: mg_stat(%s) failed: %s",
  7901. __func__,
  7902. path,
  7903. strerror(ERRNO));
  7904. ok = 0;
  7905. }
  7906. if (de.file.is_directory) {
  7907. if (remove_directory(conn, path) == 0) {
  7908. ok = 0;
  7909. }
  7910. } else {
  7911. /* This will fail file is the file is in memory */
  7912. if (mg_remove(conn, path) == 0) {
  7913. ok = 0;
  7914. }
  7915. }
  7916. }
  7917. (void)mg_closedir(dirp);
  7918. IGNORE_UNUSED_RESULT(rmdir(dir));
  7919. }
  7920. return ok;
  7921. }
  7922. #endif
  7923. struct dir_scan_data {
  7924. struct de *entries;
  7925. unsigned int num_entries;
  7926. unsigned int arr_size;
  7927. };
  7928. /* Behaves like realloc(), but frees original pointer on failure */
  7929. static void *
  7930. realloc2(void *ptr, size_t size)
  7931. {
  7932. void *new_ptr = mg_realloc(ptr, size);
  7933. if (new_ptr == NULL) {
  7934. mg_free(ptr);
  7935. }
  7936. return new_ptr;
  7937. }
  7938. static int
  7939. dir_scan_callback(struct de *de, void *data)
  7940. {
  7941. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7942. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7943. dsd->arr_size *= 2;
  7944. dsd->entries =
  7945. (struct de *)realloc2(dsd->entries,
  7946. dsd->arr_size * sizeof(dsd->entries[0]));
  7947. }
  7948. if (dsd->entries == NULL) {
  7949. /* TODO(lsm, low): propagate an error to the caller */
  7950. dsd->num_entries = 0;
  7951. } else {
  7952. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7953. dsd->entries[dsd->num_entries].file = de->file;
  7954. dsd->entries[dsd->num_entries].conn = de->conn;
  7955. dsd->num_entries++;
  7956. }
  7957. return 0;
  7958. }
  7959. static void
  7960. handle_directory_request(struct mg_connection *conn, const char *dir)
  7961. {
  7962. unsigned int i;
  7963. int sort_direction;
  7964. struct dir_scan_data data = {NULL, 0, 128};
  7965. char date[64], *esc, *p;
  7966. const char *title;
  7967. time_t curtime = time(NULL);
  7968. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7969. mg_send_http_error(conn,
  7970. 500,
  7971. "Error: Cannot open directory\nopendir(%s): %s",
  7972. dir,
  7973. strerror(ERRNO));
  7974. return;
  7975. }
  7976. gmt_time_string(date, sizeof(date), &curtime);
  7977. if (!conn) {
  7978. return;
  7979. }
  7980. esc = NULL;
  7981. title = conn->request_info.local_uri;
  7982. if (title[strcspn(title, "&<>")]) {
  7983. /* HTML escaping needed */
  7984. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  7985. if (esc) {
  7986. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  7987. mg_strlcpy(p, title + i, 2);
  7988. if (*p == '&') {
  7989. strcpy(p, "&amp;");
  7990. } else if (*p == '<') {
  7991. strcpy(p, "&lt;");
  7992. } else if (*p == '>') {
  7993. strcpy(p, "&gt;");
  7994. }
  7995. }
  7996. } else {
  7997. title = "";
  7998. }
  7999. }
  8000. sort_direction = ((conn->request_info.query_string != NULL)
  8001. && (conn->request_info.query_string[0] != '\0')
  8002. && (conn->request_info.query_string[1] == 'd'))
  8003. ? 'a'
  8004. : 'd';
  8005. conn->must_close = 1;
  8006. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8007. send_static_cache_header(conn);
  8008. send_additional_header(conn);
  8009. mg_printf(conn,
  8010. "Date: %s\r\n"
  8011. "Connection: close\r\n"
  8012. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8013. date);
  8014. mg_printf(conn,
  8015. "<html><head><title>Index of %s</title>"
  8016. "<style>th {text-align: left;}</style></head>"
  8017. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8018. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8019. "<th><a href=\"?d%c\">Modified</a></th>"
  8020. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8021. "<tr><td colspan=\"3\"><hr></td></tr>",
  8022. esc ? esc : title,
  8023. esc ? esc : title,
  8024. sort_direction,
  8025. sort_direction,
  8026. sort_direction);
  8027. mg_free(esc);
  8028. /* Print first entry - link to a parent directory */
  8029. mg_printf(conn,
  8030. "<tr><td><a href=\"%s\">%s</a></td>"
  8031. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8032. "..",
  8033. "Parent directory",
  8034. "-",
  8035. "-");
  8036. /* Sort and print directory entries */
  8037. if (data.entries != NULL) {
  8038. qsort(data.entries,
  8039. (size_t)data.num_entries,
  8040. sizeof(data.entries[0]),
  8041. compare_dir_entries);
  8042. for (i = 0; i < data.num_entries; i++) {
  8043. print_dir_entry(&data.entries[i]);
  8044. mg_free(data.entries[i].file_name);
  8045. }
  8046. mg_free(data.entries);
  8047. }
  8048. mg_printf(conn, "%s", "</table></pre></body></html>");
  8049. conn->status_code = 200;
  8050. }
  8051. /* Send len bytes from the opened file to the client. */
  8052. static void
  8053. send_file_data(struct mg_connection *conn,
  8054. struct mg_file *filep,
  8055. int64_t offset,
  8056. int64_t len)
  8057. {
  8058. char buf[MG_BUF_LEN];
  8059. int to_read, num_read, num_written;
  8060. int64_t size;
  8061. if (!filep || !conn) {
  8062. return;
  8063. }
  8064. /* Sanity check the offset */
  8065. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8066. : (int64_t)(filep->stat.size);
  8067. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8068. #if defined(MG_USE_OPEN_FILE)
  8069. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8070. /* file stored in memory */
  8071. if (len > size - offset) {
  8072. len = size - offset;
  8073. }
  8074. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8075. } else /* else block below */
  8076. #endif
  8077. if (len > 0 && filep->access.fp != NULL) {
  8078. /* file stored on disk */
  8079. #if defined(__linux__)
  8080. /* sendfile is only available for Linux */
  8081. if ((conn->ssl == 0) && (conn->throttle == 0)
  8082. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8083. "yes"))) {
  8084. off_t sf_offs = (off_t)offset;
  8085. ssize_t sf_sent;
  8086. int sf_file = fileno(filep->access.fp);
  8087. int loop_cnt = 0;
  8088. do {
  8089. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8090. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8091. size_t sf_tosend =
  8092. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8093. sf_sent =
  8094. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8095. if (sf_sent > 0) {
  8096. len -= sf_sent;
  8097. offset += sf_sent;
  8098. } else if (loop_cnt == 0) {
  8099. /* This file can not be sent using sendfile.
  8100. * This might be the case for pseudo-files in the
  8101. * /sys/ and /proc/ file system.
  8102. * Use the regular user mode copy code instead. */
  8103. break;
  8104. } else if (sf_sent == 0) {
  8105. /* No error, but 0 bytes sent. May be EOF? */
  8106. return;
  8107. }
  8108. loop_cnt++;
  8109. } while ((len > 0) && (sf_sent >= 0));
  8110. if (sf_sent > 0) {
  8111. return; /* OK */
  8112. }
  8113. /* sf_sent<0 means error, thus fall back to the classic way */
  8114. /* This is always the case, if sf_file is not a "normal" file,
  8115. * e.g., for sending data from the output of a CGI process. */
  8116. offset = (int64_t)sf_offs;
  8117. }
  8118. #endif
  8119. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8120. mg_cry_internal(conn,
  8121. "%s: fseeko() failed: %s",
  8122. __func__,
  8123. strerror(ERRNO));
  8124. mg_send_http_error(
  8125. conn,
  8126. 500,
  8127. "%s",
  8128. "Error: Unable to access file at requested position.");
  8129. } else {
  8130. while (len > 0) {
  8131. /* Calculate how much to read from the file in the buffer */
  8132. to_read = sizeof(buf);
  8133. if ((int64_t)to_read > len) {
  8134. to_read = (int)len;
  8135. }
  8136. /* Read from file, exit the loop on error */
  8137. if ((num_read =
  8138. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8139. <= 0) {
  8140. break;
  8141. }
  8142. /* Send read bytes to the client, exit the loop on error */
  8143. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8144. != num_read) {
  8145. break;
  8146. }
  8147. /* Both read and were successful, adjust counters */
  8148. len -= num_written;
  8149. }
  8150. }
  8151. }
  8152. }
  8153. static int
  8154. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8155. {
  8156. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8157. }
  8158. static void
  8159. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8160. {
  8161. if ((filestat != NULL) && (buf != NULL)) {
  8162. mg_snprintf(NULL,
  8163. NULL, /* All calls to construct_etag use 64 byte buffer */
  8164. buf,
  8165. buf_len,
  8166. "\"%lx.%" INT64_FMT "\"",
  8167. (unsigned long)filestat->last_modified,
  8168. filestat->size);
  8169. }
  8170. }
  8171. static void
  8172. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8173. {
  8174. if (filep != NULL && filep->fp != NULL) {
  8175. #if defined(_WIN32)
  8176. (void)conn; /* Unused. */
  8177. #else
  8178. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8179. mg_cry_internal(conn,
  8180. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8181. __func__,
  8182. strerror(ERRNO));
  8183. }
  8184. #endif
  8185. }
  8186. }
  8187. #if defined(USE_ZLIB)
  8188. #include "mod_zlib.inl"
  8189. #endif
  8190. static void
  8191. handle_static_file_request(struct mg_connection *conn,
  8192. const char *path,
  8193. struct mg_file *filep,
  8194. const char *mime_type,
  8195. const char *additional_headers)
  8196. {
  8197. char date[64], lm[64], etag[64];
  8198. char range[128]; /* large enough, so there will be no overflow */
  8199. const char *msg = "OK";
  8200. const char *range_hdr;
  8201. time_t curtime = time(NULL);
  8202. int64_t cl, r1, r2;
  8203. struct vec mime_vec;
  8204. int n, truncated;
  8205. char gz_path[PATH_MAX];
  8206. const char *encoding = "";
  8207. const char *origin_hdr;
  8208. const char *cors_orig_cfg;
  8209. const char *cors1, *cors2, *cors3;
  8210. int is_head_request;
  8211. #if defined(USE_ZLIB)
  8212. /* Compression is allowed, unless there is a reason not to use compression.
  8213. * If the file is already compressed, too small or a "range" request was
  8214. * made, on the fly compression is not possible. */
  8215. int allow_on_the_fly_compression = 1;
  8216. #endif
  8217. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8218. return;
  8219. }
  8220. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8221. if (mime_type == NULL) {
  8222. get_mime_type(conn, path, &mime_vec);
  8223. } else {
  8224. mime_vec.ptr = mime_type;
  8225. mime_vec.len = strlen(mime_type);
  8226. }
  8227. if (filep->stat.size > INT64_MAX) {
  8228. mg_send_http_error(conn,
  8229. 500,
  8230. "Error: File size is too large to send\n%" INT64_FMT,
  8231. filep->stat.size);
  8232. return;
  8233. }
  8234. cl = (int64_t)filep->stat.size;
  8235. conn->status_code = 200;
  8236. range[0] = '\0';
  8237. #if defined(USE_ZLIB)
  8238. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8239. * it's important to rewrite the filename after resolving
  8240. * the mime type from it, to preserve the actual file's type */
  8241. if (!conn->accept_gzip) {
  8242. allow_on_the_fly_compression = 0;
  8243. }
  8244. #endif
  8245. /* Check if there is a range header */
  8246. range_hdr = mg_get_header(conn, "Range");
  8247. /* For gzipped files, add *.gz */
  8248. if (filep->stat.is_gzipped) {
  8249. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8250. if (truncated) {
  8251. mg_send_http_error(conn,
  8252. 500,
  8253. "Error: Path of zipped file too long (%s)",
  8254. path);
  8255. return;
  8256. }
  8257. path = gz_path;
  8258. encoding = "Content-Encoding: gzip\r\n";
  8259. #if defined(USE_ZLIB)
  8260. /* File is already compressed. No "on the fly" compression. */
  8261. allow_on_the_fly_compression = 0;
  8262. #endif
  8263. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8264. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8265. struct mg_file_stat file_stat;
  8266. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8267. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8268. && !file_stat.is_directory) {
  8269. file_stat.is_gzipped = 1;
  8270. filep->stat = file_stat;
  8271. cl = (int64_t)filep->stat.size;
  8272. path = gz_path;
  8273. encoding = "Content-Encoding: gzip\r\n";
  8274. #if defined(USE_ZLIB)
  8275. /* File is already compressed. No "on the fly" compression. */
  8276. allow_on_the_fly_compression = 0;
  8277. #endif
  8278. }
  8279. }
  8280. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8281. mg_send_http_error(conn,
  8282. 500,
  8283. "Error: Cannot open file\nfopen(%s): %s",
  8284. path,
  8285. strerror(ERRNO));
  8286. return;
  8287. }
  8288. fclose_on_exec(&filep->access, conn);
  8289. /* If "Range" request was made: parse header, send only selected part
  8290. * of the file. */
  8291. r1 = r2 = 0;
  8292. if ((range_hdr != NULL)
  8293. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8294. && (r2 >= 0)) {
  8295. /* actually, range requests don't play well with a pre-gzipped
  8296. * file (since the range is specified in the uncompressed space) */
  8297. if (filep->stat.is_gzipped) {
  8298. mg_send_http_error(
  8299. conn,
  8300. 416, /* 416 = Range Not Satisfiable */
  8301. "%s",
  8302. "Error: Range requests in gzipped files are not supported");
  8303. (void)mg_fclose(
  8304. &filep->access); /* ignore error on read only file */
  8305. return;
  8306. }
  8307. conn->status_code = 206;
  8308. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8309. mg_snprintf(conn,
  8310. NULL, /* range buffer is big enough */
  8311. range,
  8312. sizeof(range),
  8313. "Content-Range: bytes "
  8314. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8315. r1,
  8316. r1 + cl - 1,
  8317. filep->stat.size);
  8318. msg = "Partial Content";
  8319. #if defined(USE_ZLIB)
  8320. /* Do not compress ranges. */
  8321. allow_on_the_fly_compression = 0;
  8322. #endif
  8323. }
  8324. /* Do not compress small files. Small files do not benefit from file
  8325. * compression, but there is still some overhead. */
  8326. #if defined(USE_ZLIB)
  8327. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8328. /* File is below the size limit. */
  8329. allow_on_the_fly_compression = 0;
  8330. }
  8331. #endif
  8332. /* Standard CORS header */
  8333. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8334. origin_hdr = mg_get_header(conn, "Origin");
  8335. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8336. /* Cross-origin resource sharing (CORS), see
  8337. * http://www.html5rocks.com/en/tutorials/cors/,
  8338. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8339. * -
  8340. * preflight is not supported for files. */
  8341. cors1 = "Access-Control-Allow-Origin: ";
  8342. cors2 = cors_orig_cfg;
  8343. cors3 = "\r\n";
  8344. } else {
  8345. cors1 = cors2 = cors3 = "";
  8346. }
  8347. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8348. * according to
  8349. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8350. gmt_time_string(date, sizeof(date), &curtime);
  8351. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8352. construct_etag(etag, sizeof(etag), &filep->stat);
  8353. /* Send header */
  8354. (void)mg_printf(conn,
  8355. "HTTP/1.1 %d %s\r\n"
  8356. "%s%s%s" /* CORS */
  8357. "Date: %s\r\n"
  8358. "Last-Modified: %s\r\n"
  8359. "Etag: %s\r\n"
  8360. "Content-Type: %.*s\r\n"
  8361. "Connection: %s\r\n",
  8362. conn->status_code,
  8363. msg,
  8364. cors1,
  8365. cors2,
  8366. cors3,
  8367. date,
  8368. lm,
  8369. etag,
  8370. (int)mime_vec.len,
  8371. mime_vec.ptr,
  8372. suggest_connection_header(conn));
  8373. send_static_cache_header(conn);
  8374. send_additional_header(conn);
  8375. #if defined(USE_ZLIB)
  8376. /* On the fly compression allowed */
  8377. if (allow_on_the_fly_compression) {
  8378. /* For on the fly compression, we don't know the content size in
  8379. * advance, so we have to use chunked encoding */
  8380. (void)mg_printf(conn,
  8381. "Content-Encoding: gzip\r\n"
  8382. "Transfer-Encoding: chunked\r\n");
  8383. } else
  8384. #endif
  8385. {
  8386. /* Without on-the-fly compression, we know the content-length
  8387. * and we can use ranges (with on-the-fly compression we cannot).
  8388. * So we send these response headers only in this case. */
  8389. (void)mg_printf(conn,
  8390. "Content-Length: %" INT64_FMT "\r\n"
  8391. "Accept-Ranges: bytes\r\n"
  8392. "%s" /* range */
  8393. "%s" /* encoding */,
  8394. cl,
  8395. range,
  8396. encoding);
  8397. }
  8398. /* The previous code must not add any header starting with X- to make
  8399. * sure no one of the additional_headers is included twice */
  8400. if (additional_headers != NULL) {
  8401. (void)mg_printf(conn,
  8402. "%.*s\r\n\r\n",
  8403. (int)strlen(additional_headers),
  8404. additional_headers);
  8405. } else {
  8406. (void)mg_printf(conn, "\r\n");
  8407. }
  8408. if (!is_head_request) {
  8409. #if defined(USE_ZLIB)
  8410. if (allow_on_the_fly_compression) {
  8411. /* Compress and send */
  8412. send_compressed_data(conn, filep);
  8413. } else
  8414. #endif
  8415. {
  8416. /* Send file directly */
  8417. send_file_data(conn, filep, r1, cl);
  8418. }
  8419. }
  8420. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8421. }
  8422. int
  8423. mg_send_file_body(struct mg_connection *conn, const char *path)
  8424. {
  8425. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8426. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8427. return -1;
  8428. }
  8429. fclose_on_exec(&file.access, conn);
  8430. send_file_data(conn, &file, 0, INT64_MAX);
  8431. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8432. return 0; /* >= 0 for OK */
  8433. }
  8434. #if !defined(NO_CACHING)
  8435. /* Return True if we should reply 304 Not Modified. */
  8436. static int
  8437. is_not_modified(const struct mg_connection *conn,
  8438. const struct mg_file_stat *filestat)
  8439. {
  8440. char etag[64];
  8441. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8442. const char *inm = mg_get_header(conn, "If-None-Match");
  8443. construct_etag(etag, sizeof(etag), filestat);
  8444. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8445. || ((ims != NULL)
  8446. && (filestat->last_modified <= parse_date_string(ims)));
  8447. }
  8448. static void
  8449. handle_not_modified_static_file_request(struct mg_connection *conn,
  8450. struct mg_file *filep)
  8451. {
  8452. char date[64], lm[64], etag[64];
  8453. time_t curtime = time(NULL);
  8454. if ((conn == NULL) || (filep == NULL)) {
  8455. return;
  8456. }
  8457. conn->status_code = 304;
  8458. gmt_time_string(date, sizeof(date), &curtime);
  8459. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8460. construct_etag(etag, sizeof(etag), &filep->stat);
  8461. (void)mg_printf(conn,
  8462. "HTTP/1.1 %d %s\r\n"
  8463. "Date: %s\r\n",
  8464. conn->status_code,
  8465. mg_get_response_code_text(conn, conn->status_code),
  8466. date);
  8467. send_static_cache_header(conn);
  8468. send_additional_header(conn);
  8469. (void)mg_printf(conn,
  8470. "Last-Modified: %s\r\n"
  8471. "Etag: %s\r\n"
  8472. "Connection: %s\r\n"
  8473. "\r\n",
  8474. lm,
  8475. etag,
  8476. suggest_connection_header(conn));
  8477. }
  8478. #endif
  8479. void
  8480. mg_send_file(struct mg_connection *conn, const char *path)
  8481. {
  8482. mg_send_mime_file2(conn, path, NULL, NULL);
  8483. }
  8484. void
  8485. mg_send_mime_file(struct mg_connection *conn,
  8486. const char *path,
  8487. const char *mime_type)
  8488. {
  8489. mg_send_mime_file2(conn, path, mime_type, NULL);
  8490. }
  8491. void
  8492. mg_send_mime_file2(struct mg_connection *conn,
  8493. const char *path,
  8494. const char *mime_type,
  8495. const char *additional_headers)
  8496. {
  8497. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8498. if (!conn) {
  8499. /* No conn */
  8500. return;
  8501. }
  8502. if (mg_stat(conn, path, &file.stat)) {
  8503. #if !defined(NO_CACHING)
  8504. if (is_not_modified(conn, &file.stat)) {
  8505. /* Send 304 "Not Modified" - this must not send any body data */
  8506. handle_not_modified_static_file_request(conn, &file);
  8507. } else
  8508. #endif /* NO_CACHING */
  8509. if (file.stat.is_directory) {
  8510. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8511. "yes")) {
  8512. handle_directory_request(conn, path);
  8513. } else {
  8514. mg_send_http_error(conn,
  8515. 403,
  8516. "%s",
  8517. "Error: Directory listing denied");
  8518. }
  8519. } else {
  8520. handle_static_file_request(
  8521. conn, path, &file, mime_type, additional_headers);
  8522. }
  8523. } else {
  8524. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8525. }
  8526. }
  8527. /* For a given PUT path, create all intermediate subdirectories.
  8528. * Return 0 if the path itself is a directory.
  8529. * Return 1 if the path leads to a file.
  8530. * Return -1 for if the path is too long.
  8531. * Return -2 if path can not be created.
  8532. */
  8533. static int
  8534. put_dir(struct mg_connection *conn, const char *path)
  8535. {
  8536. char buf[PATH_MAX];
  8537. const char *s, *p;
  8538. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8539. size_t len;
  8540. int res = 1;
  8541. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8542. len = (size_t)(p - path);
  8543. if (len >= sizeof(buf)) {
  8544. /* path too long */
  8545. res = -1;
  8546. break;
  8547. }
  8548. memcpy(buf, path, len);
  8549. buf[len] = '\0';
  8550. /* Try to create intermediate directory */
  8551. DEBUG_TRACE("mkdir(%s)", buf);
  8552. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8553. /* path does not exixt and can not be created */
  8554. res = -2;
  8555. break;
  8556. }
  8557. /* Is path itself a directory? */
  8558. if (p[1] == '\0') {
  8559. res = 0;
  8560. }
  8561. }
  8562. return res;
  8563. }
  8564. static void
  8565. remove_bad_file(const struct mg_connection *conn, const char *path)
  8566. {
  8567. int r = mg_remove(conn, path);
  8568. if (r != 0) {
  8569. mg_cry_internal(conn,
  8570. "%s: Cannot remove invalid file %s",
  8571. __func__,
  8572. path);
  8573. }
  8574. }
  8575. long long
  8576. mg_store_body(struct mg_connection *conn, const char *path)
  8577. {
  8578. char buf[MG_BUF_LEN];
  8579. long long len = 0;
  8580. int ret, n;
  8581. struct mg_file fi;
  8582. if (conn->consumed_content != 0) {
  8583. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8584. return -11;
  8585. }
  8586. ret = put_dir(conn, path);
  8587. if (ret < 0) {
  8588. /* -1 for path too long,
  8589. * -2 for path can not be created. */
  8590. return ret;
  8591. }
  8592. if (ret != 1) {
  8593. /* Return 0 means, path itself is a directory. */
  8594. return 0;
  8595. }
  8596. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8597. return -12;
  8598. }
  8599. ret = mg_read(conn, buf, sizeof(buf));
  8600. while (ret > 0) {
  8601. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8602. if (n != ret) {
  8603. (void)mg_fclose(
  8604. &fi.access); /* File is bad and will be removed anyway. */
  8605. remove_bad_file(conn, path);
  8606. return -13;
  8607. }
  8608. len += ret;
  8609. ret = mg_read(conn, buf, sizeof(buf));
  8610. }
  8611. /* File is open for writing. If fclose fails, there was probably an
  8612. * error flushing the buffer to disk, so the file on disk might be
  8613. * broken. Delete it and return an error to the caller. */
  8614. if (mg_fclose(&fi.access) != 0) {
  8615. remove_bad_file(conn, path);
  8616. return -14;
  8617. }
  8618. return len;
  8619. }
  8620. /* Parse a buffer:
  8621. * Forward the string pointer till the end of a word, then
  8622. * terminate it and forward till the begin of the next word.
  8623. */
  8624. static int
  8625. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8626. {
  8627. /* Forward until a space is found - use isgraph here */
  8628. /* See http://www.cplusplus.com/reference/cctype/ */
  8629. while (isgraph((unsigned char)**ppw)) {
  8630. (*ppw)++;
  8631. }
  8632. /* Check end of word */
  8633. if (eol) {
  8634. /* must be a end of line */
  8635. if ((**ppw != '\r') && (**ppw != '\n')) {
  8636. return -1;
  8637. }
  8638. } else {
  8639. /* must be a end of a word, but not a line */
  8640. if (**ppw != ' ') {
  8641. return -1;
  8642. }
  8643. }
  8644. /* Terminate and forward to the next word */
  8645. do {
  8646. **ppw = 0;
  8647. (*ppw)++;
  8648. } while (isspace((unsigned char)**ppw));
  8649. /* Check after term */
  8650. if (!eol) {
  8651. /* if it's not the end of line, there must be a next word */
  8652. if (!isgraph((unsigned char)**ppw)) {
  8653. return -1;
  8654. }
  8655. }
  8656. /* ok */
  8657. return 1;
  8658. }
  8659. /* Parse HTTP headers from the given buffer, advance buf pointer
  8660. * to the point where parsing stopped.
  8661. * All parameters must be valid pointers (not NULL).
  8662. * Return <0 on error. */
  8663. static int
  8664. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8665. {
  8666. int i;
  8667. int num_headers = 0;
  8668. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8669. char *dp = *buf;
  8670. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8671. dp++;
  8672. }
  8673. if (dp == *buf) {
  8674. /* End of headers reached. */
  8675. break;
  8676. }
  8677. if (*dp != ':') {
  8678. /* This is not a valid field. */
  8679. return -1;
  8680. }
  8681. /* End of header key (*dp == ':') */
  8682. /* Truncate here and set the key name */
  8683. *dp = 0;
  8684. hdr[i].name = *buf;
  8685. do {
  8686. dp++;
  8687. } while (*dp == ' ');
  8688. /* The rest of the line is the value */
  8689. hdr[i].value = dp;
  8690. *buf = dp + strcspn(dp, "\r\n");
  8691. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8692. *buf = NULL;
  8693. }
  8694. num_headers = i + 1;
  8695. if (*buf) {
  8696. (*buf)[0] = 0;
  8697. (*buf)[1] = 0;
  8698. *buf += 2;
  8699. } else {
  8700. *buf = dp;
  8701. break;
  8702. }
  8703. if ((*buf)[0] == '\r') {
  8704. /* This is the end of the header */
  8705. break;
  8706. }
  8707. }
  8708. return num_headers;
  8709. }
  8710. struct mg_http_method_info {
  8711. const char *name;
  8712. int request_has_body;
  8713. int response_has_body;
  8714. int is_safe;
  8715. int is_idempotent;
  8716. int is_cacheable;
  8717. };
  8718. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8719. static struct mg_http_method_info http_methods[] = {
  8720. /* HTTP (RFC 2616) */
  8721. {"GET", 0, 1, 1, 1, 1},
  8722. {"POST", 1, 1, 0, 0, 0},
  8723. {"PUT", 1, 0, 0, 1, 0},
  8724. {"DELETE", 0, 0, 0, 1, 0},
  8725. {"HEAD", 0, 0, 1, 1, 1},
  8726. {"OPTIONS", 0, 0, 1, 1, 0},
  8727. {"CONNECT", 1, 1, 0, 0, 0},
  8728. /* TRACE method (RFC 2616) is not supported for security reasons */
  8729. /* PATCH method (RFC 5789) */
  8730. {"PATCH", 1, 0, 0, 0, 0},
  8731. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8732. /* WEBDAV (RFC 2518) */
  8733. {"PROPFIND", 0, 1, 1, 1, 0},
  8734. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8735. * Some PROPFIND results MAY be cached, with care,
  8736. * as there is no cache validation mechanism for
  8737. * most properties. This method is both safe and
  8738. * idempotent (see Section 9.1 of [RFC2616]). */
  8739. {"MKCOL", 0, 0, 0, 1, 0},
  8740. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8741. * When MKCOL is invoked without a request body,
  8742. * the newly created collection SHOULD have no
  8743. * members. A MKCOL request message may contain
  8744. * a message body. The precise behavior of a MKCOL
  8745. * request when the body is present is undefined,
  8746. * ... ==> We do not support MKCOL with body data.
  8747. * This method is idempotent, but not safe (see
  8748. * Section 9.1 of [RFC2616]). Responses to this
  8749. * method MUST NOT be cached. */
  8750. /* Unsupported WEBDAV Methods: */
  8751. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8752. /* + 11 methods from RFC 3253 */
  8753. /* ORDERPATCH (RFC 3648) */
  8754. /* ACL (RFC 3744) */
  8755. /* SEARCH (RFC 5323) */
  8756. /* + MicroSoft extensions
  8757. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8758. /* REPORT method (RFC 3253) */
  8759. {"REPORT", 1, 1, 1, 1, 1},
  8760. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8761. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8762. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8763. * to be useful for REST in case a "GET request with body" is
  8764. * required. */
  8765. {NULL, 0, 0, 0, 0, 0}
  8766. /* end of list */
  8767. };
  8768. static const struct mg_http_method_info *
  8769. get_http_method_info(const char *method)
  8770. {
  8771. /* Check if the method is known to the server. The list of all known
  8772. * HTTP methods can be found here at
  8773. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8774. */
  8775. const struct mg_http_method_info *m = http_methods;
  8776. while (m->name) {
  8777. if (!strcmp(m->name, method)) {
  8778. return m;
  8779. }
  8780. m++;
  8781. }
  8782. return NULL;
  8783. }
  8784. static int
  8785. is_valid_http_method(const char *method)
  8786. {
  8787. return (get_http_method_info(method) != NULL);
  8788. }
  8789. /* Parse HTTP request, fill in mg_request_info structure.
  8790. * This function modifies the buffer by NUL-terminating
  8791. * HTTP request components, header names and header values.
  8792. * Parameters:
  8793. * buf (in/out): pointer to the HTTP header to parse and split
  8794. * len (in): length of HTTP header buffer
  8795. * re (out): parsed header as mg_request_info
  8796. * buf and ri must be valid pointers (not NULL), len>0.
  8797. * Returns <0 on error. */
  8798. static int
  8799. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8800. {
  8801. int request_length;
  8802. int init_skip = 0;
  8803. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8804. * remote_port */
  8805. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8806. NULL;
  8807. ri->num_headers = 0;
  8808. /* RFC says that all initial whitespaces should be ingored */
  8809. /* This included all leading \r and \n (isspace) */
  8810. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8811. while ((len > 0) && isspace((unsigned char)*buf)) {
  8812. buf++;
  8813. len--;
  8814. init_skip++;
  8815. }
  8816. if (len == 0) {
  8817. /* Incomplete request */
  8818. return 0;
  8819. }
  8820. /* Control characters are not allowed, including zero */
  8821. if (iscntrl((unsigned char)*buf)) {
  8822. return -1;
  8823. }
  8824. /* Find end of HTTP header */
  8825. request_length = get_http_header_len(buf, len);
  8826. if (request_length <= 0) {
  8827. return request_length;
  8828. }
  8829. buf[request_length - 1] = '\0';
  8830. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8831. return -1;
  8832. }
  8833. /* The first word has to be the HTTP method */
  8834. ri->request_method = buf;
  8835. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8836. return -1;
  8837. }
  8838. /* Check for a valid http method */
  8839. if (!is_valid_http_method(ri->request_method)) {
  8840. return -1;
  8841. }
  8842. /* The second word is the URI */
  8843. ri->request_uri = buf;
  8844. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8845. return -1;
  8846. }
  8847. /* Next would be the HTTP version */
  8848. ri->http_version = buf;
  8849. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8850. return -1;
  8851. }
  8852. /* Check for a valid HTTP version key */
  8853. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8854. /* Invalid request */
  8855. return -1;
  8856. }
  8857. ri->http_version += 5;
  8858. /* Parse all HTTP headers */
  8859. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8860. if (ri->num_headers < 0) {
  8861. /* Error while parsing headers */
  8862. return -1;
  8863. }
  8864. return request_length + init_skip;
  8865. }
  8866. static int
  8867. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8868. {
  8869. int response_length;
  8870. int init_skip = 0;
  8871. char *tmp, *tmp2;
  8872. long l;
  8873. /* Initialize elements. */
  8874. ri->http_version = ri->status_text = NULL;
  8875. ri->num_headers = ri->status_code = 0;
  8876. /* RFC says that all initial whitespaces should be ingored */
  8877. /* This included all leading \r and \n (isspace) */
  8878. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8879. while ((len > 0) && isspace((unsigned char)*buf)) {
  8880. buf++;
  8881. len--;
  8882. init_skip++;
  8883. }
  8884. if (len == 0) {
  8885. /* Incomplete request */
  8886. return 0;
  8887. }
  8888. /* Control characters are not allowed, including zero */
  8889. if (iscntrl((unsigned char)*buf)) {
  8890. return -1;
  8891. }
  8892. /* Find end of HTTP header */
  8893. response_length = get_http_header_len(buf, len);
  8894. if (response_length <= 0) {
  8895. return response_length;
  8896. }
  8897. buf[response_length - 1] = '\0';
  8898. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8899. return -1;
  8900. }
  8901. /* The first word is the HTTP version */
  8902. /* Check for a valid HTTP version key */
  8903. if (strncmp(buf, "HTTP/", 5) != 0) {
  8904. /* Invalid request */
  8905. return -1;
  8906. }
  8907. buf += 5;
  8908. if (!isgraph((unsigned char)buf[0])) {
  8909. /* Invalid request */
  8910. return -1;
  8911. }
  8912. ri->http_version = buf;
  8913. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8914. return -1;
  8915. }
  8916. /* The second word is the status as a number */
  8917. tmp = buf;
  8918. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8919. return -1;
  8920. }
  8921. l = strtol(tmp, &tmp2, 10);
  8922. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8923. /* Everything else but a 3 digit code is invalid */
  8924. return -1;
  8925. }
  8926. ri->status_code = (int)l;
  8927. /* The rest of the line is the status text */
  8928. ri->status_text = buf;
  8929. /* Find end of status text */
  8930. /* isgraph or isspace = isprint */
  8931. while (isprint((unsigned char)*buf)) {
  8932. buf++;
  8933. }
  8934. if ((*buf != '\r') && (*buf != '\n')) {
  8935. return -1;
  8936. }
  8937. /* Terminate string and forward buf to next line */
  8938. do {
  8939. *buf = 0;
  8940. buf++;
  8941. } while (isspace((unsigned char)*buf));
  8942. /* Parse all HTTP headers */
  8943. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8944. if (ri->num_headers < 0) {
  8945. /* Error while parsing headers */
  8946. return -1;
  8947. }
  8948. return response_length + init_skip;
  8949. }
  8950. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8951. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8952. * buffer (which marks the end of HTTP request). Buffer buf may already
  8953. * have some data. The length of the data is stored in nread.
  8954. * Upon every read operation, increase nread by the number of bytes read. */
  8955. static int
  8956. read_message(FILE *fp,
  8957. struct mg_connection *conn,
  8958. char *buf,
  8959. int bufsiz,
  8960. int *nread)
  8961. {
  8962. int request_len, n = 0;
  8963. struct timespec last_action_time;
  8964. double request_timeout;
  8965. if (!conn) {
  8966. return 0;
  8967. }
  8968. memset(&last_action_time, 0, sizeof(last_action_time));
  8969. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8970. /* value of request_timeout is in seconds, config in milliseconds */
  8971. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8972. } else {
  8973. request_timeout = -1.0;
  8974. }
  8975. if (conn->handled_requests > 0) {
  8976. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8977. request_timeout =
  8978. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8979. }
  8980. }
  8981. request_len = get_http_header_len(buf, *nread);
  8982. /* first time reading from this connection */
  8983. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8984. while (request_len == 0) {
  8985. /* Full request not yet received */
  8986. if (conn->phys_ctx->stop_flag != 0) {
  8987. /* Server is to be stopped. */
  8988. return -1;
  8989. }
  8990. if (*nread >= bufsiz) {
  8991. /* Request too long */
  8992. return -2;
  8993. }
  8994. n = pull_inner(
  8995. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8996. if (n == -2) {
  8997. /* Receive error */
  8998. return -1;
  8999. }
  9000. if (n > 0) {
  9001. *nread += n;
  9002. request_len = get_http_header_len(buf, *nread);
  9003. } else {
  9004. request_len = 0;
  9005. }
  9006. if ((request_len == 0) && (request_timeout >= 0)) {
  9007. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9008. > request_timeout) {
  9009. /* Timeout */
  9010. return -1;
  9011. }
  9012. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9013. }
  9014. }
  9015. return request_len;
  9016. }
  9017. #if !defined(NO_CGI) || !defined(NO_FILES)
  9018. static int
  9019. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9020. {
  9021. const char *expect;
  9022. char buf[MG_BUF_LEN];
  9023. int success = 0;
  9024. if (!conn) {
  9025. return 0;
  9026. }
  9027. expect = mg_get_header(conn, "Expect");
  9028. DEBUG_ASSERT(fp != NULL);
  9029. if (!fp) {
  9030. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9031. return 0;
  9032. }
  9033. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9034. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9035. */
  9036. mg_send_http_error(conn,
  9037. 417,
  9038. "Error: Can not fulfill expectation %s",
  9039. expect);
  9040. } else {
  9041. if (expect != NULL) {
  9042. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9043. conn->status_code = 100;
  9044. } else {
  9045. conn->status_code = 200;
  9046. }
  9047. DEBUG_ASSERT(conn->consumed_content == 0);
  9048. if (conn->consumed_content != 0) {
  9049. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9050. return 0;
  9051. }
  9052. for (;;) {
  9053. int nread = mg_read(conn, buf, sizeof(buf));
  9054. if (nread <= 0) {
  9055. success = (nread == 0);
  9056. break;
  9057. }
  9058. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9059. break;
  9060. }
  9061. }
  9062. /* Each error code path in this function must send an error */
  9063. if (!success) {
  9064. /* NOTE: Maybe some data has already been sent. */
  9065. /* TODO (low): If some data has been sent, a correct error
  9066. * reply can no longer be sent, so just close the connection */
  9067. mg_send_http_error(conn, 500, "%s", "");
  9068. }
  9069. }
  9070. return success;
  9071. }
  9072. #endif
  9073. #if defined(USE_TIMERS)
  9074. #define TIMER_API static
  9075. #include "timer.inl"
  9076. #endif /* USE_TIMERS */
  9077. #if !defined(NO_CGI)
  9078. /* This structure helps to create an environment for the spawned CGI
  9079. * program.
  9080. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9081. * last element must be NULL.
  9082. * However, on Windows there is a requirement that all these
  9083. * VARIABLE=VALUE\0
  9084. * strings must reside in a contiguous buffer. The end of the buffer is
  9085. * marked by two '\0' characters.
  9086. * We satisfy both worlds: we create an envp array (which is vars), all
  9087. * entries are actually pointers inside buf. */
  9088. struct cgi_environment {
  9089. struct mg_connection *conn;
  9090. /* Data block */
  9091. char *buf; /* Environment buffer */
  9092. size_t buflen; /* Space available in buf */
  9093. size_t bufused; /* Space taken in buf */
  9094. /* Index block */
  9095. char **var; /* char **envp */
  9096. size_t varlen; /* Number of variables available in var */
  9097. size_t varused; /* Number of variables stored in var */
  9098. };
  9099. static void addenv(struct cgi_environment *env,
  9100. PRINTF_FORMAT_STRING(const char *fmt),
  9101. ...) PRINTF_ARGS(2, 3);
  9102. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9103. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9104. static void
  9105. addenv(struct cgi_environment *env, const char *fmt, ...)
  9106. {
  9107. size_t i, n, space;
  9108. int truncated = 0;
  9109. char *added;
  9110. va_list ap;
  9111. if ((env->varlen - env->varused) < 2) {
  9112. mg_cry_internal(env->conn,
  9113. "%s: Cannot register CGI variable [%s]",
  9114. __func__,
  9115. fmt);
  9116. return;
  9117. }
  9118. /* Calculate how much space is left in the buffer */
  9119. space = (env->buflen - env->bufused);
  9120. do {
  9121. /* Space for "\0\0" is always needed. */
  9122. if (space <= 2) {
  9123. /* Allocate new buffer */
  9124. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9125. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9126. if (!added) {
  9127. /* Out of memory */
  9128. mg_cry_internal(
  9129. env->conn,
  9130. "%s: Cannot allocate memory for CGI variable [%s]",
  9131. __func__,
  9132. fmt);
  9133. return;
  9134. }
  9135. /* Retarget pointers */
  9136. env->buf = added;
  9137. env->buflen = n;
  9138. for (i = 0, n = 0; i < env->varused; i++) {
  9139. env->var[i] = added + n;
  9140. n += strlen(added + n) + 1;
  9141. }
  9142. space = (env->buflen - env->bufused);
  9143. }
  9144. /* Make a pointer to the free space int the buffer */
  9145. added = env->buf + env->bufused;
  9146. /* Copy VARIABLE=VALUE\0 string into the free space */
  9147. va_start(ap, fmt);
  9148. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9149. va_end(ap);
  9150. /* Do not add truncated strings to the environment */
  9151. if (truncated) {
  9152. /* Reallocate the buffer */
  9153. space = 0;
  9154. }
  9155. } while (truncated);
  9156. /* Calculate number of bytes added to the environment */
  9157. n = strlen(added) + 1;
  9158. env->bufused += n;
  9159. /* Append a pointer to the added string into the envp array */
  9160. env->var[env->varused] = added;
  9161. env->varused++;
  9162. }
  9163. /* Return 0 on success, non-zero if an error occurs. */
  9164. static int
  9165. prepare_cgi_environment(struct mg_connection *conn,
  9166. const char *prog,
  9167. struct cgi_environment *env)
  9168. {
  9169. const char *s;
  9170. struct vec var_vec;
  9171. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9172. int i, truncated, uri_len;
  9173. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9174. return -1;
  9175. }
  9176. env->conn = conn;
  9177. env->buflen = CGI_ENVIRONMENT_SIZE;
  9178. env->bufused = 0;
  9179. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9180. if (env->buf == NULL) {
  9181. mg_cry_internal(conn,
  9182. "%s: Not enough memory for environmental buffer",
  9183. __func__);
  9184. return -1;
  9185. }
  9186. env->varlen = MAX_CGI_ENVIR_VARS;
  9187. env->varused = 0;
  9188. env->var =
  9189. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9190. if (env->var == NULL) {
  9191. mg_cry_internal(conn,
  9192. "%s: Not enough memory for environmental variables",
  9193. __func__);
  9194. mg_free(env->buf);
  9195. return -1;
  9196. }
  9197. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9198. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9199. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9200. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9201. /* Prepare the environment block */
  9202. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9203. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9204. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9205. #if defined(USE_IPV6)
  9206. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9207. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9208. } else
  9209. #endif
  9210. {
  9211. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9212. }
  9213. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9214. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9215. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9216. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9217. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9218. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9219. /* SCRIPT_NAME */
  9220. uri_len = (int)strlen(conn->request_info.local_uri);
  9221. if (conn->path_info == NULL) {
  9222. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9223. /* URI: /path_to_script/script.cgi */
  9224. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9225. } else {
  9226. /* URI: /path_to_script/ ... using index.cgi */
  9227. const char *index_file = strrchr(prog, '/');
  9228. if (index_file) {
  9229. addenv(env,
  9230. "SCRIPT_NAME=%s%s",
  9231. conn->request_info.local_uri,
  9232. index_file + 1);
  9233. }
  9234. }
  9235. } else {
  9236. /* URI: /path_to_script/script.cgi/path_info */
  9237. addenv(env,
  9238. "SCRIPT_NAME=%.*s",
  9239. uri_len - (int)strlen(conn->path_info),
  9240. conn->request_info.local_uri);
  9241. }
  9242. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9243. if (conn->path_info == NULL) {
  9244. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9245. } else {
  9246. addenv(env,
  9247. "PATH_TRANSLATED=%s%s",
  9248. conn->dom_ctx->config[DOCUMENT_ROOT],
  9249. conn->path_info);
  9250. }
  9251. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9252. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9253. addenv(env, "CONTENT_TYPE=%s", s);
  9254. }
  9255. if (conn->request_info.query_string != NULL) {
  9256. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9257. }
  9258. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9259. addenv(env, "CONTENT_LENGTH=%s", s);
  9260. }
  9261. if ((s = getenv("PATH")) != NULL) {
  9262. addenv(env, "PATH=%s", s);
  9263. }
  9264. if (conn->path_info != NULL) {
  9265. addenv(env, "PATH_INFO=%s", conn->path_info);
  9266. }
  9267. if (conn->status_code > 0) {
  9268. /* CGI error handler should show the status code */
  9269. addenv(env, "STATUS=%d", conn->status_code);
  9270. }
  9271. #if defined(_WIN32)
  9272. if ((s = getenv("COMSPEC")) != NULL) {
  9273. addenv(env, "COMSPEC=%s", s);
  9274. }
  9275. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9276. addenv(env, "SYSTEMROOT=%s", s);
  9277. }
  9278. if ((s = getenv("SystemDrive")) != NULL) {
  9279. addenv(env, "SystemDrive=%s", s);
  9280. }
  9281. if ((s = getenv("ProgramFiles")) != NULL) {
  9282. addenv(env, "ProgramFiles=%s", s);
  9283. }
  9284. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9285. addenv(env, "ProgramFiles(x86)=%s", s);
  9286. }
  9287. #else
  9288. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9289. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9290. }
  9291. #endif /* _WIN32 */
  9292. if ((s = getenv("PERLLIB")) != NULL) {
  9293. addenv(env, "PERLLIB=%s", s);
  9294. }
  9295. if (conn->request_info.remote_user != NULL) {
  9296. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9297. addenv(env, "%s", "AUTH_TYPE=Digest");
  9298. }
  9299. /* Add all headers as HTTP_* variables */
  9300. for (i = 0; i < conn->request_info.num_headers; i++) {
  9301. (void)mg_snprintf(conn,
  9302. &truncated,
  9303. http_var_name,
  9304. sizeof(http_var_name),
  9305. "HTTP_%s",
  9306. conn->request_info.http_headers[i].name);
  9307. if (truncated) {
  9308. mg_cry_internal(conn,
  9309. "%s: HTTP header variable too long [%s]",
  9310. __func__,
  9311. conn->request_info.http_headers[i].name);
  9312. continue;
  9313. }
  9314. /* Convert variable name into uppercase, and change - to _ */
  9315. for (p = http_var_name; *p != '\0'; p++) {
  9316. if (*p == '-') {
  9317. *p = '_';
  9318. }
  9319. *p = (char)toupper((unsigned char)*p);
  9320. }
  9321. addenv(env,
  9322. "%s=%s",
  9323. http_var_name,
  9324. conn->request_info.http_headers[i].value);
  9325. }
  9326. /* Add user-specified variables */
  9327. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9328. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9329. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9330. }
  9331. env->var[env->varused] = NULL;
  9332. env->buf[env->bufused] = '\0';
  9333. return 0;
  9334. }
  9335. /* Data for CGI process control: PID and number of references */
  9336. struct process_control_data {
  9337. pid_t pid;
  9338. int references;
  9339. };
  9340. static int
  9341. abort_process(void *data)
  9342. {
  9343. /* Waitpid checks for child status and won't work for a pid that does not
  9344. * identify a child of the current process. Thus, if the pid is reused,
  9345. * we will not affect a different process. */
  9346. struct process_control_data *proc = (struct process_control_data *)data;
  9347. int status = 0;
  9348. int refs;
  9349. pid_t ret_pid;
  9350. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9351. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9352. /* Stop child process */
  9353. DEBUG_TRACE("CGI timer: Stop child process %p\n", proc->pid);
  9354. kill(proc->pid, SIGABRT);
  9355. /* Wait until process is terminated (don't leave zombies) */
  9356. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9357. ;
  9358. } else {
  9359. DEBUG_TRACE("CGI timer: Child process %p already stopped\n", proc->pid);
  9360. }
  9361. /* Dec reference counter */
  9362. refs = mg_atomic_dec(&proc->references);
  9363. if (refs == 0) {
  9364. /* no more references - free data */
  9365. mg_free(data);
  9366. }
  9367. return 0;
  9368. }
  9369. /* Local (static) function assumes all arguments are valid. */
  9370. static void
  9371. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9372. {
  9373. char *buf;
  9374. size_t buflen;
  9375. int headers_len, data_len, i, truncated;
  9376. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9377. const char *status, *status_text, *connection_state;
  9378. char *pbuf, dir[PATH_MAX], *p;
  9379. struct mg_request_info ri;
  9380. struct cgi_environment blk;
  9381. FILE *in = NULL, *out = NULL, *err = NULL;
  9382. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9383. pid_t pid = (pid_t)-1;
  9384. struct process_control_data *proc = NULL;
  9385. #if defined(USE_TIMERS)
  9386. double cgi_timeout = -1.0;
  9387. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9388. /* Get timeout in seconds */
  9389. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9390. }
  9391. #endif
  9392. buf = NULL;
  9393. buflen = conn->phys_ctx->max_request_size;
  9394. i = prepare_cgi_environment(conn, prog, &blk);
  9395. if (i != 0) {
  9396. blk.buf = NULL;
  9397. blk.var = NULL;
  9398. goto done;
  9399. }
  9400. /* CGI must be executed in its own directory. 'dir' must point to the
  9401. * directory containing executable program, 'p' must point to the
  9402. * executable program name relative to 'dir'. */
  9403. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9404. if (truncated) {
  9405. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9406. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9407. goto done;
  9408. }
  9409. if ((p = strrchr(dir, '/')) != NULL) {
  9410. *p++ = '\0';
  9411. } else {
  9412. dir[0] = '.';
  9413. dir[1] = '\0';
  9414. p = (char *)prog;
  9415. }
  9416. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9417. status = strerror(ERRNO);
  9418. mg_cry_internal(
  9419. conn,
  9420. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9421. prog,
  9422. status);
  9423. mg_send_http_error(conn,
  9424. 500,
  9425. "Error: Cannot create CGI pipe: %s",
  9426. status);
  9427. goto done;
  9428. }
  9429. proc = (struct process_control_data *)
  9430. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9431. if (proc == NULL) {
  9432. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9433. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9434. goto done;
  9435. }
  9436. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9437. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9438. if (pid == (pid_t)-1) {
  9439. status = strerror(ERRNO);
  9440. mg_cry_internal(
  9441. conn,
  9442. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9443. prog,
  9444. status);
  9445. mg_send_http_error(conn,
  9446. 500,
  9447. "Error: Cannot spawn CGI process [%s]: %s",
  9448. prog,
  9449. status);
  9450. mg_free(proc);
  9451. proc = NULL;
  9452. goto done;
  9453. }
  9454. /* Store data in shared process_control_data */
  9455. proc->pid = pid;
  9456. proc->references = 1;
  9457. #if defined(USE_TIMERS)
  9458. if (cgi_timeout > 0.0) {
  9459. proc->references = 2;
  9460. // Start a timer for CGI
  9461. timer_add(conn->phys_ctx,
  9462. cgi_timeout /* in seconds */,
  9463. 0.0,
  9464. 1,
  9465. abort_process,
  9466. (void *)proc);
  9467. }
  9468. #endif
  9469. /* Parent closes only one side of the pipes.
  9470. * If we don't mark them as closed, close() attempt before
  9471. * return from this function throws an exception on Windows.
  9472. * Windows does not like when closed descriptor is closed again. */
  9473. (void)close(fdin[0]);
  9474. (void)close(fdout[1]);
  9475. (void)close(fderr[1]);
  9476. fdin[0] = fdout[1] = fderr[1] = -1;
  9477. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9478. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9479. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9480. status = strerror(ERRNO);
  9481. mg_cry_internal(conn,
  9482. "Error: CGI program \"%s\": Can not open fd: %s",
  9483. prog,
  9484. status);
  9485. mg_send_http_error(conn,
  9486. 500,
  9487. "Error: CGI can not open fd\nfdopen: %s",
  9488. status);
  9489. goto done;
  9490. }
  9491. setbuf(in, NULL);
  9492. setbuf(out, NULL);
  9493. setbuf(err, NULL);
  9494. fout.access.fp = out;
  9495. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9496. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9497. conn->content_len);
  9498. /* This is a POST/PUT request, or another request with body data. */
  9499. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9500. /* Error sending the body data */
  9501. mg_cry_internal(
  9502. conn,
  9503. "Error: CGI program \"%s\": Forward body data failed",
  9504. prog);
  9505. goto done;
  9506. }
  9507. }
  9508. /* Close so child gets an EOF. */
  9509. fclose(in);
  9510. in = NULL;
  9511. fdin[1] = -1;
  9512. /* Now read CGI reply into a buffer. We need to set correct
  9513. * status code, thus we need to see all HTTP headers first.
  9514. * Do not send anything back to client, until we buffer in all
  9515. * HTTP headers. */
  9516. data_len = 0;
  9517. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9518. if (buf == NULL) {
  9519. mg_send_http_error(conn,
  9520. 500,
  9521. "Error: Not enough memory for CGI buffer (%u bytes)",
  9522. (unsigned int)buflen);
  9523. mg_cry_internal(
  9524. conn,
  9525. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9526. "bytes)",
  9527. prog,
  9528. (unsigned int)buflen);
  9529. goto done;
  9530. }
  9531. DEBUG_TRACE("CGI: %s", "wait for response");
  9532. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9533. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9534. if (headers_len <= 0) {
  9535. /* Could not parse the CGI response. Check if some error message on
  9536. * stderr. */
  9537. i = pull_all(err, conn, buf, (int)buflen);
  9538. if (i > 0) {
  9539. /* CGI program explicitly sent an error */
  9540. /* Write the error message to the internal log */
  9541. mg_cry_internal(conn,
  9542. "Error: CGI program \"%s\" sent error "
  9543. "message: [%.*s]",
  9544. prog,
  9545. i,
  9546. buf);
  9547. /* Don't send the error message back to the client */
  9548. mg_send_http_error(conn,
  9549. 500,
  9550. "Error: CGI program \"%s\" failed.",
  9551. prog);
  9552. } else {
  9553. /* CGI program did not explicitly send an error, but a broken
  9554. * respon header */
  9555. mg_cry_internal(conn,
  9556. "Error: CGI program sent malformed or too big "
  9557. "(>%u bytes) HTTP headers: [%.*s]",
  9558. (unsigned)buflen,
  9559. data_len,
  9560. buf);
  9561. mg_send_http_error(conn,
  9562. 500,
  9563. "Error: CGI program sent malformed or too big "
  9564. "(>%u bytes) HTTP headers: [%.*s]",
  9565. (unsigned)buflen,
  9566. data_len,
  9567. buf);
  9568. }
  9569. /* in both cases, abort processing CGI */
  9570. goto done;
  9571. }
  9572. pbuf = buf;
  9573. buf[headers_len - 1] = '\0';
  9574. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9575. /* Make up and send the status line */
  9576. status_text = "OK";
  9577. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9578. != NULL) {
  9579. conn->status_code = atoi(status);
  9580. status_text = status;
  9581. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9582. status_text++;
  9583. }
  9584. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9585. != NULL) {
  9586. conn->status_code = 307;
  9587. } else {
  9588. conn->status_code = 200;
  9589. }
  9590. connection_state =
  9591. get_header(ri.http_headers, ri.num_headers, "Connection");
  9592. if (!header_has_option(connection_state, "keep-alive")) {
  9593. conn->must_close = 1;
  9594. }
  9595. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9596. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9597. /* Send headers */
  9598. for (i = 0; i < ri.num_headers; i++) {
  9599. mg_printf(conn,
  9600. "%s: %s\r\n",
  9601. ri.http_headers[i].name,
  9602. ri.http_headers[i].value);
  9603. }
  9604. mg_write(conn, "\r\n", 2);
  9605. /* Send chunk of data that may have been read after the headers */
  9606. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9607. /* Read the rest of CGI output and send to the client */
  9608. DEBUG_TRACE("CGI: %s", "forward all data");
  9609. send_file_data(conn, &fout, 0, INT64_MAX);
  9610. DEBUG_TRACE("CGI: %s", "all data sent");
  9611. done:
  9612. mg_free(blk.var);
  9613. mg_free(blk.buf);
  9614. if (pid != (pid_t)-1) {
  9615. abort_process((void *)proc);
  9616. }
  9617. if (fdin[0] != -1) {
  9618. close(fdin[0]);
  9619. }
  9620. if (fdout[1] != -1) {
  9621. close(fdout[1]);
  9622. }
  9623. if (fderr[1] != -1) {
  9624. close(fderr[1]);
  9625. }
  9626. if (in != NULL) {
  9627. fclose(in);
  9628. } else if (fdin[1] != -1) {
  9629. close(fdin[1]);
  9630. }
  9631. if (out != NULL) {
  9632. fclose(out);
  9633. } else if (fdout[0] != -1) {
  9634. close(fdout[0]);
  9635. }
  9636. if (err != NULL) {
  9637. fclose(err);
  9638. } else if (fderr[0] != -1) {
  9639. close(fderr[0]);
  9640. }
  9641. mg_free(buf);
  9642. }
  9643. #endif /* !NO_CGI */
  9644. #if !defined(NO_FILES)
  9645. static void
  9646. mkcol(struct mg_connection *conn, const char *path)
  9647. {
  9648. int rc, body_len;
  9649. struct de de;
  9650. char date[64];
  9651. time_t curtime = time(NULL);
  9652. if (conn == NULL) {
  9653. return;
  9654. }
  9655. /* TODO (mid): Check the mg_send_http_error situations in this function
  9656. */
  9657. memset(&de.file, 0, sizeof(de.file));
  9658. if (!mg_stat(conn, path, &de.file)) {
  9659. mg_cry_internal(conn,
  9660. "%s: mg_stat(%s) failed: %s",
  9661. __func__,
  9662. path,
  9663. strerror(ERRNO));
  9664. }
  9665. if (de.file.last_modified) {
  9666. /* TODO (mid): This check does not seem to make any sense ! */
  9667. /* TODO (mid): Add a webdav unit test first, before changing
  9668. * anything here. */
  9669. mg_send_http_error(
  9670. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9671. return;
  9672. }
  9673. body_len = conn->data_len - conn->request_len;
  9674. if (body_len > 0) {
  9675. mg_send_http_error(
  9676. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9677. return;
  9678. }
  9679. rc = mg_mkdir(conn, path, 0755);
  9680. if (rc == 0) {
  9681. conn->status_code = 201;
  9682. gmt_time_string(date, sizeof(date), &curtime);
  9683. mg_printf(conn,
  9684. "HTTP/1.1 %d Created\r\n"
  9685. "Date: %s\r\n",
  9686. conn->status_code,
  9687. date);
  9688. send_static_cache_header(conn);
  9689. send_additional_header(conn);
  9690. mg_printf(conn,
  9691. "Content-Length: 0\r\n"
  9692. "Connection: %s\r\n\r\n",
  9693. suggest_connection_header(conn));
  9694. } else {
  9695. if (errno == EEXIST) {
  9696. mg_send_http_error(
  9697. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9698. } else if (errno == EACCES) {
  9699. mg_send_http_error(
  9700. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9701. } else if (errno == ENOENT) {
  9702. mg_send_http_error(
  9703. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9704. } else {
  9705. mg_send_http_error(
  9706. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9707. }
  9708. }
  9709. }
  9710. static void
  9711. put_file(struct mg_connection *conn, const char *path)
  9712. {
  9713. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9714. const char *range;
  9715. int64_t r1, r2;
  9716. int rc;
  9717. char date[64];
  9718. time_t curtime = time(NULL);
  9719. if (conn == NULL) {
  9720. return;
  9721. }
  9722. if (mg_stat(conn, path, &file.stat)) {
  9723. /* File already exists */
  9724. conn->status_code = 200;
  9725. if (file.stat.is_directory) {
  9726. /* This is an already existing directory,
  9727. * so there is nothing to do for the server. */
  9728. rc = 0;
  9729. } else {
  9730. /* File exists and is not a directory. */
  9731. /* Can it be replaced? */
  9732. #if defined(MG_USE_OPEN_FILE)
  9733. if (file.access.membuf != NULL) {
  9734. /* This is an "in-memory" file, that can not be replaced */
  9735. mg_send_http_error(conn,
  9736. 405,
  9737. "Error: Put not possible\nReplacing %s "
  9738. "is not supported",
  9739. path);
  9740. return;
  9741. }
  9742. #endif
  9743. /* Check if the server may write this file */
  9744. if (access(path, W_OK) == 0) {
  9745. /* Access granted */
  9746. conn->status_code = 200;
  9747. rc = 1;
  9748. } else {
  9749. mg_send_http_error(
  9750. conn,
  9751. 403,
  9752. "Error: Put not possible\nReplacing %s is not allowed",
  9753. path);
  9754. return;
  9755. }
  9756. }
  9757. } else {
  9758. /* File should be created */
  9759. conn->status_code = 201;
  9760. rc = put_dir(conn, path);
  9761. }
  9762. if (rc == 0) {
  9763. /* put_dir returns 0 if path is a directory */
  9764. gmt_time_string(date, sizeof(date), &curtime);
  9765. mg_printf(conn,
  9766. "HTTP/1.1 %d %s\r\n",
  9767. conn->status_code,
  9768. mg_get_response_code_text(NULL, conn->status_code));
  9769. send_no_cache_header(conn);
  9770. send_additional_header(conn);
  9771. mg_printf(conn,
  9772. "Date: %s\r\n"
  9773. "Content-Length: 0\r\n"
  9774. "Connection: %s\r\n\r\n",
  9775. date,
  9776. suggest_connection_header(conn));
  9777. /* Request to create a directory has been fulfilled successfully.
  9778. * No need to put a file. */
  9779. return;
  9780. }
  9781. if (rc == -1) {
  9782. /* put_dir returns -1 if the path is too long */
  9783. mg_send_http_error(conn,
  9784. 414,
  9785. "Error: Path too long\nput_dir(%s): %s",
  9786. path,
  9787. strerror(ERRNO));
  9788. return;
  9789. }
  9790. if (rc == -2) {
  9791. /* put_dir returns -2 if the directory can not be created */
  9792. mg_send_http_error(conn,
  9793. 500,
  9794. "Error: Can not create directory\nput_dir(%s): %s",
  9795. path,
  9796. strerror(ERRNO));
  9797. return;
  9798. }
  9799. /* A file should be created or overwritten. */
  9800. /* Currently CivetWeb does not nead read+write access. */
  9801. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9802. || file.access.fp == NULL) {
  9803. (void)mg_fclose(&file.access);
  9804. mg_send_http_error(conn,
  9805. 500,
  9806. "Error: Can not create file\nfopen(%s): %s",
  9807. path,
  9808. strerror(ERRNO));
  9809. return;
  9810. }
  9811. fclose_on_exec(&file.access, conn);
  9812. range = mg_get_header(conn, "Content-Range");
  9813. r1 = r2 = 0;
  9814. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9815. conn->status_code = 206; /* Partial content */
  9816. fseeko(file.access.fp, r1, SEEK_SET);
  9817. }
  9818. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9819. /* forward_body_data failed.
  9820. * The error code has already been sent to the client,
  9821. * and conn->status_code is already set. */
  9822. (void)mg_fclose(&file.access);
  9823. return;
  9824. }
  9825. if (mg_fclose(&file.access) != 0) {
  9826. /* fclose failed. This might have different reasons, but a likely
  9827. * one is "no space on disk", http 507. */
  9828. conn->status_code = 507;
  9829. }
  9830. gmt_time_string(date, sizeof(date), &curtime);
  9831. mg_printf(conn,
  9832. "HTTP/1.1 %d %s\r\n",
  9833. conn->status_code,
  9834. mg_get_response_code_text(NULL, conn->status_code));
  9835. send_no_cache_header(conn);
  9836. send_additional_header(conn);
  9837. mg_printf(conn,
  9838. "Date: %s\r\n"
  9839. "Content-Length: 0\r\n"
  9840. "Connection: %s\r\n\r\n",
  9841. date,
  9842. suggest_connection_header(conn));
  9843. }
  9844. static void
  9845. delete_file(struct mg_connection *conn, const char *path)
  9846. {
  9847. struct de de;
  9848. memset(&de.file, 0, sizeof(de.file));
  9849. if (!mg_stat(conn, path, &de.file)) {
  9850. /* mg_stat returns 0 if the file does not exist */
  9851. mg_send_http_error(conn,
  9852. 404,
  9853. "Error: Cannot delete file\nFile %s not found",
  9854. path);
  9855. return;
  9856. }
  9857. #if 0 /* Ignore if a file in memory is inside a folder */
  9858. if (de.access.membuf != NULL) {
  9859. /* the file is cached in memory */
  9860. mg_send_http_error(
  9861. conn,
  9862. 405,
  9863. "Error: Delete not possible\nDeleting %s is not supported",
  9864. path);
  9865. return;
  9866. }
  9867. #endif
  9868. if (de.file.is_directory) {
  9869. if (remove_directory(conn, path)) {
  9870. /* Delete is successful: Return 204 without content. */
  9871. mg_send_http_error(conn, 204, "%s", "");
  9872. } else {
  9873. /* Delete is not successful: Return 500 (Server error). */
  9874. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9875. }
  9876. return;
  9877. }
  9878. /* This is an existing file (not a directory).
  9879. * Check if write permission is granted. */
  9880. if (access(path, W_OK) != 0) {
  9881. /* File is read only */
  9882. mg_send_http_error(
  9883. conn,
  9884. 403,
  9885. "Error: Delete not possible\nDeleting %s is not allowed",
  9886. path);
  9887. return;
  9888. }
  9889. /* Try to delete it. */
  9890. if (mg_remove(conn, path) == 0) {
  9891. /* Delete was successful: Return 204 without content. */
  9892. mg_send_http_error(conn, 204, "%s", "");
  9893. } else {
  9894. /* Delete not successful (file locked). */
  9895. mg_send_http_error(conn,
  9896. 423,
  9897. "Error: Cannot delete file\nremove(%s): %s",
  9898. path,
  9899. strerror(ERRNO));
  9900. }
  9901. }
  9902. #endif /* !NO_FILES */
  9903. static void
  9904. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9905. static void
  9906. do_ssi_include(struct mg_connection *conn,
  9907. const char *ssi,
  9908. char *tag,
  9909. int include_level)
  9910. {
  9911. char file_name[MG_BUF_LEN], path[512], *p;
  9912. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9913. size_t len;
  9914. int truncated = 0;
  9915. if (conn == NULL) {
  9916. return;
  9917. }
  9918. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9919. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9920. * always < MG_BUF_LEN. */
  9921. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9922. /* File name is relative to the webserver root */
  9923. file_name[511] = 0;
  9924. (void)mg_snprintf(conn,
  9925. &truncated,
  9926. path,
  9927. sizeof(path),
  9928. "%s/%s",
  9929. conn->dom_ctx->config[DOCUMENT_ROOT],
  9930. file_name);
  9931. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9932. /* File name is relative to the webserver working directory
  9933. * or it is absolute system path */
  9934. file_name[511] = 0;
  9935. (void)
  9936. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9937. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9938. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9939. /* File name is relative to the currect document */
  9940. file_name[511] = 0;
  9941. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9942. if (!truncated) {
  9943. if ((p = strrchr(path, '/')) != NULL) {
  9944. p[1] = '\0';
  9945. }
  9946. len = strlen(path);
  9947. (void)mg_snprintf(conn,
  9948. &truncated,
  9949. path + len,
  9950. sizeof(path) - len,
  9951. "%s",
  9952. file_name);
  9953. }
  9954. } else {
  9955. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9956. return;
  9957. }
  9958. if (truncated) {
  9959. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9960. return;
  9961. }
  9962. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9963. mg_cry_internal(conn,
  9964. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9965. tag,
  9966. path,
  9967. strerror(ERRNO));
  9968. } else {
  9969. fclose_on_exec(&file.access, conn);
  9970. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9971. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9972. path)
  9973. > 0) {
  9974. send_ssi_file(conn, path, &file, include_level + 1);
  9975. } else {
  9976. send_file_data(conn, &file, 0, INT64_MAX);
  9977. }
  9978. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9979. }
  9980. }
  9981. #if !defined(NO_POPEN)
  9982. static void
  9983. do_ssi_exec(struct mg_connection *conn, char *tag)
  9984. {
  9985. char cmd[1024] = "";
  9986. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9987. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9988. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  9989. } else {
  9990. cmd[1023] = 0;
  9991. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9992. mg_cry_internal(conn,
  9993. "Cannot SSI #exec: [%s]: %s",
  9994. cmd,
  9995. strerror(ERRNO));
  9996. } else {
  9997. send_file_data(conn, &file, 0, INT64_MAX);
  9998. pclose(file.access.fp);
  9999. }
  10000. }
  10001. }
  10002. #endif /* !NO_POPEN */
  10003. static int
  10004. mg_fgetc(struct mg_file *filep, int offset)
  10005. {
  10006. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10007. if (filep == NULL) {
  10008. return EOF;
  10009. }
  10010. #if defined(MG_USE_OPEN_FILE)
  10011. if ((filep->access.membuf != NULL) && (offset >= 0)
  10012. && (((unsigned int)(offset)) < filep->stat.size)) {
  10013. return ((const unsigned char *)filep->access.membuf)[offset];
  10014. } else /* else block below */
  10015. #endif
  10016. if (filep->access.fp != NULL) {
  10017. return fgetc(filep->access.fp);
  10018. } else {
  10019. return EOF;
  10020. }
  10021. }
  10022. static void
  10023. send_ssi_file(struct mg_connection *conn,
  10024. const char *path,
  10025. struct mg_file *filep,
  10026. int include_level)
  10027. {
  10028. char buf[MG_BUF_LEN];
  10029. int ch, offset, len, in_tag, in_ssi_tag;
  10030. if (include_level > 10) {
  10031. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10032. return;
  10033. }
  10034. in_tag = in_ssi_tag = len = offset = 0;
  10035. /* Read file, byte by byte, and look for SSI include tags */
  10036. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10037. if (in_tag) {
  10038. /* We are in a tag, either SSI tag or html tag */
  10039. if (ch == '>') {
  10040. /* Tag is closing */
  10041. buf[len++] = '>';
  10042. if (in_ssi_tag) {
  10043. /* Handle SSI tag */
  10044. buf[len] = 0;
  10045. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10046. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10047. #if !defined(NO_POPEN)
  10048. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10049. do_ssi_exec(conn, buf + 9);
  10050. #endif /* !NO_POPEN */
  10051. } else {
  10052. mg_cry_internal(conn,
  10053. "%s: unknown SSI "
  10054. "command: \"%s\"",
  10055. path,
  10056. buf);
  10057. }
  10058. len = 0;
  10059. in_ssi_tag = in_tag = 0;
  10060. } else {
  10061. /* Not an SSI tag */
  10062. /* Flush buffer */
  10063. (void)mg_write(conn, buf, (size_t)len);
  10064. len = 0;
  10065. in_tag = 0;
  10066. }
  10067. } else {
  10068. /* Tag is still open */
  10069. buf[len++] = (char)(ch & 0xff);
  10070. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10071. /* All SSI tags start with <!--# */
  10072. in_ssi_tag = 1;
  10073. }
  10074. if ((len + 2) > (int)sizeof(buf)) {
  10075. /* Tag to long for buffer */
  10076. mg_cry_internal(conn, "%s: tag is too large", path);
  10077. return;
  10078. }
  10079. }
  10080. } else {
  10081. /* We are not in a tag yet. */
  10082. if (ch == '<') {
  10083. /* Tag is opening */
  10084. in_tag = 1;
  10085. if (len > 0) {
  10086. /* Flush current buffer.
  10087. * Buffer is filled with "len" bytes. */
  10088. (void)mg_write(conn, buf, (size_t)len);
  10089. }
  10090. /* Store the < */
  10091. len = 1;
  10092. buf[0] = '<';
  10093. } else {
  10094. /* No Tag */
  10095. /* Add data to buffer */
  10096. buf[len++] = (char)(ch & 0xff);
  10097. /* Flush if buffer is full */
  10098. if (len == (int)sizeof(buf)) {
  10099. mg_write(conn, buf, (size_t)len);
  10100. len = 0;
  10101. }
  10102. }
  10103. }
  10104. }
  10105. /* Send the rest of buffered data */
  10106. if (len > 0) {
  10107. mg_write(conn, buf, (size_t)len);
  10108. }
  10109. }
  10110. static void
  10111. handle_ssi_file_request(struct mg_connection *conn,
  10112. const char *path,
  10113. struct mg_file *filep)
  10114. {
  10115. char date[64];
  10116. time_t curtime = time(NULL);
  10117. const char *cors_orig_cfg;
  10118. const char *cors1, *cors2, *cors3;
  10119. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10120. return;
  10121. }
  10122. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10123. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10124. /* Cross-origin resource sharing (CORS). */
  10125. cors1 = "Access-Control-Allow-Origin: ";
  10126. cors2 = cors_orig_cfg;
  10127. cors3 = "\r\n";
  10128. } else {
  10129. cors1 = cors2 = cors3 = "";
  10130. }
  10131. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10132. /* File exists (precondition for calling this function),
  10133. * but can not be opened by the server. */
  10134. mg_send_http_error(conn,
  10135. 500,
  10136. "Error: Cannot read file\nfopen(%s): %s",
  10137. path,
  10138. strerror(ERRNO));
  10139. } else {
  10140. conn->must_close = 1;
  10141. gmt_time_string(date, sizeof(date), &curtime);
  10142. fclose_on_exec(&filep->access, conn);
  10143. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10144. send_no_cache_header(conn);
  10145. send_additional_header(conn);
  10146. mg_printf(conn,
  10147. "%s%s%s"
  10148. "Date: %s\r\n"
  10149. "Content-Type: text/html\r\n"
  10150. "Connection: %s\r\n\r\n",
  10151. cors1,
  10152. cors2,
  10153. cors3,
  10154. date,
  10155. suggest_connection_header(conn));
  10156. send_ssi_file(conn, path, filep, 0);
  10157. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10158. }
  10159. }
  10160. #if !defined(NO_FILES)
  10161. static void
  10162. send_options(struct mg_connection *conn)
  10163. {
  10164. char date[64];
  10165. time_t curtime = time(NULL);
  10166. if (!conn) {
  10167. return;
  10168. }
  10169. conn->status_code = 200;
  10170. conn->must_close = 1;
  10171. gmt_time_string(date, sizeof(date), &curtime);
  10172. /* We do not set a "Cache-Control" header here, but leave the default.
  10173. * Since browsers do not send an OPTIONS request, we can not test the
  10174. * effect anyway. */
  10175. mg_printf(conn,
  10176. "HTTP/1.1 200 OK\r\n"
  10177. "Date: %s\r\n"
  10178. "Connection: %s\r\n"
  10179. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10180. "PROPFIND, MKCOL\r\n"
  10181. "DAV: 1\r\n",
  10182. date,
  10183. suggest_connection_header(conn));
  10184. send_additional_header(conn);
  10185. mg_printf(conn, "\r\n");
  10186. }
  10187. /* Writes PROPFIND properties for a collection element */
  10188. static int
  10189. print_props(struct mg_connection *conn,
  10190. const char *uri,
  10191. const char *name,
  10192. struct mg_file_stat *filep)
  10193. {
  10194. size_t href_size, i, j;
  10195. int len;
  10196. char *href, mtime[64];
  10197. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10198. return 0;
  10199. }
  10200. /* Estimate worst case size for encoding */
  10201. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10202. href = (char *)mg_malloc(href_size);
  10203. if (href == NULL) {
  10204. return 0;
  10205. }
  10206. len = mg_url_encode(uri, href, href_size);
  10207. if (len >= 0) {
  10208. /* Append an extra string */
  10209. mg_url_encode(name, href + len, href_size - (size_t)len);
  10210. }
  10211. /* Directory separator should be preserved. */
  10212. for (i = j = 0; href[i]; j++) {
  10213. if (!strncmp(href + i, "%2f", 3)) {
  10214. href[j] = '/';
  10215. i += 3;
  10216. } else {
  10217. href[j] = href[i++];
  10218. }
  10219. }
  10220. href[j] = '\0';
  10221. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10222. mg_printf(conn,
  10223. "<d:response>"
  10224. "<d:href>%s</d:href>"
  10225. "<d:propstat>"
  10226. "<d:prop>"
  10227. "<d:resourcetype>%s</d:resourcetype>"
  10228. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10229. "<d:getlastmodified>%s</d:getlastmodified>"
  10230. "</d:prop>"
  10231. "<d:status>HTTP/1.1 200 OK</d:status>"
  10232. "</d:propstat>"
  10233. "</d:response>\n",
  10234. href,
  10235. filep->is_directory ? "<d:collection/>" : "",
  10236. filep->size,
  10237. mtime);
  10238. mg_free(href);
  10239. return 1;
  10240. }
  10241. static int
  10242. print_dav_dir_entry(struct de *de, void *data)
  10243. {
  10244. struct mg_connection *conn = (struct mg_connection *)data;
  10245. if (!de || !conn
  10246. || !print_props(
  10247. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10248. return -1;
  10249. }
  10250. return 0;
  10251. }
  10252. static void
  10253. handle_propfind(struct mg_connection *conn,
  10254. const char *path,
  10255. struct mg_file_stat *filep)
  10256. {
  10257. const char *depth = mg_get_header(conn, "Depth");
  10258. char date[64];
  10259. time_t curtime = time(NULL);
  10260. gmt_time_string(date, sizeof(date), &curtime);
  10261. if (!conn || !path || !filep || !conn->dom_ctx) {
  10262. return;
  10263. }
  10264. conn->must_close = 1;
  10265. conn->status_code = 207;
  10266. mg_printf(conn,
  10267. "HTTP/1.1 207 Multi-Status\r\n"
  10268. "Date: %s\r\n",
  10269. date);
  10270. send_static_cache_header(conn);
  10271. send_additional_header(conn);
  10272. mg_printf(conn,
  10273. "Connection: %s\r\n"
  10274. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10275. suggest_connection_header(conn));
  10276. mg_printf(conn,
  10277. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10278. "<d:multistatus xmlns:d='DAV:'>\n");
  10279. /* Print properties for the requested resource itself */
  10280. print_props(conn, conn->request_info.local_uri, "", filep);
  10281. /* If it is a directory, print directory entries too if Depth is not 0
  10282. */
  10283. if (filep->is_directory
  10284. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10285. "yes")
  10286. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10287. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10288. }
  10289. mg_printf(conn, "%s\n", "</d:multistatus>");
  10290. }
  10291. #endif
  10292. void
  10293. mg_lock_connection(struct mg_connection *conn)
  10294. {
  10295. if (conn) {
  10296. (void)pthread_mutex_lock(&conn->mutex);
  10297. }
  10298. }
  10299. void
  10300. mg_unlock_connection(struct mg_connection *conn)
  10301. {
  10302. if (conn) {
  10303. (void)pthread_mutex_unlock(&conn->mutex);
  10304. }
  10305. }
  10306. void
  10307. mg_lock_context(struct mg_context *ctx)
  10308. {
  10309. if (ctx) {
  10310. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10311. }
  10312. }
  10313. void
  10314. mg_unlock_context(struct mg_context *ctx)
  10315. {
  10316. if (ctx) {
  10317. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10318. }
  10319. }
  10320. #if defined(USE_LUA)
  10321. #include "mod_lua.inl"
  10322. #endif /* USE_LUA */
  10323. #if defined(USE_DUKTAPE)
  10324. #include "mod_duktape.inl"
  10325. #endif /* USE_DUKTAPE */
  10326. #if defined(USE_WEBSOCKET)
  10327. #if !defined(NO_SSL_DL)
  10328. #define SHA_API static
  10329. #include "sha1.inl"
  10330. #endif
  10331. static int
  10332. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10333. {
  10334. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10335. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10336. SHA_CTX sha_ctx;
  10337. int truncated;
  10338. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10339. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10340. if (truncated) {
  10341. conn->must_close = 1;
  10342. return 0;
  10343. }
  10344. DEBUG_TRACE("%s", "Send websocket handshake");
  10345. SHA1_Init(&sha_ctx);
  10346. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10347. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10348. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10349. mg_printf(conn,
  10350. "HTTP/1.1 101 Switching Protocols\r\n"
  10351. "Upgrade: websocket\r\n"
  10352. "Connection: Upgrade\r\n"
  10353. "Sec-WebSocket-Accept: %s\r\n",
  10354. b64_sha);
  10355. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10356. mg_printf(conn,
  10357. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10358. conn->request_info.acceptedWebSocketSubprotocol);
  10359. } else {
  10360. mg_printf(conn, "%s", "\r\n");
  10361. }
  10362. return 1;
  10363. }
  10364. #if !defined(MG_MAX_UNANSWERED_PING)
  10365. /* Configuration of the maximum number of websocket PINGs that might
  10366. * stay unanswered before the connection is considered broken.
  10367. * Note: The name of this define may still change (until it is
  10368. * defined as a compile parameter in a documentation).
  10369. */
  10370. #define MG_MAX_UNANSWERED_PING (5)
  10371. #endif
  10372. static void
  10373. read_websocket(struct mg_connection *conn,
  10374. mg_websocket_data_handler ws_data_handler,
  10375. void *callback_data)
  10376. {
  10377. /* Pointer to the beginning of the portion of the incoming websocket
  10378. * message queue.
  10379. * The original websocket upgrade request is never removed, so the queue
  10380. * begins after it. */
  10381. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10382. int n, error, exit_by_callback;
  10383. int ret;
  10384. /* body_len is the length of the entire queue in bytes
  10385. * len is the length of the current message
  10386. * data_len is the length of the current message's data payload
  10387. * header_len is the length of the current message's header */
  10388. size_t i, len, mask_len = 0, header_len, body_len;
  10389. uint64_t data_len = 0;
  10390. /* "The masking key is a 32-bit value chosen at random by the client."
  10391. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10392. */
  10393. unsigned char mask[4];
  10394. /* data points to the place where the message is stored when passed to
  10395. * the websocket_data callback. This is either mem on the stack, or a
  10396. * dynamically allocated buffer if it is too large. */
  10397. unsigned char mem[4096];
  10398. unsigned char mop; /* mask flag and opcode */
  10399. /* Variables used for connection monitoring */
  10400. double timeout = -1.0;
  10401. int enable_ping_pong = 0;
  10402. int ping_count = 0;
  10403. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10404. enable_ping_pong =
  10405. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10406. "yes");
  10407. }
  10408. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10409. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10410. }
  10411. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10412. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10413. }
  10414. /* Enter data processing loop */
  10415. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10416. conn->request_info.remote_addr,
  10417. conn->request_info.remote_port);
  10418. conn->in_websocket_handling = 1;
  10419. mg_set_thread_name("wsock");
  10420. /* Loop continuously, reading messages from the socket, invoking the
  10421. * callback, and waiting repeatedly until an error occurs. */
  10422. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10423. header_len = 0;
  10424. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10425. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10426. len = buf[1] & 127;
  10427. mask_len = (buf[1] & 128) ? 4 : 0;
  10428. if ((len < 126) && (body_len >= mask_len)) {
  10429. /* inline 7-bit length field */
  10430. data_len = len;
  10431. header_len = 2 + mask_len;
  10432. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10433. /* 16-bit length field */
  10434. header_len = 4 + mask_len;
  10435. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10436. } else if (body_len >= (10 + mask_len)) {
  10437. /* 64-bit length field */
  10438. uint32_t l1, l2;
  10439. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10440. memcpy(&l2, &buf[6], 4);
  10441. header_len = 10 + mask_len;
  10442. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10443. if (data_len > (uint64_t)0x7FFF0000ul) {
  10444. /* no can do */
  10445. mg_cry_internal(
  10446. conn,
  10447. "%s",
  10448. "websocket out of memory; closing connection");
  10449. break;
  10450. }
  10451. }
  10452. }
  10453. if ((header_len > 0) && (body_len >= header_len)) {
  10454. /* Allocate space to hold websocket payload */
  10455. unsigned char *data = mem;
  10456. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10457. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10458. conn->phys_ctx);
  10459. if (data == NULL) {
  10460. /* Allocation failed, exit the loop and then close the
  10461. * connection */
  10462. mg_cry_internal(
  10463. conn,
  10464. "%s",
  10465. "websocket out of memory; closing connection");
  10466. break;
  10467. }
  10468. }
  10469. /* Copy the mask before we shift the queue and destroy it */
  10470. if (mask_len > 0) {
  10471. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10472. } else {
  10473. memset(mask, 0, sizeof(mask));
  10474. }
  10475. /* Read frame payload from the first message in the queue into
  10476. * data and advance the queue by moving the memory in place. */
  10477. DEBUG_ASSERT(body_len >= header_len);
  10478. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10479. mop = buf[0]; /* current mask and opcode */
  10480. /* Overflow case */
  10481. len = body_len - header_len;
  10482. memcpy(data, buf + header_len, len);
  10483. error = 0;
  10484. while ((uint64_t)len < data_len) {
  10485. n = pull_inner(NULL,
  10486. conn,
  10487. (char *)(data + len),
  10488. (int)(data_len - len),
  10489. timeout);
  10490. if (n <= -2) {
  10491. error = 1;
  10492. break;
  10493. } else if (n > 0) {
  10494. len += (size_t)n;
  10495. } else {
  10496. /* Timeout: should retry */
  10497. /* TODO: retry condition */
  10498. }
  10499. }
  10500. if (error) {
  10501. mg_cry_internal(
  10502. conn,
  10503. "%s",
  10504. "Websocket pull failed; closing connection");
  10505. if (data != mem) {
  10506. mg_free(data);
  10507. }
  10508. break;
  10509. }
  10510. conn->data_len = conn->request_len;
  10511. } else {
  10512. mop = buf[0]; /* current mask and opcode, overwritten by
  10513. * memmove() */
  10514. /* Length of the message being read at the front of the
  10515. * queue. Cast to 31 bit is OK, since we limited
  10516. * data_len before. */
  10517. len = (size_t)data_len + header_len;
  10518. /* Copy the data payload into the data pointer for the
  10519. * callback. Cast to 31 bit is OK, since we
  10520. * limited data_len */
  10521. memcpy(data, buf + header_len, (size_t)data_len);
  10522. /* Move the queue forward len bytes */
  10523. memmove(buf, buf + len, body_len - len);
  10524. /* Mark the queue as advanced */
  10525. conn->data_len -= (int)len;
  10526. }
  10527. /* Apply mask if necessary */
  10528. if (mask_len > 0) {
  10529. for (i = 0; i < (size_t)data_len; i++) {
  10530. data[i] ^= mask[i & 3];
  10531. }
  10532. }
  10533. exit_by_callback = 0;
  10534. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10535. /* filter PONG messages */
  10536. DEBUG_TRACE("PONG from %s:%u",
  10537. conn->request_info.remote_addr,
  10538. conn->request_info.remote_port);
  10539. /* No unanwered PINGs left */
  10540. ping_count = 0;
  10541. } else if (enable_ping_pong
  10542. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10543. /* reply PING messages */
  10544. DEBUG_TRACE("Reply PING from %s:%u",
  10545. conn->request_info.remote_addr,
  10546. conn->request_info.remote_port);
  10547. ret = mg_websocket_write(conn,
  10548. MG_WEBSOCKET_OPCODE_PONG,
  10549. (char *)data,
  10550. (size_t)data_len);
  10551. if (ret <= 0) {
  10552. /* Error: send failed */
  10553. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10554. break;
  10555. }
  10556. } else {
  10557. /* Exit the loop if callback signals to exit (server side),
  10558. * or "connection close" opcode received (client side). */
  10559. if ((ws_data_handler != NULL)
  10560. && !ws_data_handler(conn,
  10561. mop,
  10562. (char *)data,
  10563. (size_t)data_len,
  10564. callback_data)) {
  10565. exit_by_callback = 1;
  10566. }
  10567. }
  10568. /* It a buffer has been allocated, free it again */
  10569. if (data != mem) {
  10570. mg_free(data);
  10571. }
  10572. if (exit_by_callback) {
  10573. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10574. conn->request_info.remote_addr,
  10575. conn->request_info.remote_port);
  10576. break;
  10577. }
  10578. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10579. /* Opcode == 8, connection close */
  10580. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10581. conn->request_info.remote_addr,
  10582. conn->request_info.remote_port);
  10583. break;
  10584. }
  10585. /* Not breaking the loop, process next websocket frame. */
  10586. } else {
  10587. /* Read from the socket into the next available location in the
  10588. * message queue. */
  10589. n = pull_inner(NULL,
  10590. conn,
  10591. conn->buf + conn->data_len,
  10592. conn->buf_size - conn->data_len,
  10593. timeout);
  10594. if (n <= -2) {
  10595. /* Error, no bytes read */
  10596. DEBUG_TRACE("PULL from %s:%u failed",
  10597. conn->request_info.remote_addr,
  10598. conn->request_info.remote_port);
  10599. break;
  10600. }
  10601. if (n > 0) {
  10602. conn->data_len += n;
  10603. /* Reset open PING count */
  10604. ping_count = 0;
  10605. } else {
  10606. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10607. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10608. /* Stop sending PING */
  10609. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10610. "- closing connection",
  10611. ping_count,
  10612. conn->request_info.remote_addr,
  10613. conn->request_info.remote_port);
  10614. break;
  10615. }
  10616. if (enable_ping_pong) {
  10617. /* Send Websocket PING message */
  10618. DEBUG_TRACE("PING to %s:%u",
  10619. conn->request_info.remote_addr,
  10620. conn->request_info.remote_port);
  10621. ret = mg_websocket_write(conn,
  10622. MG_WEBSOCKET_OPCODE_PING,
  10623. NULL,
  10624. 0);
  10625. if (ret <= 0) {
  10626. /* Error: send failed */
  10627. DEBUG_TRACE("Send PING failed (%i)", ret);
  10628. break;
  10629. }
  10630. ping_count++;
  10631. }
  10632. }
  10633. /* Timeout: should retry */
  10634. /* TODO: get timeout def */
  10635. }
  10636. }
  10637. }
  10638. /* Leave data processing loop */
  10639. mg_set_thread_name("worker");
  10640. conn->in_websocket_handling = 0;
  10641. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10642. conn->request_info.remote_addr,
  10643. conn->request_info.remote_port);
  10644. }
  10645. static int
  10646. mg_websocket_write_exec(struct mg_connection *conn,
  10647. int opcode,
  10648. const char *data,
  10649. size_t dataLen,
  10650. uint32_t masking_key)
  10651. {
  10652. unsigned char header[14];
  10653. size_t headerLen;
  10654. int retval;
  10655. #if defined(GCC_DIAGNOSTIC)
  10656. /* Disable spurious conversion warning for GCC */
  10657. #pragma GCC diagnostic push
  10658. #pragma GCC diagnostic ignored "-Wconversion"
  10659. #endif
  10660. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10661. #if defined(GCC_DIAGNOSTIC)
  10662. #pragma GCC diagnostic pop
  10663. #endif
  10664. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10665. if (dataLen < 126) {
  10666. /* inline 7-bit length field */
  10667. header[1] = (unsigned char)dataLen;
  10668. headerLen = 2;
  10669. } else if (dataLen <= 0xFFFF) {
  10670. /* 16-bit length field */
  10671. uint16_t len = htons((uint16_t)dataLen);
  10672. header[1] = 126;
  10673. memcpy(header + 2, &len, 2);
  10674. headerLen = 4;
  10675. } else {
  10676. /* 64-bit length field */
  10677. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10678. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10679. header[1] = 127;
  10680. memcpy(header + 2, &len1, 4);
  10681. memcpy(header + 6, &len2, 4);
  10682. headerLen = 10;
  10683. }
  10684. if (masking_key) {
  10685. /* add mask */
  10686. header[1] |= 0x80;
  10687. memcpy(header + headerLen, &masking_key, 4);
  10688. headerLen += 4;
  10689. }
  10690. /* Note that POSIX/Winsock's send() is threadsafe
  10691. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10692. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10693. * push(), although that is only a problem if the packet is large or
  10694. * outgoing buffer is full). */
  10695. /* TODO: Check if this lock should be moved to user land.
  10696. * Currently the server sets this lock for websockets, but
  10697. * not for any other connection. It must be set for every
  10698. * conn read/written by more than one thread, no matter if
  10699. * it is a websocket or regular connection. */
  10700. (void)mg_lock_connection(conn);
  10701. retval = mg_write(conn, header, headerLen);
  10702. if (retval != (int)headerLen) {
  10703. /* Did not send complete header */
  10704. retval = -1;
  10705. } else {
  10706. if (dataLen > 0) {
  10707. retval = mg_write(conn, data, dataLen);
  10708. }
  10709. /* if dataLen == 0, the header length (2) is returned */
  10710. }
  10711. /* TODO: Remove this unlock as well, when lock is removed. */
  10712. mg_unlock_connection(conn);
  10713. return retval;
  10714. }
  10715. int
  10716. mg_websocket_write(struct mg_connection *conn,
  10717. int opcode,
  10718. const char *data,
  10719. size_t dataLen)
  10720. {
  10721. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10722. }
  10723. static void
  10724. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10725. {
  10726. size_t i = 0;
  10727. i = 0;
  10728. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10729. /* Convert in 32 bit words, if data is 4 byte aligned */
  10730. while (i < (in_len - 3)) {
  10731. *(uint32_t *)(void *)(out + i) =
  10732. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10733. i += 4;
  10734. }
  10735. }
  10736. if (i != in_len) {
  10737. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10738. while (i < in_len) {
  10739. *(uint8_t *)(void *)(out + i) =
  10740. *(uint8_t *)(void *)(in + i)
  10741. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10742. i++;
  10743. }
  10744. }
  10745. }
  10746. int
  10747. mg_websocket_client_write(struct mg_connection *conn,
  10748. int opcode,
  10749. const char *data,
  10750. size_t dataLen)
  10751. {
  10752. int retval = -1;
  10753. char *masked_data =
  10754. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10755. uint32_t masking_key = 0;
  10756. if (masked_data == NULL) {
  10757. /* Return -1 in an error case */
  10758. mg_cry_internal(conn,
  10759. "%s",
  10760. "Cannot allocate buffer for masked websocket response: "
  10761. "Out of memory");
  10762. return -1;
  10763. }
  10764. do {
  10765. /* Get a masking key - but not 0 */
  10766. masking_key = (uint32_t)get_random();
  10767. } while (masking_key == 0);
  10768. mask_data(data, dataLen, masking_key, masked_data);
  10769. retval = mg_websocket_write_exec(
  10770. conn, opcode, masked_data, dataLen, masking_key);
  10771. mg_free(masked_data);
  10772. return retval;
  10773. }
  10774. static void
  10775. handle_websocket_request(struct mg_connection *conn,
  10776. const char *path,
  10777. int is_callback_resource,
  10778. struct mg_websocket_subprotocols *subprotocols,
  10779. mg_websocket_connect_handler ws_connect_handler,
  10780. mg_websocket_ready_handler ws_ready_handler,
  10781. mg_websocket_data_handler ws_data_handler,
  10782. mg_websocket_close_handler ws_close_handler,
  10783. void *cbData)
  10784. {
  10785. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10786. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10787. ptrdiff_t lua_websock = 0;
  10788. #if !defined(USE_LUA)
  10789. (void)path;
  10790. #endif
  10791. /* Step 1: Check websocket protocol version. */
  10792. /* Step 1.1: Check Sec-WebSocket-Key. */
  10793. if (!websock_key) {
  10794. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10795. * requires a Sec-WebSocket-Key header.
  10796. */
  10797. /* It could be the hixie draft version
  10798. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10799. */
  10800. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10801. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10802. char key3[8];
  10803. if ((key1 != NULL) && (key2 != NULL)) {
  10804. /* This version uses 8 byte body data in a GET request */
  10805. conn->content_len = 8;
  10806. if (8 == mg_read(conn, key3, 8)) {
  10807. /* This is the hixie version */
  10808. mg_send_http_error(conn,
  10809. 426,
  10810. "%s",
  10811. "Protocol upgrade to RFC 6455 required");
  10812. return;
  10813. }
  10814. }
  10815. /* This is an unknown version */
  10816. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10817. return;
  10818. }
  10819. /* Step 1.2: Check websocket protocol version. */
  10820. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10821. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10822. /* Reject wrong versions */
  10823. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10824. return;
  10825. }
  10826. /* Step 1.3: Could check for "Host", but we do not really nead this
  10827. * value for anything, so just ignore it. */
  10828. /* Step 2: If a callback is responsible, call it. */
  10829. if (is_callback_resource) {
  10830. /* Step 2.1 check and select subprotocol */
  10831. const char *protocols[64]; // max 64 headers
  10832. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10833. "Sec-WebSocket-Protocol",
  10834. protocols,
  10835. 64);
  10836. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10837. int cnt = 0;
  10838. int idx;
  10839. unsigned long len;
  10840. const char *sep, *curSubProtocol,
  10841. *acceptedWebSocketSubprotocol = NULL;
  10842. /* look for matching subprotocol */
  10843. do {
  10844. const char *protocol = protocols[cnt];
  10845. do {
  10846. sep = strchr(protocol, ',');
  10847. curSubProtocol = protocol;
  10848. len = sep ? (unsigned long)(sep - protocol)
  10849. : (unsigned long)strlen(protocol);
  10850. while (sep && isspace((unsigned char)*++sep))
  10851. ; // ignore leading whitespaces
  10852. protocol = sep;
  10853. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10854. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10855. && (strncmp(curSubProtocol,
  10856. subprotocols->subprotocols[idx],
  10857. len)
  10858. == 0)) {
  10859. acceptedWebSocketSubprotocol =
  10860. subprotocols->subprotocols[idx];
  10861. break;
  10862. }
  10863. }
  10864. } while (sep && !acceptedWebSocketSubprotocol);
  10865. } while (++cnt < nbSubprotocolHeader
  10866. && !acceptedWebSocketSubprotocol);
  10867. conn->request_info.acceptedWebSocketSubprotocol =
  10868. acceptedWebSocketSubprotocol;
  10869. } else if (nbSubprotocolHeader > 0) {
  10870. /* keep legacy behavior */
  10871. const char *protocol = protocols[0];
  10872. /* The protocol is a comma separated list of names. */
  10873. /* The server must only return one value from this list. */
  10874. /* First check if it is a list or just a single value. */
  10875. const char *sep = strrchr(protocol, ',');
  10876. if (sep == NULL) {
  10877. /* Just a single protocol -> accept it. */
  10878. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10879. } else {
  10880. /* Multiple protocols -> accept the last one. */
  10881. /* This is just a quick fix if the client offers multiple
  10882. * protocols. The handler should have a list of accepted
  10883. * protocols on his own
  10884. * and use it to select one protocol among those the client
  10885. * has
  10886. * offered.
  10887. */
  10888. while (isspace((unsigned char)*++sep)) {
  10889. ; /* ignore leading whitespaces */
  10890. }
  10891. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10892. }
  10893. }
  10894. if ((ws_connect_handler != NULL)
  10895. && (ws_connect_handler(conn, cbData) != 0)) {
  10896. /* C callback has returned non-zero, do not proceed with
  10897. * handshake.
  10898. */
  10899. /* Note that C callbacks are no longer called when Lua is
  10900. * responsible, so C can no longer filter callbacks for Lua. */
  10901. return;
  10902. }
  10903. }
  10904. #if defined(USE_LUA)
  10905. /* Step 3: No callback. Check if Lua is responsible. */
  10906. else {
  10907. /* Step 3.1: Check if Lua is responsible. */
  10908. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10909. lua_websock = match_prefix(
  10910. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10911. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10912. path);
  10913. }
  10914. if (lua_websock) {
  10915. /* Step 3.2: Lua is responsible: call it. */
  10916. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10917. if (!conn->lua_websocket_state) {
  10918. /* Lua rejected the new client */
  10919. return;
  10920. }
  10921. }
  10922. }
  10923. #endif
  10924. /* Step 4: Check if there is a responsible websocket handler. */
  10925. if (!is_callback_resource && !lua_websock) {
  10926. /* There is no callback, and Lua is not responsible either. */
  10927. /* Reply with a 404 Not Found. We are still at a standard
  10928. * HTTP request here, before the websocket handshake, so
  10929. * we can still send standard HTTP error replies. */
  10930. mg_send_http_error(conn, 404, "%s", "Not found");
  10931. return;
  10932. }
  10933. /* Step 5: The websocket connection has been accepted */
  10934. if (!send_websocket_handshake(conn, websock_key)) {
  10935. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10936. return;
  10937. }
  10938. /* Step 6: Call the ready handler */
  10939. if (is_callback_resource) {
  10940. if (ws_ready_handler != NULL) {
  10941. ws_ready_handler(conn, cbData);
  10942. }
  10943. #if defined(USE_LUA)
  10944. } else if (lua_websock) {
  10945. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10946. /* the ready handler returned false */
  10947. return;
  10948. }
  10949. #endif
  10950. }
  10951. /* Step 7: Enter the read loop */
  10952. if (is_callback_resource) {
  10953. read_websocket(conn, ws_data_handler, cbData);
  10954. #if defined(USE_LUA)
  10955. } else if (lua_websock) {
  10956. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10957. #endif
  10958. }
  10959. /* Step 8: Call the close handler */
  10960. if (ws_close_handler) {
  10961. ws_close_handler(conn, cbData);
  10962. }
  10963. }
  10964. static int
  10965. is_websocket_protocol(const struct mg_connection *conn)
  10966. {
  10967. const char *upgrade, *connection;
  10968. /* A websocket protocoll has the following HTTP headers:
  10969. *
  10970. * Connection: Upgrade
  10971. * Upgrade: Websocket
  10972. */
  10973. upgrade = mg_get_header(conn, "Upgrade");
  10974. if (upgrade == NULL) {
  10975. return 0; /* fail early, don't waste time checking other header
  10976. * fields
  10977. */
  10978. }
  10979. if (!mg_strcasestr(upgrade, "websocket")) {
  10980. return 0;
  10981. }
  10982. connection = mg_get_header(conn, "Connection");
  10983. if (connection == NULL) {
  10984. return 0;
  10985. }
  10986. if (!mg_strcasestr(connection, "upgrade")) {
  10987. return 0;
  10988. }
  10989. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10990. * "Sec-WebSocket-Version" are also required.
  10991. * Don't check them here, since even an unsupported websocket protocol
  10992. * request still IS a websocket request (in contrast to a standard HTTP
  10993. * request). It will fail later in handle_websocket_request.
  10994. */
  10995. return 1;
  10996. }
  10997. #endif /* !USE_WEBSOCKET */
  10998. static int
  10999. isbyte(int n)
  11000. {
  11001. return (n >= 0) && (n <= 255);
  11002. }
  11003. static int
  11004. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11005. {
  11006. int n, a, b, c, d, slash = 32, len = 0;
  11007. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11008. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11009. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11010. && (slash < 33)) {
  11011. len = n;
  11012. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11013. | (uint32_t)d;
  11014. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11015. }
  11016. return len;
  11017. }
  11018. static int
  11019. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11020. {
  11021. int throttle = 0;
  11022. struct vec vec, val;
  11023. uint32_t net, mask;
  11024. char mult;
  11025. double v;
  11026. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11027. mult = ',';
  11028. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11029. || (v < 0)
  11030. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11031. && (mult != ','))) {
  11032. continue;
  11033. }
  11034. v *= (lowercase(&mult) == 'k')
  11035. ? 1024
  11036. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11037. if (vec.len == 1 && vec.ptr[0] == '*') {
  11038. throttle = (int)v;
  11039. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11040. if ((remote_ip & mask) == net) {
  11041. throttle = (int)v;
  11042. }
  11043. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11044. throttle = (int)v;
  11045. }
  11046. }
  11047. return throttle;
  11048. }
  11049. static uint32_t
  11050. get_remote_ip(const struct mg_connection *conn)
  11051. {
  11052. if (!conn) {
  11053. return 0;
  11054. }
  11055. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11056. }
  11057. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11058. #include "handle_form.inl"
  11059. #if defined(MG_LEGACY_INTERFACE)
  11060. /* Implement the deprecated mg_upload function by calling the new
  11061. * mg_handle_form_request function. While mg_upload could only handle
  11062. * HTML forms sent as POST request in multipart/form-data format
  11063. * containing only file input elements, mg_handle_form_request can
  11064. * handle all form input elements and all standard request methods. */
  11065. struct mg_upload_user_data {
  11066. struct mg_connection *conn;
  11067. const char *destination_dir;
  11068. int num_uploaded_files;
  11069. };
  11070. /* Helper function for deprecated mg_upload. */
  11071. static int
  11072. mg_upload_field_found(const char *key,
  11073. const char *filename,
  11074. char *path,
  11075. size_t pathlen,
  11076. void *user_data)
  11077. {
  11078. int truncated = 0;
  11079. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11080. (void)key;
  11081. if (!filename) {
  11082. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11083. return FORM_FIELD_STORAGE_ABORT;
  11084. }
  11085. mg_snprintf(fud->conn,
  11086. &truncated,
  11087. path,
  11088. pathlen - 1,
  11089. "%s/%s",
  11090. fud->destination_dir,
  11091. filename);
  11092. if (truncated) {
  11093. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11094. return FORM_FIELD_STORAGE_ABORT;
  11095. }
  11096. return FORM_FIELD_STORAGE_STORE;
  11097. }
  11098. /* Helper function for deprecated mg_upload. */
  11099. static int
  11100. mg_upload_field_get(const char *key,
  11101. const char *value,
  11102. size_t value_size,
  11103. void *user_data)
  11104. {
  11105. /* Function should never be called */
  11106. (void)key;
  11107. (void)value;
  11108. (void)value_size;
  11109. (void)user_data;
  11110. return 0;
  11111. }
  11112. /* Helper function for deprecated mg_upload. */
  11113. static int
  11114. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11115. {
  11116. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11117. (void)file_size;
  11118. fud->num_uploaded_files++;
  11119. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11120. return 0;
  11121. }
  11122. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11123. int
  11124. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11125. {
  11126. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11127. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11128. mg_upload_field_get,
  11129. mg_upload_field_stored,
  11130. 0};
  11131. int ret;
  11132. fdh.user_data = (void *)&fud;
  11133. ret = mg_handle_form_request(conn, &fdh);
  11134. if (ret < 0) {
  11135. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11136. }
  11137. return fud.num_uploaded_files;
  11138. }
  11139. #endif
  11140. static int
  11141. get_first_ssl_listener_index(const struct mg_context *ctx)
  11142. {
  11143. unsigned int i;
  11144. int idx = -1;
  11145. if (ctx) {
  11146. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11147. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11148. }
  11149. }
  11150. return idx;
  11151. }
  11152. /* Return host (without port) */
  11153. /* Use mg_free to free the result */
  11154. static const char *
  11155. alloc_get_host(struct mg_connection *conn)
  11156. {
  11157. char buf[1025];
  11158. size_t buflen = sizeof(buf);
  11159. const char *host_header = get_header(conn->request_info.http_headers,
  11160. conn->request_info.num_headers,
  11161. "Host");
  11162. char *host;
  11163. if (host_header != NULL) {
  11164. char *pos;
  11165. /* Create a local copy of the "Host" header, since it might be
  11166. * modified here. */
  11167. mg_strlcpy(buf, host_header, buflen);
  11168. buf[buflen - 1] = '\0';
  11169. host = buf;
  11170. while (isspace((unsigned char)*host)) {
  11171. host++;
  11172. }
  11173. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11174. * is found. */
  11175. if (*host == '[') {
  11176. pos = strchr(host, ']');
  11177. if (!pos) {
  11178. /* Malformed hostname starts with '[', but no ']' found */
  11179. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11180. return NULL;
  11181. }
  11182. /* terminate after ']' */
  11183. pos[1] = 0;
  11184. } else {
  11185. /* Otherwise, a ':' separates hostname and port number */
  11186. pos = strchr(host, ':');
  11187. if (pos != NULL) {
  11188. *pos = '\0';
  11189. }
  11190. }
  11191. if (conn->ssl) {
  11192. /* This is a HTTPS connection, maybe we have a hostname
  11193. * from SNI (set in ssl_servername_callback). */
  11194. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11195. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11196. /* We are not using the default domain */
  11197. if (mg_strcasecmp(host, sslhost)) {
  11198. /* Mismatch between SNI domain and HTTP domain */
  11199. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11200. sslhost,
  11201. host);
  11202. return NULL;
  11203. }
  11204. }
  11205. DEBUG_TRACE("HTTPS Host: %s", host);
  11206. } else {
  11207. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11208. while (dom) {
  11209. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11210. /* Found matching domain */
  11211. DEBUG_TRACE("HTTP domain %s found",
  11212. dom->config[AUTHENTICATION_DOMAIN]);
  11213. /* TODO: Check if this is a HTTP or HTTPS domain */
  11214. conn->dom_ctx = dom;
  11215. break;
  11216. }
  11217. dom = dom->next;
  11218. }
  11219. DEBUG_TRACE("HTTP Host: %s", host);
  11220. }
  11221. } else {
  11222. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11223. host = buf;
  11224. DEBUG_TRACE("IP: %s", host);
  11225. }
  11226. return mg_strdup_ctx(host, conn->phys_ctx);
  11227. }
  11228. static void
  11229. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11230. {
  11231. char target_url[MG_BUF_LEN];
  11232. int truncated = 0;
  11233. conn->must_close = 1;
  11234. /* Send host, port, uri and (if it exists) ?query_string */
  11235. if (conn->host) {
  11236. /* Use "308 Permanent Redirect" */
  11237. int redirect_code = 308;
  11238. /* Create target URL */
  11239. mg_snprintf(
  11240. conn,
  11241. &truncated,
  11242. target_url,
  11243. sizeof(target_url),
  11244. "https://%s:%d%s%s%s",
  11245. conn->host,
  11246. #if defined(USE_IPV6)
  11247. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11248. == AF_INET6)
  11249. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11250. .lsa.sin6.sin6_port)
  11251. :
  11252. #endif
  11253. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11254. .lsa.sin.sin_port),
  11255. conn->request_info.local_uri,
  11256. (conn->request_info.query_string == NULL) ? "" : "?",
  11257. (conn->request_info.query_string == NULL)
  11258. ? ""
  11259. : conn->request_info.query_string);
  11260. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11261. * is used as buffer size) */
  11262. if (truncated) {
  11263. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11264. return;
  11265. }
  11266. /* Use redirect helper function */
  11267. mg_send_http_redirect(conn, target_url, redirect_code);
  11268. }
  11269. }
  11270. static void
  11271. handler_info_acquire(struct mg_handler_info *handler_info)
  11272. {
  11273. pthread_mutex_lock(&handler_info->refcount_mutex);
  11274. handler_info->refcount++;
  11275. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11276. }
  11277. static void
  11278. handler_info_release(struct mg_handler_info *handler_info)
  11279. {
  11280. pthread_mutex_lock(&handler_info->refcount_mutex);
  11281. handler_info->refcount--;
  11282. pthread_cond_signal(&handler_info->refcount_cond);
  11283. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11284. }
  11285. static void
  11286. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11287. {
  11288. pthread_mutex_lock(&handler_info->refcount_mutex);
  11289. while (handler_info->refcount) {
  11290. pthread_cond_wait(&handler_info->refcount_cond,
  11291. &handler_info->refcount_mutex);
  11292. }
  11293. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11294. }
  11295. static void
  11296. mg_set_handler_type(struct mg_context *phys_ctx,
  11297. struct mg_domain_context *dom_ctx,
  11298. const char *uri,
  11299. int handler_type,
  11300. int is_delete_request,
  11301. mg_request_handler handler,
  11302. struct mg_websocket_subprotocols *subprotocols,
  11303. mg_websocket_connect_handler connect_handler,
  11304. mg_websocket_ready_handler ready_handler,
  11305. mg_websocket_data_handler data_handler,
  11306. mg_websocket_close_handler close_handler,
  11307. mg_authorization_handler auth_handler,
  11308. void *cbdata)
  11309. {
  11310. struct mg_handler_info *tmp_rh, **lastref;
  11311. size_t urilen = strlen(uri);
  11312. if (handler_type == WEBSOCKET_HANDLER) {
  11313. DEBUG_ASSERT(handler == NULL);
  11314. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11315. || ready_handler != NULL || data_handler != NULL
  11316. || close_handler != NULL);
  11317. DEBUG_ASSERT(auth_handler == NULL);
  11318. if (handler != NULL) {
  11319. return;
  11320. }
  11321. if (!is_delete_request && (connect_handler == NULL)
  11322. && (ready_handler == NULL) && (data_handler == NULL)
  11323. && (close_handler == NULL)) {
  11324. return;
  11325. }
  11326. if (auth_handler != NULL) {
  11327. return;
  11328. }
  11329. } else if (handler_type == REQUEST_HANDLER) {
  11330. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11331. && data_handler == NULL && close_handler == NULL);
  11332. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11333. DEBUG_ASSERT(auth_handler == NULL);
  11334. if ((connect_handler != NULL) || (ready_handler != NULL)
  11335. || (data_handler != NULL) || (close_handler != NULL)) {
  11336. return;
  11337. }
  11338. if (!is_delete_request && (handler == NULL)) {
  11339. return;
  11340. }
  11341. if (auth_handler != NULL) {
  11342. return;
  11343. }
  11344. } else { /* AUTH_HANDLER */
  11345. DEBUG_ASSERT(handler == NULL);
  11346. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11347. && data_handler == NULL && close_handler == NULL);
  11348. DEBUG_ASSERT(auth_handler != NULL);
  11349. if (handler != NULL) {
  11350. return;
  11351. }
  11352. if ((connect_handler != NULL) || (ready_handler != NULL)
  11353. || (data_handler != NULL) || (close_handler != NULL)) {
  11354. return;
  11355. }
  11356. if (!is_delete_request && (auth_handler == NULL)) {
  11357. return;
  11358. }
  11359. }
  11360. if (!phys_ctx || !dom_ctx) {
  11361. return;
  11362. }
  11363. mg_lock_context(phys_ctx);
  11364. /* first try to find an existing handler */
  11365. lastref = &(dom_ctx->handlers);
  11366. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11367. if (tmp_rh->handler_type == handler_type) {
  11368. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11369. if (!is_delete_request) {
  11370. /* update existing handler */
  11371. if (handler_type == REQUEST_HANDLER) {
  11372. /* Wait for end of use before updating */
  11373. handler_info_wait_unused(tmp_rh);
  11374. /* Ok, the handler is no more use -> Update it */
  11375. tmp_rh->handler = handler;
  11376. } else if (handler_type == WEBSOCKET_HANDLER) {
  11377. tmp_rh->subprotocols = subprotocols;
  11378. tmp_rh->connect_handler = connect_handler;
  11379. tmp_rh->ready_handler = ready_handler;
  11380. tmp_rh->data_handler = data_handler;
  11381. tmp_rh->close_handler = close_handler;
  11382. } else { /* AUTH_HANDLER */
  11383. tmp_rh->auth_handler = auth_handler;
  11384. }
  11385. tmp_rh->cbdata = cbdata;
  11386. } else {
  11387. /* remove existing handler */
  11388. if (handler_type == REQUEST_HANDLER) {
  11389. /* Wait for end of use before removing */
  11390. handler_info_wait_unused(tmp_rh);
  11391. /* Ok, the handler is no more used -> Destroy resources
  11392. */
  11393. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11394. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11395. }
  11396. *lastref = tmp_rh->next;
  11397. mg_free(tmp_rh->uri);
  11398. mg_free(tmp_rh);
  11399. }
  11400. mg_unlock_context(phys_ctx);
  11401. return;
  11402. }
  11403. }
  11404. lastref = &(tmp_rh->next);
  11405. }
  11406. if (is_delete_request) {
  11407. /* no handler to set, this was a remove request to a non-existing
  11408. * handler */
  11409. mg_unlock_context(phys_ctx);
  11410. return;
  11411. }
  11412. tmp_rh =
  11413. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11414. 1,
  11415. phys_ctx);
  11416. if (tmp_rh == NULL) {
  11417. mg_unlock_context(phys_ctx);
  11418. mg_cry_ctx_internal(phys_ctx,
  11419. "%s",
  11420. "Cannot create new request handler struct, OOM");
  11421. return;
  11422. }
  11423. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11424. if (!tmp_rh->uri) {
  11425. mg_unlock_context(phys_ctx);
  11426. mg_free(tmp_rh);
  11427. mg_cry_ctx_internal(phys_ctx,
  11428. "%s",
  11429. "Cannot create new request handler struct, OOM");
  11430. return;
  11431. }
  11432. tmp_rh->uri_len = urilen;
  11433. if (handler_type == REQUEST_HANDLER) {
  11434. /* Init refcount mutex and condition */
  11435. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11436. mg_unlock_context(phys_ctx);
  11437. mg_free(tmp_rh);
  11438. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount mutex");
  11439. return;
  11440. }
  11441. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11442. mg_unlock_context(phys_ctx);
  11443. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11444. mg_free(tmp_rh);
  11445. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount cond");
  11446. return;
  11447. }
  11448. tmp_rh->refcount = 0;
  11449. tmp_rh->handler = handler;
  11450. } else if (handler_type == WEBSOCKET_HANDLER) {
  11451. tmp_rh->subprotocols = subprotocols;
  11452. tmp_rh->connect_handler = connect_handler;
  11453. tmp_rh->ready_handler = ready_handler;
  11454. tmp_rh->data_handler = data_handler;
  11455. tmp_rh->close_handler = close_handler;
  11456. } else { /* AUTH_HANDLER */
  11457. tmp_rh->auth_handler = auth_handler;
  11458. }
  11459. tmp_rh->cbdata = cbdata;
  11460. tmp_rh->handler_type = handler_type;
  11461. tmp_rh->next = NULL;
  11462. *lastref = tmp_rh;
  11463. mg_unlock_context(phys_ctx);
  11464. }
  11465. void
  11466. mg_set_request_handler(struct mg_context *ctx,
  11467. const char *uri,
  11468. mg_request_handler handler,
  11469. void *cbdata)
  11470. {
  11471. mg_set_handler_type(ctx,
  11472. &(ctx->dd),
  11473. uri,
  11474. REQUEST_HANDLER,
  11475. handler == NULL,
  11476. handler,
  11477. NULL,
  11478. NULL,
  11479. NULL,
  11480. NULL,
  11481. NULL,
  11482. NULL,
  11483. cbdata);
  11484. }
  11485. void
  11486. mg_set_websocket_handler(struct mg_context *ctx,
  11487. const char *uri,
  11488. mg_websocket_connect_handler connect_handler,
  11489. mg_websocket_ready_handler ready_handler,
  11490. mg_websocket_data_handler data_handler,
  11491. mg_websocket_close_handler close_handler,
  11492. void *cbdata)
  11493. {
  11494. mg_set_websocket_handler_with_subprotocols(ctx,
  11495. uri,
  11496. NULL,
  11497. connect_handler,
  11498. ready_handler,
  11499. data_handler,
  11500. close_handler,
  11501. cbdata);
  11502. }
  11503. void
  11504. mg_set_websocket_handler_with_subprotocols(
  11505. struct mg_context *ctx,
  11506. const char *uri,
  11507. struct mg_websocket_subprotocols *subprotocols,
  11508. mg_websocket_connect_handler connect_handler,
  11509. mg_websocket_ready_handler ready_handler,
  11510. mg_websocket_data_handler data_handler,
  11511. mg_websocket_close_handler close_handler,
  11512. void *cbdata)
  11513. {
  11514. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11515. && (data_handler == NULL)
  11516. && (close_handler == NULL);
  11517. mg_set_handler_type(ctx,
  11518. &(ctx->dd),
  11519. uri,
  11520. WEBSOCKET_HANDLER,
  11521. is_delete_request,
  11522. NULL,
  11523. subprotocols,
  11524. connect_handler,
  11525. ready_handler,
  11526. data_handler,
  11527. close_handler,
  11528. NULL,
  11529. cbdata);
  11530. }
  11531. void
  11532. mg_set_auth_handler(struct mg_context *ctx,
  11533. const char *uri,
  11534. mg_authorization_handler handler,
  11535. void *cbdata)
  11536. {
  11537. mg_set_handler_type(ctx,
  11538. &(ctx->dd),
  11539. uri,
  11540. AUTH_HANDLER,
  11541. handler == NULL,
  11542. NULL,
  11543. NULL,
  11544. NULL,
  11545. NULL,
  11546. NULL,
  11547. NULL,
  11548. handler,
  11549. cbdata);
  11550. }
  11551. static int
  11552. get_request_handler(struct mg_connection *conn,
  11553. int handler_type,
  11554. mg_request_handler *handler,
  11555. struct mg_websocket_subprotocols **subprotocols,
  11556. mg_websocket_connect_handler *connect_handler,
  11557. mg_websocket_ready_handler *ready_handler,
  11558. mg_websocket_data_handler *data_handler,
  11559. mg_websocket_close_handler *close_handler,
  11560. mg_authorization_handler *auth_handler,
  11561. void **cbdata,
  11562. struct mg_handler_info **handler_info)
  11563. {
  11564. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11565. if (request_info) {
  11566. const char *uri = request_info->local_uri;
  11567. size_t urilen = strlen(uri);
  11568. struct mg_handler_info *tmp_rh;
  11569. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11570. return 0;
  11571. }
  11572. mg_lock_context(conn->phys_ctx);
  11573. /* first try for an exact match */
  11574. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11575. tmp_rh = tmp_rh->next) {
  11576. if (tmp_rh->handler_type == handler_type) {
  11577. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11578. if (handler_type == WEBSOCKET_HANDLER) {
  11579. *subprotocols = tmp_rh->subprotocols;
  11580. *connect_handler = tmp_rh->connect_handler;
  11581. *ready_handler = tmp_rh->ready_handler;
  11582. *data_handler = tmp_rh->data_handler;
  11583. *close_handler = tmp_rh->close_handler;
  11584. } else if (handler_type == REQUEST_HANDLER) {
  11585. *handler = tmp_rh->handler;
  11586. /* Acquire handler and give it back */
  11587. handler_info_acquire(tmp_rh);
  11588. *handler_info = tmp_rh;
  11589. } else { /* AUTH_HANDLER */
  11590. *auth_handler = tmp_rh->auth_handler;
  11591. }
  11592. *cbdata = tmp_rh->cbdata;
  11593. mg_unlock_context(conn->phys_ctx);
  11594. return 1;
  11595. }
  11596. }
  11597. }
  11598. /* next try for a partial match, we will accept uri/something */
  11599. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11600. tmp_rh = tmp_rh->next) {
  11601. if (tmp_rh->handler_type == handler_type) {
  11602. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11603. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11604. if (handler_type == WEBSOCKET_HANDLER) {
  11605. *subprotocols = tmp_rh->subprotocols;
  11606. *connect_handler = tmp_rh->connect_handler;
  11607. *ready_handler = tmp_rh->ready_handler;
  11608. *data_handler = tmp_rh->data_handler;
  11609. *close_handler = tmp_rh->close_handler;
  11610. } else if (handler_type == REQUEST_HANDLER) {
  11611. *handler = tmp_rh->handler;
  11612. /* Acquire handler and give it back */
  11613. handler_info_acquire(tmp_rh);
  11614. *handler_info = tmp_rh;
  11615. } else { /* AUTH_HANDLER */
  11616. *auth_handler = tmp_rh->auth_handler;
  11617. }
  11618. *cbdata = tmp_rh->cbdata;
  11619. mg_unlock_context(conn->phys_ctx);
  11620. return 1;
  11621. }
  11622. }
  11623. }
  11624. /* finally try for pattern match */
  11625. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11626. tmp_rh = tmp_rh->next) {
  11627. if (tmp_rh->handler_type == handler_type) {
  11628. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11629. if (handler_type == WEBSOCKET_HANDLER) {
  11630. *subprotocols = tmp_rh->subprotocols;
  11631. *connect_handler = tmp_rh->connect_handler;
  11632. *ready_handler = tmp_rh->ready_handler;
  11633. *data_handler = tmp_rh->data_handler;
  11634. *close_handler = tmp_rh->close_handler;
  11635. } else if (handler_type == REQUEST_HANDLER) {
  11636. *handler = tmp_rh->handler;
  11637. /* Acquire handler and give it back */
  11638. handler_info_acquire(tmp_rh);
  11639. *handler_info = tmp_rh;
  11640. } else { /* AUTH_HANDLER */
  11641. *auth_handler = tmp_rh->auth_handler;
  11642. }
  11643. *cbdata = tmp_rh->cbdata;
  11644. mg_unlock_context(conn->phys_ctx);
  11645. return 1;
  11646. }
  11647. }
  11648. }
  11649. mg_unlock_context(conn->phys_ctx);
  11650. }
  11651. return 0; /* none found */
  11652. }
  11653. /* Check if the script file is in a path, allowed for script files.
  11654. * This can be used if uploading files is possible not only for the server
  11655. * admin, and the upload mechanism does not check the file extension.
  11656. */
  11657. static int
  11658. is_in_script_path(const struct mg_connection *conn, const char *path)
  11659. {
  11660. /* TODO (Feature): Add config value for allowed script path.
  11661. * Default: All allowed. */
  11662. (void)conn;
  11663. (void)path;
  11664. return 1;
  11665. }
  11666. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11667. static int
  11668. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11669. void *cbdata)
  11670. {
  11671. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11672. if (pcallbacks->websocket_connect) {
  11673. return pcallbacks->websocket_connect(conn);
  11674. }
  11675. /* No handler set - assume "OK" */
  11676. return 0;
  11677. }
  11678. static void
  11679. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11680. {
  11681. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11682. if (pcallbacks->websocket_ready) {
  11683. pcallbacks->websocket_ready(conn);
  11684. }
  11685. }
  11686. static int
  11687. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11688. int bits,
  11689. char *data,
  11690. size_t len,
  11691. void *cbdata)
  11692. {
  11693. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11694. if (pcallbacks->websocket_data) {
  11695. return pcallbacks->websocket_data(conn, bits, data, len);
  11696. }
  11697. /* No handler set - assume "OK" */
  11698. return 1;
  11699. }
  11700. #endif
  11701. /* This is the heart of the Civetweb's logic.
  11702. * This function is called when the request is read, parsed and validated,
  11703. * and Civetweb must decide what action to take: serve a file, or
  11704. * a directory, or call embedded function, etcetera. */
  11705. static void
  11706. handle_request(struct mg_connection *conn)
  11707. {
  11708. struct mg_request_info *ri = &conn->request_info;
  11709. char path[PATH_MAX];
  11710. int uri_len, ssl_index;
  11711. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11712. is_put_or_delete_request = 0, is_callback_resource = 0;
  11713. int i;
  11714. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11715. mg_request_handler callback_handler = NULL;
  11716. struct mg_handler_info *handler_info = NULL;
  11717. struct mg_websocket_subprotocols *subprotocols;
  11718. mg_websocket_connect_handler ws_connect_handler = NULL;
  11719. mg_websocket_ready_handler ws_ready_handler = NULL;
  11720. mg_websocket_data_handler ws_data_handler = NULL;
  11721. mg_websocket_close_handler ws_close_handler = NULL;
  11722. void *callback_data = NULL;
  11723. mg_authorization_handler auth_handler = NULL;
  11724. void *auth_callback_data = NULL;
  11725. int handler_type;
  11726. time_t curtime = time(NULL);
  11727. char date[64];
  11728. path[0] = 0;
  11729. /* 1. get the request url */
  11730. /* 1.1. split into url and query string */
  11731. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11732. != NULL) {
  11733. *((char *)conn->request_info.query_string++) = '\0';
  11734. }
  11735. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11736. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11737. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11738. if (ssl_index >= 0) {
  11739. redirect_to_https_port(conn, ssl_index);
  11740. } else {
  11741. /* A http to https forward port has been specified,
  11742. * but no https port to forward to. */
  11743. mg_send_http_error(conn,
  11744. 503,
  11745. "%s",
  11746. "Error: SSL forward not configured properly");
  11747. mg_cry_internal(conn,
  11748. "%s",
  11749. "Can not redirect to SSL, no SSL port available");
  11750. }
  11751. return;
  11752. }
  11753. uri_len = (int)strlen(ri->local_uri);
  11754. /* 1.3. decode url (if config says so) */
  11755. if (should_decode_url(conn)) {
  11756. mg_url_decode(
  11757. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11758. }
  11759. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11760. * not possible */
  11761. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11762. /* step 1. completed, the url is known now */
  11763. uri_len = (int)strlen(ri->local_uri);
  11764. DEBUG_TRACE("URL: %s", ri->local_uri);
  11765. /* 2. if this ip has limited speed, set it for this connection */
  11766. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11767. get_remote_ip(conn),
  11768. ri->local_uri);
  11769. /* 3. call a "handle everything" callback, if registered */
  11770. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11771. /* Note that since V1.7 the "begin_request" function is called
  11772. * before an authorization check. If an authorization check is
  11773. * required, use a request_handler instead. */
  11774. i = conn->phys_ctx->callbacks.begin_request(conn);
  11775. if (i > 0) {
  11776. /* callback already processed the request. Store the
  11777. return value as a status code for the access log. */
  11778. conn->status_code = i;
  11779. discard_unread_request_data(conn);
  11780. return;
  11781. } else if (i == 0) {
  11782. /* civetweb should process the request */
  11783. } else {
  11784. /* unspecified - may change with the next version */
  11785. return;
  11786. }
  11787. }
  11788. /* request not yet handled by a handler or redirect, so the request
  11789. * is processed here */
  11790. /* 4. Check for CORS preflight requests and handle them (if configured).
  11791. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11792. */
  11793. if (!strcmp(ri->request_method, "OPTIONS")) {
  11794. /* Send a response to CORS preflights only if
  11795. * access_control_allow_methods is not NULL and not an empty string.
  11796. * In this case, scripts can still handle CORS. */
  11797. const char *cors_meth_cfg =
  11798. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11799. const char *cors_orig_cfg =
  11800. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11801. const char *cors_origin =
  11802. get_header(ri->http_headers, ri->num_headers, "Origin");
  11803. const char *cors_acrm = get_header(ri->http_headers,
  11804. ri->num_headers,
  11805. "Access-Control-Request-Method");
  11806. /* Todo: check if cors_origin is in cors_orig_cfg.
  11807. * Or, let the client check this. */
  11808. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11809. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11810. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11811. /* This is a valid CORS preflight, and the server is configured
  11812. * to
  11813. * handle it automatically. */
  11814. const char *cors_acrh =
  11815. get_header(ri->http_headers,
  11816. ri->num_headers,
  11817. "Access-Control-Request-Headers");
  11818. gmt_time_string(date, sizeof(date), &curtime);
  11819. mg_printf(conn,
  11820. "HTTP/1.1 200 OK\r\n"
  11821. "Date: %s\r\n"
  11822. "Access-Control-Allow-Origin: %s\r\n"
  11823. "Access-Control-Allow-Methods: %s\r\n"
  11824. "Content-Length: 0\r\n"
  11825. "Connection: %s\r\n",
  11826. date,
  11827. cors_orig_cfg,
  11828. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11829. suggest_connection_header(conn));
  11830. if (cors_acrh != NULL) {
  11831. /* CORS request is asking for additional headers */
  11832. const char *cors_hdr_cfg =
  11833. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11834. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11835. /* Allow only if access_control_allow_headers is
  11836. * not NULL and not an empty string. If this
  11837. * configuration is set to *, allow everything.
  11838. * Otherwise this configuration must be a list
  11839. * of allowed HTTP header names. */
  11840. mg_printf(conn,
  11841. "Access-Control-Allow-Headers: %s\r\n",
  11842. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11843. : cors_hdr_cfg));
  11844. }
  11845. }
  11846. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11847. mg_printf(conn, "\r\n");
  11848. return;
  11849. }
  11850. }
  11851. /* 5. interpret the url to find out how the request must be handled
  11852. */
  11853. /* 5.1. first test, if the request targets the regular http(s)://
  11854. * protocol namespace or the websocket ws(s):// protocol namespace.
  11855. */
  11856. is_websocket_request = is_websocket_protocol(conn);
  11857. #if defined(USE_WEBSOCKET)
  11858. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11859. #else
  11860. handler_type = REQUEST_HANDLER;
  11861. #endif /* defined(USE_WEBSOCKET) */
  11862. /* 5.2. check if the request will be handled by a callback */
  11863. if (get_request_handler(conn,
  11864. handler_type,
  11865. &callback_handler,
  11866. &subprotocols,
  11867. &ws_connect_handler,
  11868. &ws_ready_handler,
  11869. &ws_data_handler,
  11870. &ws_close_handler,
  11871. NULL,
  11872. &callback_data,
  11873. &handler_info)) {
  11874. /* 5.2.1. A callback will handle this request. All requests
  11875. * handled
  11876. * by a callback have to be considered as requests to a script
  11877. * resource. */
  11878. is_callback_resource = 1;
  11879. is_script_resource = 1;
  11880. is_put_or_delete_request = is_put_or_delete_method(conn);
  11881. } else {
  11882. no_callback_resource:
  11883. /* 5.2.2. No callback is responsible for this request. The URI
  11884. * addresses a file based resource (static content or Lua/cgi
  11885. * scripts in the file system). */
  11886. is_callback_resource = 0;
  11887. interpret_uri(conn,
  11888. path,
  11889. sizeof(path),
  11890. &file.stat,
  11891. &is_found,
  11892. &is_script_resource,
  11893. &is_websocket_request,
  11894. &is_put_or_delete_request);
  11895. }
  11896. /* 6. authorization check */
  11897. /* 6.1. a custom authorization handler is installed */
  11898. if (get_request_handler(conn,
  11899. AUTH_HANDLER,
  11900. NULL,
  11901. NULL,
  11902. NULL,
  11903. NULL,
  11904. NULL,
  11905. NULL,
  11906. &auth_handler,
  11907. &auth_callback_data,
  11908. NULL)) {
  11909. if (!auth_handler(conn, auth_callback_data)) {
  11910. return;
  11911. }
  11912. } else if (is_put_or_delete_request && !is_script_resource
  11913. && !is_callback_resource) {
  11914. /* 6.2. this request is a PUT/DELETE to a real file */
  11915. /* 6.2.1. thus, the server must have real files */
  11916. #if defined(NO_FILES)
  11917. if (1) {
  11918. #else
  11919. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11920. #endif
  11921. /* This server does not have any real files, thus the
  11922. * PUT/DELETE methods are not valid. */
  11923. mg_send_http_error(conn,
  11924. 405,
  11925. "%s method not allowed",
  11926. conn->request_info.request_method);
  11927. return;
  11928. }
  11929. #if !defined(NO_FILES)
  11930. /* 6.2.2. Check if put authorization for static files is
  11931. * available.
  11932. */
  11933. if (!is_authorized_for_put(conn)) {
  11934. send_authorization_request(conn, NULL);
  11935. return;
  11936. }
  11937. #endif
  11938. } else {
  11939. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11940. * or it is a PUT or DELETE request to a resource that does not
  11941. * correspond to a file. Check authorization. */
  11942. if (!check_authorization(conn, path)) {
  11943. send_authorization_request(conn, NULL);
  11944. return;
  11945. }
  11946. }
  11947. /* request is authorized or does not need authorization */
  11948. /* 7. check if there are request handlers for this uri */
  11949. if (is_callback_resource) {
  11950. if (!is_websocket_request) {
  11951. i = callback_handler(conn, callback_data);
  11952. /* Callback handler will not be used anymore. Release it */
  11953. handler_info_release(handler_info);
  11954. if (i > 0) {
  11955. /* Do nothing, callback has served the request. Store
  11956. * then return value as status code for the log and discard
  11957. * all data from the client not used by the callback. */
  11958. conn->status_code = i;
  11959. discard_unread_request_data(conn);
  11960. } else {
  11961. /* The handler did NOT handle the request. */
  11962. /* Some proper reactions would be:
  11963. * a) close the connections without sending anything
  11964. * b) send a 404 not found
  11965. * c) try if there is a file matching the URI
  11966. * It would be possible to do a, b or c in the callback
  11967. * implementation, and return 1 - we cannot do anything
  11968. * here, that is not possible in the callback.
  11969. *
  11970. * TODO: What would be the best reaction here?
  11971. * (Note: The reaction may change, if there is a better
  11972. *idea.)
  11973. */
  11974. /* For the moment, use option c: We look for a proper file,
  11975. * but since a file request is not always a script resource,
  11976. * the authorization check might be different. */
  11977. interpret_uri(conn,
  11978. path,
  11979. sizeof(path),
  11980. &file.stat,
  11981. &is_found,
  11982. &is_script_resource,
  11983. &is_websocket_request,
  11984. &is_put_or_delete_request);
  11985. callback_handler = NULL;
  11986. /* Here we are at a dead end:
  11987. * According to URI matching, a callback should be
  11988. * responsible for handling the request,
  11989. * we called it, but the callback declared itself
  11990. * not responsible.
  11991. * We use a goto here, to get out of this dead end,
  11992. * and continue with the default handling.
  11993. * A goto here is simpler and better to understand
  11994. * than some curious loop. */
  11995. goto no_callback_resource;
  11996. }
  11997. } else {
  11998. #if defined(USE_WEBSOCKET)
  11999. handle_websocket_request(conn,
  12000. path,
  12001. is_callback_resource,
  12002. subprotocols,
  12003. ws_connect_handler,
  12004. ws_ready_handler,
  12005. ws_data_handler,
  12006. ws_close_handler,
  12007. callback_data);
  12008. #endif
  12009. }
  12010. return;
  12011. }
  12012. /* 8. handle websocket requests */
  12013. #if defined(USE_WEBSOCKET)
  12014. if (is_websocket_request) {
  12015. if (is_script_resource) {
  12016. if (is_in_script_path(conn, path)) {
  12017. /* Websocket Lua script */
  12018. handle_websocket_request(conn,
  12019. path,
  12020. 0 /* Lua Script */,
  12021. NULL,
  12022. NULL,
  12023. NULL,
  12024. NULL,
  12025. NULL,
  12026. conn->phys_ctx->user_data);
  12027. } else {
  12028. /* Script was in an illegal path */
  12029. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12030. }
  12031. } else {
  12032. #if defined(MG_LEGACY_INTERFACE)
  12033. handle_websocket_request(
  12034. conn,
  12035. path,
  12036. !is_script_resource /* could be deprecated global callback */,
  12037. NULL,
  12038. deprecated_websocket_connect_wrapper,
  12039. deprecated_websocket_ready_wrapper,
  12040. deprecated_websocket_data_wrapper,
  12041. NULL,
  12042. conn->phys_ctx->user_data);
  12043. #else
  12044. mg_send_http_error(conn, 404, "%s", "Not found");
  12045. #endif
  12046. }
  12047. return;
  12048. } else
  12049. #endif
  12050. #if defined(NO_FILES)
  12051. /* 9a. In case the server uses only callbacks, this uri is
  12052. * unknown.
  12053. * Then, all request handling ends here. */
  12054. mg_send_http_error(conn, 404, "%s", "Not Found");
  12055. #else
  12056. /* 9b. This request is either for a static file or resource handled
  12057. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12058. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12059. mg_send_http_error(conn, 404, "%s", "Not Found");
  12060. return;
  12061. }
  12062. /* 10. Request is handled by a script */
  12063. if (is_script_resource) {
  12064. handle_file_based_request(conn, path, &file);
  12065. return;
  12066. }
  12067. /* 11. Handle put/delete/mkcol requests */
  12068. if (is_put_or_delete_request) {
  12069. /* 11.1. PUT method */
  12070. if (!strcmp(ri->request_method, "PUT")) {
  12071. put_file(conn, path);
  12072. return;
  12073. }
  12074. /* 11.2. DELETE method */
  12075. if (!strcmp(ri->request_method, "DELETE")) {
  12076. delete_file(conn, path);
  12077. return;
  12078. }
  12079. /* 11.3. MKCOL method */
  12080. if (!strcmp(ri->request_method, "MKCOL")) {
  12081. mkcol(conn, path);
  12082. return;
  12083. }
  12084. /* 11.4. PATCH method
  12085. * This method is not supported for static resources,
  12086. * only for scripts (Lua, CGI) and callbacks. */
  12087. mg_send_http_error(conn,
  12088. 405,
  12089. "%s method not allowed",
  12090. conn->request_info.request_method);
  12091. return;
  12092. }
  12093. /* 11. File does not exist, or it was configured that it should be
  12094. * hidden */
  12095. if (!is_found || (must_hide_file(conn, path))) {
  12096. mg_send_http_error(conn, 404, "%s", "Not found");
  12097. return;
  12098. }
  12099. /* 12. Directory uris should end with a slash */
  12100. if (file.stat.is_directory && (uri_len > 0)
  12101. && (ri->local_uri[uri_len - 1] != '/')) {
  12102. gmt_time_string(date, sizeof(date), &curtime);
  12103. mg_printf(conn,
  12104. "HTTP/1.1 301 Moved Permanently\r\n"
  12105. "Location: %s/\r\n"
  12106. "Date: %s\r\n"
  12107. /* "Cache-Control: private\r\n" (= default) */
  12108. "Content-Length: 0\r\n"
  12109. "Connection: %s\r\n",
  12110. ri->request_uri,
  12111. date,
  12112. suggest_connection_header(conn));
  12113. send_additional_header(conn);
  12114. mg_printf(conn, "\r\n");
  12115. return;
  12116. }
  12117. /* 13. Handle other methods than GET/HEAD */
  12118. /* 13.1. Handle PROPFIND */
  12119. if (!strcmp(ri->request_method, "PROPFIND")) {
  12120. handle_propfind(conn, path, &file.stat);
  12121. return;
  12122. }
  12123. /* 13.2. Handle OPTIONS for files */
  12124. if (!strcmp(ri->request_method, "OPTIONS")) {
  12125. /* This standard handler is only used for real files.
  12126. * Scripts should support the OPTIONS method themselves, to allow a
  12127. * maximum flexibility.
  12128. * Lua and CGI scripts may fully support CORS this way (including
  12129. * preflights). */
  12130. send_options(conn);
  12131. return;
  12132. }
  12133. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12134. if ((0 != strcmp(ri->request_method, "GET"))
  12135. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12136. mg_send_http_error(conn,
  12137. 405,
  12138. "%s method not allowed",
  12139. conn->request_info.request_method);
  12140. return;
  12141. }
  12142. /* 14. directories */
  12143. if (file.stat.is_directory) {
  12144. /* Substitute files have already been handled above. */
  12145. /* Here we can either generate and send a directory listing,
  12146. * or send an "access denied" error. */
  12147. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12148. "yes")) {
  12149. handle_directory_request(conn, path);
  12150. } else {
  12151. mg_send_http_error(conn,
  12152. 403,
  12153. "%s",
  12154. "Error: Directory listing denied");
  12155. }
  12156. return;
  12157. }
  12158. /* 15. read a normal file with GET or HEAD */
  12159. handle_file_based_request(conn, path, &file);
  12160. #endif /* !defined(NO_FILES) */
  12161. }
  12162. static void
  12163. handle_file_based_request(struct mg_connection *conn,
  12164. const char *path,
  12165. struct mg_file *file)
  12166. {
  12167. if (!conn || !conn->dom_ctx) {
  12168. return;
  12169. }
  12170. if (0) {
  12171. #if defined(USE_LUA)
  12172. } else if (match_prefix(
  12173. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12174. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12175. path)
  12176. > 0) {
  12177. if (is_in_script_path(conn, path)) {
  12178. /* Lua server page: an SSI like page containing mostly plain
  12179. * html
  12180. * code
  12181. * plus some tags with server generated contents. */
  12182. handle_lsp_request(conn, path, file, NULL);
  12183. } else {
  12184. /* Script was in an illegal path */
  12185. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12186. }
  12187. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12188. strlen(
  12189. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12190. path)
  12191. > 0) {
  12192. if (is_in_script_path(conn, path)) {
  12193. /* Lua in-server module script: a CGI like script used to
  12194. * generate
  12195. * the
  12196. * entire reply. */
  12197. mg_exec_lua_script(conn, path, NULL);
  12198. } else {
  12199. /* Script was in an illegal path */
  12200. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12201. }
  12202. #endif
  12203. #if defined(USE_DUKTAPE)
  12204. } else if (match_prefix(
  12205. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12206. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12207. path)
  12208. > 0) {
  12209. if (is_in_script_path(conn, path)) {
  12210. /* Call duktape to generate the page */
  12211. mg_exec_duktape_script(conn, path);
  12212. } else {
  12213. /* Script was in an illegal path */
  12214. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12215. }
  12216. #endif
  12217. #if !defined(NO_CGI)
  12218. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12219. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12220. path)
  12221. > 0) {
  12222. if (is_in_script_path(conn, path)) {
  12223. /* CGI scripts may support all HTTP methods */
  12224. handle_cgi_request(conn, path);
  12225. } else {
  12226. /* Script was in an illegal path */
  12227. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12228. }
  12229. #endif /* !NO_CGI */
  12230. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12231. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12232. path)
  12233. > 0) {
  12234. if (is_in_script_path(conn, path)) {
  12235. handle_ssi_file_request(conn, path, file);
  12236. } else {
  12237. /* Script was in an illegal path */
  12238. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12239. }
  12240. #if !defined(NO_CACHING)
  12241. } else if ((!conn->in_error_handler)
  12242. && is_not_modified(conn, &file->stat)) {
  12243. /* Send 304 "Not Modified" - this must not send any body data */
  12244. handle_not_modified_static_file_request(conn, file);
  12245. #endif /* !NO_CACHING */
  12246. } else {
  12247. handle_static_file_request(conn, path, file, NULL, NULL);
  12248. }
  12249. }
  12250. static void
  12251. close_all_listening_sockets(struct mg_context *ctx)
  12252. {
  12253. unsigned int i;
  12254. if (!ctx) {
  12255. return;
  12256. }
  12257. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12258. closesocket(ctx->listening_sockets[i].sock);
  12259. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12260. }
  12261. mg_free(ctx->listening_sockets);
  12262. ctx->listening_sockets = NULL;
  12263. mg_free(ctx->listening_socket_fds);
  12264. ctx->listening_socket_fds = NULL;
  12265. }
  12266. /* Valid listening port specification is: [ip_address:]port[s]
  12267. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12268. * Examples for IPv6: [::]:80, [::1]:80,
  12269. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12270. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12271. * In order to bind to both, IPv4 and IPv6, you can either add
  12272. * both ports using 8080,[::]:8080, or the short form +8080.
  12273. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12274. * one only accepting IPv4 the other only IPv6. +8080 creates
  12275. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12276. * environment, they might work differently, or might not work
  12277. * at all - it must be tested what options work best in the
  12278. * relevant network environment.
  12279. */
  12280. static int
  12281. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12282. {
  12283. unsigned int a, b, c, d, port;
  12284. int ch, len;
  12285. const char *cb;
  12286. #if defined(USE_IPV6)
  12287. char buf[100] = {0};
  12288. #endif
  12289. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12290. * Also, all-zeroes in the socket address means binding to all addresses
  12291. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12292. memset(so, 0, sizeof(*so));
  12293. so->lsa.sin.sin_family = AF_INET;
  12294. *ip_version = 0;
  12295. /* Initialize port and len as invalid. */
  12296. port = 0;
  12297. len = 0;
  12298. /* Test for different ways to format this string */
  12299. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12300. == 5) {
  12301. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12302. so->lsa.sin.sin_addr.s_addr =
  12303. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12304. so->lsa.sin.sin_port = htons((uint16_t)port);
  12305. *ip_version = 4;
  12306. #if defined(USE_IPV6)
  12307. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12308. && mg_inet_pton(
  12309. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12310. /* IPv6 address, examples: see above */
  12311. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12312. */
  12313. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12314. *ip_version = 6;
  12315. #endif
  12316. } else if ((vec->ptr[0] == '+')
  12317. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12318. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12319. /* Add 1 to len for the + character we skipped before */
  12320. len++;
  12321. #if defined(USE_IPV6)
  12322. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12323. so->lsa.sin6.sin6_family = AF_INET6;
  12324. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12325. *ip_version = 4 + 6;
  12326. #else
  12327. /* Bind to IPv4 only, since IPv6 is not built in. */
  12328. so->lsa.sin.sin_port = htons((uint16_t)port);
  12329. *ip_version = 4;
  12330. #endif
  12331. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  12332. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12333. so->lsa.sin.sin_port = htons((uint16_t)port);
  12334. *ip_version = 4;
  12335. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12336. /* String could be a hostname. This check algotithm
  12337. * will only work for RFC 952 compliant hostnames,
  12338. * starting with a letter, containing only letters,
  12339. * digits and hyphen ('-'). Newer specs may allow
  12340. * more, but this is not guaranteed here, since it
  12341. * may interfere with rules for port option lists. */
  12342. /* According to RFC 1035, hostnames are restricted to 255 characters
  12343. * in total (63 between two dots). */
  12344. char hostname[256];
  12345. size_t hostnlen = (size_t)(cb - vec->ptr);
  12346. if (hostnlen >= sizeof(hostname)) {
  12347. /* This would be invalid in any case */
  12348. *ip_version = 0;
  12349. return 0;
  12350. }
  12351. memcpy(hostname, vec->ptr, hostnlen);
  12352. hostname[hostnlen] = 0;
  12353. if (mg_inet_pton(
  12354. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12355. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12356. *ip_version = 4;
  12357. so->lsa.sin.sin_family = AF_INET;
  12358. so->lsa.sin.sin_port = htons((uint16_t)port);
  12359. len += (int)(hostnlen + 1);
  12360. } else {
  12361. port = 0;
  12362. len = 0;
  12363. }
  12364. #if defined(USE_IPV6)
  12365. } else if (mg_inet_pton(AF_INET6,
  12366. vec->ptr,
  12367. &so->lsa.sin6,
  12368. sizeof(so->lsa.sin6))) {
  12369. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12370. *ip_version = 6;
  12371. so->lsa.sin6.sin6_family = AF_INET6;
  12372. so->lsa.sin.sin_port = htons((uint16_t)port);
  12373. len += (int)(hostnlen + 1);
  12374. } else {
  12375. port = 0;
  12376. len = 0;
  12377. }
  12378. #endif
  12379. }
  12380. } else {
  12381. /* Parsing failure. */
  12382. }
  12383. /* sscanf and the option splitting code ensure the following condition
  12384. */
  12385. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12386. *ip_version = 0;
  12387. return 0;
  12388. }
  12389. ch = vec->ptr[len]; /* Next character after the port number */
  12390. so->is_ssl = (ch == 's');
  12391. so->ssl_redir = (ch == 'r');
  12392. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12393. if (is_valid_port(port)
  12394. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12395. return 1;
  12396. }
  12397. /* Reset ip_version to 0 if there is an error */
  12398. *ip_version = 0;
  12399. return 0;
  12400. }
  12401. /* Is there any SSL port in use? */
  12402. static int
  12403. is_ssl_port_used(const char *ports)
  12404. {
  12405. if (ports) {
  12406. /* There are several different allowed syntax variants:
  12407. * - "80" for a single port using every network interface
  12408. * - "localhost:80" for a single port using only localhost
  12409. * - "80,localhost:8080" for two ports, one bound to localhost
  12410. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12411. * to IPv4 localhost, one to IPv6 localhost
  12412. * - "+80" use port 80 for IPv4 and IPv6
  12413. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12414. * for both: IPv4 and IPv4
  12415. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12416. * additionally port 8080 bound to localhost connections
  12417. *
  12418. * If we just look for 's' anywhere in the string, "localhost:80"
  12419. * will be detected as SSL (false positive).
  12420. * Looking for 's' after a digit may cause false positives in
  12421. * "my24service:8080".
  12422. * Looking from 's' backward if there are only ':' and numbers
  12423. * before will not work for "24service:8080" (non SSL, port 8080)
  12424. * or "24s" (SSL, port 24).
  12425. *
  12426. * Remark: Initially hostnames were not allowed to start with a
  12427. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12428. * Section 2.1).
  12429. *
  12430. * To get this correct, the entire string must be parsed as a whole,
  12431. * reading it as a list element for element and parsing with an
  12432. * algorithm equivalent to parse_port_string.
  12433. *
  12434. * In fact, we use local interface names here, not arbitrary hostnames,
  12435. * so in most cases the only name will be "localhost".
  12436. *
  12437. * So, for now, we use this simple algorithm, that may still return
  12438. * a false positive in bizarre cases.
  12439. */
  12440. int i;
  12441. int portslen = (int)strlen(ports);
  12442. char prevIsNumber = 0;
  12443. for (i = 0; i < portslen; i++) {
  12444. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12445. return 1;
  12446. }
  12447. if (ports[i] >= '0' && ports[i] <= '9') {
  12448. prevIsNumber = 1;
  12449. } else {
  12450. prevIsNumber = 0;
  12451. }
  12452. }
  12453. }
  12454. return 0;
  12455. }
  12456. static int
  12457. set_ports_option(struct mg_context *phys_ctx)
  12458. {
  12459. const char *list;
  12460. int on = 1;
  12461. #if defined(USE_IPV6)
  12462. int off = 0;
  12463. #endif
  12464. struct vec vec;
  12465. struct socket so, *ptr;
  12466. struct mg_pollfd *pfd;
  12467. union usa usa;
  12468. socklen_t len;
  12469. int ip_version;
  12470. int portsTotal = 0;
  12471. int portsOk = 0;
  12472. if (!phys_ctx) {
  12473. return 0;
  12474. }
  12475. memset(&so, 0, sizeof(so));
  12476. memset(&usa, 0, sizeof(usa));
  12477. len = sizeof(usa);
  12478. list = phys_ctx->dd.config[LISTENING_PORTS];
  12479. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12480. portsTotal++;
  12481. if (!parse_port_string(&vec, &so, &ip_version)) {
  12482. mg_cry_ctx_internal(
  12483. phys_ctx,
  12484. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12485. (int)vec.len,
  12486. vec.ptr,
  12487. portsTotal,
  12488. "[IP_ADDRESS:]PORT[s|r]");
  12489. continue;
  12490. }
  12491. #if !defined(NO_SSL)
  12492. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12493. mg_cry_ctx_internal(phys_ctx,
  12494. "Cannot add SSL socket (entry %i)",
  12495. portsTotal);
  12496. continue;
  12497. }
  12498. #endif
  12499. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12500. == INVALID_SOCKET) {
  12501. mg_cry_ctx_internal(phys_ctx,
  12502. "cannot create socket (entry %i)",
  12503. portsTotal);
  12504. continue;
  12505. }
  12506. #if defined(_WIN32)
  12507. /* Windows SO_REUSEADDR lets many procs binds to a
  12508. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12509. * if someone already has the socket -- DTL */
  12510. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12511. * Windows might need a few seconds before
  12512. * the same port can be used again in the
  12513. * same process, so a short Sleep may be
  12514. * required between mg_stop and mg_start.
  12515. */
  12516. if (setsockopt(so.sock,
  12517. SOL_SOCKET,
  12518. SO_EXCLUSIVEADDRUSE,
  12519. (SOCK_OPT_TYPE)&on,
  12520. sizeof(on))
  12521. != 0) {
  12522. /* Set reuse option, but don't abort on errors. */
  12523. mg_cry_ctx_internal(
  12524. phys_ctx,
  12525. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12526. portsTotal);
  12527. }
  12528. #else
  12529. if (setsockopt(so.sock,
  12530. SOL_SOCKET,
  12531. SO_REUSEADDR,
  12532. (SOCK_OPT_TYPE)&on,
  12533. sizeof(on))
  12534. != 0) {
  12535. /* Set reuse option, but don't abort on errors. */
  12536. mg_cry_ctx_internal(
  12537. phys_ctx,
  12538. "cannot set socket option SO_REUSEADDR (entry %i)",
  12539. portsTotal);
  12540. }
  12541. #endif
  12542. if (ip_version > 4) {
  12543. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12544. #if defined(USE_IPV6)
  12545. if (ip_version > 6) {
  12546. if (so.lsa.sa.sa_family == AF_INET6
  12547. && setsockopt(so.sock,
  12548. IPPROTO_IPV6,
  12549. IPV6_V6ONLY,
  12550. (void *)&off,
  12551. sizeof(off))
  12552. != 0) {
  12553. /* Set IPv6 only option, but don't abort on errors. */
  12554. mg_cry_ctx_internal(
  12555. phys_ctx,
  12556. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12557. portsTotal);
  12558. }
  12559. } else {
  12560. if (so.lsa.sa.sa_family == AF_INET6
  12561. && setsockopt(so.sock,
  12562. IPPROTO_IPV6,
  12563. IPV6_V6ONLY,
  12564. (void *)&on,
  12565. sizeof(on))
  12566. != 0) {
  12567. /* Set IPv6 only option, but don't abort on errors. */
  12568. mg_cry_ctx_internal(
  12569. phys_ctx,
  12570. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12571. portsTotal);
  12572. }
  12573. }
  12574. #else
  12575. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12576. closesocket(so.sock);
  12577. so.sock = INVALID_SOCKET;
  12578. continue;
  12579. #endif
  12580. }
  12581. if (so.lsa.sa.sa_family == AF_INET) {
  12582. len = sizeof(so.lsa.sin);
  12583. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12584. mg_cry_ctx_internal(phys_ctx,
  12585. "cannot bind to %.*s: %d (%s)",
  12586. (int)vec.len,
  12587. vec.ptr,
  12588. (int)ERRNO,
  12589. strerror(errno));
  12590. closesocket(so.sock);
  12591. so.sock = INVALID_SOCKET;
  12592. continue;
  12593. }
  12594. }
  12595. #if defined(USE_IPV6)
  12596. else if (so.lsa.sa.sa_family == AF_INET6) {
  12597. len = sizeof(so.lsa.sin6);
  12598. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12599. mg_cry_ctx_internal(phys_ctx,
  12600. "cannot bind to IPv6 %.*s: %d (%s)",
  12601. (int)vec.len,
  12602. vec.ptr,
  12603. (int)ERRNO,
  12604. strerror(errno));
  12605. closesocket(so.sock);
  12606. so.sock = INVALID_SOCKET;
  12607. continue;
  12608. }
  12609. }
  12610. #endif
  12611. else {
  12612. mg_cry_ctx_internal(
  12613. phys_ctx,
  12614. "cannot bind: address family not supported (entry %i)",
  12615. portsTotal);
  12616. closesocket(so.sock);
  12617. so.sock = INVALID_SOCKET;
  12618. continue;
  12619. }
  12620. if (listen(so.sock, SOMAXCONN) != 0) {
  12621. mg_cry_ctx_internal(phys_ctx,
  12622. "cannot listen to %.*s: %d (%s)",
  12623. (int)vec.len,
  12624. vec.ptr,
  12625. (int)ERRNO,
  12626. strerror(errno));
  12627. closesocket(so.sock);
  12628. so.sock = INVALID_SOCKET;
  12629. continue;
  12630. }
  12631. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12632. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12633. int err = (int)ERRNO;
  12634. mg_cry_ctx_internal(phys_ctx,
  12635. "call to getsockname failed %.*s: %d (%s)",
  12636. (int)vec.len,
  12637. vec.ptr,
  12638. err,
  12639. strerror(errno));
  12640. closesocket(so.sock);
  12641. so.sock = INVALID_SOCKET;
  12642. continue;
  12643. }
  12644. /* Update lsa port in case of random free ports */
  12645. #if defined(USE_IPV6)
  12646. if (so.lsa.sa.sa_family == AF_INET6) {
  12647. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12648. } else
  12649. #endif
  12650. {
  12651. so.lsa.sin.sin_port = usa.sin.sin_port;
  12652. }
  12653. if ((ptr = (struct socket *)
  12654. mg_realloc_ctx(phys_ctx->listening_sockets,
  12655. (phys_ctx->num_listening_sockets + 1)
  12656. * sizeof(phys_ctx->listening_sockets[0]),
  12657. phys_ctx))
  12658. == NULL) {
  12659. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12660. closesocket(so.sock);
  12661. so.sock = INVALID_SOCKET;
  12662. continue;
  12663. }
  12664. if ((pfd = (struct mg_pollfd *)
  12665. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12666. (phys_ctx->num_listening_sockets + 1)
  12667. * sizeof(phys_ctx->listening_socket_fds[0]),
  12668. phys_ctx))
  12669. == NULL) {
  12670. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12671. closesocket(so.sock);
  12672. so.sock = INVALID_SOCKET;
  12673. mg_free(ptr);
  12674. continue;
  12675. }
  12676. set_close_on_exec(so.sock, NULL, phys_ctx);
  12677. phys_ctx->listening_sockets = ptr;
  12678. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12679. phys_ctx->listening_socket_fds = pfd;
  12680. phys_ctx->num_listening_sockets++;
  12681. portsOk++;
  12682. }
  12683. if (portsOk != portsTotal) {
  12684. close_all_listening_sockets(phys_ctx);
  12685. portsOk = 0;
  12686. }
  12687. return portsOk;
  12688. }
  12689. static const char *
  12690. header_val(const struct mg_connection *conn, const char *header)
  12691. {
  12692. const char *header_value;
  12693. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12694. return "-";
  12695. } else {
  12696. return header_value;
  12697. }
  12698. }
  12699. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12700. static void log_access(const struct mg_connection *conn);
  12701. #include "external_log_access.inl"
  12702. #else
  12703. static void
  12704. log_access(const struct mg_connection *conn)
  12705. {
  12706. const struct mg_request_info *ri;
  12707. struct mg_file fi;
  12708. char date[64], src_addr[IP_ADDR_STR_LEN];
  12709. struct tm *tm;
  12710. const char *referer;
  12711. const char *user_agent;
  12712. char buf[4096];
  12713. if (!conn || !conn->dom_ctx) {
  12714. return;
  12715. }
  12716. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12717. if (mg_fopen(conn,
  12718. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12719. MG_FOPEN_MODE_APPEND,
  12720. &fi)
  12721. == 0) {
  12722. fi.access.fp = NULL;
  12723. }
  12724. } else {
  12725. fi.access.fp = NULL;
  12726. }
  12727. /* Log is written to a file and/or a callback. If both are not set,
  12728. * executing the rest of the function is pointless. */
  12729. if ((fi.access.fp == NULL)
  12730. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12731. return;
  12732. }
  12733. tm = localtime(&conn->conn_birth_time);
  12734. if (tm != NULL) {
  12735. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12736. } else {
  12737. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12738. date[sizeof(date) - 1] = '\0';
  12739. }
  12740. ri = &conn->request_info;
  12741. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12742. referer = header_val(conn, "Referer");
  12743. user_agent = header_val(conn, "User-Agent");
  12744. mg_snprintf(conn,
  12745. NULL, /* Ignore truncation in access log */
  12746. buf,
  12747. sizeof(buf),
  12748. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12749. src_addr,
  12750. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12751. date,
  12752. ri->request_method ? ri->request_method : "-",
  12753. ri->request_uri ? ri->request_uri : "-",
  12754. ri->query_string ? "?" : "",
  12755. ri->query_string ? ri->query_string : "",
  12756. ri->http_version,
  12757. conn->status_code,
  12758. conn->num_bytes_sent,
  12759. referer,
  12760. user_agent);
  12761. if (conn->phys_ctx->callbacks.log_access) {
  12762. conn->phys_ctx->callbacks.log_access(conn, buf);
  12763. }
  12764. if (fi.access.fp) {
  12765. int ok = 1;
  12766. flockfile(fi.access.fp);
  12767. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12768. ok = 0;
  12769. }
  12770. if (fflush(fi.access.fp) != 0) {
  12771. ok = 0;
  12772. }
  12773. funlockfile(fi.access.fp);
  12774. if (mg_fclose(&fi.access) != 0) {
  12775. ok = 0;
  12776. }
  12777. if (!ok) {
  12778. mg_cry_internal(conn,
  12779. "Error writing log file %s",
  12780. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12781. }
  12782. }
  12783. }
  12784. #endif /* Externally provided function */
  12785. /* Verify given socket address against the ACL.
  12786. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12787. */
  12788. static int
  12789. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12790. {
  12791. int allowed, flag;
  12792. uint32_t net, mask;
  12793. struct vec vec;
  12794. if (phys_ctx) {
  12795. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12796. /* If any ACL is set, deny by default */
  12797. allowed = (list == NULL) ? '+' : '-';
  12798. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12799. flag = vec.ptr[0];
  12800. if ((flag != '+' && flag != '-')
  12801. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12802. mg_cry_ctx_internal(phys_ctx,
  12803. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12804. __func__);
  12805. return -1;
  12806. }
  12807. if (net == (remote_ip & mask)) {
  12808. allowed = flag;
  12809. }
  12810. }
  12811. return allowed == '+';
  12812. }
  12813. return -1;
  12814. }
  12815. #if !defined(_WIN32)
  12816. static int
  12817. set_uid_option(struct mg_context *phys_ctx)
  12818. {
  12819. int success = 0;
  12820. if (phys_ctx) {
  12821. /* We are currently running as curr_uid. */
  12822. const uid_t curr_uid = getuid();
  12823. /* If set, we want to run as run_as_user. */
  12824. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12825. const struct passwd *to_pw = NULL;
  12826. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12827. /* run_as_user does not exist on the system. We can't proceed
  12828. * further. */
  12829. mg_cry_ctx_internal(phys_ctx,
  12830. "%s: unknown user [%s]",
  12831. __func__,
  12832. run_as_user);
  12833. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12834. /* There was either no request to change user, or we're already
  12835. * running as run_as_user. Nothing else to do.
  12836. */
  12837. success = 1;
  12838. } else {
  12839. /* Valid change request. */
  12840. if (setgid(to_pw->pw_gid) == -1) {
  12841. mg_cry_ctx_internal(phys_ctx,
  12842. "%s: setgid(%s): %s",
  12843. __func__,
  12844. run_as_user,
  12845. strerror(errno));
  12846. } else if (setgroups(0, NULL) == -1) {
  12847. mg_cry_ctx_internal(phys_ctx,
  12848. "%s: setgroups(): %s",
  12849. __func__,
  12850. strerror(errno));
  12851. } else if (setuid(to_pw->pw_uid) == -1) {
  12852. mg_cry_ctx_internal(phys_ctx,
  12853. "%s: setuid(%s): %s",
  12854. __func__,
  12855. run_as_user,
  12856. strerror(errno));
  12857. } else {
  12858. success = 1;
  12859. }
  12860. }
  12861. }
  12862. return success;
  12863. }
  12864. #endif /* !_WIN32 */
  12865. static void
  12866. tls_dtor(void *key)
  12867. {
  12868. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12869. /* key == pthread_getspecific(sTlsKey); */
  12870. if (tls) {
  12871. if (tls->is_master == 2) {
  12872. tls->is_master = -3; /* Mark memory as dead */
  12873. mg_free(tls);
  12874. }
  12875. }
  12876. pthread_setspecific(sTlsKey, NULL);
  12877. }
  12878. #if !defined(NO_SSL)
  12879. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12880. struct mg_domain_context *dom_ctx,
  12881. const char *pem,
  12882. const char *chain);
  12883. static const char *ssl_error(void);
  12884. static int
  12885. refresh_trust(struct mg_connection *conn)
  12886. {
  12887. static int reload_lock = 0;
  12888. static long int data_check = 0;
  12889. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12890. struct stat cert_buf;
  12891. long int t;
  12892. const char *pem;
  12893. const char *chain;
  12894. int should_verify_peer;
  12895. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12896. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12897. * refresh_trust still can not work. */
  12898. return 0;
  12899. }
  12900. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12901. if (chain == NULL) {
  12902. /* pem is not NULL here */
  12903. chain = pem;
  12904. }
  12905. if (*chain == 0) {
  12906. chain = NULL;
  12907. }
  12908. t = data_check;
  12909. if (stat(pem, &cert_buf) != -1) {
  12910. t = (long int)cert_buf.st_mtime;
  12911. }
  12912. if (data_check != t) {
  12913. data_check = t;
  12914. should_verify_peer = 0;
  12915. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12916. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12917. == 0) {
  12918. should_verify_peer = 1;
  12919. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12920. "optional")
  12921. == 0) {
  12922. should_verify_peer = 1;
  12923. }
  12924. }
  12925. if (should_verify_peer) {
  12926. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12927. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12928. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12929. ca_file,
  12930. ca_path)
  12931. != 1) {
  12932. mg_cry_ctx_internal(
  12933. conn->phys_ctx,
  12934. "SSL_CTX_load_verify_locations error: %s "
  12935. "ssl_verify_peer requires setting "
  12936. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12937. "present in "
  12938. "the .conf file?",
  12939. ssl_error());
  12940. return 0;
  12941. }
  12942. }
  12943. if (1 == mg_atomic_inc(p_reload_lock)) {
  12944. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12945. == 0) {
  12946. return 0;
  12947. }
  12948. *p_reload_lock = 0;
  12949. }
  12950. }
  12951. /* lock while cert is reloading */
  12952. while (*p_reload_lock) {
  12953. sleep(1);
  12954. }
  12955. return 1;
  12956. }
  12957. #if defined(OPENSSL_API_1_1)
  12958. #else
  12959. static pthread_mutex_t *ssl_mutexes;
  12960. #endif /* OPENSSL_API_1_1 */
  12961. static int
  12962. sslize(struct mg_connection *conn,
  12963. SSL_CTX *s,
  12964. int (*func)(SSL *),
  12965. volatile int *stop_server,
  12966. const struct mg_client_options *client_options)
  12967. {
  12968. int ret, err;
  12969. int short_trust;
  12970. unsigned timeout = 1024;
  12971. unsigned i;
  12972. if (!conn) {
  12973. return 0;
  12974. }
  12975. short_trust =
  12976. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  12977. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  12978. if (short_trust) {
  12979. int trust_ret = refresh_trust(conn);
  12980. if (!trust_ret) {
  12981. return trust_ret;
  12982. }
  12983. }
  12984. conn->ssl = SSL_new(s);
  12985. if (conn->ssl == NULL) {
  12986. return 0;
  12987. }
  12988. SSL_set_app_data(conn->ssl, (char *)conn);
  12989. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  12990. if (ret != 1) {
  12991. err = SSL_get_error(conn->ssl, ret);
  12992. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  12993. SSL_free(conn->ssl);
  12994. conn->ssl = NULL;
  12995. OPENSSL_REMOVE_THREAD_STATE();
  12996. return 0;
  12997. }
  12998. if (client_options) {
  12999. if (client_options->host_name) {
  13000. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13001. }
  13002. }
  13003. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13004. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13005. /* NOTE: The loop below acts as a back-off, so we can end
  13006. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13007. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13008. }
  13009. /* SSL functions may fail and require to be called again:
  13010. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13011. * Here "func" could be SSL_connect or SSL_accept. */
  13012. for (i = 0; i <= timeout; i += 50) {
  13013. ret = func(conn->ssl);
  13014. if (ret != 1) {
  13015. err = SSL_get_error(conn->ssl, ret);
  13016. if ((err == SSL_ERROR_WANT_CONNECT)
  13017. || (err == SSL_ERROR_WANT_ACCEPT)
  13018. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13019. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13020. if (*stop_server) {
  13021. /* Don't wait if the server is going to be stopped. */
  13022. break;
  13023. }
  13024. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13025. /* Simply retry the function call. */
  13026. mg_sleep(50);
  13027. } else {
  13028. /* Need to retry the function call "later".
  13029. * See https://linux.die.net/man/3/ssl_get_error
  13030. * This is typical for non-blocking sockets. */
  13031. struct mg_pollfd pfd;
  13032. pfd.fd = conn->client.sock;
  13033. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13034. || (err == SSL_ERROR_WANT_WRITE))
  13035. ? POLLOUT
  13036. : POLLIN;
  13037. mg_poll(&pfd, 1, 50, stop_server);
  13038. }
  13039. } else if (err == SSL_ERROR_SYSCALL) {
  13040. /* This is an IO error. Look at errno. */
  13041. err = errno;
  13042. mg_cry_internal(conn, "SSL syscall error %i", err);
  13043. break;
  13044. } else {
  13045. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13046. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13047. break;
  13048. }
  13049. ERR_clear_error();
  13050. } else {
  13051. /* success */
  13052. break;
  13053. }
  13054. }
  13055. if (ret != 1) {
  13056. SSL_free(conn->ssl);
  13057. conn->ssl = NULL;
  13058. OPENSSL_REMOVE_THREAD_STATE();
  13059. return 0;
  13060. }
  13061. return 1;
  13062. }
  13063. /* Return OpenSSL error message (from CRYPTO lib) */
  13064. static const char *
  13065. ssl_error(void)
  13066. {
  13067. unsigned long err;
  13068. err = ERR_get_error();
  13069. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13070. }
  13071. static int
  13072. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13073. {
  13074. int i;
  13075. const char hexdigit[] = "0123456789abcdef";
  13076. if ((memlen <= 0) || (buflen <= 0)) {
  13077. return 0;
  13078. }
  13079. if (buflen < (3 * memlen)) {
  13080. return 0;
  13081. }
  13082. for (i = 0; i < memlen; i++) {
  13083. if (i > 0) {
  13084. buf[3 * i - 1] = ' ';
  13085. }
  13086. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13087. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13088. }
  13089. buf[3 * memlen - 1] = 0;
  13090. return 1;
  13091. }
  13092. static void
  13093. ssl_get_client_cert_info(struct mg_connection *conn)
  13094. {
  13095. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13096. if (cert) {
  13097. char str_subject[1024];
  13098. char str_issuer[1024];
  13099. char str_finger[1024];
  13100. unsigned char buf[256];
  13101. char *str_serial = NULL;
  13102. unsigned int ulen;
  13103. int ilen;
  13104. unsigned char *tmp_buf;
  13105. unsigned char *tmp_p;
  13106. /* Handle to algorithm used for fingerprint */
  13107. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13108. /* Get Subject and issuer */
  13109. X509_NAME *subj = X509_get_subject_name(cert);
  13110. X509_NAME *iss = X509_get_issuer_name(cert);
  13111. /* Get serial number */
  13112. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13113. /* Translate serial number to a hex string */
  13114. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13115. str_serial = BN_bn2hex(serial_bn);
  13116. BN_free(serial_bn);
  13117. /* Translate subject and issuer to a string */
  13118. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13119. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13120. /* Calculate SHA1 fingerprint and store as a hex string */
  13121. ulen = 0;
  13122. /* ASN1_digest is deprecated. Do the calculation manually,
  13123. * using EVP_Digest. */
  13124. ilen = i2d_X509(cert, NULL);
  13125. tmp_buf = (ilen > 0)
  13126. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13127. conn->phys_ctx)
  13128. : NULL;
  13129. if (tmp_buf) {
  13130. tmp_p = tmp_buf;
  13131. (void)i2d_X509(cert, &tmp_p);
  13132. if (!EVP_Digest(
  13133. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13134. ulen = 0;
  13135. }
  13136. mg_free(tmp_buf);
  13137. }
  13138. if (!hexdump2string(
  13139. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13140. *str_finger = 0;
  13141. }
  13142. conn->request_info.client_cert = (struct mg_client_cert *)
  13143. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13144. if (conn->request_info.client_cert) {
  13145. conn->request_info.client_cert->peer_cert = (void *)cert;
  13146. conn->request_info.client_cert->subject =
  13147. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13148. conn->request_info.client_cert->issuer =
  13149. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13150. conn->request_info.client_cert->serial =
  13151. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13152. conn->request_info.client_cert->finger =
  13153. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13154. } else {
  13155. mg_cry_internal(conn,
  13156. "%s",
  13157. "Out of memory: Cannot allocate memory for client "
  13158. "certificate");
  13159. }
  13160. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13161. * see https://linux.die.net/man/3/bn_bn2hex */
  13162. OPENSSL_free(str_serial);
  13163. }
  13164. }
  13165. #if defined(OPENSSL_API_1_1)
  13166. #else
  13167. static void
  13168. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13169. {
  13170. (void)line;
  13171. (void)file;
  13172. if (mode & 1) {
  13173. /* 1 is CRYPTO_LOCK */
  13174. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13175. } else {
  13176. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13177. }
  13178. }
  13179. #endif /* OPENSSL_API_1_1 */
  13180. #if !defined(NO_SSL_DL)
  13181. static void *
  13182. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13183. {
  13184. union {
  13185. void *p;
  13186. void (*fp)(void);
  13187. } u;
  13188. void *dll_handle;
  13189. struct ssl_func *fp;
  13190. int ok;
  13191. int truncated = 0;
  13192. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13193. mg_snprintf(NULL,
  13194. NULL, /* No truncation check for ebuf */
  13195. ebuf,
  13196. ebuf_len,
  13197. "%s: cannot load %s",
  13198. __func__,
  13199. dll_name);
  13200. return NULL;
  13201. }
  13202. ok = 1;
  13203. for (fp = sw; fp->name != NULL; fp++) {
  13204. #if defined(_WIN32)
  13205. /* GetProcAddress() returns pointer to function */
  13206. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13207. #else
  13208. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13209. * pointers to function pointers. We need to use a union to make a
  13210. * cast. */
  13211. u.p = dlsym(dll_handle, fp->name);
  13212. #endif /* _WIN32 */
  13213. if (u.fp == NULL) {
  13214. if (ok) {
  13215. mg_snprintf(NULL,
  13216. &truncated,
  13217. ebuf,
  13218. ebuf_len,
  13219. "%s: %s: cannot find %s",
  13220. __func__,
  13221. dll_name,
  13222. fp->name);
  13223. ok = 0;
  13224. } else {
  13225. size_t cur_len = strlen(ebuf);
  13226. if (!truncated) {
  13227. mg_snprintf(NULL,
  13228. &truncated,
  13229. ebuf + cur_len,
  13230. ebuf_len - cur_len - 3,
  13231. ", %s",
  13232. fp->name);
  13233. if (truncated) {
  13234. /* If truncated, add "..." */
  13235. strcat(ebuf, "...");
  13236. }
  13237. }
  13238. }
  13239. /* Debug:
  13240. * printf("Missing function: %s\n", fp->name); */
  13241. } else {
  13242. fp->ptr = u.fp;
  13243. }
  13244. }
  13245. if (!ok) {
  13246. (void)dlclose(dll_handle);
  13247. return NULL;
  13248. }
  13249. return dll_handle;
  13250. }
  13251. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13252. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13253. #endif /* NO_SSL_DL */
  13254. #if defined(SSL_ALREADY_INITIALIZED)
  13255. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13256. #else
  13257. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13258. #endif
  13259. static int
  13260. initialize_ssl(char *ebuf, size_t ebuf_len)
  13261. {
  13262. #if defined(OPENSSL_API_1_1)
  13263. if (ebuf_len > 0) {
  13264. ebuf[0] = 0;
  13265. }
  13266. #if !defined(NO_SSL_DL)
  13267. if (!cryptolib_dll_handle) {
  13268. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13269. if (!cryptolib_dll_handle) {
  13270. mg_snprintf(NULL,
  13271. NULL, /* No truncation check for ebuf */
  13272. ebuf,
  13273. ebuf_len,
  13274. "%s: error loading library %s",
  13275. __func__,
  13276. CRYPTO_LIB);
  13277. DEBUG_TRACE("%s", ebuf);
  13278. return 0;
  13279. }
  13280. }
  13281. #endif /* NO_SSL_DL */
  13282. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13283. return 1;
  13284. }
  13285. #else /* not OPENSSL_API_1_1 */
  13286. int i, num_locks;
  13287. size_t size;
  13288. if (ebuf_len > 0) {
  13289. ebuf[0] = 0;
  13290. }
  13291. #if !defined(NO_SSL_DL)
  13292. if (!cryptolib_dll_handle) {
  13293. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13294. if (!cryptolib_dll_handle) {
  13295. mg_snprintf(NULL,
  13296. NULL, /* No truncation check for ebuf */
  13297. ebuf,
  13298. ebuf_len,
  13299. "%s: error loading library %s",
  13300. __func__,
  13301. CRYPTO_LIB);
  13302. DEBUG_TRACE("%s", ebuf);
  13303. return 0;
  13304. }
  13305. }
  13306. #endif /* NO_SSL_DL */
  13307. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13308. return 1;
  13309. }
  13310. /* Initialize locking callbacks, needed for thread safety.
  13311. * http://www.openssl.org/support/faq.html#PROG1
  13312. */
  13313. num_locks = CRYPTO_num_locks();
  13314. if (num_locks < 0) {
  13315. num_locks = 0;
  13316. }
  13317. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13318. /* allocate mutex array, if required */
  13319. if (num_locks == 0) {
  13320. /* No mutex array required */
  13321. ssl_mutexes = NULL;
  13322. } else {
  13323. /* Mutex array required - allocate it */
  13324. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13325. /* Check OOM */
  13326. if (ssl_mutexes == NULL) {
  13327. mg_snprintf(NULL,
  13328. NULL, /* No truncation check for ebuf */
  13329. ebuf,
  13330. ebuf_len,
  13331. "%s: cannot allocate mutexes: %s",
  13332. __func__,
  13333. ssl_error());
  13334. DEBUG_TRACE("%s", ebuf);
  13335. return 0;
  13336. }
  13337. /* initialize mutex array */
  13338. for (i = 0; i < num_locks; i++) {
  13339. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13340. mg_snprintf(NULL,
  13341. NULL, /* No truncation check for ebuf */
  13342. ebuf,
  13343. ebuf_len,
  13344. "%s: error initializing mutex %i of %i",
  13345. __func__,
  13346. i,
  13347. num_locks);
  13348. DEBUG_TRACE("%s", ebuf);
  13349. mg_free(ssl_mutexes);
  13350. return 0;
  13351. }
  13352. }
  13353. }
  13354. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13355. CRYPTO_set_id_callback(&mg_current_thread_id);
  13356. #endif /* OPENSSL_API_1_1 */
  13357. #if !defined(NO_SSL_DL)
  13358. if (!ssllib_dll_handle) {
  13359. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13360. if (!ssllib_dll_handle) {
  13361. #if !defined(OPENSSL_API_1_1)
  13362. mg_free(ssl_mutexes);
  13363. #endif
  13364. DEBUG_TRACE("%s", ebuf);
  13365. return 0;
  13366. }
  13367. }
  13368. #endif /* NO_SSL_DL */
  13369. #if defined(OPENSSL_API_1_1)
  13370. /* Initialize SSL library */
  13371. OPENSSL_init_ssl(0, NULL);
  13372. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13373. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13374. NULL);
  13375. #else
  13376. /* Initialize SSL library */
  13377. SSL_library_init();
  13378. SSL_load_error_strings();
  13379. #endif
  13380. return 1;
  13381. }
  13382. static int
  13383. ssl_use_pem_file(struct mg_context *phys_ctx,
  13384. struct mg_domain_context *dom_ctx,
  13385. const char *pem,
  13386. const char *chain)
  13387. {
  13388. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13389. mg_cry_ctx_internal(phys_ctx,
  13390. "%s: cannot open certificate file %s: %s",
  13391. __func__,
  13392. pem,
  13393. ssl_error());
  13394. return 0;
  13395. }
  13396. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13397. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13398. mg_cry_ctx_internal(phys_ctx,
  13399. "%s: cannot open private key file %s: %s",
  13400. __func__,
  13401. pem,
  13402. ssl_error());
  13403. return 0;
  13404. }
  13405. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13406. mg_cry_ctx_internal(phys_ctx,
  13407. "%s: certificate and private key do not match: %s",
  13408. __func__,
  13409. pem);
  13410. return 0;
  13411. }
  13412. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13413. * chain files that contain private keys and certificates in
  13414. * SSL_CTX_use_certificate_chain_file.
  13415. * The CivetWeb-Server used pem-Files that contained both information.
  13416. * In order to make wolfSSL work, it is split in two files.
  13417. * One file that contains key and certificate used by the server and
  13418. * an optional chain file for the ssl stack.
  13419. */
  13420. if (chain) {
  13421. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13422. mg_cry_ctx_internal(phys_ctx,
  13423. "%s: cannot use certificate chain file %s: %s",
  13424. __func__,
  13425. chain,
  13426. ssl_error());
  13427. return 0;
  13428. }
  13429. }
  13430. return 1;
  13431. }
  13432. #if defined(OPENSSL_API_1_1)
  13433. static unsigned long
  13434. ssl_get_protocol(int version_id)
  13435. {
  13436. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13437. if (version_id > 0)
  13438. ret |= SSL_OP_NO_SSLv2;
  13439. if (version_id > 1)
  13440. ret |= SSL_OP_NO_SSLv3;
  13441. if (version_id > 2)
  13442. ret |= SSL_OP_NO_TLSv1;
  13443. if (version_id > 3)
  13444. ret |= SSL_OP_NO_TLSv1_1;
  13445. if (version_id > 4)
  13446. ret |= SSL_OP_NO_TLSv1_2;
  13447. #if defined(SSL_OP_NO_TLSv1_3)
  13448. if (version_id > 5)
  13449. ret |= SSL_OP_NO_TLSv1_3;
  13450. #endif
  13451. return ret;
  13452. }
  13453. #else
  13454. static long
  13455. ssl_get_protocol(int version_id)
  13456. {
  13457. long ret = (long)SSL_OP_ALL;
  13458. if (version_id > 0)
  13459. ret |= SSL_OP_NO_SSLv2;
  13460. if (version_id > 1)
  13461. ret |= SSL_OP_NO_SSLv3;
  13462. if (version_id > 2)
  13463. ret |= SSL_OP_NO_TLSv1;
  13464. if (version_id > 3)
  13465. ret |= SSL_OP_NO_TLSv1_1;
  13466. if (version_id > 4)
  13467. ret |= SSL_OP_NO_TLSv1_2;
  13468. #if defined(SSL_OP_NO_TLSv1_3)
  13469. if (version_id > 5)
  13470. ret |= SSL_OP_NO_TLSv1_3;
  13471. #endif
  13472. return ret;
  13473. }
  13474. #endif /* OPENSSL_API_1_1 */
  13475. /* SSL callback documentation:
  13476. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13477. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13478. * https://linux.die.net/man/3/ssl_set_info_callback */
  13479. /* Note: There is no "const" for the first argument in the documentation
  13480. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13481. * / OpenSSL compatibility layers have it. Having a different definition will
  13482. * cause a warning in C and an error in C++. Use "const SSL *", while
  13483. * automatical conversion from "SSL *" works for all compilers, but not other
  13484. * way around */
  13485. static void
  13486. ssl_info_callback(const SSL *ssl, int what, int ret)
  13487. {
  13488. (void)ret;
  13489. if (what & SSL_CB_HANDSHAKE_START) {
  13490. SSL_get_app_data(ssl);
  13491. }
  13492. if (what & SSL_CB_HANDSHAKE_DONE) {
  13493. /* TODO: check for openSSL 1.1 */
  13494. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13495. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13496. }
  13497. }
  13498. static int
  13499. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13500. {
  13501. struct mg_context *ctx = (struct mg_context *)arg;
  13502. struct mg_domain_context *dom =
  13503. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13504. #if defined(GCC_DIAGNOSTIC)
  13505. #pragma GCC diagnostic push
  13506. #pragma GCC diagnostic ignored "-Wcast-align"
  13507. #endif /* defined(GCC_DIAGNOSTIC) */
  13508. /* We used an aligned pointer in SSL_set_app_data */
  13509. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13510. #if defined(GCC_DIAGNOSTIC)
  13511. #pragma GCC diagnostic pop
  13512. #endif /* defined(GCC_DIAGNOSTIC) */
  13513. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13514. (void)ad;
  13515. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13516. DEBUG_TRACE("%s", "internal error - assertion failed");
  13517. return SSL_TLSEXT_ERR_NOACK;
  13518. }
  13519. /* Old clients (Win XP) will not support SNI. Then, there
  13520. * is no server name available in the request - we can
  13521. * only work with the default certificate.
  13522. * Multiple HTTPS hosts on one IP+port are only possible
  13523. * with a certificate containing all alternative names.
  13524. */
  13525. if ((servername == NULL) || (*servername == 0)) {
  13526. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13527. conn->dom_ctx = &(ctx->dd);
  13528. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13529. return SSL_TLSEXT_ERR_NOACK;
  13530. }
  13531. DEBUG_TRACE("TLS connection to host %s", servername);
  13532. while (dom) {
  13533. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13534. /* Found matching domain */
  13535. DEBUG_TRACE("TLS domain %s found",
  13536. dom->config[AUTHENTICATION_DOMAIN]);
  13537. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13538. conn->dom_ctx = dom;
  13539. return SSL_TLSEXT_ERR_OK;
  13540. }
  13541. dom = dom->next;
  13542. }
  13543. /* Default domain */
  13544. DEBUG_TRACE("TLS default domain %s used",
  13545. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13546. conn->dom_ctx = &(ctx->dd);
  13547. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13548. return SSL_TLSEXT_ERR_OK;
  13549. }
  13550. /* Setup SSL CTX as required by CivetWeb */
  13551. static int
  13552. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13553. struct mg_domain_context *dom_ctx,
  13554. const char *pem,
  13555. const char *chain)
  13556. {
  13557. int callback_ret;
  13558. int should_verify_peer;
  13559. int peer_certificate_optional;
  13560. const char *ca_path;
  13561. const char *ca_file;
  13562. int use_default_verify_paths;
  13563. int verify_depth;
  13564. struct timespec now_mt;
  13565. md5_byte_t ssl_context_id[16];
  13566. md5_state_t md5state;
  13567. int protocol_ver;
  13568. #if defined(OPENSSL_API_1_1)
  13569. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13570. mg_cry_ctx_internal(phys_ctx,
  13571. "SSL_CTX_new (server) error: %s",
  13572. ssl_error());
  13573. return 0;
  13574. }
  13575. #else
  13576. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13577. mg_cry_ctx_internal(phys_ctx,
  13578. "SSL_CTX_new (server) error: %s",
  13579. ssl_error());
  13580. return 0;
  13581. }
  13582. #endif /* OPENSSL_API_1_1 */
  13583. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13584. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13585. | SSL_OP_NO_TLSv1_1);
  13586. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13587. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13588. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13589. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13590. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13591. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13592. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13593. #if defined(SSL_OP_NO_RENEGOTIATION)
  13594. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  13595. #endif
  13596. #if !defined(NO_SSL_DL)
  13597. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13598. #endif /* NO_SSL_DL */
  13599. /* In SSL documentation examples callback defined without const specifier
  13600. * 'void (*)(SSL *, int, int)' See:
  13601. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13602. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13603. * But in the source code const SSL is used:
  13604. * 'void (*)(const SSL *, int, int)' See:
  13605. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13606. * Problem about wrong documentation described, but not resolved:
  13607. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13608. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13609. * But when compiled with modern C++ compiler, correct const should be
  13610. * provided
  13611. */
  13612. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13613. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13614. ssl_servername_callback);
  13615. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13616. /* If a callback has been specified, call it. */
  13617. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13618. ? 0
  13619. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13620. phys_ctx->user_data));
  13621. /* If callback returns 0, civetweb sets up the SSL certificate.
  13622. * If it returns 1, civetweb assumes the calback already did this.
  13623. * If it returns -1, initializing ssl fails. */
  13624. if (callback_ret < 0) {
  13625. mg_cry_ctx_internal(phys_ctx,
  13626. "SSL callback returned error: %i",
  13627. callback_ret);
  13628. return 0;
  13629. }
  13630. if (callback_ret > 0) {
  13631. /* Callback did everything. */
  13632. return 1;
  13633. }
  13634. /* Use some combination of start time, domain and port as a SSL
  13635. * context ID. This should be unique on the current machine. */
  13636. md5_init(&md5state);
  13637. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13638. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13639. md5_append(&md5state,
  13640. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13641. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13642. md5_append(&md5state,
  13643. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13644. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13645. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13646. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13647. md5_finish(&md5state, ssl_context_id);
  13648. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13649. (unsigned char *)ssl_context_id,
  13650. sizeof(ssl_context_id));
  13651. if (pem != NULL) {
  13652. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13653. return 0;
  13654. }
  13655. }
  13656. /* Should we support client certificates? */
  13657. /* Default is "no". */
  13658. should_verify_peer = 0;
  13659. peer_certificate_optional = 0;
  13660. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13661. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13662. /* Yes, they are mandatory */
  13663. should_verify_peer = 1;
  13664. peer_certificate_optional = 0;
  13665. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13666. "optional")
  13667. == 0) {
  13668. /* Yes, they are optional */
  13669. should_verify_peer = 1;
  13670. peer_certificate_optional = 1;
  13671. }
  13672. }
  13673. use_default_verify_paths =
  13674. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13675. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13676. == 0);
  13677. if (should_verify_peer) {
  13678. ca_path = dom_ctx->config[SSL_CA_PATH];
  13679. ca_file = dom_ctx->config[SSL_CA_FILE];
  13680. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13681. != 1) {
  13682. mg_cry_ctx_internal(phys_ctx,
  13683. "SSL_CTX_load_verify_locations error: %s "
  13684. "ssl_verify_peer requires setting "
  13685. "either ssl_ca_path or ssl_ca_file. "
  13686. "Is any of them present in the "
  13687. ".conf file?",
  13688. ssl_error());
  13689. return 0;
  13690. }
  13691. if (peer_certificate_optional) {
  13692. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13693. } else {
  13694. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13695. SSL_VERIFY_PEER
  13696. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13697. NULL);
  13698. }
  13699. if (use_default_verify_paths
  13700. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13701. mg_cry_ctx_internal(phys_ctx,
  13702. "SSL_CTX_set_default_verify_paths error: %s",
  13703. ssl_error());
  13704. return 0;
  13705. }
  13706. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13707. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13708. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13709. }
  13710. }
  13711. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13712. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13713. dom_ctx->config[SSL_CIPHER_LIST])
  13714. != 1) {
  13715. mg_cry_ctx_internal(phys_ctx,
  13716. "SSL_CTX_set_cipher_list error: %s",
  13717. ssl_error());
  13718. }
  13719. }
  13720. return 1;
  13721. }
  13722. /* Check if SSL is required.
  13723. * If so, dynamically load SSL library
  13724. * and set up ctx->ssl_ctx pointer. */
  13725. static int
  13726. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13727. {
  13728. void *ssl_ctx = 0;
  13729. int callback_ret;
  13730. const char *pem;
  13731. const char *chain;
  13732. char ebuf[128];
  13733. if (!phys_ctx) {
  13734. return 0;
  13735. }
  13736. if (!dom_ctx) {
  13737. dom_ctx = &(phys_ctx->dd);
  13738. }
  13739. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13740. /* No SSL port is set. No need to setup SSL. */
  13741. return 1;
  13742. }
  13743. /* Check for external SSL_CTX */
  13744. callback_ret =
  13745. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13746. ? 0
  13747. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13748. phys_ctx->user_data));
  13749. if (callback_ret < 0) {
  13750. mg_cry_ctx_internal(phys_ctx,
  13751. "external_ssl_ctx callback returned error: %i",
  13752. callback_ret);
  13753. return 0;
  13754. } else if (callback_ret > 0) {
  13755. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13756. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13757. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  13758. return 0;
  13759. }
  13760. return 1;
  13761. }
  13762. /* else: external_ssl_ctx does not exist or returns 0,
  13763. * CivetWeb should continue initializing SSL */
  13764. /* If PEM file is not specified and the init_ssl callback
  13765. * is not specified, setup will fail. */
  13766. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13767. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13768. /* No certificate and no callback:
  13769. * Essential data to set up TLS is missing.
  13770. */
  13771. mg_cry_ctx_internal(phys_ctx,
  13772. "Initializing SSL failed: -%s is not set",
  13773. config_options[SSL_CERTIFICATE].name);
  13774. return 0;
  13775. }
  13776. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13777. if (chain == NULL) {
  13778. chain = pem;
  13779. }
  13780. if ((chain != NULL) && (*chain == 0)) {
  13781. chain = NULL;
  13782. }
  13783. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13784. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  13785. return 0;
  13786. }
  13787. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13788. }
  13789. static void
  13790. uninitialize_ssl(void)
  13791. {
  13792. #if defined(OPENSSL_API_1_1)
  13793. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13794. /* Shutdown according to
  13795. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13796. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13797. */
  13798. CONF_modules_unload(1);
  13799. #else
  13800. int i;
  13801. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13802. /* Shutdown according to
  13803. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13804. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13805. */
  13806. CRYPTO_set_locking_callback(NULL);
  13807. CRYPTO_set_id_callback(NULL);
  13808. ENGINE_cleanup();
  13809. CONF_modules_unload(1);
  13810. ERR_free_strings();
  13811. EVP_cleanup();
  13812. CRYPTO_cleanup_all_ex_data();
  13813. OPENSSL_REMOVE_THREAD_STATE();
  13814. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13815. pthread_mutex_destroy(&ssl_mutexes[i]);
  13816. }
  13817. mg_free(ssl_mutexes);
  13818. ssl_mutexes = NULL;
  13819. #endif /* OPENSSL_API_1_1 */
  13820. }
  13821. }
  13822. #endif /* !NO_SSL */
  13823. static int
  13824. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13825. {
  13826. if (phys_ctx) {
  13827. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13828. const char *path;
  13829. struct mg_connection fc;
  13830. if (!dom_ctx) {
  13831. dom_ctx = &(phys_ctx->dd);
  13832. }
  13833. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13834. if ((path != NULL)
  13835. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  13836. mg_cry_ctx_internal(phys_ctx,
  13837. "Cannot open %s: %s",
  13838. path,
  13839. strerror(ERRNO));
  13840. return 0;
  13841. }
  13842. return 1;
  13843. }
  13844. return 0;
  13845. }
  13846. static int
  13847. set_acl_option(struct mg_context *phys_ctx)
  13848. {
  13849. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13850. }
  13851. static void
  13852. reset_per_request_attributes(struct mg_connection *conn)
  13853. {
  13854. if (!conn) {
  13855. return;
  13856. }
  13857. conn->connection_type =
  13858. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13859. conn->num_bytes_sent = conn->consumed_content = 0;
  13860. conn->path_info = NULL;
  13861. conn->status_code = -1;
  13862. conn->content_len = -1;
  13863. conn->is_chunked = 0;
  13864. conn->must_close = 0;
  13865. conn->request_len = 0;
  13866. conn->throttle = 0;
  13867. conn->accept_gzip = 0;
  13868. conn->response_info.content_length = conn->request_info.content_length = -1;
  13869. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13870. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13871. conn->response_info.status_text = NULL;
  13872. conn->response_info.status_code = 0;
  13873. conn->request_info.remote_user = NULL;
  13874. conn->request_info.request_method = NULL;
  13875. conn->request_info.request_uri = NULL;
  13876. conn->request_info.local_uri = NULL;
  13877. #if defined(MG_LEGACY_INTERFACE)
  13878. /* Legacy before split into local_uri and request_uri */
  13879. conn->request_info.uri = NULL;
  13880. #endif
  13881. }
  13882. static int
  13883. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13884. {
  13885. if (setsockopt(sock,
  13886. IPPROTO_TCP,
  13887. TCP_NODELAY,
  13888. (SOCK_OPT_TYPE)&nodelay_on,
  13889. sizeof(nodelay_on))
  13890. != 0) {
  13891. /* Error */
  13892. return 1;
  13893. }
  13894. /* OK */
  13895. return 0;
  13896. }
  13897. static void
  13898. close_socket_gracefully(struct mg_connection *conn)
  13899. {
  13900. #if defined(_WIN32)
  13901. char buf[MG_BUF_LEN];
  13902. int n;
  13903. #endif
  13904. struct linger linger;
  13905. int error_code = 0;
  13906. int linger_timeout = -2;
  13907. socklen_t opt_len = sizeof(error_code);
  13908. if (!conn) {
  13909. return;
  13910. }
  13911. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13912. * "Note that enabling a nonzero timeout on a nonblocking socket
  13913. * is not recommended.", so set it to blocking now */
  13914. set_blocking_mode(conn->client.sock);
  13915. /* Send FIN to the client */
  13916. shutdown(conn->client.sock, SHUTDOWN_WR);
  13917. #if defined(_WIN32)
  13918. /* Read and discard pending incoming data. If we do not do that and
  13919. * close
  13920. * the socket, the data in the send buffer may be discarded. This
  13921. * behaviour is seen on Windows, when client keeps sending data
  13922. * when server decides to close the connection; then when client
  13923. * does recv() it gets no data back. */
  13924. do {
  13925. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13926. } while (n > 0);
  13927. #endif
  13928. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13929. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13930. }
  13931. /* Set linger option according to configuration */
  13932. if (linger_timeout >= 0) {
  13933. /* Set linger option to avoid socket hanging out after close. This
  13934. * prevent ephemeral port exhaust problem under high QPS. */
  13935. linger.l_onoff = 1;
  13936. #if defined(_MSC_VER)
  13937. #pragma warning(push)
  13938. #pragma warning(disable : 4244)
  13939. #endif
  13940. #if defined(GCC_DIAGNOSTIC)
  13941. #pragma GCC diagnostic push
  13942. #pragma GCC diagnostic ignored "-Wconversion"
  13943. #endif
  13944. /* Data type of linger structure elements may differ,
  13945. * so we don't know what cast we need here.
  13946. * Disable type conversion warnings. */
  13947. linger.l_linger = (linger_timeout + 999) / 1000;
  13948. #if defined(GCC_DIAGNOSTIC)
  13949. #pragma GCC diagnostic pop
  13950. #endif
  13951. #if defined(_MSC_VER)
  13952. #pragma warning(pop)
  13953. #endif
  13954. } else {
  13955. linger.l_onoff = 0;
  13956. linger.l_linger = 0;
  13957. }
  13958. if (linger_timeout < -1) {
  13959. /* Default: don't configure any linger */
  13960. } else if (getsockopt(conn->client.sock,
  13961. SOL_SOCKET,
  13962. SO_ERROR,
  13963. #if defined(_WIN32) /* WinSock uses different data type here */
  13964. (char *)&error_code,
  13965. #else
  13966. &error_code,
  13967. #endif
  13968. &opt_len)
  13969. != 0) {
  13970. /* Cannot determine if socket is already closed. This should
  13971. * not occur and never did in a test. Log an error message
  13972. * and continue. */
  13973. mg_cry_internal(conn,
  13974. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  13975. __func__,
  13976. strerror(ERRNO));
  13977. #if defined(_WIN32)
  13978. } else if (error_code == WSAECONNRESET) {
  13979. #else
  13980. } else if (error_code == ECONNRESET) {
  13981. #endif
  13982. /* Socket already closed by client/peer, close socket without linger
  13983. */
  13984. } else {
  13985. /* Set linger timeout */
  13986. if (setsockopt(conn->client.sock,
  13987. SOL_SOCKET,
  13988. SO_LINGER,
  13989. (char *)&linger,
  13990. sizeof(linger))
  13991. != 0) {
  13992. mg_cry_internal(
  13993. conn,
  13994. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  13995. __func__,
  13996. linger.l_onoff,
  13997. linger.l_linger,
  13998. strerror(ERRNO));
  13999. }
  14000. }
  14001. /* Now we know that our FIN is ACK-ed, safe to close */
  14002. closesocket(conn->client.sock);
  14003. conn->client.sock = INVALID_SOCKET;
  14004. }
  14005. static void
  14006. close_connection(struct mg_connection *conn)
  14007. {
  14008. #if defined(USE_SERVER_STATS)
  14009. conn->conn_state = 6; /* to close */
  14010. #endif
  14011. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14012. if (conn->lua_websocket_state) {
  14013. lua_websocket_close(conn, conn->lua_websocket_state);
  14014. conn->lua_websocket_state = NULL;
  14015. }
  14016. #endif
  14017. mg_lock_connection(conn);
  14018. /* Set close flag, so keep-alive loops will stop */
  14019. conn->must_close = 1;
  14020. /* call the connection_close callback if assigned */
  14021. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14022. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14023. conn->phys_ctx->callbacks.connection_close(conn);
  14024. }
  14025. }
  14026. /* Reset user data, after close callback is called.
  14027. * Do not reuse it. If the user needs a destructor,
  14028. * it must be done in the connection_close callback. */
  14029. mg_set_user_connection_data(conn, NULL);
  14030. #if defined(USE_SERVER_STATS)
  14031. conn->conn_state = 7; /* closing */
  14032. #endif
  14033. #if !defined(NO_SSL)
  14034. if (conn->ssl != NULL) {
  14035. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14036. */
  14037. SSL_shutdown(conn->ssl);
  14038. SSL_free(conn->ssl);
  14039. OPENSSL_REMOVE_THREAD_STATE();
  14040. conn->ssl = NULL;
  14041. }
  14042. #endif
  14043. if (conn->client.sock != INVALID_SOCKET) {
  14044. close_socket_gracefully(conn);
  14045. conn->client.sock = INVALID_SOCKET;
  14046. }
  14047. if (conn->host) {
  14048. mg_free((void *)conn->host);
  14049. conn->host = NULL;
  14050. }
  14051. mg_unlock_connection(conn);
  14052. #if defined(USE_SERVER_STATS)
  14053. conn->conn_state = 8; /* closed */
  14054. #endif
  14055. }
  14056. void
  14057. mg_close_connection(struct mg_connection *conn)
  14058. {
  14059. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14060. return;
  14061. }
  14062. #if defined(USE_WEBSOCKET)
  14063. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14064. if (conn->in_websocket_handling) {
  14065. /* Set close flag, so the server thread can exit. */
  14066. conn->must_close = 1;
  14067. return;
  14068. }
  14069. }
  14070. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14071. unsigned int i;
  14072. /* client context: loops must end */
  14073. conn->phys_ctx->stop_flag = 1;
  14074. conn->must_close = 1;
  14075. /* We need to get the client thread out of the select/recv call
  14076. * here. */
  14077. /* Since we use a sleep quantum of some seconds to check for recv
  14078. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14079. /* join worker thread */
  14080. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14081. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14082. }
  14083. }
  14084. #endif /* defined(USE_WEBSOCKET) */
  14085. close_connection(conn);
  14086. #if !defined(NO_SSL)
  14087. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14088. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14089. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14090. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14091. }
  14092. #endif
  14093. #if defined(USE_WEBSOCKET)
  14094. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14095. mg_free(conn->phys_ctx->worker_threadids);
  14096. (void)pthread_mutex_destroy(&conn->mutex);
  14097. mg_free(conn);
  14098. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14099. mg_free(conn);
  14100. }
  14101. #else
  14102. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14103. mg_free(conn);
  14104. }
  14105. #endif /* defined(USE_WEBSOCKET) */
  14106. }
  14107. static struct mg_connection *
  14108. mg_connect_client_impl(const struct mg_client_options *client_options,
  14109. int use_ssl,
  14110. char *ebuf,
  14111. size_t ebuf_len)
  14112. {
  14113. struct mg_connection *conn = NULL;
  14114. SOCKET sock;
  14115. union usa sa;
  14116. struct sockaddr *psa;
  14117. socklen_t len;
  14118. unsigned max_req_size =
  14119. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14120. /* Size of structures, aligned to 8 bytes */
  14121. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14122. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14123. conn = (struct mg_connection *)mg_calloc(
  14124. 1, conn_size + ctx_size + max_req_size);
  14125. if (conn == NULL) {
  14126. mg_snprintf(NULL,
  14127. NULL, /* No truncation check for ebuf */
  14128. ebuf,
  14129. ebuf_len,
  14130. "calloc(): %s",
  14131. strerror(ERRNO));
  14132. return NULL;
  14133. }
  14134. #if defined(GCC_DIAGNOSTIC)
  14135. #pragma GCC diagnostic push
  14136. #pragma GCC diagnostic ignored "-Wcast-align"
  14137. #endif /* defined(GCC_DIAGNOSTIC) */
  14138. /* conn_size is aligned to 8 bytes */
  14139. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14140. #if defined(GCC_DIAGNOSTIC)
  14141. #pragma GCC diagnostic pop
  14142. #endif /* defined(GCC_DIAGNOSTIC) */
  14143. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14144. conn->buf_size = (int)max_req_size;
  14145. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14146. conn->dom_ctx = &(conn->phys_ctx->dd);
  14147. if (!connect_socket(conn->phys_ctx,
  14148. client_options->host,
  14149. client_options->port,
  14150. use_ssl,
  14151. ebuf,
  14152. ebuf_len,
  14153. &sock,
  14154. &sa)) {
  14155. /* ebuf is set by connect_socket,
  14156. * free all memory and return NULL; */
  14157. mg_free(conn);
  14158. return NULL;
  14159. }
  14160. #if !defined(NO_SSL)
  14161. #if defined(OPENSSL_API_1_1)
  14162. if (use_ssl
  14163. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14164. == NULL) {
  14165. mg_snprintf(NULL,
  14166. NULL, /* No truncation check for ebuf */
  14167. ebuf,
  14168. ebuf_len,
  14169. "SSL_CTX_new error: %s",
  14170. ssl_error());
  14171. closesocket(sock);
  14172. mg_free(conn);
  14173. return NULL;
  14174. }
  14175. #else
  14176. if (use_ssl
  14177. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14178. == NULL) {
  14179. mg_snprintf(NULL,
  14180. NULL, /* No truncation check for ebuf */
  14181. ebuf,
  14182. ebuf_len,
  14183. "SSL_CTX_new error: %s",
  14184. ssl_error());
  14185. closesocket(sock);
  14186. mg_free(conn);
  14187. return NULL;
  14188. }
  14189. #endif /* OPENSSL_API_1_1 */
  14190. #endif /* NO_SSL */
  14191. #if defined(USE_IPV6)
  14192. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14193. : sizeof(conn->client.rsa.sin6);
  14194. psa = (sa.sa.sa_family == AF_INET)
  14195. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14196. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14197. #else
  14198. len = sizeof(conn->client.rsa.sin);
  14199. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14200. #endif
  14201. conn->client.sock = sock;
  14202. conn->client.lsa = sa;
  14203. if (getsockname(sock, psa, &len) != 0) {
  14204. mg_cry_internal(conn,
  14205. "%s: getsockname() failed: %s",
  14206. __func__,
  14207. strerror(ERRNO));
  14208. }
  14209. conn->client.is_ssl = use_ssl ? 1 : 0;
  14210. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14211. mg_snprintf(NULL,
  14212. NULL, /* No truncation check for ebuf */
  14213. ebuf,
  14214. ebuf_len,
  14215. "Can not create mutex");
  14216. #if !defined(NO_SSL)
  14217. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14218. #endif
  14219. closesocket(sock);
  14220. mg_free(conn);
  14221. return NULL;
  14222. }
  14223. #if !defined(NO_SSL)
  14224. if (use_ssl) {
  14225. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14226. * SSL_CTX_set_verify call is needed to switch off server
  14227. * certificate checking, which is off by default in OpenSSL and
  14228. * on in yaSSL. */
  14229. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14230. * SSL_VERIFY_PEER, verify_ssl_server); */
  14231. if (client_options->client_cert) {
  14232. if (!ssl_use_pem_file(conn->phys_ctx,
  14233. conn->dom_ctx,
  14234. client_options->client_cert,
  14235. NULL)) {
  14236. mg_snprintf(NULL,
  14237. NULL, /* No truncation check for ebuf */
  14238. ebuf,
  14239. ebuf_len,
  14240. "Can not use SSL client certificate");
  14241. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14242. closesocket(sock);
  14243. mg_free(conn);
  14244. return NULL;
  14245. }
  14246. }
  14247. if (client_options->server_cert) {
  14248. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14249. client_options->server_cert,
  14250. NULL)
  14251. != 1) {
  14252. mg_cry_internal(conn,
  14253. "SSL_CTX_load_verify_locations error: %s ",
  14254. ssl_error());
  14255. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14256. closesocket(sock);
  14257. mg_free(conn);
  14258. return NULL;
  14259. }
  14260. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14261. } else {
  14262. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14263. }
  14264. if (!sslize(conn,
  14265. conn->dom_ctx->ssl_ctx,
  14266. SSL_connect,
  14267. &(conn->phys_ctx->stop_flag),
  14268. client_options)) {
  14269. mg_snprintf(NULL,
  14270. NULL, /* No truncation check for ebuf */
  14271. ebuf,
  14272. ebuf_len,
  14273. "SSL connection error");
  14274. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14275. closesocket(sock);
  14276. mg_free(conn);
  14277. return NULL;
  14278. }
  14279. }
  14280. #endif
  14281. return conn;
  14282. }
  14283. CIVETWEB_API struct mg_connection *
  14284. mg_connect_client_secure(const struct mg_client_options *client_options,
  14285. char *error_buffer,
  14286. size_t error_buffer_size)
  14287. {
  14288. return mg_connect_client_impl(client_options,
  14289. 1,
  14290. error_buffer,
  14291. error_buffer_size);
  14292. }
  14293. struct mg_connection *
  14294. mg_connect_client(const char *host,
  14295. int port,
  14296. int use_ssl,
  14297. char *error_buffer,
  14298. size_t error_buffer_size)
  14299. {
  14300. struct mg_client_options opts;
  14301. memset(&opts, 0, sizeof(opts));
  14302. opts.host = host;
  14303. opts.port = port;
  14304. return mg_connect_client_impl(&opts,
  14305. use_ssl,
  14306. error_buffer,
  14307. error_buffer_size);
  14308. }
  14309. static const struct {
  14310. const char *proto;
  14311. size_t proto_len;
  14312. unsigned default_port;
  14313. } abs_uri_protocols[] = {{"http://", 7, 80},
  14314. {"https://", 8, 443},
  14315. {"ws://", 5, 80},
  14316. {"wss://", 6, 443},
  14317. {NULL, 0, 0}};
  14318. /* Check if the uri is valid.
  14319. * return 0 for invalid uri,
  14320. * return 1 for *,
  14321. * return 2 for relative uri,
  14322. * return 3 for absolute uri without port,
  14323. * return 4 for absolute uri with port */
  14324. static int
  14325. get_uri_type(const char *uri)
  14326. {
  14327. int i;
  14328. const char *hostend, *portbegin;
  14329. char *portend;
  14330. unsigned long port;
  14331. /* According to the HTTP standard
  14332. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14333. * URI can be an asterisk (*) or should start with slash (relative uri),
  14334. * or it should start with the protocol (absolute uri). */
  14335. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14336. /* asterisk */
  14337. return 1;
  14338. }
  14339. /* Valid URIs according to RFC 3986
  14340. * (https://www.ietf.org/rfc/rfc3986.txt)
  14341. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14342. * and unreserved characters A-Z a-z 0-9 and -._~
  14343. * and % encoded symbols.
  14344. */
  14345. for (i = 0; uri[i] != 0; i++) {
  14346. if (uri[i] < 33) {
  14347. /* control characters and spaces are invalid */
  14348. return 0;
  14349. }
  14350. if (uri[i] > 126) {
  14351. /* non-ascii characters must be % encoded */
  14352. return 0;
  14353. } else {
  14354. switch (uri[i]) {
  14355. case '"': /* 34 */
  14356. case '<': /* 60 */
  14357. case '>': /* 62 */
  14358. case '\\': /* 92 */
  14359. case '^': /* 94 */
  14360. case '`': /* 96 */
  14361. case '{': /* 123 */
  14362. case '|': /* 124 */
  14363. case '}': /* 125 */
  14364. return 0;
  14365. default:
  14366. /* character is ok */
  14367. break;
  14368. }
  14369. }
  14370. }
  14371. /* A relative uri starts with a / character */
  14372. if (uri[0] == '/') {
  14373. /* relative uri */
  14374. return 2;
  14375. }
  14376. /* It could be an absolute uri: */
  14377. /* This function only checks if the uri is valid, not if it is
  14378. * addressing the current server. So civetweb can also be used
  14379. * as a proxy server. */
  14380. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14381. if (mg_strncasecmp(uri,
  14382. abs_uri_protocols[i].proto,
  14383. abs_uri_protocols[i].proto_len)
  14384. == 0) {
  14385. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14386. if (!hostend) {
  14387. return 0;
  14388. }
  14389. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14390. if (!portbegin) {
  14391. return 3;
  14392. }
  14393. port = strtoul(portbegin + 1, &portend, 10);
  14394. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14395. return 0;
  14396. }
  14397. return 4;
  14398. }
  14399. }
  14400. return 0;
  14401. }
  14402. /* Return NULL or the relative uri at the current server */
  14403. static const char *
  14404. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14405. {
  14406. const char *server_domain;
  14407. size_t server_domain_len;
  14408. size_t request_domain_len = 0;
  14409. unsigned long port = 0;
  14410. int i, auth_domain_check_enabled;
  14411. const char *hostbegin = NULL;
  14412. const char *hostend = NULL;
  14413. const char *portbegin;
  14414. char *portend;
  14415. auth_domain_check_enabled =
  14416. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14417. /* DNS is case insensitive, so use case insensitive string compare here
  14418. */
  14419. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14420. if (mg_strncasecmp(uri,
  14421. abs_uri_protocols[i].proto,
  14422. abs_uri_protocols[i].proto_len)
  14423. == 0) {
  14424. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14425. hostend = strchr(hostbegin, '/');
  14426. if (!hostend) {
  14427. return 0;
  14428. }
  14429. portbegin = strchr(hostbegin, ':');
  14430. if ((!portbegin) || (portbegin > hostend)) {
  14431. port = abs_uri_protocols[i].default_port;
  14432. request_domain_len = (size_t)(hostend - hostbegin);
  14433. } else {
  14434. port = strtoul(portbegin + 1, &portend, 10);
  14435. if ((portend != hostend) || (port <= 0)
  14436. || !is_valid_port(port)) {
  14437. return 0;
  14438. }
  14439. request_domain_len = (size_t)(portbegin - hostbegin);
  14440. }
  14441. /* protocol found, port set */
  14442. break;
  14443. }
  14444. }
  14445. if (!port) {
  14446. /* port remains 0 if the protocol is not found */
  14447. return 0;
  14448. }
  14449. /* Check if the request is directed to a different server. */
  14450. /* First check if the port is the same (IPv4 and IPv6). */
  14451. #if defined(USE_IPV6)
  14452. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14453. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14454. /* Request is directed to a different port */
  14455. return 0;
  14456. }
  14457. } else
  14458. #endif
  14459. {
  14460. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14461. /* Request is directed to a different port */
  14462. return 0;
  14463. }
  14464. }
  14465. /* Finally check if the server corresponds to the authentication
  14466. * domain of the server (the server domain).
  14467. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14468. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14469. * but do not allow substrings (like
  14470. * http://notmydomain.com/path/file.ext
  14471. * or http://mydomain.com.fake/path/file.ext).
  14472. */
  14473. if (auth_domain_check_enabled) {
  14474. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14475. server_domain_len = strlen(server_domain);
  14476. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14477. return 0;
  14478. }
  14479. if ((request_domain_len == server_domain_len)
  14480. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14481. /* Request is directed to this server - full name match. */
  14482. } else {
  14483. if (request_domain_len < (server_domain_len + 2)) {
  14484. /* Request is directed to another server: The server name
  14485. * is longer than the request name.
  14486. * Drop this case here to avoid overflows in the
  14487. * following checks. */
  14488. return 0;
  14489. }
  14490. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14491. /* Request is directed to another server: It could be a
  14492. * substring
  14493. * like notmyserver.com */
  14494. return 0;
  14495. }
  14496. if (0
  14497. != memcmp(server_domain,
  14498. hostbegin + request_domain_len - server_domain_len,
  14499. server_domain_len)) {
  14500. /* Request is directed to another server:
  14501. * The server name is different. */
  14502. return 0;
  14503. }
  14504. }
  14505. }
  14506. return hostend;
  14507. }
  14508. static int
  14509. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14510. {
  14511. if (ebuf_len > 0) {
  14512. ebuf[0] = '\0';
  14513. }
  14514. *err = 0;
  14515. reset_per_request_attributes(conn);
  14516. if (!conn) {
  14517. mg_snprintf(conn,
  14518. NULL, /* No truncation check for ebuf */
  14519. ebuf,
  14520. ebuf_len,
  14521. "%s",
  14522. "Internal error");
  14523. *err = 500;
  14524. return 0;
  14525. }
  14526. /* Set the time the request was received. This value should be used for
  14527. * timeouts. */
  14528. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14529. conn->request_len =
  14530. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14531. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14532. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14533. mg_snprintf(conn,
  14534. NULL, /* No truncation check for ebuf */
  14535. ebuf,
  14536. ebuf_len,
  14537. "%s",
  14538. "Invalid message size");
  14539. *err = 500;
  14540. return 0;
  14541. }
  14542. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14543. mg_snprintf(conn,
  14544. NULL, /* No truncation check for ebuf */
  14545. ebuf,
  14546. ebuf_len,
  14547. "%s",
  14548. "Message too large");
  14549. *err = 413;
  14550. return 0;
  14551. }
  14552. if (conn->request_len <= 0) {
  14553. if (conn->data_len > 0) {
  14554. mg_snprintf(conn,
  14555. NULL, /* No truncation check for ebuf */
  14556. ebuf,
  14557. ebuf_len,
  14558. "%s",
  14559. "Malformed message");
  14560. *err = 400;
  14561. } else {
  14562. /* Server did not recv anything -> just close the connection */
  14563. conn->must_close = 1;
  14564. mg_snprintf(conn,
  14565. NULL, /* No truncation check for ebuf */
  14566. ebuf,
  14567. ebuf_len,
  14568. "%s",
  14569. "No data received");
  14570. *err = 0;
  14571. }
  14572. return 0;
  14573. }
  14574. return 1;
  14575. }
  14576. static int
  14577. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14578. {
  14579. const char *cl;
  14580. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14581. return 0;
  14582. }
  14583. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14584. <= 0) {
  14585. mg_snprintf(conn,
  14586. NULL, /* No truncation check for ebuf */
  14587. ebuf,
  14588. ebuf_len,
  14589. "%s",
  14590. "Bad request");
  14591. *err = 400;
  14592. return 0;
  14593. }
  14594. /* Message is a valid request */
  14595. /* Is there a "host" ? */
  14596. if (conn->host != NULL) {
  14597. mg_free((void *)conn->host);
  14598. }
  14599. conn->host = alloc_get_host(conn);
  14600. if (!conn->host) {
  14601. mg_snprintf(conn,
  14602. NULL, /* No truncation check for ebuf */
  14603. ebuf,
  14604. ebuf_len,
  14605. "%s",
  14606. "Bad request: Host mismatch");
  14607. *err = 400;
  14608. return 0;
  14609. }
  14610. if (((cl = get_header(conn->request_info.http_headers,
  14611. conn->request_info.num_headers,
  14612. "Transfer-Encoding")) != NULL)
  14613. && mg_strcasecmp(cl, "identity")) {
  14614. if (mg_strcasecmp(cl, "chunked")) {
  14615. mg_snprintf(conn,
  14616. NULL, /* No truncation check for ebuf */
  14617. ebuf,
  14618. ebuf_len,
  14619. "%s",
  14620. "Bad request");
  14621. *err = 400;
  14622. return 0;
  14623. }
  14624. conn->is_chunked = 1;
  14625. conn->content_len = 0; /* not yet read */
  14626. } else if ((cl = get_header(conn->request_info.http_headers,
  14627. conn->request_info.num_headers,
  14628. "Content-Length")) != NULL) {
  14629. /* Request has content length set */
  14630. char *endptr = NULL;
  14631. conn->content_len = strtoll(cl, &endptr, 10);
  14632. if ((endptr == cl) || (conn->content_len < 0)) {
  14633. mg_snprintf(conn,
  14634. NULL, /* No truncation check for ebuf */
  14635. ebuf,
  14636. ebuf_len,
  14637. "%s",
  14638. "Bad request");
  14639. *err = 411;
  14640. return 0;
  14641. }
  14642. /* Publish the content length back to the request info. */
  14643. conn->request_info.content_length = conn->content_len;
  14644. } else {
  14645. /* There is no exception, see RFC7230. */
  14646. conn->content_len = 0;
  14647. }
  14648. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14649. return 1;
  14650. }
  14651. /* conn is assumed to be valid in this internal function */
  14652. static int
  14653. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14654. {
  14655. const char *cl;
  14656. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14657. return 0;
  14658. }
  14659. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14660. <= 0) {
  14661. mg_snprintf(conn,
  14662. NULL, /* No truncation check for ebuf */
  14663. ebuf,
  14664. ebuf_len,
  14665. "%s",
  14666. "Bad response");
  14667. *err = 400;
  14668. return 0;
  14669. }
  14670. /* Message is a valid response */
  14671. if (((cl = get_header(conn->response_info.http_headers,
  14672. conn->response_info.num_headers,
  14673. "Transfer-Encoding")) != NULL)
  14674. && mg_strcasecmp(cl, "identity")) {
  14675. if (mg_strcasecmp(cl, "chunked")) {
  14676. mg_snprintf(conn,
  14677. NULL, /* No truncation check for ebuf */
  14678. ebuf,
  14679. ebuf_len,
  14680. "%s",
  14681. "Bad request");
  14682. *err = 400;
  14683. return 0;
  14684. }
  14685. conn->is_chunked = 1;
  14686. conn->content_len = 0; /* not yet read */
  14687. } else if ((cl = get_header(conn->response_info.http_headers,
  14688. conn->response_info.num_headers,
  14689. "Content-Length")) != NULL) {
  14690. char *endptr = NULL;
  14691. conn->content_len = strtoll(cl, &endptr, 10);
  14692. if ((endptr == cl) || (conn->content_len < 0)) {
  14693. mg_snprintf(conn,
  14694. NULL, /* No truncation check for ebuf */
  14695. ebuf,
  14696. ebuf_len,
  14697. "%s",
  14698. "Bad request");
  14699. *err = 411;
  14700. return 0;
  14701. }
  14702. /* Publish the content length back to the response info. */
  14703. conn->response_info.content_length = conn->content_len;
  14704. /* TODO: check if it is still used in response_info */
  14705. conn->request_info.content_length = conn->content_len;
  14706. /* TODO: we should also consider HEAD method */
  14707. if (conn->response_info.status_code == 304) {
  14708. conn->content_len = 0;
  14709. }
  14710. } else {
  14711. /* TODO: we should also consider HEAD method */
  14712. if (((conn->response_info.status_code >= 100)
  14713. && (conn->response_info.status_code <= 199))
  14714. || (conn->response_info.status_code == 204)
  14715. || (conn->response_info.status_code == 304)) {
  14716. conn->content_len = 0;
  14717. } else {
  14718. conn->content_len = -1; /* unknown content length */
  14719. }
  14720. }
  14721. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14722. return 1;
  14723. }
  14724. int
  14725. mg_get_response(struct mg_connection *conn,
  14726. char *ebuf,
  14727. size_t ebuf_len,
  14728. int timeout)
  14729. {
  14730. int err, ret;
  14731. char txt[32]; /* will not overflow */
  14732. char *save_timeout;
  14733. char *new_timeout;
  14734. if (ebuf_len > 0) {
  14735. ebuf[0] = '\0';
  14736. }
  14737. if (!conn) {
  14738. mg_snprintf(conn,
  14739. NULL, /* No truncation check for ebuf */
  14740. ebuf,
  14741. ebuf_len,
  14742. "%s",
  14743. "Parameter error");
  14744. return -1;
  14745. }
  14746. /* Reset the previous responses */
  14747. conn->data_len = 0;
  14748. /* Implementation of API function for HTTP clients */
  14749. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14750. if (timeout >= 0) {
  14751. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14752. new_timeout = txt;
  14753. } else {
  14754. new_timeout = NULL;
  14755. }
  14756. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14757. ret = get_response(conn, ebuf, ebuf_len, &err);
  14758. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14759. #if defined(MG_LEGACY_INTERFACE)
  14760. /* TODO: 1) uri is deprecated;
  14761. * 2) here, ri.uri is the http response code */
  14762. conn->request_info.uri = conn->request_info.request_uri;
  14763. #endif
  14764. conn->request_info.local_uri = conn->request_info.request_uri;
  14765. /* TODO (mid): Define proper return values - maybe return length?
  14766. * For the first test use <0 for error and >0 for OK */
  14767. return (ret == 0) ? -1 : +1;
  14768. }
  14769. struct mg_connection *
  14770. mg_download(const char *host,
  14771. int port,
  14772. int use_ssl,
  14773. char *ebuf,
  14774. size_t ebuf_len,
  14775. const char *fmt,
  14776. ...)
  14777. {
  14778. struct mg_connection *conn;
  14779. va_list ap;
  14780. int i;
  14781. int reqerr;
  14782. if (ebuf_len > 0) {
  14783. ebuf[0] = '\0';
  14784. }
  14785. va_start(ap, fmt);
  14786. /* open a connection */
  14787. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14788. if (conn != NULL) {
  14789. i = mg_vprintf(conn, fmt, ap);
  14790. if (i <= 0) {
  14791. mg_snprintf(conn,
  14792. NULL, /* No truncation check for ebuf */
  14793. ebuf,
  14794. ebuf_len,
  14795. "%s",
  14796. "Error sending request");
  14797. } else {
  14798. /* make sure the buffer is clear */
  14799. conn->data_len = 0;
  14800. get_response(conn, ebuf, ebuf_len, &reqerr);
  14801. #if defined(MG_LEGACY_INTERFACE)
  14802. /* TODO: 1) uri is deprecated;
  14803. * 2) here, ri.uri is the http response code */
  14804. conn->request_info.uri = conn->request_info.request_uri;
  14805. #endif
  14806. conn->request_info.local_uri = conn->request_info.request_uri;
  14807. }
  14808. }
  14809. /* if an error occurred, close the connection */
  14810. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14811. mg_close_connection(conn);
  14812. conn = NULL;
  14813. }
  14814. va_end(ap);
  14815. return conn;
  14816. }
  14817. struct websocket_client_thread_data {
  14818. struct mg_connection *conn;
  14819. mg_websocket_data_handler data_handler;
  14820. mg_websocket_close_handler close_handler;
  14821. void *callback_data;
  14822. };
  14823. #if defined(USE_WEBSOCKET)
  14824. #if defined(_WIN32)
  14825. static unsigned __stdcall websocket_client_thread(void *data)
  14826. #else
  14827. static void *
  14828. websocket_client_thread(void *data)
  14829. #endif
  14830. {
  14831. struct websocket_client_thread_data *cdata =
  14832. (struct websocket_client_thread_data *)data;
  14833. void *user_thread_ptr = NULL;
  14834. #if !defined(_WIN32)
  14835. struct sigaction sa;
  14836. /* Ignore SIGPIPE */
  14837. memset(&sa, 0, sizeof(sa));
  14838. sa.sa_handler = SIG_IGN;
  14839. sigaction(SIGPIPE, &sa, NULL);
  14840. #endif
  14841. mg_set_thread_name("ws-clnt");
  14842. if (cdata->conn->phys_ctx) {
  14843. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14844. /* 3 indicates a websocket client thread */
  14845. /* TODO: check if conn->phys_ctx can be set */
  14846. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  14847. cdata->conn->phys_ctx, 3);
  14848. }
  14849. }
  14850. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14851. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14852. if (cdata->close_handler != NULL) {
  14853. cdata->close_handler(cdata->conn, cdata->callback_data);
  14854. }
  14855. /* The websocket_client context has only this thread. If it runs out,
  14856. set the stop_flag to 2 (= "stopped"). */
  14857. cdata->conn->phys_ctx->stop_flag = 2;
  14858. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  14859. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  14860. 3,
  14861. user_thread_ptr);
  14862. }
  14863. mg_free((void *)cdata);
  14864. #if defined(_WIN32)
  14865. return 0;
  14866. #else
  14867. return NULL;
  14868. #endif
  14869. }
  14870. #endif
  14871. struct mg_connection *
  14872. mg_connect_websocket_client(const char *host,
  14873. int port,
  14874. int use_ssl,
  14875. char *error_buffer,
  14876. size_t error_buffer_size,
  14877. const char *path,
  14878. const char *origin,
  14879. mg_websocket_data_handler data_func,
  14880. mg_websocket_close_handler close_func,
  14881. void *user_data)
  14882. {
  14883. struct mg_connection *conn = NULL;
  14884. #if defined(USE_WEBSOCKET)
  14885. struct websocket_client_thread_data *thread_data;
  14886. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14887. static const char *handshake_req;
  14888. if (origin != NULL) {
  14889. handshake_req = "GET %s HTTP/1.1\r\n"
  14890. "Host: %s\r\n"
  14891. "Upgrade: websocket\r\n"
  14892. "Connection: Upgrade\r\n"
  14893. "Sec-WebSocket-Key: %s\r\n"
  14894. "Sec-WebSocket-Version: 13\r\n"
  14895. "Origin: %s\r\n"
  14896. "\r\n";
  14897. } else {
  14898. handshake_req = "GET %s HTTP/1.1\r\n"
  14899. "Host: %s\r\n"
  14900. "Upgrade: websocket\r\n"
  14901. "Connection: Upgrade\r\n"
  14902. "Sec-WebSocket-Key: %s\r\n"
  14903. "Sec-WebSocket-Version: 13\r\n"
  14904. "\r\n";
  14905. }
  14906. #if defined(__clang__)
  14907. #pragma clang diagnostic push
  14908. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  14909. #endif
  14910. /* Establish the client connection and request upgrade */
  14911. conn = mg_download(host,
  14912. port,
  14913. use_ssl,
  14914. error_buffer,
  14915. error_buffer_size,
  14916. handshake_req,
  14917. path,
  14918. host,
  14919. magic,
  14920. origin);
  14921. #if defined(__clang__)
  14922. #pragma clang diagnostic pop
  14923. #endif
  14924. /* Connection object will be null if something goes wrong */
  14925. if (conn == NULL) {
  14926. if (!*error_buffer) {
  14927. /* There should be already an error message */
  14928. mg_snprintf(conn,
  14929. NULL, /* No truncation check for ebuf */
  14930. error_buffer,
  14931. error_buffer_size,
  14932. "Unexpected error");
  14933. }
  14934. return NULL;
  14935. }
  14936. if (conn->response_info.status_code != 101) {
  14937. /* We sent an "upgrade" request. For a correct websocket
  14938. * protocol handshake, we expect a "101 Continue" response.
  14939. * Otherwise it is a protocol violation. Maybe the HTTP
  14940. * Server does not know websockets. */
  14941. if (!*error_buffer) {
  14942. /* set an error, if not yet set */
  14943. mg_snprintf(conn,
  14944. NULL, /* No truncation check for ebuf */
  14945. error_buffer,
  14946. error_buffer_size,
  14947. "Unexpected server reply");
  14948. }
  14949. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14950. mg_close_connection(conn);
  14951. return NULL;
  14952. }
  14953. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  14954. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  14955. if (!thread_data) {
  14956. DEBUG_TRACE("%s\r\n", "Out of memory");
  14957. mg_close_connection(conn);
  14958. return NULL;
  14959. }
  14960. thread_data->conn = conn;
  14961. thread_data->data_handler = data_func;
  14962. thread_data->close_handler = close_func;
  14963. thread_data->callback_data = user_data;
  14964. conn->phys_ctx->worker_threadids =
  14965. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  14966. if (!conn->phys_ctx->worker_threadids) {
  14967. DEBUG_TRACE("%s\r\n", "Out of memory");
  14968. mg_free(thread_data);
  14969. mg_close_connection(conn);
  14970. return NULL;
  14971. }
  14972. /* Now upgrade to ws/wss client context */
  14973. conn->phys_ctx->user_data = user_data;
  14974. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  14975. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  14976. /* Start a thread to read the websocket client connection
  14977. * This thread will automatically stop when mg_disconnect is
  14978. * called on the client connection */
  14979. if (mg_start_thread_with_id(websocket_client_thread,
  14980. thread_data,
  14981. conn->phys_ctx->worker_threadids)
  14982. != 0) {
  14983. conn->phys_ctx->cfg_worker_threads = 0;
  14984. mg_free(thread_data);
  14985. mg_close_connection(conn);
  14986. conn = NULL;
  14987. DEBUG_TRACE("%s",
  14988. "Websocket client connect thread could not be started\r\n");
  14989. }
  14990. #else
  14991. /* Appease "unused parameter" warnings */
  14992. (void)host;
  14993. (void)port;
  14994. (void)use_ssl;
  14995. (void)error_buffer;
  14996. (void)error_buffer_size;
  14997. (void)path;
  14998. (void)origin;
  14999. (void)user_data;
  15000. (void)data_func;
  15001. (void)close_func;
  15002. #endif
  15003. return conn;
  15004. }
  15005. /* Prepare connection data structure */
  15006. static void
  15007. init_connection(struct mg_connection *conn)
  15008. {
  15009. /* Is keep alive allowed by the server */
  15010. int keep_alive_enabled =
  15011. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15012. if (!keep_alive_enabled) {
  15013. conn->must_close = 1;
  15014. }
  15015. /* Important: on new connection, reset the receiving buffer. Credit
  15016. * goes to crule42. */
  15017. conn->data_len = 0;
  15018. conn->handled_requests = 0;
  15019. mg_set_user_connection_data(conn, NULL);
  15020. #if defined(USE_SERVER_STATS)
  15021. conn->conn_state = 2; /* init */
  15022. #endif
  15023. /* call the init_connection callback if assigned */
  15024. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15025. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15026. void *conn_data = NULL;
  15027. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15028. mg_set_user_connection_data(conn, conn_data);
  15029. }
  15030. }
  15031. }
  15032. /* Process a connection - may handle multiple requests
  15033. * using the same connection.
  15034. * Must be called with a valid connection (conn and
  15035. * conn->phys_ctx must be valid).
  15036. */
  15037. static void
  15038. process_new_connection(struct mg_connection *conn)
  15039. {
  15040. struct mg_request_info *ri = &conn->request_info;
  15041. int keep_alive, discard_len;
  15042. char ebuf[100];
  15043. const char *hostend;
  15044. int reqerr, uri_type;
  15045. #if defined(USE_SERVER_STATS)
  15046. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15047. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15048. if (mcon > (conn->phys_ctx->max_connections)) {
  15049. /* could use atomic compare exchange, but this
  15050. * seems overkill for statistics data */
  15051. conn->phys_ctx->max_connections = mcon;
  15052. }
  15053. #endif
  15054. init_connection(conn);
  15055. DEBUG_TRACE("Start processing connection from %s",
  15056. conn->request_info.remote_addr);
  15057. /* Loop over multiple requests sent using the same connection
  15058. * (while "keep alive"). */
  15059. do {
  15060. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15061. conn->handled_requests + 1);
  15062. #if defined(USE_SERVER_STATS)
  15063. conn->conn_state = 3; /* ready */
  15064. #endif
  15065. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15066. /* The request sent by the client could not be understood by
  15067. * the server, or it was incomplete or a timeout. Send an
  15068. * error message and close the connection. */
  15069. if (reqerr > 0) {
  15070. DEBUG_ASSERT(ebuf[0] != '\0');
  15071. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15072. }
  15073. } else if (strcmp(ri->http_version, "1.0")
  15074. && strcmp(ri->http_version, "1.1")) {
  15075. mg_snprintf(conn,
  15076. NULL, /* No truncation check for ebuf */
  15077. ebuf,
  15078. sizeof(ebuf),
  15079. "Bad HTTP version: [%s]",
  15080. ri->http_version);
  15081. mg_send_http_error(conn, 505, "%s", ebuf);
  15082. }
  15083. if (ebuf[0] == '\0') {
  15084. uri_type = get_uri_type(conn->request_info.request_uri);
  15085. switch (uri_type) {
  15086. case 1:
  15087. /* Asterisk */
  15088. conn->request_info.local_uri = NULL;
  15089. break;
  15090. case 2:
  15091. /* relative uri */
  15092. conn->request_info.local_uri = conn->request_info.request_uri;
  15093. break;
  15094. case 3:
  15095. case 4:
  15096. /* absolute uri (with/without port) */
  15097. hostend = get_rel_url_at_current_server(
  15098. conn->request_info.request_uri, conn);
  15099. if (hostend) {
  15100. conn->request_info.local_uri = hostend;
  15101. } else {
  15102. conn->request_info.local_uri = NULL;
  15103. }
  15104. break;
  15105. default:
  15106. mg_snprintf(conn,
  15107. NULL, /* No truncation check for ebuf */
  15108. ebuf,
  15109. sizeof(ebuf),
  15110. "Invalid URI");
  15111. mg_send_http_error(conn, 400, "%s", ebuf);
  15112. conn->request_info.local_uri = NULL;
  15113. break;
  15114. }
  15115. #if defined(MG_LEGACY_INTERFACE)
  15116. /* Legacy before split into local_uri and request_uri */
  15117. conn->request_info.uri = conn->request_info.local_uri;
  15118. #endif
  15119. }
  15120. DEBUG_TRACE("http: %s, error: %s",
  15121. (ri->http_version ? ri->http_version : "none"),
  15122. (ebuf[0] ? ebuf : "none"));
  15123. if (ebuf[0] == '\0') {
  15124. if (conn->request_info.local_uri) {
  15125. /* handle request to local server */
  15126. #if defined(USE_SERVER_STATS)
  15127. conn->conn_state = 4; /* processing */
  15128. #endif
  15129. handle_request(conn);
  15130. #if defined(USE_SERVER_STATS)
  15131. conn->conn_state = 5; /* processed */
  15132. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15133. conn->consumed_content);
  15134. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15135. conn->num_bytes_sent);
  15136. #endif
  15137. DEBUG_TRACE("%s", "handle_request done");
  15138. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15139. conn->phys_ctx->callbacks.end_request(conn,
  15140. conn->status_code);
  15141. DEBUG_TRACE("%s", "end_request callback done");
  15142. }
  15143. log_access(conn);
  15144. } else {
  15145. /* TODO: handle non-local request (PROXY) */
  15146. conn->must_close = 1;
  15147. }
  15148. } else {
  15149. conn->must_close = 1;
  15150. }
  15151. if (ri->remote_user != NULL) {
  15152. mg_free((void *)ri->remote_user);
  15153. /* Important! When having connections with and without auth
  15154. * would cause double free and then crash */
  15155. ri->remote_user = NULL;
  15156. }
  15157. /* NOTE(lsm): order is important here. should_keep_alive() call
  15158. * is using parsed request, which will be invalid after
  15159. * memmove's below.
  15160. * Therefore, memorize should_keep_alive() result now for later
  15161. * use in loop exit condition. */
  15162. /* Enable it only if this request is completely discardable. */
  15163. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15164. && (conn->content_len >= 0) && (conn->request_len > 0)
  15165. && ((conn->is_chunked == 4)
  15166. || (!conn->is_chunked
  15167. && ((conn->consumed_content == conn->content_len)
  15168. || ((conn->request_len + conn->content_len)
  15169. <= conn->data_len))));
  15170. if (keep_alive) {
  15171. /* Discard all buffered data for this request */
  15172. discard_len = ((conn->request_len + conn->content_len)
  15173. < conn->data_len)
  15174. ? (int)(conn->request_len + conn->content_len)
  15175. : conn->data_len;
  15176. conn->data_len -= discard_len;
  15177. if (conn->data_len > 0) {
  15178. DEBUG_TRACE("discard_len = %d", discard_len);
  15179. memmove(conn->buf, conn->buf + discard_len,
  15180. (size_t)conn->data_len);
  15181. }
  15182. }
  15183. DEBUG_ASSERT(conn->data_len >= 0);
  15184. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15185. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15186. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15187. (long int)conn->data_len,
  15188. (long int)conn->buf_size);
  15189. break;
  15190. }
  15191. conn->handled_requests++;
  15192. } while (keep_alive);
  15193. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15194. conn->request_info.remote_addr,
  15195. difftime(time(NULL), conn->conn_birth_time));
  15196. close_connection(conn);
  15197. #if defined(USE_SERVER_STATS)
  15198. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15199. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15200. #endif
  15201. }
  15202. #if defined(ALTERNATIVE_QUEUE)
  15203. static void
  15204. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15205. {
  15206. unsigned int i;
  15207. while (!ctx->stop_flag) {
  15208. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15209. /* find a free worker slot and signal it */
  15210. if (ctx->client_socks[i].in_use == 2) {
  15211. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15212. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15213. ctx->client_socks[i] = *sp;
  15214. ctx->client_socks[i].in_use = 1;
  15215. /* socket has been moved to the consumer */
  15216. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15217. (void)event_signal(ctx->client_wait_events[i]);
  15218. return;
  15219. }
  15220. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15221. }
  15222. }
  15223. /* queue is full */
  15224. mg_sleep(1);
  15225. }
  15226. /* must consume */
  15227. set_blocking_mode(sp->sock);
  15228. closesocket(sp->sock);
  15229. }
  15230. static int
  15231. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15232. {
  15233. DEBUG_TRACE("%s", "going idle");
  15234. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15235. ctx->client_socks[thread_index].in_use = 2;
  15236. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15237. event_wait(ctx->client_wait_events[thread_index]);
  15238. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15239. *sp = ctx->client_socks[thread_index];
  15240. if (ctx->stop_flag) {
  15241. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15242. if (sp->in_use == 1) {
  15243. /* must consume */
  15244. set_blocking_mode(sp->sock);
  15245. closesocket(sp->sock);
  15246. }
  15247. return 0;
  15248. }
  15249. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15250. if (sp->in_use == 1) {
  15251. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15252. return 1;
  15253. }
  15254. /* must not reach here */
  15255. DEBUG_ASSERT(0);
  15256. return 0;
  15257. }
  15258. #else /* ALTERNATIVE_QUEUE */
  15259. /* Worker threads take accepted socket from the queue */
  15260. static int
  15261. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15262. {
  15263. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15264. (void)thread_index;
  15265. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15266. DEBUG_TRACE("%s", "going idle");
  15267. /* If the queue is empty, wait. We're idle at this point. */
  15268. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15269. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15270. }
  15271. /* If we're stopping, sq_head may be equal to sq_tail. */
  15272. if (ctx->sq_head > ctx->sq_tail) {
  15273. /* Copy socket from the queue and increment tail */
  15274. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15275. ctx->sq_tail++;
  15276. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15277. /* Wrap pointers if needed */
  15278. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15279. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15280. ctx->sq_head -= QUEUE_SIZE(ctx);
  15281. }
  15282. }
  15283. (void)pthread_cond_signal(&ctx->sq_empty);
  15284. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15285. return !ctx->stop_flag;
  15286. #undef QUEUE_SIZE
  15287. }
  15288. /* Master thread adds accepted socket to a queue */
  15289. static void
  15290. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15291. {
  15292. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15293. if (!ctx) {
  15294. return;
  15295. }
  15296. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15297. /* If the queue is full, wait */
  15298. while ((ctx->stop_flag == 0)
  15299. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15300. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15301. }
  15302. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15303. /* Copy socket to the queue and increment head */
  15304. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15305. ctx->sq_head++;
  15306. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15307. }
  15308. (void)pthread_cond_signal(&ctx->sq_full);
  15309. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15310. #undef QUEUE_SIZE
  15311. }
  15312. #endif /* ALTERNATIVE_QUEUE */
  15313. static void
  15314. worker_thread_run(struct mg_connection *conn)
  15315. {
  15316. struct mg_context *ctx = conn->phys_ctx;
  15317. int thread_index;
  15318. struct mg_workerTLS tls;
  15319. #if defined(MG_LEGACY_INTERFACE)
  15320. uint32_t addr;
  15321. #endif
  15322. mg_set_thread_name("worker");
  15323. tls.is_master = 0;
  15324. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15325. #if defined(_WIN32)
  15326. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15327. #endif
  15328. /* Initialize thread local storage before calling any callback */
  15329. pthread_setspecific(sTlsKey, &tls);
  15330. /* Check if there is a user callback */
  15331. if (ctx->callbacks.init_thread) {
  15332. /* call init_thread for a worker thread (type 1), and store the return
  15333. * value */
  15334. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  15335. } else {
  15336. /* No callback: set user pointer to NULL */
  15337. tls.user_ptr = NULL;
  15338. }
  15339. /* Connection structure has been pre-allocated */
  15340. thread_index = (int)(conn - ctx->worker_connections);
  15341. if ((thread_index < 0)
  15342. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  15343. mg_cry_ctx_internal(ctx,
  15344. "Internal error: Invalid worker index %i",
  15345. thread_index);
  15346. return;
  15347. }
  15348. /* Request buffers are not pre-allocated. They are private to the
  15349. * request and do not contain any state information that might be
  15350. * of interest to anyone observing a server status. */
  15351. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15352. if (conn->buf == NULL) {
  15353. mg_cry_ctx_internal(
  15354. ctx,
  15355. "Out of memory: Cannot allocate buffer for worker %i",
  15356. thread_index);
  15357. return;
  15358. }
  15359. conn->buf_size = (int)ctx->max_request_size;
  15360. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15361. conn->host = NULL; /* until we have more information. */
  15362. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  15363. conn->request_info.user_data = ctx->user_data;
  15364. /* Allocate a mutex for this connection to allow communication both
  15365. * within the request handler and from elsewhere in the application
  15366. */
  15367. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15368. mg_free(conn->buf);
  15369. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  15370. return;
  15371. }
  15372. #if defined(USE_SERVER_STATS)
  15373. conn->conn_state = 1; /* not consumed */
  15374. #endif
  15375. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15376. * signal sq_empty condvar to wake up the master waiting in
  15377. * produce_socket() */
  15378. while (consume_socket(ctx, &conn->client, thread_index)) {
  15379. conn->conn_birth_time = time(NULL);
  15380. /* Fill in IP, port info early so even if SSL setup below fails,
  15381. * error handler would have the corresponding info.
  15382. * Thanks to Johannes Winkelmann for the patch.
  15383. */
  15384. #if defined(USE_IPV6)
  15385. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15386. conn->request_info.remote_port =
  15387. ntohs(conn->client.rsa.sin6.sin6_port);
  15388. } else
  15389. #endif
  15390. {
  15391. conn->request_info.remote_port =
  15392. ntohs(conn->client.rsa.sin.sin_port);
  15393. }
  15394. sockaddr_to_string(conn->request_info.remote_addr,
  15395. sizeof(conn->request_info.remote_addr),
  15396. &conn->client.rsa);
  15397. DEBUG_TRACE("Start processing connection from %s",
  15398. conn->request_info.remote_addr);
  15399. conn->request_info.is_ssl = conn->client.is_ssl;
  15400. if (conn->client.is_ssl) {
  15401. #if !defined(NO_SSL)
  15402. /* HTTPS connection */
  15403. if (sslize(conn,
  15404. conn->dom_ctx->ssl_ctx,
  15405. SSL_accept,
  15406. &(conn->phys_ctx->stop_flag),
  15407. NULL)) {
  15408. /* conn->dom_ctx is set in get_request */
  15409. /* Get SSL client certificate information (if set) */
  15410. ssl_get_client_cert_info(conn);
  15411. /* process HTTPS connection */
  15412. process_new_connection(conn);
  15413. /* Free client certificate info */
  15414. if (conn->request_info.client_cert) {
  15415. mg_free((void *)(conn->request_info.client_cert->subject));
  15416. mg_free((void *)(conn->request_info.client_cert->issuer));
  15417. mg_free((void *)(conn->request_info.client_cert->serial));
  15418. mg_free((void *)(conn->request_info.client_cert->finger));
  15419. /* Free certificate memory */
  15420. X509_free(
  15421. (X509 *)conn->request_info.client_cert->peer_cert);
  15422. conn->request_info.client_cert->peer_cert = 0;
  15423. conn->request_info.client_cert->subject = 0;
  15424. conn->request_info.client_cert->issuer = 0;
  15425. conn->request_info.client_cert->serial = 0;
  15426. conn->request_info.client_cert->finger = 0;
  15427. mg_free(conn->request_info.client_cert);
  15428. conn->request_info.client_cert = 0;
  15429. }
  15430. } else {
  15431. /* make sure the connection is cleaned up on SSL failure */
  15432. close_connection(conn);
  15433. }
  15434. #endif
  15435. } else {
  15436. /* process HTTP connection */
  15437. process_new_connection(conn);
  15438. }
  15439. DEBUG_TRACE("%s", "Connection closed");
  15440. }
  15441. /* Call exit thread user callback */
  15442. if (ctx->callbacks.exit_thread) {
  15443. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  15444. }
  15445. /* delete thread local storage objects */
  15446. pthread_setspecific(sTlsKey, NULL);
  15447. #if defined(_WIN32)
  15448. CloseHandle(tls.pthread_cond_helper_mutex);
  15449. #endif
  15450. pthread_mutex_destroy(&conn->mutex);
  15451. /* Free the request buffer. */
  15452. conn->buf_size = 0;
  15453. mg_free(conn->buf);
  15454. conn->buf = NULL;
  15455. #if defined(USE_SERVER_STATS)
  15456. conn->conn_state = 9; /* done */
  15457. #endif
  15458. DEBUG_TRACE("%s", "exiting");
  15459. }
  15460. /* Threads have different return types on Windows and Unix. */
  15461. #if defined(_WIN32)
  15462. static unsigned __stdcall worker_thread(void *thread_func_param)
  15463. {
  15464. worker_thread_run((struct mg_connection *)thread_func_param);
  15465. return 0;
  15466. }
  15467. #else
  15468. static void *
  15469. worker_thread(void *thread_func_param)
  15470. {
  15471. struct sigaction sa;
  15472. /* Ignore SIGPIPE */
  15473. memset(&sa, 0, sizeof(sa));
  15474. sa.sa_handler = SIG_IGN;
  15475. sigaction(SIGPIPE, &sa, NULL);
  15476. worker_thread_run((struct mg_connection *)thread_func_param);
  15477. return NULL;
  15478. }
  15479. #endif /* _WIN32 */
  15480. /* This is an internal function, thus all arguments are expected to be
  15481. * valid - a NULL check is not required. */
  15482. static void
  15483. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15484. {
  15485. struct socket so;
  15486. char src_addr[IP_ADDR_STR_LEN];
  15487. socklen_t len = sizeof(so.rsa);
  15488. int on = 1;
  15489. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15490. == INVALID_SOCKET) {
  15491. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15492. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15493. mg_cry_ctx_internal(ctx,
  15494. "%s: %s is not allowed to connect",
  15495. __func__,
  15496. src_addr);
  15497. closesocket(so.sock);
  15498. } else {
  15499. /* Put so socket structure into the queue */
  15500. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15501. set_close_on_exec(so.sock, NULL, ctx);
  15502. so.is_ssl = listener->is_ssl;
  15503. so.ssl_redir = listener->ssl_redir;
  15504. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15505. mg_cry_ctx_internal(ctx,
  15506. "%s: getsockname() failed: %s",
  15507. __func__,
  15508. strerror(ERRNO));
  15509. }
  15510. /* Set TCP keep-alive. This is needed because if HTTP-level
  15511. * keep-alive
  15512. * is enabled, and client resets the connection, server won't get
  15513. * TCP FIN or RST and will keep the connection open forever. With
  15514. * TCP keep-alive, next keep-alive handshake will figure out that
  15515. * the client is down and will close the server end.
  15516. * Thanks to Igor Klopov who suggested the patch. */
  15517. if (setsockopt(so.sock,
  15518. SOL_SOCKET,
  15519. SO_KEEPALIVE,
  15520. (SOCK_OPT_TYPE)&on,
  15521. sizeof(on))
  15522. != 0) {
  15523. mg_cry_ctx_internal(
  15524. ctx,
  15525. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15526. __func__,
  15527. strerror(ERRNO));
  15528. }
  15529. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15530. * to effectively fill up the underlying IP packet payload and
  15531. * reduce the overhead of sending lots of small buffers. However
  15532. * this hurts the server's throughput (ie. operations per second)
  15533. * when HTTP 1.1 persistent connections are used and the responses
  15534. * are relatively small (eg. less than 1400 bytes).
  15535. */
  15536. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15537. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15538. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15539. mg_cry_ctx_internal(
  15540. ctx,
  15541. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15542. __func__,
  15543. strerror(ERRNO));
  15544. }
  15545. }
  15546. /* The "non blocking" property should already be
  15547. * inherited from the parent socket. Set it for
  15548. * non-compliant socket implementations. */
  15549. set_non_blocking_mode(so.sock);
  15550. so.in_use = 0;
  15551. produce_socket(ctx, &so);
  15552. }
  15553. }
  15554. static void
  15555. master_thread_run(struct mg_context *ctx)
  15556. {
  15557. struct mg_workerTLS tls;
  15558. struct mg_pollfd *pfd;
  15559. unsigned int i;
  15560. unsigned int workerthreadcount;
  15561. if (!ctx) {
  15562. return;
  15563. }
  15564. mg_set_thread_name("master");
  15565. /* Increase priority of the master thread */
  15566. #if defined(_WIN32)
  15567. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15568. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15569. int min_prio = sched_get_priority_min(SCHED_RR);
  15570. int max_prio = sched_get_priority_max(SCHED_RR);
  15571. if ((min_prio >= 0) && (max_prio >= 0)
  15572. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15573. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15574. struct sched_param sched_param = {0};
  15575. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15576. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15577. }
  15578. #endif
  15579. /* Initialize thread local storage */
  15580. #if defined(_WIN32)
  15581. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15582. #endif
  15583. tls.is_master = 1;
  15584. pthread_setspecific(sTlsKey, &tls);
  15585. if (ctx->callbacks.init_thread) {
  15586. /* Callback for the master thread (type 0) */
  15587. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  15588. } else {
  15589. tls.user_ptr = NULL;
  15590. }
  15591. /* Server starts *now* */
  15592. ctx->start_time = time(NULL);
  15593. /* Start the server */
  15594. pfd = ctx->listening_socket_fds;
  15595. while (ctx->stop_flag == 0) {
  15596. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15597. pfd[i].fd = ctx->listening_sockets[i].sock;
  15598. pfd[i].events = POLLIN;
  15599. }
  15600. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15601. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15602. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15603. * successful poll, and POLLIN is defined as
  15604. * (POLLRDNORM | POLLRDBAND)
  15605. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15606. * pfd[i].revents == POLLIN. */
  15607. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15608. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15609. }
  15610. }
  15611. }
  15612. }
  15613. /* Here stop_flag is 1 - Initiate shutdown. */
  15614. DEBUG_TRACE("%s", "stopping workers");
  15615. /* Stop signal received: somebody called mg_stop. Quit. */
  15616. close_all_listening_sockets(ctx);
  15617. /* Wakeup workers that are waiting for connections to handle. */
  15618. #if defined(ALTERNATIVE_QUEUE)
  15619. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15620. event_signal(ctx->client_wait_events[i]);
  15621. }
  15622. #else
  15623. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15624. pthread_cond_broadcast(&ctx->sq_full);
  15625. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15626. #endif
  15627. /* Join all worker threads to avoid leaking threads. */
  15628. workerthreadcount = ctx->cfg_worker_threads;
  15629. for (i = 0; i < workerthreadcount; i++) {
  15630. if (ctx->worker_threadids[i] != 0) {
  15631. mg_join_thread(ctx->worker_threadids[i]);
  15632. }
  15633. }
  15634. #if defined(USE_LUA)
  15635. /* Free Lua state of lua background task */
  15636. if (ctx->lua_background_state) {
  15637. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15638. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15639. if (lua_istable(lstate, -1)) {
  15640. reg_boolean(lstate, "shutdown", 1);
  15641. lua_pop(lstate, 1);
  15642. mg_sleep(2);
  15643. }
  15644. lua_close(lstate);
  15645. ctx->lua_background_state = 0;
  15646. }
  15647. #endif
  15648. DEBUG_TRACE("%s", "exiting");
  15649. /* call exit thread callback */
  15650. if (ctx->callbacks.exit_thread) {
  15651. /* Callback for the master thread (type 0) */
  15652. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  15653. }
  15654. #if defined(_WIN32)
  15655. CloseHandle(tls.pthread_cond_helper_mutex);
  15656. #endif
  15657. pthread_setspecific(sTlsKey, NULL);
  15658. /* Signal mg_stop() that we're done.
  15659. * WARNING: This must be the very last thing this
  15660. * thread does, as ctx becomes invalid after this line. */
  15661. ctx->stop_flag = 2;
  15662. }
  15663. /* Threads have different return types on Windows and Unix. */
  15664. #if defined(_WIN32)
  15665. static unsigned __stdcall master_thread(void *thread_func_param)
  15666. {
  15667. master_thread_run((struct mg_context *)thread_func_param);
  15668. return 0;
  15669. }
  15670. #else
  15671. static void *
  15672. master_thread(void *thread_func_param)
  15673. {
  15674. struct sigaction sa;
  15675. /* Ignore SIGPIPE */
  15676. memset(&sa, 0, sizeof(sa));
  15677. sa.sa_handler = SIG_IGN;
  15678. sigaction(SIGPIPE, &sa, NULL);
  15679. master_thread_run((struct mg_context *)thread_func_param);
  15680. return NULL;
  15681. }
  15682. #endif /* _WIN32 */
  15683. static void
  15684. free_context(struct mg_context *ctx)
  15685. {
  15686. int i;
  15687. struct mg_handler_info *tmp_rh;
  15688. if (ctx == NULL) {
  15689. return;
  15690. }
  15691. if (ctx->callbacks.exit_context) {
  15692. ctx->callbacks.exit_context(ctx);
  15693. }
  15694. /* All threads exited, no sync is needed. Destroy thread mutex and
  15695. * condvars
  15696. */
  15697. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15698. #if defined(ALTERNATIVE_QUEUE)
  15699. mg_free(ctx->client_socks);
  15700. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15701. event_destroy(ctx->client_wait_events[i]);
  15702. }
  15703. mg_free(ctx->client_wait_events);
  15704. #else
  15705. (void)pthread_cond_destroy(&ctx->sq_empty);
  15706. (void)pthread_cond_destroy(&ctx->sq_full);
  15707. #endif
  15708. /* Destroy other context global data structures mutex */
  15709. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15710. #if defined(USE_TIMERS)
  15711. timers_exit(ctx);
  15712. #endif
  15713. /* Deallocate config parameters */
  15714. for (i = 0; i < NUM_OPTIONS; i++) {
  15715. if (ctx->dd.config[i] != NULL) {
  15716. #if defined(_MSC_VER)
  15717. #pragma warning(suppress : 6001)
  15718. #endif
  15719. mg_free(ctx->dd.config[i]);
  15720. }
  15721. }
  15722. /* Deallocate request handlers */
  15723. while (ctx->dd.handlers) {
  15724. tmp_rh = ctx->dd.handlers;
  15725. ctx->dd.handlers = tmp_rh->next;
  15726. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15727. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15728. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15729. }
  15730. mg_free(tmp_rh->uri);
  15731. mg_free(tmp_rh);
  15732. }
  15733. #if !defined(NO_SSL)
  15734. /* Deallocate SSL context */
  15735. if (ctx->dd.ssl_ctx != NULL) {
  15736. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15737. int callback_ret =
  15738. (ctx->callbacks.external_ssl_ctx == NULL)
  15739. ? 0
  15740. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15741. if (callback_ret == 0) {
  15742. SSL_CTX_free(ctx->dd.ssl_ctx);
  15743. }
  15744. /* else: ignore error and ommit SSL_CTX_free in case
  15745. * callback_ret is 1 */
  15746. }
  15747. #endif /* !NO_SSL */
  15748. /* Deallocate worker thread ID array */
  15749. mg_free(ctx->worker_threadids);
  15750. /* Deallocate worker thread ID array */
  15751. mg_free(ctx->worker_connections);
  15752. /* deallocate system name string */
  15753. mg_free(ctx->systemName);
  15754. /* Deallocate context itself */
  15755. mg_free(ctx);
  15756. }
  15757. void
  15758. mg_stop(struct mg_context *ctx)
  15759. {
  15760. pthread_t mt;
  15761. if (!ctx) {
  15762. return;
  15763. }
  15764. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15765. * two threads is not allowed. */
  15766. mt = ctx->masterthreadid;
  15767. if (mt == 0) {
  15768. return;
  15769. }
  15770. ctx->masterthreadid = 0;
  15771. /* Set stop flag, so all threads know they have to exit. */
  15772. ctx->stop_flag = 1;
  15773. /* Wait until everything has stopped. */
  15774. while (ctx->stop_flag != 2) {
  15775. (void)mg_sleep(10);
  15776. }
  15777. mg_join_thread(mt);
  15778. free_context(ctx);
  15779. #if defined(_WIN32)
  15780. (void)WSACleanup();
  15781. #endif /* _WIN32 */
  15782. }
  15783. static void
  15784. get_system_name(char **sysName)
  15785. {
  15786. #if defined(_WIN32)
  15787. #if !defined(__SYMBIAN32__)
  15788. #if defined(_WIN32_WCE)
  15789. *sysName = mg_strdup("WinCE");
  15790. #else
  15791. char name[128];
  15792. DWORD dwVersion = 0;
  15793. DWORD dwMajorVersion = 0;
  15794. DWORD dwMinorVersion = 0;
  15795. DWORD dwBuild = 0;
  15796. BOOL wowRet, isWoW = FALSE;
  15797. #if defined(_MSC_VER)
  15798. #pragma warning(push)
  15799. /* GetVersion was declared deprecated */
  15800. #pragma warning(disable : 4996)
  15801. #endif
  15802. dwVersion = GetVersion();
  15803. #if defined(_MSC_VER)
  15804. #pragma warning(pop)
  15805. #endif
  15806. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15807. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15808. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15809. (void)dwBuild;
  15810. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15811. sprintf(name,
  15812. "Windows %u.%u%s",
  15813. (unsigned)dwMajorVersion,
  15814. (unsigned)dwMinorVersion,
  15815. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15816. *sysName = mg_strdup(name);
  15817. #endif
  15818. #else
  15819. *sysName = mg_strdup("Symbian");
  15820. #endif
  15821. #else
  15822. struct utsname name;
  15823. memset(&name, 0, sizeof(name));
  15824. uname(&name);
  15825. *sysName = mg_strdup(name.sysname);
  15826. #endif
  15827. }
  15828. struct mg_context *
  15829. mg_start(const struct mg_callbacks *callbacks,
  15830. void *user_data,
  15831. const char **options)
  15832. {
  15833. struct mg_context *ctx;
  15834. const char *name, *value, *default_value;
  15835. int idx, ok, workerthreadcount;
  15836. unsigned int i;
  15837. int itmp;
  15838. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15839. struct mg_workerTLS tls;
  15840. #if defined(_WIN32)
  15841. WSADATA data;
  15842. WSAStartup(MAKEWORD(2, 2), &data);
  15843. #endif /* _WIN32 */
  15844. /* Allocate context and initialize reasonable general case defaults. */
  15845. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15846. return NULL;
  15847. }
  15848. /* Random number generator will initialize at the first call */
  15849. ctx->dd.auth_nonce_mask =
  15850. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15851. if (mg_init_library_called == 0) {
  15852. /* Legacy INIT, if mg_start is called without mg_init_library.
  15853. * Note: This may cause a memory leak */
  15854. const char *ports_option =
  15855. config_options[LISTENING_PORTS].default_value;
  15856. if (options) {
  15857. const char **run_options = options;
  15858. const char *optname = config_options[LISTENING_PORTS].name;
  15859. /* Try to find the "listening_ports" option */
  15860. while (*run_options) {
  15861. if (!strcmp(*run_options, optname)) {
  15862. ports_option = run_options[1];
  15863. }
  15864. run_options += 2;
  15865. }
  15866. }
  15867. if (is_ssl_port_used(ports_option)) {
  15868. /* Initialize with SSL support */
  15869. mg_init_library(MG_FEATURES_TLS);
  15870. } else {
  15871. /* Initialize without SSL support */
  15872. mg_init_library(MG_FEATURES_DEFAULT);
  15873. }
  15874. }
  15875. tls.is_master = -1;
  15876. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15877. #if defined(_WIN32)
  15878. tls.pthread_cond_helper_mutex = NULL;
  15879. #endif
  15880. pthread_setspecific(sTlsKey, &tls);
  15881. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  15882. #if !defined(ALTERNATIVE_QUEUE)
  15883. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  15884. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  15885. #endif
  15886. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  15887. if (!ok) {
  15888. /* Fatal error - abort start. However, this situation should never
  15889. * occur in practice. */
  15890. mg_cry_ctx_internal(
  15891. ctx,
  15892. "%s",
  15893. "Cannot initialize thread synchronization objects");
  15894. mg_free(ctx);
  15895. pthread_setspecific(sTlsKey, NULL);
  15896. return NULL;
  15897. }
  15898. if (callbacks) {
  15899. ctx->callbacks = *callbacks;
  15900. exit_callback = callbacks->exit_context;
  15901. ctx->callbacks.exit_context = 0;
  15902. }
  15903. ctx->user_data = user_data;
  15904. ctx->dd.handlers = NULL;
  15905. ctx->dd.next = NULL;
  15906. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15907. ctx->dd.shared_lua_websockets = NULL;
  15908. #endif
  15909. /* Store options */
  15910. while (options && (name = *options++) != NULL) {
  15911. if ((idx = get_option_index(name)) == -1) {
  15912. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  15913. free_context(ctx);
  15914. pthread_setspecific(sTlsKey, NULL);
  15915. return NULL;
  15916. } else if ((value = *options++) == NULL) {
  15917. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  15918. free_context(ctx);
  15919. pthread_setspecific(sTlsKey, NULL);
  15920. return NULL;
  15921. }
  15922. if (ctx->dd.config[idx] != NULL) {
  15923. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  15924. mg_free(ctx->dd.config[idx]);
  15925. }
  15926. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15927. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15928. }
  15929. /* Set default value if needed */
  15930. for (i = 0; config_options[i].name != NULL; i++) {
  15931. default_value = config_options[i].default_value;
  15932. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15933. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15934. }
  15935. }
  15936. /* Request size option */
  15937. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15938. if (itmp < 1024) {
  15939. mg_cry_ctx_internal(ctx, "%s", "max_request_size too small");
  15940. free_context(ctx);
  15941. pthread_setspecific(sTlsKey, NULL);
  15942. return NULL;
  15943. }
  15944. ctx->max_request_size = (unsigned)itmp;
  15945. /* Worker thread count option */
  15946. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15947. if (workerthreadcount > MAX_WORKER_THREADS) {
  15948. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  15949. free_context(ctx);
  15950. pthread_setspecific(sTlsKey, NULL);
  15951. return NULL;
  15952. }
  15953. if (workerthreadcount <= 0) {
  15954. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  15955. free_context(ctx);
  15956. pthread_setspecific(sTlsKey, NULL);
  15957. return NULL;
  15958. }
  15959. /* Document root */
  15960. #if defined(NO_FILES)
  15961. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  15962. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  15963. free_context(ctx);
  15964. pthread_setspecific(sTlsKey, NULL);
  15965. return NULL;
  15966. }
  15967. #endif
  15968. get_system_name(&ctx->systemName);
  15969. #if defined(USE_LUA)
  15970. /* If a Lua background script has been configured, start it. */
  15971. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  15972. char ebuf[256];
  15973. struct vec opt_vec;
  15974. struct vec eq_vec;
  15975. const char *sparams;
  15976. lua_State *state = mg_prepare_lua_context_script(
  15977. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  15978. if (!state) {
  15979. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  15980. free_context(ctx);
  15981. pthread_setspecific(sTlsKey, NULL);
  15982. return NULL;
  15983. }
  15984. ctx->lua_background_state = (void *)state;
  15985. lua_newtable(state);
  15986. reg_boolean(state, "shutdown", 0);
  15987. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  15988. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  15989. reg_llstring(
  15990. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  15991. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  15992. break;
  15993. }
  15994. lua_setglobal(state, LUABACKGROUNDPARAMS);
  15995. } else {
  15996. ctx->lua_background_state = 0;
  15997. }
  15998. #endif
  15999. /* NOTE(lsm): order is important here. SSL certificates must
  16000. * be initialized before listening ports. UID must be set last. */
  16001. if (!set_gpass_option(ctx, NULL) ||
  16002. #if !defined(NO_SSL)
  16003. !init_ssl_ctx(ctx, NULL) ||
  16004. #endif
  16005. !set_ports_option(ctx) ||
  16006. #if !defined(_WIN32)
  16007. !set_uid_option(ctx) ||
  16008. #endif
  16009. !set_acl_option(ctx)) {
  16010. free_context(ctx);
  16011. pthread_setspecific(sTlsKey, NULL);
  16012. return NULL;
  16013. }
  16014. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16015. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16016. sizeof(pthread_t),
  16017. ctx);
  16018. if (ctx->worker_threadids == NULL) {
  16019. mg_cry_ctx_internal(ctx,
  16020. "%s",
  16021. "Not enough memory for worker thread ID array");
  16022. free_context(ctx);
  16023. pthread_setspecific(sTlsKey, NULL);
  16024. return NULL;
  16025. }
  16026. ctx->worker_connections =
  16027. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16028. sizeof(struct mg_connection),
  16029. ctx);
  16030. if (ctx->worker_connections == NULL) {
  16031. mg_cry_ctx_internal(
  16032. ctx,
  16033. "%s",
  16034. "Not enough memory for worker thread connection array");
  16035. free_context(ctx);
  16036. pthread_setspecific(sTlsKey, NULL);
  16037. return NULL;
  16038. }
  16039. #if defined(ALTERNATIVE_QUEUE)
  16040. ctx->client_wait_events =
  16041. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  16042. ctx->cfg_worker_threads,
  16043. ctx);
  16044. if (ctx->client_wait_events == NULL) {
  16045. mg_cry_ctx_internal(ctx,
  16046. "%s",
  16047. "Not enough memory for worker event array");
  16048. mg_free(ctx->worker_threadids);
  16049. free_context(ctx);
  16050. pthread_setspecific(sTlsKey, NULL);
  16051. return NULL;
  16052. }
  16053. ctx->client_socks =
  16054. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  16055. ctx->cfg_worker_threads,
  16056. ctx);
  16057. if (ctx->client_socks == NULL) {
  16058. mg_cry_ctx_internal(ctx,
  16059. "%s",
  16060. "Not enough memory for worker socket array");
  16061. mg_free(ctx->client_wait_events);
  16062. mg_free(ctx->worker_threadids);
  16063. free_context(ctx);
  16064. pthread_setspecific(sTlsKey, NULL);
  16065. return NULL;
  16066. }
  16067. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16068. ctx->client_wait_events[i] = event_create();
  16069. if (ctx->client_wait_events[i] == 0) {
  16070. mg_cry_ctx_internal(ctx, "Error creating worker event %i", i);
  16071. while (i > 0) {
  16072. i--;
  16073. event_destroy(ctx->client_wait_events[i]);
  16074. }
  16075. mg_free(ctx->client_socks);
  16076. mg_free(ctx->client_wait_events);
  16077. mg_free(ctx->worker_threadids);
  16078. free_context(ctx);
  16079. pthread_setspecific(sTlsKey, NULL);
  16080. return NULL;
  16081. }
  16082. }
  16083. #endif
  16084. #if defined(USE_TIMERS)
  16085. if (timers_init(ctx) != 0) {
  16086. mg_cry_ctx_internal(ctx, "%s", "Error creating timers");
  16087. free_context(ctx);
  16088. pthread_setspecific(sTlsKey, NULL);
  16089. return NULL;
  16090. }
  16091. #endif
  16092. /* Context has been created - init user libraries */
  16093. if (ctx->callbacks.init_context) {
  16094. ctx->callbacks.init_context(ctx);
  16095. }
  16096. ctx->callbacks.exit_context = exit_callback;
  16097. ctx->context_type = CONTEXT_SERVER; /* server context */
  16098. /* Start master (listening) thread */
  16099. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16100. /* Start worker threads */
  16101. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16102. /* worker_thread sets up the other fields */
  16103. ctx->worker_connections[i].phys_ctx = ctx;
  16104. if (mg_start_thread_with_id(worker_thread,
  16105. &ctx->worker_connections[i],
  16106. &ctx->worker_threadids[i])
  16107. != 0) {
  16108. /* thread was not created */
  16109. if (i > 0) {
  16110. mg_cry_ctx_internal(ctx,
  16111. "Cannot start worker thread %i: error %ld",
  16112. i + 1,
  16113. (long)ERRNO);
  16114. } else {
  16115. mg_cry_ctx_internal(ctx,
  16116. "Cannot create threads: error %ld",
  16117. (long)ERRNO);
  16118. free_context(ctx);
  16119. pthread_setspecific(sTlsKey, NULL);
  16120. return NULL;
  16121. }
  16122. break;
  16123. }
  16124. }
  16125. pthread_setspecific(sTlsKey, NULL);
  16126. return ctx;
  16127. }
  16128. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16129. /* Add an additional domain to an already running web server. */
  16130. int
  16131. mg_start_domain(struct mg_context *ctx, const char **options)
  16132. {
  16133. const char *name;
  16134. const char *value;
  16135. const char *default_value;
  16136. struct mg_domain_context *new_dom;
  16137. struct mg_domain_context *dom;
  16138. int idx, i;
  16139. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  16140. return -1;
  16141. }
  16142. new_dom = (struct mg_domain_context *)
  16143. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16144. if (!new_dom) {
  16145. /* Out of memory */
  16146. return -6;
  16147. }
  16148. /* Store options - TODO: unite duplicate code */
  16149. while (options && (name = *options++) != NULL) {
  16150. if ((idx = get_option_index(name)) == -1) {
  16151. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16152. mg_free(new_dom);
  16153. return -2;
  16154. } else if ((value = *options++) == NULL) {
  16155. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16156. mg_free(new_dom);
  16157. return -2;
  16158. }
  16159. if (new_dom->config[idx] != NULL) {
  16160. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16161. mg_free(new_dom->config[idx]);
  16162. }
  16163. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16164. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16165. }
  16166. /* Authentication domain is mandatory */
  16167. /* TODO: Maybe use a new option hostname? */
  16168. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16169. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  16170. mg_free(new_dom);
  16171. return -4;
  16172. }
  16173. /* Set default value if needed. Take the config value from
  16174. * ctx as a default value. */
  16175. for (i = 0; config_options[i].name != NULL; i++) {
  16176. default_value = ctx->dd.config[i];
  16177. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16178. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16179. }
  16180. }
  16181. new_dom->handlers = NULL;
  16182. new_dom->next = NULL;
  16183. new_dom->nonce_count = 0;
  16184. new_dom->auth_nonce_mask =
  16185. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16186. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16187. new_dom->shared_lua_websockets = NULL;
  16188. #endif
  16189. if (!init_ssl_ctx(ctx, new_dom)) {
  16190. /* Init SSL failed */
  16191. mg_free(new_dom);
  16192. return -3;
  16193. }
  16194. /* Add element to linked list. */
  16195. mg_lock_context(ctx);
  16196. idx = 0;
  16197. dom = &(ctx->dd);
  16198. for (;;) {
  16199. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16200. dom->config[AUTHENTICATION_DOMAIN])) {
  16201. /* Domain collision */
  16202. mg_cry_ctx_internal(ctx,
  16203. "domain %s already in use",
  16204. new_dom->config[AUTHENTICATION_DOMAIN]);
  16205. mg_free(new_dom);
  16206. return -5;
  16207. }
  16208. /* Count number of domains */
  16209. idx++;
  16210. if (dom->next == NULL) {
  16211. dom->next = new_dom;
  16212. break;
  16213. }
  16214. dom = dom->next;
  16215. }
  16216. mg_unlock_context(ctx);
  16217. /* Return domain number */
  16218. return idx;
  16219. }
  16220. #endif
  16221. /* Feature check API function */
  16222. unsigned
  16223. mg_check_feature(unsigned feature)
  16224. {
  16225. static const unsigned feature_set = 0
  16226. /* Set bits for available features according to API documentation.
  16227. * This bit mask is created at compile time, according to the active
  16228. * preprocessor defines. It is a single const value at runtime. */
  16229. #if !defined(NO_FILES)
  16230. | MG_FEATURES_FILES
  16231. #endif
  16232. #if !defined(NO_SSL)
  16233. | MG_FEATURES_SSL
  16234. #endif
  16235. #if !defined(NO_CGI)
  16236. | MG_FEATURES_CGI
  16237. #endif
  16238. #if defined(USE_IPV6)
  16239. | MG_FEATURES_IPV6
  16240. #endif
  16241. #if defined(USE_WEBSOCKET)
  16242. | MG_FEATURES_WEBSOCKET
  16243. #endif
  16244. #if defined(USE_LUA)
  16245. | MG_FEATURES_LUA
  16246. #endif
  16247. #if defined(USE_DUKTAPE)
  16248. | MG_FEATURES_SSJS
  16249. #endif
  16250. #if !defined(NO_CACHING)
  16251. | MG_FEATURES_CACHE
  16252. #endif
  16253. #if defined(USE_SERVER_STATS)
  16254. | MG_FEATURES_STATS
  16255. #endif
  16256. #if defined(USE_ZLIB)
  16257. | MG_FEATURES_COMPRESSION
  16258. #endif
  16259. /* Set some extra bits not defined in the API documentation.
  16260. * These bits may change without further notice. */
  16261. #if defined(MG_LEGACY_INTERFACE)
  16262. | 0x00008000u
  16263. #endif
  16264. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16265. | 0x00004000u
  16266. #endif
  16267. #if defined(MEMORY_DEBUGGING)
  16268. | 0x00001000u
  16269. #endif
  16270. #if defined(USE_TIMERS)
  16271. | 0x00020000u
  16272. #endif
  16273. #if !defined(NO_NONCE_CHECK)
  16274. | 0x00040000u
  16275. #endif
  16276. #if !defined(NO_POPEN)
  16277. | 0x00080000u
  16278. #endif
  16279. ;
  16280. return (feature & feature_set);
  16281. }
  16282. static size_t
  16283. mg_str_append(char **dst, char *end, const char *src)
  16284. {
  16285. size_t len = strlen(src);
  16286. if (*dst != end) {
  16287. /* Append src if enough space, or close dst. */
  16288. if ((size_t)(end - *dst) > len) {
  16289. strcpy(*dst, src);
  16290. *dst += len;
  16291. } else {
  16292. *dst = end;
  16293. }
  16294. }
  16295. return len;
  16296. }
  16297. /* Get system information. It can be printed or stored by the caller.
  16298. * Return the size of available information. */
  16299. int
  16300. mg_get_system_info(char *buffer, int buflen)
  16301. {
  16302. char *end, *append_eoobj = NULL, block[256];
  16303. size_t system_info_length = 0;
  16304. #if defined(_WIN32)
  16305. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16306. #else
  16307. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16308. #endif
  16309. if ((buffer == NULL) || (buflen < 1)) {
  16310. buflen = 0;
  16311. end = buffer;
  16312. } else {
  16313. *buffer = 0;
  16314. end = buffer + buflen;
  16315. }
  16316. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16317. /* has enough space to append eoobj */
  16318. append_eoobj = buffer;
  16319. end -= sizeof(eoobj) - 1;
  16320. }
  16321. system_info_length += mg_str_append(&buffer, end, "{");
  16322. /* Server version */
  16323. {
  16324. const char *version = mg_version();
  16325. mg_snprintf(NULL,
  16326. NULL,
  16327. block,
  16328. sizeof(block),
  16329. "%s\"version\" : \"%s\"",
  16330. eol,
  16331. version);
  16332. system_info_length += mg_str_append(&buffer, end, block);
  16333. }
  16334. /* System info */
  16335. {
  16336. #if defined(_WIN32)
  16337. DWORD dwVersion = 0;
  16338. DWORD dwMajorVersion = 0;
  16339. DWORD dwMinorVersion = 0;
  16340. SYSTEM_INFO si;
  16341. GetSystemInfo(&si);
  16342. #if defined(_MSC_VER)
  16343. #pragma warning(push)
  16344. /* GetVersion was declared deprecated */
  16345. #pragma warning(disable : 4996)
  16346. #endif
  16347. dwVersion = GetVersion();
  16348. #if defined(_MSC_VER)
  16349. #pragma warning(pop)
  16350. #endif
  16351. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16352. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16353. mg_snprintf(NULL,
  16354. NULL,
  16355. block,
  16356. sizeof(block),
  16357. ",%s\"os\" : \"Windows %u.%u\"",
  16358. eol,
  16359. (unsigned)dwMajorVersion,
  16360. (unsigned)dwMinorVersion);
  16361. system_info_length += mg_str_append(&buffer, end, block);
  16362. mg_snprintf(NULL,
  16363. NULL,
  16364. block,
  16365. sizeof(block),
  16366. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  16367. eol,
  16368. (unsigned)si.wProcessorArchitecture,
  16369. (unsigned)si.dwNumberOfProcessors,
  16370. (unsigned)si.dwActiveProcessorMask);
  16371. system_info_length += mg_str_append(&buffer, end, block);
  16372. #else
  16373. struct utsname name;
  16374. memset(&name, 0, sizeof(name));
  16375. uname(&name);
  16376. mg_snprintf(NULL,
  16377. NULL,
  16378. block,
  16379. sizeof(block),
  16380. ",%s\"os\" : \"%s %s (%s) - %s\"",
  16381. eol,
  16382. name.sysname,
  16383. name.version,
  16384. name.release,
  16385. name.machine);
  16386. system_info_length += mg_str_append(&buffer, end, block);
  16387. #endif
  16388. }
  16389. /* Features */
  16390. {
  16391. mg_snprintf(NULL,
  16392. NULL,
  16393. block,
  16394. sizeof(block),
  16395. ",%s\"features\" : %lu"
  16396. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  16397. eol,
  16398. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16399. eol,
  16400. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16401. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16402. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16403. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16404. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16405. : "",
  16406. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16407. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16408. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16409. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  16410. system_info_length += mg_str_append(&buffer, end, block);
  16411. #if defined(USE_LUA)
  16412. mg_snprintf(NULL,
  16413. NULL,
  16414. block,
  16415. sizeof(block),
  16416. ",%s\"lua_version\" : \"%u (%s)\"",
  16417. eol,
  16418. (unsigned)LUA_VERSION_NUM,
  16419. LUA_RELEASE);
  16420. system_info_length += mg_str_append(&buffer, end, block);
  16421. #endif
  16422. #if defined(USE_DUKTAPE)
  16423. mg_snprintf(NULL,
  16424. NULL,
  16425. block,
  16426. sizeof(block),
  16427. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  16428. eol,
  16429. (unsigned)DUK_VERSION / 10000,
  16430. ((unsigned)DUK_VERSION / 100) % 100,
  16431. (unsigned)DUK_VERSION % 100);
  16432. system_info_length += mg_str_append(&buffer, end, block);
  16433. #endif
  16434. }
  16435. /* Build date */
  16436. {
  16437. #if defined(GCC_DIAGNOSTIC)
  16438. #if GCC_VERSION >= 40900
  16439. #pragma GCC diagnostic push
  16440. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  16441. #pragma GCC diagnostic ignored "-Wdate-time"
  16442. #endif
  16443. #endif
  16444. mg_snprintf(NULL,
  16445. NULL,
  16446. block,
  16447. sizeof(block),
  16448. ",%s\"build\" : \"%s\"",
  16449. eol,
  16450. __DATE__);
  16451. #if defined(GCC_DIAGNOSTIC)
  16452. #if GCC_VERSION >= 40900
  16453. #pragma GCC diagnostic pop
  16454. #endif
  16455. #endif
  16456. system_info_length += mg_str_append(&buffer, end, block);
  16457. }
  16458. /* Compiler information */
  16459. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16460. {
  16461. #if defined(_MSC_VER)
  16462. mg_snprintf(NULL,
  16463. NULL,
  16464. block,
  16465. sizeof(block),
  16466. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  16467. eol,
  16468. (unsigned)_MSC_VER,
  16469. (unsigned)_MSC_FULL_VER);
  16470. system_info_length += mg_str_append(&buffer, end, block);
  16471. #elif defined(__MINGW64__)
  16472. mg_snprintf(NULL,
  16473. NULL,
  16474. block,
  16475. sizeof(block),
  16476. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  16477. eol,
  16478. (unsigned)__MINGW64_VERSION_MAJOR,
  16479. (unsigned)__MINGW64_VERSION_MINOR);
  16480. system_info_length += mg_str_append(&buffer, end, block);
  16481. mg_snprintf(NULL,
  16482. NULL,
  16483. block,
  16484. sizeof(block),
  16485. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16486. eol,
  16487. (unsigned)__MINGW32_MAJOR_VERSION,
  16488. (unsigned)__MINGW32_MINOR_VERSION);
  16489. system_info_length += mg_str_append(&buffer, end, block);
  16490. #elif defined(__MINGW32__)
  16491. mg_snprintf(NULL,
  16492. NULL,
  16493. block,
  16494. sizeof(block),
  16495. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16496. eol,
  16497. (unsigned)__MINGW32_MAJOR_VERSION,
  16498. (unsigned)__MINGW32_MINOR_VERSION);
  16499. system_info_length += mg_str_append(&buffer, end, block);
  16500. #elif defined(__clang__)
  16501. mg_snprintf(NULL,
  16502. NULL,
  16503. block,
  16504. sizeof(block),
  16505. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  16506. eol,
  16507. __clang_major__,
  16508. __clang_minor__,
  16509. __clang_patchlevel__,
  16510. __clang_version__);
  16511. system_info_length += mg_str_append(&buffer, end, block);
  16512. #elif defined(__GNUC__)
  16513. mg_snprintf(NULL,
  16514. NULL,
  16515. block,
  16516. sizeof(block),
  16517. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  16518. eol,
  16519. (unsigned)__GNUC__,
  16520. (unsigned)__GNUC_MINOR__,
  16521. (unsigned)__GNUC_PATCHLEVEL__);
  16522. system_info_length += mg_str_append(&buffer, end, block);
  16523. #elif defined(__INTEL_COMPILER)
  16524. mg_snprintf(NULL,
  16525. NULL,
  16526. block,
  16527. sizeof(block),
  16528. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  16529. eol,
  16530. (unsigned)__INTEL_COMPILER);
  16531. system_info_length += mg_str_append(&buffer, end, block);
  16532. #elif defined(__BORLANDC__)
  16533. mg_snprintf(NULL,
  16534. NULL,
  16535. block,
  16536. sizeof(block),
  16537. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  16538. eol,
  16539. (unsigned)__BORLANDC__);
  16540. system_info_length += mg_str_append(&buffer, end, block);
  16541. #elif defined(__SUNPRO_C)
  16542. mg_snprintf(NULL,
  16543. NULL,
  16544. block,
  16545. sizeof(block),
  16546. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  16547. eol,
  16548. (unsigned)__SUNPRO_C);
  16549. system_info_length += mg_str_append(&buffer, end, block);
  16550. #else
  16551. mg_snprintf(NULL,
  16552. NULL,
  16553. block,
  16554. sizeof(block),
  16555. ",%s\"compiler\" : \"other\"",
  16556. eol);
  16557. system_info_length += mg_str_append(&buffer, end, block);
  16558. #endif
  16559. }
  16560. /* Determine 32/64 bit data mode.
  16561. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16562. {
  16563. mg_snprintf(NULL,
  16564. NULL,
  16565. block,
  16566. sizeof(block),
  16567. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16568. "char:%u/%u, "
  16569. "ptr:%u, size:%u, time:%u\"",
  16570. eol,
  16571. (unsigned)sizeof(short),
  16572. (unsigned)sizeof(int),
  16573. (unsigned)sizeof(long),
  16574. (unsigned)sizeof(long long),
  16575. (unsigned)sizeof(float),
  16576. (unsigned)sizeof(double),
  16577. (unsigned)sizeof(long double),
  16578. (unsigned)sizeof(char),
  16579. (unsigned)sizeof(wchar_t),
  16580. (unsigned)sizeof(void *),
  16581. (unsigned)sizeof(size_t),
  16582. (unsigned)sizeof(time_t));
  16583. system_info_length += mg_str_append(&buffer, end, block);
  16584. }
  16585. /* Terminate string */
  16586. if (append_eoobj) {
  16587. strcat(append_eoobj, eoobj);
  16588. }
  16589. system_info_length += sizeof(eoobj) - 1;
  16590. return (int)system_info_length;
  16591. }
  16592. /* Get context information. It can be printed or stored by the caller.
  16593. * Return the size of available information. */
  16594. int
  16595. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16596. {
  16597. #if defined(USE_SERVER_STATS)
  16598. char *end, *append_eoobj = NULL, block[256];
  16599. size_t context_info_length = 0;
  16600. #if defined(_WIN32)
  16601. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16602. #else
  16603. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16604. #endif
  16605. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16606. if ((buffer == NULL) || (buflen < 1)) {
  16607. buflen = 0;
  16608. end = buffer;
  16609. } else {
  16610. *buffer = 0;
  16611. end = buffer + buflen;
  16612. }
  16613. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16614. /* has enough space to append eoobj */
  16615. append_eoobj = buffer;
  16616. end -= sizeof(eoobj) - 1;
  16617. }
  16618. context_info_length += mg_str_append(&buffer, end, "{");
  16619. if (ms) { /* <-- should be always true */
  16620. /* Memory information */
  16621. mg_snprintf(NULL,
  16622. NULL,
  16623. block,
  16624. sizeof(block),
  16625. "%s\"memory\" : {%s"
  16626. "\"blocks\" : %i,%s"
  16627. "\"used\" : %" INT64_FMT ",%s"
  16628. "\"maxUsed\" : %" INT64_FMT "%s"
  16629. "}",
  16630. eol,
  16631. eol,
  16632. ms->blockCount,
  16633. eol,
  16634. ms->totalMemUsed,
  16635. eol,
  16636. ms->maxMemUsed,
  16637. eol);
  16638. context_info_length += mg_str_append(&buffer, end, block);
  16639. }
  16640. if (ctx) {
  16641. /* Declare all variables at begin of the block, to comply
  16642. * with old C standards. */
  16643. char start_time_str[64] = {0};
  16644. char now_str[64] = {0};
  16645. time_t start_time = ctx->start_time;
  16646. time_t now = time(NULL);
  16647. /* Connections information */
  16648. mg_snprintf(NULL,
  16649. NULL,
  16650. block,
  16651. sizeof(block),
  16652. ",%s\"connections\" : {%s"
  16653. "\"active\" : %i,%s"
  16654. "\"maxActive\" : %i,%s"
  16655. "\"total\" : %" INT64_FMT "%s"
  16656. "}",
  16657. eol,
  16658. eol,
  16659. ctx->active_connections,
  16660. eol,
  16661. ctx->max_connections,
  16662. eol,
  16663. ctx->total_connections,
  16664. eol);
  16665. context_info_length += mg_str_append(&buffer, end, block);
  16666. /* Requests information */
  16667. mg_snprintf(NULL,
  16668. NULL,
  16669. block,
  16670. sizeof(block),
  16671. ",%s\"requests\" : {%s"
  16672. "\"total\" : %" INT64_FMT "%s"
  16673. "}",
  16674. eol,
  16675. eol,
  16676. ctx->total_requests,
  16677. eol);
  16678. context_info_length += mg_str_append(&buffer, end, block);
  16679. /* Data information */
  16680. mg_snprintf(NULL,
  16681. NULL,
  16682. block,
  16683. sizeof(block),
  16684. ",%s\"data\" : {%s"
  16685. "\"read\" : %" INT64_FMT ",%s"
  16686. "\"written\" : %" INT64_FMT "%s"
  16687. "}",
  16688. eol,
  16689. eol,
  16690. ctx->total_data_read,
  16691. eol,
  16692. ctx->total_data_written,
  16693. eol);
  16694. context_info_length += mg_str_append(&buffer, end, block);
  16695. /* Execution time information */
  16696. gmt_time_string(start_time_str,
  16697. sizeof(start_time_str) - 1,
  16698. &start_time);
  16699. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16700. mg_snprintf(NULL,
  16701. NULL,
  16702. block,
  16703. sizeof(block),
  16704. ",%s\"time\" : {%s"
  16705. "\"uptime\" : %.0f,%s"
  16706. "\"start\" : \"%s\",%s"
  16707. "\"now\" : \"%s\"%s"
  16708. "}",
  16709. eol,
  16710. eol,
  16711. difftime(now, start_time),
  16712. eol,
  16713. start_time_str,
  16714. eol,
  16715. now_str,
  16716. eol);
  16717. context_info_length += mg_str_append(&buffer, end, block);
  16718. }
  16719. /* Terminate string */
  16720. if (append_eoobj) {
  16721. strcat(append_eoobj, eoobj);
  16722. }
  16723. context_info_length += sizeof(eoobj) - 1;
  16724. return (int)context_info_length;
  16725. #else
  16726. (void)ctx;
  16727. if ((buffer != NULL) && (buflen > 0)) {
  16728. *buffer = 0;
  16729. }
  16730. return 0;
  16731. #endif
  16732. }
  16733. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16734. /* Get connection information. It can be printed or stored by the caller.
  16735. * Return the size of available information. */
  16736. int
  16737. mg_get_connection_info(const struct mg_context *ctx,
  16738. int idx,
  16739. char *buffer,
  16740. int buflen)
  16741. {
  16742. const struct mg_connection *conn;
  16743. const struct mg_request_info *ri;
  16744. char *end, *append_eoobj = NULL, block[256];
  16745. size_t connection_info_length = 0;
  16746. int state = 0;
  16747. const char *state_str = "unknown";
  16748. #if defined(_WIN32)
  16749. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16750. #else
  16751. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16752. #endif
  16753. if ((buffer == NULL) || (buflen < 1)) {
  16754. buflen = 0;
  16755. end = buffer;
  16756. } else {
  16757. *buffer = 0;
  16758. end = buffer + buflen;
  16759. }
  16760. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16761. /* has enough space to append eoobj */
  16762. append_eoobj = buffer;
  16763. end -= sizeof(eoobj) - 1;
  16764. }
  16765. if ((ctx == NULL) || (idx < 0)) {
  16766. /* Parameter error */
  16767. return 0;
  16768. }
  16769. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16770. /* Out of range */
  16771. return 0;
  16772. }
  16773. /* Take connection [idx]. This connection is not locked in
  16774. * any way, so some other thread might use it. */
  16775. conn = (ctx->worker_connections) + idx;
  16776. /* Initialize output string */
  16777. connection_info_length += mg_str_append(&buffer, end, "{");
  16778. /* Init variables */
  16779. ri = &(conn->request_info);
  16780. #if defined(USE_SERVER_STATS)
  16781. state = conn->conn_state;
  16782. /* State as string */
  16783. switch (state) {
  16784. case 0:
  16785. state_str = "undefined";
  16786. break;
  16787. case 1:
  16788. state_str = "not used";
  16789. break;
  16790. case 2:
  16791. state_str = "init";
  16792. break;
  16793. case 3:
  16794. state_str = "ready";
  16795. break;
  16796. case 4:
  16797. state_str = "processing";
  16798. break;
  16799. case 5:
  16800. state_str = "processed";
  16801. break;
  16802. case 6:
  16803. state_str = "to close";
  16804. break;
  16805. case 7:
  16806. state_str = "closing";
  16807. break;
  16808. case 8:
  16809. state_str = "closed";
  16810. break;
  16811. case 9:
  16812. state_str = "done";
  16813. break;
  16814. }
  16815. #endif
  16816. /* Connection info */
  16817. if ((state >= 3) && (state < 9)) {
  16818. mg_snprintf(NULL,
  16819. NULL,
  16820. block,
  16821. sizeof(block),
  16822. "%s\"connection\" : {%s"
  16823. "\"remote\" : {%s"
  16824. "\"protocol\" : \"%s\",%s"
  16825. "\"addr\" : \"%s\",%s"
  16826. "\"port\" : %u%s"
  16827. "},%s"
  16828. "\"handled_requests\" : %u%s"
  16829. "}",
  16830. eol,
  16831. eol,
  16832. eol,
  16833. get_proto_name(conn),
  16834. eol,
  16835. ri->remote_addr,
  16836. eol,
  16837. ri->remote_port,
  16838. eol,
  16839. eol,
  16840. conn->handled_requests,
  16841. eol);
  16842. connection_info_length += mg_str_append(&buffer, end, block);
  16843. }
  16844. /* Request info */
  16845. if ((state >= 4) && (state < 6)) {
  16846. mg_snprintf(NULL,
  16847. NULL,
  16848. block,
  16849. sizeof(block),
  16850. "%s%s\"request_info\" : {%s"
  16851. "\"method\" : \"%s\",%s"
  16852. "\"uri\" : \"%s\",%s"
  16853. "\"query\" : %s%s%s%s"
  16854. "}",
  16855. (connection_info_length > 1 ? "," : ""),
  16856. eol,
  16857. eol,
  16858. ri->request_method,
  16859. eol,
  16860. ri->request_uri,
  16861. eol,
  16862. ri->query_string ? "\"" : "",
  16863. ri->query_string ? ri->query_string : "null",
  16864. ri->query_string ? "\"" : "",
  16865. eol);
  16866. connection_info_length += mg_str_append(&buffer, end, block);
  16867. }
  16868. /* Execution time information */
  16869. if ((state >= 2) && (state < 9)) {
  16870. char start_time_str[64] = {0};
  16871. char now_str[64] = {0};
  16872. time_t start_time = conn->conn_birth_time;
  16873. time_t now = time(NULL);
  16874. gmt_time_string(start_time_str,
  16875. sizeof(start_time_str) - 1,
  16876. &start_time);
  16877. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16878. mg_snprintf(NULL,
  16879. NULL,
  16880. block,
  16881. sizeof(block),
  16882. "%s%s\"time\" : {%s"
  16883. "\"uptime\" : %.0f,%s"
  16884. "\"start\" : \"%s\",%s"
  16885. "\"now\" : \"%s\"%s"
  16886. "}",
  16887. (connection_info_length > 1 ? "," : ""),
  16888. eol,
  16889. eol,
  16890. difftime(now, start_time),
  16891. eol,
  16892. start_time_str,
  16893. eol,
  16894. now_str,
  16895. eol);
  16896. connection_info_length += mg_str_append(&buffer, end, block);
  16897. }
  16898. /* Remote user name */
  16899. if ((ri->remote_user) && (state < 9)) {
  16900. mg_snprintf(NULL,
  16901. NULL,
  16902. block,
  16903. sizeof(block),
  16904. "%s%s\"user\" : {%s"
  16905. "\"name\" : \"%s\",%s"
  16906. "}",
  16907. (connection_info_length > 1 ? "," : ""),
  16908. eol,
  16909. eol,
  16910. ri->remote_user,
  16911. eol);
  16912. connection_info_length += mg_str_append(&buffer, end, block);
  16913. }
  16914. /* Data block */
  16915. if (state >= 3) {
  16916. mg_snprintf(NULL,
  16917. NULL,
  16918. block,
  16919. sizeof(block),
  16920. "%s%s\"data\" : {%s"
  16921. "\"read\" : %" INT64_FMT ",%s"
  16922. "\"written\" : %" INT64_FMT "%s"
  16923. "}",
  16924. (connection_info_length > 1 ? "," : ""),
  16925. eol,
  16926. eol,
  16927. conn->consumed_content,
  16928. eol,
  16929. conn->num_bytes_sent,
  16930. eol);
  16931. connection_info_length += mg_str_append(&buffer, end, block);
  16932. }
  16933. /* State */
  16934. mg_snprintf(NULL,
  16935. NULL,
  16936. block,
  16937. sizeof(block),
  16938. "%s%s\"state\" : \"%s\"",
  16939. (connection_info_length > 1 ? "," : ""),
  16940. eol,
  16941. state_str);
  16942. connection_info_length += mg_str_append(&buffer, end, block);
  16943. /* Terminate string */
  16944. if (append_eoobj) {
  16945. strcat(append_eoobj, eoobj);
  16946. }
  16947. connection_info_length += sizeof(eoobj) - 1;
  16948. return (int)connection_info_length;
  16949. }
  16950. #endif
  16951. /* Initialize this library. This function does not need to be thread safe.
  16952. */
  16953. unsigned
  16954. mg_init_library(unsigned features)
  16955. {
  16956. #if !defined(NO_SSL)
  16957. char ebuf[128];
  16958. #endif
  16959. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  16960. unsigned features_inited = features_to_init;
  16961. if (mg_init_library_called <= 0) {
  16962. /* Not initialized yet */
  16963. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  16964. return 0;
  16965. }
  16966. }
  16967. mg_global_lock();
  16968. if (mg_init_library_called <= 0) {
  16969. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  16970. /* Fatal error - abort start. However, this situation should
  16971. * never occur in practice. */
  16972. mg_global_unlock();
  16973. return 0;
  16974. }
  16975. #if defined(_WIN32)
  16976. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  16977. #else
  16978. pthread_mutexattr_init(&pthread_mutex_attr);
  16979. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  16980. #endif
  16981. #if defined(USE_LUA)
  16982. lua_init_optional_libraries();
  16983. #endif
  16984. }
  16985. mg_global_unlock();
  16986. #if !defined(NO_SSL)
  16987. if (features_to_init & MG_FEATURES_SSL) {
  16988. if (!mg_ssl_initialized) {
  16989. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  16990. mg_ssl_initialized = 1;
  16991. } else {
  16992. (void)ebuf;
  16993. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  16994. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  16995. }
  16996. } else {
  16997. /* ssl already initialized */
  16998. }
  16999. }
  17000. #endif
  17001. /* Start WinSock for Windows */
  17002. mg_global_lock();
  17003. if (mg_init_library_called <= 0) {
  17004. #if defined(_WIN32)
  17005. WSADATA data;
  17006. WSAStartup(MAKEWORD(2, 2), &data);
  17007. #endif /* _WIN32 */
  17008. mg_init_library_called = 1;
  17009. } else {
  17010. mg_init_library_called++;
  17011. }
  17012. mg_global_unlock();
  17013. return features_inited;
  17014. }
  17015. /* Un-initialize this library. */
  17016. unsigned
  17017. mg_exit_library(void)
  17018. {
  17019. if (mg_init_library_called <= 0) {
  17020. return 0;
  17021. }
  17022. mg_global_lock();
  17023. mg_init_library_called--;
  17024. if (mg_init_library_called == 0) {
  17025. #if defined(_WIN32)
  17026. (void)WSACleanup();
  17027. #endif /* _WIN32 */
  17028. #if !defined(NO_SSL)
  17029. if (mg_ssl_initialized) {
  17030. uninitialize_ssl();
  17031. mg_ssl_initialized = 0;
  17032. }
  17033. #endif
  17034. #if defined(_WIN32)
  17035. (void)pthread_mutex_destroy(&global_log_file_lock);
  17036. #else
  17037. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17038. #endif
  17039. (void)pthread_key_delete(sTlsKey);
  17040. #if defined(USE_LUA)
  17041. lua_exit_optional_libraries();
  17042. #endif
  17043. mg_global_unlock();
  17044. (void)pthread_mutex_destroy(&global_lock_mutex);
  17045. return 1;
  17046. }
  17047. mg_global_unlock();
  17048. return 1;
  17049. }
  17050. /* End of civetweb.c */