civetweb.c 529 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830
  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) (EnterCriticalSection(&global_log_file_lock))
  473. #define funlockfile(x) (LeaveCriticalSection(&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 HANDLE pthread_mutex_t;
  487. typedef DWORD pthread_key_t;
  488. typedef HANDLE pthread_t;
  489. typedef struct {
  490. CRITICAL_SECTION threadIdSec;
  491. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  492. } pthread_cond_t;
  493. #if !defined(__clockid_t_defined)
  494. typedef DWORD clockid_t;
  495. #endif
  496. #if !defined(CLOCK_MONOTONIC)
  497. #define CLOCK_MONOTONIC (1)
  498. #endif
  499. #if !defined(CLOCK_REALTIME)
  500. #define CLOCK_REALTIME (2)
  501. #endif
  502. #if !defined(CLOCK_THREAD)
  503. #define CLOCK_THREAD (3)
  504. #endif
  505. #if !defined(CLOCK_PROCESS)
  506. #define CLOCK_PROCESS (4)
  507. #endif
  508. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  509. #define _TIMESPEC_DEFINED
  510. #endif
  511. #if !defined(_TIMESPEC_DEFINED)
  512. struct timespec {
  513. time_t tv_sec; /* seconds */
  514. long tv_nsec; /* nanoseconds */
  515. };
  516. #endif
  517. #if !defined(WIN_PTHREADS_TIME_H)
  518. #define MUST_IMPLEMENT_CLOCK_GETTIME
  519. #endif
  520. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  521. #define clock_gettime mg_clock_gettime
  522. static int
  523. clock_gettime(clockid_t clk_id, struct timespec *tp)
  524. {
  525. FILETIME ft;
  526. ULARGE_INTEGER li, li2;
  527. BOOL ok = FALSE;
  528. double d;
  529. static double perfcnt_per_sec = 0.0;
  530. static BOOL initialized = FALSE;
  531. if (!initialized) {
  532. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  533. perfcnt_per_sec = 1.0 / li.QuadPart;
  534. initialized = TRUE;
  535. }
  536. if (tp) {
  537. memset(tp, 0, sizeof(*tp));
  538. if (clk_id == CLOCK_REALTIME) {
  539. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  540. GetSystemTimeAsFileTime(&ft);
  541. li.LowPart = ft.dwLowDateTime;
  542. li.HighPart = ft.dwHighDateTime;
  543. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  544. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  545. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  546. ok = TRUE;
  547. /* END: CLOCK_REALTIME */
  548. } else if (clk_id == CLOCK_MONOTONIC) {
  549. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  550. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  551. d = li.QuadPart * perfcnt_per_sec;
  552. tp->tv_sec = (time_t)d;
  553. d -= (double)tp->tv_sec;
  554. tp->tv_nsec = (long)(d * 1.0E9);
  555. ok = TRUE;
  556. /* END: CLOCK_MONOTONIC */
  557. } else if (clk_id == CLOCK_THREAD) {
  558. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  559. FILETIME t_create, t_exit, t_kernel, t_user;
  560. if (GetThreadTimes(GetCurrentThread(),
  561. &t_create,
  562. &t_exit,
  563. &t_kernel,
  564. &t_user)) {
  565. li.LowPart = t_user.dwLowDateTime;
  566. li.HighPart = t_user.dwHighDateTime;
  567. li2.LowPart = t_kernel.dwLowDateTime;
  568. li2.HighPart = t_kernel.dwHighDateTime;
  569. li.QuadPart += li2.QuadPart;
  570. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  571. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  572. ok = TRUE;
  573. }
  574. /* END: CLOCK_THREAD */
  575. } else if (clk_id == CLOCK_PROCESS) {
  576. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  577. FILETIME t_create, t_exit, t_kernel, t_user;
  578. if (GetProcessTimes(GetCurrentProcess(),
  579. &t_create,
  580. &t_exit,
  581. &t_kernel,
  582. &t_user)) {
  583. li.LowPart = t_user.dwLowDateTime;
  584. li.HighPart = t_user.dwHighDateTime;
  585. li2.LowPart = t_kernel.dwLowDateTime;
  586. li2.HighPart = t_kernel.dwHighDateTime;
  587. li.QuadPart += li2.QuadPart;
  588. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  589. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  590. ok = TRUE;
  591. }
  592. /* END: CLOCK_PROCESS */
  593. } else {
  594. /* BEGIN: unknown clock */
  595. /* ok = FALSE; already set by init */
  596. /* END: unknown clock */
  597. }
  598. }
  599. return ok ? 0 : -1;
  600. }
  601. #endif
  602. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  603. static int pthread_mutex_lock(pthread_mutex_t *);
  604. static int pthread_mutex_unlock(pthread_mutex_t *);
  605. static void path_to_unicode(const struct mg_connection *conn,
  606. const char *path,
  607. wchar_t *wbuf,
  608. size_t wbuf_len);
  609. /* All file operations need to be rewritten to solve #246. */
  610. struct mg_file;
  611. static const char *
  612. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  613. /* POSIX dirent interface */
  614. struct dirent {
  615. char d_name[PATH_MAX];
  616. };
  617. typedef struct DIR {
  618. HANDLE handle;
  619. WIN32_FIND_DATAW info;
  620. struct dirent result;
  621. } DIR;
  622. #if defined(HAVE_POLL)
  623. #define mg_pollfd pollfd
  624. #else
  625. struct mg_pollfd {
  626. SOCKET fd;
  627. short events;
  628. short revents;
  629. };
  630. #endif
  631. /* Mark required libraries */
  632. #if defined(_MSC_VER)
  633. #pragma comment(lib, "Ws2_32.lib")
  634. #endif
  635. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  636. #include <arpa/inet.h>
  637. #include <inttypes.h>
  638. #include <netdb.h>
  639. #include <netinet/in.h>
  640. #include <netinet/tcp.h>
  641. #include <stdint.h>
  642. #include <sys/poll.h>
  643. #include <sys/socket.h>
  644. #include <sys/time.h>
  645. #include <sys/utsname.h>
  646. #include <sys/wait.h>
  647. typedef const void *SOCK_OPT_TYPE;
  648. #if defined(ANDROID)
  649. typedef unsigned short int in_port_t;
  650. #endif
  651. #include <dirent.h>
  652. #include <grp.h>
  653. #include <pwd.h>
  654. #include <unistd.h>
  655. #define vsnprintf_impl vsnprintf
  656. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  657. #include <dlfcn.h>
  658. #endif
  659. #include <pthread.h>
  660. #if defined(__MACH__)
  661. #define SSL_LIB "libssl.dylib"
  662. #define CRYPTO_LIB "libcrypto.dylib"
  663. #else
  664. #if !defined(SSL_LIB)
  665. #define SSL_LIB "libssl.so"
  666. #endif
  667. #if !defined(CRYPTO_LIB)
  668. #define CRYPTO_LIB "libcrypto.so"
  669. #endif
  670. #endif
  671. #if !defined(O_BINARY)
  672. #define O_BINARY (0)
  673. #endif /* O_BINARY */
  674. #define closesocket(a) (close(a))
  675. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  676. #define mg_remove(conn, x) (remove(x))
  677. #define mg_sleep(x) (usleep((x)*1000))
  678. #define mg_opendir(conn, x) (opendir(x))
  679. #define mg_closedir(x) (closedir(x))
  680. #define mg_readdir(x) (readdir(x))
  681. #define ERRNO (errno)
  682. #define INVALID_SOCKET (-1)
  683. #define INT64_FMT PRId64
  684. #define UINT64_FMT PRIu64
  685. typedef int SOCKET;
  686. #define WINCDECL
  687. #if defined(__hpux)
  688. /* HPUX 11 does not have monotonic, fall back to realtime */
  689. #if !defined(CLOCK_MONOTONIC)
  690. #define CLOCK_MONOTONIC CLOCK_REALTIME
  691. #endif
  692. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  693. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  694. * the prototypes use int* rather than socklen_t* which matches the
  695. * actual library expectation. When called with the wrong size arg
  696. * accept() returns a zero client inet addr and check_acl() always
  697. * fails. Since socklen_t is widely used below, just force replace
  698. * their typedef with int. - DTL
  699. */
  700. #define socklen_t int
  701. #endif /* hpux */
  702. #define mg_pollfd pollfd
  703. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  704. /* Maximum queue length for pending connections. This value is passed as
  705. * parameter to the "listen" socket call. */
  706. #if !defined(SOMAXCONN)
  707. /* This symbol may be defined in winsock2.h so this must after that include */
  708. #define SOMAXCONN (100) /* in pending connections (count) */
  709. #endif
  710. /* In case our C library is missing "timegm", provide an implementation */
  711. #if defined(NEED_TIMEGM)
  712. static inline int
  713. is_leap(int y)
  714. {
  715. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  716. }
  717. static inline int
  718. count_leap(int y)
  719. {
  720. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  721. }
  722. time_t
  723. timegm(struct tm *tm)
  724. {
  725. static const unsigned short ydays[] = {
  726. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  727. int year = tm->tm_year + 1900;
  728. int mon = tm->tm_mon;
  729. int mday = tm->tm_mday - 1;
  730. int hour = tm->tm_hour;
  731. int min = tm->tm_min;
  732. int sec = tm->tm_sec;
  733. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  734. || (mday >= ydays[mon + 1] - ydays[mon]
  735. + (mon == 1 && is_leap(year) ? 1 : 0))
  736. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  737. return -1;
  738. time_t res = year - 1970;
  739. res *= 365;
  740. res += mday;
  741. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  742. res += count_leap(year);
  743. res *= 24;
  744. res += hour;
  745. res *= 60;
  746. res += min;
  747. res *= 60;
  748. res += sec;
  749. return res;
  750. }
  751. #endif /* NEED_TIMEGM */
  752. /* va_copy should always be a macro, C99 and C++11 - DTL */
  753. #if !defined(va_copy)
  754. #define va_copy(x, y) ((x) = (y))
  755. #endif
  756. #if defined(_WIN32)
  757. /* Create substitutes for POSIX functions in Win32. */
  758. #if defined(GCC_DIAGNOSTIC)
  759. /* Show no warning in case system functions are not used. */
  760. #pragma GCC diagnostic push
  761. #pragma GCC diagnostic ignored "-Wunused-function"
  762. #endif
  763. static CRITICAL_SECTION global_log_file_lock;
  764. FUNCTION_MAY_BE_UNUSED
  765. static DWORD
  766. pthread_self(void)
  767. {
  768. return GetCurrentThreadId();
  769. }
  770. FUNCTION_MAY_BE_UNUSED
  771. static int
  772. pthread_key_create(
  773. pthread_key_t *key,
  774. void (*_ignored)(void *) /* destructor not supported for Windows */
  775. )
  776. {
  777. (void)_ignored;
  778. if ((key != 0)) {
  779. *key = TlsAlloc();
  780. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  781. }
  782. return -2;
  783. }
  784. FUNCTION_MAY_BE_UNUSED
  785. static int
  786. pthread_key_delete(pthread_key_t key)
  787. {
  788. return TlsFree(key) ? 0 : 1;
  789. }
  790. FUNCTION_MAY_BE_UNUSED
  791. static int
  792. pthread_setspecific(pthread_key_t key, void *value)
  793. {
  794. return TlsSetValue(key, value) ? 0 : 1;
  795. }
  796. FUNCTION_MAY_BE_UNUSED
  797. static void *
  798. pthread_getspecific(pthread_key_t key)
  799. {
  800. return TlsGetValue(key);
  801. }
  802. #if defined(GCC_DIAGNOSTIC)
  803. /* Enable unused function warning again */
  804. #pragma GCC diagnostic pop
  805. #endif
  806. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  807. #else
  808. static pthread_mutexattr_t pthread_mutex_attr;
  809. #endif /* _WIN32 */
  810. #if defined(_WIN32_WCE)
  811. /* Create substitutes for POSIX functions in Win32. */
  812. #if defined(GCC_DIAGNOSTIC)
  813. /* Show no warning in case system functions are not used. */
  814. #pragma GCC diagnostic push
  815. #pragma GCC diagnostic ignored "-Wunused-function"
  816. #endif
  817. FUNCTION_MAY_BE_UNUSED
  818. static time_t
  819. time(time_t *ptime)
  820. {
  821. time_t t;
  822. SYSTEMTIME st;
  823. FILETIME ft;
  824. GetSystemTime(&st);
  825. SystemTimeToFileTime(&st, &ft);
  826. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  827. if (ptime != NULL) {
  828. *ptime = t;
  829. }
  830. return t;
  831. }
  832. FUNCTION_MAY_BE_UNUSED
  833. static struct tm *
  834. localtime_s(const time_t *ptime, struct tm *ptm)
  835. {
  836. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  837. FILETIME ft, lft;
  838. SYSTEMTIME st;
  839. TIME_ZONE_INFORMATION tzinfo;
  840. if (ptm == NULL) {
  841. return NULL;
  842. }
  843. *(int64_t *)&ft = t;
  844. FileTimeToLocalFileTime(&ft, &lft);
  845. FileTimeToSystemTime(&lft, &st);
  846. ptm->tm_year = st.wYear - 1900;
  847. ptm->tm_mon = st.wMonth - 1;
  848. ptm->tm_wday = st.wDayOfWeek;
  849. ptm->tm_mday = st.wDay;
  850. ptm->tm_hour = st.wHour;
  851. ptm->tm_min = st.wMinute;
  852. ptm->tm_sec = st.wSecond;
  853. ptm->tm_yday = 0; /* hope nobody uses this */
  854. ptm->tm_isdst =
  855. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  856. return ptm;
  857. }
  858. FUNCTION_MAY_BE_UNUSED
  859. static struct tm *
  860. gmtime_s(const time_t *ptime, struct tm *ptm)
  861. {
  862. /* FIXME(lsm): fix this. */
  863. return localtime_s(ptime, ptm);
  864. }
  865. static int mg_atomic_inc(volatile int *addr);
  866. static struct tm tm_array[MAX_WORKER_THREADS];
  867. static int tm_index = 0;
  868. FUNCTION_MAY_BE_UNUSED
  869. static struct tm *
  870. localtime(const time_t *ptime)
  871. {
  872. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  873. return localtime_s(ptime, tm_array + i);
  874. }
  875. FUNCTION_MAY_BE_UNUSED
  876. static struct tm *
  877. gmtime(const time_t *ptime)
  878. {
  879. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  880. return gmtime_s(ptime, tm_array + i);
  881. }
  882. FUNCTION_MAY_BE_UNUSED
  883. static size_t
  884. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  885. {
  886. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  887. * for WinCE"); */
  888. return 0;
  889. }
  890. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  891. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  892. #define remove(f) mg_remove(NULL, f)
  893. FUNCTION_MAY_BE_UNUSED
  894. static int
  895. rename(const char *a, const char *b)
  896. {
  897. wchar_t wa[W_PATH_MAX];
  898. wchar_t wb[W_PATH_MAX];
  899. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  900. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  901. return MoveFileW(wa, wb) ? 0 : -1;
  902. }
  903. struct stat {
  904. int64_t st_size;
  905. time_t st_mtime;
  906. };
  907. FUNCTION_MAY_BE_UNUSED
  908. static int
  909. stat(const char *name, struct stat *st)
  910. {
  911. wchar_t wbuf[W_PATH_MAX];
  912. WIN32_FILE_ATTRIBUTE_DATA attr;
  913. time_t creation_time, write_time;
  914. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  915. memset(&attr, 0, sizeof(attr));
  916. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  917. st->st_size =
  918. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  919. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  920. attr.ftLastWriteTime.dwHighDateTime);
  921. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  922. attr.ftCreationTime.dwHighDateTime);
  923. if (creation_time > write_time) {
  924. st->st_mtime = creation_time;
  925. } else {
  926. st->st_mtime = write_time;
  927. }
  928. return 0;
  929. }
  930. #define access(x, a) 1 /* not required anyway */
  931. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  932. /* Values from errno.h in Windows SDK (Visual Studio). */
  933. #define EEXIST 17
  934. #define EACCES 13
  935. #define ENOENT 2
  936. #if defined(GCC_DIAGNOSTIC)
  937. /* Enable unused function warning again */
  938. #pragma GCC diagnostic pop
  939. #endif
  940. #endif /* defined(_WIN32_WCE) */
  941. #if defined(GCC_DIAGNOSTIC)
  942. /* Show no warning in case system functions are not used. */
  943. #pragma GCC diagnostic push
  944. #pragma GCC diagnostic ignored "-Wunused-function"
  945. #endif /* defined(GCC_DIAGNOSTIC) */
  946. #if defined(__clang__)
  947. /* Show no warning in case system functions are not used. */
  948. #pragma clang diagnostic push
  949. #pragma clang diagnostic ignored "-Wunused-function"
  950. #endif
  951. static pthread_mutex_t global_lock_mutex;
  952. #if defined(_WIN32)
  953. /* Forward declaration for Windows */
  954. FUNCTION_MAY_BE_UNUSED
  955. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  956. FUNCTION_MAY_BE_UNUSED
  957. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  958. #endif
  959. FUNCTION_MAY_BE_UNUSED
  960. static void
  961. mg_global_lock(void)
  962. {
  963. (void)pthread_mutex_lock(&global_lock_mutex);
  964. }
  965. FUNCTION_MAY_BE_UNUSED
  966. static void
  967. mg_global_unlock(void)
  968. {
  969. (void)pthread_mutex_unlock(&global_lock_mutex);
  970. }
  971. FUNCTION_MAY_BE_UNUSED
  972. static int
  973. mg_atomic_inc(volatile int *addr)
  974. {
  975. int ret;
  976. #if defined(_WIN32) && !defined(NO_ATOMICS)
  977. /* Depending on the SDK, this function uses either
  978. * (volatile unsigned int *) or (volatile LONG *),
  979. * so whatever you use, the other SDK is likely to raise a warning. */
  980. ret = InterlockedIncrement((volatile long *)addr);
  981. #elif defined(__GNUC__) \
  982. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  983. && !defined(NO_ATOMICS)
  984. ret = __sync_add_and_fetch(addr, 1);
  985. #else
  986. mg_global_lock();
  987. ret = (++(*addr));
  988. mg_global_unlock();
  989. #endif
  990. return ret;
  991. }
  992. FUNCTION_MAY_BE_UNUSED
  993. static int
  994. mg_atomic_dec(volatile int *addr)
  995. {
  996. int ret;
  997. #if defined(_WIN32) && !defined(NO_ATOMICS)
  998. /* Depending on the SDK, this function uses either
  999. * (volatile unsigned int *) or (volatile LONG *),
  1000. * so whatever you use, the other SDK is likely to raise a warning. */
  1001. ret = InterlockedDecrement((volatile long *)addr);
  1002. #elif defined(__GNUC__) \
  1003. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1004. && !defined(NO_ATOMICS)
  1005. ret = __sync_sub_and_fetch(addr, 1);
  1006. #else
  1007. mg_global_lock();
  1008. ret = (--(*addr));
  1009. mg_global_unlock();
  1010. #endif
  1011. return ret;
  1012. }
  1013. #if defined(USE_SERVER_STATS)
  1014. static int64_t
  1015. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1016. {
  1017. int64_t ret;
  1018. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1019. ret = InterlockedAdd64(addr, value);
  1020. #elif defined(__GNUC__) \
  1021. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1022. && !defined(NO_ATOMICS)
  1023. ret = __sync_add_and_fetch(addr, value);
  1024. #else
  1025. mg_global_lock();
  1026. *addr += value;
  1027. ret = (*addr);
  1028. mg_global_unlock();
  1029. #endif
  1030. return ret;
  1031. }
  1032. #endif
  1033. #if defined(GCC_DIAGNOSTIC)
  1034. /* Show no warning in case system functions are not used. */
  1035. #pragma GCC diagnostic pop
  1036. #endif /* defined(GCC_DIAGNOSTIC) */
  1037. #if defined(__clang__)
  1038. /* Show no warning in case system functions are not used. */
  1039. #pragma clang diagnostic pop
  1040. #endif
  1041. #if defined(USE_SERVER_STATS)
  1042. struct mg_memory_stat {
  1043. volatile int64_t totalMemUsed;
  1044. volatile int64_t maxMemUsed;
  1045. volatile int blockCount;
  1046. };
  1047. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1048. static void *
  1049. mg_malloc_ex(size_t size,
  1050. struct mg_context *ctx,
  1051. const char *file,
  1052. unsigned line)
  1053. {
  1054. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1055. void *memory = 0;
  1056. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1057. #if defined(MEMORY_DEBUGGING)
  1058. char mallocStr[256];
  1059. #else
  1060. (void)file;
  1061. (void)line;
  1062. #endif
  1063. if (data) {
  1064. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1065. if (mmem > mstat->maxMemUsed) {
  1066. /* could use atomic compare exchange, but this
  1067. * seems overkill for statistics data */
  1068. mstat->maxMemUsed = mmem;
  1069. }
  1070. mg_atomic_inc(&mstat->blockCount);
  1071. ((uintptr_t *)data)[0] = size;
  1072. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1073. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1074. }
  1075. #if defined(MEMORY_DEBUGGING)
  1076. sprintf(mallocStr,
  1077. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1078. memory,
  1079. (unsigned long)size,
  1080. (unsigned long)mstat->totalMemUsed,
  1081. (unsigned long)mstat->blockCount,
  1082. file,
  1083. line);
  1084. #if defined(_WIN32)
  1085. OutputDebugStringA(mallocStr);
  1086. #else
  1087. DEBUG_TRACE("%s", mallocStr);
  1088. #endif
  1089. #endif
  1090. return memory;
  1091. }
  1092. static void *
  1093. mg_calloc_ex(size_t count,
  1094. size_t size,
  1095. struct mg_context *ctx,
  1096. const char *file,
  1097. unsigned line)
  1098. {
  1099. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1100. if (data) {
  1101. memset(data, 0, size * count);
  1102. }
  1103. return data;
  1104. }
  1105. static void
  1106. mg_free_ex(void *memory, const char *file, unsigned line)
  1107. {
  1108. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1109. #if defined(MEMORY_DEBUGGING)
  1110. char mallocStr[256];
  1111. #else
  1112. (void)file;
  1113. (void)line;
  1114. #endif
  1115. if (memory) {
  1116. uintptr_t size = ((uintptr_t *)data)[0];
  1117. struct mg_memory_stat *mstat =
  1118. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1119. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1120. mg_atomic_dec(&mstat->blockCount);
  1121. #if defined(MEMORY_DEBUGGING)
  1122. sprintf(mallocStr,
  1123. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1124. memory,
  1125. (unsigned long)size,
  1126. (unsigned long)mstat->totalMemUsed,
  1127. (unsigned long)mstat->blockCount,
  1128. file,
  1129. line);
  1130. #if defined(_WIN32)
  1131. OutputDebugStringA(mallocStr);
  1132. #else
  1133. DEBUG_TRACE("%s", mallocStr);
  1134. #endif
  1135. #endif
  1136. free(data);
  1137. }
  1138. }
  1139. static void *
  1140. mg_realloc_ex(void *memory,
  1141. size_t newsize,
  1142. struct mg_context *ctx,
  1143. const char *file,
  1144. unsigned line)
  1145. {
  1146. void *data;
  1147. void *_realloc;
  1148. uintptr_t oldsize;
  1149. #if defined(MEMORY_DEBUGGING)
  1150. char mallocStr[256];
  1151. #else
  1152. (void)file;
  1153. (void)line;
  1154. #endif
  1155. if (newsize) {
  1156. if (memory) {
  1157. /* Reallocate existing block */
  1158. struct mg_memory_stat *mstat;
  1159. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1160. oldsize = ((uintptr_t *)data)[0];
  1161. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1162. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1163. if (_realloc) {
  1164. data = _realloc;
  1165. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1166. #if defined(MEMORY_DEBUGGING)
  1167. sprintf(mallocStr,
  1168. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1169. memory,
  1170. (unsigned long)oldsize,
  1171. (unsigned long)mstat->totalMemUsed,
  1172. (unsigned long)mstat->blockCount,
  1173. file,
  1174. line);
  1175. #if defined(_WIN32)
  1176. OutputDebugStringA(mallocStr);
  1177. #else
  1178. DEBUG_TRACE("%s", mallocStr);
  1179. #endif
  1180. #endif
  1181. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1182. #if defined(MEMORY_DEBUGGING)
  1183. sprintf(mallocStr,
  1184. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1185. memory,
  1186. (unsigned long)newsize,
  1187. (unsigned long)mstat->totalMemUsed,
  1188. (unsigned long)mstat->blockCount,
  1189. file,
  1190. line);
  1191. #if defined(_WIN32)
  1192. OutputDebugStringA(mallocStr);
  1193. #else
  1194. DEBUG_TRACE("%s", mallocStr);
  1195. #endif
  1196. #endif
  1197. *(uintptr_t *)data = newsize;
  1198. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1199. } else {
  1200. #if defined(MEMORY_DEBUGGING)
  1201. #if defined(_WIN32)
  1202. OutputDebugStringA("MEM: realloc failed\n");
  1203. #else
  1204. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1205. #endif
  1206. #endif
  1207. return _realloc;
  1208. }
  1209. } else {
  1210. /* Allocate new block */
  1211. data = mg_malloc_ex(newsize, ctx, file, line);
  1212. }
  1213. } else {
  1214. /* Free existing block */
  1215. data = 0;
  1216. mg_free_ex(memory, file, line);
  1217. }
  1218. return data;
  1219. }
  1220. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1221. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1222. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1223. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1224. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1225. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1226. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1227. #else /* USE_SERVER_STATS */
  1228. static __inline void *
  1229. mg_malloc(size_t a)
  1230. {
  1231. return malloc(a);
  1232. }
  1233. static __inline void *
  1234. mg_calloc(size_t a, size_t b)
  1235. {
  1236. return calloc(a, b);
  1237. }
  1238. static __inline void *
  1239. mg_realloc(void *a, size_t b)
  1240. {
  1241. return realloc(a, b);
  1242. }
  1243. static __inline void
  1244. mg_free(void *a)
  1245. {
  1246. free(a);
  1247. }
  1248. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1249. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1250. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1251. #define mg_free_ctx(a, c) mg_free(a)
  1252. #endif /* USE_SERVER_STATS */
  1253. static void mg_vsnprintf(const struct mg_connection *conn,
  1254. int *truncated,
  1255. char *buf,
  1256. size_t buflen,
  1257. const char *fmt,
  1258. va_list ap);
  1259. static void mg_snprintf(const struct mg_connection *conn,
  1260. int *truncated,
  1261. char *buf,
  1262. size_t buflen,
  1263. PRINTF_FORMAT_STRING(const char *fmt),
  1264. ...) PRINTF_ARGS(5, 6);
  1265. /* This following lines are just meant as a reminder to use the mg-functions
  1266. * for memory management */
  1267. #if defined(malloc)
  1268. #undef malloc
  1269. #endif
  1270. #if defined(calloc)
  1271. #undef calloc
  1272. #endif
  1273. #if defined(realloc)
  1274. #undef realloc
  1275. #endif
  1276. #if defined(free)
  1277. #undef free
  1278. #endif
  1279. #if defined(snprintf)
  1280. #undef snprintf
  1281. #endif
  1282. #if defined(vsnprintf)
  1283. #undef vsnprintf
  1284. #endif
  1285. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1286. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1287. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1288. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1289. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1290. #if defined(_WIN32)
  1291. /* vsnprintf must not be used in any system,
  1292. * but this define only works well for Windows. */
  1293. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1294. #endif
  1295. /* mg_init_library counter */
  1296. static int mg_init_library_called = 0;
  1297. #if !defined(NO_SSL)
  1298. static int mg_ssl_initialized = 0;
  1299. #endif
  1300. static pthread_key_t sTlsKey; /* Thread local storage index */
  1301. static int thread_idx_max = 0;
  1302. #if defined(MG_LEGACY_INTERFACE)
  1303. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1304. #endif
  1305. struct mg_workerTLS {
  1306. int is_master;
  1307. unsigned long thread_idx;
  1308. void *user_ptr;
  1309. #if defined(_WIN32)
  1310. HANDLE pthread_cond_helper_mutex;
  1311. struct mg_workerTLS *next_waiting_thread;
  1312. #endif
  1313. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1314. char txtbuf[4];
  1315. #endif
  1316. };
  1317. #if defined(GCC_DIAGNOSTIC)
  1318. /* Show no warning in case system functions are not used. */
  1319. #pragma GCC diagnostic push
  1320. #pragma GCC diagnostic ignored "-Wunused-function"
  1321. #endif /* defined(GCC_DIAGNOSTIC) */
  1322. #if defined(__clang__)
  1323. /* Show no warning in case system functions are not used. */
  1324. #pragma clang diagnostic push
  1325. #pragma clang diagnostic ignored "-Wunused-function"
  1326. #endif
  1327. /* Get a unique thread ID as unsigned long, independent from the data type
  1328. * of thread IDs defined by the operating system API.
  1329. * If two calls to mg_current_thread_id return the same value, they calls
  1330. * are done from the same thread. If they return different values, they are
  1331. * done from different threads. (Provided this function is used in the same
  1332. * process context and threads are not repeatedly created and deleted, but
  1333. * CivetWeb does not do that).
  1334. * This function must match the signature required for SSL id callbacks:
  1335. * CRYPTO_set_id_callback
  1336. */
  1337. FUNCTION_MAY_BE_UNUSED
  1338. static unsigned long
  1339. mg_current_thread_id(void)
  1340. {
  1341. #if defined(_WIN32)
  1342. return GetCurrentThreadId();
  1343. #else
  1344. #if defined(__clang__)
  1345. #pragma clang diagnostic push
  1346. #pragma clang diagnostic ignored "-Wunreachable-code"
  1347. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1348. * or not, so one of the two conditions will be unreachable by construction.
  1349. * Unfortunately the C standard does not define a way to check this at
  1350. * compile time, since the #if preprocessor conditions can not use the sizeof
  1351. * operator as an argument. */
  1352. #endif
  1353. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1354. /* This is the problematic case for CRYPTO_set_id_callback:
  1355. * The OS pthread_t can not be cast to unsigned long. */
  1356. struct mg_workerTLS *tls =
  1357. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1358. if (tls == NULL) {
  1359. /* SSL called from an unknown thread: Create some thread index.
  1360. */
  1361. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1362. tls->is_master = -2; /* -2 means "3rd party thread" */
  1363. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1364. pthread_setspecific(sTlsKey, tls);
  1365. }
  1366. return tls->thread_idx;
  1367. } else {
  1368. /* pthread_t may be any data type, so a simple cast to unsigned long
  1369. * can rise a warning/error, depending on the platform.
  1370. * Here memcpy is used as an anything-to-anything cast. */
  1371. unsigned long ret = 0;
  1372. pthread_t t = pthread_self();
  1373. memcpy(&ret, &t, sizeof(pthread_t));
  1374. return ret;
  1375. }
  1376. #if defined(__clang__)
  1377. #pragma clang diagnostic pop
  1378. #endif
  1379. #endif
  1380. }
  1381. FUNCTION_MAY_BE_UNUSED
  1382. static uint64_t
  1383. mg_get_current_time_ns(void)
  1384. {
  1385. struct timespec tsnow;
  1386. clock_gettime(CLOCK_REALTIME, &tsnow);
  1387. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1388. }
  1389. #if defined(GCC_DIAGNOSTIC)
  1390. /* Show no warning in case system functions are not used. */
  1391. #pragma GCC diagnostic pop
  1392. #endif /* defined(GCC_DIAGNOSTIC) */
  1393. #if defined(__clang__)
  1394. /* Show no warning in case system functions are not used. */
  1395. #pragma clang diagnostic pop
  1396. #endif
  1397. #if defined(NEED_DEBUG_TRACE_FUNC)
  1398. static void
  1399. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1400. {
  1401. va_list args;
  1402. uint64_t nsnow;
  1403. static uint64_t nslast;
  1404. struct timespec tsnow;
  1405. /* Get some operating system independent thread id */
  1406. unsigned long thread_id = mg_current_thread_id();
  1407. clock_gettime(CLOCK_REALTIME, &tsnow);
  1408. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1409. + ((uint64_t)tsnow.tv_nsec);
  1410. if (!nslast) {
  1411. nslast = nsnow;
  1412. }
  1413. flockfile(stdout);
  1414. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1415. (unsigned long)tsnow.tv_sec,
  1416. (unsigned long)tsnow.tv_nsec,
  1417. nsnow - nslast,
  1418. thread_id,
  1419. func,
  1420. line);
  1421. va_start(args, fmt);
  1422. vprintf(fmt, args);
  1423. va_end(args);
  1424. putchar('\n');
  1425. fflush(stdout);
  1426. funlockfile(stdout);
  1427. nslast = nsnow;
  1428. }
  1429. #endif /* NEED_DEBUG_TRACE_FUNC */
  1430. #define MD5_STATIC static
  1431. #include "md5.inl"
  1432. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1433. #if defined(NO_SOCKLEN_T)
  1434. typedef int socklen_t;
  1435. #endif /* NO_SOCKLEN_T */
  1436. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1437. #if !defined(MSG_NOSIGNAL)
  1438. #define MSG_NOSIGNAL (0)
  1439. #endif
  1440. #if defined(NO_SSL)
  1441. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1442. typedef struct SSL_CTX SSL_CTX;
  1443. #else
  1444. #if defined(NO_SSL_DL)
  1445. #include <openssl/bn.h>
  1446. #include <openssl/conf.h>
  1447. #include <openssl/crypto.h>
  1448. #include <openssl/dh.h>
  1449. #include <openssl/engine.h>
  1450. #include <openssl/err.h>
  1451. #include <openssl/opensslv.h>
  1452. #include <openssl/pem.h>
  1453. #include <openssl/ssl.h>
  1454. #include <openssl/tls1.h>
  1455. #include <openssl/x509.h>
  1456. #if defined(WOLFSSL_VERSION)
  1457. /* Additional defines for WolfSSL, see
  1458. * https://github.com/civetweb/civetweb/issues/583 */
  1459. #include "wolfssl_extras.inl"
  1460. #endif
  1461. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1462. /* If OpenSSL headers are included, automatically select the API version */
  1463. #if !defined(OPENSSL_API_1_1)
  1464. #define OPENSSL_API_1_1
  1465. #endif
  1466. #define OPENSSL_REMOVE_THREAD_STATE()
  1467. #else
  1468. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1469. #endif
  1470. #else
  1471. /* SSL loaded dynamically from DLL.
  1472. * I put the prototypes here to be independent from OpenSSL source
  1473. * installation. */
  1474. typedef struct ssl_st SSL;
  1475. typedef struct ssl_method_st SSL_METHOD;
  1476. typedef struct ssl_ctx_st SSL_CTX;
  1477. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1478. typedef struct x509_name X509_NAME;
  1479. typedef struct asn1_integer ASN1_INTEGER;
  1480. typedef struct bignum BIGNUM;
  1481. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1482. typedef struct evp_md EVP_MD;
  1483. typedef struct x509 X509;
  1484. #define SSL_CTRL_OPTIONS (32)
  1485. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1486. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1487. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1488. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1489. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1490. #define SSL_VERIFY_NONE (0)
  1491. #define SSL_VERIFY_PEER (1)
  1492. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1493. #define SSL_VERIFY_CLIENT_ONCE (4)
  1494. #define SSL_OP_ALL (0x80000BFFul)
  1495. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1496. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1497. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1498. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1499. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1500. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1501. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1502. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1503. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1504. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1505. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1506. #define SSL_CB_HANDSHAKE_START (0x10)
  1507. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1508. #define SSL_ERROR_NONE (0)
  1509. #define SSL_ERROR_SSL (1)
  1510. #define SSL_ERROR_WANT_READ (2)
  1511. #define SSL_ERROR_WANT_WRITE (3)
  1512. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1513. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1514. #define SSL_ERROR_ZERO_RETURN (6)
  1515. #define SSL_ERROR_WANT_CONNECT (7)
  1516. #define SSL_ERROR_WANT_ACCEPT (8)
  1517. #define TLSEXT_TYPE_server_name (0)
  1518. #define TLSEXT_NAMETYPE_host_name (0)
  1519. #define SSL_TLSEXT_ERR_OK (0)
  1520. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1521. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1522. #define SSL_TLSEXT_ERR_NOACK (3)
  1523. struct ssl_func {
  1524. const char *name; /* SSL function name */
  1525. void (*ptr)(void); /* Function pointer */
  1526. };
  1527. #if defined(OPENSSL_API_1_1)
  1528. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1529. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1530. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1531. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1532. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1533. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1534. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1535. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1536. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1537. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1538. #define OPENSSL_init_ssl \
  1539. (*(int (*)(uint64_t opts, \
  1540. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1541. .ptr)
  1542. #define SSL_CTX_use_PrivateKey_file \
  1543. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1544. #define SSL_CTX_use_certificate_file \
  1545. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1546. #define SSL_CTX_set_default_passwd_cb \
  1547. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1548. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1549. #define SSL_CTX_use_certificate_chain_file \
  1550. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1551. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1552. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1553. #define SSL_CTX_set_verify \
  1554. (*(void (*)(SSL_CTX *, \
  1555. int, \
  1556. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1557. .ptr)
  1558. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1559. #define SSL_CTX_load_verify_locations \
  1560. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1561. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1562. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1563. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1564. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1565. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1566. #define SSL_CIPHER_get_name \
  1567. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1568. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1569. #define SSL_CTX_set_session_id_context \
  1570. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1571. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1572. #define SSL_CTX_set_cipher_list \
  1573. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1574. #define SSL_CTX_set_options \
  1575. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1576. #define SSL_CTX_set_info_callback \
  1577. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1578. ssl_sw[32] \
  1579. .ptr)
  1580. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1581. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1582. #define SSL_CTX_callback_ctrl \
  1583. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1584. #define SSL_get_servername \
  1585. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1586. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1587. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1588. #define SSL_CTX_clear_options(ctx, op) \
  1589. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1590. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1591. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1592. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1593. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1594. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1595. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1596. SSL_CTX_callback_ctrl(ctx, \
  1597. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1598. (void (*)(void))cb)
  1599. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1600. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1601. #define SSL_set_tlsext_host_name(ctx, arg) \
  1602. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1603. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1604. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1605. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1606. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1607. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1608. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1609. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1610. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1611. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1612. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1613. #define X509_NAME_oneline \
  1614. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1615. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1616. #define EVP_get_digestbyname \
  1617. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1618. #define EVP_Digest \
  1619. (*(int (*)( \
  1620. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1621. crypto_sw[9] \
  1622. .ptr)
  1623. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1624. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1625. #define ASN1_INTEGER_to_BN \
  1626. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1627. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1628. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1629. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1630. #define OPENSSL_free(a) CRYPTO_free(a)
  1631. #define OPENSSL_REMOVE_THREAD_STATE()
  1632. /* init_ssl_ctx() function updates this array.
  1633. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1634. * of respective functions. The macros above (like SSL_connect()) are really
  1635. * just calling these functions indirectly via the pointer. */
  1636. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1637. {"SSL_accept", NULL},
  1638. {"SSL_connect", NULL},
  1639. {"SSL_read", NULL},
  1640. {"SSL_write", NULL},
  1641. {"SSL_get_error", NULL},
  1642. {"SSL_set_fd", NULL},
  1643. {"SSL_new", NULL},
  1644. {"SSL_CTX_new", NULL},
  1645. {"TLS_server_method", NULL},
  1646. {"OPENSSL_init_ssl", NULL},
  1647. {"SSL_CTX_use_PrivateKey_file", NULL},
  1648. {"SSL_CTX_use_certificate_file", NULL},
  1649. {"SSL_CTX_set_default_passwd_cb", NULL},
  1650. {"SSL_CTX_free", NULL},
  1651. {"SSL_CTX_use_certificate_chain_file", NULL},
  1652. {"TLS_client_method", NULL},
  1653. {"SSL_pending", NULL},
  1654. {"SSL_CTX_set_verify", NULL},
  1655. {"SSL_shutdown", NULL},
  1656. {"SSL_CTX_load_verify_locations", NULL},
  1657. {"SSL_CTX_set_default_verify_paths", NULL},
  1658. {"SSL_CTX_set_verify_depth", NULL},
  1659. {"SSL_get_peer_certificate", NULL},
  1660. {"SSL_get_version", NULL},
  1661. {"SSL_get_current_cipher", NULL},
  1662. {"SSL_CIPHER_get_name", NULL},
  1663. {"SSL_CTX_check_private_key", NULL},
  1664. {"SSL_CTX_set_session_id_context", NULL},
  1665. {"SSL_CTX_ctrl", NULL},
  1666. {"SSL_CTX_set_cipher_list", NULL},
  1667. {"SSL_CTX_set_options", NULL},
  1668. {"SSL_CTX_set_info_callback", NULL},
  1669. {"SSL_get_ex_data", NULL},
  1670. {"SSL_set_ex_data", NULL},
  1671. {"SSL_CTX_callback_ctrl", NULL},
  1672. {"SSL_get_servername", NULL},
  1673. {"SSL_set_SSL_CTX", NULL},
  1674. {"SSL_ctrl", NULL},
  1675. {NULL, NULL}};
  1676. /* Similar array as ssl_sw. These functions could be located in different
  1677. * lib. */
  1678. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1679. {"ERR_error_string", NULL},
  1680. {"CONF_modules_unload", NULL},
  1681. {"X509_free", NULL},
  1682. {"X509_get_subject_name", NULL},
  1683. {"X509_get_issuer_name", NULL},
  1684. {"X509_NAME_oneline", NULL},
  1685. {"X509_get_serialNumber", NULL},
  1686. {"EVP_get_digestbyname", NULL},
  1687. {"EVP_Digest", NULL},
  1688. {"i2d_X509", NULL},
  1689. {"BN_bn2hex", NULL},
  1690. {"ASN1_INTEGER_to_BN", NULL},
  1691. {"BN_free", NULL},
  1692. {"CRYPTO_free", NULL},
  1693. {"ERR_clear_error", NULL},
  1694. {NULL, NULL}};
  1695. #else
  1696. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1697. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1698. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1699. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1700. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1701. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1702. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1703. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1704. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1705. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1706. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1707. #define SSL_CTX_use_PrivateKey_file \
  1708. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1709. #define SSL_CTX_use_certificate_file \
  1710. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1711. #define SSL_CTX_set_default_passwd_cb \
  1712. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1713. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1714. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1715. #define SSL_CTX_use_certificate_chain_file \
  1716. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1717. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1718. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1719. #define SSL_CTX_set_verify \
  1720. (*(void (*)(SSL_CTX *, \
  1721. int, \
  1722. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1723. .ptr)
  1724. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1725. #define SSL_CTX_load_verify_locations \
  1726. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1727. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1728. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1729. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1730. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1731. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1732. #define SSL_CIPHER_get_name \
  1733. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1734. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1735. #define SSL_CTX_set_session_id_context \
  1736. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1737. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1738. #define SSL_CTX_set_cipher_list \
  1739. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1740. #define SSL_CTX_set_info_callback \
  1741. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1742. .ptr)
  1743. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1744. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1745. #define SSL_CTX_callback_ctrl \
  1746. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1747. #define SSL_get_servername \
  1748. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1749. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1750. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1751. #define SSL_CTX_set_options(ctx, op) \
  1752. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1753. #define SSL_CTX_clear_options(ctx, op) \
  1754. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1755. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1756. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1757. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1758. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1759. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1760. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1761. SSL_CTX_callback_ctrl(ctx, \
  1762. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1763. (void (*)(void))cb)
  1764. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1765. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1766. #define SSL_set_tlsext_host_name(ctx, arg) \
  1767. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1768. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1769. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1770. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1771. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1772. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1773. #define CRYPTO_set_locking_callback \
  1774. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1775. #define CRYPTO_set_id_callback \
  1776. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1777. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1778. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1779. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1780. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1781. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1782. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1783. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1784. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1785. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1786. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1787. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1788. #define X509_NAME_oneline \
  1789. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1790. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1791. #define i2c_ASN1_INTEGER \
  1792. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1793. #define EVP_get_digestbyname \
  1794. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1795. #define EVP_Digest \
  1796. (*(int (*)( \
  1797. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1798. crypto_sw[18] \
  1799. .ptr)
  1800. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1801. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1802. #define ASN1_INTEGER_to_BN \
  1803. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1804. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1805. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1806. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1807. #define OPENSSL_free(a) CRYPTO_free(a)
  1808. /* use here ERR_remove_state,
  1809. * while on some platforms function is not included into library due to
  1810. * deprication */
  1811. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1812. /* init_ssl_ctx() function updates this array.
  1813. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1814. * of respective functions. The macros above (like SSL_connect()) are really
  1815. * just calling these functions indirectly via the pointer. */
  1816. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1817. {"SSL_accept", NULL},
  1818. {"SSL_connect", NULL},
  1819. {"SSL_read", NULL},
  1820. {"SSL_write", NULL},
  1821. {"SSL_get_error", NULL},
  1822. {"SSL_set_fd", NULL},
  1823. {"SSL_new", NULL},
  1824. {"SSL_CTX_new", NULL},
  1825. {"SSLv23_server_method", NULL},
  1826. {"SSL_library_init", NULL},
  1827. {"SSL_CTX_use_PrivateKey_file", NULL},
  1828. {"SSL_CTX_use_certificate_file", NULL},
  1829. {"SSL_CTX_set_default_passwd_cb", NULL},
  1830. {"SSL_CTX_free", NULL},
  1831. {"SSL_load_error_strings", NULL},
  1832. {"SSL_CTX_use_certificate_chain_file", NULL},
  1833. {"SSLv23_client_method", NULL},
  1834. {"SSL_pending", NULL},
  1835. {"SSL_CTX_set_verify", NULL},
  1836. {"SSL_shutdown", NULL},
  1837. {"SSL_CTX_load_verify_locations", NULL},
  1838. {"SSL_CTX_set_default_verify_paths", NULL},
  1839. {"SSL_CTX_set_verify_depth", NULL},
  1840. {"SSL_get_peer_certificate", NULL},
  1841. {"SSL_get_version", NULL},
  1842. {"SSL_get_current_cipher", NULL},
  1843. {"SSL_CIPHER_get_name", NULL},
  1844. {"SSL_CTX_check_private_key", NULL},
  1845. {"SSL_CTX_set_session_id_context", NULL},
  1846. {"SSL_CTX_ctrl", NULL},
  1847. {"SSL_CTX_set_cipher_list", NULL},
  1848. {"SSL_CTX_set_info_callback", NULL},
  1849. {"SSL_get_ex_data", NULL},
  1850. {"SSL_set_ex_data", NULL},
  1851. {"SSL_CTX_callback_ctrl", NULL},
  1852. {"SSL_get_servername", NULL},
  1853. {"SSL_set_SSL_CTX", NULL},
  1854. {"SSL_ctrl", NULL},
  1855. {NULL, NULL}};
  1856. /* Similar array as ssl_sw. These functions could be located in different
  1857. * lib. */
  1858. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1859. {"CRYPTO_set_locking_callback", NULL},
  1860. {"CRYPTO_set_id_callback", NULL},
  1861. {"ERR_get_error", NULL},
  1862. {"ERR_error_string", NULL},
  1863. {"ERR_remove_state", NULL},
  1864. {"ERR_free_strings", NULL},
  1865. {"ENGINE_cleanup", NULL},
  1866. {"CONF_modules_unload", NULL},
  1867. {"CRYPTO_cleanup_all_ex_data", NULL},
  1868. {"EVP_cleanup", NULL},
  1869. {"X509_free", NULL},
  1870. {"X509_get_subject_name", NULL},
  1871. {"X509_get_issuer_name", NULL},
  1872. {"X509_NAME_oneline", NULL},
  1873. {"X509_get_serialNumber", NULL},
  1874. {"i2c_ASN1_INTEGER", NULL},
  1875. {"EVP_get_digestbyname", NULL},
  1876. {"EVP_Digest", NULL},
  1877. {"i2d_X509", NULL},
  1878. {"BN_bn2hex", NULL},
  1879. {"ASN1_INTEGER_to_BN", NULL},
  1880. {"BN_free", NULL},
  1881. {"CRYPTO_free", NULL},
  1882. {"ERR_clear_error", NULL},
  1883. {NULL, NULL}};
  1884. #endif /* OPENSSL_API_1_1 */
  1885. #endif /* NO_SSL_DL */
  1886. #endif /* NO_SSL */
  1887. #if !defined(NO_CACHING)
  1888. static const char month_names[][4] = {"Jan",
  1889. "Feb",
  1890. "Mar",
  1891. "Apr",
  1892. "May",
  1893. "Jun",
  1894. "Jul",
  1895. "Aug",
  1896. "Sep",
  1897. "Oct",
  1898. "Nov",
  1899. "Dec"};
  1900. #endif /* !NO_CACHING */
  1901. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1902. * the
  1903. * union u. */
  1904. union usa {
  1905. struct sockaddr sa;
  1906. struct sockaddr_in sin;
  1907. #if defined(USE_IPV6)
  1908. struct sockaddr_in6 sin6;
  1909. #endif
  1910. };
  1911. /* Describes a string (chunk of memory). */
  1912. struct vec {
  1913. const char *ptr;
  1914. size_t len;
  1915. };
  1916. struct mg_file_stat {
  1917. /* File properties filled by mg_stat: */
  1918. uint64_t size;
  1919. time_t last_modified;
  1920. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1921. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1922. * case we need a "Content-Eencoding: gzip" header */
  1923. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1924. };
  1925. struct mg_file_in_memory {
  1926. char *p;
  1927. uint32_t pos;
  1928. char mode;
  1929. };
  1930. struct mg_file_access {
  1931. /* File properties filled by mg_fopen: */
  1932. FILE *fp;
  1933. #if defined(MG_USE_OPEN_FILE)
  1934. /* TODO (low): Remove obsolete "file in memory" implementation.
  1935. * In an "early 2017" discussion at Google groups
  1936. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1937. * we decided to get rid of this feature (after some fade-out
  1938. * phase). */
  1939. const char *membuf;
  1940. #endif
  1941. };
  1942. struct mg_file {
  1943. struct mg_file_stat stat;
  1944. struct mg_file_access access;
  1945. };
  1946. #if defined(MG_USE_OPEN_FILE)
  1947. #define STRUCT_FILE_INITIALIZER \
  1948. { \
  1949. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1950. { \
  1951. (FILE *)NULL, (const char *)NULL \
  1952. } \
  1953. }
  1954. #else
  1955. #define STRUCT_FILE_INITIALIZER \
  1956. { \
  1957. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1958. { \
  1959. (FILE *)NULL \
  1960. } \
  1961. }
  1962. #endif
  1963. /* Describes listening socket, or socket which was accept()-ed by the master
  1964. * thread and queued for future handling by the worker thread. */
  1965. struct socket {
  1966. SOCKET sock; /* Listening socket */
  1967. union usa lsa; /* Local socket address */
  1968. union usa rsa; /* Remote socket address */
  1969. unsigned char is_ssl; /* Is port SSL-ed */
  1970. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1971. * port */
  1972. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1973. };
  1974. /* Enum const for all options must be in sync with
  1975. * static struct mg_option config_options[]
  1976. * This is tested in the unit test (test/private.c)
  1977. * "Private Config Options"
  1978. */
  1979. enum {
  1980. /* Once for each server */
  1981. LISTENING_PORTS,
  1982. NUM_THREADS,
  1983. RUN_AS_USER,
  1984. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1985. * socket option typedef TCP_NODELAY. */
  1986. MAX_REQUEST_SIZE,
  1987. LINGER_TIMEOUT,
  1988. #if defined(__linux__)
  1989. ALLOW_SENDFILE_CALL,
  1990. #endif
  1991. #if defined(_WIN32)
  1992. CASE_SENSITIVE_FILES,
  1993. #endif
  1994. THROTTLE,
  1995. ACCESS_LOG_FILE,
  1996. ERROR_LOG_FILE,
  1997. ENABLE_KEEP_ALIVE,
  1998. REQUEST_TIMEOUT,
  1999. KEEP_ALIVE_TIMEOUT,
  2000. #if defined(USE_WEBSOCKET)
  2001. WEBSOCKET_TIMEOUT,
  2002. ENABLE_WEBSOCKET_PING_PONG,
  2003. #endif
  2004. DECODE_URL,
  2005. #if defined(USE_LUA)
  2006. LUA_BACKGROUND_SCRIPT,
  2007. LUA_BACKGROUND_SCRIPT_PARAMS,
  2008. #endif
  2009. #if defined(USE_TIMERS)
  2010. CGI_TIMEOUT,
  2011. #endif
  2012. /* Once for each domain */
  2013. DOCUMENT_ROOT,
  2014. CGI_EXTENSIONS,
  2015. CGI_ENVIRONMENT,
  2016. PUT_DELETE_PASSWORDS_FILE,
  2017. CGI_INTERPRETER,
  2018. PROTECT_URI,
  2019. AUTHENTICATION_DOMAIN,
  2020. ENABLE_AUTH_DOMAIN_CHECK,
  2021. SSI_EXTENSIONS,
  2022. ENABLE_DIRECTORY_LISTING,
  2023. GLOBAL_PASSWORDS_FILE,
  2024. INDEX_FILES,
  2025. ACCESS_CONTROL_LIST,
  2026. EXTRA_MIME_TYPES,
  2027. SSL_CERTIFICATE,
  2028. SSL_CERTIFICATE_CHAIN,
  2029. URL_REWRITE_PATTERN,
  2030. HIDE_FILES,
  2031. SSL_DO_VERIFY_PEER,
  2032. SSL_CA_PATH,
  2033. SSL_CA_FILE,
  2034. SSL_VERIFY_DEPTH,
  2035. SSL_DEFAULT_VERIFY_PATHS,
  2036. SSL_CIPHER_LIST,
  2037. SSL_PROTOCOL_VERSION,
  2038. SSL_SHORT_TRUST,
  2039. #if defined(USE_LUA)
  2040. LUA_PRELOAD_FILE,
  2041. LUA_SCRIPT_EXTENSIONS,
  2042. LUA_SERVER_PAGE_EXTENSIONS,
  2043. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2044. LUA_DEBUG_PARAMS,
  2045. #endif
  2046. #endif
  2047. #if defined(USE_DUKTAPE)
  2048. DUKTAPE_SCRIPT_EXTENSIONS,
  2049. #endif
  2050. #if defined(USE_WEBSOCKET)
  2051. WEBSOCKET_ROOT,
  2052. #endif
  2053. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2054. LUA_WEBSOCKET_EXTENSIONS,
  2055. #endif
  2056. ACCESS_CONTROL_ALLOW_ORIGIN,
  2057. ACCESS_CONTROL_ALLOW_METHODS,
  2058. ACCESS_CONTROL_ALLOW_HEADERS,
  2059. ERROR_PAGES,
  2060. #if !defined(NO_CACHING)
  2061. STATIC_FILE_MAX_AGE,
  2062. #endif
  2063. #if !defined(NO_SSL)
  2064. STRICT_HTTPS_MAX_AGE,
  2065. #endif
  2066. ADDITIONAL_HEADER,
  2067. ALLOW_INDEX_SCRIPT_SUB_RES,
  2068. #if defined(DAEMONIZE)
  2069. ENABLE_DAEMONIZE,
  2070. #endif
  2071. NUM_OPTIONS
  2072. };
  2073. /* Config option name, config types, default value.
  2074. * Must be in the same order as the enum const above.
  2075. */
  2076. static const struct mg_option config_options[] = {
  2077. /* Once for each server */
  2078. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2079. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2080. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2081. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2082. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2083. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2084. #if defined(__linux__)
  2085. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2086. #endif
  2087. #if defined(_WIN32)
  2088. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2089. #endif
  2090. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2091. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2092. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2093. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2094. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2095. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2096. #if defined(USE_WEBSOCKET)
  2097. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2098. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2099. #endif
  2100. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2101. #if defined(USE_LUA)
  2102. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2103. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2104. #endif
  2105. #if defined(USE_TIMERS)
  2106. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2107. #endif
  2108. /* Once for each domain */
  2109. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2110. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2111. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2112. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2113. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2114. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2115. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2116. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2117. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2118. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2119. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2120. {"index_files",
  2121. MG_CONFIG_TYPE_STRING_LIST,
  2122. #if defined(USE_LUA)
  2123. "index.xhtml,index.html,index.htm,"
  2124. "index.lp,index.lsp,index.lua,index.cgi,"
  2125. "index.shtml,index.php"},
  2126. #else
  2127. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2128. #endif
  2129. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2130. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2131. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2132. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2133. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2134. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2135. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2136. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2137. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2138. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2139. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2140. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2141. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2142. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2143. #if defined(USE_LUA)
  2144. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2145. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2146. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2147. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2148. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2149. #endif
  2150. #endif
  2151. #if defined(USE_DUKTAPE)
  2152. /* The support for duktape is still in alpha version state.
  2153. * The name of this config option might change. */
  2154. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2155. #endif
  2156. #if defined(USE_WEBSOCKET)
  2157. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2158. #endif
  2159. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2160. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2161. #endif
  2162. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2163. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2164. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2165. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2166. #if !defined(NO_CACHING)
  2167. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2168. #endif
  2169. #if !defined(NO_SSL)
  2170. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2171. #endif
  2172. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2173. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2174. #if defined(DAEMONIZE)
  2175. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2176. #endif
  2177. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2178. /* Check if the config_options and the corresponding enum have compatible
  2179. * sizes. */
  2180. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2181. == (NUM_OPTIONS + 1),
  2182. "config_options and enum not sync");
  2183. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2184. struct mg_handler_info {
  2185. /* Name/Pattern of the URI. */
  2186. char *uri;
  2187. size_t uri_len;
  2188. /* handler type */
  2189. int handler_type;
  2190. /* Handler for http/https or authorization requests. */
  2191. mg_request_handler handler;
  2192. unsigned int refcount;
  2193. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2194. pthread_cond_t
  2195. refcount_cond; /* Signaled when handler refcount is decremented */
  2196. /* Handler for ws/wss (websocket) requests. */
  2197. mg_websocket_connect_handler connect_handler;
  2198. mg_websocket_ready_handler ready_handler;
  2199. mg_websocket_data_handler data_handler;
  2200. mg_websocket_close_handler close_handler;
  2201. /* accepted subprotocols for ws/wss requests. */
  2202. struct mg_websocket_subprotocols *subprotocols;
  2203. /* Handler for authorization requests */
  2204. mg_authorization_handler auth_handler;
  2205. /* User supplied argument for the handler function. */
  2206. void *cbdata;
  2207. /* next handler in a linked list */
  2208. struct mg_handler_info *next;
  2209. };
  2210. enum {
  2211. CONTEXT_INVALID,
  2212. CONTEXT_SERVER,
  2213. CONTEXT_HTTP_CLIENT,
  2214. CONTEXT_WS_CLIENT
  2215. };
  2216. struct mg_domain_context {
  2217. SSL_CTX *ssl_ctx; /* SSL context */
  2218. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2219. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2220. /* Server nonce */
  2221. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2222. unsigned long nonce_count; /* Used nonces, used for authentication */
  2223. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2224. /* linked list of shared lua websockets */
  2225. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2226. #endif
  2227. /* Linked list of domains */
  2228. struct mg_domain_context *next;
  2229. };
  2230. struct mg_context {
  2231. /* Part 1 - Physical context:
  2232. * This holds threads, ports, timeouts, ...
  2233. * set for the entire server, independent from the
  2234. * addressed hostname.
  2235. */
  2236. /* Connection related */
  2237. int context_type; /* See CONTEXT_* above */
  2238. struct socket *listening_sockets;
  2239. struct mg_pollfd *listening_socket_fds;
  2240. unsigned int num_listening_sockets;
  2241. struct mg_connection *worker_connections; /* The connection struct, pre-
  2242. * allocated for each worker */
  2243. #if defined(USE_SERVER_STATS)
  2244. int active_connections;
  2245. int max_connections;
  2246. int64_t total_connections;
  2247. int64_t total_requests;
  2248. int64_t total_data_read;
  2249. int64_t total_data_written;
  2250. #endif
  2251. /* Thread related */
  2252. volatile int stop_flag; /* Should we stop event loop */
  2253. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2254. pthread_t masterthreadid; /* The master thread ID */
  2255. unsigned int
  2256. cfg_worker_threads; /* The number of configured worker threads. */
  2257. pthread_t *worker_threadids; /* The worker thread IDs */
  2258. /* Connection to thread dispatching */
  2259. #if defined(ALTERNATIVE_QUEUE)
  2260. struct socket *client_socks;
  2261. void **client_wait_events;
  2262. #else
  2263. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2264. volatile int sq_head; /* Head of the socket queue */
  2265. volatile int sq_tail; /* Tail of the socket queue */
  2266. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2267. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2268. #endif
  2269. /* Memory related */
  2270. unsigned int max_request_size; /* The max request size */
  2271. #if defined(USE_SERVER_STATS)
  2272. struct mg_memory_stat ctx_memory;
  2273. #endif
  2274. /* Operating system related */
  2275. char *systemName; /* What operating system is running */
  2276. time_t start_time; /* Server start time, used for authentication
  2277. * and for diagnstics. */
  2278. #if defined(USE_TIMERS)
  2279. struct ttimers *timers;
  2280. #endif
  2281. /* Lua specific: Background operations and shared websockets */
  2282. #if defined(USE_LUA)
  2283. void *lua_background_state;
  2284. #endif
  2285. /* Server nonce */
  2286. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2287. /* Server callbacks */
  2288. struct mg_callbacks callbacks; /* User-defined callback function */
  2289. void *user_data; /* User-defined data */
  2290. /* Part 2 - Logical domain:
  2291. * This holds hostname, TLS certificate, document root, ...
  2292. * set for a domain hosted at the server.
  2293. * There may be multiple domains hosted at one physical server.
  2294. * The default domain "dd" is the first element of a list of
  2295. * domains.
  2296. */
  2297. struct mg_domain_context dd; /* default domain */
  2298. };
  2299. #if defined(USE_SERVER_STATS)
  2300. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2301. static struct mg_memory_stat *
  2302. get_memory_stat(struct mg_context *ctx)
  2303. {
  2304. if (ctx) {
  2305. return &(ctx->ctx_memory);
  2306. }
  2307. return &mg_common_memory;
  2308. }
  2309. #endif
  2310. enum {
  2311. CONNECTION_TYPE_INVALID,
  2312. CONNECTION_TYPE_REQUEST,
  2313. CONNECTION_TYPE_RESPONSE
  2314. };
  2315. struct mg_connection {
  2316. int connection_type; /* see CONNECTION_TYPE_* above */
  2317. struct mg_request_info request_info;
  2318. struct mg_response_info response_info;
  2319. struct mg_context *phys_ctx;
  2320. struct mg_domain_context *dom_ctx;
  2321. #if defined(USE_SERVER_STATS)
  2322. int conn_state; /* 0 = undef, numerical value may change in different
  2323. * versions. For the current definition, see
  2324. * mg_get_connection_info_impl */
  2325. #endif
  2326. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2327. SSL *ssl; /* SSL descriptor */
  2328. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2329. struct socket client; /* Connected client */
  2330. time_t conn_birth_time; /* Time (wall clock) when connection was
  2331. * established */
  2332. struct timespec req_time; /* Time (since system start) when the request
  2333. * was received */
  2334. int64_t num_bytes_sent; /* Total bytes sent to client */
  2335. int64_t content_len; /* How many bytes of content can be read
  2336. * !is_chunked: Content-Length header value
  2337. * or -1 (until connection closed,
  2338. * not allowed for a request)
  2339. * is_chunked: >= 0, appended gradually
  2340. */
  2341. int64_t consumed_content; /* How many bytes of content have been read */
  2342. int is_chunked; /* Transfer-Encoding is chunked:
  2343. * 0 = not chunked,
  2344. * 1 = chunked, not yet, or some data read,
  2345. * 2 = chunked, has error,
  2346. * 3 = chunked, all data read except trailer,
  2347. * 4 = chunked, all data read
  2348. */
  2349. char *buf; /* Buffer for received data */
  2350. char *path_info; /* PATH_INFO part of the URL */
  2351. int must_close; /* 1 if connection must be closed */
  2352. int accept_gzip; /* 1 if gzip encoding is accepted */
  2353. int in_error_handler; /* 1 if in handler for user defined error
  2354. * pages */
  2355. #if defined(USE_WEBSOCKET)
  2356. int in_websocket_handling; /* 1 if in read_websocket */
  2357. #endif
  2358. int handled_requests; /* Number of requests handled by this connection
  2359. */
  2360. int buf_size; /* Buffer size */
  2361. int request_len; /* Size of the request + headers in a buffer */
  2362. int data_len; /* Total size of data in a buffer */
  2363. int status_code; /* HTTP reply status code, e.g. 200 */
  2364. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2365. * throttle */
  2366. time_t last_throttle_time; /* Last time throttled data was sent */
  2367. int last_throttle_bytes; /* Bytes sent this second */
  2368. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2369. * atomic transmissions for websockets */
  2370. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2371. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2372. #endif
  2373. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2374. * for quick access */
  2375. };
  2376. /* Directory entry */
  2377. struct de {
  2378. struct mg_connection *conn;
  2379. char *file_name;
  2380. struct mg_file_stat file;
  2381. };
  2382. #if defined(USE_WEBSOCKET)
  2383. static int is_websocket_protocol(const struct mg_connection *conn);
  2384. #else
  2385. #define is_websocket_protocol(conn) (0)
  2386. #endif
  2387. #define mg_cry_internal(conn, fmt, ...) \
  2388. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2389. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2390. const char *func,
  2391. unsigned line,
  2392. const char *fmt,
  2393. ...) PRINTF_ARGS(4, 5);
  2394. #if !defined(NO_THREAD_NAME)
  2395. #if defined(_WIN32) && defined(_MSC_VER)
  2396. /* Set the thread name for debugging purposes in Visual Studio
  2397. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2398. */
  2399. #pragma pack(push, 8)
  2400. typedef struct tagTHREADNAME_INFO {
  2401. DWORD dwType; /* Must be 0x1000. */
  2402. LPCSTR szName; /* Pointer to name (in user addr space). */
  2403. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2404. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2405. } THREADNAME_INFO;
  2406. #pragma pack(pop)
  2407. #elif defined(__linux__)
  2408. #include <sys/prctl.h>
  2409. #include <sys/sendfile.h>
  2410. #if defined(ALTERNATIVE_QUEUE)
  2411. #include <sys/eventfd.h>
  2412. #endif /* ALTERNATIVE_QUEUE */
  2413. #if defined(ALTERNATIVE_QUEUE)
  2414. static void *
  2415. event_create(void)
  2416. {
  2417. int evhdl = eventfd(0, EFD_CLOEXEC);
  2418. int *ret;
  2419. if (evhdl == -1) {
  2420. /* Linux uses -1 on error, Windows NULL. */
  2421. /* However, Linux does not return 0 on success either. */
  2422. return 0;
  2423. }
  2424. ret = (int *)mg_malloc(sizeof(int));
  2425. if (ret) {
  2426. *ret = evhdl;
  2427. } else {
  2428. (void)close(evhdl);
  2429. }
  2430. return (void *)ret;
  2431. }
  2432. static int
  2433. event_wait(void *eventhdl)
  2434. {
  2435. uint64_t u;
  2436. int evhdl, s;
  2437. if (!eventhdl) {
  2438. /* error */
  2439. return 0;
  2440. }
  2441. evhdl = *(int *)eventhdl;
  2442. s = (int)read(evhdl, &u, sizeof(u));
  2443. if (s != sizeof(u)) {
  2444. /* error */
  2445. return 0;
  2446. }
  2447. (void)u; /* the value is not required */
  2448. return 1;
  2449. }
  2450. static int
  2451. event_signal(void *eventhdl)
  2452. {
  2453. uint64_t u = 1;
  2454. int evhdl, s;
  2455. if (!eventhdl) {
  2456. /* error */
  2457. return 0;
  2458. }
  2459. evhdl = *(int *)eventhdl;
  2460. s = (int)write(evhdl, &u, sizeof(u));
  2461. if (s != sizeof(u)) {
  2462. /* error */
  2463. return 0;
  2464. }
  2465. return 1;
  2466. }
  2467. static void
  2468. event_destroy(void *eventhdl)
  2469. {
  2470. int evhdl;
  2471. if (!eventhdl) {
  2472. /* error */
  2473. return;
  2474. }
  2475. evhdl = *(int *)eventhdl;
  2476. close(evhdl);
  2477. mg_free(eventhdl);
  2478. }
  2479. #endif
  2480. #endif
  2481. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2482. struct posix_event {
  2483. pthread_mutex_t mutex;
  2484. pthread_cond_t cond;
  2485. int signaled;
  2486. };
  2487. static void *
  2488. event_create(void)
  2489. {
  2490. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2491. if (ret == 0) {
  2492. /* out of memory */
  2493. return 0;
  2494. }
  2495. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2496. /* pthread mutex not available */
  2497. mg_free(ret);
  2498. return 0;
  2499. }
  2500. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2501. /* pthread cond not available */
  2502. pthread_mutex_destroy(&(ret->mutex));
  2503. mg_free(ret);
  2504. return 0;
  2505. }
  2506. ret->signaled = 0;
  2507. return (void *)ret;
  2508. }
  2509. static int
  2510. event_wait(void *eventhdl)
  2511. {
  2512. struct posix_event *ev = (struct posix_event *)eventhdl;
  2513. pthread_mutex_lock(&(ev->mutex));
  2514. while (!ev->signaled) {
  2515. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2516. }
  2517. ev->signaled = 0;
  2518. pthread_mutex_unlock(&(ev->mutex));
  2519. return 1;
  2520. }
  2521. static int
  2522. event_signal(void *eventhdl)
  2523. {
  2524. struct posix_event *ev = (struct posix_event *)eventhdl;
  2525. pthread_mutex_lock(&(ev->mutex));
  2526. pthread_cond_signal(&(ev->cond));
  2527. ev->signaled = 1;
  2528. pthread_mutex_unlock(&(ev->mutex));
  2529. return 1;
  2530. }
  2531. static void
  2532. event_destroy(void *eventhdl)
  2533. {
  2534. struct posix_event *ev = (struct posix_event *)eventhdl;
  2535. pthread_cond_destroy(&(ev->cond));
  2536. pthread_mutex_destroy(&(ev->mutex));
  2537. mg_free(ev);
  2538. }
  2539. #endif
  2540. static void
  2541. mg_set_thread_name(const char *name)
  2542. {
  2543. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2544. mg_snprintf(
  2545. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2546. #if defined(_WIN32)
  2547. #if defined(_MSC_VER)
  2548. /* Windows and Visual Studio Compiler */
  2549. __try {
  2550. THREADNAME_INFO info;
  2551. info.dwType = 0x1000;
  2552. info.szName = threadName;
  2553. info.dwThreadID = ~0U;
  2554. info.dwFlags = 0;
  2555. RaiseException(0x406D1388,
  2556. 0,
  2557. sizeof(info) / sizeof(ULONG_PTR),
  2558. (ULONG_PTR *)&info);
  2559. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2560. }
  2561. #elif defined(__MINGW32__)
  2562. /* No option known to set thread name for MinGW */
  2563. #endif
  2564. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2565. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2566. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2567. #if defined(__MACH__)
  2568. /* OS X only current thread name can be changed */
  2569. (void)pthread_setname_np(threadName);
  2570. #else
  2571. (void)pthread_setname_np(pthread_self(), threadName);
  2572. #endif
  2573. #elif defined(__linux__)
  2574. /* on linux we can use the old prctl function */
  2575. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2576. #endif
  2577. }
  2578. #else /* !defined(NO_THREAD_NAME) */
  2579. void
  2580. mg_set_thread_name(const char *threadName)
  2581. {
  2582. }
  2583. #endif
  2584. #if defined(MG_LEGACY_INTERFACE)
  2585. const char **
  2586. mg_get_valid_option_names(void)
  2587. {
  2588. /* This function is deprecated. Use mg_get_valid_options instead. */
  2589. static const char
  2590. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2591. int i;
  2592. for (i = 0; config_options[i].name != NULL; i++) {
  2593. data[i * 2] = config_options[i].name;
  2594. data[i * 2 + 1] = config_options[i].default_value;
  2595. }
  2596. return data;
  2597. }
  2598. #endif
  2599. const struct mg_option *
  2600. mg_get_valid_options(void)
  2601. {
  2602. return config_options;
  2603. }
  2604. /* Do not open file (used in is_file_in_memory) */
  2605. #define MG_FOPEN_MODE_NONE (0)
  2606. /* Open file for read only access */
  2607. #define MG_FOPEN_MODE_READ (1)
  2608. /* Open file for writing, create and overwrite */
  2609. #define MG_FOPEN_MODE_WRITE (2)
  2610. /* Open file for writing, create and append */
  2611. #define MG_FOPEN_MODE_APPEND (4)
  2612. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2613. * output filep and return 1, otherwise return 0 and don't modify anything.
  2614. */
  2615. static int
  2616. open_file_in_memory(const struct mg_connection *conn,
  2617. const char *path,
  2618. struct mg_file *filep,
  2619. int mode)
  2620. {
  2621. #if defined(MG_USE_OPEN_FILE)
  2622. size_t size = 0;
  2623. const char *buf = NULL;
  2624. if (!conn) {
  2625. return 0;
  2626. }
  2627. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2628. return 0;
  2629. }
  2630. if (conn->phys_ctx->callbacks.open_file) {
  2631. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2632. if (buf != NULL) {
  2633. if (filep == NULL) {
  2634. /* This is a file in memory, but we cannot store the
  2635. * properties
  2636. * now.
  2637. * Called from "is_file_in_memory" function. */
  2638. return 1;
  2639. }
  2640. /* NOTE: override filep->size only on success. Otherwise, it
  2641. * might
  2642. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2643. filep->access.membuf = buf;
  2644. filep->access.fp = NULL;
  2645. /* Size was set by the callback */
  2646. filep->stat.size = size;
  2647. /* Assume the data may change during runtime by setting
  2648. * last_modified = now */
  2649. filep->stat.last_modified = time(NULL);
  2650. filep->stat.is_directory = 0;
  2651. filep->stat.is_gzipped = 0;
  2652. }
  2653. }
  2654. return (buf != NULL);
  2655. #else
  2656. (void)conn;
  2657. (void)path;
  2658. (void)filep;
  2659. (void)mode;
  2660. return 0;
  2661. #endif
  2662. }
  2663. static int
  2664. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2665. {
  2666. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2667. }
  2668. static int
  2669. is_file_opened(const struct mg_file_access *fileacc)
  2670. {
  2671. if (!fileacc) {
  2672. return 0;
  2673. }
  2674. #if defined(MG_USE_OPEN_FILE)
  2675. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2676. #else
  2677. return (fileacc->fp != NULL);
  2678. #endif
  2679. }
  2680. static int mg_stat(const struct mg_connection *conn,
  2681. const char *path,
  2682. struct mg_file_stat *filep);
  2683. /* mg_fopen will open a file either in memory or on the disk.
  2684. * The input parameter path is a string in UTF-8 encoding.
  2685. * The input parameter mode is MG_FOPEN_MODE_*
  2686. * On success, either fp or membuf will be set in the output
  2687. * struct file. All status members will also be set.
  2688. * The function returns 1 on success, 0 on error. */
  2689. static int
  2690. mg_fopen(const struct mg_connection *conn,
  2691. const char *path,
  2692. int mode,
  2693. struct mg_file *filep)
  2694. {
  2695. int found;
  2696. if (!filep) {
  2697. return 0;
  2698. }
  2699. filep->access.fp = NULL;
  2700. #if defined(MG_USE_OPEN_FILE)
  2701. filep->access.membuf = NULL;
  2702. #endif
  2703. if (!is_file_in_memory(conn, path)) {
  2704. /* filep is initialized in mg_stat: all fields with memset to,
  2705. * some fields like size and modification date with values */
  2706. found = mg_stat(conn, path, &(filep->stat));
  2707. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2708. /* file does not exist and will not be created */
  2709. return 0;
  2710. }
  2711. #if defined(_WIN32)
  2712. {
  2713. wchar_t wbuf[W_PATH_MAX];
  2714. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2715. switch (mode) {
  2716. case MG_FOPEN_MODE_READ:
  2717. filep->access.fp = _wfopen(wbuf, L"rb");
  2718. break;
  2719. case MG_FOPEN_MODE_WRITE:
  2720. filep->access.fp = _wfopen(wbuf, L"wb");
  2721. break;
  2722. case MG_FOPEN_MODE_APPEND:
  2723. filep->access.fp = _wfopen(wbuf, L"ab");
  2724. break;
  2725. }
  2726. }
  2727. #else
  2728. /* Linux et al already use unicode. No need to convert. */
  2729. switch (mode) {
  2730. case MG_FOPEN_MODE_READ:
  2731. filep->access.fp = fopen(path, "r");
  2732. break;
  2733. case MG_FOPEN_MODE_WRITE:
  2734. filep->access.fp = fopen(path, "w");
  2735. break;
  2736. case MG_FOPEN_MODE_APPEND:
  2737. filep->access.fp = fopen(path, "a");
  2738. break;
  2739. }
  2740. #endif
  2741. if (!found) {
  2742. /* File did not exist before fopen was called.
  2743. * Maybe it has been created now. Get stat info
  2744. * like creation time now. */
  2745. found = mg_stat(conn, path, &(filep->stat));
  2746. (void)found;
  2747. }
  2748. /* file is on disk */
  2749. return (filep->access.fp != NULL);
  2750. } else {
  2751. #if defined(MG_USE_OPEN_FILE)
  2752. /* is_file_in_memory returned true */
  2753. if (open_file_in_memory(conn, path, filep, mode)) {
  2754. /* file is in memory */
  2755. return (filep->access.membuf != NULL);
  2756. }
  2757. #endif
  2758. }
  2759. /* Open failed */
  2760. return 0;
  2761. }
  2762. /* return 0 on success, just like fclose */
  2763. static int
  2764. mg_fclose(struct mg_file_access *fileacc)
  2765. {
  2766. int ret = -1;
  2767. if (fileacc != NULL) {
  2768. if (fileacc->fp != NULL) {
  2769. ret = fclose(fileacc->fp);
  2770. #if defined(MG_USE_OPEN_FILE)
  2771. } else if (fileacc->membuf != NULL) {
  2772. ret = 0;
  2773. #endif
  2774. }
  2775. /* reset all members of fileacc */
  2776. memset(fileacc, 0, sizeof(*fileacc));
  2777. }
  2778. return ret;
  2779. }
  2780. static void
  2781. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2782. {
  2783. for (; *src != '\0' && n > 1; n--) {
  2784. *dst++ = *src++;
  2785. }
  2786. *dst = '\0';
  2787. }
  2788. static int
  2789. lowercase(const char *s)
  2790. {
  2791. return tolower((unsigned char)*s);
  2792. }
  2793. int
  2794. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2795. {
  2796. int diff = 0;
  2797. if (len > 0) {
  2798. do {
  2799. diff = lowercase(s1++) - lowercase(s2++);
  2800. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2801. }
  2802. return diff;
  2803. }
  2804. int
  2805. mg_strcasecmp(const char *s1, const char *s2)
  2806. {
  2807. int diff;
  2808. do {
  2809. diff = lowercase(s1++) - lowercase(s2++);
  2810. } while (diff == 0 && s1[-1] != '\0');
  2811. return diff;
  2812. }
  2813. static char *
  2814. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2815. {
  2816. char *p;
  2817. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2818. * defined */
  2819. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2820. mg_strlcpy(p, ptr, len + 1);
  2821. }
  2822. return p;
  2823. }
  2824. static char *
  2825. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2826. {
  2827. return mg_strndup_ctx(str, strlen(str), ctx);
  2828. }
  2829. static char *
  2830. mg_strdup(const char *str)
  2831. {
  2832. return mg_strndup_ctx(str, strlen(str), NULL);
  2833. }
  2834. static const char *
  2835. mg_strcasestr(const char *big_str, const char *small_str)
  2836. {
  2837. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2838. if (big_len >= small_len) {
  2839. for (i = 0; i <= (big_len - small_len); i++) {
  2840. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2841. return big_str + i;
  2842. }
  2843. }
  2844. }
  2845. return NULL;
  2846. }
  2847. /* Return null terminated string of given maximum length.
  2848. * Report errors if length is exceeded. */
  2849. static void
  2850. mg_vsnprintf(const struct mg_connection *conn,
  2851. int *truncated,
  2852. char *buf,
  2853. size_t buflen,
  2854. const char *fmt,
  2855. va_list ap)
  2856. {
  2857. int n, ok;
  2858. if (buflen == 0) {
  2859. if (truncated) {
  2860. *truncated = 1;
  2861. }
  2862. return;
  2863. }
  2864. #if defined(__clang__)
  2865. #pragma clang diagnostic push
  2866. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2867. /* Using fmt as a non-literal is intended here, since it is mostly called
  2868. * indirectly by mg_snprintf */
  2869. #endif
  2870. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2871. ok = (n >= 0) && ((size_t)n < buflen);
  2872. #if defined(__clang__)
  2873. #pragma clang diagnostic pop
  2874. #endif
  2875. if (ok) {
  2876. if (truncated) {
  2877. *truncated = 0;
  2878. }
  2879. } else {
  2880. if (truncated) {
  2881. *truncated = 1;
  2882. }
  2883. mg_cry_internal(conn,
  2884. "truncating vsnprintf buffer: [%.*s]",
  2885. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2886. buf);
  2887. n = (int)buflen - 1;
  2888. }
  2889. buf[n] = '\0';
  2890. }
  2891. static void
  2892. mg_snprintf(const struct mg_connection *conn,
  2893. int *truncated,
  2894. char *buf,
  2895. size_t buflen,
  2896. const char *fmt,
  2897. ...)
  2898. {
  2899. va_list ap;
  2900. va_start(ap, fmt);
  2901. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2902. va_end(ap);
  2903. }
  2904. static int
  2905. get_option_index(const char *name)
  2906. {
  2907. int i;
  2908. for (i = 0; config_options[i].name != NULL; i++) {
  2909. if (strcmp(config_options[i].name, name) == 0) {
  2910. return i;
  2911. }
  2912. }
  2913. return -1;
  2914. }
  2915. const char *
  2916. mg_get_option(const struct mg_context *ctx, const char *name)
  2917. {
  2918. int i;
  2919. if ((i = get_option_index(name)) == -1) {
  2920. return NULL;
  2921. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2922. return "";
  2923. } else {
  2924. return ctx->dd.config[i];
  2925. }
  2926. }
  2927. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2928. struct mg_context *
  2929. mg_get_context(const struct mg_connection *conn)
  2930. {
  2931. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2932. }
  2933. void *
  2934. mg_get_user_data(const struct mg_context *ctx)
  2935. {
  2936. return (ctx == NULL) ? NULL : ctx->user_data;
  2937. }
  2938. void *
  2939. mg_get_thread_pointer(const struct mg_connection *conn)
  2940. {
  2941. /* both methods should return the same pointer */
  2942. if (conn) {
  2943. /* quick access, in case conn is known */
  2944. return conn->tls_user_ptr;
  2945. } else {
  2946. /* otherwise get pointer from thread local storage (TLS) */
  2947. struct mg_workerTLS *tls =
  2948. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2949. return tls->user_ptr;
  2950. }
  2951. }
  2952. void
  2953. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2954. {
  2955. if (conn != NULL) {
  2956. conn->request_info.conn_data = data;
  2957. }
  2958. }
  2959. void *
  2960. mg_get_user_connection_data(const struct mg_connection *conn)
  2961. {
  2962. if (conn != NULL) {
  2963. return conn->request_info.conn_data;
  2964. }
  2965. return NULL;
  2966. }
  2967. #if defined(MG_LEGACY_INTERFACE)
  2968. /* Deprecated: Use mg_get_server_ports instead. */
  2969. size_t
  2970. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2971. {
  2972. size_t i;
  2973. if (!ctx) {
  2974. return 0;
  2975. }
  2976. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2977. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2978. ports[i] =
  2979. #if defined(USE_IPV6)
  2980. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2981. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2982. :
  2983. #endif
  2984. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2985. }
  2986. return i;
  2987. }
  2988. #endif
  2989. int
  2990. mg_get_server_ports(const struct mg_context *ctx,
  2991. int size,
  2992. struct mg_server_port *ports)
  2993. {
  2994. int i, cnt = 0;
  2995. if (size <= 0) {
  2996. return -1;
  2997. }
  2998. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2999. if (!ctx) {
  3000. return -1;
  3001. }
  3002. if (!ctx->listening_sockets) {
  3003. return -1;
  3004. }
  3005. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3006. ports[cnt].port =
  3007. #if defined(USE_IPV6)
  3008. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3009. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3010. :
  3011. #endif
  3012. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3013. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3014. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3015. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3016. /* IPv4 */
  3017. ports[cnt].protocol = 1;
  3018. cnt++;
  3019. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3020. /* IPv6 */
  3021. ports[cnt].protocol = 3;
  3022. cnt++;
  3023. }
  3024. }
  3025. return cnt;
  3026. }
  3027. static void
  3028. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3029. {
  3030. buf[0] = '\0';
  3031. if (!usa) {
  3032. return;
  3033. }
  3034. if (usa->sa.sa_family == AF_INET) {
  3035. getnameinfo(&usa->sa,
  3036. sizeof(usa->sin),
  3037. buf,
  3038. (unsigned)len,
  3039. NULL,
  3040. 0,
  3041. NI_NUMERICHOST);
  3042. }
  3043. #if defined(USE_IPV6)
  3044. else if (usa->sa.sa_family == AF_INET6) {
  3045. getnameinfo(&usa->sa,
  3046. sizeof(usa->sin6),
  3047. buf,
  3048. (unsigned)len,
  3049. NULL,
  3050. 0,
  3051. NI_NUMERICHOST);
  3052. }
  3053. #endif
  3054. }
  3055. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3056. * included in all responses other than 100, 101, 5xx. */
  3057. static void
  3058. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3059. {
  3060. #if !defined(REENTRANT_TIME)
  3061. struct tm *tm;
  3062. tm = ((t != NULL) ? gmtime(t) : NULL);
  3063. if (tm != NULL) {
  3064. #else
  3065. struct tm _tm;
  3066. struct tm *tm = &_tm;
  3067. if (t != NULL) {
  3068. gmtime_r(t, tm);
  3069. #endif
  3070. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3071. } else {
  3072. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3073. buf[buf_len - 1] = '\0';
  3074. }
  3075. }
  3076. /* difftime for struct timespec. Return value is in seconds. */
  3077. static double
  3078. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3079. {
  3080. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3081. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3082. }
  3083. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3084. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3085. const char *func,
  3086. unsigned line,
  3087. const char *fmt,
  3088. va_list ap);
  3089. #include "external_mg_cry_internal_impl.inl"
  3090. #else
  3091. /* Print error message to the opened error log stream. */
  3092. static void
  3093. mg_cry_internal_impl(const struct mg_connection *conn,
  3094. const char *func,
  3095. unsigned line,
  3096. const char *fmt,
  3097. va_list ap)
  3098. {
  3099. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3100. struct mg_file fi;
  3101. time_t timestamp;
  3102. /* Unused, in the RELEASE build */
  3103. (void)func;
  3104. (void)line;
  3105. #if defined(GCC_DIAGNOSTIC)
  3106. #pragma GCC diagnostic push
  3107. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3108. #endif
  3109. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3110. #if defined(GCC_DIAGNOSTIC)
  3111. #pragma GCC diagnostic pop
  3112. #endif
  3113. buf[sizeof(buf) - 1] = 0;
  3114. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3115. if (!conn) {
  3116. puts(buf);
  3117. return;
  3118. }
  3119. /* Do not lock when getting the callback value, here and below.
  3120. * I suppose this is fine, since function cannot disappear in the
  3121. * same way string option can. */
  3122. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3123. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3124. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3125. if (mg_fopen(conn,
  3126. conn->dom_ctx->config[ERROR_LOG_FILE],
  3127. MG_FOPEN_MODE_APPEND,
  3128. &fi)
  3129. == 0) {
  3130. fi.access.fp = NULL;
  3131. }
  3132. } else {
  3133. fi.access.fp = NULL;
  3134. }
  3135. if (fi.access.fp != NULL) {
  3136. flockfile(fi.access.fp);
  3137. timestamp = time(NULL);
  3138. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3139. fprintf(fi.access.fp,
  3140. "[%010lu] [error] [client %s] ",
  3141. (unsigned long)timestamp,
  3142. src_addr);
  3143. if (conn->request_info.request_method != NULL) {
  3144. fprintf(fi.access.fp,
  3145. "%s %s: ",
  3146. conn->request_info.request_method,
  3147. conn->request_info.request_uri
  3148. ? conn->request_info.request_uri
  3149. : "");
  3150. }
  3151. fprintf(fi.access.fp, "%s", buf);
  3152. fputc('\n', fi.access.fp);
  3153. fflush(fi.access.fp);
  3154. funlockfile(fi.access.fp);
  3155. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3156. * mg_cry here anyway ;-) */
  3157. }
  3158. }
  3159. }
  3160. #endif /* Externally provided function */
  3161. static void
  3162. mg_cry_internal_wrap(const struct mg_connection *conn,
  3163. const char *func,
  3164. unsigned line,
  3165. const char *fmt,
  3166. ...)
  3167. {
  3168. va_list ap;
  3169. va_start(ap, fmt);
  3170. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3171. va_end(ap);
  3172. }
  3173. void
  3174. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3175. {
  3176. va_list ap;
  3177. va_start(ap, fmt);
  3178. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3179. va_end(ap);
  3180. }
  3181. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3182. /* Return fake connection structure. Used for logging, if connection
  3183. * is not applicable at the moment of logging. */
  3184. static struct mg_connection *
  3185. fc(struct mg_context *ctx)
  3186. {
  3187. static struct mg_connection fake_connection;
  3188. fake_connection.phys_ctx = ctx;
  3189. fake_connection.dom_ctx = &(ctx->dd);
  3190. return &fake_connection;
  3191. }
  3192. const char *
  3193. mg_version(void)
  3194. {
  3195. return CIVETWEB_VERSION;
  3196. }
  3197. const struct mg_request_info *
  3198. mg_get_request_info(const struct mg_connection *conn)
  3199. {
  3200. if (!conn) {
  3201. return NULL;
  3202. }
  3203. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3204. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3205. char txt[16];
  3206. struct mg_workerTLS *tls =
  3207. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3208. sprintf(txt, "%03i", conn->response_info.status_code);
  3209. if (strlen(txt) == 3) {
  3210. memcpy(tls->txtbuf, txt, 4);
  3211. } else {
  3212. strcpy(tls->txtbuf, "ERR");
  3213. }
  3214. ((struct mg_connection *)conn)->request_info.local_uri =
  3215. ((struct mg_connection *)conn)->request_info.request_uri =
  3216. tls->txtbuf; /* use thread safe buffer */
  3217. ((struct mg_connection *)conn)->request_info.num_headers =
  3218. conn->response_info.num_headers;
  3219. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3220. conn->response_info.http_headers,
  3221. sizeof(conn->response_info.http_headers));
  3222. } else
  3223. #endif
  3224. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3225. return NULL;
  3226. }
  3227. return &conn->request_info;
  3228. }
  3229. const struct mg_response_info *
  3230. mg_get_response_info(const struct mg_connection *conn)
  3231. {
  3232. if (!conn) {
  3233. return NULL;
  3234. }
  3235. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3236. return NULL;
  3237. }
  3238. return &conn->response_info;
  3239. }
  3240. static const char *
  3241. get_proto_name(const struct mg_connection *conn)
  3242. {
  3243. #if defined(__clang__)
  3244. #pragma clang diagnostic push
  3245. #pragma clang diagnostic ignored "-Wunreachable-code"
  3246. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3247. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3248. * unreachable, but splitting into four different #ifdef clauses here is more
  3249. * complicated.
  3250. */
  3251. #endif
  3252. const struct mg_request_info *ri = &conn->request_info;
  3253. const char *proto =
  3254. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3255. : (ri->is_ssl ? "https" : "http"));
  3256. return proto;
  3257. #if defined(__clang__)
  3258. #pragma clang diagnostic pop
  3259. #endif
  3260. }
  3261. int
  3262. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3263. {
  3264. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3265. return -1;
  3266. } else {
  3267. int truncated = 0;
  3268. const struct mg_request_info *ri = &conn->request_info;
  3269. const char *proto = get_proto_name(conn);
  3270. if (ri->local_uri == NULL) {
  3271. return -1;
  3272. }
  3273. if ((ri->request_uri != NULL)
  3274. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3275. /* The request uri is different from the local uri.
  3276. * This is usually if an absolute URI, including server
  3277. * name has been provided. */
  3278. mg_snprintf(conn,
  3279. &truncated,
  3280. buf,
  3281. buflen,
  3282. "%s://%s",
  3283. proto,
  3284. ri->request_uri);
  3285. if (truncated) {
  3286. return -1;
  3287. }
  3288. return 0;
  3289. } else {
  3290. /* The common case is a relative URI, so we have to
  3291. * construct an absolute URI from server name and port */
  3292. #if defined(USE_IPV6)
  3293. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3294. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3295. : htons(conn->client.lsa.sin.sin_port);
  3296. #else
  3297. int port = htons(conn->client.lsa.sin.sin_port);
  3298. #endif
  3299. int def_port = ri->is_ssl ? 443 : 80;
  3300. int auth_domain_check_enabled =
  3301. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3302. && (!mg_strcasecmp(
  3303. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3304. const char *server_domain =
  3305. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3306. char portstr[16];
  3307. char server_ip[48];
  3308. if (port != def_port) {
  3309. sprintf(portstr, ":%u", (unsigned)port);
  3310. } else {
  3311. portstr[0] = 0;
  3312. }
  3313. if (!auth_domain_check_enabled || !server_domain) {
  3314. sockaddr_to_string(server_ip,
  3315. sizeof(server_ip),
  3316. &conn->client.lsa);
  3317. server_domain = server_ip;
  3318. }
  3319. mg_snprintf(conn,
  3320. &truncated,
  3321. buf,
  3322. buflen,
  3323. "%s://%s%s%s",
  3324. proto,
  3325. server_domain,
  3326. portstr,
  3327. ri->local_uri);
  3328. if (truncated) {
  3329. return -1;
  3330. }
  3331. return 0;
  3332. }
  3333. }
  3334. }
  3335. /* Skip the characters until one of the delimiters characters found.
  3336. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3337. * Advance pointer to buffer to the next word. Return found 0-terminated
  3338. * word.
  3339. * Delimiters can be quoted with quotechar. */
  3340. static char *
  3341. skip_quoted(char **buf,
  3342. const char *delimiters,
  3343. const char *whitespace,
  3344. char quotechar)
  3345. {
  3346. char *p, *begin_word, *end_word, *end_whitespace;
  3347. begin_word = *buf;
  3348. end_word = begin_word + strcspn(begin_word, delimiters);
  3349. /* Check for quotechar */
  3350. if (end_word > begin_word) {
  3351. p = end_word - 1;
  3352. while (*p == quotechar) {
  3353. /* While the delimiter is quoted, look for the next delimiter.
  3354. */
  3355. /* This happens, e.g., in calls from parse_auth_header,
  3356. * if the user name contains a " character. */
  3357. /* If there is anything beyond end_word, copy it. */
  3358. if (*end_word != '\0') {
  3359. size_t end_off = strcspn(end_word + 1, delimiters);
  3360. memmove(p, end_word, end_off + 1);
  3361. p += end_off; /* p must correspond to end_word - 1 */
  3362. end_word += end_off + 1;
  3363. } else {
  3364. *p = '\0';
  3365. break;
  3366. }
  3367. }
  3368. for (p++; p < end_word; p++) {
  3369. *p = '\0';
  3370. }
  3371. }
  3372. if (*end_word == '\0') {
  3373. *buf = end_word;
  3374. } else {
  3375. #if defined(GCC_DIAGNOSTIC)
  3376. /* Disable spurious conversion warning for GCC */
  3377. #pragma GCC diagnostic push
  3378. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3379. #endif /* defined(GCC_DIAGNOSTIC) */
  3380. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3381. #if defined(GCC_DIAGNOSTIC)
  3382. #pragma GCC diagnostic pop
  3383. #endif /* defined(GCC_DIAGNOSTIC) */
  3384. for (p = end_word; p < end_whitespace; p++) {
  3385. *p = '\0';
  3386. }
  3387. *buf = end_whitespace;
  3388. }
  3389. return begin_word;
  3390. }
  3391. /* Return HTTP header value, or NULL if not found. */
  3392. static const char *
  3393. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3394. {
  3395. int i;
  3396. for (i = 0; i < num_hdr; i++) {
  3397. if (!mg_strcasecmp(name, hdr[i].name)) {
  3398. return hdr[i].value;
  3399. }
  3400. }
  3401. return NULL;
  3402. }
  3403. #if defined(USE_WEBSOCKET)
  3404. /* Retrieve requested HTTP header multiple values, and return the number of
  3405. * found occurrences */
  3406. static int
  3407. get_req_headers(const struct mg_request_info *ri,
  3408. const char *name,
  3409. const char **output,
  3410. int output_max_size)
  3411. {
  3412. int i;
  3413. int cnt = 0;
  3414. if (ri) {
  3415. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3416. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3417. output[cnt++] = ri->http_headers[i].value;
  3418. }
  3419. }
  3420. }
  3421. return cnt;
  3422. }
  3423. #endif
  3424. const char *
  3425. mg_get_header(const struct mg_connection *conn, const char *name)
  3426. {
  3427. if (!conn) {
  3428. return NULL;
  3429. }
  3430. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3431. return get_header(conn->request_info.http_headers,
  3432. conn->request_info.num_headers,
  3433. name);
  3434. }
  3435. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3436. return get_header(conn->response_info.http_headers,
  3437. conn->response_info.num_headers,
  3438. name);
  3439. }
  3440. return NULL;
  3441. }
  3442. static const char *
  3443. get_http_version(const struct mg_connection *conn)
  3444. {
  3445. if (!conn) {
  3446. return NULL;
  3447. }
  3448. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3449. return conn->request_info.http_version;
  3450. }
  3451. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3452. return conn->response_info.http_version;
  3453. }
  3454. return NULL;
  3455. }
  3456. /* A helper function for traversing a comma separated list of values.
  3457. * It returns a list pointer shifted to the next value, or NULL if the end
  3458. * of the list found.
  3459. * Value is stored in val vector. If value has form "x=y", then eq_val
  3460. * vector is initialized to point to the "y" part, and val vector length
  3461. * is adjusted to point only to "x". */
  3462. static const char *
  3463. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3464. {
  3465. int end;
  3466. reparse:
  3467. if (val == NULL || list == NULL || *list == '\0') {
  3468. /* End of the list */
  3469. return NULL;
  3470. }
  3471. /* Skip over leading LWS */
  3472. while (*list == ' ' || *list == '\t')
  3473. list++;
  3474. val->ptr = list;
  3475. if ((list = strchr(val->ptr, ',')) != NULL) {
  3476. /* Comma found. Store length and shift the list ptr */
  3477. val->len = ((size_t)(list - val->ptr));
  3478. list++;
  3479. } else {
  3480. /* This value is the last one */
  3481. list = val->ptr + strlen(val->ptr);
  3482. val->len = ((size_t)(list - val->ptr));
  3483. }
  3484. /* Adjust length for trailing LWS */
  3485. end = (int)val->len - 1;
  3486. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3487. end--;
  3488. val->len = (size_t)(end) + (size_t)(1);
  3489. if (val->len == 0) {
  3490. /* Ignore any empty entries. */
  3491. goto reparse;
  3492. }
  3493. if (eq_val != NULL) {
  3494. /* Value has form "x=y", adjust pointers and lengths
  3495. * so that val points to "x", and eq_val points to "y". */
  3496. eq_val->len = 0;
  3497. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3498. if (eq_val->ptr != NULL) {
  3499. eq_val->ptr++; /* Skip over '=' character */
  3500. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3501. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3502. }
  3503. }
  3504. return list;
  3505. }
  3506. /* A helper function for checking if a comma separated list of values
  3507. * contains
  3508. * the given option (case insensitvely).
  3509. * 'header' can be NULL, in which case false is returned. */
  3510. static int
  3511. header_has_option(const char *header, const char *option)
  3512. {
  3513. struct vec opt_vec;
  3514. struct vec eq_vec;
  3515. DEBUG_ASSERT(option != NULL);
  3516. DEBUG_ASSERT(option[0] != '\0');
  3517. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3518. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3519. return 1;
  3520. }
  3521. return 0;
  3522. }
  3523. /* Perform case-insensitive match of string against pattern */
  3524. static ptrdiff_t
  3525. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3526. {
  3527. const char *or_str;
  3528. ptrdiff_t i, j, len, res;
  3529. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3530. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3531. return (res > 0) ? res
  3532. : match_prefix(or_str + 1,
  3533. (size_t)((pattern + pattern_len)
  3534. - (or_str + 1)),
  3535. str);
  3536. }
  3537. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3538. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3539. continue;
  3540. } else if (pattern[i] == '$') {
  3541. return (str[j] == '\0') ? j : -1;
  3542. } else if (pattern[i] == '*') {
  3543. i++;
  3544. if (pattern[i] == '*') {
  3545. i++;
  3546. len = strlen(str + j);
  3547. } else {
  3548. len = strcspn(str + j, "/");
  3549. }
  3550. if (i == (ptrdiff_t)pattern_len) {
  3551. return j + len;
  3552. }
  3553. do {
  3554. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3555. } while (res == -1 && len-- > 0);
  3556. return (res == -1) ? -1 : j + res + len;
  3557. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3558. return -1;
  3559. }
  3560. }
  3561. return (ptrdiff_t)j;
  3562. }
  3563. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3564. * This function must tolerate situations when connection info is not
  3565. * set up, for example if request parsing failed. */
  3566. static int
  3567. should_keep_alive(const struct mg_connection *conn)
  3568. {
  3569. const char *http_version;
  3570. const char *header;
  3571. /* First satisfy needs of the server */
  3572. if ((conn == NULL) || conn->must_close) {
  3573. /* Close, if civetweb framework needs to close */
  3574. return 0;
  3575. }
  3576. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3577. /* Close, if keep alive is not enabled */
  3578. return 0;
  3579. }
  3580. /* Check explicit wish of the client */
  3581. header = mg_get_header(conn, "Connection");
  3582. if (header) {
  3583. /* If there is a connection header from the client, obey */
  3584. if (header_has_option(header, "keep-alive")) {
  3585. return 1;
  3586. }
  3587. return 0;
  3588. }
  3589. /* Use default of the standard */
  3590. http_version = get_http_version(conn);
  3591. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3592. /* HTTP 1.1 default is keep alive */
  3593. return 1;
  3594. }
  3595. /* HTTP 1.0 (and earlier) default is to close the connection */
  3596. return 0;
  3597. }
  3598. static int
  3599. should_decode_url(const struct mg_connection *conn)
  3600. {
  3601. if (!conn || !conn->dom_ctx) {
  3602. return 0;
  3603. }
  3604. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3605. }
  3606. static const char *
  3607. suggest_connection_header(const struct mg_connection *conn)
  3608. {
  3609. return should_keep_alive(conn) ? "keep-alive" : "close";
  3610. }
  3611. static int
  3612. send_no_cache_header(struct mg_connection *conn)
  3613. {
  3614. /* Send all current and obsolete cache opt-out directives. */
  3615. return mg_printf(conn,
  3616. "Cache-Control: no-cache, no-store, "
  3617. "must-revalidate, private, max-age=0\r\n"
  3618. "Pragma: no-cache\r\n"
  3619. "Expires: 0\r\n");
  3620. }
  3621. static int
  3622. send_static_cache_header(struct mg_connection *conn)
  3623. {
  3624. #if !defined(NO_CACHING)
  3625. /* Read the server config to check how long a file may be cached.
  3626. * The configuration is in seconds. */
  3627. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3628. if (max_age <= 0) {
  3629. /* 0 means "do not cache". All values <0 are reserved
  3630. * and may be used differently in the future. */
  3631. /* If a file should not be cached, do not only send
  3632. * max-age=0, but also pragmas and Expires headers. */
  3633. return send_no_cache_header(conn);
  3634. }
  3635. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3636. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3637. /* See also https://www.mnot.net/cache_docs/ */
  3638. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3639. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3640. * leap
  3641. * year to 31622400 seconds. For the moment, we just send whatever has
  3642. * been configured, still the behavior for >1 year should be considered
  3643. * as undefined. */
  3644. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3645. #else /* NO_CACHING */
  3646. return send_no_cache_header(conn);
  3647. #endif /* !NO_CACHING */
  3648. }
  3649. static int
  3650. send_additional_header(struct mg_connection *conn)
  3651. {
  3652. int i = 0;
  3653. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3654. #if !defined(NO_SSL)
  3655. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3656. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3657. if (max_age >= 0) {
  3658. i += mg_printf(conn,
  3659. "Strict-Transport-Security: max-age=%u\r\n",
  3660. (unsigned)max_age);
  3661. }
  3662. }
  3663. #endif
  3664. if (header && header[0]) {
  3665. i += mg_printf(conn, "%s\r\n", header);
  3666. }
  3667. return i;
  3668. }
  3669. static void handle_file_based_request(struct mg_connection *conn,
  3670. const char *path,
  3671. struct mg_file *filep);
  3672. const char *
  3673. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3674. {
  3675. /* See IANA HTTP status code assignment:
  3676. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3677. */
  3678. switch (response_code) {
  3679. /* RFC2616 Section 10.1 - Informational 1xx */
  3680. case 100:
  3681. return "Continue"; /* RFC2616 Section 10.1.1 */
  3682. case 101:
  3683. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3684. case 102:
  3685. return "Processing"; /* RFC2518 Section 10.1 */
  3686. /* RFC2616 Section 10.2 - Successful 2xx */
  3687. case 200:
  3688. return "OK"; /* RFC2616 Section 10.2.1 */
  3689. case 201:
  3690. return "Created"; /* RFC2616 Section 10.2.2 */
  3691. case 202:
  3692. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3693. case 203:
  3694. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3695. case 204:
  3696. return "No Content"; /* RFC2616 Section 10.2.5 */
  3697. case 205:
  3698. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3699. case 206:
  3700. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3701. case 207:
  3702. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3703. */
  3704. case 208:
  3705. return "Already Reported"; /* RFC5842 Section 7.1 */
  3706. case 226:
  3707. return "IM used"; /* RFC3229 Section 10.4.1 */
  3708. /* RFC2616 Section 10.3 - Redirection 3xx */
  3709. case 300:
  3710. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3711. case 301:
  3712. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3713. case 302:
  3714. return "Found"; /* RFC2616 Section 10.3.3 */
  3715. case 303:
  3716. return "See Other"; /* RFC2616 Section 10.3.4 */
  3717. case 304:
  3718. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3719. case 305:
  3720. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3721. case 307:
  3722. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3723. case 308:
  3724. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3725. /* RFC2616 Section 10.4 - Client Error 4xx */
  3726. case 400:
  3727. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3728. case 401:
  3729. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3730. case 402:
  3731. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3732. case 403:
  3733. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3734. case 404:
  3735. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3736. case 405:
  3737. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3738. case 406:
  3739. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3740. case 407:
  3741. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3742. case 408:
  3743. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3744. case 409:
  3745. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3746. case 410:
  3747. return "Gone"; /* RFC2616 Section 10.4.11 */
  3748. case 411:
  3749. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3750. case 412:
  3751. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3752. case 413:
  3753. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3754. case 414:
  3755. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3756. case 415:
  3757. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3758. case 416:
  3759. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3760. */
  3761. case 417:
  3762. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3763. case 421:
  3764. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3765. case 422:
  3766. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3767. * Section 11.2 */
  3768. case 423:
  3769. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3770. case 424:
  3771. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3772. * Section 11.4 */
  3773. case 426:
  3774. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3775. case 428:
  3776. return "Precondition Required"; /* RFC 6585, Section 3 */
  3777. case 429:
  3778. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3779. case 431:
  3780. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3781. case 451:
  3782. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3783. * Section 3 */
  3784. /* RFC2616 Section 10.5 - Server Error 5xx */
  3785. case 500:
  3786. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3787. case 501:
  3788. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3789. case 502:
  3790. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3791. case 503:
  3792. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3793. case 504:
  3794. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3795. case 505:
  3796. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3797. case 506:
  3798. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3799. case 507:
  3800. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3801. * Section 11.5 */
  3802. case 508:
  3803. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3804. case 510:
  3805. return "Not Extended"; /* RFC 2774, Section 7 */
  3806. case 511:
  3807. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3808. /* Other status codes, not shown in the IANA HTTP status code
  3809. * assignment.
  3810. * E.g., "de facto" standards due to common use, ... */
  3811. case 418:
  3812. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3813. case 419:
  3814. return "Authentication Timeout"; /* common use */
  3815. case 420:
  3816. return "Enhance Your Calm"; /* common use */
  3817. case 440:
  3818. return "Login Timeout"; /* common use */
  3819. case 509:
  3820. return "Bandwidth Limit Exceeded"; /* common use */
  3821. default:
  3822. /* This error code is unknown. This should not happen. */
  3823. if (conn) {
  3824. mg_cry_internal(conn,
  3825. "Unknown HTTP response code: %u",
  3826. response_code);
  3827. }
  3828. /* Return at least a category according to RFC 2616 Section 10. */
  3829. if (response_code >= 100 && response_code < 200) {
  3830. /* Unknown informational status code */
  3831. return "Information";
  3832. }
  3833. if (response_code >= 200 && response_code < 300) {
  3834. /* Unknown success code */
  3835. return "Success";
  3836. }
  3837. if (response_code >= 300 && response_code < 400) {
  3838. /* Unknown redirection code */
  3839. return "Redirection";
  3840. }
  3841. if (response_code >= 400 && response_code < 500) {
  3842. /* Unknown request error code */
  3843. return "Client Error";
  3844. }
  3845. if (response_code >= 500 && response_code < 600) {
  3846. /* Unknown server error code */
  3847. return "Server Error";
  3848. }
  3849. /* Response code not even within reasonable range */
  3850. return "";
  3851. }
  3852. }
  3853. static int
  3854. mg_send_http_error_impl(struct mg_connection *conn,
  3855. int status,
  3856. const char *fmt,
  3857. va_list args)
  3858. {
  3859. char errmsg_buf[MG_BUF_LEN];
  3860. char path_buf[PATH_MAX];
  3861. va_list ap;
  3862. int len, i, page_handler_found, scope, truncated, has_body;
  3863. char date[64];
  3864. time_t curtime = time(NULL);
  3865. const char *error_handler = NULL;
  3866. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3867. const char *error_page_file_ext, *tstr;
  3868. int handled_by_callback = 0;
  3869. const char *status_text = mg_get_response_code_text(conn, status);
  3870. if ((conn == NULL) || (fmt == NULL)) {
  3871. return -2;
  3872. }
  3873. /* Set status (for log) */
  3874. conn->status_code = status;
  3875. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3876. has_body = ((status > 199) && (status != 204) && (status != 304));
  3877. /* Prepare message in buf, if required */
  3878. if (has_body
  3879. || (!conn->in_error_handler
  3880. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3881. /* Store error message in errmsg_buf */
  3882. va_copy(ap, args);
  3883. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3884. va_end(ap);
  3885. /* In a debug build, print all html errors */
  3886. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3887. }
  3888. /* If there is a http_error callback, call it.
  3889. * But don't do it recursively, if callback calls mg_send_http_error again.
  3890. */
  3891. if (!conn->in_error_handler
  3892. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3893. /* Mark in_error_handler to avoid recursion and call user callback. */
  3894. conn->in_error_handler = 1;
  3895. handled_by_callback =
  3896. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3897. == 0);
  3898. conn->in_error_handler = 0;
  3899. }
  3900. if (!handled_by_callback) {
  3901. /* Check for recursion */
  3902. if (conn->in_error_handler) {
  3903. DEBUG_TRACE(
  3904. "Recursion when handling error %u - fall back to default",
  3905. status);
  3906. } else {
  3907. /* Send user defined error pages, if defined */
  3908. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3909. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3910. page_handler_found = 0;
  3911. if (error_handler != NULL) {
  3912. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3913. switch (scope) {
  3914. case 1: /* Handler for specific error, e.g. 404 error */
  3915. mg_snprintf(conn,
  3916. &truncated,
  3917. path_buf,
  3918. sizeof(path_buf) - 32,
  3919. "%serror%03u.",
  3920. error_handler,
  3921. status);
  3922. break;
  3923. case 2: /* Handler for error group, e.g., 5xx error
  3924. * handler
  3925. * for all server errors (500-599) */
  3926. mg_snprintf(conn,
  3927. &truncated,
  3928. path_buf,
  3929. sizeof(path_buf) - 32,
  3930. "%serror%01uxx.",
  3931. error_handler,
  3932. status / 100);
  3933. break;
  3934. default: /* Handler for all errors */
  3935. mg_snprintf(conn,
  3936. &truncated,
  3937. path_buf,
  3938. sizeof(path_buf) - 32,
  3939. "%serror.",
  3940. error_handler);
  3941. break;
  3942. }
  3943. /* String truncation in buf may only occur if
  3944. * error_handler is too long. This string is
  3945. * from the config, not from a client. */
  3946. (void)truncated;
  3947. len = (int)strlen(path_buf);
  3948. tstr = strchr(error_page_file_ext, '.');
  3949. while (tstr) {
  3950. for (i = 1;
  3951. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3952. i++) {
  3953. /* buffer overrun is not possible here, since
  3954. * (i < 32) && (len < sizeof(path_buf) - 32)
  3955. * ==> (i + len) < sizeof(path_buf) */
  3956. path_buf[len + i - 1] = tstr[i];
  3957. }
  3958. /* buffer overrun is not possible here, since
  3959. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3960. * ==> (i + len) <= sizeof(path_buf) */
  3961. path_buf[len + i - 1] = 0;
  3962. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3963. DEBUG_TRACE("Check error page %s - found",
  3964. path_buf);
  3965. page_handler_found = 1;
  3966. break;
  3967. }
  3968. DEBUG_TRACE("Check error page %s - not found",
  3969. path_buf);
  3970. tstr = strchr(tstr + i, '.');
  3971. }
  3972. }
  3973. }
  3974. if (page_handler_found) {
  3975. conn->in_error_handler = 1;
  3976. handle_file_based_request(conn, path_buf, &error_page_file);
  3977. conn->in_error_handler = 0;
  3978. return 0;
  3979. }
  3980. }
  3981. /* No custom error page. Send default error page. */
  3982. gmt_time_string(date, sizeof(date), &curtime);
  3983. conn->must_close = 1;
  3984. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3985. send_no_cache_header(conn);
  3986. send_additional_header(conn);
  3987. if (has_body) {
  3988. mg_printf(conn,
  3989. "%s",
  3990. "Content-Type: text/plain; charset=utf-8\r\n");
  3991. }
  3992. mg_printf(conn,
  3993. "Date: %s\r\n"
  3994. "Connection: close\r\n\r\n",
  3995. date);
  3996. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3997. if (has_body) {
  3998. /* For other errors, send a generic error message. */
  3999. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4000. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4001. } else {
  4002. /* No body allowed. Close the connection. */
  4003. DEBUG_TRACE("Error %i", status);
  4004. }
  4005. }
  4006. return 0;
  4007. }
  4008. int
  4009. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4010. {
  4011. va_list ap;
  4012. int ret;
  4013. va_start(ap, fmt);
  4014. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4015. va_end(ap);
  4016. return ret;
  4017. }
  4018. int
  4019. mg_send_http_ok(struct mg_connection *conn,
  4020. const char *mime_type,
  4021. long long content_length)
  4022. {
  4023. char date[64];
  4024. time_t curtime = time(NULL);
  4025. if ((mime_type == NULL) || (*mime_type == 0)) {
  4026. /* Parameter error */
  4027. return -2;
  4028. }
  4029. gmt_time_string(date, sizeof(date), &curtime);
  4030. mg_printf(conn,
  4031. "HTTP/1.1 200 OK\r\n"
  4032. "Content-Type: %s\r\n"
  4033. "Date: %s\r\n"
  4034. "Connection: %s\r\n",
  4035. mime_type,
  4036. date,
  4037. suggest_connection_header(conn));
  4038. send_no_cache_header(conn);
  4039. send_additional_header(conn);
  4040. if (content_length < 0) {
  4041. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4042. } else {
  4043. mg_printf(conn,
  4044. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4045. (uint64_t)content_length);
  4046. }
  4047. return 0;
  4048. }
  4049. int
  4050. mg_send_http_redirect(struct mg_connection *conn,
  4051. const char *target_url,
  4052. int redirect_code)
  4053. {
  4054. /* Send a 30x redirect response.
  4055. *
  4056. * Redirect types (status codes):
  4057. *
  4058. * Status | Perm/Temp | Method | Version
  4059. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4060. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4061. * 303 | temporary | always use GET | HTTP/1.1
  4062. * 307 | temporary | always keep method | HTTP/1.1
  4063. * 308 | permanent | always keep method | HTTP/1.1
  4064. */
  4065. const char *redirect_text;
  4066. int ret;
  4067. size_t content_len = 0;
  4068. char reply[MG_BUF_LEN];
  4069. /* In case redirect_code=0, use 307. */
  4070. if (redirect_code == 0) {
  4071. redirect_code = 307;
  4072. }
  4073. /* In case redirect_code is none of the above, return error. */
  4074. if ((redirect_code != 301) && (redirect_code != 302)
  4075. && (redirect_code != 303) && (redirect_code != 307)
  4076. && (redirect_code != 308)) {
  4077. /* Parameter error */
  4078. return -2;
  4079. }
  4080. /* Get proper text for response code */
  4081. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4082. /* If target_url is not defined, redirect to "/". */
  4083. if ((target_url == NULL) || (*target_url == 0)) {
  4084. target_url = "/";
  4085. }
  4086. #if defined(MG_SEND_REDIRECT_BODY)
  4087. /* TODO: condition name? */
  4088. /* Prepare a response body with a hyperlink.
  4089. *
  4090. * According to RFC2616 (and RFC1945 before):
  4091. * Unless the request method was HEAD, the entity of the
  4092. * response SHOULD contain a short hypertext note with a hyperlink to
  4093. * the new URI(s).
  4094. *
  4095. * However, this response body is not useful in M2M communication.
  4096. * Probably the original reason in the RFC was, clients not supporting
  4097. * a 30x HTTP redirect could still show the HTML page and let the user
  4098. * press the link. Since current browsers support 30x HTTP, the additional
  4099. * HTML body does not seem to make sense anymore.
  4100. *
  4101. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4102. * but it only notes:
  4103. * The server's response payload usually contains a short
  4104. * hypertext note with a hyperlink to the new URI(s).
  4105. *
  4106. * Deactivated by default. If you need the 30x body, set the define.
  4107. */
  4108. mg_snprintf(
  4109. conn,
  4110. NULL /* ignore truncation */,
  4111. reply,
  4112. sizeof(reply),
  4113. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4114. redirect_text,
  4115. target_url,
  4116. target_url);
  4117. content_len = strlen(reply);
  4118. #else
  4119. reply[0] = 0;
  4120. #endif
  4121. /* Do not send any additional header. For all other options,
  4122. * including caching, there are suitable defaults. */
  4123. ret = mg_printf(conn,
  4124. "HTTP/1.1 %i %s\r\n"
  4125. "Location: %s\r\n"
  4126. "Content-Length: %u\r\n"
  4127. "Connection: %s\r\n\r\n",
  4128. redirect_code,
  4129. redirect_text,
  4130. target_url,
  4131. (unsigned int)content_len,
  4132. suggest_connection_header(conn));
  4133. /* Send response body */
  4134. if (ret > 0) {
  4135. /* ... unless it is a HEAD request */
  4136. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4137. ret = mg_write(conn, reply, content_len);
  4138. }
  4139. }
  4140. return (ret > 0) ? ret : -1;
  4141. }
  4142. #if defined(_WIN32)
  4143. /* Create substitutes for POSIX functions in Win32. */
  4144. #if defined(GCC_DIAGNOSTIC)
  4145. /* Show no warning in case system functions are not used. */
  4146. #pragma GCC diagnostic push
  4147. #pragma GCC diagnostic ignored "-Wunused-function"
  4148. #endif
  4149. FUNCTION_MAY_BE_UNUSED
  4150. static int
  4151. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4152. {
  4153. (void)unused;
  4154. *mutex = CreateMutex(NULL, FALSE, NULL);
  4155. return (*mutex == NULL) ? -1 : 0;
  4156. }
  4157. FUNCTION_MAY_BE_UNUSED
  4158. static int
  4159. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4160. {
  4161. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  4162. }
  4163. FUNCTION_MAY_BE_UNUSED
  4164. static int
  4165. pthread_mutex_lock(pthread_mutex_t *mutex)
  4166. {
  4167. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  4168. : -1;
  4169. }
  4170. #if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS)
  4171. FUNCTION_MAY_BE_UNUSED
  4172. static int
  4173. pthread_mutex_trylock(pthread_mutex_t *mutex)
  4174. {
  4175. switch (WaitForSingleObject(*mutex, 0)) {
  4176. case WAIT_OBJECT_0:
  4177. return 0;
  4178. case WAIT_TIMEOUT:
  4179. return -2; /* EBUSY */
  4180. }
  4181. return -1;
  4182. }
  4183. #endif
  4184. FUNCTION_MAY_BE_UNUSED
  4185. static int
  4186. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4187. {
  4188. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  4189. }
  4190. FUNCTION_MAY_BE_UNUSED
  4191. static int
  4192. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4193. {
  4194. (void)unused;
  4195. InitializeCriticalSection(&cv->threadIdSec);
  4196. cv->waiting_thread = NULL;
  4197. return 0;
  4198. }
  4199. FUNCTION_MAY_BE_UNUSED
  4200. static int
  4201. pthread_cond_timedwait(pthread_cond_t *cv,
  4202. pthread_mutex_t *mutex,
  4203. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4204. {
  4205. struct mg_workerTLS **ptls,
  4206. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4207. int ok;
  4208. int64_t nsnow, nswaitabs, nswaitrel;
  4209. DWORD mswaitrel;
  4210. EnterCriticalSection(&cv->threadIdSec);
  4211. /* Add this thread to cv's waiting list */
  4212. ptls = &cv->waiting_thread;
  4213. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4214. ;
  4215. tls->next_waiting_thread = NULL;
  4216. *ptls = tls;
  4217. LeaveCriticalSection(&cv->threadIdSec);
  4218. if (abstime) {
  4219. nsnow = mg_get_current_time_ns();
  4220. nswaitabs =
  4221. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4222. nswaitrel = nswaitabs - nsnow;
  4223. if (nswaitrel < 0) {
  4224. nswaitrel = 0;
  4225. }
  4226. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4227. } else {
  4228. mswaitrel = (DWORD)INFINITE;
  4229. }
  4230. pthread_mutex_unlock(mutex);
  4231. ok = (WAIT_OBJECT_0
  4232. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4233. if (!ok) {
  4234. ok = 1;
  4235. EnterCriticalSection(&cv->threadIdSec);
  4236. ptls = &cv->waiting_thread;
  4237. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4238. if (*ptls == tls) {
  4239. *ptls = tls->next_waiting_thread;
  4240. ok = 0;
  4241. break;
  4242. }
  4243. }
  4244. LeaveCriticalSection(&cv->threadIdSec);
  4245. if (ok) {
  4246. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4247. (DWORD)INFINITE);
  4248. }
  4249. }
  4250. /* This thread has been removed from cv's waiting list */
  4251. pthread_mutex_lock(mutex);
  4252. return ok ? 0 : -1;
  4253. }
  4254. FUNCTION_MAY_BE_UNUSED
  4255. static int
  4256. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4257. {
  4258. return pthread_cond_timedwait(cv, mutex, NULL);
  4259. }
  4260. FUNCTION_MAY_BE_UNUSED
  4261. static int
  4262. pthread_cond_signal(pthread_cond_t *cv)
  4263. {
  4264. HANDLE wkup = NULL;
  4265. BOOL ok = FALSE;
  4266. EnterCriticalSection(&cv->threadIdSec);
  4267. if (cv->waiting_thread) {
  4268. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4269. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4270. ok = SetEvent(wkup);
  4271. DEBUG_ASSERT(ok);
  4272. }
  4273. LeaveCriticalSection(&cv->threadIdSec);
  4274. return ok ? 0 : 1;
  4275. }
  4276. FUNCTION_MAY_BE_UNUSED
  4277. static int
  4278. pthread_cond_broadcast(pthread_cond_t *cv)
  4279. {
  4280. EnterCriticalSection(&cv->threadIdSec);
  4281. while (cv->waiting_thread) {
  4282. pthread_cond_signal(cv);
  4283. }
  4284. LeaveCriticalSection(&cv->threadIdSec);
  4285. return 0;
  4286. }
  4287. FUNCTION_MAY_BE_UNUSED
  4288. static int
  4289. pthread_cond_destroy(pthread_cond_t *cv)
  4290. {
  4291. EnterCriticalSection(&cv->threadIdSec);
  4292. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4293. LeaveCriticalSection(&cv->threadIdSec);
  4294. DeleteCriticalSection(&cv->threadIdSec);
  4295. return 0;
  4296. }
  4297. #if defined(ALTERNATIVE_QUEUE)
  4298. FUNCTION_MAY_BE_UNUSED
  4299. static void *
  4300. event_create(void)
  4301. {
  4302. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4303. }
  4304. FUNCTION_MAY_BE_UNUSED
  4305. static int
  4306. event_wait(void *eventhdl)
  4307. {
  4308. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4309. return (res == WAIT_OBJECT_0);
  4310. }
  4311. FUNCTION_MAY_BE_UNUSED
  4312. static int
  4313. event_signal(void *eventhdl)
  4314. {
  4315. return (int)SetEvent((HANDLE)eventhdl);
  4316. }
  4317. FUNCTION_MAY_BE_UNUSED
  4318. static void
  4319. event_destroy(void *eventhdl)
  4320. {
  4321. CloseHandle((HANDLE)eventhdl);
  4322. }
  4323. #endif
  4324. #if defined(GCC_DIAGNOSTIC)
  4325. /* Enable unused function warning again */
  4326. #pragma GCC diagnostic pop
  4327. #endif
  4328. /* For Windows, change all slashes to backslashes in path names. */
  4329. static void
  4330. change_slashes_to_backslashes(char *path)
  4331. {
  4332. int i;
  4333. for (i = 0; path[i] != '\0'; i++) {
  4334. if (path[i] == '/') {
  4335. path[i] = '\\';
  4336. }
  4337. /* remove double backslash (check i > 0 to preserve UNC paths,
  4338. * like \\server\file.txt) */
  4339. if ((path[i] == '\\') && (i > 0)) {
  4340. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4341. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4342. }
  4343. }
  4344. }
  4345. }
  4346. static int
  4347. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4348. {
  4349. int diff;
  4350. do {
  4351. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4352. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4353. s1++;
  4354. s2++;
  4355. } while ((diff == 0) && (s1[-1] != L'\0'));
  4356. return diff;
  4357. }
  4358. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4359. * wbuf and wbuf_len is a target buffer and its length. */
  4360. static void
  4361. path_to_unicode(const struct mg_connection *conn,
  4362. const char *path,
  4363. wchar_t *wbuf,
  4364. size_t wbuf_len)
  4365. {
  4366. char buf[PATH_MAX], buf2[PATH_MAX];
  4367. wchar_t wbuf2[W_PATH_MAX + 1];
  4368. DWORD long_len, err;
  4369. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4370. mg_strlcpy(buf, path, sizeof(buf));
  4371. change_slashes_to_backslashes(buf);
  4372. /* Convert to Unicode and back. If doubly-converted string does not
  4373. * match the original, something is fishy, reject. */
  4374. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4375. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4376. WideCharToMultiByte(
  4377. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4378. if (strcmp(buf, buf2) != 0) {
  4379. wbuf[0] = L'\0';
  4380. }
  4381. /* Windows file systems are not case sensitive, but you can still use
  4382. * uppercase and lowercase letters (on all modern file systems).
  4383. * The server can check if the URI uses the same upper/lowercase
  4384. * letters an the file system, effectively making Windows servers
  4385. * case sensitive (like Linux servers are). It is still not possible
  4386. * to use two files with the same name in different cases on Windows
  4387. * (like /a and /A) - this would be possible in Linux.
  4388. * As a default, Windows is not case sensitive, but the case sensitive
  4389. * file name check can be activated by an additional configuration. */
  4390. if (conn) {
  4391. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4392. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4393. "yes")) {
  4394. /* Use case sensitive compare function */
  4395. fcompare = wcscmp;
  4396. }
  4397. }
  4398. (void)conn; /* conn is currently unused */
  4399. #if !defined(_WIN32_WCE)
  4400. /* Only accept a full file path, not a Windows short (8.3) path. */
  4401. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4402. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4403. if (long_len == 0) {
  4404. err = GetLastError();
  4405. if (err == ERROR_FILE_NOT_FOUND) {
  4406. /* File does not exist. This is not always a problem here. */
  4407. return;
  4408. }
  4409. }
  4410. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4411. /* Short name is used. */
  4412. wbuf[0] = L'\0';
  4413. }
  4414. #else
  4415. (void)long_len;
  4416. (void)wbuf2;
  4417. (void)err;
  4418. if (strchr(path, '~')) {
  4419. wbuf[0] = L'\0';
  4420. }
  4421. #endif
  4422. }
  4423. static int
  4424. mg_stat(const struct mg_connection *conn,
  4425. const char *path,
  4426. struct mg_file_stat *filep)
  4427. {
  4428. wchar_t wbuf[W_PATH_MAX];
  4429. WIN32_FILE_ATTRIBUTE_DATA info;
  4430. time_t creation_time;
  4431. size_t len;
  4432. if (!filep) {
  4433. return 0;
  4434. }
  4435. memset(filep, 0, sizeof(*filep));
  4436. if (conn && is_file_in_memory(conn, path)) {
  4437. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4438. * memset */
  4439. /* Quick fix (for 1.9.x): */
  4440. /* mg_stat must fill all fields, also for files in memory */
  4441. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4442. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4443. filep->size = tmp_file.stat.size;
  4444. filep->location = 2;
  4445. /* TODO: for 1.10: restructure how files in memory are handled */
  4446. /* The "file in memory" feature is a candidate for deletion.
  4447. * Please join the discussion at
  4448. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4449. */
  4450. filep->last_modified = time(NULL); /* TODO */
  4451. /* last_modified = now ... assumes the file may change during
  4452. * runtime,
  4453. * so every mg_fopen call may return different data */
  4454. /* last_modified = conn->phys_ctx.start_time;
  4455. * May be used it the data does not change during runtime. This
  4456. * allows
  4457. * browser caching. Since we do not know, we have to assume the file
  4458. * in memory may change. */
  4459. return 1;
  4460. }
  4461. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4462. /* Windows happily opens files with some garbage at the end of file name.
  4463. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4464. * "a.cgi", despite one would expect an error back. */
  4465. len = strlen(path);
  4466. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4467. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4468. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4469. filep->last_modified =
  4470. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4471. info.ftLastWriteTime.dwHighDateTime);
  4472. /* On Windows, the file creation time can be higher than the
  4473. * modification time, e.g. when a file is copied.
  4474. * Since the Last-Modified timestamp is used for caching
  4475. * it should be based on the most recent timestamp. */
  4476. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4477. info.ftCreationTime.dwHighDateTime);
  4478. if (creation_time > filep->last_modified) {
  4479. filep->last_modified = creation_time;
  4480. }
  4481. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4482. return 1;
  4483. }
  4484. return 0;
  4485. }
  4486. static int
  4487. mg_remove(const struct mg_connection *conn, const char *path)
  4488. {
  4489. wchar_t wbuf[W_PATH_MAX];
  4490. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4491. return DeleteFileW(wbuf) ? 0 : -1;
  4492. }
  4493. static int
  4494. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4495. {
  4496. wchar_t wbuf[W_PATH_MAX];
  4497. (void)mode;
  4498. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4499. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4500. }
  4501. /* Create substitutes for POSIX functions in Win32. */
  4502. #if defined(GCC_DIAGNOSTIC)
  4503. /* Show no warning in case system functions are not used. */
  4504. #pragma GCC diagnostic push
  4505. #pragma GCC diagnostic ignored "-Wunused-function"
  4506. #endif
  4507. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4508. FUNCTION_MAY_BE_UNUSED
  4509. static DIR *
  4510. mg_opendir(const struct mg_connection *conn, const char *name)
  4511. {
  4512. DIR *dir = NULL;
  4513. wchar_t wpath[W_PATH_MAX];
  4514. DWORD attrs;
  4515. if (name == NULL) {
  4516. SetLastError(ERROR_BAD_ARGUMENTS);
  4517. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4518. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4519. } else {
  4520. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4521. attrs = GetFileAttributesW(wpath);
  4522. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4523. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4524. (void)wcscat(wpath, L"\\*");
  4525. dir->handle = FindFirstFileW(wpath, &dir->info);
  4526. dir->result.d_name[0] = '\0';
  4527. } else {
  4528. mg_free(dir);
  4529. dir = NULL;
  4530. }
  4531. }
  4532. return dir;
  4533. }
  4534. FUNCTION_MAY_BE_UNUSED
  4535. static int
  4536. mg_closedir(DIR *dir)
  4537. {
  4538. int result = 0;
  4539. if (dir != NULL) {
  4540. if (dir->handle != INVALID_HANDLE_VALUE)
  4541. result = FindClose(dir->handle) ? 0 : -1;
  4542. mg_free(dir);
  4543. } else {
  4544. result = -1;
  4545. SetLastError(ERROR_BAD_ARGUMENTS);
  4546. }
  4547. return result;
  4548. }
  4549. FUNCTION_MAY_BE_UNUSED
  4550. static struct dirent *
  4551. mg_readdir(DIR *dir)
  4552. {
  4553. struct dirent *result = 0;
  4554. if (dir) {
  4555. if (dir->handle != INVALID_HANDLE_VALUE) {
  4556. result = &dir->result;
  4557. (void)WideCharToMultiByte(CP_UTF8,
  4558. 0,
  4559. dir->info.cFileName,
  4560. -1,
  4561. result->d_name,
  4562. sizeof(result->d_name),
  4563. NULL,
  4564. NULL);
  4565. if (!FindNextFileW(dir->handle, &dir->info)) {
  4566. (void)FindClose(dir->handle);
  4567. dir->handle = INVALID_HANDLE_VALUE;
  4568. }
  4569. } else {
  4570. SetLastError(ERROR_FILE_NOT_FOUND);
  4571. }
  4572. } else {
  4573. SetLastError(ERROR_BAD_ARGUMENTS);
  4574. }
  4575. return result;
  4576. }
  4577. #if !defined(HAVE_POLL)
  4578. #undef POLLIN
  4579. #undef POLLPRI
  4580. #undef POLLOUT
  4581. #define POLLIN (1) /* Data ready - read will not block. */
  4582. #define POLLPRI (2) /* Priority data ready. */
  4583. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4584. FUNCTION_MAY_BE_UNUSED
  4585. static int
  4586. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4587. {
  4588. struct timeval tv;
  4589. fd_set rset;
  4590. fd_set wset;
  4591. unsigned int i;
  4592. int result;
  4593. SOCKET maxfd = 0;
  4594. memset(&tv, 0, sizeof(tv));
  4595. tv.tv_sec = milliseconds / 1000;
  4596. tv.tv_usec = (milliseconds % 1000) * 1000;
  4597. FD_ZERO(&rset);
  4598. FD_ZERO(&wset);
  4599. for (i = 0; i < n; i++) {
  4600. if (pfd[i].events & POLLIN) {
  4601. FD_SET(pfd[i].fd, &rset);
  4602. }
  4603. if (pfd[i].events & POLLOUT) {
  4604. FD_SET(pfd[i].fd, &wset);
  4605. }
  4606. pfd[i].revents = 0;
  4607. if (pfd[i].fd > maxfd) {
  4608. maxfd = pfd[i].fd;
  4609. }
  4610. }
  4611. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4612. for (i = 0; i < n; i++) {
  4613. if (FD_ISSET(pfd[i].fd, &rset)) {
  4614. pfd[i].revents |= POLLIN;
  4615. }
  4616. if (FD_ISSET(pfd[i].fd, &wset)) {
  4617. pfd[i].revents |= POLLOUT;
  4618. }
  4619. }
  4620. }
  4621. /* We should subtract the time used in select from remaining
  4622. * "milliseconds", in particular if called from mg_poll with a
  4623. * timeout quantum.
  4624. * Unfortunately, the remaining time is not stored in "tv" in all
  4625. * implementations, so the result in "tv" must be considered undefined.
  4626. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4627. return result;
  4628. }
  4629. #endif /* HAVE_POLL */
  4630. #if defined(GCC_DIAGNOSTIC)
  4631. /* Enable unused function warning again */
  4632. #pragma GCC diagnostic pop
  4633. #endif
  4634. static void
  4635. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4636. {
  4637. (void)conn; /* Unused. */
  4638. #if defined(_WIN32_WCE)
  4639. (void)sock;
  4640. #else
  4641. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4642. #endif
  4643. }
  4644. int
  4645. mg_start_thread(mg_thread_func_t f, void *p)
  4646. {
  4647. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4648. /* Compile-time option to control stack size, e.g.
  4649. * -DUSE_STACK_SIZE=16384
  4650. */
  4651. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4652. == ((uintptr_t)(-1L)))
  4653. ? -1
  4654. : 0);
  4655. #else
  4656. return (
  4657. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4658. ? -1
  4659. : 0);
  4660. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4661. }
  4662. /* Start a thread storing the thread context. */
  4663. static int
  4664. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4665. void *p,
  4666. pthread_t *threadidptr)
  4667. {
  4668. uintptr_t uip;
  4669. HANDLE threadhandle;
  4670. int result = -1;
  4671. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4672. threadhandle = (HANDLE)uip;
  4673. if ((uip != 0) && (threadidptr != NULL)) {
  4674. *threadidptr = threadhandle;
  4675. result = 0;
  4676. }
  4677. return result;
  4678. }
  4679. /* Wait for a thread to finish. */
  4680. static int
  4681. mg_join_thread(pthread_t threadid)
  4682. {
  4683. int result;
  4684. DWORD dwevent;
  4685. result = -1;
  4686. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4687. if (dwevent == WAIT_FAILED) {
  4688. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4689. } else {
  4690. if (dwevent == WAIT_OBJECT_0) {
  4691. CloseHandle(threadid);
  4692. result = 0;
  4693. }
  4694. }
  4695. return result;
  4696. }
  4697. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4698. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4699. /* Create substitutes for POSIX functions in Win32. */
  4700. #if defined(GCC_DIAGNOSTIC)
  4701. /* Show no warning in case system functions are not used. */
  4702. #pragma GCC diagnostic push
  4703. #pragma GCC diagnostic ignored "-Wunused-function"
  4704. #endif
  4705. FUNCTION_MAY_BE_UNUSED
  4706. static HANDLE
  4707. dlopen(const char *dll_name, int flags)
  4708. {
  4709. wchar_t wbuf[W_PATH_MAX];
  4710. (void)flags;
  4711. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4712. return LoadLibraryW(wbuf);
  4713. }
  4714. FUNCTION_MAY_BE_UNUSED
  4715. static int
  4716. dlclose(void *handle)
  4717. {
  4718. int result;
  4719. if (FreeLibrary((HMODULE)handle) != 0) {
  4720. result = 0;
  4721. } else {
  4722. result = -1;
  4723. }
  4724. return result;
  4725. }
  4726. #if defined(GCC_DIAGNOSTIC)
  4727. /* Enable unused function warning again */
  4728. #pragma GCC diagnostic pop
  4729. #endif
  4730. #endif
  4731. #if !defined(NO_CGI)
  4732. #define SIGKILL (0)
  4733. static int
  4734. kill(pid_t pid, int sig_num)
  4735. {
  4736. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4737. (void)CloseHandle((HANDLE)pid);
  4738. return 0;
  4739. }
  4740. #if !defined(WNOHANG)
  4741. #define WNOHANG (1)
  4742. #endif
  4743. static pid_t
  4744. waitpid(pid_t pid, int *status, int flags)
  4745. {
  4746. DWORD timeout = INFINITE;
  4747. DWORD waitres;
  4748. (void)status; /* Currently not used by any client here */
  4749. if ((flags | WNOHANG) == WNOHANG) {
  4750. timeout = 0;
  4751. }
  4752. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4753. if (waitres == WAIT_OBJECT_0) {
  4754. return pid;
  4755. }
  4756. if (waitres == WAIT_TIMEOUT) {
  4757. return 0;
  4758. }
  4759. return (pid_t)-1;
  4760. }
  4761. static void
  4762. trim_trailing_whitespaces(char *s)
  4763. {
  4764. char *e = s + strlen(s);
  4765. while ((e > s) && isspace((unsigned char)e[-1])) {
  4766. *(--e) = '\0';
  4767. }
  4768. }
  4769. static pid_t
  4770. spawn_process(struct mg_connection *conn,
  4771. const char *prog,
  4772. char *envblk,
  4773. char *envp[],
  4774. int fdin[2],
  4775. int fdout[2],
  4776. int fderr[2],
  4777. const char *dir)
  4778. {
  4779. HANDLE me;
  4780. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4781. cmdline[PATH_MAX], buf[PATH_MAX];
  4782. int truncated;
  4783. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4784. STARTUPINFOA si;
  4785. PROCESS_INFORMATION pi = {0};
  4786. (void)envp;
  4787. memset(&si, 0, sizeof(si));
  4788. si.cb = sizeof(si);
  4789. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4790. si.wShowWindow = SW_HIDE;
  4791. me = GetCurrentProcess();
  4792. DuplicateHandle(me,
  4793. (HANDLE)_get_osfhandle(fdin[0]),
  4794. me,
  4795. &si.hStdInput,
  4796. 0,
  4797. TRUE,
  4798. DUPLICATE_SAME_ACCESS);
  4799. DuplicateHandle(me,
  4800. (HANDLE)_get_osfhandle(fdout[1]),
  4801. me,
  4802. &si.hStdOutput,
  4803. 0,
  4804. TRUE,
  4805. DUPLICATE_SAME_ACCESS);
  4806. DuplicateHandle(me,
  4807. (HANDLE)_get_osfhandle(fderr[1]),
  4808. me,
  4809. &si.hStdError,
  4810. 0,
  4811. TRUE,
  4812. DUPLICATE_SAME_ACCESS);
  4813. /* Mark handles that should not be inherited. See
  4814. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4815. */
  4816. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4817. HANDLE_FLAG_INHERIT,
  4818. 0);
  4819. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4820. HANDLE_FLAG_INHERIT,
  4821. 0);
  4822. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4823. HANDLE_FLAG_INHERIT,
  4824. 0);
  4825. /* If CGI file is a script, try to read the interpreter line */
  4826. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4827. if (interp == NULL) {
  4828. buf[0] = buf[1] = '\0';
  4829. /* Read the first line of the script into the buffer */
  4830. mg_snprintf(
  4831. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4832. if (truncated) {
  4833. pi.hProcess = (pid_t)-1;
  4834. goto spawn_cleanup;
  4835. }
  4836. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4837. #if defined(MG_USE_OPEN_FILE)
  4838. p = (char *)file.access.membuf;
  4839. #else
  4840. p = (char *)NULL;
  4841. #endif
  4842. mg_fgets(buf, sizeof(buf), &file, &p);
  4843. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4844. buf[sizeof(buf) - 1] = '\0';
  4845. }
  4846. if ((buf[0] == '#') && (buf[1] == '!')) {
  4847. trim_trailing_whitespaces(buf + 2);
  4848. } else {
  4849. buf[2] = '\0';
  4850. }
  4851. interp = buf + 2;
  4852. }
  4853. if (interp[0] != '\0') {
  4854. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4855. interp = full_interp;
  4856. }
  4857. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4858. if (interp[0] != '\0') {
  4859. mg_snprintf(conn,
  4860. &truncated,
  4861. cmdline,
  4862. sizeof(cmdline),
  4863. "\"%s\" \"%s\\%s\"",
  4864. interp,
  4865. full_dir,
  4866. prog);
  4867. } else {
  4868. mg_snprintf(conn,
  4869. &truncated,
  4870. cmdline,
  4871. sizeof(cmdline),
  4872. "\"%s\\%s\"",
  4873. full_dir,
  4874. prog);
  4875. }
  4876. if (truncated) {
  4877. pi.hProcess = (pid_t)-1;
  4878. goto spawn_cleanup;
  4879. }
  4880. DEBUG_TRACE("Running [%s]", cmdline);
  4881. if (CreateProcessA(NULL,
  4882. cmdline,
  4883. NULL,
  4884. NULL,
  4885. TRUE,
  4886. CREATE_NEW_PROCESS_GROUP,
  4887. envblk,
  4888. NULL,
  4889. &si,
  4890. &pi)
  4891. == 0) {
  4892. mg_cry_internal(
  4893. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4894. pi.hProcess = (pid_t)-1;
  4895. /* goto spawn_cleanup; */
  4896. }
  4897. spawn_cleanup:
  4898. (void)CloseHandle(si.hStdOutput);
  4899. (void)CloseHandle(si.hStdError);
  4900. (void)CloseHandle(si.hStdInput);
  4901. if (pi.hThread != NULL) {
  4902. (void)CloseHandle(pi.hThread);
  4903. }
  4904. return (pid_t)pi.hProcess;
  4905. }
  4906. #endif /* !NO_CGI */
  4907. static int
  4908. set_blocking_mode(SOCKET sock)
  4909. {
  4910. unsigned long non_blocking = 0;
  4911. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4912. }
  4913. static int
  4914. set_non_blocking_mode(SOCKET sock)
  4915. {
  4916. unsigned long non_blocking = 1;
  4917. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4918. }
  4919. #else
  4920. static int
  4921. mg_stat(const struct mg_connection *conn,
  4922. const char *path,
  4923. struct mg_file_stat *filep)
  4924. {
  4925. struct stat st;
  4926. if (!filep) {
  4927. return 0;
  4928. }
  4929. memset(filep, 0, sizeof(*filep));
  4930. if (conn && is_file_in_memory(conn, path)) {
  4931. /* Quick fix (for 1.9.x): */
  4932. /* mg_stat must fill all fields, also for files in memory */
  4933. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4934. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4935. filep->size = tmp_file.stat.size;
  4936. filep->last_modified = time(NULL);
  4937. filep->location = 2;
  4938. /* TODO: remove legacy "files in memory" feature */
  4939. return 1;
  4940. }
  4941. if (0 == stat(path, &st)) {
  4942. filep->size = (uint64_t)(st.st_size);
  4943. filep->last_modified = st.st_mtime;
  4944. filep->is_directory = S_ISDIR(st.st_mode);
  4945. return 1;
  4946. }
  4947. return 0;
  4948. }
  4949. static void
  4950. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4951. {
  4952. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4953. if (conn) {
  4954. mg_cry_internal(conn,
  4955. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4956. __func__,
  4957. strerror(ERRNO));
  4958. }
  4959. }
  4960. }
  4961. int
  4962. mg_start_thread(mg_thread_func_t func, void *param)
  4963. {
  4964. pthread_t thread_id;
  4965. pthread_attr_t attr;
  4966. int result;
  4967. (void)pthread_attr_init(&attr);
  4968. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4969. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4970. /* Compile-time option to control stack size,
  4971. * e.g. -DUSE_STACK_SIZE=16384 */
  4972. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4973. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4974. result = pthread_create(&thread_id, &attr, func, param);
  4975. pthread_attr_destroy(&attr);
  4976. return result;
  4977. }
  4978. /* Start a thread storing the thread context. */
  4979. static int
  4980. mg_start_thread_with_id(mg_thread_func_t func,
  4981. void *param,
  4982. pthread_t *threadidptr)
  4983. {
  4984. pthread_t thread_id;
  4985. pthread_attr_t attr;
  4986. int result;
  4987. (void)pthread_attr_init(&attr);
  4988. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4989. /* Compile-time option to control stack size,
  4990. * e.g. -DUSE_STACK_SIZE=16384 */
  4991. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4992. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4993. result = pthread_create(&thread_id, &attr, func, param);
  4994. pthread_attr_destroy(&attr);
  4995. if ((result == 0) && (threadidptr != NULL)) {
  4996. *threadidptr = thread_id;
  4997. }
  4998. return result;
  4999. }
  5000. /* Wait for a thread to finish. */
  5001. static int
  5002. mg_join_thread(pthread_t threadid)
  5003. {
  5004. int result;
  5005. result = pthread_join(threadid, NULL);
  5006. return result;
  5007. }
  5008. #if !defined(NO_CGI)
  5009. static pid_t
  5010. spawn_process(struct mg_connection *conn,
  5011. const char *prog,
  5012. char *envblk,
  5013. char *envp[],
  5014. int fdin[2],
  5015. int fdout[2],
  5016. int fderr[2],
  5017. const char *dir)
  5018. {
  5019. pid_t pid;
  5020. const char *interp;
  5021. (void)envblk;
  5022. if (conn == NULL) {
  5023. return 0;
  5024. }
  5025. if ((pid = fork()) == -1) {
  5026. /* Parent */
  5027. mg_send_http_error(conn,
  5028. 500,
  5029. "Error: Creating CGI process\nfork(): %s",
  5030. strerror(ERRNO));
  5031. } else if (pid == 0) {
  5032. /* Child */
  5033. if (chdir(dir) != 0) {
  5034. mg_cry_internal(
  5035. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5036. } else if (dup2(fdin[0], 0) == -1) {
  5037. mg_cry_internal(conn,
  5038. "%s: dup2(%d, 0): %s",
  5039. __func__,
  5040. fdin[0],
  5041. strerror(ERRNO));
  5042. } else if (dup2(fdout[1], 1) == -1) {
  5043. mg_cry_internal(conn,
  5044. "%s: dup2(%d, 1): %s",
  5045. __func__,
  5046. fdout[1],
  5047. strerror(ERRNO));
  5048. } else if (dup2(fderr[1], 2) == -1) {
  5049. mg_cry_internal(conn,
  5050. "%s: dup2(%d, 2): %s",
  5051. __func__,
  5052. fderr[1],
  5053. strerror(ERRNO));
  5054. } else {
  5055. struct sigaction sa;
  5056. /* Keep stderr and stdout in two different pipes.
  5057. * Stdout will be sent back to the client,
  5058. * stderr should go into a server error log. */
  5059. (void)close(fdin[0]);
  5060. (void)close(fdout[1]);
  5061. (void)close(fderr[1]);
  5062. /* Close write end fdin and read end fdout and fderr */
  5063. (void)close(fdin[1]);
  5064. (void)close(fdout[0]);
  5065. (void)close(fderr[0]);
  5066. /* After exec, all signal handlers are restored to their default
  5067. * values, with one exception of SIGCHLD. According to
  5068. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5069. * will leave unchanged after exec if it was set to be ignored.
  5070. * Restore it to default action. */
  5071. memset(&sa, 0, sizeof(sa));
  5072. sa.sa_handler = SIG_DFL;
  5073. sigaction(SIGCHLD, &sa, NULL);
  5074. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5075. if (interp == NULL) {
  5076. (void)execle(prog, prog, NULL, envp);
  5077. mg_cry_internal(conn,
  5078. "%s: execle(%s): %s",
  5079. __func__,
  5080. prog,
  5081. strerror(ERRNO));
  5082. } else {
  5083. (void)execle(interp, interp, prog, NULL, envp);
  5084. mg_cry_internal(conn,
  5085. "%s: execle(%s %s): %s",
  5086. __func__,
  5087. interp,
  5088. prog,
  5089. strerror(ERRNO));
  5090. }
  5091. }
  5092. exit(EXIT_FAILURE);
  5093. }
  5094. return pid;
  5095. }
  5096. #endif /* !NO_CGI */
  5097. static int
  5098. set_non_blocking_mode(SOCKET sock)
  5099. {
  5100. int flags = fcntl(sock, F_GETFL, 0);
  5101. if (flags < 0) {
  5102. return -1;
  5103. }
  5104. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5105. return -1;
  5106. }
  5107. return 0;
  5108. }
  5109. static int
  5110. set_blocking_mode(SOCKET sock)
  5111. {
  5112. int flags = fcntl(sock, F_GETFL, 0);
  5113. if (flags < 0) {
  5114. return -1;
  5115. }
  5116. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5117. return -1;
  5118. }
  5119. return 0;
  5120. }
  5121. #endif /* _WIN32 / else */
  5122. /* End of initial operating system specific define block. */
  5123. /* Get a random number (independent of C rand function) */
  5124. static uint64_t
  5125. get_random(void)
  5126. {
  5127. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5128. static uint64_t lcg = 0; /* Linear congruential generator */
  5129. uint64_t now = mg_get_current_time_ns();
  5130. if (lfsr == 0) {
  5131. /* lfsr will be only 0 if has not been initialized,
  5132. * so this code is called only once. */
  5133. lfsr = mg_get_current_time_ns();
  5134. lcg = mg_get_current_time_ns();
  5135. } else {
  5136. /* Get the next step of both random number generators. */
  5137. lfsr = (lfsr >> 1)
  5138. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5139. << 63);
  5140. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5141. }
  5142. /* Combining two pseudo-random number generators and a high resolution
  5143. * part
  5144. * of the current server time will make it hard (impossible?) to guess
  5145. * the
  5146. * next number. */
  5147. return (lfsr ^ lcg ^ now);
  5148. }
  5149. static int
  5150. mg_poll(struct mg_pollfd *pfd,
  5151. unsigned int n,
  5152. int milliseconds,
  5153. volatile int *stop_server)
  5154. {
  5155. /* Call poll, but only for a maximum time of a few seconds.
  5156. * This will allow to stop the server after some seconds, instead
  5157. * of having to wait for a long socket timeout. */
  5158. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5159. do {
  5160. int result;
  5161. if (*stop_server) {
  5162. /* Shut down signal */
  5163. return -2;
  5164. }
  5165. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5166. ms_now = milliseconds;
  5167. }
  5168. result = poll(pfd, n, ms_now);
  5169. if (result != 0) {
  5170. /* Poll returned either success (1) or error (-1).
  5171. * Forward both to the caller. */
  5172. return result;
  5173. }
  5174. /* Poll returned timeout (0). */
  5175. if (milliseconds > 0) {
  5176. milliseconds -= ms_now;
  5177. }
  5178. } while (milliseconds != 0);
  5179. /* timeout: return 0 */
  5180. return 0;
  5181. }
  5182. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5183. * descriptor.
  5184. * Return value:
  5185. * >=0 .. number of bytes successfully written
  5186. * -1 .. timeout
  5187. * -2 .. error
  5188. */
  5189. static int
  5190. push_inner(struct mg_context *ctx,
  5191. FILE *fp,
  5192. SOCKET sock,
  5193. SSL *ssl,
  5194. const char *buf,
  5195. int len,
  5196. double timeout)
  5197. {
  5198. uint64_t start = 0, now = 0, timeout_ns = 0;
  5199. int n, err;
  5200. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5201. #if defined(_WIN32)
  5202. typedef int len_t;
  5203. #else
  5204. typedef size_t len_t;
  5205. #endif
  5206. if (timeout > 0) {
  5207. now = mg_get_current_time_ns();
  5208. start = now;
  5209. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5210. }
  5211. if (ctx == NULL) {
  5212. return -2;
  5213. }
  5214. #if defined(NO_SSL)
  5215. if (ssl) {
  5216. return -2;
  5217. }
  5218. #endif
  5219. /* Try to read until it succeeds, fails, times out, or the server
  5220. * shuts down. */
  5221. for (;;) {
  5222. #if !defined(NO_SSL)
  5223. if (ssl != NULL) {
  5224. n = SSL_write(ssl, buf, len);
  5225. if (n <= 0) {
  5226. err = SSL_get_error(ssl, n);
  5227. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5228. err = ERRNO;
  5229. } else if ((err == SSL_ERROR_WANT_READ)
  5230. || (err == SSL_ERROR_WANT_WRITE)) {
  5231. n = 0;
  5232. } else {
  5233. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5234. return -2;
  5235. }
  5236. } else {
  5237. err = 0;
  5238. }
  5239. } else
  5240. #endif
  5241. if (fp != NULL) {
  5242. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5243. if (ferror(fp)) {
  5244. n = -1;
  5245. err = ERRNO;
  5246. } else {
  5247. err = 0;
  5248. }
  5249. } else {
  5250. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5251. err = (n < 0) ? ERRNO : 0;
  5252. #if defined(_WIN32)
  5253. if (err == WSAEWOULDBLOCK) {
  5254. err = 0;
  5255. n = 0;
  5256. }
  5257. #else
  5258. if (err == EWOULDBLOCK) {
  5259. err = 0;
  5260. n = 0;
  5261. }
  5262. #endif
  5263. if (n < 0) {
  5264. /* shutdown of the socket at client side */
  5265. return -2;
  5266. }
  5267. }
  5268. if (ctx->stop_flag) {
  5269. return -2;
  5270. }
  5271. if ((n > 0) || ((n == 0) && (len == 0))) {
  5272. /* some data has been read, or no data was requested */
  5273. return n;
  5274. }
  5275. if (n < 0) {
  5276. /* socket error - check errno */
  5277. DEBUG_TRACE("send() failed, error %d", err);
  5278. /* TODO (mid): error handling depending on the error code.
  5279. * These codes are different between Windows and Linux.
  5280. * Currently there is no problem with failing send calls,
  5281. * if there is a reproducible situation, it should be
  5282. * investigated in detail.
  5283. */
  5284. return -2;
  5285. }
  5286. /* Only in case n=0 (timeout), repeat calling the write function */
  5287. /* If send failed, wait before retry */
  5288. if (fp != NULL) {
  5289. /* For files, just wait a fixed time.
  5290. * Maybe it helps, maybe not. */
  5291. mg_sleep(5);
  5292. } else {
  5293. /* For sockets, wait for the socket using poll */
  5294. struct mg_pollfd pfd[1];
  5295. int pollres;
  5296. pfd[0].fd = sock;
  5297. pfd[0].events = POLLOUT;
  5298. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5299. if (ctx->stop_flag) {
  5300. return -2;
  5301. }
  5302. if (pollres > 0) {
  5303. continue;
  5304. }
  5305. }
  5306. if (timeout > 0) {
  5307. now = mg_get_current_time_ns();
  5308. if ((now - start) > timeout_ns) {
  5309. /* Timeout */
  5310. break;
  5311. }
  5312. }
  5313. }
  5314. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5315. used */
  5316. return -1;
  5317. }
  5318. static int
  5319. push_all(struct mg_context *ctx,
  5320. FILE *fp,
  5321. SOCKET sock,
  5322. SSL *ssl,
  5323. const char *buf,
  5324. int len)
  5325. {
  5326. double timeout = -1.0;
  5327. int n, nwritten = 0;
  5328. if (ctx == NULL) {
  5329. return -1;
  5330. }
  5331. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5332. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5333. }
  5334. while ((len > 0) && (ctx->stop_flag == 0)) {
  5335. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5336. if (n < 0) {
  5337. if (nwritten == 0) {
  5338. nwritten = -1; /* Propagate the error */
  5339. }
  5340. break;
  5341. } else if (n == 0) {
  5342. break; /* No more data to write */
  5343. } else {
  5344. nwritten += n;
  5345. len -= n;
  5346. }
  5347. }
  5348. return nwritten;
  5349. }
  5350. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5351. * Return value:
  5352. * >=0 .. number of bytes successfully read
  5353. * -1 .. timeout
  5354. * -2 .. error
  5355. */
  5356. static int
  5357. pull_inner(FILE *fp,
  5358. struct mg_connection *conn,
  5359. char *buf,
  5360. int len,
  5361. double timeout)
  5362. {
  5363. int nread, err = 0;
  5364. #if defined(_WIN32)
  5365. typedef int len_t;
  5366. #else
  5367. typedef size_t len_t;
  5368. #endif
  5369. #if !defined(NO_SSL)
  5370. int ssl_pending;
  5371. #endif
  5372. /* We need an additional wait loop around this, because in some cases
  5373. * with TLSwe may get data from the socket but not from SSL_read.
  5374. * In this case we need to repeat at least once.
  5375. */
  5376. if (fp != NULL) {
  5377. #if !defined(_WIN32_WCE)
  5378. /* Use read() instead of fread(), because if we're reading from the
  5379. * CGI pipe, fread() may block until IO buffer is filled up. We
  5380. * cannot afford to block and must pass all read bytes immediately
  5381. * to the client. */
  5382. nread = (int)read(fileno(fp), buf, (size_t)len);
  5383. #else
  5384. /* WinCE does not support CGI pipes */
  5385. nread = (int)fread(buf, 1, (size_t)len, fp);
  5386. #endif
  5387. err = (nread < 0) ? ERRNO : 0;
  5388. if ((nread == 0) && (len > 0)) {
  5389. /* Should get data, but got EOL */
  5390. return -2;
  5391. }
  5392. #if !defined(NO_SSL)
  5393. } else if ((conn->ssl != NULL)
  5394. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5395. /* We already know there is no more data buffered in conn->buf
  5396. * but there is more available in the SSL layer. So don't poll
  5397. * conn->client.sock yet. */
  5398. if (ssl_pending > len) {
  5399. ssl_pending = len;
  5400. }
  5401. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5402. if (nread <= 0) {
  5403. err = SSL_get_error(conn->ssl, nread);
  5404. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5405. err = ERRNO;
  5406. } else if ((err == SSL_ERROR_WANT_READ)
  5407. || (err == SSL_ERROR_WANT_WRITE)) {
  5408. nread = 0;
  5409. } else {
  5410. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5411. return -1;
  5412. }
  5413. ERR_clear_error();
  5414. } else {
  5415. err = 0;
  5416. }
  5417. } else if (conn->ssl != NULL) {
  5418. struct mg_pollfd pfd[1];
  5419. int pollres;
  5420. pfd[0].fd = conn->client.sock;
  5421. pfd[0].events = POLLIN;
  5422. pollres = mg_poll(pfd,
  5423. 1,
  5424. (int)(timeout * 1000.0),
  5425. &(conn->phys_ctx->stop_flag));
  5426. if (conn->phys_ctx->stop_flag) {
  5427. return -2;
  5428. }
  5429. if (pollres > 0) {
  5430. nread = SSL_read(conn->ssl, buf, len);
  5431. if (nread <= 0) {
  5432. err = SSL_get_error(conn->ssl, nread);
  5433. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5434. err = ERRNO;
  5435. } else if ((err == SSL_ERROR_WANT_READ)
  5436. || (err == SSL_ERROR_WANT_WRITE)) {
  5437. nread = 0;
  5438. } else {
  5439. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5440. return -2;
  5441. }
  5442. } else {
  5443. err = 0;
  5444. }
  5445. ERR_clear_error();
  5446. } else if (pollres < 0) {
  5447. /* Error */
  5448. return -2;
  5449. } else {
  5450. /* pollres = 0 means timeout */
  5451. nread = 0;
  5452. }
  5453. #endif
  5454. } else {
  5455. struct mg_pollfd pfd[1];
  5456. int pollres;
  5457. pfd[0].fd = conn->client.sock;
  5458. pfd[0].events = POLLIN;
  5459. pollres = mg_poll(pfd,
  5460. 1,
  5461. (int)(timeout * 1000.0),
  5462. &(conn->phys_ctx->stop_flag));
  5463. if (conn->phys_ctx->stop_flag) {
  5464. return -2;
  5465. }
  5466. if (pollres > 0) {
  5467. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5468. err = (nread < 0) ? ERRNO : 0;
  5469. if (nread <= 0) {
  5470. /* shutdown of the socket at client side */
  5471. return -2;
  5472. }
  5473. } else if (pollres < 0) {
  5474. /* error callint poll */
  5475. return -2;
  5476. } else {
  5477. /* pollres = 0 means timeout */
  5478. nread = 0;
  5479. }
  5480. }
  5481. if (conn->phys_ctx->stop_flag) {
  5482. return -2;
  5483. }
  5484. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5485. /* some data has been read, or no data was requested */
  5486. return nread;
  5487. }
  5488. if (nread < 0) {
  5489. /* socket error - check errno */
  5490. #if defined(_WIN32)
  5491. if (err == WSAEWOULDBLOCK) {
  5492. /* TODO (low): check if this is still required */
  5493. /* standard case if called from close_socket_gracefully */
  5494. return -2;
  5495. } else if (err == WSAETIMEDOUT) {
  5496. /* TODO (low): check if this is still required */
  5497. /* timeout is handled by the while loop */
  5498. return 0;
  5499. } else if (err == WSAECONNABORTED) {
  5500. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5501. return -2;
  5502. } else {
  5503. DEBUG_TRACE("recv() failed, error %d", err);
  5504. return -2;
  5505. }
  5506. #else
  5507. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5508. * if the timeout is reached and if the socket was set to non-
  5509. * blocking in close_socket_gracefully, so we can not distinguish
  5510. * here. We have to wait for the timeout in both cases for now.
  5511. */
  5512. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5513. /* TODO (low): check if this is still required */
  5514. /* EAGAIN/EWOULDBLOCK:
  5515. * standard case if called from close_socket_gracefully
  5516. * => should return -1 */
  5517. /* or timeout occurred
  5518. * => the code must stay in the while loop */
  5519. /* EINTR can be generated on a socket with a timeout set even
  5520. * when SA_RESTART is effective for all relevant signals
  5521. * (see signal(7)).
  5522. * => stay in the while loop */
  5523. } else {
  5524. DEBUG_TRACE("recv() failed, error %d", err);
  5525. return -2;
  5526. }
  5527. #endif
  5528. }
  5529. /* Timeout occurred, but no data available. */
  5530. return -1;
  5531. }
  5532. static int
  5533. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5534. {
  5535. int n, nread = 0;
  5536. double timeout = -1.0;
  5537. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5538. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5539. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5540. }
  5541. if (timeout >= 0.0) {
  5542. start_time = mg_get_current_time_ns();
  5543. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5544. }
  5545. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5546. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5547. if (n == -2) {
  5548. if (nread == 0) {
  5549. nread = -1; /* Propagate the error */
  5550. }
  5551. break;
  5552. } else if (n == -1) {
  5553. /* timeout */
  5554. if (timeout >= 0.0) {
  5555. now = mg_get_current_time_ns();
  5556. if ((now - start_time) <= timeout_ns) {
  5557. continue;
  5558. }
  5559. }
  5560. break;
  5561. } else if (n == 0) {
  5562. break; /* No more data to read */
  5563. } else {
  5564. nread += n;
  5565. len -= n;
  5566. }
  5567. }
  5568. return nread;
  5569. }
  5570. static void
  5571. discard_unread_request_data(struct mg_connection *conn)
  5572. {
  5573. char buf[MG_BUF_LEN];
  5574. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5575. ;
  5576. }
  5577. static int
  5578. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5579. {
  5580. int64_t content_len, n, buffered_len, nread;
  5581. int64_t len64 =
  5582. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5583. * int, we may not read more
  5584. * bytes */
  5585. const char *body;
  5586. if (conn == NULL) {
  5587. return 0;
  5588. }
  5589. /* If Content-Length is not set for a response with body data,
  5590. * we do not know in advance how much data should be read. */
  5591. content_len = conn->content_len;
  5592. if (content_len < 0) {
  5593. /* The body data is completed when the connection is closed. */
  5594. content_len = INT64_MAX;
  5595. }
  5596. nread = 0;
  5597. if (conn->consumed_content < content_len) {
  5598. /* Adjust number of bytes to read. */
  5599. int64_t left_to_read = content_len - conn->consumed_content;
  5600. if (left_to_read < len64) {
  5601. /* Do not read more than the total content length of the
  5602. * request.
  5603. */
  5604. len64 = left_to_read;
  5605. }
  5606. /* Return buffered data */
  5607. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5608. - conn->consumed_content;
  5609. if (buffered_len > 0) {
  5610. if (len64 < buffered_len) {
  5611. buffered_len = len64;
  5612. }
  5613. body = conn->buf + conn->request_len + conn->consumed_content;
  5614. memcpy(buf, body, (size_t)buffered_len);
  5615. len64 -= buffered_len;
  5616. conn->consumed_content += buffered_len;
  5617. nread += buffered_len;
  5618. buf = (char *)buf + buffered_len;
  5619. }
  5620. /* We have returned all buffered data. Read new data from the remote
  5621. * socket.
  5622. */
  5623. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5624. conn->consumed_content += n;
  5625. nread += n;
  5626. } else {
  5627. nread = ((nread > 0) ? nread : n);
  5628. }
  5629. }
  5630. return (int)nread;
  5631. }
  5632. int
  5633. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5634. {
  5635. if (len > INT_MAX) {
  5636. len = INT_MAX;
  5637. }
  5638. if (conn == NULL) {
  5639. return 0;
  5640. }
  5641. if (conn->is_chunked) {
  5642. size_t all_read = 0;
  5643. while (len > 0) {
  5644. if (conn->is_chunked >= 3) {
  5645. /* No more data left to read */
  5646. return 0;
  5647. }
  5648. if (conn->is_chunked != 1) {
  5649. /* Has error */
  5650. return -1;
  5651. }
  5652. if (conn->consumed_content != conn->content_len) {
  5653. /* copy from the current chunk */
  5654. int read_ret = mg_read_inner(conn, (char *)buf + all_read,
  5655. len);
  5656. if (read_ret < 1) {
  5657. /* read error */
  5658. conn->is_chunked = 2;
  5659. return -1;
  5660. }
  5661. all_read += (size_t)read_ret;
  5662. len -= (size_t)read_ret;
  5663. if (conn->consumed_content == conn->content_len) {
  5664. /* Add data bytes in the current chunk have been read,
  5665. * so we are expecting \r\n now. */
  5666. char x[2];
  5667. conn->content_len += 2;
  5668. if ((mg_read_inner(conn, x, 2) != 2)
  5669. || (x[0] != '\r') || (x[1] != '\n')) {
  5670. /* Protocol violation */
  5671. conn->is_chunked = 2;
  5672. return -1;
  5673. }
  5674. }
  5675. } else {
  5676. /* fetch a new chunk */
  5677. size_t i;
  5678. char lenbuf[64];
  5679. char *end = NULL;
  5680. unsigned long chunkSize = 0;
  5681. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5682. conn->content_len++;
  5683. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5684. lenbuf[i] = 0;
  5685. }
  5686. if ((i > 0) && (lenbuf[i] == '\r')
  5687. && (lenbuf[i - 1] != '\r')) {
  5688. continue;
  5689. }
  5690. if ((i > 1) && (lenbuf[i] == '\n')
  5691. && (lenbuf[i - 1] == '\r')) {
  5692. lenbuf[i + 1] = 0;
  5693. chunkSize = strtoul(lenbuf, &end, 16);
  5694. if (chunkSize == 0) {
  5695. /* regular end of content */
  5696. conn->is_chunked = 3;
  5697. }
  5698. break;
  5699. }
  5700. if (!isxdigit((unsigned char)lenbuf[i])) {
  5701. /* illegal character for chunk length */
  5702. conn->is_chunked = 2;
  5703. return -1;
  5704. }
  5705. }
  5706. if ((end == NULL) || (*end != '\r')) {
  5707. /* chunksize not set correctly */
  5708. conn->is_chunked = 2;
  5709. return -1;
  5710. }
  5711. if (chunkSize == 0) {
  5712. /* try discarding trailer for keep-alive */
  5713. conn->content_len += 2;
  5714. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5715. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5716. conn->is_chunked = 4;
  5717. }
  5718. break;
  5719. }
  5720. /* append a new chunk */
  5721. conn->content_len += chunkSize;
  5722. }
  5723. }
  5724. return (int)all_read;
  5725. }
  5726. return mg_read_inner(conn, buf, len);
  5727. }
  5728. int
  5729. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5730. {
  5731. time_t now;
  5732. int n, total, allowed;
  5733. if (conn == NULL) {
  5734. return 0;
  5735. }
  5736. if (len > INT_MAX) {
  5737. return -1;
  5738. }
  5739. if (conn->throttle > 0) {
  5740. if ((now = time(NULL)) != conn->last_throttle_time) {
  5741. conn->last_throttle_time = now;
  5742. conn->last_throttle_bytes = 0;
  5743. }
  5744. allowed = conn->throttle - conn->last_throttle_bytes;
  5745. if (allowed > (int)len) {
  5746. allowed = (int)len;
  5747. }
  5748. if ((total = push_all(conn->phys_ctx,
  5749. NULL,
  5750. conn->client.sock,
  5751. conn->ssl,
  5752. (const char *)buf,
  5753. allowed))
  5754. == allowed) {
  5755. buf = (const char *)buf + total;
  5756. conn->last_throttle_bytes += total;
  5757. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5758. allowed = (conn->throttle > ((int)len - total))
  5759. ? (int)len - total
  5760. : conn->throttle;
  5761. if ((n = push_all(conn->phys_ctx,
  5762. NULL,
  5763. conn->client.sock,
  5764. conn->ssl,
  5765. (const char *)buf,
  5766. allowed))
  5767. != allowed) {
  5768. break;
  5769. }
  5770. sleep(1);
  5771. conn->last_throttle_bytes = allowed;
  5772. conn->last_throttle_time = time(NULL);
  5773. buf = (const char *)buf + n;
  5774. total += n;
  5775. }
  5776. }
  5777. } else {
  5778. total = push_all(conn->phys_ctx,
  5779. NULL,
  5780. conn->client.sock,
  5781. conn->ssl,
  5782. (const char *)buf,
  5783. (int)len);
  5784. }
  5785. if (total > 0) {
  5786. conn->num_bytes_sent += total;
  5787. }
  5788. return total;
  5789. }
  5790. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5791. int
  5792. mg_send_chunk(struct mg_connection *conn,
  5793. const char *chunk,
  5794. unsigned int chunk_len)
  5795. {
  5796. char lenbuf[16];
  5797. size_t lenbuf_len;
  5798. int ret;
  5799. int t;
  5800. /* First store the length information in a text buffer. */
  5801. sprintf(lenbuf, "%x\r\n", chunk_len);
  5802. lenbuf_len = strlen(lenbuf);
  5803. /* Then send length information, chunk and terminating \r\n. */
  5804. ret = mg_write(conn, lenbuf, lenbuf_len);
  5805. if (ret != (int)lenbuf_len) {
  5806. return -1;
  5807. }
  5808. t = ret;
  5809. ret = mg_write(conn, chunk, chunk_len);
  5810. if (ret != (int)chunk_len) {
  5811. return -1;
  5812. }
  5813. t += ret;
  5814. ret = mg_write(conn, "\r\n", 2);
  5815. if (ret != 2) {
  5816. return -1;
  5817. }
  5818. t += ret;
  5819. return t;
  5820. }
  5821. #if defined(GCC_DIAGNOSTIC)
  5822. /* This block forwards format strings to printf implementations,
  5823. * so we need to disable the format-nonliteral warning. */
  5824. #pragma GCC diagnostic push
  5825. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5826. #endif
  5827. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5828. static int
  5829. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5830. {
  5831. va_list ap_copy;
  5832. size_t size = MG_BUF_LEN / 4;
  5833. int len = -1;
  5834. *buf = NULL;
  5835. while (len < 0) {
  5836. if (*buf) {
  5837. mg_free(*buf);
  5838. }
  5839. size *= 4;
  5840. *buf = (char *)mg_malloc(size);
  5841. if (!*buf) {
  5842. break;
  5843. }
  5844. va_copy(ap_copy, ap);
  5845. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5846. va_end(ap_copy);
  5847. (*buf)[size - 1] = 0;
  5848. }
  5849. return len;
  5850. }
  5851. /* Print message to buffer. If buffer is large enough to hold the message,
  5852. * return buffer. If buffer is to small, allocate large enough buffer on
  5853. * heap,
  5854. * and return allocated buffer. */
  5855. static int
  5856. alloc_vprintf(char **out_buf,
  5857. char *prealloc_buf,
  5858. size_t prealloc_size,
  5859. const char *fmt,
  5860. va_list ap)
  5861. {
  5862. va_list ap_copy;
  5863. int len;
  5864. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5865. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5866. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5867. * Therefore, we make two passes: on first pass, get required message
  5868. * length.
  5869. * On second pass, actually print the message. */
  5870. va_copy(ap_copy, ap);
  5871. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5872. va_end(ap_copy);
  5873. if (len < 0) {
  5874. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5875. * Switch to alternative code path that uses incremental
  5876. * allocations.
  5877. */
  5878. va_copy(ap_copy, ap);
  5879. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5880. va_end(ap_copy);
  5881. } else if ((size_t)(len) >= prealloc_size) {
  5882. /* The pre-allocated buffer not large enough. */
  5883. /* Allocate a new buffer. */
  5884. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5885. if (!*out_buf) {
  5886. /* Allocation failed. Return -1 as "out of memory" error. */
  5887. return -1;
  5888. }
  5889. /* Buffer allocation successful. Store the string there. */
  5890. va_copy(ap_copy, ap);
  5891. IGNORE_UNUSED_RESULT(
  5892. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5893. va_end(ap_copy);
  5894. } else {
  5895. /* The pre-allocated buffer is large enough.
  5896. * Use it to store the string and return the address. */
  5897. va_copy(ap_copy, ap);
  5898. IGNORE_UNUSED_RESULT(
  5899. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5900. va_end(ap_copy);
  5901. *out_buf = prealloc_buf;
  5902. }
  5903. return len;
  5904. }
  5905. #if defined(GCC_DIAGNOSTIC)
  5906. /* Enable format-nonliteral warning again. */
  5907. #pragma GCC diagnostic pop
  5908. #endif
  5909. static int
  5910. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5911. {
  5912. char mem[MG_BUF_LEN];
  5913. char *buf = NULL;
  5914. int len;
  5915. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5916. len = mg_write(conn, buf, (size_t)len);
  5917. }
  5918. if (buf != mem) {
  5919. mg_free(buf);
  5920. }
  5921. return len;
  5922. }
  5923. int
  5924. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5925. {
  5926. va_list ap;
  5927. int result;
  5928. va_start(ap, fmt);
  5929. result = mg_vprintf(conn, fmt, ap);
  5930. va_end(ap);
  5931. return result;
  5932. }
  5933. int
  5934. mg_url_decode(const char *src,
  5935. int src_len,
  5936. char *dst,
  5937. int dst_len,
  5938. int is_form_url_encoded)
  5939. {
  5940. int i, j, a, b;
  5941. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5942. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5943. if ((i < src_len - 2) && (src[i] == '%')
  5944. && isxdigit((unsigned char)src[i + 1])
  5945. && isxdigit((unsigned char)src[i + 2])) {
  5946. a = tolower((unsigned char)src[i + 1]);
  5947. b = tolower((unsigned char)src[i + 2]);
  5948. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5949. i += 2;
  5950. } else if (is_form_url_encoded && (src[i] == '+')) {
  5951. dst[j] = ' ';
  5952. } else {
  5953. dst[j] = src[i];
  5954. }
  5955. }
  5956. dst[j] = '\0'; /* Null-terminate the destination */
  5957. return (i >= src_len) ? j : -1;
  5958. }
  5959. int
  5960. mg_get_var(const char *data,
  5961. size_t data_len,
  5962. const char *name,
  5963. char *dst,
  5964. size_t dst_len)
  5965. {
  5966. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5967. }
  5968. int
  5969. mg_get_var2(const char *data,
  5970. size_t data_len,
  5971. const char *name,
  5972. char *dst,
  5973. size_t dst_len,
  5974. size_t occurrence)
  5975. {
  5976. const char *p, *e, *s;
  5977. size_t name_len;
  5978. int len;
  5979. if ((dst == NULL) || (dst_len == 0)) {
  5980. len = -2;
  5981. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5982. len = -1;
  5983. dst[0] = '\0';
  5984. } else {
  5985. name_len = strlen(name);
  5986. e = data + data_len;
  5987. len = -1;
  5988. dst[0] = '\0';
  5989. /* data is "var1=val1&var2=val2...". Find variable first */
  5990. for (p = data; p + name_len < e; p++) {
  5991. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5992. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5993. /* Point p to variable value */
  5994. p += name_len + 1;
  5995. /* Point s to the end of the value */
  5996. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5997. if (s == NULL) {
  5998. s = e;
  5999. }
  6000. DEBUG_ASSERT(s >= p);
  6001. if (s < p) {
  6002. return -3;
  6003. }
  6004. /* Decode variable into destination buffer */
  6005. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6006. /* Redirect error code from -1 to -2 (destination buffer too
  6007. * small). */
  6008. if (len == -1) {
  6009. len = -2;
  6010. }
  6011. break;
  6012. }
  6013. }
  6014. }
  6015. return len;
  6016. }
  6017. /* HCP24: some changes to compare hole var_name */
  6018. int
  6019. mg_get_cookie(const char *cookie_header,
  6020. const char *var_name,
  6021. char *dst,
  6022. size_t dst_size)
  6023. {
  6024. const char *s, *p, *end;
  6025. int name_len, len = -1;
  6026. if ((dst == NULL) || (dst_size == 0)) {
  6027. return -2;
  6028. }
  6029. dst[0] = '\0';
  6030. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6031. return -1;
  6032. }
  6033. name_len = (int)strlen(var_name);
  6034. end = s + strlen(s);
  6035. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6036. if (s[name_len] == '=') {
  6037. /* HCP24: now check is it a substring or a full cookie name */
  6038. if ((s == cookie_header) || (s[-1] == ' ')) {
  6039. s += name_len + 1;
  6040. if ((p = strchr(s, ' ')) == NULL) {
  6041. p = end;
  6042. }
  6043. if (p[-1] == ';') {
  6044. p--;
  6045. }
  6046. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6047. s++;
  6048. p--;
  6049. }
  6050. if ((size_t)(p - s) < dst_size) {
  6051. len = (int)(p - s);
  6052. mg_strlcpy(dst, s, (size_t)len + 1);
  6053. } else {
  6054. len = -3;
  6055. }
  6056. break;
  6057. }
  6058. }
  6059. }
  6060. return len;
  6061. }
  6062. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6063. static void
  6064. base64_encode(const unsigned char *src, int src_len, char *dst)
  6065. {
  6066. static const char *b64 =
  6067. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6068. int i, j, a, b, c;
  6069. for (i = j = 0; i < src_len; i += 3) {
  6070. a = src[i];
  6071. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6072. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6073. dst[j++] = b64[a >> 2];
  6074. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6075. if (i + 1 < src_len) {
  6076. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6077. }
  6078. if (i + 2 < src_len) {
  6079. dst[j++] = b64[c & 63];
  6080. }
  6081. }
  6082. while (j % 4 != 0) {
  6083. dst[j++] = '=';
  6084. }
  6085. dst[j++] = '\0';
  6086. }
  6087. #endif
  6088. #if defined(USE_LUA)
  6089. static unsigned char
  6090. b64reverse(char letter)
  6091. {
  6092. if ((letter >= 'A') && (letter <= 'Z')) {
  6093. return letter - 'A';
  6094. }
  6095. if ((letter >= 'a') && (letter <= 'z')) {
  6096. return letter - 'a' + 26;
  6097. }
  6098. if ((letter >= '0') && (letter <= '9')) {
  6099. return letter - '0' + 52;
  6100. }
  6101. if (letter == '+') {
  6102. return 62;
  6103. }
  6104. if (letter == '/') {
  6105. return 63;
  6106. }
  6107. if (letter == '=') {
  6108. return 255; /* normal end */
  6109. }
  6110. return 254; /* error */
  6111. }
  6112. static int
  6113. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6114. {
  6115. int i;
  6116. unsigned char a, b, c, d;
  6117. *dst_len = 0;
  6118. for (i = 0; i < src_len; i += 4) {
  6119. a = b64reverse(src[i]);
  6120. if (a >= 254) {
  6121. return i;
  6122. }
  6123. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6124. if (b >= 254) {
  6125. return i + 1;
  6126. }
  6127. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6128. if (c == 254) {
  6129. return i + 2;
  6130. }
  6131. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6132. if (d == 254) {
  6133. return i + 3;
  6134. }
  6135. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6136. if (c != 255) {
  6137. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6138. if (d != 255) {
  6139. dst[(*dst_len)++] = (c << 6) + d;
  6140. }
  6141. }
  6142. }
  6143. return -1;
  6144. }
  6145. #endif
  6146. static int
  6147. is_put_or_delete_method(const struct mg_connection *conn)
  6148. {
  6149. if (conn) {
  6150. const char *s = conn->request_info.request_method;
  6151. return (s != NULL)
  6152. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6153. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6154. }
  6155. return 0;
  6156. }
  6157. #if !defined(NO_FILES)
  6158. static int
  6159. extention_matches_script(
  6160. struct mg_connection *conn, /* in: request (must be valid) */
  6161. const char *filename /* in: filename (must be valid) */
  6162. )
  6163. {
  6164. #if !defined(NO_CGI)
  6165. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6166. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6167. filename)
  6168. > 0) {
  6169. return 1;
  6170. }
  6171. #endif
  6172. #if defined(USE_LUA)
  6173. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6174. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6175. filename)
  6176. > 0) {
  6177. return 1;
  6178. }
  6179. #endif
  6180. #if defined(USE_DUKTAPE)
  6181. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6182. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6183. filename)
  6184. > 0) {
  6185. return 1;
  6186. }
  6187. #endif
  6188. /* filename and conn could be unused, if all preocessor conditions
  6189. * are false (no script language supported). */
  6190. (void)filename;
  6191. (void)conn;
  6192. return 0;
  6193. }
  6194. /* For given directory path, substitute it to valid index file.
  6195. * Return 1 if index file has been found, 0 if not found.
  6196. * If the file is found, it's stats is returned in stp. */
  6197. static int
  6198. substitute_index_file(struct mg_connection *conn,
  6199. char *path,
  6200. size_t path_len,
  6201. struct mg_file_stat *filestat)
  6202. {
  6203. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6204. struct vec filename_vec;
  6205. size_t n = strlen(path);
  6206. int found = 0;
  6207. /* The 'path' given to us points to the directory. Remove all trailing
  6208. * directory separator characters from the end of the path, and
  6209. * then append single directory separator character. */
  6210. while ((n > 0) && (path[n - 1] == '/')) {
  6211. n--;
  6212. }
  6213. path[n] = '/';
  6214. /* Traverse index files list. For each entry, append it to the given
  6215. * path and see if the file exists. If it exists, break the loop */
  6216. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6217. /* Ignore too long entries that may overflow path buffer */
  6218. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6219. continue;
  6220. }
  6221. /* Prepare full path to the index file */
  6222. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6223. /* Does it exist? */
  6224. if (mg_stat(conn, path, filestat)) {
  6225. /* Yes it does, break the loop */
  6226. found = 1;
  6227. break;
  6228. }
  6229. }
  6230. /* If no index file exists, restore directory path */
  6231. if (!found) {
  6232. path[n] = '\0';
  6233. }
  6234. return found;
  6235. }
  6236. #endif
  6237. static void
  6238. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6239. char *filename, /* out: filename */
  6240. size_t filename_buf_len, /* in: size of filename buffer */
  6241. struct mg_file_stat *filestat, /* out: file status structure */
  6242. int *is_found, /* out: file found (directly) */
  6243. int *is_script_resource, /* out: handled by a script? */
  6244. int *is_websocket_request, /* out: websocket connetion? */
  6245. int *is_put_or_delete_request /* out: put/delete a file? */
  6246. )
  6247. {
  6248. char const *accept_encoding;
  6249. #if !defined(NO_FILES)
  6250. const char *uri = conn->request_info.local_uri;
  6251. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6252. const char *rewrite;
  6253. struct vec a, b;
  6254. ptrdiff_t match_len;
  6255. char gz_path[PATH_MAX];
  6256. int truncated;
  6257. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6258. char *tmp_str;
  6259. size_t tmp_str_len, sep_pos;
  6260. int allow_substitute_script_subresources;
  6261. #endif
  6262. #else
  6263. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6264. #endif
  6265. /* Step 1: Set all initially unknown outputs to zero */
  6266. memset(filestat, 0, sizeof(*filestat));
  6267. *filename = 0;
  6268. *is_found = 0;
  6269. *is_script_resource = 0;
  6270. /* Step 2: Check if the request attempts to modify the file system */
  6271. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6272. /* Step 3: Check if it is a websocket request, and modify the document
  6273. * root if required */
  6274. #if defined(USE_WEBSOCKET)
  6275. *is_websocket_request = is_websocket_protocol(conn);
  6276. #if !defined(NO_FILES)
  6277. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6278. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6279. }
  6280. #endif /* !NO_FILES */
  6281. #else /* USE_WEBSOCKET */
  6282. *is_websocket_request = 0;
  6283. #endif /* USE_WEBSOCKET */
  6284. /* Step 4: Check if gzip encoded response is allowed */
  6285. conn->accept_gzip = 0;
  6286. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6287. if (strstr(accept_encoding, "gzip") != NULL) {
  6288. conn->accept_gzip = 1;
  6289. }
  6290. }
  6291. #if !defined(NO_FILES)
  6292. /* Step 5: If there is no root directory, don't look for files. */
  6293. /* Note that root == NULL is a regular use case here. This occurs,
  6294. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6295. * config is not required. */
  6296. if (root == NULL) {
  6297. /* all file related outputs have already been set to 0, just return
  6298. */
  6299. return;
  6300. }
  6301. /* Step 6: Determine the local file path from the root path and the
  6302. * request uri. */
  6303. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6304. * part of the path one byte on the right. */
  6305. mg_snprintf(
  6306. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6307. if (truncated) {
  6308. goto interpret_cleanup;
  6309. }
  6310. /* Step 7: URI rewriting */
  6311. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6312. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6313. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6314. mg_snprintf(conn,
  6315. &truncated,
  6316. filename,
  6317. filename_buf_len - 1,
  6318. "%.*s%s",
  6319. (int)b.len,
  6320. b.ptr,
  6321. uri + match_len);
  6322. break;
  6323. }
  6324. }
  6325. if (truncated) {
  6326. goto interpret_cleanup;
  6327. }
  6328. /* Step 8: Check if the file exists at the server */
  6329. /* Local file path and name, corresponding to requested URI
  6330. * is now stored in "filename" variable. */
  6331. if (mg_stat(conn, filename, filestat)) {
  6332. int uri_len = (int)strlen(uri);
  6333. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6334. /* 8.1: File exists. */
  6335. *is_found = 1;
  6336. /* 8.2: Check if it is a script type. */
  6337. if (extention_matches_script(conn, filename)) {
  6338. /* The request addresses a CGI resource, Lua script or
  6339. * server-side javascript.
  6340. * The URI corresponds to the script itself (like
  6341. * /path/script.cgi), and there is no additional resource
  6342. * path (like /path/script.cgi/something).
  6343. * Requests that modify (replace or delete) a resource, like
  6344. * PUT and DELETE requests, should replace/delete the script
  6345. * file.
  6346. * Requests that read or write from/to a resource, like GET and
  6347. * POST requests, should call the script and return the
  6348. * generated response. */
  6349. *is_script_resource = (!*is_put_or_delete_request);
  6350. }
  6351. /* 8.3: If the request target is a directory, there could be
  6352. * a substitute file (index.html, index.cgi, ...). */
  6353. if (filestat->is_directory && is_uri_end_slash) {
  6354. /* Use a local copy here, since substitute_index_file will
  6355. * change the content of the file status */
  6356. struct mg_file_stat tmp_filestat;
  6357. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6358. if (substitute_index_file(
  6359. conn, filename, filename_buf_len, &tmp_filestat)) {
  6360. /* Substitute file found. Copy stat to the output, then
  6361. * check if the file is a script file */
  6362. *filestat = tmp_filestat;
  6363. if (extention_matches_script(conn, filename)) {
  6364. /* Substitute file is a script file */
  6365. *is_script_resource = 1;
  6366. } else {
  6367. /* Substitute file is a regular file */
  6368. *is_script_resource = 0;
  6369. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6370. }
  6371. }
  6372. /* If there is no substitute file, the server could return
  6373. * a directory listing in a later step */
  6374. }
  6375. return;
  6376. }
  6377. /* Step 9: Check for zipped files: */
  6378. /* If we can't find the actual file, look for the file
  6379. * with the same name but a .gz extension. If we find it,
  6380. * use that and set the gzipped flag in the file struct
  6381. * to indicate that the response need to have the content-
  6382. * encoding: gzip header.
  6383. * We can only do this if the browser declares support. */
  6384. if (conn->accept_gzip) {
  6385. mg_snprintf(
  6386. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6387. if (truncated) {
  6388. goto interpret_cleanup;
  6389. }
  6390. if (mg_stat(conn, gz_path, filestat)) {
  6391. if (filestat) {
  6392. filestat->is_gzipped = 1;
  6393. *is_found = 1;
  6394. }
  6395. /* Currently gz files can not be scripts. */
  6396. return;
  6397. }
  6398. }
  6399. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6400. /* Step 10: Script resources may handle sub-resources */
  6401. /* Support PATH_INFO for CGI scripts. */
  6402. tmp_str_len = strlen(filename);
  6403. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6404. if (!tmp_str) {
  6405. /* Out of memory */
  6406. goto interpret_cleanup;
  6407. }
  6408. memcpy(tmp_str, filename, tmp_str_len + 1);
  6409. /* Check config, if index scripts may have sub-resources */
  6410. allow_substitute_script_subresources =
  6411. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6412. "yes");
  6413. sep_pos = tmp_str_len;
  6414. while (sep_pos > 0) {
  6415. sep_pos--;
  6416. if (tmp_str[sep_pos] == '/') {
  6417. int is_script = 0, does_exist = 0;
  6418. tmp_str[sep_pos] = 0;
  6419. if (tmp_str[0]) {
  6420. is_script = extention_matches_script(conn, tmp_str);
  6421. does_exist = mg_stat(conn, tmp_str, filestat);
  6422. }
  6423. if (does_exist && is_script) {
  6424. filename[sep_pos] = 0;
  6425. memmove(filename + sep_pos + 2,
  6426. filename + sep_pos + 1,
  6427. strlen(filename + sep_pos + 1) + 1);
  6428. conn->path_info = filename + sep_pos + 1;
  6429. filename[sep_pos + 1] = '/';
  6430. *is_script_resource = 1;
  6431. *is_found = 1;
  6432. break;
  6433. }
  6434. if (allow_substitute_script_subresources) {
  6435. if (substitute_index_file(
  6436. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6437. /* some intermediate directory has an index file */
  6438. if (extention_matches_script(conn, tmp_str)) {
  6439. char *tmp_str2;
  6440. DEBUG_TRACE("Substitute script %s serving path %s",
  6441. tmp_str,
  6442. filename);
  6443. /* this index file is a script */
  6444. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6445. conn->phys_ctx);
  6446. mg_snprintf(conn,
  6447. &truncated,
  6448. filename,
  6449. filename_buf_len,
  6450. "%s//%s",
  6451. tmp_str,
  6452. tmp_str2);
  6453. mg_free(tmp_str2);
  6454. if (truncated) {
  6455. mg_free(tmp_str);
  6456. goto interpret_cleanup;
  6457. }
  6458. sep_pos = strlen(tmp_str);
  6459. filename[sep_pos] = 0;
  6460. conn->path_info = filename + sep_pos + 1;
  6461. *is_script_resource = 1;
  6462. *is_found = 1;
  6463. break;
  6464. } else {
  6465. DEBUG_TRACE("Substitute file %s serving path %s",
  6466. tmp_str,
  6467. filename);
  6468. /* non-script files will not have sub-resources */
  6469. filename[sep_pos] = 0;
  6470. conn->path_info = 0;
  6471. *is_script_resource = 0;
  6472. *is_found = 0;
  6473. break;
  6474. }
  6475. }
  6476. }
  6477. tmp_str[sep_pos] = '/';
  6478. }
  6479. }
  6480. mg_free(tmp_str);
  6481. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6482. #endif /* !defined(NO_FILES) */
  6483. return;
  6484. #if !defined(NO_FILES)
  6485. /* Reset all outputs */
  6486. interpret_cleanup:
  6487. memset(filestat, 0, sizeof(*filestat));
  6488. *filename = 0;
  6489. *is_found = 0;
  6490. *is_script_resource = 0;
  6491. *is_websocket_request = 0;
  6492. *is_put_or_delete_request = 0;
  6493. #endif /* !defined(NO_FILES) */
  6494. }
  6495. /* Check whether full request is buffered. Return:
  6496. * -1 if request or response is malformed
  6497. * 0 if request or response is not yet fully buffered
  6498. * >0 actual request length, including last \r\n\r\n */
  6499. static int
  6500. get_http_header_len(const char *buf, int buflen)
  6501. {
  6502. int i;
  6503. for (i = 0; i < buflen; i++) {
  6504. /* Do an unsigned comparison in some conditions below */
  6505. const unsigned char c = (unsigned char)buf[i];
  6506. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6507. && !isprint(c)) {
  6508. /* abort scan as soon as one malformed character is found */
  6509. return -1;
  6510. }
  6511. if (i < buflen - 1) {
  6512. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6513. /* Two newline, no carriage return - not standard compliant,
  6514. * but
  6515. * it
  6516. * should be accepted */
  6517. return i + 2;
  6518. }
  6519. }
  6520. if (i < buflen - 3) {
  6521. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6522. && (buf[i + 3] == '\n')) {
  6523. /* Two \r\n - standard compliant */
  6524. return i + 4;
  6525. }
  6526. }
  6527. }
  6528. return 0;
  6529. }
  6530. #if !defined(NO_CACHING)
  6531. /* Convert month to the month number. Return -1 on error, or month number */
  6532. static int
  6533. get_month_index(const char *s)
  6534. {
  6535. size_t i;
  6536. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6537. if (!strcmp(s, month_names[i])) {
  6538. return (int)i;
  6539. }
  6540. }
  6541. return -1;
  6542. }
  6543. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6544. static time_t
  6545. parse_date_string(const char *datetime)
  6546. {
  6547. char month_str[32] = {0};
  6548. int second, minute, hour, day, month, year;
  6549. time_t result = (time_t)0;
  6550. struct tm tm;
  6551. if ((sscanf(datetime,
  6552. "%d/%3s/%d %d:%d:%d",
  6553. &day,
  6554. month_str,
  6555. &year,
  6556. &hour,
  6557. &minute,
  6558. &second)
  6559. == 6)
  6560. || (sscanf(datetime,
  6561. "%d %3s %d %d:%d:%d",
  6562. &day,
  6563. month_str,
  6564. &year,
  6565. &hour,
  6566. &minute,
  6567. &second)
  6568. == 6)
  6569. || (sscanf(datetime,
  6570. "%*3s, %d %3s %d %d:%d:%d",
  6571. &day,
  6572. month_str,
  6573. &year,
  6574. &hour,
  6575. &minute,
  6576. &second)
  6577. == 6)
  6578. || (sscanf(datetime,
  6579. "%d-%3s-%d %d:%d:%d",
  6580. &day,
  6581. month_str,
  6582. &year,
  6583. &hour,
  6584. &minute,
  6585. &second)
  6586. == 6)) {
  6587. month = get_month_index(month_str);
  6588. if ((month >= 0) && (year >= 1970)) {
  6589. memset(&tm, 0, sizeof(tm));
  6590. tm.tm_year = year - 1900;
  6591. tm.tm_mon = month;
  6592. tm.tm_mday = day;
  6593. tm.tm_hour = hour;
  6594. tm.tm_min = minute;
  6595. tm.tm_sec = second;
  6596. result = timegm(&tm);
  6597. }
  6598. }
  6599. return result;
  6600. }
  6601. #endif /* !NO_CACHING */
  6602. /* Protect against directory disclosure attack by removing '..',
  6603. * excessive '/' and '\' characters */
  6604. static void
  6605. remove_double_dots_and_double_slashes(char *s)
  6606. {
  6607. char *p = s;
  6608. while ((s[0] == '.') && (s[1] == '.')) {
  6609. s++;
  6610. }
  6611. while (*s != '\0') {
  6612. *p++ = *s++;
  6613. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6614. /* Skip all following slashes, backslashes and double-dots */
  6615. while (s[0] != '\0') {
  6616. if ((s[0] == '/') || (s[0] == '\\')) {
  6617. s++;
  6618. } else if ((s[0] == '.') && (s[1] == '.')) {
  6619. s += 2;
  6620. } else {
  6621. break;
  6622. }
  6623. }
  6624. }
  6625. }
  6626. *p = '\0';
  6627. }
  6628. static const struct {
  6629. const char *extension;
  6630. size_t ext_len;
  6631. const char *mime_type;
  6632. } builtin_mime_types[] = {
  6633. /* IANA registered MIME types
  6634. * (http://www.iana.org/assignments/media-types)
  6635. * application types */
  6636. {".doc", 4, "application/msword"},
  6637. {".eps", 4, "application/postscript"},
  6638. {".exe", 4, "application/octet-stream"},
  6639. {".js", 3, "application/javascript"},
  6640. {".json", 5, "application/json"},
  6641. {".pdf", 4, "application/pdf"},
  6642. {".ps", 3, "application/postscript"},
  6643. {".rtf", 4, "application/rtf"},
  6644. {".xhtml", 6, "application/xhtml+xml"},
  6645. {".xsl", 4, "application/xml"},
  6646. {".xslt", 5, "application/xml"},
  6647. /* fonts */
  6648. {".ttf", 4, "application/font-sfnt"},
  6649. {".cff", 4, "application/font-sfnt"},
  6650. {".otf", 4, "application/font-sfnt"},
  6651. {".aat", 4, "application/font-sfnt"},
  6652. {".sil", 4, "application/font-sfnt"},
  6653. {".pfr", 4, "application/font-tdpfr"},
  6654. {".woff", 5, "application/font-woff"},
  6655. /* audio */
  6656. {".mp3", 4, "audio/mpeg"},
  6657. {".oga", 4, "audio/ogg"},
  6658. {".ogg", 4, "audio/ogg"},
  6659. /* image */
  6660. {".gif", 4, "image/gif"},
  6661. {".ief", 4, "image/ief"},
  6662. {".jpeg", 5, "image/jpeg"},
  6663. {".jpg", 4, "image/jpeg"},
  6664. {".jpm", 4, "image/jpm"},
  6665. {".jpx", 4, "image/jpx"},
  6666. {".png", 4, "image/png"},
  6667. {".svg", 4, "image/svg+xml"},
  6668. {".tif", 4, "image/tiff"},
  6669. {".tiff", 5, "image/tiff"},
  6670. /* model */
  6671. {".wrl", 4, "model/vrml"},
  6672. /* text */
  6673. {".css", 4, "text/css"},
  6674. {".csv", 4, "text/csv"},
  6675. {".htm", 4, "text/html"},
  6676. {".html", 5, "text/html"},
  6677. {".sgm", 4, "text/sgml"},
  6678. {".shtm", 5, "text/html"},
  6679. {".shtml", 6, "text/html"},
  6680. {".txt", 4, "text/plain"},
  6681. {".xml", 4, "text/xml"},
  6682. /* video */
  6683. {".mov", 4, "video/quicktime"},
  6684. {".mp4", 4, "video/mp4"},
  6685. {".mpeg", 5, "video/mpeg"},
  6686. {".mpg", 4, "video/mpeg"},
  6687. {".ogv", 4, "video/ogg"},
  6688. {".qt", 3, "video/quicktime"},
  6689. /* not registered types
  6690. * (http://reference.sitepoint.com/html/mime-types-full,
  6691. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6692. {".arj", 4, "application/x-arj-compressed"},
  6693. {".gz", 3, "application/x-gunzip"},
  6694. {".rar", 4, "application/x-arj-compressed"},
  6695. {".swf", 4, "application/x-shockwave-flash"},
  6696. {".tar", 4, "application/x-tar"},
  6697. {".tgz", 4, "application/x-tar-gz"},
  6698. {".torrent", 8, "application/x-bittorrent"},
  6699. {".ppt", 4, "application/x-mspowerpoint"},
  6700. {".xls", 4, "application/x-msexcel"},
  6701. {".zip", 4, "application/x-zip-compressed"},
  6702. {".aac",
  6703. 4,
  6704. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6705. {".aif", 4, "audio/x-aif"},
  6706. {".m3u", 4, "audio/x-mpegurl"},
  6707. {".mid", 4, "audio/x-midi"},
  6708. {".ra", 3, "audio/x-pn-realaudio"},
  6709. {".ram", 4, "audio/x-pn-realaudio"},
  6710. {".wav", 4, "audio/x-wav"},
  6711. {".bmp", 4, "image/bmp"},
  6712. {".ico", 4, "image/x-icon"},
  6713. {".pct", 4, "image/x-pct"},
  6714. {".pict", 5, "image/pict"},
  6715. {".rgb", 4, "image/x-rgb"},
  6716. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6717. {".asf", 4, "video/x-ms-asf"},
  6718. {".avi", 4, "video/x-msvideo"},
  6719. {".m4v", 4, "video/x-m4v"},
  6720. {NULL, 0, NULL}};
  6721. const char *
  6722. mg_get_builtin_mime_type(const char *path)
  6723. {
  6724. const char *ext;
  6725. size_t i, path_len;
  6726. path_len = strlen(path);
  6727. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6728. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6729. if ((path_len > builtin_mime_types[i].ext_len)
  6730. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6731. return builtin_mime_types[i].mime_type;
  6732. }
  6733. }
  6734. return "text/plain";
  6735. }
  6736. /* Look at the "path" extension and figure what mime type it has.
  6737. * Store mime type in the vector. */
  6738. static void
  6739. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6740. {
  6741. struct vec ext_vec, mime_vec;
  6742. const char *list, *ext;
  6743. size_t path_len;
  6744. path_len = strlen(path);
  6745. if ((conn == NULL) || (vec == NULL)) {
  6746. if (vec != NULL) {
  6747. memset(vec, '\0', sizeof(struct vec));
  6748. }
  6749. return;
  6750. }
  6751. /* Scan user-defined mime types first, in case user wants to
  6752. * override default mime types. */
  6753. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6754. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6755. /* ext now points to the path suffix */
  6756. ext = path + path_len - ext_vec.len;
  6757. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6758. *vec = mime_vec;
  6759. return;
  6760. }
  6761. }
  6762. vec->ptr = mg_get_builtin_mime_type(path);
  6763. vec->len = strlen(vec->ptr);
  6764. }
  6765. /* Stringify binary data. Output buffer must be twice as big as input,
  6766. * because each byte takes 2 bytes in string representation */
  6767. static void
  6768. bin2str(char *to, const unsigned char *p, size_t len)
  6769. {
  6770. static const char *hex = "0123456789abcdef";
  6771. for (; len--; p++) {
  6772. *to++ = hex[p[0] >> 4];
  6773. *to++ = hex[p[0] & 0x0f];
  6774. }
  6775. *to = '\0';
  6776. }
  6777. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6778. */
  6779. char *
  6780. mg_md5(char buf[33], ...)
  6781. {
  6782. md5_byte_t hash[16];
  6783. const char *p;
  6784. va_list ap;
  6785. md5_state_t ctx;
  6786. md5_init(&ctx);
  6787. va_start(ap, buf);
  6788. while ((p = va_arg(ap, const char *)) != NULL) {
  6789. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6790. }
  6791. va_end(ap);
  6792. md5_finish(&ctx, hash);
  6793. bin2str(buf, hash, sizeof(hash));
  6794. return buf;
  6795. }
  6796. /* Check the user's password, return 1 if OK */
  6797. static int
  6798. check_password(const char *method,
  6799. const char *ha1,
  6800. const char *uri,
  6801. const char *nonce,
  6802. const char *nc,
  6803. const char *cnonce,
  6804. const char *qop,
  6805. const char *response)
  6806. {
  6807. char ha2[32 + 1], expected_response[32 + 1];
  6808. /* Some of the parameters may be NULL */
  6809. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6810. || (qop == NULL) || (response == NULL)) {
  6811. return 0;
  6812. }
  6813. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6814. if (strlen(response) != 32) {
  6815. return 0;
  6816. }
  6817. mg_md5(ha2, method, ":", uri, NULL);
  6818. mg_md5(expected_response,
  6819. ha1,
  6820. ":",
  6821. nonce,
  6822. ":",
  6823. nc,
  6824. ":",
  6825. cnonce,
  6826. ":",
  6827. qop,
  6828. ":",
  6829. ha2,
  6830. NULL);
  6831. return mg_strcasecmp(response, expected_response) == 0;
  6832. }
  6833. /* Use the global passwords file, if specified by auth_gpass option,
  6834. * or search for .htpasswd in the requested directory. */
  6835. static void
  6836. open_auth_file(struct mg_connection *conn,
  6837. const char *path,
  6838. struct mg_file *filep)
  6839. {
  6840. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6841. char name[PATH_MAX];
  6842. const char *p, *e,
  6843. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6844. int truncated;
  6845. if (gpass != NULL) {
  6846. /* Use global passwords file */
  6847. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6848. #if defined(DEBUG)
  6849. /* Use mg_cry_internal here, since gpass has been configured. */
  6850. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6851. #endif
  6852. }
  6853. /* Important: using local struct mg_file to test path for
  6854. * is_directory flag. If filep is used, mg_stat() makes it
  6855. * appear as if auth file was opened.
  6856. * TODO(mid): Check if this is still required after rewriting
  6857. * mg_stat */
  6858. } else if (mg_stat(conn, path, &filep->stat)
  6859. && filep->stat.is_directory) {
  6860. mg_snprintf(conn,
  6861. &truncated,
  6862. name,
  6863. sizeof(name),
  6864. "%s/%s",
  6865. path,
  6866. PASSWORDS_FILE_NAME);
  6867. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6868. #if defined(DEBUG)
  6869. /* Don't use mg_cry_internal here, but only a trace, since this
  6870. * is
  6871. * a typical case. It will occur for every directory
  6872. * without a password file. */
  6873. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6874. #endif
  6875. }
  6876. } else {
  6877. /* Try to find .htpasswd in requested directory. */
  6878. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6879. if (e[0] == '/') {
  6880. break;
  6881. }
  6882. }
  6883. mg_snprintf(conn,
  6884. &truncated,
  6885. name,
  6886. sizeof(name),
  6887. "%.*s/%s",
  6888. (int)(e - p),
  6889. p,
  6890. PASSWORDS_FILE_NAME);
  6891. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6892. #if defined(DEBUG)
  6893. /* Don't use mg_cry_internal here, but only a trace, since this
  6894. * is
  6895. * a typical case. It will occur for every directory
  6896. * without a password file. */
  6897. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6898. #endif
  6899. }
  6900. }
  6901. }
  6902. }
  6903. /* Parsed Authorization header */
  6904. struct ah {
  6905. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6906. };
  6907. /* Return 1 on success. Always initializes the ah structure. */
  6908. static int
  6909. parse_auth_header(struct mg_connection *conn,
  6910. char *buf,
  6911. size_t buf_size,
  6912. struct ah *ah)
  6913. {
  6914. char *name, *value, *s;
  6915. const char *auth_header;
  6916. uint64_t nonce;
  6917. if (!ah || !conn) {
  6918. return 0;
  6919. }
  6920. (void)memset(ah, 0, sizeof(*ah));
  6921. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6922. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6923. return 0;
  6924. }
  6925. /* Make modifiable copy of the auth header */
  6926. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6927. s = buf;
  6928. /* Parse authorization header */
  6929. for (;;) {
  6930. /* Gobble initial spaces */
  6931. while (isspace((unsigned char)*s)) {
  6932. s++;
  6933. }
  6934. name = skip_quoted(&s, "=", " ", 0);
  6935. /* Value is either quote-delimited, or ends at first comma or space.
  6936. */
  6937. if (s[0] == '\"') {
  6938. s++;
  6939. value = skip_quoted(&s, "\"", " ", '\\');
  6940. if (s[0] == ',') {
  6941. s++;
  6942. }
  6943. } else {
  6944. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6945. * spaces */
  6946. }
  6947. if (*name == '\0') {
  6948. break;
  6949. }
  6950. if (!strcmp(name, "username")) {
  6951. ah->user = value;
  6952. } else if (!strcmp(name, "cnonce")) {
  6953. ah->cnonce = value;
  6954. } else if (!strcmp(name, "response")) {
  6955. ah->response = value;
  6956. } else if (!strcmp(name, "uri")) {
  6957. ah->uri = value;
  6958. } else if (!strcmp(name, "qop")) {
  6959. ah->qop = value;
  6960. } else if (!strcmp(name, "nc")) {
  6961. ah->nc = value;
  6962. } else if (!strcmp(name, "nonce")) {
  6963. ah->nonce = value;
  6964. }
  6965. }
  6966. #if !defined(NO_NONCE_CHECK)
  6967. /* Read the nonce from the response. */
  6968. if (ah->nonce == NULL) {
  6969. return 0;
  6970. }
  6971. s = NULL;
  6972. nonce = strtoull(ah->nonce, &s, 10);
  6973. if ((s == NULL) || (*s != 0)) {
  6974. return 0;
  6975. }
  6976. /* Convert the nonce from the client to a number. */
  6977. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6978. /* The converted number corresponds to the time the nounce has been
  6979. * created. This should not be earlier than the server start. */
  6980. /* Server side nonce check is valuable in all situations but one:
  6981. * if the server restarts frequently, but the client should not see
  6982. * that, so the server should accept nonces from previous starts. */
  6983. /* However, the reasonable default is to not accept a nonce from a
  6984. * previous start, so if anyone changed the access rights between
  6985. * two restarts, a new login is required. */
  6986. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6987. /* nonce is from a previous start of the server and no longer valid
  6988. * (replay attack?) */
  6989. return 0;
  6990. }
  6991. /* Check if the nonce is too high, so it has not (yet) been used by the
  6992. * server. */
  6993. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6994. + conn->dom_ctx->nonce_count)) {
  6995. return 0;
  6996. }
  6997. #else
  6998. (void)nonce;
  6999. #endif
  7000. /* CGI needs it as REMOTE_USER */
  7001. if (ah->user != NULL) {
  7002. conn->request_info.remote_user =
  7003. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7004. } else {
  7005. return 0;
  7006. }
  7007. return 1;
  7008. }
  7009. static const char *
  7010. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7011. {
  7012. #if defined(MG_USE_OPEN_FILE)
  7013. const char *eof;
  7014. size_t len;
  7015. const char *memend;
  7016. #else
  7017. (void)p; /* parameter is unused */
  7018. #endif
  7019. if (!filep) {
  7020. return NULL;
  7021. }
  7022. #if defined(MG_USE_OPEN_FILE)
  7023. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7024. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7025. /* Search for \n from p till the end of stream */
  7026. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7027. if (eof != NULL) {
  7028. eof += 1; /* Include \n */
  7029. } else {
  7030. eof = memend; /* Copy remaining data */
  7031. }
  7032. len =
  7033. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7034. memcpy(buf, *p, len);
  7035. buf[len] = '\0';
  7036. *p += len;
  7037. return len ? eof : NULL;
  7038. } else /* filep->access.fp block below */
  7039. #endif
  7040. if (filep->access.fp != NULL) {
  7041. return fgets(buf, (int)size, filep->access.fp);
  7042. } else {
  7043. return NULL;
  7044. }
  7045. }
  7046. /* Define the initial recursion depth for procesesing htpasswd files that
  7047. * include other htpasswd
  7048. * (or even the same) files. It is not difficult to provide a file or files
  7049. * s.t. they force civetweb
  7050. * to infinitely recurse and then crash.
  7051. */
  7052. #define INITIAL_DEPTH 9
  7053. #if INITIAL_DEPTH <= 0
  7054. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7055. #endif
  7056. struct read_auth_file_struct {
  7057. struct mg_connection *conn;
  7058. struct ah ah;
  7059. const char *domain;
  7060. char buf[256 + 256 + 40];
  7061. const char *f_user;
  7062. const char *f_domain;
  7063. const char *f_ha1;
  7064. };
  7065. static int
  7066. read_auth_file(struct mg_file *filep,
  7067. struct read_auth_file_struct *workdata,
  7068. int depth)
  7069. {
  7070. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7071. int is_authorized = 0;
  7072. struct mg_file fp;
  7073. size_t l;
  7074. if (!filep || !workdata || (0 == depth)) {
  7075. return 0;
  7076. }
  7077. /* Loop over passwords file */
  7078. #if defined(MG_USE_OPEN_FILE)
  7079. p = (char *)filep->access.membuf;
  7080. #endif
  7081. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7082. l = strlen(workdata->buf);
  7083. while (l > 0) {
  7084. if (isspace((unsigned char)workdata->buf[l - 1])
  7085. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7086. l--;
  7087. workdata->buf[l] = 0;
  7088. } else
  7089. break;
  7090. }
  7091. if (l < 1) {
  7092. continue;
  7093. }
  7094. workdata->f_user = workdata->buf;
  7095. if (workdata->f_user[0] == ':') {
  7096. /* user names may not contain a ':' and may not be empty,
  7097. * so lines starting with ':' may be used for a special purpose
  7098. */
  7099. if (workdata->f_user[1] == '#') {
  7100. /* :# is a comment */
  7101. continue;
  7102. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7103. if (mg_fopen(workdata->conn,
  7104. workdata->f_user + 9,
  7105. MG_FOPEN_MODE_READ,
  7106. &fp)) {
  7107. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7108. (void)mg_fclose(
  7109. &fp.access); /* ignore error on read only file */
  7110. /* No need to continue processing files once we have a
  7111. * match, since nothing will reset it back
  7112. * to 0.
  7113. */
  7114. if (is_authorized) {
  7115. return is_authorized;
  7116. }
  7117. } else {
  7118. mg_cry_internal(workdata->conn,
  7119. "%s: cannot open authorization file: %s",
  7120. __func__,
  7121. workdata->buf);
  7122. }
  7123. continue;
  7124. }
  7125. /* everything is invalid for the moment (might change in the
  7126. * future) */
  7127. mg_cry_internal(workdata->conn,
  7128. "%s: syntax error in authorization file: %s",
  7129. __func__,
  7130. workdata->buf);
  7131. continue;
  7132. }
  7133. workdata->f_domain = strchr(workdata->f_user, ':');
  7134. if (workdata->f_domain == NULL) {
  7135. mg_cry_internal(workdata->conn,
  7136. "%s: syntax error in authorization file: %s",
  7137. __func__,
  7138. workdata->buf);
  7139. continue;
  7140. }
  7141. *(char *)(workdata->f_domain) = 0;
  7142. (workdata->f_domain)++;
  7143. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7144. if (workdata->f_ha1 == NULL) {
  7145. mg_cry_internal(workdata->conn,
  7146. "%s: syntax error in authorization file: %s",
  7147. __func__,
  7148. workdata->buf);
  7149. continue;
  7150. }
  7151. *(char *)(workdata->f_ha1) = 0;
  7152. (workdata->f_ha1)++;
  7153. if (!strcmp(workdata->ah.user, workdata->f_user)
  7154. && !strcmp(workdata->domain, workdata->f_domain)) {
  7155. return check_password(workdata->conn->request_info.request_method,
  7156. workdata->f_ha1,
  7157. workdata->ah.uri,
  7158. workdata->ah.nonce,
  7159. workdata->ah.nc,
  7160. workdata->ah.cnonce,
  7161. workdata->ah.qop,
  7162. workdata->ah.response);
  7163. }
  7164. }
  7165. return is_authorized;
  7166. }
  7167. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7168. static int
  7169. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7170. {
  7171. struct read_auth_file_struct workdata;
  7172. char buf[MG_BUF_LEN];
  7173. if (!conn || !conn->dom_ctx) {
  7174. return 0;
  7175. }
  7176. memset(&workdata, 0, sizeof(workdata));
  7177. workdata.conn = conn;
  7178. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7179. return 0;
  7180. }
  7181. if (realm) {
  7182. workdata.domain = realm;
  7183. } else {
  7184. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7185. }
  7186. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7187. }
  7188. /* Public function to check http digest authentication header */
  7189. int
  7190. mg_check_digest_access_authentication(struct mg_connection *conn,
  7191. const char *realm,
  7192. const char *filename)
  7193. {
  7194. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7195. int auth;
  7196. if (!conn || !filename) {
  7197. return -1;
  7198. }
  7199. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7200. return -2;
  7201. }
  7202. auth = authorize(conn, &file, realm);
  7203. mg_fclose(&file.access);
  7204. return auth;
  7205. }
  7206. /* Return 1 if request is authorised, 0 otherwise. */
  7207. static int
  7208. check_authorization(struct mg_connection *conn, const char *path)
  7209. {
  7210. char fname[PATH_MAX];
  7211. struct vec uri_vec, filename_vec;
  7212. const char *list;
  7213. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7214. int authorized = 1, truncated;
  7215. if (!conn || !conn->dom_ctx) {
  7216. return 0;
  7217. }
  7218. list = conn->dom_ctx->config[PROTECT_URI];
  7219. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7220. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7221. mg_snprintf(conn,
  7222. &truncated,
  7223. fname,
  7224. sizeof(fname),
  7225. "%.*s",
  7226. (int)filename_vec.len,
  7227. filename_vec.ptr);
  7228. if (truncated
  7229. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7230. mg_cry_internal(conn,
  7231. "%s: cannot open %s: %s",
  7232. __func__,
  7233. fname,
  7234. strerror(errno));
  7235. }
  7236. break;
  7237. }
  7238. }
  7239. if (!is_file_opened(&file.access)) {
  7240. open_auth_file(conn, path, &file);
  7241. }
  7242. if (is_file_opened(&file.access)) {
  7243. authorized = authorize(conn, &file, NULL);
  7244. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7245. }
  7246. return authorized;
  7247. }
  7248. /* Internal function. Assumes conn is valid */
  7249. static void
  7250. send_authorization_request(struct mg_connection *conn, const char *realm)
  7251. {
  7252. char date[64];
  7253. time_t curtime = time(NULL);
  7254. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7255. if (!realm) {
  7256. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7257. }
  7258. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7259. nonce += conn->dom_ctx->nonce_count;
  7260. ++conn->dom_ctx->nonce_count;
  7261. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7262. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7263. conn->status_code = 401;
  7264. conn->must_close = 1;
  7265. gmt_time_string(date, sizeof(date), &curtime);
  7266. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7267. send_no_cache_header(conn);
  7268. send_additional_header(conn);
  7269. mg_printf(conn,
  7270. "Date: %s\r\n"
  7271. "Connection: %s\r\n"
  7272. "Content-Length: 0\r\n"
  7273. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7274. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7275. date,
  7276. suggest_connection_header(conn),
  7277. realm,
  7278. nonce);
  7279. }
  7280. /* Interface function. Parameters are provided by the user, so do
  7281. * at least some basic checks.
  7282. */
  7283. int
  7284. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7285. const char *realm)
  7286. {
  7287. if (conn && conn->dom_ctx) {
  7288. send_authorization_request(conn, realm);
  7289. return 0;
  7290. }
  7291. return -1;
  7292. }
  7293. #if !defined(NO_FILES)
  7294. static int
  7295. is_authorized_for_put(struct mg_connection *conn)
  7296. {
  7297. if (conn) {
  7298. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7299. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7300. int ret = 0;
  7301. if (passfile != NULL
  7302. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7303. ret = authorize(conn, &file, NULL);
  7304. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7305. }
  7306. return ret;
  7307. }
  7308. return 0;
  7309. }
  7310. #endif
  7311. int
  7312. mg_modify_passwords_file(const char *fname,
  7313. const char *domain,
  7314. const char *user,
  7315. const char *pass)
  7316. {
  7317. int found, i;
  7318. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7319. FILE *fp, *fp2;
  7320. found = 0;
  7321. fp = fp2 = NULL;
  7322. /* Regard empty password as no password - remove user record. */
  7323. if ((pass != NULL) && (pass[0] == '\0')) {
  7324. pass = NULL;
  7325. }
  7326. /* Other arguments must not be empty */
  7327. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7328. return 0;
  7329. }
  7330. /* Using the given file format, user name and domain must not contain
  7331. * ':'
  7332. */
  7333. if (strchr(user, ':') != NULL) {
  7334. return 0;
  7335. }
  7336. if (strchr(domain, ':') != NULL) {
  7337. return 0;
  7338. }
  7339. /* Do not allow control characters like newline in user name and domain.
  7340. * Do not allow excessively long names either. */
  7341. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7342. if (iscntrl((unsigned char)user[i])) {
  7343. return 0;
  7344. }
  7345. }
  7346. if (user[i]) {
  7347. return 0;
  7348. }
  7349. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7350. if (iscntrl((unsigned char)domain[i])) {
  7351. return 0;
  7352. }
  7353. }
  7354. if (domain[i]) {
  7355. return 0;
  7356. }
  7357. /* The maximum length of the path to the password file is limited */
  7358. if ((strlen(fname) + 4) >= PATH_MAX) {
  7359. return 0;
  7360. }
  7361. /* Create a temporary file name. Length has been checked before. */
  7362. strcpy(tmp, fname);
  7363. strcat(tmp, ".tmp");
  7364. /* Create the file if does not exist */
  7365. /* Use of fopen here is OK, since fname is only ASCII */
  7366. if ((fp = fopen(fname, "a+")) != NULL) {
  7367. (void)fclose(fp);
  7368. }
  7369. /* Open the given file and temporary file */
  7370. if ((fp = fopen(fname, "r")) == NULL) {
  7371. return 0;
  7372. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7373. fclose(fp);
  7374. return 0;
  7375. }
  7376. /* Copy the stuff to temporary file */
  7377. while (fgets(line, sizeof(line), fp) != NULL) {
  7378. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7379. continue;
  7380. }
  7381. u[255] = 0;
  7382. d[255] = 0;
  7383. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7384. found++;
  7385. if (pass != NULL) {
  7386. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7387. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7388. }
  7389. } else {
  7390. fprintf(fp2, "%s", line);
  7391. }
  7392. }
  7393. /* If new user, just add it */
  7394. if (!found && (pass != NULL)) {
  7395. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7396. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7397. }
  7398. /* Close files */
  7399. fclose(fp);
  7400. fclose(fp2);
  7401. /* Put the temp file in place of real file */
  7402. IGNORE_UNUSED_RESULT(remove(fname));
  7403. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7404. return 1;
  7405. }
  7406. static int
  7407. is_valid_port(unsigned long port)
  7408. {
  7409. return (port <= 0xffff);
  7410. }
  7411. static int
  7412. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7413. {
  7414. struct addrinfo hints, *res, *ressave;
  7415. int func_ret = 0;
  7416. int gai_ret;
  7417. memset(&hints, 0, sizeof(struct addrinfo));
  7418. hints.ai_family = af;
  7419. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7420. if (gai_ret != 0) {
  7421. /* gai_strerror could be used to convert gai_ret to a string */
  7422. /* POSIX return values: see
  7423. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7424. */
  7425. /* Windows return values: see
  7426. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7427. */
  7428. return 0;
  7429. }
  7430. ressave = res;
  7431. while (res) {
  7432. if (dstlen >= (size_t)res->ai_addrlen) {
  7433. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7434. func_ret = 1;
  7435. }
  7436. res = res->ai_next;
  7437. }
  7438. freeaddrinfo(ressave);
  7439. return func_ret;
  7440. }
  7441. static int
  7442. connect_socket(struct mg_context *ctx /* may be NULL */,
  7443. const char *host,
  7444. int port,
  7445. int use_ssl,
  7446. char *ebuf,
  7447. size_t ebuf_len,
  7448. SOCKET *sock /* output: socket, must not be NULL */,
  7449. union usa *sa /* output: socket address, must not be NULL */
  7450. )
  7451. {
  7452. int ip_ver = 0;
  7453. int conn_ret = -1;
  7454. int sockerr = 0;
  7455. *sock = INVALID_SOCKET;
  7456. memset(sa, 0, sizeof(*sa));
  7457. if (ebuf_len > 0) {
  7458. *ebuf = 0;
  7459. }
  7460. if (host == NULL) {
  7461. mg_snprintf(NULL,
  7462. NULL, /* No truncation check for ebuf */
  7463. ebuf,
  7464. ebuf_len,
  7465. "%s",
  7466. "NULL host");
  7467. return 0;
  7468. }
  7469. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7470. mg_snprintf(NULL,
  7471. NULL, /* No truncation check for ebuf */
  7472. ebuf,
  7473. ebuf_len,
  7474. "%s",
  7475. "invalid port");
  7476. return 0;
  7477. }
  7478. #if !defined(NO_SSL)
  7479. #if !defined(NO_SSL_DL)
  7480. #if defined(OPENSSL_API_1_1)
  7481. if (use_ssl && (TLS_client_method == NULL)) {
  7482. mg_snprintf(NULL,
  7483. NULL, /* No truncation check for ebuf */
  7484. ebuf,
  7485. ebuf_len,
  7486. "%s",
  7487. "SSL is not initialized");
  7488. return 0;
  7489. }
  7490. #else
  7491. if (use_ssl && (SSLv23_client_method == NULL)) {
  7492. mg_snprintf(NULL,
  7493. NULL, /* No truncation check for ebuf */
  7494. ebuf,
  7495. ebuf_len,
  7496. "%s",
  7497. "SSL is not initialized");
  7498. return 0;
  7499. }
  7500. #endif /* OPENSSL_API_1_1 */
  7501. #else
  7502. (void)use_ssl;
  7503. #endif /* NO_SSL_DL */
  7504. #else
  7505. (void)use_ssl;
  7506. #endif /* !defined(NO_SSL) */
  7507. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7508. sa->sin.sin_family = AF_INET;
  7509. sa->sin.sin_port = htons((uint16_t)port);
  7510. ip_ver = 4;
  7511. #if defined(USE_IPV6)
  7512. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7513. sa->sin6.sin6_family = AF_INET6;
  7514. sa->sin6.sin6_port = htons((uint16_t)port);
  7515. ip_ver = 6;
  7516. } else if (host[0] == '[') {
  7517. /* While getaddrinfo on Windows will work with [::1],
  7518. * getaddrinfo on Linux only works with ::1 (without []). */
  7519. size_t l = strlen(host + 1);
  7520. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7521. if (h) {
  7522. h[l - 1] = 0;
  7523. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7524. sa->sin6.sin6_family = AF_INET6;
  7525. sa->sin6.sin6_port = htons((uint16_t)port);
  7526. ip_ver = 6;
  7527. }
  7528. mg_free(h);
  7529. }
  7530. #endif
  7531. }
  7532. if (ip_ver == 0) {
  7533. mg_snprintf(NULL,
  7534. NULL, /* No truncation check for ebuf */
  7535. ebuf,
  7536. ebuf_len,
  7537. "%s",
  7538. "host not found");
  7539. return 0;
  7540. }
  7541. if (ip_ver == 4) {
  7542. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7543. }
  7544. #if defined(USE_IPV6)
  7545. else if (ip_ver == 6) {
  7546. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7547. }
  7548. #endif
  7549. if (*sock == INVALID_SOCKET) {
  7550. mg_snprintf(NULL,
  7551. NULL, /* No truncation check for ebuf */
  7552. ebuf,
  7553. ebuf_len,
  7554. "socket(): %s",
  7555. strerror(ERRNO));
  7556. return 0;
  7557. }
  7558. if (0 != set_non_blocking_mode(*sock)) {
  7559. mg_snprintf(NULL,
  7560. NULL, /* No truncation check for ebuf */
  7561. ebuf,
  7562. ebuf_len,
  7563. "Cannot set socket to non-blocking: %s",
  7564. strerror(ERRNO));
  7565. closesocket(*sock);
  7566. *sock = INVALID_SOCKET;
  7567. return 0;
  7568. }
  7569. set_close_on_exec(*sock, fc(ctx));
  7570. if (ip_ver == 4) {
  7571. /* connected with IPv4 */
  7572. conn_ret = connect(*sock,
  7573. (struct sockaddr *)((void *)&sa->sin),
  7574. sizeof(sa->sin));
  7575. }
  7576. #if defined(USE_IPV6)
  7577. else if (ip_ver == 6) {
  7578. /* connected with IPv6 */
  7579. conn_ret = connect(*sock,
  7580. (struct sockaddr *)((void *)&sa->sin6),
  7581. sizeof(sa->sin6));
  7582. }
  7583. #endif
  7584. if (conn_ret != 0) {
  7585. sockerr = ERRNO;
  7586. }
  7587. #if defined(_WIN32)
  7588. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7589. #else
  7590. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7591. #endif
  7592. /* Data for getsockopt */
  7593. void *psockerr = &sockerr;
  7594. int ret;
  7595. #if defined(_WIN32)
  7596. int len = (int)sizeof(sockerr);
  7597. #else
  7598. socklen_t len = (socklen_t)sizeof(sockerr);
  7599. #endif
  7600. /* Data for poll */
  7601. struct mg_pollfd pfd[1];
  7602. int pollres;
  7603. int ms_wait = 10000; /* 10 second timeout */
  7604. int nonstop = 0;
  7605. /* For a non-blocking socket, the connect sequence is:
  7606. * 1) call connect (will not block)
  7607. * 2) wait until the socket is ready for writing (select or poll)
  7608. * 3) check connection state with getsockopt
  7609. */
  7610. pfd[0].fd = *sock;
  7611. pfd[0].events = POLLOUT;
  7612. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7613. if (pollres != 1) {
  7614. /* Not connected */
  7615. mg_snprintf(NULL,
  7616. NULL, /* No truncation check for ebuf */
  7617. ebuf,
  7618. ebuf_len,
  7619. "connect(%s:%d): timeout",
  7620. host,
  7621. port);
  7622. closesocket(*sock);
  7623. *sock = INVALID_SOCKET;
  7624. return 0;
  7625. }
  7626. #if defined(_WIN32)
  7627. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7628. #else
  7629. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7630. #endif
  7631. if ((ret == 0) && (sockerr == 0)) {
  7632. conn_ret = 0;
  7633. }
  7634. }
  7635. if (conn_ret != 0) {
  7636. /* Not connected */
  7637. mg_snprintf(NULL,
  7638. NULL, /* No truncation check for ebuf */
  7639. ebuf,
  7640. ebuf_len,
  7641. "connect(%s:%d): error %s",
  7642. host,
  7643. port,
  7644. strerror(sockerr));
  7645. closesocket(*sock);
  7646. *sock = INVALID_SOCKET;
  7647. return 0;
  7648. }
  7649. return 1;
  7650. }
  7651. int
  7652. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7653. {
  7654. static const char *dont_escape = "._-$,;~()";
  7655. static const char *hex = "0123456789abcdef";
  7656. char *pos = dst;
  7657. const char *end = dst + dst_len - 1;
  7658. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7659. if (isalnum((unsigned char)*src)
  7660. || (strchr(dont_escape, *src) != NULL)) {
  7661. *pos = *src;
  7662. } else if (pos + 2 < end) {
  7663. pos[0] = '%';
  7664. pos[1] = hex[(unsigned char)*src >> 4];
  7665. pos[2] = hex[(unsigned char)*src & 0xf];
  7666. pos += 2;
  7667. } else {
  7668. break;
  7669. }
  7670. }
  7671. *pos = '\0';
  7672. return (*src == '\0') ? (int)(pos - dst) : -1;
  7673. }
  7674. /* Return 0 on success, non-zero if an error occurs. */
  7675. static int
  7676. print_dir_entry(struct de *de)
  7677. {
  7678. size_t namesize, escsize, i;
  7679. char *href, *esc, *p;
  7680. char size[64], mod[64];
  7681. #if defined(REENTRANT_TIME)
  7682. struct tm _tm;
  7683. struct tm *tm = &_tm;
  7684. #else
  7685. struct tm *tm;
  7686. #endif
  7687. /* Estimate worst case size for encoding and escaping */
  7688. namesize = strlen(de->file_name) + 1;
  7689. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7690. href = (char *)mg_malloc(namesize * 3 + escsize);
  7691. if (href == NULL) {
  7692. return -1;
  7693. }
  7694. mg_url_encode(de->file_name, href, namesize * 3);
  7695. esc = NULL;
  7696. if (escsize > 0) {
  7697. /* HTML escaping needed */
  7698. esc = href + namesize * 3;
  7699. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7700. mg_strlcpy(p, de->file_name + i, 2);
  7701. if (*p == '&') {
  7702. strcpy(p, "&amp;");
  7703. } else if (*p == '<') {
  7704. strcpy(p, "&lt;");
  7705. } else if (*p == '>') {
  7706. strcpy(p, "&gt;");
  7707. }
  7708. }
  7709. }
  7710. if (de->file.is_directory) {
  7711. mg_snprintf(de->conn,
  7712. NULL, /* Buffer is big enough */
  7713. size,
  7714. sizeof(size),
  7715. "%s",
  7716. "[DIRECTORY]");
  7717. } else {
  7718. /* We use (signed) cast below because MSVC 6 compiler cannot
  7719. * convert unsigned __int64 to double. Sigh. */
  7720. if (de->file.size < 1024) {
  7721. mg_snprintf(de->conn,
  7722. NULL, /* Buffer is big enough */
  7723. size,
  7724. sizeof(size),
  7725. "%d",
  7726. (int)de->file.size);
  7727. } else if (de->file.size < 0x100000) {
  7728. mg_snprintf(de->conn,
  7729. NULL, /* Buffer is big enough */
  7730. size,
  7731. sizeof(size),
  7732. "%.1fk",
  7733. (double)de->file.size / 1024.0);
  7734. } else if (de->file.size < 0x40000000) {
  7735. mg_snprintf(de->conn,
  7736. NULL, /* Buffer is big enough */
  7737. size,
  7738. sizeof(size),
  7739. "%.1fM",
  7740. (double)de->file.size / 1048576);
  7741. } else {
  7742. mg_snprintf(de->conn,
  7743. NULL, /* Buffer is big enough */
  7744. size,
  7745. sizeof(size),
  7746. "%.1fG",
  7747. (double)de->file.size / 1073741824);
  7748. }
  7749. }
  7750. /* Note: mg_snprintf will not cause a buffer overflow above.
  7751. * So, string truncation checks are not required here. */
  7752. #if defined(REENTRANT_TIME)
  7753. localtime_r(&de->file.last_modified, tm);
  7754. #else
  7755. tm = localtime(&de->file.last_modified);
  7756. #endif
  7757. if (tm != NULL) {
  7758. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7759. } else {
  7760. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7761. mod[sizeof(mod) - 1] = '\0';
  7762. }
  7763. mg_printf(de->conn,
  7764. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7765. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7766. href,
  7767. de->file.is_directory ? "/" : "",
  7768. esc ? esc : de->file_name,
  7769. de->file.is_directory ? "/" : "",
  7770. mod,
  7771. size);
  7772. mg_free(href);
  7773. return 0;
  7774. }
  7775. /* This function is called from send_directory() and used for
  7776. * sorting directory entries by size, or name, or modification time.
  7777. * On windows, __cdecl specification is needed in case if project is built
  7778. * with __stdcall convention. qsort always requires __cdels callback. */
  7779. static int WINCDECL
  7780. compare_dir_entries(const void *p1, const void *p2)
  7781. {
  7782. if (p1 && p2) {
  7783. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7784. const char *query_string = a->conn->request_info.query_string;
  7785. int cmp_result = 0;
  7786. if ((query_string == NULL) || (query_string[0] == '\0')) {
  7787. query_string = "n";
  7788. }
  7789. if (a->file.is_directory && !b->file.is_directory) {
  7790. return -1; /* Always put directories on top */
  7791. } else if (!a->file.is_directory && b->file.is_directory) {
  7792. return 1; /* Always put directories on top */
  7793. } else if (*query_string == 'n') {
  7794. cmp_result = strcmp(a->file_name, b->file_name);
  7795. } else if (*query_string == 's') {
  7796. cmp_result = (a->file.size == b->file.size)
  7797. ? 0
  7798. : ((a->file.size > b->file.size) ? 1 : -1);
  7799. } else if (*query_string == 'd') {
  7800. cmp_result =
  7801. (a->file.last_modified == b->file.last_modified)
  7802. ? 0
  7803. : ((a->file.last_modified > b->file.last_modified) ? 1
  7804. : -1);
  7805. }
  7806. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7807. }
  7808. return 0;
  7809. }
  7810. static int
  7811. must_hide_file(struct mg_connection *conn, const char *path)
  7812. {
  7813. if (conn && conn->dom_ctx) {
  7814. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7815. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7816. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7817. || ((pattern != NULL)
  7818. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7819. }
  7820. return 0;
  7821. }
  7822. static int
  7823. scan_directory(struct mg_connection *conn,
  7824. const char *dir,
  7825. void *data,
  7826. int (*cb)(struct de *, void *))
  7827. {
  7828. char path[PATH_MAX];
  7829. struct dirent *dp;
  7830. DIR *dirp;
  7831. struct de de;
  7832. int truncated;
  7833. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7834. return 0;
  7835. } else {
  7836. de.conn = conn;
  7837. while ((dp = mg_readdir(dirp)) != NULL) {
  7838. /* Do not show current dir and hidden files */
  7839. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7840. || must_hide_file(conn, dp->d_name)) {
  7841. continue;
  7842. }
  7843. mg_snprintf(
  7844. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7845. /* If we don't memset stat structure to zero, mtime will have
  7846. * garbage and strftime() will segfault later on in
  7847. * print_dir_entry(). memset is required only if mg_stat()
  7848. * fails. For more details, see
  7849. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7850. memset(&de.file, 0, sizeof(de.file));
  7851. if (truncated) {
  7852. /* If the path is not complete, skip processing. */
  7853. continue;
  7854. }
  7855. if (!mg_stat(conn, path, &de.file)) {
  7856. mg_cry_internal(conn,
  7857. "%s: mg_stat(%s) failed: %s",
  7858. __func__,
  7859. path,
  7860. strerror(ERRNO));
  7861. }
  7862. de.file_name = dp->d_name;
  7863. cb(&de, data);
  7864. }
  7865. (void)mg_closedir(dirp);
  7866. }
  7867. return 1;
  7868. }
  7869. #if !defined(NO_FILES)
  7870. static int
  7871. remove_directory(struct mg_connection *conn, const char *dir)
  7872. {
  7873. char path[PATH_MAX];
  7874. struct dirent *dp;
  7875. DIR *dirp;
  7876. struct de de;
  7877. int truncated;
  7878. int ok = 1;
  7879. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7880. return 0;
  7881. } else {
  7882. de.conn = conn;
  7883. while ((dp = mg_readdir(dirp)) != NULL) {
  7884. /* Do not show current dir (but show hidden files as they will
  7885. * also be removed) */
  7886. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7887. continue;
  7888. }
  7889. mg_snprintf(
  7890. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7891. /* If we don't memset stat structure to zero, mtime will have
  7892. * garbage and strftime() will segfault later on in
  7893. * print_dir_entry(). memset is required only if mg_stat()
  7894. * fails. For more details, see
  7895. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7896. memset(&de.file, 0, sizeof(de.file));
  7897. if (truncated) {
  7898. /* Do not delete anything shorter */
  7899. ok = 0;
  7900. continue;
  7901. }
  7902. if (!mg_stat(conn, path, &de.file)) {
  7903. mg_cry_internal(conn,
  7904. "%s: mg_stat(%s) failed: %s",
  7905. __func__,
  7906. path,
  7907. strerror(ERRNO));
  7908. ok = 0;
  7909. }
  7910. if (de.file.is_directory) {
  7911. if (remove_directory(conn, path) == 0) {
  7912. ok = 0;
  7913. }
  7914. } else {
  7915. /* This will fail file is the file is in memory */
  7916. if (mg_remove(conn, path) == 0) {
  7917. ok = 0;
  7918. }
  7919. }
  7920. }
  7921. (void)mg_closedir(dirp);
  7922. IGNORE_UNUSED_RESULT(rmdir(dir));
  7923. }
  7924. return ok;
  7925. }
  7926. #endif
  7927. struct dir_scan_data {
  7928. struct de *entries;
  7929. unsigned int num_entries;
  7930. unsigned int arr_size;
  7931. };
  7932. /* Behaves like realloc(), but frees original pointer on failure */
  7933. static void *
  7934. realloc2(void *ptr, size_t size)
  7935. {
  7936. void *new_ptr = mg_realloc(ptr, size);
  7937. if (new_ptr == NULL) {
  7938. mg_free(ptr);
  7939. }
  7940. return new_ptr;
  7941. }
  7942. static int
  7943. dir_scan_callback(struct de *de, void *data)
  7944. {
  7945. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7946. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7947. dsd->arr_size *= 2;
  7948. dsd->entries =
  7949. (struct de *)realloc2(dsd->entries,
  7950. dsd->arr_size * sizeof(dsd->entries[0]));
  7951. }
  7952. if (dsd->entries == NULL) {
  7953. /* TODO(lsm, low): propagate an error to the caller */
  7954. dsd->num_entries = 0;
  7955. } else {
  7956. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7957. dsd->entries[dsd->num_entries].file = de->file;
  7958. dsd->entries[dsd->num_entries].conn = de->conn;
  7959. dsd->num_entries++;
  7960. }
  7961. return 0;
  7962. }
  7963. static void
  7964. handle_directory_request(struct mg_connection *conn, const char *dir)
  7965. {
  7966. unsigned int i;
  7967. int sort_direction;
  7968. struct dir_scan_data data = {NULL, 0, 128};
  7969. char date[64], *esc, *p;
  7970. const char *title;
  7971. time_t curtime = time(NULL);
  7972. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7973. mg_send_http_error(conn,
  7974. 500,
  7975. "Error: Cannot open directory\nopendir(%s): %s",
  7976. dir,
  7977. strerror(ERRNO));
  7978. return;
  7979. }
  7980. gmt_time_string(date, sizeof(date), &curtime);
  7981. if (!conn) {
  7982. return;
  7983. }
  7984. esc = NULL;
  7985. title = conn->request_info.local_uri;
  7986. if (title[strcspn(title, "&<>")]) {
  7987. /* HTML escaping needed */
  7988. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  7989. if (esc) {
  7990. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  7991. mg_strlcpy(p, title + i, 2);
  7992. if (*p == '&') {
  7993. strcpy(p, "&amp;");
  7994. } else if (*p == '<') {
  7995. strcpy(p, "&lt;");
  7996. } else if (*p == '>') {
  7997. strcpy(p, "&gt;");
  7998. }
  7999. }
  8000. } else {
  8001. title = "";
  8002. }
  8003. }
  8004. sort_direction = ((conn->request_info.query_string != NULL)
  8005. && (conn->request_info.query_string[0] != '\0')
  8006. && (conn->request_info.query_string[1] == 'd'))
  8007. ? 'a'
  8008. : 'd';
  8009. conn->must_close = 1;
  8010. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8011. send_static_cache_header(conn);
  8012. send_additional_header(conn);
  8013. mg_printf(conn,
  8014. "Date: %s\r\n"
  8015. "Connection: close\r\n"
  8016. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8017. date);
  8018. mg_printf(conn,
  8019. "<html><head><title>Index of %s</title>"
  8020. "<style>th {text-align: left;}</style></head>"
  8021. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8022. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8023. "<th><a href=\"?d%c\">Modified</a></th>"
  8024. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8025. "<tr><td colspan=\"3\"><hr></td></tr>",
  8026. esc ? esc : title,
  8027. esc ? esc : title,
  8028. sort_direction,
  8029. sort_direction,
  8030. sort_direction);
  8031. mg_free(esc);
  8032. /* Print first entry - link to a parent directory */
  8033. mg_printf(conn,
  8034. "<tr><td><a href=\"%s\">%s</a></td>"
  8035. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8036. "..",
  8037. "Parent directory",
  8038. "-",
  8039. "-");
  8040. /* Sort and print directory entries */
  8041. if (data.entries != NULL) {
  8042. qsort(data.entries,
  8043. (size_t)data.num_entries,
  8044. sizeof(data.entries[0]),
  8045. compare_dir_entries);
  8046. for (i = 0; i < data.num_entries; i++) {
  8047. print_dir_entry(&data.entries[i]);
  8048. mg_free(data.entries[i].file_name);
  8049. }
  8050. mg_free(data.entries);
  8051. }
  8052. mg_printf(conn, "%s", "</table></pre></body></html>");
  8053. conn->status_code = 200;
  8054. }
  8055. /* Send len bytes from the opened file to the client. */
  8056. static void
  8057. send_file_data(struct mg_connection *conn,
  8058. struct mg_file *filep,
  8059. int64_t offset,
  8060. int64_t len)
  8061. {
  8062. char buf[MG_BUF_LEN];
  8063. int to_read, num_read, num_written;
  8064. int64_t size;
  8065. if (!filep || !conn) {
  8066. return;
  8067. }
  8068. /* Sanity check the offset */
  8069. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8070. : (int64_t)(filep->stat.size);
  8071. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8072. #if defined(MG_USE_OPEN_FILE)
  8073. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8074. /* file stored in memory */
  8075. if (len > size - offset) {
  8076. len = size - offset;
  8077. }
  8078. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8079. } else /* else block below */
  8080. #endif
  8081. if (len > 0 && filep->access.fp != NULL) {
  8082. /* file stored on disk */
  8083. #if defined(__linux__)
  8084. /* sendfile is only available for Linux */
  8085. if ((conn->ssl == 0) && (conn->throttle == 0)
  8086. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8087. "yes"))) {
  8088. off_t sf_offs = (off_t)offset;
  8089. ssize_t sf_sent;
  8090. int sf_file = fileno(filep->access.fp);
  8091. int loop_cnt = 0;
  8092. do {
  8093. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8094. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8095. size_t sf_tosend =
  8096. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8097. sf_sent =
  8098. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8099. if (sf_sent > 0) {
  8100. len -= sf_sent;
  8101. offset += sf_sent;
  8102. } else if (loop_cnt == 0) {
  8103. /* This file can not be sent using sendfile.
  8104. * This might be the case for pseudo-files in the
  8105. * /sys/ and /proc/ file system.
  8106. * Use the regular user mode copy code instead. */
  8107. break;
  8108. } else if (sf_sent == 0) {
  8109. /* No error, but 0 bytes sent. May be EOF? */
  8110. return;
  8111. }
  8112. loop_cnt++;
  8113. } while ((len > 0) && (sf_sent >= 0));
  8114. if (sf_sent > 0) {
  8115. return; /* OK */
  8116. }
  8117. /* sf_sent<0 means error, thus fall back to the classic way */
  8118. /* This is always the case, if sf_file is not a "normal" file,
  8119. * e.g., for sending data from the output of a CGI process. */
  8120. offset = (int64_t)sf_offs;
  8121. }
  8122. #endif
  8123. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8124. mg_cry_internal(conn,
  8125. "%s: fseeko() failed: %s",
  8126. __func__,
  8127. strerror(ERRNO));
  8128. mg_send_http_error(
  8129. conn,
  8130. 500,
  8131. "%s",
  8132. "Error: Unable to access file at requested position.");
  8133. } else {
  8134. while (len > 0) {
  8135. /* Calculate how much to read from the file in the buffer */
  8136. to_read = sizeof(buf);
  8137. if ((int64_t)to_read > len) {
  8138. to_read = (int)len;
  8139. }
  8140. /* Read from file, exit the loop on error */
  8141. if ((num_read =
  8142. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8143. <= 0) {
  8144. break;
  8145. }
  8146. /* Send read bytes to the client, exit the loop on error */
  8147. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8148. != num_read) {
  8149. break;
  8150. }
  8151. /* Both read and were successful, adjust counters */
  8152. len -= num_written;
  8153. }
  8154. }
  8155. }
  8156. }
  8157. static int
  8158. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8159. {
  8160. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8161. }
  8162. static void
  8163. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8164. {
  8165. if ((filestat != NULL) && (buf != NULL)) {
  8166. mg_snprintf(NULL,
  8167. NULL, /* All calls to construct_etag use 64 byte buffer */
  8168. buf,
  8169. buf_len,
  8170. "\"%lx.%" INT64_FMT "\"",
  8171. (unsigned long)filestat->last_modified,
  8172. filestat->size);
  8173. }
  8174. }
  8175. static void
  8176. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8177. {
  8178. if (filep != NULL && filep->fp != NULL) {
  8179. #if defined(_WIN32)
  8180. (void)conn; /* Unused. */
  8181. #else
  8182. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8183. mg_cry_internal(conn,
  8184. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8185. __func__,
  8186. strerror(ERRNO));
  8187. }
  8188. #endif
  8189. }
  8190. }
  8191. #if defined(USE_ZLIB)
  8192. #include "mod_zlib.inl"
  8193. #endif
  8194. static void
  8195. handle_static_file_request(struct mg_connection *conn,
  8196. const char *path,
  8197. struct mg_file *filep,
  8198. const char *mime_type,
  8199. const char *additional_headers)
  8200. {
  8201. char date[64], lm[64], etag[64];
  8202. char range[128]; /* large enough, so there will be no overflow */
  8203. const char *msg = "OK";
  8204. const char *range_hdr;
  8205. time_t curtime = time(NULL);
  8206. int64_t cl, r1, r2;
  8207. struct vec mime_vec;
  8208. int n, truncated;
  8209. char gz_path[PATH_MAX];
  8210. const char *encoding = "";
  8211. const char *origin_hdr;
  8212. const char *cors_orig_cfg;
  8213. const char *cors1, *cors2, *cors3;
  8214. int is_head_request;
  8215. #if defined(USE_ZLIB)
  8216. /* Compression is allowed, unless there is a reason not to use compression.
  8217. * If the file is already compressed, too small or a "range" request was
  8218. * made, on the fly compression is not possible. */
  8219. int allow_on_the_fly_compression = 1;
  8220. #endif
  8221. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8222. return;
  8223. }
  8224. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8225. if (mime_type == NULL) {
  8226. get_mime_type(conn, path, &mime_vec);
  8227. } else {
  8228. mime_vec.ptr = mime_type;
  8229. mime_vec.len = strlen(mime_type);
  8230. }
  8231. if (filep->stat.size > INT64_MAX) {
  8232. mg_send_http_error(conn,
  8233. 500,
  8234. "Error: File size is too large to send\n%" INT64_FMT,
  8235. filep->stat.size);
  8236. return;
  8237. }
  8238. cl = (int64_t)filep->stat.size;
  8239. conn->status_code = 200;
  8240. range[0] = '\0';
  8241. #if defined(USE_ZLIB)
  8242. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8243. * it's important to rewrite the filename after resolving
  8244. * the mime type from it, to preserve the actual file's type */
  8245. if (!conn->accept_gzip) {
  8246. allow_on_the_fly_compression = 0;
  8247. }
  8248. #endif
  8249. /* Check if there is a range header */
  8250. range_hdr = mg_get_header(conn, "Range");
  8251. /* For gzipped files, add *.gz */
  8252. if (filep->stat.is_gzipped) {
  8253. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8254. if (truncated) {
  8255. mg_send_http_error(conn,
  8256. 500,
  8257. "Error: Path of zipped file too long (%s)",
  8258. path);
  8259. return;
  8260. }
  8261. path = gz_path;
  8262. encoding = "Content-Encoding: gzip\r\n";
  8263. #if defined(USE_ZLIB)
  8264. /* File is already compressed. No "on the fly" compression. */
  8265. allow_on_the_fly_compression = 0;
  8266. #endif
  8267. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8268. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8269. struct mg_file_stat file_stat;
  8270. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8271. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8272. && !file_stat.is_directory) {
  8273. file_stat.is_gzipped = 1;
  8274. filep->stat = file_stat;
  8275. cl = (int64_t)filep->stat.size;
  8276. path = gz_path;
  8277. encoding = "Content-Encoding: gzip\r\n";
  8278. #if defined(USE_ZLIB)
  8279. /* File is already compressed. No "on the fly" compression. */
  8280. allow_on_the_fly_compression = 0;
  8281. #endif
  8282. }
  8283. }
  8284. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8285. mg_send_http_error(conn,
  8286. 500,
  8287. "Error: Cannot open file\nfopen(%s): %s",
  8288. path,
  8289. strerror(ERRNO));
  8290. return;
  8291. }
  8292. fclose_on_exec(&filep->access, conn);
  8293. /* If "Range" request was made: parse header, send only selected part
  8294. * of the file. */
  8295. r1 = r2 = 0;
  8296. if ((range_hdr != NULL)
  8297. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8298. && (r2 >= 0)) {
  8299. /* actually, range requests don't play well with a pre-gzipped
  8300. * file (since the range is specified in the uncompressed space) */
  8301. if (filep->stat.is_gzipped) {
  8302. mg_send_http_error(
  8303. conn,
  8304. 416, /* 416 = Range Not Satisfiable */
  8305. "%s",
  8306. "Error: Range requests in gzipped files are not supported");
  8307. (void)mg_fclose(
  8308. &filep->access); /* ignore error on read only file */
  8309. return;
  8310. }
  8311. conn->status_code = 206;
  8312. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8313. mg_snprintf(conn,
  8314. NULL, /* range buffer is big enough */
  8315. range,
  8316. sizeof(range),
  8317. "Content-Range: bytes "
  8318. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8319. r1,
  8320. r1 + cl - 1,
  8321. filep->stat.size);
  8322. msg = "Partial Content";
  8323. #if defined(USE_ZLIB)
  8324. /* Do not compress ranges. */
  8325. allow_on_the_fly_compression = 0;
  8326. #endif
  8327. }
  8328. /* Do not compress small files. Small files do not benefit from file
  8329. * compression, but there is still some overhead. */
  8330. #if defined(USE_ZLIB)
  8331. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8332. /* File is below the size limit. */
  8333. allow_on_the_fly_compression = 0;
  8334. }
  8335. #endif
  8336. /* Standard CORS header */
  8337. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8338. origin_hdr = mg_get_header(conn, "Origin");
  8339. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8340. /* Cross-origin resource sharing (CORS), see
  8341. * http://www.html5rocks.com/en/tutorials/cors/,
  8342. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8343. * -
  8344. * preflight is not supported for files. */
  8345. cors1 = "Access-Control-Allow-Origin: ";
  8346. cors2 = cors_orig_cfg;
  8347. cors3 = "\r\n";
  8348. } else {
  8349. cors1 = cors2 = cors3 = "";
  8350. }
  8351. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8352. * according to
  8353. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8354. gmt_time_string(date, sizeof(date), &curtime);
  8355. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8356. construct_etag(etag, sizeof(etag), &filep->stat);
  8357. /* Send header */
  8358. (void)mg_printf(conn,
  8359. "HTTP/1.1 %d %s\r\n"
  8360. "%s%s%s" /* CORS */
  8361. "Date: %s\r\n"
  8362. "Last-Modified: %s\r\n"
  8363. "Etag: %s\r\n"
  8364. "Content-Type: %.*s\r\n"
  8365. "Connection: %s\r\n",
  8366. conn->status_code,
  8367. msg,
  8368. cors1,
  8369. cors2,
  8370. cors3,
  8371. date,
  8372. lm,
  8373. etag,
  8374. (int)mime_vec.len,
  8375. mime_vec.ptr,
  8376. suggest_connection_header(conn));
  8377. send_static_cache_header(conn);
  8378. send_additional_header(conn);
  8379. #if defined(USE_ZLIB)
  8380. /* On the fly compression allowed */
  8381. if (allow_on_the_fly_compression) {
  8382. /* For on the fly compression, we don't know the content size in
  8383. * advance, so we have to use chunked encoding */
  8384. (void)mg_printf(conn,
  8385. "Content-Encoding: gzip\r\n"
  8386. "Transfer-Encoding: chunked\r\n");
  8387. } else
  8388. #endif
  8389. {
  8390. /* Without on-the-fly compression, we know the content-length
  8391. * and we can use ranges (with on-the-fly compression we cannot).
  8392. * So we send these response headers only in this case. */
  8393. (void)mg_printf(conn,
  8394. "Content-Length: %" INT64_FMT "\r\n"
  8395. "Accept-Ranges: bytes\r\n"
  8396. "%s" /* range */
  8397. "%s" /* encoding */,
  8398. cl,
  8399. range,
  8400. encoding);
  8401. }
  8402. /* The previous code must not add any header starting with X- to make
  8403. * sure no one of the additional_headers is included twice */
  8404. if (additional_headers != NULL) {
  8405. (void)mg_printf(conn,
  8406. "%.*s\r\n\r\n",
  8407. (int)strlen(additional_headers),
  8408. additional_headers);
  8409. } else {
  8410. (void)mg_printf(conn, "\r\n");
  8411. }
  8412. if (!is_head_request) {
  8413. #if defined(USE_ZLIB)
  8414. if (allow_on_the_fly_compression) {
  8415. /* Compress and send */
  8416. send_compressed_data(conn, filep);
  8417. } else
  8418. #endif
  8419. {
  8420. /* Send file directly */
  8421. send_file_data(conn, filep, r1, cl);
  8422. }
  8423. }
  8424. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8425. }
  8426. int
  8427. mg_send_file_body(struct mg_connection *conn, const char *path)
  8428. {
  8429. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8430. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8431. return -1;
  8432. }
  8433. fclose_on_exec(&file.access, conn);
  8434. send_file_data(conn, &file, 0, INT64_MAX);
  8435. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8436. return 0; /* >= 0 for OK */
  8437. }
  8438. #if !defined(NO_CACHING)
  8439. /* Return True if we should reply 304 Not Modified. */
  8440. static int
  8441. is_not_modified(const struct mg_connection *conn,
  8442. const struct mg_file_stat *filestat)
  8443. {
  8444. char etag[64];
  8445. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8446. const char *inm = mg_get_header(conn, "If-None-Match");
  8447. construct_etag(etag, sizeof(etag), filestat);
  8448. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8449. || ((ims != NULL)
  8450. && (filestat->last_modified <= parse_date_string(ims)));
  8451. }
  8452. static void
  8453. handle_not_modified_static_file_request(struct mg_connection *conn,
  8454. struct mg_file *filep)
  8455. {
  8456. char date[64], lm[64], etag[64];
  8457. time_t curtime = time(NULL);
  8458. if ((conn == NULL) || (filep == NULL)) {
  8459. return;
  8460. }
  8461. conn->status_code = 304;
  8462. gmt_time_string(date, sizeof(date), &curtime);
  8463. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8464. construct_etag(etag, sizeof(etag), &filep->stat);
  8465. (void)mg_printf(conn,
  8466. "HTTP/1.1 %d %s\r\n"
  8467. "Date: %s\r\n",
  8468. conn->status_code,
  8469. mg_get_response_code_text(conn, conn->status_code),
  8470. date);
  8471. send_static_cache_header(conn);
  8472. send_additional_header(conn);
  8473. (void)mg_printf(conn,
  8474. "Last-Modified: %s\r\n"
  8475. "Etag: %s\r\n"
  8476. "Connection: %s\r\n"
  8477. "\r\n",
  8478. lm,
  8479. etag,
  8480. suggest_connection_header(conn));
  8481. }
  8482. #endif
  8483. void
  8484. mg_send_file(struct mg_connection *conn, const char *path)
  8485. {
  8486. mg_send_mime_file2(conn, path, NULL, NULL);
  8487. }
  8488. void
  8489. mg_send_mime_file(struct mg_connection *conn,
  8490. const char *path,
  8491. const char *mime_type)
  8492. {
  8493. mg_send_mime_file2(conn, path, mime_type, NULL);
  8494. }
  8495. void
  8496. mg_send_mime_file2(struct mg_connection *conn,
  8497. const char *path,
  8498. const char *mime_type,
  8499. const char *additional_headers)
  8500. {
  8501. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8502. if (!conn) {
  8503. /* No conn */
  8504. return;
  8505. }
  8506. if (mg_stat(conn, path, &file.stat)) {
  8507. #if !defined(NO_CACHING)
  8508. if (is_not_modified(conn, &file.stat)) {
  8509. /* Send 304 "Not Modified" - this must not send any body data */
  8510. handle_not_modified_static_file_request(conn, &file);
  8511. } else
  8512. #endif /* NO_CACHING */
  8513. if (file.stat.is_directory) {
  8514. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8515. "yes")) {
  8516. handle_directory_request(conn, path);
  8517. } else {
  8518. mg_send_http_error(conn,
  8519. 403,
  8520. "%s",
  8521. "Error: Directory listing denied");
  8522. }
  8523. } else {
  8524. handle_static_file_request(
  8525. conn, path, &file, mime_type, additional_headers);
  8526. }
  8527. } else {
  8528. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8529. }
  8530. }
  8531. /* For a given PUT path, create all intermediate subdirectories.
  8532. * Return 0 if the path itself is a directory.
  8533. * Return 1 if the path leads to a file.
  8534. * Return -1 for if the path is too long.
  8535. * Return -2 if path can not be created.
  8536. */
  8537. static int
  8538. put_dir(struct mg_connection *conn, const char *path)
  8539. {
  8540. char buf[PATH_MAX];
  8541. const char *s, *p;
  8542. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8543. size_t len;
  8544. int res = 1;
  8545. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8546. len = (size_t)(p - path);
  8547. if (len >= sizeof(buf)) {
  8548. /* path too long */
  8549. res = -1;
  8550. break;
  8551. }
  8552. memcpy(buf, path, len);
  8553. buf[len] = '\0';
  8554. /* Try to create intermediate directory */
  8555. DEBUG_TRACE("mkdir(%s)", buf);
  8556. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8557. /* path does not exixt and can not be created */
  8558. res = -2;
  8559. break;
  8560. }
  8561. /* Is path itself a directory? */
  8562. if (p[1] == '\0') {
  8563. res = 0;
  8564. }
  8565. }
  8566. return res;
  8567. }
  8568. static void
  8569. remove_bad_file(const struct mg_connection *conn, const char *path)
  8570. {
  8571. int r = mg_remove(conn, path);
  8572. if (r != 0) {
  8573. mg_cry_internal(conn,
  8574. "%s: Cannot remove invalid file %s",
  8575. __func__,
  8576. path);
  8577. }
  8578. }
  8579. long long
  8580. mg_store_body(struct mg_connection *conn, const char *path)
  8581. {
  8582. char buf[MG_BUF_LEN];
  8583. long long len = 0;
  8584. int ret, n;
  8585. struct mg_file fi;
  8586. if (conn->consumed_content != 0) {
  8587. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8588. return -11;
  8589. }
  8590. ret = put_dir(conn, path);
  8591. if (ret < 0) {
  8592. /* -1 for path too long,
  8593. * -2 for path can not be created. */
  8594. return ret;
  8595. }
  8596. if (ret != 1) {
  8597. /* Return 0 means, path itself is a directory. */
  8598. return 0;
  8599. }
  8600. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8601. return -12;
  8602. }
  8603. ret = mg_read(conn, buf, sizeof(buf));
  8604. while (ret > 0) {
  8605. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8606. if (n != ret) {
  8607. (void)mg_fclose(
  8608. &fi.access); /* File is bad and will be removed anyway. */
  8609. remove_bad_file(conn, path);
  8610. return -13;
  8611. }
  8612. len += ret;
  8613. ret = mg_read(conn, buf, sizeof(buf));
  8614. }
  8615. /* File is open for writing. If fclose fails, there was probably an
  8616. * error flushing the buffer to disk, so the file on disk might be
  8617. * broken. Delete it and return an error to the caller. */
  8618. if (mg_fclose(&fi.access) != 0) {
  8619. remove_bad_file(conn, path);
  8620. return -14;
  8621. }
  8622. return len;
  8623. }
  8624. /* Parse a buffer:
  8625. * Forward the string pointer till the end of a word, then
  8626. * terminate it and forward till the begin of the next word.
  8627. */
  8628. static int
  8629. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8630. {
  8631. /* Forward until a space is found - use isgraph here */
  8632. /* See http://www.cplusplus.com/reference/cctype/ */
  8633. while (isgraph((unsigned char)**ppw)) {
  8634. (*ppw)++;
  8635. }
  8636. /* Check end of word */
  8637. if (eol) {
  8638. /* must be a end of line */
  8639. if ((**ppw != '\r') && (**ppw != '\n')) {
  8640. return -1;
  8641. }
  8642. } else {
  8643. /* must be a end of a word, but not a line */
  8644. if (**ppw != ' ') {
  8645. return -1;
  8646. }
  8647. }
  8648. /* Terminate and forward to the next word */
  8649. do {
  8650. **ppw = 0;
  8651. (*ppw)++;
  8652. } while (isspace((unsigned char)**ppw));
  8653. /* Check after term */
  8654. if (!eol) {
  8655. /* if it's not the end of line, there must be a next word */
  8656. if (!isgraph((unsigned char)**ppw)) {
  8657. return -1;
  8658. }
  8659. }
  8660. /* ok */
  8661. return 1;
  8662. }
  8663. /* Parse HTTP headers from the given buffer, advance buf pointer
  8664. * to the point where parsing stopped.
  8665. * All parameters must be valid pointers (not NULL).
  8666. * Return <0 on error. */
  8667. static int
  8668. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8669. {
  8670. int i;
  8671. int num_headers = 0;
  8672. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8673. char *dp = *buf;
  8674. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8675. dp++;
  8676. }
  8677. if (dp == *buf) {
  8678. /* End of headers reached. */
  8679. break;
  8680. }
  8681. if (*dp != ':') {
  8682. /* This is not a valid field. */
  8683. return -1;
  8684. }
  8685. /* End of header key (*dp == ':') */
  8686. /* Truncate here and set the key name */
  8687. *dp = 0;
  8688. hdr[i].name = *buf;
  8689. do {
  8690. dp++;
  8691. } while (*dp == ' ');
  8692. /* The rest of the line is the value */
  8693. hdr[i].value = dp;
  8694. *buf = dp + strcspn(dp, "\r\n");
  8695. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8696. *buf = NULL;
  8697. }
  8698. num_headers = i + 1;
  8699. if (*buf) {
  8700. (*buf)[0] = 0;
  8701. (*buf)[1] = 0;
  8702. *buf += 2;
  8703. } else {
  8704. *buf = dp;
  8705. break;
  8706. }
  8707. if ((*buf)[0] == '\r') {
  8708. /* This is the end of the header */
  8709. break;
  8710. }
  8711. }
  8712. return num_headers;
  8713. }
  8714. struct mg_http_method_info {
  8715. const char *name;
  8716. int request_has_body;
  8717. int response_has_body;
  8718. int is_safe;
  8719. int is_idempotent;
  8720. int is_cacheable;
  8721. };
  8722. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8723. static struct mg_http_method_info http_methods[] = {
  8724. /* HTTP (RFC 2616) */
  8725. {"GET", 0, 1, 1, 1, 1},
  8726. {"POST", 1, 1, 0, 0, 0},
  8727. {"PUT", 1, 0, 0, 1, 0},
  8728. {"DELETE", 0, 0, 0, 1, 0},
  8729. {"HEAD", 0, 0, 1, 1, 1},
  8730. {"OPTIONS", 0, 0, 1, 1, 0},
  8731. {"CONNECT", 1, 1, 0, 0, 0},
  8732. /* TRACE method (RFC 2616) is not supported for security reasons */
  8733. /* PATCH method (RFC 5789) */
  8734. {"PATCH", 1, 0, 0, 0, 0},
  8735. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8736. /* WEBDAV (RFC 2518) */
  8737. {"PROPFIND", 0, 1, 1, 1, 0},
  8738. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8739. * Some PROPFIND results MAY be cached, with care,
  8740. * as there is no cache validation mechanism for
  8741. * most properties. This method is both safe and
  8742. * idempotent (see Section 9.1 of [RFC2616]). */
  8743. {"MKCOL", 0, 0, 0, 1, 0},
  8744. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8745. * When MKCOL is invoked without a request body,
  8746. * the newly created collection SHOULD have no
  8747. * members. A MKCOL request message may contain
  8748. * a message body. The precise behavior of a MKCOL
  8749. * request when the body is present is undefined,
  8750. * ... ==> We do not support MKCOL with body data.
  8751. * This method is idempotent, but not safe (see
  8752. * Section 9.1 of [RFC2616]). Responses to this
  8753. * method MUST NOT be cached. */
  8754. /* Unsupported WEBDAV Methods: */
  8755. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8756. /* + 11 methods from RFC 3253 */
  8757. /* ORDERPATCH (RFC 3648) */
  8758. /* ACL (RFC 3744) */
  8759. /* SEARCH (RFC 5323) */
  8760. /* + MicroSoft extensions
  8761. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8762. /* REPORT method (RFC 3253) */
  8763. {"REPORT", 1, 1, 1, 1, 1},
  8764. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8765. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8766. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8767. * to be useful for REST in case a "GET request with body" is
  8768. * required. */
  8769. {NULL, 0, 0, 0, 0, 0}
  8770. /* end of list */
  8771. };
  8772. static const struct mg_http_method_info *
  8773. get_http_method_info(const char *method)
  8774. {
  8775. /* Check if the method is known to the server. The list of all known
  8776. * HTTP methods can be found here at
  8777. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8778. */
  8779. const struct mg_http_method_info *m = http_methods;
  8780. while (m->name) {
  8781. if (!strcmp(m->name, method)) {
  8782. return m;
  8783. }
  8784. m++;
  8785. }
  8786. return NULL;
  8787. }
  8788. static int
  8789. is_valid_http_method(const char *method)
  8790. {
  8791. return (get_http_method_info(method) != NULL);
  8792. }
  8793. /* Parse HTTP request, fill in mg_request_info structure.
  8794. * This function modifies the buffer by NUL-terminating
  8795. * HTTP request components, header names and header values.
  8796. * Parameters:
  8797. * buf (in/out): pointer to the HTTP header to parse and split
  8798. * len (in): length of HTTP header buffer
  8799. * re (out): parsed header as mg_request_info
  8800. * buf and ri must be valid pointers (not NULL), len>0.
  8801. * Returns <0 on error. */
  8802. static int
  8803. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8804. {
  8805. int request_length;
  8806. int init_skip = 0;
  8807. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8808. * remote_port */
  8809. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8810. NULL;
  8811. ri->num_headers = 0;
  8812. /* RFC says that all initial whitespaces should be ingored */
  8813. /* This included all leading \r and \n (isspace) */
  8814. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8815. while ((len > 0) && isspace((unsigned char)*buf)) {
  8816. buf++;
  8817. len--;
  8818. init_skip++;
  8819. }
  8820. if (len == 0) {
  8821. /* Incomplete request */
  8822. return 0;
  8823. }
  8824. /* Control characters are not allowed, including zero */
  8825. if (iscntrl((unsigned char)*buf)) {
  8826. return -1;
  8827. }
  8828. /* Find end of HTTP header */
  8829. request_length = get_http_header_len(buf, len);
  8830. if (request_length <= 0) {
  8831. return request_length;
  8832. }
  8833. buf[request_length - 1] = '\0';
  8834. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8835. return -1;
  8836. }
  8837. /* The first word has to be the HTTP method */
  8838. ri->request_method = buf;
  8839. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8840. return -1;
  8841. }
  8842. /* Check for a valid http method */
  8843. if (!is_valid_http_method(ri->request_method)) {
  8844. return -1;
  8845. }
  8846. /* The second word is the URI */
  8847. ri->request_uri = buf;
  8848. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8849. return -1;
  8850. }
  8851. /* Next would be the HTTP version */
  8852. ri->http_version = buf;
  8853. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8854. return -1;
  8855. }
  8856. /* Check for a valid HTTP version key */
  8857. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8858. /* Invalid request */
  8859. return -1;
  8860. }
  8861. ri->http_version += 5;
  8862. /* Parse all HTTP headers */
  8863. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8864. if (ri->num_headers < 0) {
  8865. /* Error while parsing headers */
  8866. return -1;
  8867. }
  8868. return request_length + init_skip;
  8869. }
  8870. static int
  8871. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8872. {
  8873. int response_length;
  8874. int init_skip = 0;
  8875. char *tmp, *tmp2;
  8876. long l;
  8877. /* Initialize elements. */
  8878. ri->http_version = ri->status_text = NULL;
  8879. ri->num_headers = ri->status_code = 0;
  8880. /* RFC says that all initial whitespaces should be ingored */
  8881. /* This included all leading \r and \n (isspace) */
  8882. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8883. while ((len > 0) && isspace((unsigned char)*buf)) {
  8884. buf++;
  8885. len--;
  8886. init_skip++;
  8887. }
  8888. if (len == 0) {
  8889. /* Incomplete request */
  8890. return 0;
  8891. }
  8892. /* Control characters are not allowed, including zero */
  8893. if (iscntrl((unsigned char)*buf)) {
  8894. return -1;
  8895. }
  8896. /* Find end of HTTP header */
  8897. response_length = get_http_header_len(buf, len);
  8898. if (response_length <= 0) {
  8899. return response_length;
  8900. }
  8901. buf[response_length - 1] = '\0';
  8902. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8903. return -1;
  8904. }
  8905. /* The first word is the HTTP version */
  8906. /* Check for a valid HTTP version key */
  8907. if (strncmp(buf, "HTTP/", 5) != 0) {
  8908. /* Invalid request */
  8909. return -1;
  8910. }
  8911. buf += 5;
  8912. if (!isgraph((unsigned char)buf[0])) {
  8913. /* Invalid request */
  8914. return -1;
  8915. }
  8916. ri->http_version = buf;
  8917. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8918. return -1;
  8919. }
  8920. /* The second word is the status as a number */
  8921. tmp = buf;
  8922. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8923. return -1;
  8924. }
  8925. l = strtol(tmp, &tmp2, 10);
  8926. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8927. /* Everything else but a 3 digit code is invalid */
  8928. return -1;
  8929. }
  8930. ri->status_code = (int)l;
  8931. /* The rest of the line is the status text */
  8932. ri->status_text = buf;
  8933. /* Find end of status text */
  8934. /* isgraph or isspace = isprint */
  8935. while (isprint((unsigned char)*buf)) {
  8936. buf++;
  8937. }
  8938. if ((*buf != '\r') && (*buf != '\n')) {
  8939. return -1;
  8940. }
  8941. /* Terminate string and forward buf to next line */
  8942. do {
  8943. *buf = 0;
  8944. buf++;
  8945. } while (isspace((unsigned char)*buf));
  8946. /* Parse all HTTP headers */
  8947. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8948. if (ri->num_headers < 0) {
  8949. /* Error while parsing headers */
  8950. return -1;
  8951. }
  8952. return response_length + init_skip;
  8953. }
  8954. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8955. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8956. * buffer (which marks the end of HTTP request). Buffer buf may already
  8957. * have some data. The length of the data is stored in nread.
  8958. * Upon every read operation, increase nread by the number of bytes read. */
  8959. static int
  8960. read_message(FILE *fp,
  8961. struct mg_connection *conn,
  8962. char *buf,
  8963. int bufsiz,
  8964. int *nread)
  8965. {
  8966. int request_len, n = 0;
  8967. struct timespec last_action_time;
  8968. double request_timeout;
  8969. if (!conn) {
  8970. return 0;
  8971. }
  8972. memset(&last_action_time, 0, sizeof(last_action_time));
  8973. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8974. /* value of request_timeout is in seconds, config in milliseconds */
  8975. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8976. } else {
  8977. request_timeout = -1.0;
  8978. }
  8979. if (conn->handled_requests > 0) {
  8980. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8981. request_timeout =
  8982. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8983. }
  8984. }
  8985. request_len = get_http_header_len(buf, *nread);
  8986. /* first time reading from this connection */
  8987. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8988. while (request_len == 0) {
  8989. /* Full request not yet received */
  8990. if (conn->phys_ctx->stop_flag != 0) {
  8991. /* Server is to be stopped. */
  8992. return -1;
  8993. }
  8994. if (*nread >= bufsiz) {
  8995. /* Request too long */
  8996. return -2;
  8997. }
  8998. n = pull_inner(
  8999. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9000. if (n == -2) {
  9001. /* Receive error */
  9002. return -1;
  9003. }
  9004. if (n > 0) {
  9005. *nread += n;
  9006. request_len = get_http_header_len(buf, *nread);
  9007. } else {
  9008. request_len = 0;
  9009. }
  9010. if ((request_len == 0) && (request_timeout >= 0)) {
  9011. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9012. > request_timeout) {
  9013. /* Timeout */
  9014. return -1;
  9015. }
  9016. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9017. }
  9018. }
  9019. return request_len;
  9020. }
  9021. #if !defined(NO_CGI) || !defined(NO_FILES)
  9022. static int
  9023. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9024. {
  9025. const char *expect;
  9026. char buf[MG_BUF_LEN];
  9027. int success = 0;
  9028. if (!conn) {
  9029. return 0;
  9030. }
  9031. expect = mg_get_header(conn, "Expect");
  9032. DEBUG_ASSERT(fp != NULL);
  9033. if (!fp) {
  9034. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9035. return 0;
  9036. }
  9037. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9038. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9039. */
  9040. mg_send_http_error(conn,
  9041. 417,
  9042. "Error: Can not fulfill expectation %s",
  9043. expect);
  9044. } else {
  9045. if (expect != NULL) {
  9046. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9047. conn->status_code = 100;
  9048. } else {
  9049. conn->status_code = 200;
  9050. }
  9051. DEBUG_ASSERT(conn->consumed_content == 0);
  9052. if (conn->consumed_content != 0) {
  9053. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9054. return 0;
  9055. }
  9056. for (;;) {
  9057. int nread = mg_read(conn, buf, sizeof(buf));
  9058. if (nread <= 0) {
  9059. success = (nread == 0);
  9060. break;
  9061. }
  9062. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9063. break;
  9064. }
  9065. }
  9066. /* Each error code path in this function must send an error */
  9067. if (!success) {
  9068. /* NOTE: Maybe some data has already been sent. */
  9069. /* TODO (low): If some data has been sent, a correct error
  9070. * reply can no longer be sent, so just close the connection */
  9071. mg_send_http_error(conn, 500, "%s", "");
  9072. }
  9073. }
  9074. return success;
  9075. }
  9076. #endif
  9077. #if defined(USE_TIMERS)
  9078. #define TIMER_API static
  9079. #include "timer.inl"
  9080. #endif /* USE_TIMERS */
  9081. #if !defined(NO_CGI)
  9082. /* This structure helps to create an environment for the spawned CGI
  9083. * program.
  9084. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9085. * last element must be NULL.
  9086. * However, on Windows there is a requirement that all these
  9087. * VARIABLE=VALUE\0
  9088. * strings must reside in a contiguous buffer. The end of the buffer is
  9089. * marked by two '\0' characters.
  9090. * We satisfy both worlds: we create an envp array (which is vars), all
  9091. * entries are actually pointers inside buf. */
  9092. struct cgi_environment {
  9093. struct mg_connection *conn;
  9094. /* Data block */
  9095. char *buf; /* Environment buffer */
  9096. size_t buflen; /* Space available in buf */
  9097. size_t bufused; /* Space taken in buf */
  9098. /* Index block */
  9099. char **var; /* char **envp */
  9100. size_t varlen; /* Number of variables available in var */
  9101. size_t varused; /* Number of variables stored in var */
  9102. };
  9103. static void addenv(struct cgi_environment *env,
  9104. PRINTF_FORMAT_STRING(const char *fmt),
  9105. ...) PRINTF_ARGS(2, 3);
  9106. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9107. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9108. static void
  9109. addenv(struct cgi_environment *env, const char *fmt, ...)
  9110. {
  9111. size_t i, n, space;
  9112. int truncated = 0;
  9113. char *added;
  9114. va_list ap;
  9115. if ((env->varlen - env->varused) < 2) {
  9116. mg_cry_internal(env->conn,
  9117. "%s: Cannot register CGI variable [%s]",
  9118. __func__,
  9119. fmt);
  9120. return;
  9121. }
  9122. /* Calculate how much space is left in the buffer */
  9123. space = (env->buflen - env->bufused);
  9124. do {
  9125. /* Space for "\0\0" is always needed. */
  9126. if (space <= 2) {
  9127. /* Allocate new buffer */
  9128. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9129. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9130. if (!added) {
  9131. /* Out of memory */
  9132. mg_cry_internal(
  9133. env->conn,
  9134. "%s: Cannot allocate memory for CGI variable [%s]",
  9135. __func__,
  9136. fmt);
  9137. return;
  9138. }
  9139. /* Retarget pointers */
  9140. env->buf = added;
  9141. env->buflen = n;
  9142. for (i = 0, n = 0; i < env->varused; i++) {
  9143. env->var[i] = added + n;
  9144. n += strlen(added + n) + 1;
  9145. }
  9146. space = (env->buflen - env->bufused);
  9147. }
  9148. /* Make a pointer to the free space int the buffer */
  9149. added = env->buf + env->bufused;
  9150. /* Copy VARIABLE=VALUE\0 string into the free space */
  9151. va_start(ap, fmt);
  9152. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9153. va_end(ap);
  9154. /* Do not add truncated strings to the environment */
  9155. if (truncated) {
  9156. /* Reallocate the buffer */
  9157. space = 0;
  9158. }
  9159. } while (truncated);
  9160. /* Calculate number of bytes added to the environment */
  9161. n = strlen(added) + 1;
  9162. env->bufused += n;
  9163. /* Append a pointer to the added string into the envp array */
  9164. env->var[env->varused] = added;
  9165. env->varused++;
  9166. }
  9167. /* Return 0 on success, non-zero if an error occurs. */
  9168. static int
  9169. prepare_cgi_environment(struct mg_connection *conn,
  9170. const char *prog,
  9171. struct cgi_environment *env)
  9172. {
  9173. const char *s;
  9174. struct vec var_vec;
  9175. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9176. int i, truncated, uri_len;
  9177. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9178. return -1;
  9179. }
  9180. env->conn = conn;
  9181. env->buflen = CGI_ENVIRONMENT_SIZE;
  9182. env->bufused = 0;
  9183. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9184. if (env->buf == NULL) {
  9185. mg_cry_internal(conn,
  9186. "%s: Not enough memory for environmental buffer",
  9187. __func__);
  9188. return -1;
  9189. }
  9190. env->varlen = MAX_CGI_ENVIR_VARS;
  9191. env->varused = 0;
  9192. env->var =
  9193. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9194. if (env->var == NULL) {
  9195. mg_cry_internal(conn,
  9196. "%s: Not enough memory for environmental variables",
  9197. __func__);
  9198. mg_free(env->buf);
  9199. return -1;
  9200. }
  9201. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9202. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9203. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9204. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9205. /* Prepare the environment block */
  9206. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9207. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9208. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9209. #if defined(USE_IPV6)
  9210. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9211. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9212. } else
  9213. #endif
  9214. {
  9215. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9216. }
  9217. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9218. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9219. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9220. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9221. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9222. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9223. /* SCRIPT_NAME */
  9224. uri_len = (int)strlen(conn->request_info.local_uri);
  9225. if (conn->path_info == NULL) {
  9226. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9227. /* URI: /path_to_script/script.cgi */
  9228. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9229. } else {
  9230. /* URI: /path_to_script/ ... using index.cgi */
  9231. const char *index_file = strrchr(prog, '/');
  9232. if (index_file) {
  9233. addenv(env,
  9234. "SCRIPT_NAME=%s%s",
  9235. conn->request_info.local_uri,
  9236. index_file + 1);
  9237. }
  9238. }
  9239. } else {
  9240. /* URI: /path_to_script/script.cgi/path_info */
  9241. addenv(env,
  9242. "SCRIPT_NAME=%.*s",
  9243. uri_len - (int)strlen(conn->path_info),
  9244. conn->request_info.local_uri);
  9245. }
  9246. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9247. if (conn->path_info == NULL) {
  9248. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9249. } else {
  9250. addenv(env,
  9251. "PATH_TRANSLATED=%s%s",
  9252. conn->dom_ctx->config[DOCUMENT_ROOT],
  9253. conn->path_info);
  9254. }
  9255. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9256. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9257. addenv(env, "CONTENT_TYPE=%s", s);
  9258. }
  9259. if (conn->request_info.query_string != NULL) {
  9260. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9261. }
  9262. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9263. addenv(env, "CONTENT_LENGTH=%s", s);
  9264. }
  9265. if ((s = getenv("PATH")) != NULL) {
  9266. addenv(env, "PATH=%s", s);
  9267. }
  9268. if (conn->path_info != NULL) {
  9269. addenv(env, "PATH_INFO=%s", conn->path_info);
  9270. }
  9271. if (conn->status_code > 0) {
  9272. /* CGI error handler should show the status code */
  9273. addenv(env, "STATUS=%d", conn->status_code);
  9274. }
  9275. #if defined(_WIN32)
  9276. if ((s = getenv("COMSPEC")) != NULL) {
  9277. addenv(env, "COMSPEC=%s", s);
  9278. }
  9279. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9280. addenv(env, "SYSTEMROOT=%s", s);
  9281. }
  9282. if ((s = getenv("SystemDrive")) != NULL) {
  9283. addenv(env, "SystemDrive=%s", s);
  9284. }
  9285. if ((s = getenv("ProgramFiles")) != NULL) {
  9286. addenv(env, "ProgramFiles=%s", s);
  9287. }
  9288. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9289. addenv(env, "ProgramFiles(x86)=%s", s);
  9290. }
  9291. #else
  9292. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9293. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9294. }
  9295. #endif /* _WIN32 */
  9296. if ((s = getenv("PERLLIB")) != NULL) {
  9297. addenv(env, "PERLLIB=%s", s);
  9298. }
  9299. if (conn->request_info.remote_user != NULL) {
  9300. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9301. addenv(env, "%s", "AUTH_TYPE=Digest");
  9302. }
  9303. /* Add all headers as HTTP_* variables */
  9304. for (i = 0; i < conn->request_info.num_headers; i++) {
  9305. (void)mg_snprintf(conn,
  9306. &truncated,
  9307. http_var_name,
  9308. sizeof(http_var_name),
  9309. "HTTP_%s",
  9310. conn->request_info.http_headers[i].name);
  9311. if (truncated) {
  9312. mg_cry_internal(conn,
  9313. "%s: HTTP header variable too long [%s]",
  9314. __func__,
  9315. conn->request_info.http_headers[i].name);
  9316. continue;
  9317. }
  9318. /* Convert variable name into uppercase, and change - to _ */
  9319. for (p = http_var_name; *p != '\0'; p++) {
  9320. if (*p == '-') {
  9321. *p = '_';
  9322. }
  9323. *p = (char)toupper((unsigned char)*p);
  9324. }
  9325. addenv(env,
  9326. "%s=%s",
  9327. http_var_name,
  9328. conn->request_info.http_headers[i].value);
  9329. }
  9330. /* Add user-specified variables */
  9331. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9332. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9333. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9334. }
  9335. env->var[env->varused] = NULL;
  9336. env->buf[env->bufused] = '\0';
  9337. return 0;
  9338. }
  9339. /* Data for CGI process control: PID and number of references */
  9340. struct process_control_data {
  9341. pid_t pid;
  9342. int references;
  9343. };
  9344. static int
  9345. abort_process(void *data)
  9346. {
  9347. /* Waitpid checks for child status and won't work for a pid that does not
  9348. * identify a child of the current process. Thus, if the pid is reused,
  9349. * we will not affect a different process. */
  9350. struct process_control_data *proc = (struct process_control_data *)data;
  9351. int status = 0;
  9352. int refs;
  9353. pid_t ret_pid;
  9354. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9355. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9356. /* Stop child process */
  9357. DEBUG_TRACE("CGI timer: Stop child process %p\n", proc->pid);
  9358. kill(proc->pid, SIGABRT);
  9359. /* Wait until process is terminated (don't leave zombies) */
  9360. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9361. ;
  9362. } else {
  9363. DEBUG_TRACE("CGI timer: Child process %p already stopped\n", proc->pid);
  9364. }
  9365. /* Dec reference counter */
  9366. refs = mg_atomic_dec(&proc->references);
  9367. if (refs == 0) {
  9368. /* no more references - free data */
  9369. mg_free(data);
  9370. }
  9371. return 0;
  9372. }
  9373. /* Local (static) function assumes all arguments are valid. */
  9374. static void
  9375. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9376. {
  9377. char *buf;
  9378. size_t buflen;
  9379. int headers_len, data_len, i, truncated;
  9380. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9381. const char *status, *status_text, *connection_state;
  9382. char *pbuf, dir[PATH_MAX], *p;
  9383. struct mg_request_info ri;
  9384. struct cgi_environment blk;
  9385. FILE *in = NULL, *out = NULL, *err = NULL;
  9386. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9387. pid_t pid = (pid_t)-1;
  9388. struct process_control_data *proc = NULL;
  9389. #if defined(USE_TIMERS)
  9390. double cgi_timeout = -1.0;
  9391. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9392. /* Get timeout in seconds */
  9393. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9394. }
  9395. #endif
  9396. buf = NULL;
  9397. buflen = conn->phys_ctx->max_request_size;
  9398. i = prepare_cgi_environment(conn, prog, &blk);
  9399. if (i != 0) {
  9400. blk.buf = NULL;
  9401. blk.var = NULL;
  9402. goto done;
  9403. }
  9404. /* CGI must be executed in its own directory. 'dir' must point to the
  9405. * directory containing executable program, 'p' must point to the
  9406. * executable program name relative to 'dir'. */
  9407. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9408. if (truncated) {
  9409. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9410. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9411. goto done;
  9412. }
  9413. if ((p = strrchr(dir, '/')) != NULL) {
  9414. *p++ = '\0';
  9415. } else {
  9416. dir[0] = '.';
  9417. dir[1] = '\0';
  9418. p = (char *)prog;
  9419. }
  9420. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9421. status = strerror(ERRNO);
  9422. mg_cry_internal(
  9423. conn,
  9424. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9425. prog,
  9426. status);
  9427. mg_send_http_error(conn,
  9428. 500,
  9429. "Error: Cannot create CGI pipe: %s",
  9430. status);
  9431. goto done;
  9432. }
  9433. proc = (struct process_control_data *)
  9434. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9435. if (proc == NULL) {
  9436. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9437. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9438. goto done;
  9439. }
  9440. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9441. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9442. if (pid == (pid_t)-1) {
  9443. status = strerror(ERRNO);
  9444. mg_cry_internal(
  9445. conn,
  9446. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9447. prog,
  9448. status);
  9449. mg_send_http_error(conn,
  9450. 500,
  9451. "Error: Cannot spawn CGI process [%s]: %s",
  9452. prog,
  9453. status);
  9454. mg_free(proc);
  9455. proc = NULL;
  9456. goto done;
  9457. }
  9458. /* Store data in shared process_control_data */
  9459. proc->pid = pid;
  9460. proc->references = 1;
  9461. #if defined(USE_TIMERS)
  9462. if (cgi_timeout > 0.0) {
  9463. proc->references = 2;
  9464. // Start a timer for CGI
  9465. timer_add(conn->phys_ctx,
  9466. cgi_timeout /* in seconds */,
  9467. 0.0,
  9468. 1,
  9469. abort_process,
  9470. (void *)proc);
  9471. }
  9472. #endif
  9473. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  9474. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  9475. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  9476. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  9477. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  9478. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  9479. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  9480. /* Parent closes only one side of the pipes.
  9481. * If we don't mark them as closed, close() attempt before
  9482. * return from this function throws an exception on Windows.
  9483. * Windows does not like when closed descriptor is closed again. */
  9484. (void)close(fdin[0]);
  9485. (void)close(fdout[1]);
  9486. (void)close(fderr[1]);
  9487. fdin[0] = fdout[1] = fderr[1] = -1;
  9488. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  9489. status = strerror(ERRNO);
  9490. mg_cry_internal(conn,
  9491. "Error: CGI program \"%s\": Can not open stdin: %s",
  9492. prog,
  9493. status);
  9494. mg_send_http_error(conn,
  9495. 500,
  9496. "Error: CGI can not open fdin\nfopen: %s",
  9497. status);
  9498. goto done;
  9499. }
  9500. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  9501. status = strerror(ERRNO);
  9502. mg_cry_internal(conn,
  9503. "Error: CGI program \"%s\": Can not open stdout: %s",
  9504. prog,
  9505. status);
  9506. mg_send_http_error(conn,
  9507. 500,
  9508. "Error: CGI can not open fdout\nfopen: %s",
  9509. status);
  9510. goto done;
  9511. }
  9512. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  9513. status = strerror(ERRNO);
  9514. mg_cry_internal(conn,
  9515. "Error: CGI program \"%s\": Can not open stderr: %s",
  9516. prog,
  9517. status);
  9518. mg_send_http_error(conn,
  9519. 500,
  9520. "Error: CGI can not open fderr\nfopen: %s",
  9521. status);
  9522. goto done;
  9523. }
  9524. setbuf(in, NULL);
  9525. setbuf(out, NULL);
  9526. setbuf(err, NULL);
  9527. fout.access.fp = out;
  9528. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9529. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9530. conn->content_len);
  9531. /* This is a POST/PUT request, or another request with body data. */
  9532. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9533. /* Error sending the body data */
  9534. mg_cry_internal(
  9535. conn,
  9536. "Error: CGI program \"%s\": Forward body data failed",
  9537. prog);
  9538. goto done;
  9539. }
  9540. }
  9541. /* Close so child gets an EOF. */
  9542. fclose(in);
  9543. in = NULL;
  9544. fdin[1] = -1;
  9545. /* Now read CGI reply into a buffer. We need to set correct
  9546. * status code, thus we need to see all HTTP headers first.
  9547. * Do not send anything back to client, until we buffer in all
  9548. * HTTP headers. */
  9549. data_len = 0;
  9550. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9551. if (buf == NULL) {
  9552. mg_send_http_error(conn,
  9553. 500,
  9554. "Error: Not enough memory for CGI buffer (%u bytes)",
  9555. (unsigned int)buflen);
  9556. mg_cry_internal(
  9557. conn,
  9558. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9559. "bytes)",
  9560. prog,
  9561. (unsigned int)buflen);
  9562. goto done;
  9563. }
  9564. DEBUG_TRACE("CGI: %s", "wait for response");
  9565. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9566. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9567. if (headers_len <= 0) {
  9568. /* Could not parse the CGI response. Check if some error message on
  9569. * stderr. */
  9570. i = pull_all(err, conn, buf, (int)buflen);
  9571. if (i > 0) {
  9572. /* CGI program explicitly sent an error */
  9573. /* Write the error message to the internal log */
  9574. mg_cry_internal(conn,
  9575. "Error: CGI program \"%s\" sent error "
  9576. "message: [%.*s]",
  9577. prog,
  9578. i,
  9579. buf);
  9580. /* Don't send the error message back to the client */
  9581. mg_send_http_error(conn,
  9582. 500,
  9583. "Error: CGI program \"%s\" failed.",
  9584. prog);
  9585. } else {
  9586. /* CGI program did not explicitly send an error, but a broken
  9587. * respon header */
  9588. mg_cry_internal(conn,
  9589. "Error: CGI program sent malformed or too big "
  9590. "(>%u bytes) HTTP headers: [%.*s]",
  9591. (unsigned)buflen,
  9592. data_len,
  9593. buf);
  9594. mg_send_http_error(conn,
  9595. 500,
  9596. "Error: CGI program sent malformed or too big "
  9597. "(>%u bytes) HTTP headers: [%.*s]",
  9598. (unsigned)buflen,
  9599. data_len,
  9600. buf);
  9601. }
  9602. /* in both cases, abort processing CGI */
  9603. goto done;
  9604. }
  9605. pbuf = buf;
  9606. buf[headers_len - 1] = '\0';
  9607. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9608. /* Make up and send the status line */
  9609. status_text = "OK";
  9610. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9611. != NULL) {
  9612. conn->status_code = atoi(status);
  9613. status_text = status;
  9614. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9615. status_text++;
  9616. }
  9617. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9618. != NULL) {
  9619. conn->status_code = 307;
  9620. } else {
  9621. conn->status_code = 200;
  9622. }
  9623. connection_state =
  9624. get_header(ri.http_headers, ri.num_headers, "Connection");
  9625. if (!header_has_option(connection_state, "keep-alive")) {
  9626. conn->must_close = 1;
  9627. }
  9628. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9629. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9630. /* Send headers */
  9631. for (i = 0; i < ri.num_headers; i++) {
  9632. mg_printf(conn,
  9633. "%s: %s\r\n",
  9634. ri.http_headers[i].name,
  9635. ri.http_headers[i].value);
  9636. }
  9637. mg_write(conn, "\r\n", 2);
  9638. /* Send chunk of data that may have been read after the headers */
  9639. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9640. /* Read the rest of CGI output and send to the client */
  9641. DEBUG_TRACE("CGI: %s", "forward all data");
  9642. send_file_data(conn, &fout, 0, INT64_MAX);
  9643. DEBUG_TRACE("CGI: %s", "all data sent");
  9644. done:
  9645. mg_free(blk.var);
  9646. mg_free(blk.buf);
  9647. if (pid != (pid_t)-1) {
  9648. abort_process((void *)proc);
  9649. }
  9650. if (fdin[0] != -1) {
  9651. close(fdin[0]);
  9652. }
  9653. if (fdout[1] != -1) {
  9654. close(fdout[1]);
  9655. }
  9656. if (in != NULL) {
  9657. fclose(in);
  9658. } else if (fdin[1] != -1) {
  9659. close(fdin[1]);
  9660. }
  9661. if (out != NULL) {
  9662. fclose(out);
  9663. } else if (fdout[0] != -1) {
  9664. close(fdout[0]);
  9665. }
  9666. if (err != NULL) {
  9667. fclose(err);
  9668. } else if (fderr[0] != -1) {
  9669. close(fderr[0]);
  9670. }
  9671. mg_free(buf);
  9672. }
  9673. #endif /* !NO_CGI */
  9674. #if !defined(NO_FILES)
  9675. static void
  9676. mkcol(struct mg_connection *conn, const char *path)
  9677. {
  9678. int rc, body_len;
  9679. struct de de;
  9680. char date[64];
  9681. time_t curtime = time(NULL);
  9682. if (conn == NULL) {
  9683. return;
  9684. }
  9685. /* TODO (mid): Check the mg_send_http_error situations in this function
  9686. */
  9687. memset(&de.file, 0, sizeof(de.file));
  9688. if (!mg_stat(conn, path, &de.file)) {
  9689. mg_cry_internal(conn,
  9690. "%s: mg_stat(%s) failed: %s",
  9691. __func__,
  9692. path,
  9693. strerror(ERRNO));
  9694. }
  9695. if (de.file.last_modified) {
  9696. /* TODO (mid): This check does not seem to make any sense ! */
  9697. /* TODO (mid): Add a webdav unit test first, before changing
  9698. * anything here. */
  9699. mg_send_http_error(
  9700. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9701. return;
  9702. }
  9703. body_len = conn->data_len - conn->request_len;
  9704. if (body_len > 0) {
  9705. mg_send_http_error(
  9706. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9707. return;
  9708. }
  9709. rc = mg_mkdir(conn, path, 0755);
  9710. if (rc == 0) {
  9711. conn->status_code = 201;
  9712. gmt_time_string(date, sizeof(date), &curtime);
  9713. mg_printf(conn,
  9714. "HTTP/1.1 %d Created\r\n"
  9715. "Date: %s\r\n",
  9716. conn->status_code,
  9717. date);
  9718. send_static_cache_header(conn);
  9719. send_additional_header(conn);
  9720. mg_printf(conn,
  9721. "Content-Length: 0\r\n"
  9722. "Connection: %s\r\n\r\n",
  9723. suggest_connection_header(conn));
  9724. } else {
  9725. if (errno == EEXIST) {
  9726. mg_send_http_error(
  9727. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9728. } else if (errno == EACCES) {
  9729. mg_send_http_error(
  9730. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9731. } else if (errno == ENOENT) {
  9732. mg_send_http_error(
  9733. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9734. } else {
  9735. mg_send_http_error(
  9736. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9737. }
  9738. }
  9739. }
  9740. static void
  9741. put_file(struct mg_connection *conn, const char *path)
  9742. {
  9743. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9744. const char *range;
  9745. int64_t r1, r2;
  9746. int rc;
  9747. char date[64];
  9748. time_t curtime = time(NULL);
  9749. if (conn == NULL) {
  9750. return;
  9751. }
  9752. if (mg_stat(conn, path, &file.stat)) {
  9753. /* File already exists */
  9754. conn->status_code = 200;
  9755. if (file.stat.is_directory) {
  9756. /* This is an already existing directory,
  9757. * so there is nothing to do for the server. */
  9758. rc = 0;
  9759. } else {
  9760. /* File exists and is not a directory. */
  9761. /* Can it be replaced? */
  9762. #if defined(MG_USE_OPEN_FILE)
  9763. if (file.access.membuf != NULL) {
  9764. /* This is an "in-memory" file, that can not be replaced */
  9765. mg_send_http_error(conn,
  9766. 405,
  9767. "Error: Put not possible\nReplacing %s "
  9768. "is not supported",
  9769. path);
  9770. return;
  9771. }
  9772. #endif
  9773. /* Check if the server may write this file */
  9774. if (access(path, W_OK) == 0) {
  9775. /* Access granted */
  9776. conn->status_code = 200;
  9777. rc = 1;
  9778. } else {
  9779. mg_send_http_error(
  9780. conn,
  9781. 403,
  9782. "Error: Put not possible\nReplacing %s is not allowed",
  9783. path);
  9784. return;
  9785. }
  9786. }
  9787. } else {
  9788. /* File should be created */
  9789. conn->status_code = 201;
  9790. rc = put_dir(conn, path);
  9791. }
  9792. if (rc == 0) {
  9793. /* put_dir returns 0 if path is a directory */
  9794. gmt_time_string(date, sizeof(date), &curtime);
  9795. mg_printf(conn,
  9796. "HTTP/1.1 %d %s\r\n",
  9797. conn->status_code,
  9798. mg_get_response_code_text(NULL, conn->status_code));
  9799. send_no_cache_header(conn);
  9800. send_additional_header(conn);
  9801. mg_printf(conn,
  9802. "Date: %s\r\n"
  9803. "Content-Length: 0\r\n"
  9804. "Connection: %s\r\n\r\n",
  9805. date,
  9806. suggest_connection_header(conn));
  9807. /* Request to create a directory has been fulfilled successfully.
  9808. * No need to put a file. */
  9809. return;
  9810. }
  9811. if (rc == -1) {
  9812. /* put_dir returns -1 if the path is too long */
  9813. mg_send_http_error(conn,
  9814. 414,
  9815. "Error: Path too long\nput_dir(%s): %s",
  9816. path,
  9817. strerror(ERRNO));
  9818. return;
  9819. }
  9820. if (rc == -2) {
  9821. /* put_dir returns -2 if the directory can not be created */
  9822. mg_send_http_error(conn,
  9823. 500,
  9824. "Error: Can not create directory\nput_dir(%s): %s",
  9825. path,
  9826. strerror(ERRNO));
  9827. return;
  9828. }
  9829. /* A file should be created or overwritten. */
  9830. /* Currently CivetWeb does not nead read+write access. */
  9831. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9832. || file.access.fp == NULL) {
  9833. (void)mg_fclose(&file.access);
  9834. mg_send_http_error(conn,
  9835. 500,
  9836. "Error: Can not create file\nfopen(%s): %s",
  9837. path,
  9838. strerror(ERRNO));
  9839. return;
  9840. }
  9841. fclose_on_exec(&file.access, conn);
  9842. range = mg_get_header(conn, "Content-Range");
  9843. r1 = r2 = 0;
  9844. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9845. conn->status_code = 206; /* Partial content */
  9846. fseeko(file.access.fp, r1, SEEK_SET);
  9847. }
  9848. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9849. /* forward_body_data failed.
  9850. * The error code has already been sent to the client,
  9851. * and conn->status_code is already set. */
  9852. (void)mg_fclose(&file.access);
  9853. return;
  9854. }
  9855. if (mg_fclose(&file.access) != 0) {
  9856. /* fclose failed. This might have different reasons, but a likely
  9857. * one is "no space on disk", http 507. */
  9858. conn->status_code = 507;
  9859. }
  9860. gmt_time_string(date, sizeof(date), &curtime);
  9861. mg_printf(conn,
  9862. "HTTP/1.1 %d %s\r\n",
  9863. conn->status_code,
  9864. mg_get_response_code_text(NULL, conn->status_code));
  9865. send_no_cache_header(conn);
  9866. send_additional_header(conn);
  9867. mg_printf(conn,
  9868. "Date: %s\r\n"
  9869. "Content-Length: 0\r\n"
  9870. "Connection: %s\r\n\r\n",
  9871. date,
  9872. suggest_connection_header(conn));
  9873. }
  9874. static void
  9875. delete_file(struct mg_connection *conn, const char *path)
  9876. {
  9877. struct de de;
  9878. memset(&de.file, 0, sizeof(de.file));
  9879. if (!mg_stat(conn, path, &de.file)) {
  9880. /* mg_stat returns 0 if the file does not exist */
  9881. mg_send_http_error(conn,
  9882. 404,
  9883. "Error: Cannot delete file\nFile %s not found",
  9884. path);
  9885. return;
  9886. }
  9887. #if 0 /* Ignore if a file in memory is inside a folder */
  9888. if (de.access.membuf != NULL) {
  9889. /* the file is cached in memory */
  9890. mg_send_http_error(
  9891. conn,
  9892. 405,
  9893. "Error: Delete not possible\nDeleting %s is not supported",
  9894. path);
  9895. return;
  9896. }
  9897. #endif
  9898. if (de.file.is_directory) {
  9899. if (remove_directory(conn, path)) {
  9900. /* Delete is successful: Return 204 without content. */
  9901. mg_send_http_error(conn, 204, "%s", "");
  9902. } else {
  9903. /* Delete is not successful: Return 500 (Server error). */
  9904. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9905. }
  9906. return;
  9907. }
  9908. /* This is an existing file (not a directory).
  9909. * Check if write permission is granted. */
  9910. if (access(path, W_OK) != 0) {
  9911. /* File is read only */
  9912. mg_send_http_error(
  9913. conn,
  9914. 403,
  9915. "Error: Delete not possible\nDeleting %s is not allowed",
  9916. path);
  9917. return;
  9918. }
  9919. /* Try to delete it. */
  9920. if (mg_remove(conn, path) == 0) {
  9921. /* Delete was successful: Return 204 without content. */
  9922. mg_send_http_error(conn, 204, "%s", "");
  9923. } else {
  9924. /* Delete not successful (file locked). */
  9925. mg_send_http_error(conn,
  9926. 423,
  9927. "Error: Cannot delete file\nremove(%s): %s",
  9928. path,
  9929. strerror(ERRNO));
  9930. }
  9931. }
  9932. #endif /* !NO_FILES */
  9933. static void
  9934. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9935. static void
  9936. do_ssi_include(struct mg_connection *conn,
  9937. const char *ssi,
  9938. char *tag,
  9939. int include_level)
  9940. {
  9941. char file_name[MG_BUF_LEN], path[512], *p;
  9942. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9943. size_t len;
  9944. int truncated = 0;
  9945. if (conn == NULL) {
  9946. return;
  9947. }
  9948. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9949. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9950. * always < MG_BUF_LEN. */
  9951. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9952. /* File name is relative to the webserver root */
  9953. file_name[511] = 0;
  9954. (void)mg_snprintf(conn,
  9955. &truncated,
  9956. path,
  9957. sizeof(path),
  9958. "%s/%s",
  9959. conn->dom_ctx->config[DOCUMENT_ROOT],
  9960. file_name);
  9961. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9962. /* File name is relative to the webserver working directory
  9963. * or it is absolute system path */
  9964. file_name[511] = 0;
  9965. (void)
  9966. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9967. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9968. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9969. /* File name is relative to the currect document */
  9970. file_name[511] = 0;
  9971. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9972. if (!truncated) {
  9973. if ((p = strrchr(path, '/')) != NULL) {
  9974. p[1] = '\0';
  9975. }
  9976. len = strlen(path);
  9977. (void)mg_snprintf(conn,
  9978. &truncated,
  9979. path + len,
  9980. sizeof(path) - len,
  9981. "%s",
  9982. file_name);
  9983. }
  9984. } else {
  9985. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9986. return;
  9987. }
  9988. if (truncated) {
  9989. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9990. return;
  9991. }
  9992. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9993. mg_cry_internal(conn,
  9994. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9995. tag,
  9996. path,
  9997. strerror(ERRNO));
  9998. } else {
  9999. fclose_on_exec(&file.access, conn);
  10000. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10001. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10002. path)
  10003. > 0) {
  10004. send_ssi_file(conn, path, &file, include_level + 1);
  10005. } else {
  10006. send_file_data(conn, &file, 0, INT64_MAX);
  10007. }
  10008. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10009. }
  10010. }
  10011. #if !defined(NO_POPEN)
  10012. static void
  10013. do_ssi_exec(struct mg_connection *conn, char *tag)
  10014. {
  10015. char cmd[1024] = "";
  10016. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10017. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10018. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10019. } else {
  10020. cmd[1023] = 0;
  10021. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10022. mg_cry_internal(conn,
  10023. "Cannot SSI #exec: [%s]: %s",
  10024. cmd,
  10025. strerror(ERRNO));
  10026. } else {
  10027. send_file_data(conn, &file, 0, INT64_MAX);
  10028. pclose(file.access.fp);
  10029. }
  10030. }
  10031. }
  10032. #endif /* !NO_POPEN */
  10033. static int
  10034. mg_fgetc(struct mg_file *filep, int offset)
  10035. {
  10036. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10037. if (filep == NULL) {
  10038. return EOF;
  10039. }
  10040. #if defined(MG_USE_OPEN_FILE)
  10041. if ((filep->access.membuf != NULL) && (offset >= 0)
  10042. && (((unsigned int)(offset)) < filep->stat.size)) {
  10043. return ((const unsigned char *)filep->access.membuf)[offset];
  10044. } else /* else block below */
  10045. #endif
  10046. if (filep->access.fp != NULL) {
  10047. return fgetc(filep->access.fp);
  10048. } else {
  10049. return EOF;
  10050. }
  10051. }
  10052. static void
  10053. send_ssi_file(struct mg_connection *conn,
  10054. const char *path,
  10055. struct mg_file *filep,
  10056. int include_level)
  10057. {
  10058. char buf[MG_BUF_LEN];
  10059. int ch, offset, len, in_tag, in_ssi_tag;
  10060. if (include_level > 10) {
  10061. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10062. return;
  10063. }
  10064. in_tag = in_ssi_tag = len = offset = 0;
  10065. /* Read file, byte by byte, and look for SSI include tags */
  10066. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10067. if (in_tag) {
  10068. /* We are in a tag, either SSI tag or html tag */
  10069. if (ch == '>') {
  10070. /* Tag is closing */
  10071. buf[len++] = '>';
  10072. if (in_ssi_tag) {
  10073. /* Handle SSI tag */
  10074. buf[len] = 0;
  10075. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10076. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10077. #if !defined(NO_POPEN)
  10078. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10079. do_ssi_exec(conn, buf + 9);
  10080. #endif /* !NO_POPEN */
  10081. } else {
  10082. mg_cry_internal(conn,
  10083. "%s: unknown SSI "
  10084. "command: \"%s\"",
  10085. path,
  10086. buf);
  10087. }
  10088. len = 0;
  10089. in_ssi_tag = in_tag = 0;
  10090. } else {
  10091. /* Not an SSI tag */
  10092. /* Flush buffer */
  10093. (void)mg_write(conn, buf, (size_t)len);
  10094. len = 0;
  10095. in_tag = 0;
  10096. }
  10097. } else {
  10098. /* Tag is still open */
  10099. buf[len++] = (char)(ch & 0xff);
  10100. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10101. /* All SSI tags start with <!--# */
  10102. in_ssi_tag = 1;
  10103. }
  10104. if ((len + 2) > (int)sizeof(buf)) {
  10105. /* Tag to long for buffer */
  10106. mg_cry_internal(conn, "%s: tag is too large", path);
  10107. return;
  10108. }
  10109. }
  10110. } else {
  10111. /* We are not in a tag yet. */
  10112. if (ch == '<') {
  10113. /* Tag is opening */
  10114. in_tag = 1;
  10115. if (len > 0) {
  10116. /* Flush current buffer.
  10117. * Buffer is filled with "len" bytes. */
  10118. (void)mg_write(conn, buf, (size_t)len);
  10119. }
  10120. /* Store the < */
  10121. len = 1;
  10122. buf[0] = '<';
  10123. } else {
  10124. /* No Tag */
  10125. /* Add data to buffer */
  10126. buf[len++] = (char)(ch & 0xff);
  10127. /* Flush if buffer is full */
  10128. if (len == (int)sizeof(buf)) {
  10129. mg_write(conn, buf, (size_t)len);
  10130. len = 0;
  10131. }
  10132. }
  10133. }
  10134. }
  10135. /* Send the rest of buffered data */
  10136. if (len > 0) {
  10137. mg_write(conn, buf, (size_t)len);
  10138. }
  10139. }
  10140. static void
  10141. handle_ssi_file_request(struct mg_connection *conn,
  10142. const char *path,
  10143. struct mg_file *filep)
  10144. {
  10145. char date[64];
  10146. time_t curtime = time(NULL);
  10147. const char *cors_orig_cfg;
  10148. const char *cors1, *cors2, *cors3;
  10149. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10150. return;
  10151. }
  10152. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10153. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10154. /* Cross-origin resource sharing (CORS). */
  10155. cors1 = "Access-Control-Allow-Origin: ";
  10156. cors2 = cors_orig_cfg;
  10157. cors3 = "\r\n";
  10158. } else {
  10159. cors1 = cors2 = cors3 = "";
  10160. }
  10161. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10162. /* File exists (precondition for calling this function),
  10163. * but can not be opened by the server. */
  10164. mg_send_http_error(conn,
  10165. 500,
  10166. "Error: Cannot read file\nfopen(%s): %s",
  10167. path,
  10168. strerror(ERRNO));
  10169. } else {
  10170. conn->must_close = 1;
  10171. gmt_time_string(date, sizeof(date), &curtime);
  10172. fclose_on_exec(&filep->access, conn);
  10173. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10174. send_no_cache_header(conn);
  10175. send_additional_header(conn);
  10176. mg_printf(conn,
  10177. "%s%s%s"
  10178. "Date: %s\r\n"
  10179. "Content-Type: text/html\r\n"
  10180. "Connection: %s\r\n\r\n",
  10181. cors1,
  10182. cors2,
  10183. cors3,
  10184. date,
  10185. suggest_connection_header(conn));
  10186. send_ssi_file(conn, path, filep, 0);
  10187. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10188. }
  10189. }
  10190. #if !defined(NO_FILES)
  10191. static void
  10192. send_options(struct mg_connection *conn)
  10193. {
  10194. char date[64];
  10195. time_t curtime = time(NULL);
  10196. if (!conn) {
  10197. return;
  10198. }
  10199. conn->status_code = 200;
  10200. conn->must_close = 1;
  10201. gmt_time_string(date, sizeof(date), &curtime);
  10202. /* We do not set a "Cache-Control" header here, but leave the default.
  10203. * Since browsers do not send an OPTIONS request, we can not test the
  10204. * effect anyway. */
  10205. mg_printf(conn,
  10206. "HTTP/1.1 200 OK\r\n"
  10207. "Date: %s\r\n"
  10208. "Connection: %s\r\n"
  10209. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10210. "PROPFIND, MKCOL\r\n"
  10211. "DAV: 1\r\n",
  10212. date,
  10213. suggest_connection_header(conn));
  10214. send_additional_header(conn);
  10215. mg_printf(conn, "\r\n");
  10216. }
  10217. /* Writes PROPFIND properties for a collection element */
  10218. static int
  10219. print_props(struct mg_connection *conn,
  10220. const char *uri,
  10221. const char *name,
  10222. struct mg_file_stat *filep)
  10223. {
  10224. size_t href_size, i, j;
  10225. int len;
  10226. char *href, mtime[64];
  10227. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10228. return 0;
  10229. }
  10230. /* Estimate worst case size for encoding */
  10231. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10232. href = (char *)mg_malloc(href_size);
  10233. if (href == NULL) {
  10234. return 0;
  10235. }
  10236. len = mg_url_encode(uri, href, href_size);
  10237. if (len >= 0) {
  10238. /* Append an extra string */
  10239. mg_url_encode(name, href + len, href_size - (size_t)len);
  10240. }
  10241. /* Directory separator should be preserved. */
  10242. for (i = j = 0; href[i]; j++) {
  10243. if (!strncmp(href + i, "%2f", 3)) {
  10244. href[j] = '/';
  10245. i += 3;
  10246. } else {
  10247. href[j] = href[i++];
  10248. }
  10249. }
  10250. href[j] = '\0';
  10251. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10252. mg_printf(conn,
  10253. "<d:response>"
  10254. "<d:href>%s</d:href>"
  10255. "<d:propstat>"
  10256. "<d:prop>"
  10257. "<d:resourcetype>%s</d:resourcetype>"
  10258. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10259. "<d:getlastmodified>%s</d:getlastmodified>"
  10260. "</d:prop>"
  10261. "<d:status>HTTP/1.1 200 OK</d:status>"
  10262. "</d:propstat>"
  10263. "</d:response>\n",
  10264. href,
  10265. filep->is_directory ? "<d:collection/>" : "",
  10266. filep->size,
  10267. mtime);
  10268. mg_free(href);
  10269. return 1;
  10270. }
  10271. static int
  10272. print_dav_dir_entry(struct de *de, void *data)
  10273. {
  10274. struct mg_connection *conn = (struct mg_connection *)data;
  10275. if (!de || !conn
  10276. || !print_props(
  10277. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10278. return -1;
  10279. }
  10280. return 0;
  10281. }
  10282. static void
  10283. handle_propfind(struct mg_connection *conn,
  10284. const char *path,
  10285. struct mg_file_stat *filep)
  10286. {
  10287. const char *depth = mg_get_header(conn, "Depth");
  10288. char date[64];
  10289. time_t curtime = time(NULL);
  10290. gmt_time_string(date, sizeof(date), &curtime);
  10291. if (!conn || !path || !filep || !conn->dom_ctx) {
  10292. return;
  10293. }
  10294. conn->must_close = 1;
  10295. conn->status_code = 207;
  10296. mg_printf(conn,
  10297. "HTTP/1.1 207 Multi-Status\r\n"
  10298. "Date: %s\r\n",
  10299. date);
  10300. send_static_cache_header(conn);
  10301. send_additional_header(conn);
  10302. mg_printf(conn,
  10303. "Connection: %s\r\n"
  10304. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10305. suggest_connection_header(conn));
  10306. mg_printf(conn,
  10307. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10308. "<d:multistatus xmlns:d='DAV:'>\n");
  10309. /* Print properties for the requested resource itself */
  10310. print_props(conn, conn->request_info.local_uri, "", filep);
  10311. /* If it is a directory, print directory entries too if Depth is not 0
  10312. */
  10313. if (filep->is_directory
  10314. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10315. "yes")
  10316. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10317. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10318. }
  10319. mg_printf(conn, "%s\n", "</d:multistatus>");
  10320. }
  10321. #endif
  10322. void
  10323. mg_lock_connection(struct mg_connection *conn)
  10324. {
  10325. if (conn) {
  10326. (void)pthread_mutex_lock(&conn->mutex);
  10327. }
  10328. }
  10329. void
  10330. mg_unlock_connection(struct mg_connection *conn)
  10331. {
  10332. if (conn) {
  10333. (void)pthread_mutex_unlock(&conn->mutex);
  10334. }
  10335. }
  10336. void
  10337. mg_lock_context(struct mg_context *ctx)
  10338. {
  10339. if (ctx) {
  10340. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10341. }
  10342. }
  10343. void
  10344. mg_unlock_context(struct mg_context *ctx)
  10345. {
  10346. if (ctx) {
  10347. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10348. }
  10349. }
  10350. #if defined(USE_LUA)
  10351. #include "mod_lua.inl"
  10352. #endif /* USE_LUA */
  10353. #if defined(USE_DUKTAPE)
  10354. #include "mod_duktape.inl"
  10355. #endif /* USE_DUKTAPE */
  10356. #if defined(USE_WEBSOCKET)
  10357. #if !defined(NO_SSL_DL)
  10358. #define SHA_API static
  10359. #include "sha1.inl"
  10360. #endif
  10361. static int
  10362. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10363. {
  10364. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10365. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10366. SHA_CTX sha_ctx;
  10367. int truncated;
  10368. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10369. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10370. if (truncated) {
  10371. conn->must_close = 1;
  10372. return 0;
  10373. }
  10374. DEBUG_TRACE("%s", "Send websocket handshake");
  10375. SHA1_Init(&sha_ctx);
  10376. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10377. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10378. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10379. mg_printf(conn,
  10380. "HTTP/1.1 101 Switching Protocols\r\n"
  10381. "Upgrade: websocket\r\n"
  10382. "Connection: Upgrade\r\n"
  10383. "Sec-WebSocket-Accept: %s\r\n",
  10384. b64_sha);
  10385. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10386. mg_printf(conn,
  10387. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10388. conn->request_info.acceptedWebSocketSubprotocol);
  10389. } else {
  10390. mg_printf(conn, "%s", "\r\n");
  10391. }
  10392. return 1;
  10393. }
  10394. #if !defined(MG_MAX_UNANSWERED_PING)
  10395. /* Configuration of the maximum number of websocket PINGs that might
  10396. * stay unanswered before the connection is considered broken.
  10397. * Note: The name of this define may still change (until it is
  10398. * defined as a compile parameter in a documentation).
  10399. */
  10400. #define MG_MAX_UNANSWERED_PING (5)
  10401. #endif
  10402. static void
  10403. read_websocket(struct mg_connection *conn,
  10404. mg_websocket_data_handler ws_data_handler,
  10405. void *callback_data)
  10406. {
  10407. /* Pointer to the beginning of the portion of the incoming websocket
  10408. * message queue.
  10409. * The original websocket upgrade request is never removed, so the queue
  10410. * begins after it. */
  10411. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10412. int n, error, exit_by_callback;
  10413. int ret;
  10414. /* body_len is the length of the entire queue in bytes
  10415. * len is the length of the current message
  10416. * data_len is the length of the current message's data payload
  10417. * header_len is the length of the current message's header */
  10418. size_t i, len, mask_len = 0, header_len, body_len;
  10419. uint64_t data_len = 0;
  10420. /* "The masking key is a 32-bit value chosen at random by the client."
  10421. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10422. */
  10423. unsigned char mask[4];
  10424. /* data points to the place where the message is stored when passed to
  10425. * the websocket_data callback. This is either mem on the stack, or a
  10426. * dynamically allocated buffer if it is too large. */
  10427. unsigned char mem[4096];
  10428. unsigned char mop; /* mask flag and opcode */
  10429. /* Variables used for connection monitoring */
  10430. double timeout = -1.0;
  10431. int enable_ping_pong = 0;
  10432. int ping_count = 0;
  10433. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10434. enable_ping_pong =
  10435. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10436. "yes");
  10437. }
  10438. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10439. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10440. }
  10441. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10442. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10443. }
  10444. /* Enter data processing loop */
  10445. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10446. conn->request_info.remote_addr,
  10447. conn->request_info.remote_port);
  10448. conn->in_websocket_handling = 1;
  10449. mg_set_thread_name("wsock");
  10450. /* Loop continuously, reading messages from the socket, invoking the
  10451. * callback, and waiting repeatedly until an error occurs. */
  10452. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10453. header_len = 0;
  10454. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10455. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10456. len = buf[1] & 127;
  10457. mask_len = (buf[1] & 128) ? 4 : 0;
  10458. if ((len < 126) && (body_len >= mask_len)) {
  10459. /* inline 7-bit length field */
  10460. data_len = len;
  10461. header_len = 2 + mask_len;
  10462. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10463. /* 16-bit length field */
  10464. header_len = 4 + mask_len;
  10465. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10466. } else if (body_len >= (10 + mask_len)) {
  10467. /* 64-bit length field */
  10468. uint32_t l1, l2;
  10469. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10470. memcpy(&l2, &buf[6], 4);
  10471. header_len = 10 + mask_len;
  10472. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10473. if (data_len > (uint64_t)0x7FFF0000ul) {
  10474. /* no can do */
  10475. mg_cry_internal(
  10476. conn,
  10477. "%s",
  10478. "websocket out of memory; closing connection");
  10479. break;
  10480. }
  10481. }
  10482. }
  10483. if ((header_len > 0) && (body_len >= header_len)) {
  10484. /* Allocate space to hold websocket payload */
  10485. unsigned char *data = mem;
  10486. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10487. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10488. conn->phys_ctx);
  10489. if (data == NULL) {
  10490. /* Allocation failed, exit the loop and then close the
  10491. * connection */
  10492. mg_cry_internal(
  10493. conn,
  10494. "%s",
  10495. "websocket out of memory; closing connection");
  10496. break;
  10497. }
  10498. }
  10499. /* Copy the mask before we shift the queue and destroy it */
  10500. if (mask_len > 0) {
  10501. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10502. } else {
  10503. memset(mask, 0, sizeof(mask));
  10504. }
  10505. /* Read frame payload from the first message in the queue into
  10506. * data and advance the queue by moving the memory in place. */
  10507. DEBUG_ASSERT(body_len >= header_len);
  10508. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10509. mop = buf[0]; /* current mask and opcode */
  10510. /* Overflow case */
  10511. len = body_len - header_len;
  10512. memcpy(data, buf + header_len, len);
  10513. error = 0;
  10514. while ((uint64_t)len < data_len) {
  10515. n = pull_inner(NULL,
  10516. conn,
  10517. (char *)(data + len),
  10518. (int)(data_len - len),
  10519. timeout);
  10520. if (n <= -2) {
  10521. error = 1;
  10522. break;
  10523. } else if (n > 0) {
  10524. len += (size_t)n;
  10525. } else {
  10526. /* Timeout: should retry */
  10527. /* TODO: retry condition */
  10528. }
  10529. }
  10530. if (error) {
  10531. mg_cry_internal(
  10532. conn,
  10533. "%s",
  10534. "Websocket pull failed; closing connection");
  10535. if (data != mem) {
  10536. mg_free(data);
  10537. }
  10538. break;
  10539. }
  10540. conn->data_len = conn->request_len;
  10541. } else {
  10542. mop = buf[0]; /* current mask and opcode, overwritten by
  10543. * memmove() */
  10544. /* Length of the message being read at the front of the
  10545. * queue. Cast to 31 bit is OK, since we limited
  10546. * data_len before. */
  10547. len = (size_t)data_len + header_len;
  10548. /* Copy the data payload into the data pointer for the
  10549. * callback. Cast to 31 bit is OK, since we
  10550. * limited data_len */
  10551. memcpy(data, buf + header_len, (size_t)data_len);
  10552. /* Move the queue forward len bytes */
  10553. memmove(buf, buf + len, body_len - len);
  10554. /* Mark the queue as advanced */
  10555. conn->data_len -= (int)len;
  10556. }
  10557. /* Apply mask if necessary */
  10558. if (mask_len > 0) {
  10559. for (i = 0; i < (size_t)data_len; i++) {
  10560. data[i] ^= mask[i & 3];
  10561. }
  10562. }
  10563. exit_by_callback = 0;
  10564. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10565. /* filter PONG messages */
  10566. DEBUG_TRACE("PONG from %s:%u",
  10567. conn->request_info.remote_addr,
  10568. conn->request_info.remote_port);
  10569. /* No unanwered PINGs left */
  10570. ping_count = 0;
  10571. } else if (enable_ping_pong
  10572. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10573. /* reply PING messages */
  10574. DEBUG_TRACE("Reply PING from %s:%u",
  10575. conn->request_info.remote_addr,
  10576. conn->request_info.remote_port);
  10577. ret = mg_websocket_write(conn,
  10578. MG_WEBSOCKET_OPCODE_PONG,
  10579. (char *)data,
  10580. (size_t)data_len);
  10581. if (ret <= 0) {
  10582. /* Error: send failed */
  10583. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10584. break;
  10585. }
  10586. } else {
  10587. /* Exit the loop if callback signals to exit (server side),
  10588. * or "connection close" opcode received (client side). */
  10589. if ((ws_data_handler != NULL)
  10590. && !ws_data_handler(conn,
  10591. mop,
  10592. (char *)data,
  10593. (size_t)data_len,
  10594. callback_data)) {
  10595. exit_by_callback = 1;
  10596. }
  10597. }
  10598. /* It a buffer has been allocated, free it again */
  10599. if (data != mem) {
  10600. mg_free(data);
  10601. }
  10602. if (exit_by_callback) {
  10603. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10604. conn->request_info.remote_addr,
  10605. conn->request_info.remote_port);
  10606. break;
  10607. }
  10608. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10609. /* Opcode == 8, connection close */
  10610. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10611. conn->request_info.remote_addr,
  10612. conn->request_info.remote_port);
  10613. break;
  10614. }
  10615. /* Not breaking the loop, process next websocket frame. */
  10616. } else {
  10617. /* Read from the socket into the next available location in the
  10618. * message queue. */
  10619. n = pull_inner(NULL,
  10620. conn,
  10621. conn->buf + conn->data_len,
  10622. conn->buf_size - conn->data_len,
  10623. timeout);
  10624. if (n <= -2) {
  10625. /* Error, no bytes read */
  10626. DEBUG_TRACE("PULL from %s:%u failed",
  10627. conn->request_info.remote_addr,
  10628. conn->request_info.remote_port);
  10629. break;
  10630. }
  10631. if (n > 0) {
  10632. conn->data_len += n;
  10633. /* Reset open PING count */
  10634. ping_count = 0;
  10635. } else {
  10636. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10637. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10638. /* Stop sending PING */
  10639. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10640. "- closing connection",
  10641. ping_count,
  10642. conn->request_info.remote_addr,
  10643. conn->request_info.remote_port);
  10644. break;
  10645. }
  10646. if (enable_ping_pong) {
  10647. /* Send Websocket PING message */
  10648. DEBUG_TRACE("PING to %s:%u",
  10649. conn->request_info.remote_addr,
  10650. conn->request_info.remote_port);
  10651. ret = mg_websocket_write(conn,
  10652. MG_WEBSOCKET_OPCODE_PING,
  10653. NULL,
  10654. 0);
  10655. if (ret <= 0) {
  10656. /* Error: send failed */
  10657. DEBUG_TRACE("Send PING failed (%i)", ret);
  10658. break;
  10659. }
  10660. ping_count++;
  10661. }
  10662. }
  10663. /* Timeout: should retry */
  10664. /* TODO: get timeout def */
  10665. }
  10666. }
  10667. }
  10668. /* Leave data processing loop */
  10669. mg_set_thread_name("worker");
  10670. conn->in_websocket_handling = 0;
  10671. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10672. conn->request_info.remote_addr,
  10673. conn->request_info.remote_port);
  10674. }
  10675. static int
  10676. mg_websocket_write_exec(struct mg_connection *conn,
  10677. int opcode,
  10678. const char *data,
  10679. size_t dataLen,
  10680. uint32_t masking_key)
  10681. {
  10682. unsigned char header[14];
  10683. size_t headerLen;
  10684. int retval;
  10685. #if defined(GCC_DIAGNOSTIC)
  10686. /* Disable spurious conversion warning for GCC */
  10687. #pragma GCC diagnostic push
  10688. #pragma GCC diagnostic ignored "-Wconversion"
  10689. #endif
  10690. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10691. #if defined(GCC_DIAGNOSTIC)
  10692. #pragma GCC diagnostic pop
  10693. #endif
  10694. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10695. if (dataLen < 126) {
  10696. /* inline 7-bit length field */
  10697. header[1] = (unsigned char)dataLen;
  10698. headerLen = 2;
  10699. } else if (dataLen <= 0xFFFF) {
  10700. /* 16-bit length field */
  10701. uint16_t len = htons((uint16_t)dataLen);
  10702. header[1] = 126;
  10703. memcpy(header + 2, &len, 2);
  10704. headerLen = 4;
  10705. } else {
  10706. /* 64-bit length field */
  10707. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10708. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10709. header[1] = 127;
  10710. memcpy(header + 2, &len1, 4);
  10711. memcpy(header + 6, &len2, 4);
  10712. headerLen = 10;
  10713. }
  10714. if (masking_key) {
  10715. /* add mask */
  10716. header[1] |= 0x80;
  10717. memcpy(header + headerLen, &masking_key, 4);
  10718. headerLen += 4;
  10719. }
  10720. /* Note that POSIX/Winsock's send() is threadsafe
  10721. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10722. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10723. * push(), although that is only a problem if the packet is large or
  10724. * outgoing buffer is full). */
  10725. /* TODO: Check if this lock should be moved to user land.
  10726. * Currently the server sets this lock for websockets, but
  10727. * not for any other connection. It must be set for every
  10728. * conn read/written by more than one thread, no matter if
  10729. * it is a websocket or regular connection. */
  10730. (void)mg_lock_connection(conn);
  10731. retval = mg_write(conn, header, headerLen);
  10732. if (retval != (int)headerLen) {
  10733. /* Did not send complete header */
  10734. retval = -1;
  10735. } else {
  10736. if (dataLen > 0) {
  10737. retval = mg_write(conn, data, dataLen);
  10738. }
  10739. /* if dataLen == 0, the header length (2) is returned */
  10740. }
  10741. /* TODO: Remove this unlock as well, when lock is removed. */
  10742. mg_unlock_connection(conn);
  10743. return retval;
  10744. }
  10745. int
  10746. mg_websocket_write(struct mg_connection *conn,
  10747. int opcode,
  10748. const char *data,
  10749. size_t dataLen)
  10750. {
  10751. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10752. }
  10753. static void
  10754. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10755. {
  10756. size_t i = 0;
  10757. i = 0;
  10758. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10759. /* Convert in 32 bit words, if data is 4 byte aligned */
  10760. while (i < (in_len - 3)) {
  10761. *(uint32_t *)(void *)(out + i) =
  10762. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10763. i += 4;
  10764. }
  10765. }
  10766. if (i != in_len) {
  10767. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10768. while (i < in_len) {
  10769. *(uint8_t *)(void *)(out + i) =
  10770. *(uint8_t *)(void *)(in + i)
  10771. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10772. i++;
  10773. }
  10774. }
  10775. }
  10776. int
  10777. mg_websocket_client_write(struct mg_connection *conn,
  10778. int opcode,
  10779. const char *data,
  10780. size_t dataLen)
  10781. {
  10782. int retval = -1;
  10783. char *masked_data =
  10784. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10785. uint32_t masking_key = 0;
  10786. if (masked_data == NULL) {
  10787. /* Return -1 in an error case */
  10788. mg_cry_internal(conn,
  10789. "%s",
  10790. "Cannot allocate buffer for masked websocket response: "
  10791. "Out of memory");
  10792. return -1;
  10793. }
  10794. do {
  10795. /* Get a masking key - but not 0 */
  10796. masking_key = (uint32_t)get_random();
  10797. } while (masking_key == 0);
  10798. mask_data(data, dataLen, masking_key, masked_data);
  10799. retval = mg_websocket_write_exec(
  10800. conn, opcode, masked_data, dataLen, masking_key);
  10801. mg_free(masked_data);
  10802. return retval;
  10803. }
  10804. static void
  10805. handle_websocket_request(struct mg_connection *conn,
  10806. const char *path,
  10807. int is_callback_resource,
  10808. struct mg_websocket_subprotocols *subprotocols,
  10809. mg_websocket_connect_handler ws_connect_handler,
  10810. mg_websocket_ready_handler ws_ready_handler,
  10811. mg_websocket_data_handler ws_data_handler,
  10812. mg_websocket_close_handler ws_close_handler,
  10813. void *cbData)
  10814. {
  10815. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10816. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10817. ptrdiff_t lua_websock = 0;
  10818. #if !defined(USE_LUA)
  10819. (void)path;
  10820. #endif
  10821. /* Step 1: Check websocket protocol version. */
  10822. /* Step 1.1: Check Sec-WebSocket-Key. */
  10823. if (!websock_key) {
  10824. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10825. * requires a Sec-WebSocket-Key header.
  10826. */
  10827. /* It could be the hixie draft version
  10828. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10829. */
  10830. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10831. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10832. char key3[8];
  10833. if ((key1 != NULL) && (key2 != NULL)) {
  10834. /* This version uses 8 byte body data in a GET request */
  10835. conn->content_len = 8;
  10836. if (8 == mg_read(conn, key3, 8)) {
  10837. /* This is the hixie version */
  10838. mg_send_http_error(conn,
  10839. 426,
  10840. "%s",
  10841. "Protocol upgrade to RFC 6455 required");
  10842. return;
  10843. }
  10844. }
  10845. /* This is an unknown version */
  10846. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10847. return;
  10848. }
  10849. /* Step 1.2: Check websocket protocol version. */
  10850. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10851. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10852. /* Reject wrong versions */
  10853. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10854. return;
  10855. }
  10856. /* Step 1.3: Could check for "Host", but we do not really nead this
  10857. * value for anything, so just ignore it. */
  10858. /* Step 2: If a callback is responsible, call it. */
  10859. if (is_callback_resource) {
  10860. /* Step 2.1 check and select subprotocol */
  10861. const char *protocols[64]; // max 64 headers
  10862. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10863. "Sec-WebSocket-Protocol",
  10864. protocols,
  10865. 64);
  10866. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10867. int cnt = 0;
  10868. int idx;
  10869. unsigned long len;
  10870. const char *sep, *curSubProtocol,
  10871. *acceptedWebSocketSubprotocol = NULL;
  10872. /* look for matching subprotocol */
  10873. do {
  10874. const char *protocol = protocols[cnt];
  10875. do {
  10876. sep = strchr(protocol, ',');
  10877. curSubProtocol = protocol;
  10878. len = sep ? (unsigned long)(sep - protocol)
  10879. : (unsigned long)strlen(protocol);
  10880. while (sep && isspace((unsigned char)*++sep))
  10881. ; // ignore leading whitespaces
  10882. protocol = sep;
  10883. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10884. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10885. && (strncmp(curSubProtocol,
  10886. subprotocols->subprotocols[idx],
  10887. len)
  10888. == 0)) {
  10889. acceptedWebSocketSubprotocol =
  10890. subprotocols->subprotocols[idx];
  10891. break;
  10892. }
  10893. }
  10894. } while (sep && !acceptedWebSocketSubprotocol);
  10895. } while (++cnt < nbSubprotocolHeader
  10896. && !acceptedWebSocketSubprotocol);
  10897. conn->request_info.acceptedWebSocketSubprotocol =
  10898. acceptedWebSocketSubprotocol;
  10899. } else if (nbSubprotocolHeader > 0) {
  10900. /* keep legacy behavior */
  10901. const char *protocol = protocols[0];
  10902. /* The protocol is a comma separated list of names. */
  10903. /* The server must only return one value from this list. */
  10904. /* First check if it is a list or just a single value. */
  10905. const char *sep = strrchr(protocol, ',');
  10906. if (sep == NULL) {
  10907. /* Just a single protocol -> accept it. */
  10908. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10909. } else {
  10910. /* Multiple protocols -> accept the last one. */
  10911. /* This is just a quick fix if the client offers multiple
  10912. * protocols. The handler should have a list of accepted
  10913. * protocols on his own
  10914. * and use it to select one protocol among those the client
  10915. * has
  10916. * offered.
  10917. */
  10918. while (isspace((unsigned char)*++sep)) {
  10919. ; /* ignore leading whitespaces */
  10920. }
  10921. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10922. }
  10923. }
  10924. if ((ws_connect_handler != NULL)
  10925. && (ws_connect_handler(conn, cbData) != 0)) {
  10926. /* C callback has returned non-zero, do not proceed with
  10927. * handshake.
  10928. */
  10929. /* Note that C callbacks are no longer called when Lua is
  10930. * responsible, so C can no longer filter callbacks for Lua. */
  10931. return;
  10932. }
  10933. }
  10934. #if defined(USE_LUA)
  10935. /* Step 3: No callback. Check if Lua is responsible. */
  10936. else {
  10937. /* Step 3.1: Check if Lua is responsible. */
  10938. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10939. lua_websock = match_prefix(
  10940. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10941. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10942. path);
  10943. }
  10944. if (lua_websock) {
  10945. /* Step 3.2: Lua is responsible: call it. */
  10946. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10947. if (!conn->lua_websocket_state) {
  10948. /* Lua rejected the new client */
  10949. return;
  10950. }
  10951. }
  10952. }
  10953. #endif
  10954. /* Step 4: Check if there is a responsible websocket handler. */
  10955. if (!is_callback_resource && !lua_websock) {
  10956. /* There is no callback, and Lua is not responsible either. */
  10957. /* Reply with a 404 Not Found. We are still at a standard
  10958. * HTTP request here, before the websocket handshake, so
  10959. * we can still send standard HTTP error replies. */
  10960. mg_send_http_error(conn, 404, "%s", "Not found");
  10961. return;
  10962. }
  10963. /* Step 5: The websocket connection has been accepted */
  10964. if (!send_websocket_handshake(conn, websock_key)) {
  10965. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10966. return;
  10967. }
  10968. /* Step 6: Call the ready handler */
  10969. if (is_callback_resource) {
  10970. if (ws_ready_handler != NULL) {
  10971. ws_ready_handler(conn, cbData);
  10972. }
  10973. #if defined(USE_LUA)
  10974. } else if (lua_websock) {
  10975. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10976. /* the ready handler returned false */
  10977. return;
  10978. }
  10979. #endif
  10980. }
  10981. /* Step 7: Enter the read loop */
  10982. if (is_callback_resource) {
  10983. read_websocket(conn, ws_data_handler, cbData);
  10984. #if defined(USE_LUA)
  10985. } else if (lua_websock) {
  10986. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10987. #endif
  10988. }
  10989. /* Step 8: Call the close handler */
  10990. if (ws_close_handler) {
  10991. ws_close_handler(conn, cbData);
  10992. }
  10993. }
  10994. static int
  10995. is_websocket_protocol(const struct mg_connection *conn)
  10996. {
  10997. const char *upgrade, *connection;
  10998. /* A websocket protocoll has the following HTTP headers:
  10999. *
  11000. * Connection: Upgrade
  11001. * Upgrade: Websocket
  11002. */
  11003. upgrade = mg_get_header(conn, "Upgrade");
  11004. if (upgrade == NULL) {
  11005. return 0; /* fail early, don't waste time checking other header
  11006. * fields
  11007. */
  11008. }
  11009. if (!mg_strcasestr(upgrade, "websocket")) {
  11010. return 0;
  11011. }
  11012. connection = mg_get_header(conn, "Connection");
  11013. if (connection == NULL) {
  11014. return 0;
  11015. }
  11016. if (!mg_strcasestr(connection, "upgrade")) {
  11017. return 0;
  11018. }
  11019. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11020. * "Sec-WebSocket-Version" are also required.
  11021. * Don't check them here, since even an unsupported websocket protocol
  11022. * request still IS a websocket request (in contrast to a standard HTTP
  11023. * request). It will fail later in handle_websocket_request.
  11024. */
  11025. return 1;
  11026. }
  11027. #endif /* !USE_WEBSOCKET */
  11028. static int
  11029. isbyte(int n)
  11030. {
  11031. return (n >= 0) && (n <= 255);
  11032. }
  11033. static int
  11034. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11035. {
  11036. int n, a, b, c, d, slash = 32, len = 0;
  11037. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11038. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11039. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11040. && (slash < 33)) {
  11041. len = n;
  11042. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11043. | (uint32_t)d;
  11044. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11045. }
  11046. return len;
  11047. }
  11048. static int
  11049. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11050. {
  11051. int throttle = 0;
  11052. struct vec vec, val;
  11053. uint32_t net, mask;
  11054. char mult;
  11055. double v;
  11056. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11057. mult = ',';
  11058. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11059. || (v < 0)
  11060. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11061. && (mult != ','))) {
  11062. continue;
  11063. }
  11064. v *= (lowercase(&mult) == 'k')
  11065. ? 1024
  11066. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11067. if (vec.len == 1 && vec.ptr[0] == '*') {
  11068. throttle = (int)v;
  11069. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11070. if ((remote_ip & mask) == net) {
  11071. throttle = (int)v;
  11072. }
  11073. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11074. throttle = (int)v;
  11075. }
  11076. }
  11077. return throttle;
  11078. }
  11079. static uint32_t
  11080. get_remote_ip(const struct mg_connection *conn)
  11081. {
  11082. if (!conn) {
  11083. return 0;
  11084. }
  11085. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11086. }
  11087. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11088. #include "handle_form.inl"
  11089. #if defined(MG_LEGACY_INTERFACE)
  11090. /* Implement the deprecated mg_upload function by calling the new
  11091. * mg_handle_form_request function. While mg_upload could only handle
  11092. * HTML forms sent as POST request in multipart/form-data format
  11093. * containing only file input elements, mg_handle_form_request can
  11094. * handle all form input elements and all standard request methods. */
  11095. struct mg_upload_user_data {
  11096. struct mg_connection *conn;
  11097. const char *destination_dir;
  11098. int num_uploaded_files;
  11099. };
  11100. /* Helper function for deprecated mg_upload. */
  11101. static int
  11102. mg_upload_field_found(const char *key,
  11103. const char *filename,
  11104. char *path,
  11105. size_t pathlen,
  11106. void *user_data)
  11107. {
  11108. int truncated = 0;
  11109. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11110. (void)key;
  11111. if (!filename) {
  11112. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11113. return FORM_FIELD_STORAGE_ABORT;
  11114. }
  11115. mg_snprintf(fud->conn,
  11116. &truncated,
  11117. path,
  11118. pathlen - 1,
  11119. "%s/%s",
  11120. fud->destination_dir,
  11121. filename);
  11122. if (truncated) {
  11123. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11124. return FORM_FIELD_STORAGE_ABORT;
  11125. }
  11126. return FORM_FIELD_STORAGE_STORE;
  11127. }
  11128. /* Helper function for deprecated mg_upload. */
  11129. static int
  11130. mg_upload_field_get(const char *key,
  11131. const char *value,
  11132. size_t value_size,
  11133. void *user_data)
  11134. {
  11135. /* Function should never be called */
  11136. (void)key;
  11137. (void)value;
  11138. (void)value_size;
  11139. (void)user_data;
  11140. return 0;
  11141. }
  11142. /* Helper function for deprecated mg_upload. */
  11143. static int
  11144. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11145. {
  11146. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11147. (void)file_size;
  11148. fud->num_uploaded_files++;
  11149. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11150. return 0;
  11151. }
  11152. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11153. int
  11154. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11155. {
  11156. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11157. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11158. mg_upload_field_get,
  11159. mg_upload_field_stored,
  11160. 0};
  11161. int ret;
  11162. fdh.user_data = (void *)&fud;
  11163. ret = mg_handle_form_request(conn, &fdh);
  11164. if (ret < 0) {
  11165. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11166. }
  11167. return fud.num_uploaded_files;
  11168. }
  11169. #endif
  11170. static int
  11171. get_first_ssl_listener_index(const struct mg_context *ctx)
  11172. {
  11173. unsigned int i;
  11174. int idx = -1;
  11175. if (ctx) {
  11176. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11177. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11178. }
  11179. }
  11180. return idx;
  11181. }
  11182. /* Return host (without port) */
  11183. /* Use mg_free to free the result */
  11184. static const char *
  11185. alloc_get_host(struct mg_connection *conn)
  11186. {
  11187. char buf[1025];
  11188. size_t buflen = sizeof(buf);
  11189. const char *host_header = get_header(conn->request_info.http_headers,
  11190. conn->request_info.num_headers,
  11191. "Host");
  11192. char *host;
  11193. if (host_header != NULL) {
  11194. char *pos;
  11195. /* Create a local copy of the "Host" header, since it might be
  11196. * modified here. */
  11197. mg_strlcpy(buf, host_header, buflen);
  11198. buf[buflen - 1] = '\0';
  11199. host = buf;
  11200. while (isspace((unsigned char)*host)) {
  11201. host++;
  11202. }
  11203. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11204. * is found. */
  11205. if (*host == '[') {
  11206. pos = strchr(host, ']');
  11207. if (!pos) {
  11208. /* Malformed hostname starts with '[', but no ']' found */
  11209. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11210. return NULL;
  11211. }
  11212. /* terminate after ']' */
  11213. pos[1] = 0;
  11214. } else {
  11215. /* Otherwise, a ':' separates hostname and port number */
  11216. pos = strchr(host, ':');
  11217. if (pos != NULL) {
  11218. *pos = '\0';
  11219. }
  11220. }
  11221. if (conn->ssl) {
  11222. /* This is a HTTPS connection, maybe we have a hostname
  11223. * from SNI (set in ssl_servername_callback). */
  11224. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11225. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11226. /* We are not using the default domain */
  11227. if (mg_strcasecmp(host, sslhost)) {
  11228. /* Mismatch between SNI domain and HTTP domain */
  11229. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11230. sslhost,
  11231. host);
  11232. return NULL;
  11233. }
  11234. }
  11235. DEBUG_TRACE("HTTPS Host: %s", host);
  11236. } else {
  11237. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11238. while (dom) {
  11239. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11240. /* Found matching domain */
  11241. DEBUG_TRACE("HTTP domain %s found",
  11242. dom->config[AUTHENTICATION_DOMAIN]);
  11243. /* TODO: Check if this is a HTTP or HTTPS domain */
  11244. conn->dom_ctx = dom;
  11245. break;
  11246. }
  11247. dom = dom->next;
  11248. }
  11249. DEBUG_TRACE("HTTP Host: %s", host);
  11250. }
  11251. } else {
  11252. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11253. host = buf;
  11254. DEBUG_TRACE("IP: %s", host);
  11255. }
  11256. return mg_strdup_ctx(host, conn->phys_ctx);
  11257. }
  11258. static void
  11259. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11260. {
  11261. char target_url[MG_BUF_LEN];
  11262. int truncated = 0;
  11263. conn->must_close = 1;
  11264. /* Send host, port, uri and (if it exists) ?query_string */
  11265. if (conn->host) {
  11266. /* Use "308 Permanent Redirect" */
  11267. int redirect_code = 308;
  11268. /* Create target URL */
  11269. mg_snprintf(
  11270. conn,
  11271. &truncated,
  11272. target_url,
  11273. sizeof(target_url),
  11274. "https://%s:%d%s%s%s",
  11275. conn->host,
  11276. #if defined(USE_IPV6)
  11277. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11278. == AF_INET6)
  11279. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11280. .lsa.sin6.sin6_port)
  11281. :
  11282. #endif
  11283. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11284. .lsa.sin.sin_port),
  11285. conn->request_info.local_uri,
  11286. (conn->request_info.query_string == NULL) ? "" : "?",
  11287. (conn->request_info.query_string == NULL)
  11288. ? ""
  11289. : conn->request_info.query_string);
  11290. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11291. * is used as buffer size) */
  11292. if (truncated) {
  11293. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11294. return;
  11295. }
  11296. /* Use redirect helper function */
  11297. mg_send_http_redirect(conn, target_url, redirect_code);
  11298. }
  11299. }
  11300. static void
  11301. handler_info_acquire(struct mg_handler_info *handler_info)
  11302. {
  11303. pthread_mutex_lock(&handler_info->refcount_mutex);
  11304. handler_info->refcount++;
  11305. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11306. }
  11307. static void
  11308. handler_info_release(struct mg_handler_info *handler_info)
  11309. {
  11310. pthread_mutex_lock(&handler_info->refcount_mutex);
  11311. handler_info->refcount--;
  11312. pthread_cond_signal(&handler_info->refcount_cond);
  11313. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11314. }
  11315. static void
  11316. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11317. {
  11318. pthread_mutex_lock(&handler_info->refcount_mutex);
  11319. while (handler_info->refcount) {
  11320. pthread_cond_wait(&handler_info->refcount_cond,
  11321. &handler_info->refcount_mutex);
  11322. }
  11323. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11324. }
  11325. static void
  11326. mg_set_handler_type(struct mg_context *phys_ctx,
  11327. struct mg_domain_context *dom_ctx,
  11328. const char *uri,
  11329. int handler_type,
  11330. int is_delete_request,
  11331. mg_request_handler handler,
  11332. struct mg_websocket_subprotocols *subprotocols,
  11333. mg_websocket_connect_handler connect_handler,
  11334. mg_websocket_ready_handler ready_handler,
  11335. mg_websocket_data_handler data_handler,
  11336. mg_websocket_close_handler close_handler,
  11337. mg_authorization_handler auth_handler,
  11338. void *cbdata)
  11339. {
  11340. struct mg_handler_info *tmp_rh, **lastref;
  11341. size_t urilen = strlen(uri);
  11342. if (handler_type == WEBSOCKET_HANDLER) {
  11343. DEBUG_ASSERT(handler == NULL);
  11344. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11345. || ready_handler != NULL || data_handler != NULL
  11346. || close_handler != NULL);
  11347. DEBUG_ASSERT(auth_handler == NULL);
  11348. if (handler != NULL) {
  11349. return;
  11350. }
  11351. if (!is_delete_request && (connect_handler == NULL)
  11352. && (ready_handler == NULL) && (data_handler == NULL)
  11353. && (close_handler == NULL)) {
  11354. return;
  11355. }
  11356. if (auth_handler != NULL) {
  11357. return;
  11358. }
  11359. } else if (handler_type == REQUEST_HANDLER) {
  11360. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11361. && data_handler == NULL && close_handler == NULL);
  11362. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11363. DEBUG_ASSERT(auth_handler == NULL);
  11364. if ((connect_handler != NULL) || (ready_handler != NULL)
  11365. || (data_handler != NULL) || (close_handler != NULL)) {
  11366. return;
  11367. }
  11368. if (!is_delete_request && (handler == NULL)) {
  11369. return;
  11370. }
  11371. if (auth_handler != NULL) {
  11372. return;
  11373. }
  11374. } else { /* AUTH_HANDLER */
  11375. DEBUG_ASSERT(handler == NULL);
  11376. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11377. && data_handler == NULL && close_handler == NULL);
  11378. DEBUG_ASSERT(auth_handler != NULL);
  11379. if (handler != NULL) {
  11380. return;
  11381. }
  11382. if ((connect_handler != NULL) || (ready_handler != NULL)
  11383. || (data_handler != NULL) || (close_handler != NULL)) {
  11384. return;
  11385. }
  11386. if (!is_delete_request && (auth_handler == NULL)) {
  11387. return;
  11388. }
  11389. }
  11390. if (!phys_ctx || !dom_ctx) {
  11391. return;
  11392. }
  11393. mg_lock_context(phys_ctx);
  11394. /* first try to find an existing handler */
  11395. lastref = &(dom_ctx->handlers);
  11396. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11397. if (tmp_rh->handler_type == handler_type) {
  11398. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11399. if (!is_delete_request) {
  11400. /* update existing handler */
  11401. if (handler_type == REQUEST_HANDLER) {
  11402. /* Wait for end of use before updating */
  11403. handler_info_wait_unused(tmp_rh);
  11404. /* Ok, the handler is no more use -> Update it */
  11405. tmp_rh->handler = handler;
  11406. } else if (handler_type == WEBSOCKET_HANDLER) {
  11407. tmp_rh->subprotocols = subprotocols;
  11408. tmp_rh->connect_handler = connect_handler;
  11409. tmp_rh->ready_handler = ready_handler;
  11410. tmp_rh->data_handler = data_handler;
  11411. tmp_rh->close_handler = close_handler;
  11412. } else { /* AUTH_HANDLER */
  11413. tmp_rh->auth_handler = auth_handler;
  11414. }
  11415. tmp_rh->cbdata = cbdata;
  11416. } else {
  11417. /* remove existing handler */
  11418. if (handler_type == REQUEST_HANDLER) {
  11419. /* Wait for end of use before removing */
  11420. handler_info_wait_unused(tmp_rh);
  11421. /* Ok, the handler is no more used -> Destroy resources
  11422. */
  11423. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11424. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11425. }
  11426. *lastref = tmp_rh->next;
  11427. mg_free(tmp_rh->uri);
  11428. mg_free(tmp_rh);
  11429. }
  11430. mg_unlock_context(phys_ctx);
  11431. return;
  11432. }
  11433. }
  11434. lastref = &(tmp_rh->next);
  11435. }
  11436. if (is_delete_request) {
  11437. /* no handler to set, this was a remove request to a non-existing
  11438. * handler */
  11439. mg_unlock_context(phys_ctx);
  11440. return;
  11441. }
  11442. tmp_rh =
  11443. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11444. 1,
  11445. phys_ctx);
  11446. if (tmp_rh == NULL) {
  11447. mg_unlock_context(phys_ctx);
  11448. mg_cry_internal(fc(phys_ctx),
  11449. "%s",
  11450. "Cannot create new request handler struct, OOM");
  11451. return;
  11452. }
  11453. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11454. if (!tmp_rh->uri) {
  11455. mg_unlock_context(phys_ctx);
  11456. mg_free(tmp_rh);
  11457. mg_cry_internal(fc(phys_ctx),
  11458. "%s",
  11459. "Cannot create new request handler struct, OOM");
  11460. return;
  11461. }
  11462. tmp_rh->uri_len = urilen;
  11463. if (handler_type == REQUEST_HANDLER) {
  11464. /* Init refcount mutex and condition */
  11465. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11466. mg_unlock_context(phys_ctx);
  11467. mg_free(tmp_rh);
  11468. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");
  11469. return;
  11470. }
  11471. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11472. mg_unlock_context(phys_ctx);
  11473. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11474. mg_free(tmp_rh);
  11475. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");
  11476. return;
  11477. }
  11478. tmp_rh->refcount = 0;
  11479. tmp_rh->handler = handler;
  11480. } else if (handler_type == WEBSOCKET_HANDLER) {
  11481. tmp_rh->subprotocols = subprotocols;
  11482. tmp_rh->connect_handler = connect_handler;
  11483. tmp_rh->ready_handler = ready_handler;
  11484. tmp_rh->data_handler = data_handler;
  11485. tmp_rh->close_handler = close_handler;
  11486. } else { /* AUTH_HANDLER */
  11487. tmp_rh->auth_handler = auth_handler;
  11488. }
  11489. tmp_rh->cbdata = cbdata;
  11490. tmp_rh->handler_type = handler_type;
  11491. tmp_rh->next = NULL;
  11492. *lastref = tmp_rh;
  11493. mg_unlock_context(phys_ctx);
  11494. }
  11495. void
  11496. mg_set_request_handler(struct mg_context *ctx,
  11497. const char *uri,
  11498. mg_request_handler handler,
  11499. void *cbdata)
  11500. {
  11501. mg_set_handler_type(ctx,
  11502. &(ctx->dd),
  11503. uri,
  11504. REQUEST_HANDLER,
  11505. handler == NULL,
  11506. handler,
  11507. NULL,
  11508. NULL,
  11509. NULL,
  11510. NULL,
  11511. NULL,
  11512. NULL,
  11513. cbdata);
  11514. }
  11515. void
  11516. mg_set_websocket_handler(struct mg_context *ctx,
  11517. const char *uri,
  11518. mg_websocket_connect_handler connect_handler,
  11519. mg_websocket_ready_handler ready_handler,
  11520. mg_websocket_data_handler data_handler,
  11521. mg_websocket_close_handler close_handler,
  11522. void *cbdata)
  11523. {
  11524. mg_set_websocket_handler_with_subprotocols(ctx,
  11525. uri,
  11526. NULL,
  11527. connect_handler,
  11528. ready_handler,
  11529. data_handler,
  11530. close_handler,
  11531. cbdata);
  11532. }
  11533. void
  11534. mg_set_websocket_handler_with_subprotocols(
  11535. struct mg_context *ctx,
  11536. const char *uri,
  11537. struct mg_websocket_subprotocols *subprotocols,
  11538. mg_websocket_connect_handler connect_handler,
  11539. mg_websocket_ready_handler ready_handler,
  11540. mg_websocket_data_handler data_handler,
  11541. mg_websocket_close_handler close_handler,
  11542. void *cbdata)
  11543. {
  11544. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11545. && (data_handler == NULL)
  11546. && (close_handler == NULL);
  11547. mg_set_handler_type(ctx,
  11548. &(ctx->dd),
  11549. uri,
  11550. WEBSOCKET_HANDLER,
  11551. is_delete_request,
  11552. NULL,
  11553. subprotocols,
  11554. connect_handler,
  11555. ready_handler,
  11556. data_handler,
  11557. close_handler,
  11558. NULL,
  11559. cbdata);
  11560. }
  11561. void
  11562. mg_set_auth_handler(struct mg_context *ctx,
  11563. const char *uri,
  11564. mg_authorization_handler handler,
  11565. void *cbdata)
  11566. {
  11567. mg_set_handler_type(ctx,
  11568. &(ctx->dd),
  11569. uri,
  11570. AUTH_HANDLER,
  11571. handler == NULL,
  11572. NULL,
  11573. NULL,
  11574. NULL,
  11575. NULL,
  11576. NULL,
  11577. NULL,
  11578. handler,
  11579. cbdata);
  11580. }
  11581. static int
  11582. get_request_handler(struct mg_connection *conn,
  11583. int handler_type,
  11584. mg_request_handler *handler,
  11585. struct mg_websocket_subprotocols **subprotocols,
  11586. mg_websocket_connect_handler *connect_handler,
  11587. mg_websocket_ready_handler *ready_handler,
  11588. mg_websocket_data_handler *data_handler,
  11589. mg_websocket_close_handler *close_handler,
  11590. mg_authorization_handler *auth_handler,
  11591. void **cbdata,
  11592. struct mg_handler_info **handler_info)
  11593. {
  11594. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11595. if (request_info) {
  11596. const char *uri = request_info->local_uri;
  11597. size_t urilen = strlen(uri);
  11598. struct mg_handler_info *tmp_rh;
  11599. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11600. return 0;
  11601. }
  11602. mg_lock_context(conn->phys_ctx);
  11603. /* first try for an exact match */
  11604. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11605. tmp_rh = tmp_rh->next) {
  11606. if (tmp_rh->handler_type == handler_type) {
  11607. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11608. if (handler_type == WEBSOCKET_HANDLER) {
  11609. *subprotocols = tmp_rh->subprotocols;
  11610. *connect_handler = tmp_rh->connect_handler;
  11611. *ready_handler = tmp_rh->ready_handler;
  11612. *data_handler = tmp_rh->data_handler;
  11613. *close_handler = tmp_rh->close_handler;
  11614. } else if (handler_type == REQUEST_HANDLER) {
  11615. *handler = tmp_rh->handler;
  11616. /* Acquire handler and give it back */
  11617. handler_info_acquire(tmp_rh);
  11618. *handler_info = tmp_rh;
  11619. } else { /* AUTH_HANDLER */
  11620. *auth_handler = tmp_rh->auth_handler;
  11621. }
  11622. *cbdata = tmp_rh->cbdata;
  11623. mg_unlock_context(conn->phys_ctx);
  11624. return 1;
  11625. }
  11626. }
  11627. }
  11628. /* next try for a partial match, we will accept uri/something */
  11629. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11630. tmp_rh = tmp_rh->next) {
  11631. if (tmp_rh->handler_type == handler_type) {
  11632. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11633. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11634. if (handler_type == WEBSOCKET_HANDLER) {
  11635. *subprotocols = tmp_rh->subprotocols;
  11636. *connect_handler = tmp_rh->connect_handler;
  11637. *ready_handler = tmp_rh->ready_handler;
  11638. *data_handler = tmp_rh->data_handler;
  11639. *close_handler = tmp_rh->close_handler;
  11640. } else if (handler_type == REQUEST_HANDLER) {
  11641. *handler = tmp_rh->handler;
  11642. /* Acquire handler and give it back */
  11643. handler_info_acquire(tmp_rh);
  11644. *handler_info = tmp_rh;
  11645. } else { /* AUTH_HANDLER */
  11646. *auth_handler = tmp_rh->auth_handler;
  11647. }
  11648. *cbdata = tmp_rh->cbdata;
  11649. mg_unlock_context(conn->phys_ctx);
  11650. return 1;
  11651. }
  11652. }
  11653. }
  11654. /* finally try for pattern match */
  11655. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11656. tmp_rh = tmp_rh->next) {
  11657. if (tmp_rh->handler_type == handler_type) {
  11658. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11659. if (handler_type == WEBSOCKET_HANDLER) {
  11660. *subprotocols = tmp_rh->subprotocols;
  11661. *connect_handler = tmp_rh->connect_handler;
  11662. *ready_handler = tmp_rh->ready_handler;
  11663. *data_handler = tmp_rh->data_handler;
  11664. *close_handler = tmp_rh->close_handler;
  11665. } else if (handler_type == REQUEST_HANDLER) {
  11666. *handler = tmp_rh->handler;
  11667. /* Acquire handler and give it back */
  11668. handler_info_acquire(tmp_rh);
  11669. *handler_info = tmp_rh;
  11670. } else { /* AUTH_HANDLER */
  11671. *auth_handler = tmp_rh->auth_handler;
  11672. }
  11673. *cbdata = tmp_rh->cbdata;
  11674. mg_unlock_context(conn->phys_ctx);
  11675. return 1;
  11676. }
  11677. }
  11678. }
  11679. mg_unlock_context(conn->phys_ctx);
  11680. }
  11681. return 0; /* none found */
  11682. }
  11683. /* Check if the script file is in a path, allowed for script files.
  11684. * This can be used if uploading files is possible not only for the server
  11685. * admin, and the upload mechanism does not check the file extension.
  11686. */
  11687. static int
  11688. is_in_script_path(const struct mg_connection *conn, const char *path)
  11689. {
  11690. /* TODO (Feature): Add config value for allowed script path.
  11691. * Default: All allowed. */
  11692. (void)conn;
  11693. (void)path;
  11694. return 1;
  11695. }
  11696. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11697. static int
  11698. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11699. void *cbdata)
  11700. {
  11701. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11702. if (pcallbacks->websocket_connect) {
  11703. return pcallbacks->websocket_connect(conn);
  11704. }
  11705. /* No handler set - assume "OK" */
  11706. return 0;
  11707. }
  11708. static void
  11709. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11710. {
  11711. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11712. if (pcallbacks->websocket_ready) {
  11713. pcallbacks->websocket_ready(conn);
  11714. }
  11715. }
  11716. static int
  11717. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11718. int bits,
  11719. char *data,
  11720. size_t len,
  11721. void *cbdata)
  11722. {
  11723. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11724. if (pcallbacks->websocket_data) {
  11725. return pcallbacks->websocket_data(conn, bits, data, len);
  11726. }
  11727. /* No handler set - assume "OK" */
  11728. return 1;
  11729. }
  11730. #endif
  11731. /* This is the heart of the Civetweb's logic.
  11732. * This function is called when the request is read, parsed and validated,
  11733. * and Civetweb must decide what action to take: serve a file, or
  11734. * a directory, or call embedded function, etcetera. */
  11735. static void
  11736. handle_request(struct mg_connection *conn)
  11737. {
  11738. struct mg_request_info *ri = &conn->request_info;
  11739. char path[PATH_MAX];
  11740. int uri_len, ssl_index;
  11741. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11742. is_put_or_delete_request = 0, is_callback_resource = 0;
  11743. int i;
  11744. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11745. mg_request_handler callback_handler = NULL;
  11746. struct mg_handler_info *handler_info = NULL;
  11747. struct mg_websocket_subprotocols *subprotocols;
  11748. mg_websocket_connect_handler ws_connect_handler = NULL;
  11749. mg_websocket_ready_handler ws_ready_handler = NULL;
  11750. mg_websocket_data_handler ws_data_handler = NULL;
  11751. mg_websocket_close_handler ws_close_handler = NULL;
  11752. void *callback_data = NULL;
  11753. mg_authorization_handler auth_handler = NULL;
  11754. void *auth_callback_data = NULL;
  11755. int handler_type;
  11756. time_t curtime = time(NULL);
  11757. char date[64];
  11758. path[0] = 0;
  11759. /* 1. get the request url */
  11760. /* 1.1. split into url and query string */
  11761. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11762. != NULL) {
  11763. *((char *)conn->request_info.query_string++) = '\0';
  11764. }
  11765. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11766. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11767. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11768. if (ssl_index >= 0) {
  11769. redirect_to_https_port(conn, ssl_index);
  11770. } else {
  11771. /* A http to https forward port has been specified,
  11772. * but no https port to forward to. */
  11773. mg_send_http_error(conn,
  11774. 503,
  11775. "%s",
  11776. "Error: SSL forward not configured properly");
  11777. mg_cry_internal(conn,
  11778. "%s",
  11779. "Can not redirect to SSL, no SSL port available");
  11780. }
  11781. return;
  11782. }
  11783. uri_len = (int)strlen(ri->local_uri);
  11784. /* 1.3. decode url (if config says so) */
  11785. if (should_decode_url(conn)) {
  11786. mg_url_decode(
  11787. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11788. }
  11789. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11790. * not possible */
  11791. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11792. /* step 1. completed, the url is known now */
  11793. uri_len = (int)strlen(ri->local_uri);
  11794. DEBUG_TRACE("URL: %s", ri->local_uri);
  11795. /* 2. if this ip has limited speed, set it for this connection */
  11796. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11797. get_remote_ip(conn),
  11798. ri->local_uri);
  11799. /* 3. call a "handle everything" callback, if registered */
  11800. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11801. /* Note that since V1.7 the "begin_request" function is called
  11802. * before an authorization check. If an authorization check is
  11803. * required, use a request_handler instead. */
  11804. i = conn->phys_ctx->callbacks.begin_request(conn);
  11805. if (i > 0) {
  11806. /* callback already processed the request. Store the
  11807. return value as a status code for the access log. */
  11808. conn->status_code = i;
  11809. discard_unread_request_data(conn);
  11810. return;
  11811. } else if (i == 0) {
  11812. /* civetweb should process the request */
  11813. } else {
  11814. /* unspecified - may change with the next version */
  11815. return;
  11816. }
  11817. }
  11818. /* request not yet handled by a handler or redirect, so the request
  11819. * is processed here */
  11820. /* 4. Check for CORS preflight requests and handle them (if configured).
  11821. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11822. */
  11823. if (!strcmp(ri->request_method, "OPTIONS")) {
  11824. /* Send a response to CORS preflights only if
  11825. * access_control_allow_methods is not NULL and not an empty string.
  11826. * In this case, scripts can still handle CORS. */
  11827. const char *cors_meth_cfg =
  11828. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11829. const char *cors_orig_cfg =
  11830. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11831. const char *cors_origin =
  11832. get_header(ri->http_headers, ri->num_headers, "Origin");
  11833. const char *cors_acrm = get_header(ri->http_headers,
  11834. ri->num_headers,
  11835. "Access-Control-Request-Method");
  11836. /* Todo: check if cors_origin is in cors_orig_cfg.
  11837. * Or, let the client check this. */
  11838. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11839. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11840. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11841. /* This is a valid CORS preflight, and the server is configured
  11842. * to
  11843. * handle it automatically. */
  11844. const char *cors_acrh =
  11845. get_header(ri->http_headers,
  11846. ri->num_headers,
  11847. "Access-Control-Request-Headers");
  11848. gmt_time_string(date, sizeof(date), &curtime);
  11849. mg_printf(conn,
  11850. "HTTP/1.1 200 OK\r\n"
  11851. "Date: %s\r\n"
  11852. "Access-Control-Allow-Origin: %s\r\n"
  11853. "Access-Control-Allow-Methods: %s\r\n"
  11854. "Content-Length: 0\r\n"
  11855. "Connection: %s\r\n",
  11856. date,
  11857. cors_orig_cfg,
  11858. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11859. suggest_connection_header(conn));
  11860. if (cors_acrh != NULL) {
  11861. /* CORS request is asking for additional headers */
  11862. const char *cors_hdr_cfg =
  11863. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11864. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11865. /* Allow only if access_control_allow_headers is
  11866. * not NULL and not an empty string. If this
  11867. * configuration is set to *, allow everything.
  11868. * Otherwise this configuration must be a list
  11869. * of allowed HTTP header names. */
  11870. mg_printf(conn,
  11871. "Access-Control-Allow-Headers: %s\r\n",
  11872. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11873. : cors_hdr_cfg));
  11874. }
  11875. }
  11876. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11877. mg_printf(conn, "\r\n");
  11878. return;
  11879. }
  11880. }
  11881. /* 5. interpret the url to find out how the request must be handled
  11882. */
  11883. /* 5.1. first test, if the request targets the regular http(s)://
  11884. * protocol namespace or the websocket ws(s):// protocol namespace.
  11885. */
  11886. is_websocket_request = is_websocket_protocol(conn);
  11887. #if defined(USE_WEBSOCKET)
  11888. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11889. #else
  11890. handler_type = REQUEST_HANDLER;
  11891. #endif /* defined(USE_WEBSOCKET) */
  11892. /* 5.2. check if the request will be handled by a callback */
  11893. if (get_request_handler(conn,
  11894. handler_type,
  11895. &callback_handler,
  11896. &subprotocols,
  11897. &ws_connect_handler,
  11898. &ws_ready_handler,
  11899. &ws_data_handler,
  11900. &ws_close_handler,
  11901. NULL,
  11902. &callback_data,
  11903. &handler_info)) {
  11904. /* 5.2.1. A callback will handle this request. All requests
  11905. * handled
  11906. * by a callback have to be considered as requests to a script
  11907. * resource. */
  11908. is_callback_resource = 1;
  11909. is_script_resource = 1;
  11910. is_put_or_delete_request = is_put_or_delete_method(conn);
  11911. } else {
  11912. no_callback_resource:
  11913. /* 5.2.2. No callback is responsible for this request. The URI
  11914. * addresses a file based resource (static content or Lua/cgi
  11915. * scripts in the file system). */
  11916. is_callback_resource = 0;
  11917. interpret_uri(conn,
  11918. path,
  11919. sizeof(path),
  11920. &file.stat,
  11921. &is_found,
  11922. &is_script_resource,
  11923. &is_websocket_request,
  11924. &is_put_or_delete_request);
  11925. }
  11926. /* 6. authorization check */
  11927. /* 6.1. a custom authorization handler is installed */
  11928. if (get_request_handler(conn,
  11929. AUTH_HANDLER,
  11930. NULL,
  11931. NULL,
  11932. NULL,
  11933. NULL,
  11934. NULL,
  11935. NULL,
  11936. &auth_handler,
  11937. &auth_callback_data,
  11938. NULL)) {
  11939. if (!auth_handler(conn, auth_callback_data)) {
  11940. return;
  11941. }
  11942. } else if (is_put_or_delete_request && !is_script_resource
  11943. && !is_callback_resource) {
  11944. /* 6.2. this request is a PUT/DELETE to a real file */
  11945. /* 6.2.1. thus, the server must have real files */
  11946. #if defined(NO_FILES)
  11947. if (1) {
  11948. #else
  11949. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11950. #endif
  11951. /* This server does not have any real files, thus the
  11952. * PUT/DELETE methods are not valid. */
  11953. mg_send_http_error(conn,
  11954. 405,
  11955. "%s method not allowed",
  11956. conn->request_info.request_method);
  11957. return;
  11958. }
  11959. #if !defined(NO_FILES)
  11960. /* 6.2.2. Check if put authorization for static files is
  11961. * available.
  11962. */
  11963. if (!is_authorized_for_put(conn)) {
  11964. send_authorization_request(conn, NULL);
  11965. return;
  11966. }
  11967. #endif
  11968. } else {
  11969. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11970. * or it is a PUT or DELETE request to a resource that does not
  11971. * correspond to a file. Check authorization. */
  11972. if (!check_authorization(conn, path)) {
  11973. send_authorization_request(conn, NULL);
  11974. return;
  11975. }
  11976. }
  11977. /* request is authorized or does not need authorization */
  11978. /* 7. check if there are request handlers for this uri */
  11979. if (is_callback_resource) {
  11980. if (!is_websocket_request) {
  11981. i = callback_handler(conn, callback_data);
  11982. /* Callback handler will not be used anymore. Release it */
  11983. handler_info_release(handler_info);
  11984. if (i > 0) {
  11985. /* Do nothing, callback has served the request. Store
  11986. * then return value as status code for the log and discard
  11987. * all data from the client not used by the callback. */
  11988. conn->status_code = i;
  11989. discard_unread_request_data(conn);
  11990. } else {
  11991. /* The handler did NOT handle the request. */
  11992. /* Some proper reactions would be:
  11993. * a) close the connections without sending anything
  11994. * b) send a 404 not found
  11995. * c) try if there is a file matching the URI
  11996. * It would be possible to do a, b or c in the callback
  11997. * implementation, and return 1 - we cannot do anything
  11998. * here, that is not possible in the callback.
  11999. *
  12000. * TODO: What would be the best reaction here?
  12001. * (Note: The reaction may change, if there is a better
  12002. *idea.)
  12003. */
  12004. /* For the moment, use option c: We look for a proper file,
  12005. * but since a file request is not always a script resource,
  12006. * the authorization check might be different. */
  12007. interpret_uri(conn,
  12008. path,
  12009. sizeof(path),
  12010. &file.stat,
  12011. &is_found,
  12012. &is_script_resource,
  12013. &is_websocket_request,
  12014. &is_put_or_delete_request);
  12015. callback_handler = NULL;
  12016. /* Here we are at a dead end:
  12017. * According to URI matching, a callback should be
  12018. * responsible for handling the request,
  12019. * we called it, but the callback declared itself
  12020. * not responsible.
  12021. * We use a goto here, to get out of this dead end,
  12022. * and continue with the default handling.
  12023. * A goto here is simpler and better to understand
  12024. * than some curious loop. */
  12025. goto no_callback_resource;
  12026. }
  12027. } else {
  12028. #if defined(USE_WEBSOCKET)
  12029. handle_websocket_request(conn,
  12030. path,
  12031. is_callback_resource,
  12032. subprotocols,
  12033. ws_connect_handler,
  12034. ws_ready_handler,
  12035. ws_data_handler,
  12036. ws_close_handler,
  12037. callback_data);
  12038. #endif
  12039. }
  12040. return;
  12041. }
  12042. /* 8. handle websocket requests */
  12043. #if defined(USE_WEBSOCKET)
  12044. if (is_websocket_request) {
  12045. if (is_script_resource) {
  12046. if (is_in_script_path(conn, path)) {
  12047. /* Websocket Lua script */
  12048. handle_websocket_request(conn,
  12049. path,
  12050. 0 /* Lua Script */,
  12051. NULL,
  12052. NULL,
  12053. NULL,
  12054. NULL,
  12055. NULL,
  12056. conn->phys_ctx->user_data);
  12057. } else {
  12058. /* Script was in an illegal path */
  12059. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12060. }
  12061. } else {
  12062. #if defined(MG_LEGACY_INTERFACE)
  12063. handle_websocket_request(
  12064. conn,
  12065. path,
  12066. !is_script_resource /* could be deprecated global callback */,
  12067. NULL,
  12068. deprecated_websocket_connect_wrapper,
  12069. deprecated_websocket_ready_wrapper,
  12070. deprecated_websocket_data_wrapper,
  12071. NULL,
  12072. conn->phys_ctx->user_data);
  12073. #else
  12074. mg_send_http_error(conn, 404, "%s", "Not found");
  12075. #endif
  12076. }
  12077. return;
  12078. } else
  12079. #endif
  12080. #if defined(NO_FILES)
  12081. /* 9a. In case the server uses only callbacks, this uri is
  12082. * unknown.
  12083. * Then, all request handling ends here. */
  12084. mg_send_http_error(conn, 404, "%s", "Not Found");
  12085. #else
  12086. /* 9b. This request is either for a static file or resource handled
  12087. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12088. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12089. mg_send_http_error(conn, 404, "%s", "Not Found");
  12090. return;
  12091. }
  12092. /* 10. Request is handled by a script */
  12093. if (is_script_resource) {
  12094. handle_file_based_request(conn, path, &file);
  12095. return;
  12096. }
  12097. /* 11. Handle put/delete/mkcol requests */
  12098. if (is_put_or_delete_request) {
  12099. /* 11.1. PUT method */
  12100. if (!strcmp(ri->request_method, "PUT")) {
  12101. put_file(conn, path);
  12102. return;
  12103. }
  12104. /* 11.2. DELETE method */
  12105. if (!strcmp(ri->request_method, "DELETE")) {
  12106. delete_file(conn, path);
  12107. return;
  12108. }
  12109. /* 11.3. MKCOL method */
  12110. if (!strcmp(ri->request_method, "MKCOL")) {
  12111. mkcol(conn, path);
  12112. return;
  12113. }
  12114. /* 11.4. PATCH method
  12115. * This method is not supported for static resources,
  12116. * only for scripts (Lua, CGI) and callbacks. */
  12117. mg_send_http_error(conn,
  12118. 405,
  12119. "%s method not allowed",
  12120. conn->request_info.request_method);
  12121. return;
  12122. }
  12123. /* 11. File does not exist, or it was configured that it should be
  12124. * hidden */
  12125. if (!is_found || (must_hide_file(conn, path))) {
  12126. mg_send_http_error(conn, 404, "%s", "Not found");
  12127. return;
  12128. }
  12129. /* 12. Directory uris should end with a slash */
  12130. if (file.stat.is_directory && (uri_len > 0)
  12131. && (ri->local_uri[uri_len - 1] != '/')) {
  12132. gmt_time_string(date, sizeof(date), &curtime);
  12133. mg_printf(conn,
  12134. "HTTP/1.1 301 Moved Permanently\r\n"
  12135. "Location: %s/\r\n"
  12136. "Date: %s\r\n"
  12137. /* "Cache-Control: private\r\n" (= default) */
  12138. "Content-Length: 0\r\n"
  12139. "Connection: %s\r\n",
  12140. ri->request_uri,
  12141. date,
  12142. suggest_connection_header(conn));
  12143. send_additional_header(conn);
  12144. mg_printf(conn, "\r\n");
  12145. return;
  12146. }
  12147. /* 13. Handle other methods than GET/HEAD */
  12148. /* 13.1. Handle PROPFIND */
  12149. if (!strcmp(ri->request_method, "PROPFIND")) {
  12150. handle_propfind(conn, path, &file.stat);
  12151. return;
  12152. }
  12153. /* 13.2. Handle OPTIONS for files */
  12154. if (!strcmp(ri->request_method, "OPTIONS")) {
  12155. /* This standard handler is only used for real files.
  12156. * Scripts should support the OPTIONS method themselves, to allow a
  12157. * maximum flexibility.
  12158. * Lua and CGI scripts may fully support CORS this way (including
  12159. * preflights). */
  12160. send_options(conn);
  12161. return;
  12162. }
  12163. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12164. if ((0 != strcmp(ri->request_method, "GET"))
  12165. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12166. mg_send_http_error(conn,
  12167. 405,
  12168. "%s method not allowed",
  12169. conn->request_info.request_method);
  12170. return;
  12171. }
  12172. /* 14. directories */
  12173. if (file.stat.is_directory) {
  12174. /* Substitute files have already been handled above. */
  12175. /* Here we can either generate and send a directory listing,
  12176. * or send an "access denied" error. */
  12177. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12178. "yes")) {
  12179. handle_directory_request(conn, path);
  12180. } else {
  12181. mg_send_http_error(conn,
  12182. 403,
  12183. "%s",
  12184. "Error: Directory listing denied");
  12185. }
  12186. return;
  12187. }
  12188. /* 15. read a normal file with GET or HEAD */
  12189. handle_file_based_request(conn, path, &file);
  12190. #endif /* !defined(NO_FILES) */
  12191. }
  12192. static void
  12193. handle_file_based_request(struct mg_connection *conn,
  12194. const char *path,
  12195. struct mg_file *file)
  12196. {
  12197. if (!conn || !conn->dom_ctx) {
  12198. return;
  12199. }
  12200. if (0) {
  12201. #if defined(USE_LUA)
  12202. } else if (match_prefix(
  12203. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12204. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12205. path)
  12206. > 0) {
  12207. if (is_in_script_path(conn, path)) {
  12208. /* Lua server page: an SSI like page containing mostly plain
  12209. * html
  12210. * code
  12211. * plus some tags with server generated contents. */
  12212. handle_lsp_request(conn, path, file, NULL);
  12213. } else {
  12214. /* Script was in an illegal path */
  12215. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12216. }
  12217. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12218. strlen(
  12219. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12220. path)
  12221. > 0) {
  12222. if (is_in_script_path(conn, path)) {
  12223. /* Lua in-server module script: a CGI like script used to
  12224. * generate
  12225. * the
  12226. * entire reply. */
  12227. mg_exec_lua_script(conn, path, NULL);
  12228. } else {
  12229. /* Script was in an illegal path */
  12230. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12231. }
  12232. #endif
  12233. #if defined(USE_DUKTAPE)
  12234. } else if (match_prefix(
  12235. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12236. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12237. path)
  12238. > 0) {
  12239. if (is_in_script_path(conn, path)) {
  12240. /* Call duktape to generate the page */
  12241. mg_exec_duktape_script(conn, path);
  12242. } else {
  12243. /* Script was in an illegal path */
  12244. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12245. }
  12246. #endif
  12247. #if !defined(NO_CGI)
  12248. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12249. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12250. path)
  12251. > 0) {
  12252. if (is_in_script_path(conn, path)) {
  12253. /* CGI scripts may support all HTTP methods */
  12254. handle_cgi_request(conn, path);
  12255. } else {
  12256. /* Script was in an illegal path */
  12257. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12258. }
  12259. #endif /* !NO_CGI */
  12260. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12261. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12262. path)
  12263. > 0) {
  12264. if (is_in_script_path(conn, path)) {
  12265. handle_ssi_file_request(conn, path, file);
  12266. } else {
  12267. /* Script was in an illegal path */
  12268. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12269. }
  12270. #if !defined(NO_CACHING)
  12271. } else if ((!conn->in_error_handler)
  12272. && is_not_modified(conn, &file->stat)) {
  12273. /* Send 304 "Not Modified" - this must not send any body data */
  12274. handle_not_modified_static_file_request(conn, file);
  12275. #endif /* !NO_CACHING */
  12276. } else {
  12277. handle_static_file_request(conn, path, file, NULL, NULL);
  12278. }
  12279. }
  12280. static void
  12281. close_all_listening_sockets(struct mg_context *ctx)
  12282. {
  12283. unsigned int i;
  12284. if (!ctx) {
  12285. return;
  12286. }
  12287. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12288. closesocket(ctx->listening_sockets[i].sock);
  12289. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12290. }
  12291. mg_free(ctx->listening_sockets);
  12292. ctx->listening_sockets = NULL;
  12293. mg_free(ctx->listening_socket_fds);
  12294. ctx->listening_socket_fds = NULL;
  12295. }
  12296. /* Valid listening port specification is: [ip_address:]port[s]
  12297. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12298. * Examples for IPv6: [::]:80, [::1]:80,
  12299. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12300. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12301. * In order to bind to both, IPv4 and IPv6, you can either add
  12302. * both ports using 8080,[::]:8080, or the short form +8080.
  12303. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12304. * one only accepting IPv4 the other only IPv6. +8080 creates
  12305. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12306. * environment, they might work differently, or might not work
  12307. * at all - it must be tested what options work best in the
  12308. * relevant network environment.
  12309. */
  12310. static int
  12311. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12312. {
  12313. unsigned int a, b, c, d, port;
  12314. int ch, len;
  12315. const char *cb;
  12316. #if defined(USE_IPV6)
  12317. char buf[100] = {0};
  12318. #endif
  12319. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12320. * Also, all-zeroes in the socket address means binding to all addresses
  12321. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12322. memset(so, 0, sizeof(*so));
  12323. so->lsa.sin.sin_family = AF_INET;
  12324. *ip_version = 0;
  12325. /* Initialize port and len as invalid. */
  12326. port = 0;
  12327. len = 0;
  12328. /* Test for different ways to format this string */
  12329. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12330. == 5) {
  12331. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12332. so->lsa.sin.sin_addr.s_addr =
  12333. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12334. so->lsa.sin.sin_port = htons((uint16_t)port);
  12335. *ip_version = 4;
  12336. #if defined(USE_IPV6)
  12337. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12338. && mg_inet_pton(
  12339. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12340. /* IPv6 address, examples: see above */
  12341. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12342. */
  12343. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12344. *ip_version = 6;
  12345. #endif
  12346. } else if ((vec->ptr[0] == '+')
  12347. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12348. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12349. /* Add 1 to len for the + character we skipped before */
  12350. len++;
  12351. #if defined(USE_IPV6)
  12352. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12353. so->lsa.sin6.sin6_family = AF_INET6;
  12354. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12355. *ip_version = 4 + 6;
  12356. #else
  12357. /* Bind to IPv4 only, since IPv6 is not built in. */
  12358. so->lsa.sin.sin_port = htons((uint16_t)port);
  12359. *ip_version = 4;
  12360. #endif
  12361. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  12362. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12363. so->lsa.sin.sin_port = htons((uint16_t)port);
  12364. *ip_version = 4;
  12365. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12366. /* String could be a hostname. This check algotithm
  12367. * will only work for RFC 952 compliant hostnames,
  12368. * starting with a letter, containing only letters,
  12369. * digits and hyphen ('-'). Newer specs may allow
  12370. * more, but this is not guaranteed here, since it
  12371. * may interfere with rules for port option lists. */
  12372. /* According to RFC 1035, hostnames are restricted to 255 characters
  12373. * in total (63 between two dots). */
  12374. char hostname[256];
  12375. size_t hostnlen = (size_t)(cb - vec->ptr);
  12376. if (hostnlen >= sizeof(hostname)) {
  12377. /* This would be invalid in any case */
  12378. *ip_version = 0;
  12379. return 0;
  12380. }
  12381. memcpy(hostname, vec->ptr, hostnlen);
  12382. hostname[hostnlen] = 0;
  12383. if (mg_inet_pton(
  12384. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12385. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12386. *ip_version = 4;
  12387. so->lsa.sin.sin_family = AF_INET;
  12388. so->lsa.sin.sin_port = htons((uint16_t)port);
  12389. len += (int)(hostnlen + 1);
  12390. } else {
  12391. port = 0;
  12392. len = 0;
  12393. }
  12394. #if defined(USE_IPV6)
  12395. } else if (mg_inet_pton(AF_INET6,
  12396. vec->ptr,
  12397. &so->lsa.sin6,
  12398. sizeof(so->lsa.sin6))) {
  12399. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12400. *ip_version = 6;
  12401. so->lsa.sin6.sin6_family = AF_INET6;
  12402. so->lsa.sin.sin_port = htons((uint16_t)port);
  12403. len += (int)(hostnlen + 1);
  12404. } else {
  12405. port = 0;
  12406. len = 0;
  12407. }
  12408. #endif
  12409. }
  12410. } else {
  12411. /* Parsing failure. */
  12412. }
  12413. /* sscanf and the option splitting code ensure the following condition
  12414. */
  12415. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12416. *ip_version = 0;
  12417. return 0;
  12418. }
  12419. ch = vec->ptr[len]; /* Next character after the port number */
  12420. so->is_ssl = (ch == 's');
  12421. so->ssl_redir = (ch == 'r');
  12422. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12423. if (is_valid_port(port)
  12424. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12425. return 1;
  12426. }
  12427. /* Reset ip_version to 0 if there is an error */
  12428. *ip_version = 0;
  12429. return 0;
  12430. }
  12431. /* Is there any SSL port in use? */
  12432. static int
  12433. is_ssl_port_used(const char *ports)
  12434. {
  12435. if (ports) {
  12436. /* There are several different allowed syntax variants:
  12437. * - "80" for a single port using every network interface
  12438. * - "localhost:80" for a single port using only localhost
  12439. * - "80,localhost:8080" for two ports, one bound to localhost
  12440. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12441. * to IPv4 localhost, one to IPv6 localhost
  12442. * - "+80" use port 80 for IPv4 and IPv6
  12443. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12444. * for both: IPv4 and IPv4
  12445. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12446. * additionally port 8080 bound to localhost connections
  12447. *
  12448. * If we just look for 's' anywhere in the string, "localhost:80"
  12449. * will be detected as SSL (false positive).
  12450. * Looking for 's' after a digit may cause false positives in
  12451. * "my24service:8080".
  12452. * Looking from 's' backward if there are only ':' and numbers
  12453. * before will not work for "24service:8080" (non SSL, port 8080)
  12454. * or "24s" (SSL, port 24).
  12455. *
  12456. * Remark: Initially hostnames were not allowed to start with a
  12457. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12458. * Section 2.1).
  12459. *
  12460. * To get this correct, the entire string must be parsed as a whole,
  12461. * reading it as a list element for element and parsing with an
  12462. * algorithm equivalent to parse_port_string.
  12463. *
  12464. * In fact, we use local interface names here, not arbitrary hostnames,
  12465. * so in most cases the only name will be "localhost".
  12466. *
  12467. * So, for now, we use this simple algorithm, that may still return
  12468. * a false positive in bizarre cases.
  12469. */
  12470. int i;
  12471. int portslen = (int)strlen(ports);
  12472. char prevIsNumber = 0;
  12473. for (i = 0; i < portslen; i++) {
  12474. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12475. return 1;
  12476. }
  12477. if (ports[i] >= '0' && ports[i] <= '9') {
  12478. prevIsNumber = 1;
  12479. } else {
  12480. prevIsNumber = 0;
  12481. }
  12482. }
  12483. }
  12484. return 0;
  12485. }
  12486. static int
  12487. set_ports_option(struct mg_context *phys_ctx)
  12488. {
  12489. const char *list;
  12490. int on = 1;
  12491. #if defined(USE_IPV6)
  12492. int off = 0;
  12493. #endif
  12494. struct vec vec;
  12495. struct socket so, *ptr;
  12496. struct mg_pollfd *pfd;
  12497. union usa usa;
  12498. socklen_t len;
  12499. int ip_version;
  12500. int portsTotal = 0;
  12501. int portsOk = 0;
  12502. if (!phys_ctx) {
  12503. return 0;
  12504. }
  12505. memset(&so, 0, sizeof(so));
  12506. memset(&usa, 0, sizeof(usa));
  12507. len = sizeof(usa);
  12508. list = phys_ctx->dd.config[LISTENING_PORTS];
  12509. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12510. portsTotal++;
  12511. if (!parse_port_string(&vec, &so, &ip_version)) {
  12512. mg_cry_internal(
  12513. fc(phys_ctx),
  12514. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12515. (int)vec.len,
  12516. vec.ptr,
  12517. portsTotal,
  12518. "[IP_ADDRESS:]PORT[s|r]");
  12519. continue;
  12520. }
  12521. #if !defined(NO_SSL)
  12522. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12523. mg_cry_internal(fc(phys_ctx),
  12524. "Cannot add SSL socket (entry %i)",
  12525. portsTotal);
  12526. continue;
  12527. }
  12528. #endif
  12529. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12530. == INVALID_SOCKET) {
  12531. mg_cry_internal(fc(phys_ctx),
  12532. "cannot create socket (entry %i)",
  12533. portsTotal);
  12534. continue;
  12535. }
  12536. #if defined(_WIN32)
  12537. /* Windows SO_REUSEADDR lets many procs binds to a
  12538. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12539. * if someone already has the socket -- DTL */
  12540. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12541. * Windows might need a few seconds before
  12542. * the same port can be used again in the
  12543. * same process, so a short Sleep may be
  12544. * required between mg_stop and mg_start.
  12545. */
  12546. if (setsockopt(so.sock,
  12547. SOL_SOCKET,
  12548. SO_EXCLUSIVEADDRUSE,
  12549. (SOCK_OPT_TYPE)&on,
  12550. sizeof(on))
  12551. != 0) {
  12552. /* Set reuse option, but don't abort on errors. */
  12553. mg_cry_internal(
  12554. fc(phys_ctx),
  12555. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12556. portsTotal);
  12557. }
  12558. #else
  12559. if (setsockopt(so.sock,
  12560. SOL_SOCKET,
  12561. SO_REUSEADDR,
  12562. (SOCK_OPT_TYPE)&on,
  12563. sizeof(on))
  12564. != 0) {
  12565. /* Set reuse option, but don't abort on errors. */
  12566. mg_cry_internal(fc(phys_ctx),
  12567. "cannot set socket option SO_REUSEADDR (entry %i)",
  12568. portsTotal);
  12569. }
  12570. #endif
  12571. if (ip_version > 4) {
  12572. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12573. #if defined(USE_IPV6)
  12574. if (ip_version > 6) {
  12575. if (so.lsa.sa.sa_family == AF_INET6
  12576. && setsockopt(so.sock,
  12577. IPPROTO_IPV6,
  12578. IPV6_V6ONLY,
  12579. (void *)&off,
  12580. sizeof(off))
  12581. != 0) {
  12582. /* Set IPv6 only option, but don't abort on errors. */
  12583. mg_cry_internal(
  12584. fc(phys_ctx),
  12585. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12586. portsTotal);
  12587. }
  12588. } else {
  12589. if (so.lsa.sa.sa_family == AF_INET6
  12590. && setsockopt(so.sock,
  12591. IPPROTO_IPV6,
  12592. IPV6_V6ONLY,
  12593. (void *)&on,
  12594. sizeof(on))
  12595. != 0) {
  12596. /* Set IPv6 only option, but don't abort on errors. */
  12597. mg_cry_internal(
  12598. fc(phys_ctx),
  12599. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12600. portsTotal);
  12601. }
  12602. }
  12603. #else
  12604. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  12605. closesocket(so.sock);
  12606. so.sock = INVALID_SOCKET;
  12607. continue;
  12608. #endif
  12609. }
  12610. if (so.lsa.sa.sa_family == AF_INET) {
  12611. len = sizeof(so.lsa.sin);
  12612. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12613. mg_cry_internal(fc(phys_ctx),
  12614. "cannot bind to %.*s: %d (%s)",
  12615. (int)vec.len,
  12616. vec.ptr,
  12617. (int)ERRNO,
  12618. strerror(errno));
  12619. closesocket(so.sock);
  12620. so.sock = INVALID_SOCKET;
  12621. continue;
  12622. }
  12623. }
  12624. #if defined(USE_IPV6)
  12625. else if (so.lsa.sa.sa_family == AF_INET6) {
  12626. len = sizeof(so.lsa.sin6);
  12627. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12628. mg_cry_internal(fc(phys_ctx),
  12629. "cannot bind to IPv6 %.*s: %d (%s)",
  12630. (int)vec.len,
  12631. vec.ptr,
  12632. (int)ERRNO,
  12633. strerror(errno));
  12634. closesocket(so.sock);
  12635. so.sock = INVALID_SOCKET;
  12636. continue;
  12637. }
  12638. }
  12639. #endif
  12640. else {
  12641. mg_cry_internal(
  12642. fc(phys_ctx),
  12643. "cannot bind: address family not supported (entry %i)",
  12644. portsTotal);
  12645. closesocket(so.sock);
  12646. so.sock = INVALID_SOCKET;
  12647. continue;
  12648. }
  12649. if (listen(so.sock, SOMAXCONN) != 0) {
  12650. mg_cry_internal(fc(phys_ctx),
  12651. "cannot listen to %.*s: %d (%s)",
  12652. (int)vec.len,
  12653. vec.ptr,
  12654. (int)ERRNO,
  12655. strerror(errno));
  12656. closesocket(so.sock);
  12657. so.sock = INVALID_SOCKET;
  12658. continue;
  12659. }
  12660. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12661. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12662. int err = (int)ERRNO;
  12663. mg_cry_internal(fc(phys_ctx),
  12664. "call to getsockname failed %.*s: %d (%s)",
  12665. (int)vec.len,
  12666. vec.ptr,
  12667. err,
  12668. strerror(errno));
  12669. closesocket(so.sock);
  12670. so.sock = INVALID_SOCKET;
  12671. continue;
  12672. }
  12673. /* Update lsa port in case of random free ports */
  12674. #if defined(USE_IPV6)
  12675. if (so.lsa.sa.sa_family == AF_INET6) {
  12676. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12677. } else
  12678. #endif
  12679. {
  12680. so.lsa.sin.sin_port = usa.sin.sin_port;
  12681. }
  12682. if ((ptr = (struct socket *)
  12683. mg_realloc_ctx(phys_ctx->listening_sockets,
  12684. (phys_ctx->num_listening_sockets + 1)
  12685. * sizeof(phys_ctx->listening_sockets[0]),
  12686. phys_ctx))
  12687. == NULL) {
  12688. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12689. closesocket(so.sock);
  12690. so.sock = INVALID_SOCKET;
  12691. continue;
  12692. }
  12693. if ((pfd = (struct mg_pollfd *)
  12694. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12695. (phys_ctx->num_listening_sockets + 1)
  12696. * sizeof(phys_ctx->listening_socket_fds[0]),
  12697. phys_ctx))
  12698. == NULL) {
  12699. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12700. closesocket(so.sock);
  12701. so.sock = INVALID_SOCKET;
  12702. mg_free(ptr);
  12703. continue;
  12704. }
  12705. set_close_on_exec(so.sock, fc(phys_ctx));
  12706. phys_ctx->listening_sockets = ptr;
  12707. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12708. phys_ctx->listening_socket_fds = pfd;
  12709. phys_ctx->num_listening_sockets++;
  12710. portsOk++;
  12711. }
  12712. if (portsOk != portsTotal) {
  12713. close_all_listening_sockets(phys_ctx);
  12714. portsOk = 0;
  12715. }
  12716. return portsOk;
  12717. }
  12718. static const char *
  12719. header_val(const struct mg_connection *conn, const char *header)
  12720. {
  12721. const char *header_value;
  12722. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12723. return "-";
  12724. } else {
  12725. return header_value;
  12726. }
  12727. }
  12728. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12729. static void log_access(const struct mg_connection *conn);
  12730. #include "external_log_access.inl"
  12731. #else
  12732. static void
  12733. log_access(const struct mg_connection *conn)
  12734. {
  12735. const struct mg_request_info *ri;
  12736. struct mg_file fi;
  12737. char date[64], src_addr[IP_ADDR_STR_LEN];
  12738. struct tm *tm;
  12739. const char *referer;
  12740. const char *user_agent;
  12741. char buf[4096];
  12742. if (!conn || !conn->dom_ctx) {
  12743. return;
  12744. }
  12745. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12746. if (mg_fopen(conn,
  12747. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12748. MG_FOPEN_MODE_APPEND,
  12749. &fi)
  12750. == 0) {
  12751. fi.access.fp = NULL;
  12752. }
  12753. } else {
  12754. fi.access.fp = NULL;
  12755. }
  12756. /* Log is written to a file and/or a callback. If both are not set,
  12757. * executing the rest of the function is pointless. */
  12758. if ((fi.access.fp == NULL)
  12759. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12760. return;
  12761. }
  12762. tm = localtime(&conn->conn_birth_time);
  12763. if (tm != NULL) {
  12764. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12765. } else {
  12766. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12767. date[sizeof(date) - 1] = '\0';
  12768. }
  12769. ri = &conn->request_info;
  12770. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12771. referer = header_val(conn, "Referer");
  12772. user_agent = header_val(conn, "User-Agent");
  12773. mg_snprintf(conn,
  12774. NULL, /* Ignore truncation in access log */
  12775. buf,
  12776. sizeof(buf),
  12777. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12778. src_addr,
  12779. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12780. date,
  12781. ri->request_method ? ri->request_method : "-",
  12782. ri->request_uri ? ri->request_uri : "-",
  12783. ri->query_string ? "?" : "",
  12784. ri->query_string ? ri->query_string : "",
  12785. ri->http_version,
  12786. conn->status_code,
  12787. conn->num_bytes_sent,
  12788. referer,
  12789. user_agent);
  12790. if (conn->phys_ctx->callbacks.log_access) {
  12791. conn->phys_ctx->callbacks.log_access(conn, buf);
  12792. }
  12793. if (fi.access.fp) {
  12794. int ok = 1;
  12795. flockfile(fi.access.fp);
  12796. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12797. ok = 0;
  12798. }
  12799. if (fflush(fi.access.fp) != 0) {
  12800. ok = 0;
  12801. }
  12802. funlockfile(fi.access.fp);
  12803. if (mg_fclose(&fi.access) != 0) {
  12804. ok = 0;
  12805. }
  12806. if (!ok) {
  12807. mg_cry_internal(conn,
  12808. "Error writing log file %s",
  12809. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12810. }
  12811. }
  12812. }
  12813. #endif /* Externally provided function */
  12814. /* Verify given socket address against the ACL.
  12815. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12816. */
  12817. static int
  12818. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12819. {
  12820. int allowed, flag;
  12821. uint32_t net, mask;
  12822. struct vec vec;
  12823. if (phys_ctx) {
  12824. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12825. /* If any ACL is set, deny by default */
  12826. allowed = (list == NULL) ? '+' : '-';
  12827. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12828. flag = vec.ptr[0];
  12829. if ((flag != '+' && flag != '-')
  12830. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12831. mg_cry_internal(fc(phys_ctx),
  12832. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12833. __func__);
  12834. return -1;
  12835. }
  12836. if (net == (remote_ip & mask)) {
  12837. allowed = flag;
  12838. }
  12839. }
  12840. return allowed == '+';
  12841. }
  12842. return -1;
  12843. }
  12844. #if !defined(_WIN32)
  12845. static int
  12846. set_uid_option(struct mg_context *phys_ctx)
  12847. {
  12848. int success = 0;
  12849. if (phys_ctx) {
  12850. /* We are currently running as curr_uid. */
  12851. const uid_t curr_uid = getuid();
  12852. /* If set, we want to run as run_as_user. */
  12853. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12854. const struct passwd *to_pw = NULL;
  12855. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12856. /* run_as_user does not exist on the system. We can't proceed
  12857. * further. */
  12858. mg_cry_internal(fc(phys_ctx),
  12859. "%s: unknown user [%s]",
  12860. __func__,
  12861. run_as_user);
  12862. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12863. /* There was either no request to change user, or we're already
  12864. * running as run_as_user. Nothing else to do.
  12865. */
  12866. success = 1;
  12867. } else {
  12868. /* Valid change request. */
  12869. if (setgid(to_pw->pw_gid) == -1) {
  12870. mg_cry_internal(fc(phys_ctx),
  12871. "%s: setgid(%s): %s",
  12872. __func__,
  12873. run_as_user,
  12874. strerror(errno));
  12875. } else if (setgroups(0, NULL) == -1) {
  12876. mg_cry_internal(fc(phys_ctx),
  12877. "%s: setgroups(): %s",
  12878. __func__,
  12879. strerror(errno));
  12880. } else if (setuid(to_pw->pw_uid) == -1) {
  12881. mg_cry_internal(fc(phys_ctx),
  12882. "%s: setuid(%s): %s",
  12883. __func__,
  12884. run_as_user,
  12885. strerror(errno));
  12886. } else {
  12887. success = 1;
  12888. }
  12889. }
  12890. }
  12891. return success;
  12892. }
  12893. #endif /* !_WIN32 */
  12894. static void
  12895. tls_dtor(void *key)
  12896. {
  12897. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12898. /* key == pthread_getspecific(sTlsKey); */
  12899. if (tls) {
  12900. if (tls->is_master == 2) {
  12901. tls->is_master = -3; /* Mark memory as dead */
  12902. mg_free(tls);
  12903. }
  12904. }
  12905. pthread_setspecific(sTlsKey, NULL);
  12906. }
  12907. #if !defined(NO_SSL)
  12908. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12909. struct mg_domain_context *dom_ctx,
  12910. const char *pem,
  12911. const char *chain);
  12912. static const char *ssl_error(void);
  12913. static int
  12914. refresh_trust(struct mg_connection *conn)
  12915. {
  12916. static int reload_lock = 0;
  12917. static long int data_check = 0;
  12918. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12919. struct stat cert_buf;
  12920. long int t;
  12921. const char *pem;
  12922. const char *chain;
  12923. int should_verify_peer;
  12924. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12925. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12926. * refresh_trust still can not work. */
  12927. return 0;
  12928. }
  12929. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12930. if (chain == NULL) {
  12931. /* pem is not NULL here */
  12932. chain = pem;
  12933. }
  12934. if (*chain == 0) {
  12935. chain = NULL;
  12936. }
  12937. t = data_check;
  12938. if (stat(pem, &cert_buf) != -1) {
  12939. t = (long int)cert_buf.st_mtime;
  12940. }
  12941. if (data_check != t) {
  12942. data_check = t;
  12943. should_verify_peer = 0;
  12944. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12945. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12946. == 0) {
  12947. should_verify_peer = 1;
  12948. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12949. "optional")
  12950. == 0) {
  12951. should_verify_peer = 1;
  12952. }
  12953. }
  12954. if (should_verify_peer) {
  12955. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12956. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12957. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12958. ca_file,
  12959. ca_path)
  12960. != 1) {
  12961. mg_cry_internal(
  12962. fc(conn->phys_ctx),
  12963. "SSL_CTX_load_verify_locations error: %s "
  12964. "ssl_verify_peer requires setting "
  12965. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12966. "present in "
  12967. "the .conf file?",
  12968. ssl_error());
  12969. return 0;
  12970. }
  12971. }
  12972. if (1 == mg_atomic_inc(p_reload_lock)) {
  12973. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12974. == 0) {
  12975. return 0;
  12976. }
  12977. *p_reload_lock = 0;
  12978. }
  12979. }
  12980. /* lock while cert is reloading */
  12981. while (*p_reload_lock) {
  12982. sleep(1);
  12983. }
  12984. return 1;
  12985. }
  12986. #if defined(OPENSSL_API_1_1)
  12987. #else
  12988. static pthread_mutex_t *ssl_mutexes;
  12989. #endif /* OPENSSL_API_1_1 */
  12990. static int
  12991. sslize(struct mg_connection *conn,
  12992. SSL_CTX *s,
  12993. int (*func)(SSL *),
  12994. volatile int *stop_server,
  12995. const struct mg_client_options *client_options)
  12996. {
  12997. int ret, err;
  12998. int short_trust;
  12999. unsigned timeout = 1024;
  13000. unsigned i;
  13001. if (!conn) {
  13002. return 0;
  13003. }
  13004. short_trust =
  13005. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13006. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13007. if (short_trust) {
  13008. int trust_ret = refresh_trust(conn);
  13009. if (!trust_ret) {
  13010. return trust_ret;
  13011. }
  13012. }
  13013. conn->ssl = SSL_new(s);
  13014. if (conn->ssl == NULL) {
  13015. return 0;
  13016. }
  13017. SSL_set_app_data(conn->ssl, (char *)conn);
  13018. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13019. if (ret != 1) {
  13020. err = SSL_get_error(conn->ssl, ret);
  13021. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13022. SSL_free(conn->ssl);
  13023. conn->ssl = NULL;
  13024. OPENSSL_REMOVE_THREAD_STATE();
  13025. return 0;
  13026. }
  13027. if (client_options) {
  13028. if (client_options->host_name) {
  13029. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13030. }
  13031. }
  13032. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13033. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13034. /* NOTE: The loop below acts as a back-off, so we can end
  13035. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13036. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13037. }
  13038. /* SSL functions may fail and require to be called again:
  13039. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13040. * Here "func" could be SSL_connect or SSL_accept. */
  13041. for (i = 0; i <= timeout; i += 50) {
  13042. ret = func(conn->ssl);
  13043. if (ret != 1) {
  13044. err = SSL_get_error(conn->ssl, ret);
  13045. if ((err == SSL_ERROR_WANT_CONNECT)
  13046. || (err == SSL_ERROR_WANT_ACCEPT)
  13047. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13048. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13049. if (*stop_server) {
  13050. /* Don't wait if the server is going to be stopped. */
  13051. break;
  13052. }
  13053. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13054. /* Simply retry the function call. */
  13055. mg_sleep(50);
  13056. } else {
  13057. /* Need to retry the function call "later".
  13058. * See https://linux.die.net/man/3/ssl_get_error
  13059. * This is typical for non-blocking sockets. */
  13060. struct mg_pollfd pfd;
  13061. pfd.fd = conn->client.sock;
  13062. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13063. || (err == SSL_ERROR_WANT_WRITE))
  13064. ? POLLOUT
  13065. : POLLIN;
  13066. mg_poll(&pfd, 1, 50, stop_server);
  13067. }
  13068. } else if (err == SSL_ERROR_SYSCALL) {
  13069. /* This is an IO error. Look at errno. */
  13070. err = errno;
  13071. mg_cry_internal(conn, "SSL syscall error %i", err);
  13072. break;
  13073. } else {
  13074. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13075. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13076. break;
  13077. }
  13078. ERR_clear_error();
  13079. } else {
  13080. /* success */
  13081. break;
  13082. }
  13083. }
  13084. if (ret != 1) {
  13085. SSL_free(conn->ssl);
  13086. conn->ssl = NULL;
  13087. OPENSSL_REMOVE_THREAD_STATE();
  13088. return 0;
  13089. }
  13090. return 1;
  13091. }
  13092. /* Return OpenSSL error message (from CRYPTO lib) */
  13093. static const char *
  13094. ssl_error(void)
  13095. {
  13096. unsigned long err;
  13097. err = ERR_get_error();
  13098. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13099. }
  13100. static int
  13101. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13102. {
  13103. int i;
  13104. const char hexdigit[] = "0123456789abcdef";
  13105. if ((memlen <= 0) || (buflen <= 0)) {
  13106. return 0;
  13107. }
  13108. if (buflen < (3 * memlen)) {
  13109. return 0;
  13110. }
  13111. for (i = 0; i < memlen; i++) {
  13112. if (i > 0) {
  13113. buf[3 * i - 1] = ' ';
  13114. }
  13115. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13116. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13117. }
  13118. buf[3 * memlen - 1] = 0;
  13119. return 1;
  13120. }
  13121. static void
  13122. ssl_get_client_cert_info(struct mg_connection *conn)
  13123. {
  13124. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13125. if (cert) {
  13126. char str_subject[1024];
  13127. char str_issuer[1024];
  13128. char str_finger[1024];
  13129. unsigned char buf[256];
  13130. char *str_serial = NULL;
  13131. unsigned int ulen;
  13132. int ilen;
  13133. unsigned char *tmp_buf;
  13134. unsigned char *tmp_p;
  13135. /* Handle to algorithm used for fingerprint */
  13136. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13137. /* Get Subject and issuer */
  13138. X509_NAME *subj = X509_get_subject_name(cert);
  13139. X509_NAME *iss = X509_get_issuer_name(cert);
  13140. /* Get serial number */
  13141. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13142. /* Translate serial number to a hex string */
  13143. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13144. str_serial = BN_bn2hex(serial_bn);
  13145. BN_free(serial_bn);
  13146. /* Translate subject and issuer to a string */
  13147. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13148. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13149. /* Calculate SHA1 fingerprint and store as a hex string */
  13150. ulen = 0;
  13151. /* ASN1_digest is deprecated. Do the calculation manually,
  13152. * using EVP_Digest. */
  13153. ilen = i2d_X509(cert, NULL);
  13154. tmp_buf = (ilen > 0)
  13155. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13156. conn->phys_ctx)
  13157. : NULL;
  13158. if (tmp_buf) {
  13159. tmp_p = tmp_buf;
  13160. (void)i2d_X509(cert, &tmp_p);
  13161. if (!EVP_Digest(
  13162. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13163. ulen = 0;
  13164. }
  13165. mg_free(tmp_buf);
  13166. }
  13167. if (!hexdump2string(
  13168. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13169. *str_finger = 0;
  13170. }
  13171. conn->request_info.client_cert = (struct mg_client_cert *)
  13172. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13173. if (conn->request_info.client_cert) {
  13174. conn->request_info.client_cert->peer_cert = (void *)cert;
  13175. conn->request_info.client_cert->subject =
  13176. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13177. conn->request_info.client_cert->issuer =
  13178. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13179. conn->request_info.client_cert->serial =
  13180. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13181. conn->request_info.client_cert->finger =
  13182. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13183. } else {
  13184. mg_cry_internal(conn,
  13185. "%s",
  13186. "Out of memory: Cannot allocate memory for client "
  13187. "certificate");
  13188. }
  13189. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13190. * see https://linux.die.net/man/3/bn_bn2hex */
  13191. OPENSSL_free(str_serial);
  13192. }
  13193. }
  13194. #if defined(OPENSSL_API_1_1)
  13195. #else
  13196. static void
  13197. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13198. {
  13199. (void)line;
  13200. (void)file;
  13201. if (mode & 1) {
  13202. /* 1 is CRYPTO_LOCK */
  13203. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13204. } else {
  13205. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13206. }
  13207. }
  13208. #endif /* OPENSSL_API_1_1 */
  13209. #if !defined(NO_SSL_DL)
  13210. static void *
  13211. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13212. {
  13213. union {
  13214. void *p;
  13215. void (*fp)(void);
  13216. } u;
  13217. void *dll_handle;
  13218. struct ssl_func *fp;
  13219. int ok;
  13220. int truncated = 0;
  13221. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13222. mg_snprintf(NULL,
  13223. NULL, /* No truncation check for ebuf */
  13224. ebuf,
  13225. ebuf_len,
  13226. "%s: cannot load %s",
  13227. __func__,
  13228. dll_name);
  13229. return NULL;
  13230. }
  13231. ok = 1;
  13232. for (fp = sw; fp->name != NULL; fp++) {
  13233. #if defined(_WIN32)
  13234. /* GetProcAddress() returns pointer to function */
  13235. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13236. #else
  13237. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13238. * pointers to function pointers. We need to use a union to make a
  13239. * cast. */
  13240. u.p = dlsym(dll_handle, fp->name);
  13241. #endif /* _WIN32 */
  13242. if (u.fp == NULL) {
  13243. if (ok) {
  13244. mg_snprintf(NULL,
  13245. &truncated,
  13246. ebuf,
  13247. ebuf_len,
  13248. "%s: %s: cannot find %s",
  13249. __func__,
  13250. dll_name,
  13251. fp->name);
  13252. ok = 0;
  13253. } else {
  13254. size_t cur_len = strlen(ebuf);
  13255. if (!truncated) {
  13256. mg_snprintf(NULL,
  13257. &truncated,
  13258. ebuf + cur_len,
  13259. ebuf_len - cur_len - 3,
  13260. ", %s",
  13261. fp->name);
  13262. if (truncated) {
  13263. /* If truncated, add "..." */
  13264. strcat(ebuf, "...");
  13265. }
  13266. }
  13267. }
  13268. /* Debug:
  13269. * printf("Missing function: %s\n", fp->name); */
  13270. } else {
  13271. fp->ptr = u.fp;
  13272. }
  13273. }
  13274. if (!ok) {
  13275. (void)dlclose(dll_handle);
  13276. return NULL;
  13277. }
  13278. return dll_handle;
  13279. }
  13280. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13281. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13282. #endif /* NO_SSL_DL */
  13283. #if defined(SSL_ALREADY_INITIALIZED)
  13284. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13285. #else
  13286. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13287. #endif
  13288. static int
  13289. initialize_ssl(char *ebuf, size_t ebuf_len)
  13290. {
  13291. #if defined(OPENSSL_API_1_1)
  13292. if (ebuf_len > 0) {
  13293. ebuf[0] = 0;
  13294. }
  13295. #if !defined(NO_SSL_DL)
  13296. if (!cryptolib_dll_handle) {
  13297. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13298. if (!cryptolib_dll_handle) {
  13299. mg_snprintf(NULL,
  13300. NULL, /* No truncation check for ebuf */
  13301. ebuf,
  13302. ebuf_len,
  13303. "%s: error loading library %s",
  13304. __func__,
  13305. CRYPTO_LIB);
  13306. DEBUG_TRACE("%s", ebuf);
  13307. return 0;
  13308. }
  13309. }
  13310. #endif /* NO_SSL_DL */
  13311. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13312. return 1;
  13313. }
  13314. #else /* not OPENSSL_API_1_1 */
  13315. int i, num_locks;
  13316. size_t size;
  13317. if (ebuf_len > 0) {
  13318. ebuf[0] = 0;
  13319. }
  13320. #if !defined(NO_SSL_DL)
  13321. if (!cryptolib_dll_handle) {
  13322. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13323. if (!cryptolib_dll_handle) {
  13324. mg_snprintf(NULL,
  13325. NULL, /* No truncation check for ebuf */
  13326. ebuf,
  13327. ebuf_len,
  13328. "%s: error loading library %s",
  13329. __func__,
  13330. CRYPTO_LIB);
  13331. DEBUG_TRACE("%s", ebuf);
  13332. return 0;
  13333. }
  13334. }
  13335. #endif /* NO_SSL_DL */
  13336. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13337. return 1;
  13338. }
  13339. /* Initialize locking callbacks, needed for thread safety.
  13340. * http://www.openssl.org/support/faq.html#PROG1
  13341. */
  13342. num_locks = CRYPTO_num_locks();
  13343. if (num_locks < 0) {
  13344. num_locks = 0;
  13345. }
  13346. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13347. /* allocate mutex array, if required */
  13348. if (num_locks == 0) {
  13349. /* No mutex array required */
  13350. ssl_mutexes = NULL;
  13351. } else {
  13352. /* Mutex array required - allocate it */
  13353. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13354. /* Check OOM */
  13355. if (ssl_mutexes == NULL) {
  13356. mg_snprintf(NULL,
  13357. NULL, /* No truncation check for ebuf */
  13358. ebuf,
  13359. ebuf_len,
  13360. "%s: cannot allocate mutexes: %s",
  13361. __func__,
  13362. ssl_error());
  13363. DEBUG_TRACE("%s", ebuf);
  13364. return 0;
  13365. }
  13366. /* initialize mutex array */
  13367. for (i = 0; i < num_locks; i++) {
  13368. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13369. mg_snprintf(NULL,
  13370. NULL, /* No truncation check for ebuf */
  13371. ebuf,
  13372. ebuf_len,
  13373. "%s: error initializing mutex %i of %i",
  13374. __func__,
  13375. i,
  13376. num_locks);
  13377. DEBUG_TRACE("%s", ebuf);
  13378. mg_free(ssl_mutexes);
  13379. return 0;
  13380. }
  13381. }
  13382. }
  13383. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13384. CRYPTO_set_id_callback(&mg_current_thread_id);
  13385. #endif /* OPENSSL_API_1_1 */
  13386. #if !defined(NO_SSL_DL)
  13387. if (!ssllib_dll_handle) {
  13388. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13389. if (!ssllib_dll_handle) {
  13390. #if !defined(OPENSSL_API_1_1)
  13391. mg_free(ssl_mutexes);
  13392. #endif
  13393. DEBUG_TRACE("%s", ebuf);
  13394. return 0;
  13395. }
  13396. }
  13397. #endif /* NO_SSL_DL */
  13398. #if defined(OPENSSL_API_1_1)
  13399. /* Initialize SSL library */
  13400. OPENSSL_init_ssl(0, NULL);
  13401. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13402. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13403. NULL);
  13404. #else
  13405. /* Initialize SSL library */
  13406. SSL_library_init();
  13407. SSL_load_error_strings();
  13408. #endif
  13409. return 1;
  13410. }
  13411. static int
  13412. ssl_use_pem_file(struct mg_context *phys_ctx,
  13413. struct mg_domain_context *dom_ctx,
  13414. const char *pem,
  13415. const char *chain)
  13416. {
  13417. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13418. mg_cry_internal(fc(phys_ctx),
  13419. "%s: cannot open certificate file %s: %s",
  13420. __func__,
  13421. pem,
  13422. ssl_error());
  13423. return 0;
  13424. }
  13425. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13426. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13427. mg_cry_internal(fc(phys_ctx),
  13428. "%s: cannot open private key file %s: %s",
  13429. __func__,
  13430. pem,
  13431. ssl_error());
  13432. return 0;
  13433. }
  13434. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13435. mg_cry_internal(fc(phys_ctx),
  13436. "%s: certificate and private key do not match: %s",
  13437. __func__,
  13438. pem);
  13439. return 0;
  13440. }
  13441. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13442. * chain files that contain private keys and certificates in
  13443. * SSL_CTX_use_certificate_chain_file.
  13444. * The CivetWeb-Server used pem-Files that contained both information.
  13445. * In order to make wolfSSL work, it is split in two files.
  13446. * One file that contains key and certificate used by the server and
  13447. * an optional chain file for the ssl stack.
  13448. */
  13449. if (chain) {
  13450. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13451. mg_cry_internal(fc(phys_ctx),
  13452. "%s: cannot use certificate chain file %s: %s",
  13453. __func__,
  13454. pem,
  13455. ssl_error());
  13456. return 0;
  13457. }
  13458. }
  13459. return 1;
  13460. }
  13461. #if defined(OPENSSL_API_1_1)
  13462. static unsigned long
  13463. ssl_get_protocol(int version_id)
  13464. {
  13465. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13466. if (version_id > 0)
  13467. ret |= SSL_OP_NO_SSLv2;
  13468. if (version_id > 1)
  13469. ret |= SSL_OP_NO_SSLv3;
  13470. if (version_id > 2)
  13471. ret |= SSL_OP_NO_TLSv1;
  13472. if (version_id > 3)
  13473. ret |= SSL_OP_NO_TLSv1_1;
  13474. if (version_id > 4)
  13475. ret |= SSL_OP_NO_TLSv1_2;
  13476. #if defined(SSL_OP_NO_TLSv1_3)
  13477. if (version_id > 5)
  13478. ret |= SSL_OP_NO_TLSv1_3;
  13479. #endif
  13480. return ret;
  13481. }
  13482. #else
  13483. static long
  13484. ssl_get_protocol(int version_id)
  13485. {
  13486. long ret = (long)SSL_OP_ALL;
  13487. if (version_id > 0)
  13488. ret |= SSL_OP_NO_SSLv2;
  13489. if (version_id > 1)
  13490. ret |= SSL_OP_NO_SSLv3;
  13491. if (version_id > 2)
  13492. ret |= SSL_OP_NO_TLSv1;
  13493. if (version_id > 3)
  13494. ret |= SSL_OP_NO_TLSv1_1;
  13495. if (version_id > 4)
  13496. ret |= SSL_OP_NO_TLSv1_2;
  13497. #if defined(SSL_OP_NO_TLSv1_3)
  13498. if (version_id > 5)
  13499. ret |= SSL_OP_NO_TLSv1_3;
  13500. #endif
  13501. return ret;
  13502. }
  13503. #endif /* OPENSSL_API_1_1 */
  13504. /* SSL callback documentation:
  13505. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13506. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13507. * https://linux.die.net/man/3/ssl_set_info_callback */
  13508. /* Note: There is no "const" for the first argument in the documentation
  13509. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13510. * / OpenSSL compatibility layers have it. Having a different definition will
  13511. * cause a warning in C and an error in C++. Use "const SSL *", while
  13512. * automatical conversion from "SSL *" works for all compilers, but not other
  13513. * way around */
  13514. static void
  13515. ssl_info_callback(const SSL *ssl, int what, int ret)
  13516. {
  13517. (void)ret;
  13518. if (what & SSL_CB_HANDSHAKE_START) {
  13519. SSL_get_app_data(ssl);
  13520. }
  13521. if (what & SSL_CB_HANDSHAKE_DONE) {
  13522. /* TODO: check for openSSL 1.1 */
  13523. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13524. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13525. }
  13526. }
  13527. static int
  13528. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13529. {
  13530. struct mg_context *ctx = (struct mg_context *)arg;
  13531. struct mg_domain_context *dom =
  13532. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13533. #if defined(GCC_DIAGNOSTIC)
  13534. #pragma GCC diagnostic push
  13535. #pragma GCC diagnostic ignored "-Wcast-align"
  13536. #endif /* defined(GCC_DIAGNOSTIC) */
  13537. /* We used an aligned pointer in SSL_set_app_data */
  13538. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13539. #if defined(GCC_DIAGNOSTIC)
  13540. #pragma GCC diagnostic pop
  13541. #endif /* defined(GCC_DIAGNOSTIC) */
  13542. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13543. (void)ad;
  13544. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13545. DEBUG_TRACE("%s", "internal error - assertion failed");
  13546. return SSL_TLSEXT_ERR_NOACK;
  13547. }
  13548. /* Old clients (Win XP) will not support SNI. Then, there
  13549. * is no server name available in the request - we can
  13550. * only work with the default certificate.
  13551. * Multiple HTTPS hosts on one IP+port are only possible
  13552. * with a certificate containing all alternative names.
  13553. */
  13554. if ((servername == NULL) || (*servername == 0)) {
  13555. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13556. conn->dom_ctx = &(ctx->dd);
  13557. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13558. return SSL_TLSEXT_ERR_NOACK;
  13559. }
  13560. DEBUG_TRACE("TLS connection to host %s", servername);
  13561. while (dom) {
  13562. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13563. /* Found matching domain */
  13564. DEBUG_TRACE("TLS domain %s found",
  13565. dom->config[AUTHENTICATION_DOMAIN]);
  13566. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13567. conn->dom_ctx = dom;
  13568. return SSL_TLSEXT_ERR_OK;
  13569. }
  13570. dom = dom->next;
  13571. }
  13572. /* Default domain */
  13573. DEBUG_TRACE("TLS default domain %s used",
  13574. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13575. conn->dom_ctx = &(ctx->dd);
  13576. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13577. return SSL_TLSEXT_ERR_OK;
  13578. }
  13579. /* Setup SSL CTX as required by CivetWeb */
  13580. static int
  13581. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13582. struct mg_domain_context *dom_ctx,
  13583. const char *pem,
  13584. const char *chain)
  13585. {
  13586. int callback_ret;
  13587. int should_verify_peer;
  13588. int peer_certificate_optional;
  13589. const char *ca_path;
  13590. const char *ca_file;
  13591. int use_default_verify_paths;
  13592. int verify_depth;
  13593. struct timespec now_mt;
  13594. md5_byte_t ssl_context_id[16];
  13595. md5_state_t md5state;
  13596. int protocol_ver;
  13597. #if defined(OPENSSL_API_1_1)
  13598. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13599. mg_cry_internal(fc(phys_ctx),
  13600. "SSL_CTX_new (server) error: %s",
  13601. ssl_error());
  13602. return 0;
  13603. }
  13604. #else
  13605. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13606. mg_cry_internal(fc(phys_ctx),
  13607. "SSL_CTX_new (server) error: %s",
  13608. ssl_error());
  13609. return 0;
  13610. }
  13611. #endif /* OPENSSL_API_1_1 */
  13612. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13613. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13614. | SSL_OP_NO_TLSv1_1);
  13615. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13616. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13617. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13618. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13619. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13620. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13621. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13622. #if defined(SSL_OP_NO_RENEGOTIATION)
  13623. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  13624. #endif
  13625. #if !defined(NO_SSL_DL)
  13626. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13627. #endif /* NO_SSL_DL */
  13628. /* In SSL documentation examples callback defined without const specifier
  13629. * 'void (*)(SSL *, int, int)' See:
  13630. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13631. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13632. * But in the source code const SSL is used:
  13633. * 'void (*)(const SSL *, int, int)' See:
  13634. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13635. * Problem about wrong documentation described, but not resolved:
  13636. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13637. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13638. * But when compiled with modern C++ compiler, correct const should be
  13639. * provided
  13640. */
  13641. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13642. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13643. ssl_servername_callback);
  13644. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13645. /* If a callback has been specified, call it. */
  13646. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13647. ? 0
  13648. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13649. phys_ctx->user_data));
  13650. /* If callback returns 0, civetweb sets up the SSL certificate.
  13651. * If it returns 1, civetweb assumes the calback already did this.
  13652. * If it returns -1, initializing ssl fails. */
  13653. if (callback_ret < 0) {
  13654. mg_cry_internal(fc(phys_ctx),
  13655. "SSL callback returned error: %i",
  13656. callback_ret);
  13657. return 0;
  13658. }
  13659. if (callback_ret > 0) {
  13660. /* Callback did everything. */
  13661. return 1;
  13662. }
  13663. /* Use some combination of start time, domain and port as a SSL
  13664. * context ID. This should be unique on the current machine. */
  13665. md5_init(&md5state);
  13666. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13667. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13668. md5_append(&md5state,
  13669. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13670. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13671. md5_append(&md5state,
  13672. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13673. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13674. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13675. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13676. md5_finish(&md5state, ssl_context_id);
  13677. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13678. (unsigned char *)ssl_context_id,
  13679. sizeof(ssl_context_id));
  13680. if (pem != NULL) {
  13681. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13682. return 0;
  13683. }
  13684. }
  13685. /* Should we support client certificates? */
  13686. /* Default is "no". */
  13687. should_verify_peer = 0;
  13688. peer_certificate_optional = 0;
  13689. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13690. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13691. /* Yes, they are mandatory */
  13692. should_verify_peer = 1;
  13693. peer_certificate_optional = 0;
  13694. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13695. "optional")
  13696. == 0) {
  13697. /* Yes, they are optional */
  13698. should_verify_peer = 1;
  13699. peer_certificate_optional = 1;
  13700. }
  13701. }
  13702. use_default_verify_paths =
  13703. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13704. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13705. == 0);
  13706. if (should_verify_peer) {
  13707. ca_path = dom_ctx->config[SSL_CA_PATH];
  13708. ca_file = dom_ctx->config[SSL_CA_FILE];
  13709. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13710. != 1) {
  13711. mg_cry_internal(fc(phys_ctx),
  13712. "SSL_CTX_load_verify_locations error: %s "
  13713. "ssl_verify_peer requires setting "
  13714. "either ssl_ca_path or ssl_ca_file. "
  13715. "Is any of them present in the "
  13716. ".conf file?",
  13717. ssl_error());
  13718. return 0;
  13719. }
  13720. if (peer_certificate_optional) {
  13721. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13722. } else {
  13723. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13724. SSL_VERIFY_PEER
  13725. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13726. NULL);
  13727. }
  13728. if (use_default_verify_paths
  13729. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13730. mg_cry_internal(fc(phys_ctx),
  13731. "SSL_CTX_set_default_verify_paths error: %s",
  13732. ssl_error());
  13733. return 0;
  13734. }
  13735. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13736. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13737. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13738. }
  13739. }
  13740. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13741. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13742. dom_ctx->config[SSL_CIPHER_LIST])
  13743. != 1) {
  13744. mg_cry_internal(fc(phys_ctx),
  13745. "SSL_CTX_set_cipher_list error: %s",
  13746. ssl_error());
  13747. }
  13748. }
  13749. return 1;
  13750. }
  13751. /* Check if SSL is required.
  13752. * If so, dynamically load SSL library
  13753. * and set up ctx->ssl_ctx pointer. */
  13754. static int
  13755. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13756. {
  13757. void *ssl_ctx = 0;
  13758. int callback_ret;
  13759. const char *pem;
  13760. const char *chain;
  13761. char ebuf[128];
  13762. if (!phys_ctx) {
  13763. return 0;
  13764. }
  13765. if (!dom_ctx) {
  13766. dom_ctx = &(phys_ctx->dd);
  13767. }
  13768. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13769. /* No SSL port is set. No need to setup SSL. */
  13770. return 1;
  13771. }
  13772. /* Check for external SSL_CTX */
  13773. callback_ret =
  13774. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13775. ? 0
  13776. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13777. phys_ctx->user_data));
  13778. if (callback_ret < 0) {
  13779. mg_cry_internal(fc(phys_ctx),
  13780. "external_ssl_ctx callback returned error: %i",
  13781. callback_ret);
  13782. return 0;
  13783. } else if (callback_ret > 0) {
  13784. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13785. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13786. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13787. return 0;
  13788. }
  13789. return 1;
  13790. }
  13791. /* else: external_ssl_ctx does not exist or returns 0,
  13792. * CivetWeb should continue initializing SSL */
  13793. /* If PEM file is not specified and the init_ssl callback
  13794. * is not specified, setup will fail. */
  13795. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13796. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13797. /* No certificate and no callback:
  13798. * Essential data to set up TLS is missing.
  13799. */
  13800. mg_cry_internal(fc(phys_ctx),
  13801. "Initializing SSL failed: -%s is not set",
  13802. config_options[SSL_CERTIFICATE].name);
  13803. return 0;
  13804. }
  13805. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13806. if (chain == NULL) {
  13807. chain = pem;
  13808. }
  13809. if ((chain != NULL) && (*chain == 0)) {
  13810. chain = NULL;
  13811. }
  13812. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13813. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13814. return 0;
  13815. }
  13816. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13817. }
  13818. static void
  13819. uninitialize_ssl(void)
  13820. {
  13821. #if defined(OPENSSL_API_1_1)
  13822. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13823. /* Shutdown according to
  13824. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13825. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13826. */
  13827. CONF_modules_unload(1);
  13828. #else
  13829. int i;
  13830. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13831. /* Shutdown according to
  13832. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13833. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13834. */
  13835. CRYPTO_set_locking_callback(NULL);
  13836. CRYPTO_set_id_callback(NULL);
  13837. ENGINE_cleanup();
  13838. CONF_modules_unload(1);
  13839. ERR_free_strings();
  13840. EVP_cleanup();
  13841. CRYPTO_cleanup_all_ex_data();
  13842. OPENSSL_REMOVE_THREAD_STATE();
  13843. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13844. pthread_mutex_destroy(&ssl_mutexes[i]);
  13845. }
  13846. mg_free(ssl_mutexes);
  13847. ssl_mutexes = NULL;
  13848. #endif /* OPENSSL_API_1_1 */
  13849. }
  13850. }
  13851. #endif /* !NO_SSL */
  13852. static int
  13853. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13854. {
  13855. if (phys_ctx) {
  13856. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13857. const char *path;
  13858. if (!dom_ctx) {
  13859. dom_ctx = &(phys_ctx->dd);
  13860. }
  13861. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13862. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  13863. mg_cry_internal(fc(phys_ctx),
  13864. "Cannot open %s: %s",
  13865. path,
  13866. strerror(ERRNO));
  13867. return 0;
  13868. }
  13869. return 1;
  13870. }
  13871. return 0;
  13872. }
  13873. static int
  13874. set_acl_option(struct mg_context *phys_ctx)
  13875. {
  13876. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13877. }
  13878. static void
  13879. reset_per_request_attributes(struct mg_connection *conn)
  13880. {
  13881. if (!conn) {
  13882. return;
  13883. }
  13884. conn->connection_type =
  13885. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13886. conn->num_bytes_sent = conn->consumed_content = 0;
  13887. conn->path_info = NULL;
  13888. conn->status_code = -1;
  13889. conn->content_len = -1;
  13890. conn->is_chunked = 0;
  13891. conn->must_close = 0;
  13892. conn->request_len = 0;
  13893. conn->throttle = 0;
  13894. conn->accept_gzip = 0;
  13895. conn->response_info.content_length = conn->request_info.content_length = -1;
  13896. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13897. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13898. conn->response_info.status_text = NULL;
  13899. conn->response_info.status_code = 0;
  13900. conn->request_info.remote_user = NULL;
  13901. conn->request_info.request_method = NULL;
  13902. conn->request_info.request_uri = NULL;
  13903. conn->request_info.local_uri = NULL;
  13904. #if defined(MG_LEGACY_INTERFACE)
  13905. /* Legacy before split into local_uri and request_uri */
  13906. conn->request_info.uri = NULL;
  13907. #endif
  13908. }
  13909. #if 0
  13910. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13911. * Leave this function here (commented out) for reference until
  13912. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13913. * no longer required.
  13914. */
  13915. static int
  13916. set_sock_timeout(SOCKET sock, int milliseconds)
  13917. {
  13918. int r0 = 0, r1, r2;
  13919. #if defined(_WIN32)
  13920. /* Windows specific */
  13921. DWORD tv = (DWORD)milliseconds;
  13922. #else
  13923. /* Linux, ... (not Windows) */
  13924. struct timeval tv;
  13925. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13926. * max. time waiting for the acknowledged of TCP data before the connection
  13927. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13928. * If this option is not set, the default timeout of 20-30 minutes is used.
  13929. */
  13930. /* #define TCP_USER_TIMEOUT (18) */
  13931. #if defined(TCP_USER_TIMEOUT)
  13932. unsigned int uto = (unsigned int)milliseconds;
  13933. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13934. #endif
  13935. memset(&tv, 0, sizeof(tv));
  13936. tv.tv_sec = milliseconds / 1000;
  13937. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13938. #endif /* _WIN32 */
  13939. r1 = setsockopt(
  13940. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13941. r2 = setsockopt(
  13942. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13943. return r0 || r1 || r2;
  13944. }
  13945. #endif
  13946. static int
  13947. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13948. {
  13949. if (setsockopt(sock,
  13950. IPPROTO_TCP,
  13951. TCP_NODELAY,
  13952. (SOCK_OPT_TYPE)&nodelay_on,
  13953. sizeof(nodelay_on))
  13954. != 0) {
  13955. /* Error */
  13956. return 1;
  13957. }
  13958. /* OK */
  13959. return 0;
  13960. }
  13961. static void
  13962. close_socket_gracefully(struct mg_connection *conn)
  13963. {
  13964. #if defined(_WIN32)
  13965. char buf[MG_BUF_LEN];
  13966. int n;
  13967. #endif
  13968. struct linger linger;
  13969. int error_code = 0;
  13970. int linger_timeout = -2;
  13971. socklen_t opt_len = sizeof(error_code);
  13972. if (!conn) {
  13973. return;
  13974. }
  13975. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13976. * "Note that enabling a nonzero timeout on a nonblocking socket
  13977. * is not recommended.", so set it to blocking now */
  13978. set_blocking_mode(conn->client.sock);
  13979. /* Send FIN to the client */
  13980. shutdown(conn->client.sock, SHUTDOWN_WR);
  13981. #if defined(_WIN32)
  13982. /* Read and discard pending incoming data. If we do not do that and
  13983. * close
  13984. * the socket, the data in the send buffer may be discarded. This
  13985. * behaviour is seen on Windows, when client keeps sending data
  13986. * when server decides to close the connection; then when client
  13987. * does recv() it gets no data back. */
  13988. do {
  13989. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13990. } while (n > 0);
  13991. #endif
  13992. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13993. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13994. }
  13995. /* Set linger option according to configuration */
  13996. if (linger_timeout >= 0) {
  13997. /* Set linger option to avoid socket hanging out after close. This
  13998. * prevent ephemeral port exhaust problem under high QPS. */
  13999. linger.l_onoff = 1;
  14000. #if defined(_MSC_VER)
  14001. #pragma warning(push)
  14002. #pragma warning(disable : 4244)
  14003. #endif
  14004. #if defined(GCC_DIAGNOSTIC)
  14005. #pragma GCC diagnostic push
  14006. #pragma GCC diagnostic ignored "-Wconversion"
  14007. #endif
  14008. /* Data type of linger structure elements may differ,
  14009. * so we don't know what cast we need here.
  14010. * Disable type conversion warnings. */
  14011. linger.l_linger = (linger_timeout + 999) / 1000;
  14012. #if defined(GCC_DIAGNOSTIC)
  14013. #pragma GCC diagnostic pop
  14014. #endif
  14015. #if defined(_MSC_VER)
  14016. #pragma warning(pop)
  14017. #endif
  14018. } else {
  14019. linger.l_onoff = 0;
  14020. linger.l_linger = 0;
  14021. }
  14022. if (linger_timeout < -1) {
  14023. /* Default: don't configure any linger */
  14024. } else if (getsockopt(conn->client.sock,
  14025. SOL_SOCKET,
  14026. SO_ERROR,
  14027. #if defined(_WIN32) /* WinSock uses different data type here */
  14028. (char *)&error_code,
  14029. #else
  14030. &error_code,
  14031. #endif
  14032. &opt_len)
  14033. != 0) {
  14034. /* Cannot determine if socket is already closed. This should
  14035. * not occur and never did in a test. Log an error message
  14036. * and continue. */
  14037. mg_cry_internal(conn,
  14038. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14039. __func__,
  14040. strerror(ERRNO));
  14041. #if defined(_WIN32)
  14042. } else if (error_code == WSAECONNRESET) {
  14043. #else
  14044. } else if (error_code == ECONNRESET) {
  14045. #endif
  14046. /* Socket already closed by client/peer, close socket without linger
  14047. */
  14048. } else {
  14049. /* Set linger timeout */
  14050. if (setsockopt(conn->client.sock,
  14051. SOL_SOCKET,
  14052. SO_LINGER,
  14053. (char *)&linger,
  14054. sizeof(linger))
  14055. != 0) {
  14056. mg_cry_internal(
  14057. conn,
  14058. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14059. __func__,
  14060. linger.l_onoff,
  14061. linger.l_linger,
  14062. strerror(ERRNO));
  14063. }
  14064. }
  14065. /* Now we know that our FIN is ACK-ed, safe to close */
  14066. closesocket(conn->client.sock);
  14067. conn->client.sock = INVALID_SOCKET;
  14068. }
  14069. static void
  14070. close_connection(struct mg_connection *conn)
  14071. {
  14072. #if defined(USE_SERVER_STATS)
  14073. conn->conn_state = 6; /* to close */
  14074. #endif
  14075. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14076. if (conn->lua_websocket_state) {
  14077. lua_websocket_close(conn, conn->lua_websocket_state);
  14078. conn->lua_websocket_state = NULL;
  14079. }
  14080. #endif
  14081. mg_lock_connection(conn);
  14082. /* Set close flag, so keep-alive loops will stop */
  14083. conn->must_close = 1;
  14084. /* call the connection_close callback if assigned */
  14085. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14086. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14087. conn->phys_ctx->callbacks.connection_close(conn);
  14088. }
  14089. }
  14090. /* Reset user data, after close callback is called.
  14091. * Do not reuse it. If the user needs a destructor,
  14092. * it must be done in the connection_close callback. */
  14093. mg_set_user_connection_data(conn, NULL);
  14094. #if defined(USE_SERVER_STATS)
  14095. conn->conn_state = 7; /* closing */
  14096. #endif
  14097. #if !defined(NO_SSL)
  14098. if (conn->ssl != NULL) {
  14099. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14100. */
  14101. SSL_shutdown(conn->ssl);
  14102. SSL_free(conn->ssl);
  14103. OPENSSL_REMOVE_THREAD_STATE();
  14104. conn->ssl = NULL;
  14105. }
  14106. #endif
  14107. if (conn->client.sock != INVALID_SOCKET) {
  14108. close_socket_gracefully(conn);
  14109. conn->client.sock = INVALID_SOCKET;
  14110. }
  14111. if (conn->host) {
  14112. mg_free((void *)conn->host);
  14113. conn->host = NULL;
  14114. }
  14115. mg_unlock_connection(conn);
  14116. #if defined(USE_SERVER_STATS)
  14117. conn->conn_state = 8; /* closed */
  14118. #endif
  14119. }
  14120. void
  14121. mg_close_connection(struct mg_connection *conn)
  14122. {
  14123. #if defined(USE_WEBSOCKET)
  14124. struct mg_context *client_ctx = NULL;
  14125. #endif /* defined(USE_WEBSOCKET) */
  14126. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14127. return;
  14128. }
  14129. #if defined(USE_WEBSOCKET)
  14130. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14131. if (conn->in_websocket_handling) {
  14132. /* Set close flag, so the server thread can exit. */
  14133. conn->must_close = 1;
  14134. return;
  14135. }
  14136. }
  14137. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14138. unsigned int i;
  14139. /* ws/wss client */
  14140. client_ctx = conn->phys_ctx;
  14141. /* client context: loops must end */
  14142. client_ctx->stop_flag = 1;
  14143. conn->must_close = 1;
  14144. /* We need to get the client thread out of the select/recv call
  14145. * here. */
  14146. /* Since we use a sleep quantum of some seconds to check for recv
  14147. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14148. /* join worker thread */
  14149. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  14150. if (client_ctx->worker_threadids[i] != 0) {
  14151. mg_join_thread(client_ctx->worker_threadids[i]);
  14152. }
  14153. }
  14154. }
  14155. #endif /* defined(USE_WEBSOCKET) */
  14156. close_connection(conn);
  14157. #if !defined(NO_SSL)
  14158. if (conn->client_ssl_ctx != NULL) {
  14159. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  14160. }
  14161. #endif
  14162. #if defined(USE_WEBSOCKET)
  14163. if (client_ctx != NULL) {
  14164. /* free context */
  14165. mg_free(client_ctx->worker_threadids);
  14166. mg_free(client_ctx);
  14167. (void)pthread_mutex_destroy(&conn->mutex);
  14168. mg_free(conn);
  14169. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14170. mg_free(conn);
  14171. }
  14172. #else
  14173. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14174. mg_free(conn);
  14175. }
  14176. #endif /* defined(USE_WEBSOCKET) */
  14177. }
  14178. /* Only for memory statistics */
  14179. static struct mg_context common_client_context;
  14180. static struct mg_connection *
  14181. mg_connect_client_impl(const struct mg_client_options *client_options,
  14182. int use_ssl,
  14183. char *ebuf,
  14184. size_t ebuf_len)
  14185. {
  14186. struct mg_connection *conn = NULL;
  14187. SOCKET sock;
  14188. union usa sa;
  14189. struct sockaddr *psa;
  14190. socklen_t len;
  14191. unsigned max_req_size =
  14192. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14193. /* Size of structures, aligned to 8 bytes */
  14194. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14195. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14196. conn = (struct mg_connection *)mg_calloc_ctx(
  14197. 1, conn_size + ctx_size + max_req_size, &common_client_context);
  14198. if (conn == NULL) {
  14199. mg_snprintf(NULL,
  14200. NULL, /* No truncation check for ebuf */
  14201. ebuf,
  14202. ebuf_len,
  14203. "calloc(): %s",
  14204. strerror(ERRNO));
  14205. return NULL;
  14206. }
  14207. #if defined(GCC_DIAGNOSTIC)
  14208. #pragma GCC diagnostic push
  14209. #pragma GCC diagnostic ignored "-Wcast-align"
  14210. #endif /* defined(GCC_DIAGNOSTIC) */
  14211. /* conn_size is aligned to 8 bytes */
  14212. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14213. #if defined(GCC_DIAGNOSTIC)
  14214. #pragma GCC diagnostic pop
  14215. #endif /* defined(GCC_DIAGNOSTIC) */
  14216. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14217. conn->buf_size = (int)max_req_size;
  14218. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14219. conn->dom_ctx = &(conn->phys_ctx->dd);
  14220. if (!connect_socket(&common_client_context,
  14221. client_options->host,
  14222. client_options->port,
  14223. use_ssl,
  14224. ebuf,
  14225. ebuf_len,
  14226. &sock,
  14227. &sa)) {
  14228. /* ebuf is set by connect_socket,
  14229. * free all memory and return NULL; */
  14230. mg_free(conn);
  14231. return NULL;
  14232. }
  14233. #if !defined(NO_SSL)
  14234. #if defined(OPENSSL_API_1_1)
  14235. if (use_ssl
  14236. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  14237. mg_snprintf(NULL,
  14238. NULL, /* No truncation check for ebuf */
  14239. ebuf,
  14240. ebuf_len,
  14241. "SSL_CTX_new error: %s",
  14242. ssl_error());
  14243. closesocket(sock);
  14244. mg_free(conn);
  14245. return NULL;
  14246. }
  14247. #else
  14248. if (use_ssl
  14249. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14250. == NULL) {
  14251. mg_snprintf(NULL,
  14252. NULL, /* No truncation check for ebuf */
  14253. ebuf,
  14254. ebuf_len,
  14255. "SSL_CTX_new error: %s",
  14256. ssl_error());
  14257. closesocket(sock);
  14258. mg_free(conn);
  14259. return NULL;
  14260. }
  14261. #endif /* OPENSSL_API_1_1 */
  14262. #endif /* NO_SSL */
  14263. #if defined(USE_IPV6)
  14264. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14265. : sizeof(conn->client.rsa.sin6);
  14266. psa = (sa.sa.sa_family == AF_INET)
  14267. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14268. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14269. #else
  14270. len = sizeof(conn->client.rsa.sin);
  14271. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14272. #endif
  14273. conn->client.sock = sock;
  14274. conn->client.lsa = sa;
  14275. if (getsockname(sock, psa, &len) != 0) {
  14276. mg_cry_internal(conn,
  14277. "%s: getsockname() failed: %s",
  14278. __func__,
  14279. strerror(ERRNO));
  14280. }
  14281. conn->client.is_ssl = use_ssl ? 1 : 0;
  14282. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14283. mg_snprintf(NULL,
  14284. NULL, /* No truncation check for ebuf */
  14285. ebuf,
  14286. ebuf_len,
  14287. "Can not create mutex");
  14288. #if !defined(NO_SSL)
  14289. SSL_CTX_free(conn->client_ssl_ctx);
  14290. #endif
  14291. closesocket(sock);
  14292. mg_free(conn);
  14293. return NULL;
  14294. }
  14295. #if !defined(NO_SSL)
  14296. if (use_ssl) {
  14297. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  14298. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14299. * SSL_CTX_set_verify call is needed to switch off server
  14300. * certificate checking, which is off by default in OpenSSL and
  14301. * on in yaSSL. */
  14302. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  14303. * SSL_VERIFY_PEER, verify_ssl_server); */
  14304. if (client_options->client_cert) {
  14305. if (!ssl_use_pem_file(&common_client_context,
  14306. &(common_client_context.dd),
  14307. client_options->client_cert,
  14308. NULL)) {
  14309. mg_snprintf(NULL,
  14310. NULL, /* No truncation check for ebuf */
  14311. ebuf,
  14312. ebuf_len,
  14313. "Can not use SSL client certificate");
  14314. SSL_CTX_free(conn->client_ssl_ctx);
  14315. closesocket(sock);
  14316. mg_free(conn);
  14317. return NULL;
  14318. }
  14319. }
  14320. if (client_options->server_cert) {
  14321. if (SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  14322. client_options->server_cert,
  14323. NULL)
  14324. != 1) {
  14325. mg_cry_internal(conn,
  14326. "SSL_CTX_load_verify_locations error: %s ",
  14327. ssl_error());
  14328. SSL_CTX_free(conn->client_ssl_ctx);
  14329. closesocket(sock);
  14330. mg_free(conn);
  14331. return NULL;
  14332. }
  14333. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  14334. } else {
  14335. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  14336. }
  14337. if (!sslize(conn,
  14338. conn->client_ssl_ctx,
  14339. SSL_connect,
  14340. &(conn->phys_ctx->stop_flag),
  14341. client_options)) {
  14342. mg_snprintf(NULL,
  14343. NULL, /* No truncation check for ebuf */
  14344. ebuf,
  14345. ebuf_len,
  14346. "SSL connection error");
  14347. SSL_CTX_free(conn->client_ssl_ctx);
  14348. closesocket(sock);
  14349. mg_free(conn);
  14350. return NULL;
  14351. }
  14352. }
  14353. #endif
  14354. if (0 != set_non_blocking_mode(sock)) {
  14355. mg_cry_internal(conn,
  14356. "Cannot set non-blocking mode for client %s:%i",
  14357. client_options->host,
  14358. client_options->port);
  14359. }
  14360. return conn;
  14361. }
  14362. CIVETWEB_API struct mg_connection *
  14363. mg_connect_client_secure(const struct mg_client_options *client_options,
  14364. char *error_buffer,
  14365. size_t error_buffer_size)
  14366. {
  14367. return mg_connect_client_impl(client_options,
  14368. 1,
  14369. error_buffer,
  14370. error_buffer_size);
  14371. }
  14372. struct mg_connection *
  14373. mg_connect_client(const char *host,
  14374. int port,
  14375. int use_ssl,
  14376. char *error_buffer,
  14377. size_t error_buffer_size)
  14378. {
  14379. struct mg_client_options opts;
  14380. memset(&opts, 0, sizeof(opts));
  14381. opts.host = host;
  14382. opts.port = port;
  14383. return mg_connect_client_impl(&opts,
  14384. use_ssl,
  14385. error_buffer,
  14386. error_buffer_size);
  14387. }
  14388. static const struct {
  14389. const char *proto;
  14390. size_t proto_len;
  14391. unsigned default_port;
  14392. } abs_uri_protocols[] = {{"http://", 7, 80},
  14393. {"https://", 8, 443},
  14394. {"ws://", 5, 80},
  14395. {"wss://", 6, 443},
  14396. {NULL, 0, 0}};
  14397. /* Check if the uri is valid.
  14398. * return 0 for invalid uri,
  14399. * return 1 for *,
  14400. * return 2 for relative uri,
  14401. * return 3 for absolute uri without port,
  14402. * return 4 for absolute uri with port */
  14403. static int
  14404. get_uri_type(const char *uri)
  14405. {
  14406. int i;
  14407. const char *hostend, *portbegin;
  14408. char *portend;
  14409. unsigned long port;
  14410. /* According to the HTTP standard
  14411. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14412. * URI can be an asterisk (*) or should start with slash (relative uri),
  14413. * or it should start with the protocol (absolute uri). */
  14414. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14415. /* asterisk */
  14416. return 1;
  14417. }
  14418. /* Valid URIs according to RFC 3986
  14419. * (https://www.ietf.org/rfc/rfc3986.txt)
  14420. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14421. * and unreserved characters A-Z a-z 0-9 and -._~
  14422. * and % encoded symbols.
  14423. */
  14424. for (i = 0; uri[i] != 0; i++) {
  14425. if (uri[i] < 33) {
  14426. /* control characters and spaces are invalid */
  14427. return 0;
  14428. }
  14429. if (uri[i] > 126) {
  14430. /* non-ascii characters must be % encoded */
  14431. return 0;
  14432. } else {
  14433. switch (uri[i]) {
  14434. case '"': /* 34 */
  14435. case '<': /* 60 */
  14436. case '>': /* 62 */
  14437. case '\\': /* 92 */
  14438. case '^': /* 94 */
  14439. case '`': /* 96 */
  14440. case '{': /* 123 */
  14441. case '|': /* 124 */
  14442. case '}': /* 125 */
  14443. return 0;
  14444. default:
  14445. /* character is ok */
  14446. break;
  14447. }
  14448. }
  14449. }
  14450. /* A relative uri starts with a / character */
  14451. if (uri[0] == '/') {
  14452. /* relative uri */
  14453. return 2;
  14454. }
  14455. /* It could be an absolute uri: */
  14456. /* This function only checks if the uri is valid, not if it is
  14457. * addressing the current server. So civetweb can also be used
  14458. * as a proxy server. */
  14459. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14460. if (mg_strncasecmp(uri,
  14461. abs_uri_protocols[i].proto,
  14462. abs_uri_protocols[i].proto_len)
  14463. == 0) {
  14464. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14465. if (!hostend) {
  14466. return 0;
  14467. }
  14468. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14469. if (!portbegin) {
  14470. return 3;
  14471. }
  14472. port = strtoul(portbegin + 1, &portend, 10);
  14473. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14474. return 0;
  14475. }
  14476. return 4;
  14477. }
  14478. }
  14479. return 0;
  14480. }
  14481. /* Return NULL or the relative uri at the current server */
  14482. static const char *
  14483. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14484. {
  14485. const char *server_domain;
  14486. size_t server_domain_len;
  14487. size_t request_domain_len = 0;
  14488. unsigned long port = 0;
  14489. int i, auth_domain_check_enabled;
  14490. const char *hostbegin = NULL;
  14491. const char *hostend = NULL;
  14492. const char *portbegin;
  14493. char *portend;
  14494. auth_domain_check_enabled =
  14495. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14496. /* DNS is case insensitive, so use case insensitive string compare here
  14497. */
  14498. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14499. if (mg_strncasecmp(uri,
  14500. abs_uri_protocols[i].proto,
  14501. abs_uri_protocols[i].proto_len)
  14502. == 0) {
  14503. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14504. hostend = strchr(hostbegin, '/');
  14505. if (!hostend) {
  14506. return 0;
  14507. }
  14508. portbegin = strchr(hostbegin, ':');
  14509. if ((!portbegin) || (portbegin > hostend)) {
  14510. port = abs_uri_protocols[i].default_port;
  14511. request_domain_len = (size_t)(hostend - hostbegin);
  14512. } else {
  14513. port = strtoul(portbegin + 1, &portend, 10);
  14514. if ((portend != hostend) || (port <= 0)
  14515. || !is_valid_port(port)) {
  14516. return 0;
  14517. }
  14518. request_domain_len = (size_t)(portbegin - hostbegin);
  14519. }
  14520. /* protocol found, port set */
  14521. break;
  14522. }
  14523. }
  14524. if (!port) {
  14525. /* port remains 0 if the protocol is not found */
  14526. return 0;
  14527. }
  14528. /* Check if the request is directed to a different server. */
  14529. /* First check if the port is the same (IPv4 and IPv6). */
  14530. #if defined(USE_IPV6)
  14531. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14532. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14533. /* Request is directed to a different port */
  14534. return 0;
  14535. }
  14536. } else
  14537. #endif
  14538. {
  14539. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14540. /* Request is directed to a different port */
  14541. return 0;
  14542. }
  14543. }
  14544. /* Finally check if the server corresponds to the authentication
  14545. * domain of the server (the server domain).
  14546. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14547. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14548. * but do not allow substrings (like
  14549. * http://notmydomain.com/path/file.ext
  14550. * or http://mydomain.com.fake/path/file.ext).
  14551. */
  14552. if (auth_domain_check_enabled) {
  14553. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14554. server_domain_len = strlen(server_domain);
  14555. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14556. return 0;
  14557. }
  14558. if ((request_domain_len == server_domain_len)
  14559. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14560. /* Request is directed to this server - full name match. */
  14561. } else {
  14562. if (request_domain_len < (server_domain_len + 2)) {
  14563. /* Request is directed to another server: The server name
  14564. * is longer than the request name.
  14565. * Drop this case here to avoid overflows in the
  14566. * following checks. */
  14567. return 0;
  14568. }
  14569. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14570. /* Request is directed to another server: It could be a
  14571. * substring
  14572. * like notmyserver.com */
  14573. return 0;
  14574. }
  14575. if (0
  14576. != memcmp(server_domain,
  14577. hostbegin + request_domain_len - server_domain_len,
  14578. server_domain_len)) {
  14579. /* Request is directed to another server:
  14580. * The server name is different. */
  14581. return 0;
  14582. }
  14583. }
  14584. }
  14585. return hostend;
  14586. }
  14587. static int
  14588. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14589. {
  14590. if (ebuf_len > 0) {
  14591. ebuf[0] = '\0';
  14592. }
  14593. *err = 0;
  14594. reset_per_request_attributes(conn);
  14595. if (!conn) {
  14596. mg_snprintf(conn,
  14597. NULL, /* No truncation check for ebuf */
  14598. ebuf,
  14599. ebuf_len,
  14600. "%s",
  14601. "Internal error");
  14602. *err = 500;
  14603. return 0;
  14604. }
  14605. /* Set the time the request was received. This value should be used for
  14606. * timeouts. */
  14607. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14608. conn->request_len =
  14609. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14610. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14611. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14612. mg_snprintf(conn,
  14613. NULL, /* No truncation check for ebuf */
  14614. ebuf,
  14615. ebuf_len,
  14616. "%s",
  14617. "Invalid message size");
  14618. *err = 500;
  14619. return 0;
  14620. }
  14621. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14622. mg_snprintf(conn,
  14623. NULL, /* No truncation check for ebuf */
  14624. ebuf,
  14625. ebuf_len,
  14626. "%s",
  14627. "Message too large");
  14628. *err = 413;
  14629. return 0;
  14630. }
  14631. if (conn->request_len <= 0) {
  14632. if (conn->data_len > 0) {
  14633. mg_snprintf(conn,
  14634. NULL, /* No truncation check for ebuf */
  14635. ebuf,
  14636. ebuf_len,
  14637. "%s",
  14638. "Malformed message");
  14639. *err = 400;
  14640. } else {
  14641. /* Server did not recv anything -> just close the connection */
  14642. conn->must_close = 1;
  14643. mg_snprintf(conn,
  14644. NULL, /* No truncation check for ebuf */
  14645. ebuf,
  14646. ebuf_len,
  14647. "%s",
  14648. "No data received");
  14649. *err = 0;
  14650. }
  14651. return 0;
  14652. }
  14653. return 1;
  14654. }
  14655. static int
  14656. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14657. {
  14658. const char *cl;
  14659. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14660. return 0;
  14661. }
  14662. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14663. <= 0) {
  14664. mg_snprintf(conn,
  14665. NULL, /* No truncation check for ebuf */
  14666. ebuf,
  14667. ebuf_len,
  14668. "%s",
  14669. "Bad request");
  14670. *err = 400;
  14671. return 0;
  14672. }
  14673. /* Message is a valid request */
  14674. /* Is there a "host" ? */
  14675. if (conn->host != NULL) {
  14676. mg_free((void *)conn->host);
  14677. }
  14678. conn->host = alloc_get_host(conn);
  14679. if (!conn->host) {
  14680. mg_snprintf(conn,
  14681. NULL, /* No truncation check for ebuf */
  14682. ebuf,
  14683. ebuf_len,
  14684. "%s",
  14685. "Bad request: Host mismatch");
  14686. *err = 400;
  14687. return 0;
  14688. }
  14689. if (((cl = get_header(conn->request_info.http_headers,
  14690. conn->request_info.num_headers,
  14691. "Transfer-Encoding")) != NULL)
  14692. && mg_strcasecmp(cl, "identity")) {
  14693. if (mg_strcasecmp(cl, "chunked")) {
  14694. mg_snprintf(conn,
  14695. NULL, /* No truncation check for ebuf */
  14696. ebuf,
  14697. ebuf_len,
  14698. "%s",
  14699. "Bad request");
  14700. *err = 400;
  14701. return 0;
  14702. }
  14703. conn->is_chunked = 1;
  14704. conn->content_len = 0; /* not yet read */
  14705. } else if ((cl = get_header(conn->request_info.http_headers,
  14706. conn->request_info.num_headers,
  14707. "Content-Length")) != NULL) {
  14708. /* Request has content length set */
  14709. char *endptr = NULL;
  14710. conn->content_len = strtoll(cl, &endptr, 10);
  14711. if ((endptr == cl) || (conn->content_len < 0)) {
  14712. mg_snprintf(conn,
  14713. NULL, /* No truncation check for ebuf */
  14714. ebuf,
  14715. ebuf_len,
  14716. "%s",
  14717. "Bad request");
  14718. *err = 411;
  14719. return 0;
  14720. }
  14721. /* Publish the content length back to the request info. */
  14722. conn->request_info.content_length = conn->content_len;
  14723. } else {
  14724. /* There is no exception, see RFC7230. */
  14725. conn->content_len = 0;
  14726. }
  14727. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14728. return 1;
  14729. }
  14730. /* conn is assumed to be valid in this internal function */
  14731. static int
  14732. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14733. {
  14734. const char *cl;
  14735. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14736. return 0;
  14737. }
  14738. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14739. <= 0) {
  14740. mg_snprintf(conn,
  14741. NULL, /* No truncation check for ebuf */
  14742. ebuf,
  14743. ebuf_len,
  14744. "%s",
  14745. "Bad response");
  14746. *err = 400;
  14747. return 0;
  14748. }
  14749. /* Message is a valid response */
  14750. if (((cl = get_header(conn->response_info.http_headers,
  14751. conn->response_info.num_headers,
  14752. "Transfer-Encoding")) != NULL)
  14753. && mg_strcasecmp(cl, "identity")) {
  14754. if (mg_strcasecmp(cl, "chunked")) {
  14755. mg_snprintf(conn,
  14756. NULL, /* No truncation check for ebuf */
  14757. ebuf,
  14758. ebuf_len,
  14759. "%s",
  14760. "Bad request");
  14761. *err = 400;
  14762. return 0;
  14763. }
  14764. conn->is_chunked = 1;
  14765. conn->content_len = 0; /* not yet read */
  14766. } else if ((cl = get_header(conn->response_info.http_headers,
  14767. conn->response_info.num_headers,
  14768. "Content-Length")) != NULL) {
  14769. char *endptr = NULL;
  14770. conn->content_len = strtoll(cl, &endptr, 10);
  14771. if ((endptr == cl) || (conn->content_len < 0)) {
  14772. mg_snprintf(conn,
  14773. NULL, /* No truncation check for ebuf */
  14774. ebuf,
  14775. ebuf_len,
  14776. "%s",
  14777. "Bad request");
  14778. *err = 411;
  14779. return 0;
  14780. }
  14781. /* Publish the content length back to the response info. */
  14782. conn->response_info.content_length = conn->content_len;
  14783. /* TODO: check if it is still used in response_info */
  14784. conn->request_info.content_length = conn->content_len;
  14785. /* TODO: we should also consider HEAD method */
  14786. if (conn->response_info.status_code == 304) {
  14787. conn->content_len = 0;
  14788. }
  14789. } else {
  14790. /* TODO: we should also consider HEAD method */
  14791. if (((conn->response_info.status_code >= 100)
  14792. && (conn->response_info.status_code <= 199))
  14793. || (conn->response_info.status_code == 204)
  14794. || (conn->response_info.status_code == 304)) {
  14795. conn->content_len = 0;
  14796. } else {
  14797. conn->content_len = -1; /* unknown content length */
  14798. }
  14799. }
  14800. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14801. return 1;
  14802. }
  14803. int
  14804. mg_get_response(struct mg_connection *conn,
  14805. char *ebuf,
  14806. size_t ebuf_len,
  14807. int timeout)
  14808. {
  14809. int err, ret;
  14810. char txt[32]; /* will not overflow */
  14811. char *save_timeout;
  14812. char *new_timeout;
  14813. if (ebuf_len > 0) {
  14814. ebuf[0] = '\0';
  14815. }
  14816. if (!conn) {
  14817. mg_snprintf(conn,
  14818. NULL, /* No truncation check for ebuf */
  14819. ebuf,
  14820. ebuf_len,
  14821. "%s",
  14822. "Parameter error");
  14823. return -1;
  14824. }
  14825. /* Reset the previous responses */
  14826. conn->data_len = 0;
  14827. /* Implementation of API function for HTTP clients */
  14828. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14829. if (timeout >= 0) {
  14830. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14831. new_timeout = txt;
  14832. /* Not required for non-blocking sockets.
  14833. set_sock_timeout(conn->client.sock, timeout);
  14834. */
  14835. } else {
  14836. new_timeout = NULL;
  14837. }
  14838. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14839. ret = get_response(conn, ebuf, ebuf_len, &err);
  14840. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14841. #if defined(MG_LEGACY_INTERFACE)
  14842. /* TODO: 1) uri is deprecated;
  14843. * 2) here, ri.uri is the http response code */
  14844. conn->request_info.uri = conn->request_info.request_uri;
  14845. #endif
  14846. conn->request_info.local_uri = conn->request_info.request_uri;
  14847. /* TODO (mid): Define proper return values - maybe return length?
  14848. * For the first test use <0 for error and >0 for OK */
  14849. return (ret == 0) ? -1 : +1;
  14850. }
  14851. struct mg_connection *
  14852. mg_download(const char *host,
  14853. int port,
  14854. int use_ssl,
  14855. char *ebuf,
  14856. size_t ebuf_len,
  14857. const char *fmt,
  14858. ...)
  14859. {
  14860. struct mg_connection *conn;
  14861. va_list ap;
  14862. int i;
  14863. int reqerr;
  14864. if (ebuf_len > 0) {
  14865. ebuf[0] = '\0';
  14866. }
  14867. va_start(ap, fmt);
  14868. /* open a connection */
  14869. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14870. if (conn != NULL) {
  14871. i = mg_vprintf(conn, fmt, ap);
  14872. if (i <= 0) {
  14873. mg_snprintf(conn,
  14874. NULL, /* No truncation check for ebuf */
  14875. ebuf,
  14876. ebuf_len,
  14877. "%s",
  14878. "Error sending request");
  14879. } else {
  14880. /* make sure the buffer is clear */
  14881. conn->data_len = 0;
  14882. get_response(conn, ebuf, ebuf_len, &reqerr);
  14883. #if defined(MG_LEGACY_INTERFACE)
  14884. /* TODO: 1) uri is deprecated;
  14885. * 2) here, ri.uri is the http response code */
  14886. conn->request_info.uri = conn->request_info.request_uri;
  14887. #endif
  14888. conn->request_info.local_uri = conn->request_info.request_uri;
  14889. }
  14890. }
  14891. /* if an error occurred, close the connection */
  14892. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14893. mg_close_connection(conn);
  14894. conn = NULL;
  14895. }
  14896. va_end(ap);
  14897. return conn;
  14898. }
  14899. struct websocket_client_thread_data {
  14900. struct mg_connection *conn;
  14901. mg_websocket_data_handler data_handler;
  14902. mg_websocket_close_handler close_handler;
  14903. void *callback_data;
  14904. };
  14905. #if defined(USE_WEBSOCKET)
  14906. #if defined(_WIN32)
  14907. static unsigned __stdcall websocket_client_thread(void *data)
  14908. #else
  14909. static void *
  14910. websocket_client_thread(void *data)
  14911. #endif
  14912. {
  14913. struct websocket_client_thread_data *cdata =
  14914. (struct websocket_client_thread_data *)data;
  14915. void *user_thread_ptr = NULL;
  14916. #if !defined(_WIN32)
  14917. struct sigaction sa;
  14918. /* Ignore SIGPIPE */
  14919. memset(&sa, 0, sizeof(sa));
  14920. sa.sa_handler = SIG_IGN;
  14921. sigaction(SIGPIPE, &sa, NULL);
  14922. #endif
  14923. mg_set_thread_name("ws-clnt");
  14924. if (cdata->conn->phys_ctx) {
  14925. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14926. /* 3 indicates a websocket client thread */
  14927. /* TODO: check if conn->phys_ctx can be set */
  14928. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  14929. cdata->conn->phys_ctx, 3);
  14930. }
  14931. }
  14932. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14933. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14934. if (cdata->close_handler != NULL) {
  14935. cdata->close_handler(cdata->conn, cdata->callback_data);
  14936. }
  14937. /* The websocket_client context has only this thread. If it runs out,
  14938. set the stop_flag to 2 (= "stopped"). */
  14939. cdata->conn->phys_ctx->stop_flag = 2;
  14940. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  14941. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  14942. 3,
  14943. user_thread_ptr);
  14944. }
  14945. mg_free((void *)cdata);
  14946. #if defined(_WIN32)
  14947. return 0;
  14948. #else
  14949. return NULL;
  14950. #endif
  14951. }
  14952. #endif
  14953. struct mg_connection *
  14954. mg_connect_websocket_client(const char *host,
  14955. int port,
  14956. int use_ssl,
  14957. char *error_buffer,
  14958. size_t error_buffer_size,
  14959. const char *path,
  14960. const char *origin,
  14961. mg_websocket_data_handler data_func,
  14962. mg_websocket_close_handler close_func,
  14963. void *user_data)
  14964. {
  14965. struct mg_connection *conn = NULL;
  14966. #if defined(USE_WEBSOCKET)
  14967. struct mg_context *newctx = NULL;
  14968. struct websocket_client_thread_data *thread_data;
  14969. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14970. static const char *handshake_req;
  14971. if (origin != NULL) {
  14972. handshake_req = "GET %s HTTP/1.1\r\n"
  14973. "Host: %s\r\n"
  14974. "Upgrade: websocket\r\n"
  14975. "Connection: Upgrade\r\n"
  14976. "Sec-WebSocket-Key: %s\r\n"
  14977. "Sec-WebSocket-Version: 13\r\n"
  14978. "Origin: %s\r\n"
  14979. "\r\n";
  14980. } else {
  14981. handshake_req = "GET %s HTTP/1.1\r\n"
  14982. "Host: %s\r\n"
  14983. "Upgrade: websocket\r\n"
  14984. "Connection: Upgrade\r\n"
  14985. "Sec-WebSocket-Key: %s\r\n"
  14986. "Sec-WebSocket-Version: 13\r\n"
  14987. "\r\n";
  14988. }
  14989. #if defined(__clang__)
  14990. #pragma clang diagnostic push
  14991. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  14992. #endif
  14993. /* Establish the client connection and request upgrade */
  14994. conn = mg_download(host,
  14995. port,
  14996. use_ssl,
  14997. error_buffer,
  14998. error_buffer_size,
  14999. handshake_req,
  15000. path,
  15001. host,
  15002. magic,
  15003. origin);
  15004. #if defined(__clang__)
  15005. #pragma clang diagnostic pop
  15006. #endif
  15007. /* Connection object will be null if something goes wrong */
  15008. if (conn == NULL) {
  15009. if (!*error_buffer) {
  15010. /* There should be already an error message */
  15011. mg_snprintf(conn,
  15012. NULL, /* No truncation check for ebuf */
  15013. error_buffer,
  15014. error_buffer_size,
  15015. "Unexpected error");
  15016. }
  15017. return NULL;
  15018. }
  15019. if (conn->response_info.status_code != 101) {
  15020. /* We sent an "upgrade" request. For a correct websocket
  15021. * protocol handshake, we expect a "101 Continue" response.
  15022. * Otherwise it is a protocol violation. Maybe the HTTP
  15023. * Server does not know websockets. */
  15024. if (!*error_buffer) {
  15025. /* set an error, if not yet set */
  15026. mg_snprintf(conn,
  15027. NULL, /* No truncation check for ebuf */
  15028. error_buffer,
  15029. error_buffer_size,
  15030. "Unexpected server reply");
  15031. }
  15032. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15033. mg_free(conn);
  15034. return NULL;
  15035. }
  15036. /* For client connections, mg_context is fake. Since we need to set a
  15037. * callback function, we need to create a copy and modify it. */
  15038. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  15039. if (!newctx) {
  15040. DEBUG_TRACE("%s\r\n", "Out of memory");
  15041. mg_free(conn);
  15042. return NULL;
  15043. }
  15044. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  15045. newctx->user_data = user_data;
  15046. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  15047. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  15048. newctx->worker_threadids =
  15049. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  15050. sizeof(pthread_t),
  15051. newctx);
  15052. conn->phys_ctx = newctx;
  15053. conn->dom_ctx = &(newctx->dd);
  15054. thread_data = (struct websocket_client_thread_data *)
  15055. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  15056. if (!thread_data) {
  15057. DEBUG_TRACE("%s\r\n", "Out of memory");
  15058. mg_free(newctx);
  15059. mg_free(conn);
  15060. return NULL;
  15061. }
  15062. thread_data->conn = conn;
  15063. thread_data->data_handler = data_func;
  15064. thread_data->close_handler = close_func;
  15065. thread_data->callback_data = user_data;
  15066. /* Start a thread to read the websocket client connection
  15067. * This thread will automatically stop when mg_disconnect is
  15068. * called on the client connection */
  15069. if (mg_start_thread_with_id(websocket_client_thread,
  15070. (void *)thread_data,
  15071. newctx->worker_threadids)
  15072. != 0) {
  15073. mg_free((void *)thread_data);
  15074. mg_free((void *)newctx->worker_threadids);
  15075. mg_free((void *)newctx);
  15076. mg_free((void *)conn);
  15077. conn = NULL;
  15078. DEBUG_TRACE("%s",
  15079. "Websocket client connect thread could not be started\r\n");
  15080. }
  15081. #else
  15082. /* Appease "unused parameter" warnings */
  15083. (void)host;
  15084. (void)port;
  15085. (void)use_ssl;
  15086. (void)error_buffer;
  15087. (void)error_buffer_size;
  15088. (void)path;
  15089. (void)origin;
  15090. (void)user_data;
  15091. (void)data_func;
  15092. (void)close_func;
  15093. #endif
  15094. return conn;
  15095. }
  15096. /* Prepare connection data structure */
  15097. static void
  15098. init_connection(struct mg_connection *conn)
  15099. {
  15100. /* Is keep alive allowed by the server */
  15101. int keep_alive_enabled =
  15102. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15103. if (!keep_alive_enabled) {
  15104. conn->must_close = 1;
  15105. }
  15106. /* Important: on new connection, reset the receiving buffer. Credit
  15107. * goes to crule42. */
  15108. conn->data_len = 0;
  15109. conn->handled_requests = 0;
  15110. mg_set_user_connection_data(conn, NULL);
  15111. #if defined(USE_SERVER_STATS)
  15112. conn->conn_state = 2; /* init */
  15113. #endif
  15114. /* call the init_connection callback if assigned */
  15115. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15116. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15117. void *conn_data = NULL;
  15118. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15119. mg_set_user_connection_data(conn, conn_data);
  15120. }
  15121. }
  15122. }
  15123. /* Process a connection - may handle multiple requests
  15124. * using the same connection.
  15125. * Must be called with a valid connection (conn and
  15126. * conn->phys_ctx must be valid).
  15127. */
  15128. static void
  15129. process_new_connection(struct mg_connection *conn)
  15130. {
  15131. struct mg_request_info *ri = &conn->request_info;
  15132. int keep_alive, discard_len;
  15133. char ebuf[100];
  15134. const char *hostend;
  15135. int reqerr, uri_type;
  15136. #if defined(USE_SERVER_STATS)
  15137. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15138. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15139. if (mcon > (conn->phys_ctx->max_connections)) {
  15140. /* could use atomic compare exchange, but this
  15141. * seems overkill for statistics data */
  15142. conn->phys_ctx->max_connections = mcon;
  15143. }
  15144. #endif
  15145. init_connection(conn);
  15146. DEBUG_TRACE("Start processing connection from %s",
  15147. conn->request_info.remote_addr);
  15148. /* Loop over multiple requests sent using the same connection
  15149. * (while "keep alive"). */
  15150. do {
  15151. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15152. conn->handled_requests + 1);
  15153. #if defined(USE_SERVER_STATS)
  15154. conn->conn_state = 3; /* ready */
  15155. #endif
  15156. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15157. /* The request sent by the client could not be understood by
  15158. * the server, or it was incomplete or a timeout. Send an
  15159. * error message and close the connection. */
  15160. if (reqerr > 0) {
  15161. DEBUG_ASSERT(ebuf[0] != '\0');
  15162. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15163. }
  15164. } else if (strcmp(ri->http_version, "1.0")
  15165. && strcmp(ri->http_version, "1.1")) {
  15166. mg_snprintf(conn,
  15167. NULL, /* No truncation check for ebuf */
  15168. ebuf,
  15169. sizeof(ebuf),
  15170. "Bad HTTP version: [%s]",
  15171. ri->http_version);
  15172. mg_send_http_error(conn, 505, "%s", ebuf);
  15173. }
  15174. if (ebuf[0] == '\0') {
  15175. uri_type = get_uri_type(conn->request_info.request_uri);
  15176. switch (uri_type) {
  15177. case 1:
  15178. /* Asterisk */
  15179. conn->request_info.local_uri = NULL;
  15180. break;
  15181. case 2:
  15182. /* relative uri */
  15183. conn->request_info.local_uri = conn->request_info.request_uri;
  15184. break;
  15185. case 3:
  15186. case 4:
  15187. /* absolute uri (with/without port) */
  15188. hostend = get_rel_url_at_current_server(
  15189. conn->request_info.request_uri, conn);
  15190. if (hostend) {
  15191. conn->request_info.local_uri = hostend;
  15192. } else {
  15193. conn->request_info.local_uri = NULL;
  15194. }
  15195. break;
  15196. default:
  15197. mg_snprintf(conn,
  15198. NULL, /* No truncation check for ebuf */
  15199. ebuf,
  15200. sizeof(ebuf),
  15201. "Invalid URI");
  15202. mg_send_http_error(conn, 400, "%s", ebuf);
  15203. conn->request_info.local_uri = NULL;
  15204. break;
  15205. }
  15206. #if defined(MG_LEGACY_INTERFACE)
  15207. /* Legacy before split into local_uri and request_uri */
  15208. conn->request_info.uri = conn->request_info.local_uri;
  15209. #endif
  15210. }
  15211. DEBUG_TRACE("http: %s, error: %s",
  15212. (ri->http_version ? ri->http_version : "none"),
  15213. (ebuf[0] ? ebuf : "none"));
  15214. if (ebuf[0] == '\0') {
  15215. if (conn->request_info.local_uri) {
  15216. /* handle request to local server */
  15217. #if defined(USE_SERVER_STATS)
  15218. conn->conn_state = 4; /* processing */
  15219. #endif
  15220. handle_request(conn);
  15221. #if defined(USE_SERVER_STATS)
  15222. conn->conn_state = 5; /* processed */
  15223. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15224. conn->consumed_content);
  15225. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15226. conn->num_bytes_sent);
  15227. #endif
  15228. DEBUG_TRACE("%s", "handle_request done");
  15229. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15230. conn->phys_ctx->callbacks.end_request(conn,
  15231. conn->status_code);
  15232. DEBUG_TRACE("%s", "end_request callback done");
  15233. }
  15234. log_access(conn);
  15235. } else {
  15236. /* TODO: handle non-local request (PROXY) */
  15237. conn->must_close = 1;
  15238. }
  15239. } else {
  15240. conn->must_close = 1;
  15241. }
  15242. if (ri->remote_user != NULL) {
  15243. mg_free((void *)ri->remote_user);
  15244. /* Important! When having connections with and without auth
  15245. * would cause double free and then crash */
  15246. ri->remote_user = NULL;
  15247. }
  15248. /* NOTE(lsm): order is important here. should_keep_alive() call
  15249. * is using parsed request, which will be invalid after
  15250. * memmove's below.
  15251. * Therefore, memorize should_keep_alive() result now for later
  15252. * use in loop exit condition. */
  15253. /* Enable it only if this request is completely discardable. */
  15254. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15255. && (conn->content_len >= 0) && (conn->request_len > 0)
  15256. && ((conn->is_chunked == 4)
  15257. || (!conn->is_chunked
  15258. && ((conn->consumed_content == conn->content_len)
  15259. || ((conn->request_len + conn->content_len)
  15260. <= conn->data_len))));
  15261. if (keep_alive) {
  15262. /* Discard all buffered data for this request */
  15263. discard_len = ((conn->request_len + conn->content_len)
  15264. < conn->data_len)
  15265. ? (int)(conn->request_len + conn->content_len)
  15266. : conn->data_len;
  15267. conn->data_len -= discard_len;
  15268. if (conn->data_len > 0) {
  15269. DEBUG_TRACE("discard_len = %d", discard_len);
  15270. memmove(conn->buf, conn->buf + discard_len,
  15271. (size_t)conn->data_len);
  15272. }
  15273. }
  15274. DEBUG_ASSERT(conn->data_len >= 0);
  15275. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15276. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15277. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15278. (long int)conn->data_len,
  15279. (long int)conn->buf_size);
  15280. break;
  15281. }
  15282. conn->handled_requests++;
  15283. } while (keep_alive);
  15284. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15285. conn->request_info.remote_addr,
  15286. difftime(time(NULL), conn->conn_birth_time));
  15287. close_connection(conn);
  15288. #if defined(USE_SERVER_STATS)
  15289. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15290. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15291. #endif
  15292. }
  15293. #if defined(ALTERNATIVE_QUEUE)
  15294. static void
  15295. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15296. {
  15297. unsigned int i;
  15298. while (!ctx->stop_flag) {
  15299. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15300. /* find a free worker slot and signal it */
  15301. if (ctx->client_socks[i].in_use == 2) {
  15302. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15303. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15304. ctx->client_socks[i] = *sp;
  15305. ctx->client_socks[i].in_use = 1;
  15306. /* socket has been moved to the consumer */
  15307. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15308. (void)event_signal(ctx->client_wait_events[i]);
  15309. return;
  15310. }
  15311. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15312. }
  15313. }
  15314. /* queue is full */
  15315. mg_sleep(1);
  15316. }
  15317. /* must consume */
  15318. set_blocking_mode(sp->sock);
  15319. closesocket(sp->sock);
  15320. }
  15321. static int
  15322. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15323. {
  15324. DEBUG_TRACE("%s", "going idle");
  15325. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15326. ctx->client_socks[thread_index].in_use = 2;
  15327. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15328. event_wait(ctx->client_wait_events[thread_index]);
  15329. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15330. *sp = ctx->client_socks[thread_index];
  15331. if (ctx->stop_flag) {
  15332. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15333. if (sp->in_use == 1) {
  15334. /* must consume */
  15335. set_blocking_mode(sp->sock);
  15336. closesocket(sp->sock);
  15337. }
  15338. return 0;
  15339. }
  15340. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15341. if (sp->in_use == 1) {
  15342. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15343. return 1;
  15344. }
  15345. /* must not reach here */
  15346. DEBUG_ASSERT(0);
  15347. return 0;
  15348. }
  15349. #else /* ALTERNATIVE_QUEUE */
  15350. /* Worker threads take accepted socket from the queue */
  15351. static int
  15352. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15353. {
  15354. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15355. (void)thread_index;
  15356. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15357. DEBUG_TRACE("%s", "going idle");
  15358. /* If the queue is empty, wait. We're idle at this point. */
  15359. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15360. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15361. }
  15362. /* If we're stopping, sq_head may be equal to sq_tail. */
  15363. if (ctx->sq_head > ctx->sq_tail) {
  15364. /* Copy socket from the queue and increment tail */
  15365. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15366. ctx->sq_tail++;
  15367. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15368. /* Wrap pointers if needed */
  15369. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15370. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15371. ctx->sq_head -= QUEUE_SIZE(ctx);
  15372. }
  15373. }
  15374. (void)pthread_cond_signal(&ctx->sq_empty);
  15375. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15376. return !ctx->stop_flag;
  15377. #undef QUEUE_SIZE
  15378. }
  15379. /* Master thread adds accepted socket to a queue */
  15380. static void
  15381. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15382. {
  15383. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15384. if (!ctx) {
  15385. return;
  15386. }
  15387. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15388. /* If the queue is full, wait */
  15389. while ((ctx->stop_flag == 0)
  15390. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15391. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15392. }
  15393. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15394. /* Copy socket to the queue and increment head */
  15395. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15396. ctx->sq_head++;
  15397. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15398. }
  15399. (void)pthread_cond_signal(&ctx->sq_full);
  15400. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15401. #undef QUEUE_SIZE
  15402. }
  15403. #endif /* ALTERNATIVE_QUEUE */
  15404. static void
  15405. worker_thread_run(struct mg_connection *conn)
  15406. {
  15407. struct mg_context *ctx = conn->phys_ctx;
  15408. int thread_index;
  15409. struct mg_workerTLS tls;
  15410. #if defined(MG_LEGACY_INTERFACE)
  15411. uint32_t addr;
  15412. #endif
  15413. mg_set_thread_name("worker");
  15414. tls.is_master = 0;
  15415. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15416. #if defined(_WIN32)
  15417. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15418. #endif
  15419. /* Initialize thread local storage before calling any callback */
  15420. pthread_setspecific(sTlsKey, &tls);
  15421. /* Check if there is a user callback */
  15422. if (ctx->callbacks.init_thread) {
  15423. /* call init_thread for a worker thread (type 1), and store the return
  15424. * value */
  15425. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  15426. } else {
  15427. /* No callback: set user pointer to NULL */
  15428. tls.user_ptr = NULL;
  15429. }
  15430. /* Connection structure has been pre-allocated */
  15431. thread_index = (int)(conn - ctx->worker_connections);
  15432. if ((thread_index < 0)
  15433. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  15434. mg_cry_internal(fc(ctx),
  15435. "Internal error: Invalid worker index %i",
  15436. thread_index);
  15437. return;
  15438. }
  15439. /* Request buffers are not pre-allocated. They are private to the
  15440. * request and do not contain any state information that might be
  15441. * of interest to anyone observing a server status. */
  15442. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15443. if (conn->buf == NULL) {
  15444. mg_cry_internal(fc(ctx),
  15445. "Out of memory: Cannot allocate buffer for worker %i",
  15446. thread_index);
  15447. return;
  15448. }
  15449. conn->buf_size = (int)ctx->max_request_size;
  15450. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15451. conn->host = NULL; /* until we have more information. */
  15452. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  15453. conn->request_info.user_data = ctx->user_data;
  15454. /* Allocate a mutex for this connection to allow communication both
  15455. * within the request handler and from elsewhere in the application
  15456. */
  15457. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15458. mg_free(conn->buf);
  15459. mg_cry_internal(fc(ctx), "%s", "Cannot create mutex");
  15460. return;
  15461. }
  15462. #if defined(USE_SERVER_STATS)
  15463. conn->conn_state = 1; /* not consumed */
  15464. #endif
  15465. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15466. * signal sq_empty condvar to wake up the master waiting in
  15467. * produce_socket() */
  15468. while (consume_socket(ctx, &conn->client, thread_index)) {
  15469. conn->conn_birth_time = time(NULL);
  15470. /* Fill in IP, port info early so even if SSL setup below fails,
  15471. * error handler would have the corresponding info.
  15472. * Thanks to Johannes Winkelmann for the patch.
  15473. */
  15474. #if defined(USE_IPV6)
  15475. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15476. conn->request_info.remote_port =
  15477. ntohs(conn->client.rsa.sin6.sin6_port);
  15478. } else
  15479. #endif
  15480. {
  15481. conn->request_info.remote_port =
  15482. ntohs(conn->client.rsa.sin.sin_port);
  15483. }
  15484. sockaddr_to_string(conn->request_info.remote_addr,
  15485. sizeof(conn->request_info.remote_addr),
  15486. &conn->client.rsa);
  15487. DEBUG_TRACE("Start processing connection from %s",
  15488. conn->request_info.remote_addr);
  15489. conn->request_info.is_ssl = conn->client.is_ssl;
  15490. if (conn->client.is_ssl) {
  15491. #if !defined(NO_SSL)
  15492. /* HTTPS connection */
  15493. if (sslize(conn,
  15494. conn->dom_ctx->ssl_ctx,
  15495. SSL_accept,
  15496. &(conn->phys_ctx->stop_flag),
  15497. NULL)) {
  15498. /* conn->dom_ctx is set in get_request */
  15499. /* Get SSL client certificate information (if set) */
  15500. ssl_get_client_cert_info(conn);
  15501. /* process HTTPS connection */
  15502. process_new_connection(conn);
  15503. /* Free client certificate info */
  15504. if (conn->request_info.client_cert) {
  15505. mg_free((void *)(conn->request_info.client_cert->subject));
  15506. mg_free((void *)(conn->request_info.client_cert->issuer));
  15507. mg_free((void *)(conn->request_info.client_cert->serial));
  15508. mg_free((void *)(conn->request_info.client_cert->finger));
  15509. /* Free certificate memory */
  15510. X509_free(
  15511. (X509 *)conn->request_info.client_cert->peer_cert);
  15512. conn->request_info.client_cert->peer_cert = 0;
  15513. conn->request_info.client_cert->subject = 0;
  15514. conn->request_info.client_cert->issuer = 0;
  15515. conn->request_info.client_cert->serial = 0;
  15516. conn->request_info.client_cert->finger = 0;
  15517. mg_free(conn->request_info.client_cert);
  15518. conn->request_info.client_cert = 0;
  15519. }
  15520. } else {
  15521. /* make sure the connection is cleaned up on SSL failure */
  15522. close_connection(conn);
  15523. }
  15524. #endif
  15525. } else {
  15526. /* process HTTP connection */
  15527. process_new_connection(conn);
  15528. }
  15529. DEBUG_TRACE("%s", "Connection closed");
  15530. }
  15531. /* Call exit thread user callback */
  15532. if (ctx->callbacks.exit_thread) {
  15533. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  15534. }
  15535. /* delete thread local storage objects */
  15536. pthread_setspecific(sTlsKey, NULL);
  15537. #if defined(_WIN32)
  15538. CloseHandle(tls.pthread_cond_helper_mutex);
  15539. #endif
  15540. pthread_mutex_destroy(&conn->mutex);
  15541. /* Free the request buffer. */
  15542. conn->buf_size = 0;
  15543. mg_free(conn->buf);
  15544. conn->buf = NULL;
  15545. #if defined(USE_SERVER_STATS)
  15546. conn->conn_state = 9; /* done */
  15547. #endif
  15548. DEBUG_TRACE("%s", "exiting");
  15549. }
  15550. /* Threads have different return types on Windows and Unix. */
  15551. #if defined(_WIN32)
  15552. static unsigned __stdcall worker_thread(void *thread_func_param)
  15553. {
  15554. worker_thread_run((struct mg_connection *)thread_func_param);
  15555. return 0;
  15556. }
  15557. #else
  15558. static void *
  15559. worker_thread(void *thread_func_param)
  15560. {
  15561. struct sigaction sa;
  15562. /* Ignore SIGPIPE */
  15563. memset(&sa, 0, sizeof(sa));
  15564. sa.sa_handler = SIG_IGN;
  15565. sigaction(SIGPIPE, &sa, NULL);
  15566. worker_thread_run((struct mg_connection *)thread_func_param);
  15567. return NULL;
  15568. }
  15569. #endif /* _WIN32 */
  15570. /* This is an internal function, thus all arguments are expected to be
  15571. * valid - a NULL check is not required. */
  15572. static void
  15573. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15574. {
  15575. struct socket so;
  15576. char src_addr[IP_ADDR_STR_LEN];
  15577. socklen_t len = sizeof(so.rsa);
  15578. int on = 1;
  15579. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15580. == INVALID_SOCKET) {
  15581. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15582. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15583. mg_cry_internal(fc(ctx),
  15584. "%s: %s is not allowed to connect",
  15585. __func__,
  15586. src_addr);
  15587. closesocket(so.sock);
  15588. } else {
  15589. /* Put so socket structure into the queue */
  15590. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15591. set_close_on_exec(so.sock, fc(ctx));
  15592. so.is_ssl = listener->is_ssl;
  15593. so.ssl_redir = listener->ssl_redir;
  15594. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15595. mg_cry_internal(fc(ctx),
  15596. "%s: getsockname() failed: %s",
  15597. __func__,
  15598. strerror(ERRNO));
  15599. }
  15600. /* Set TCP keep-alive. This is needed because if HTTP-level
  15601. * keep-alive
  15602. * is enabled, and client resets the connection, server won't get
  15603. * TCP FIN or RST and will keep the connection open forever. With
  15604. * TCP keep-alive, next keep-alive handshake will figure out that
  15605. * the client is down and will close the server end.
  15606. * Thanks to Igor Klopov who suggested the patch. */
  15607. if (setsockopt(so.sock,
  15608. SOL_SOCKET,
  15609. SO_KEEPALIVE,
  15610. (SOCK_OPT_TYPE)&on,
  15611. sizeof(on))
  15612. != 0) {
  15613. mg_cry_internal(
  15614. fc(ctx),
  15615. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15616. __func__,
  15617. strerror(ERRNO));
  15618. }
  15619. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15620. * to effectively fill up the underlying IP packet payload and
  15621. * reduce the overhead of sending lots of small buffers. However
  15622. * this hurts the server's throughput (ie. operations per second)
  15623. * when HTTP 1.1 persistent connections are used and the responses
  15624. * are relatively small (eg. less than 1400 bytes).
  15625. */
  15626. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15627. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15628. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15629. mg_cry_internal(
  15630. fc(ctx),
  15631. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15632. __func__,
  15633. strerror(ERRNO));
  15634. }
  15635. }
  15636. /* We are using non-blocking sockets. Thus, the
  15637. * set_sock_timeout(so.sock, timeout);
  15638. * call is no longer required. */
  15639. /* The "non blocking" property should already be
  15640. * inherited from the parent socket. Set it for
  15641. * non-compliant socket implementations. */
  15642. set_non_blocking_mode(so.sock);
  15643. so.in_use = 0;
  15644. produce_socket(ctx, &so);
  15645. }
  15646. }
  15647. static void
  15648. master_thread_run(struct mg_context *ctx)
  15649. {
  15650. struct mg_workerTLS tls;
  15651. struct mg_pollfd *pfd;
  15652. unsigned int i;
  15653. unsigned int workerthreadcount;
  15654. if (!ctx) {
  15655. return;
  15656. }
  15657. mg_set_thread_name("master");
  15658. /* Increase priority of the master thread */
  15659. #if defined(_WIN32)
  15660. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15661. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15662. int min_prio = sched_get_priority_min(SCHED_RR);
  15663. int max_prio = sched_get_priority_max(SCHED_RR);
  15664. if ((min_prio >= 0) && (max_prio >= 0)
  15665. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15666. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15667. struct sched_param sched_param = {0};
  15668. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15669. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15670. }
  15671. #endif
  15672. /* Initialize thread local storage */
  15673. #if defined(_WIN32)
  15674. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15675. #endif
  15676. tls.is_master = 1;
  15677. pthread_setspecific(sTlsKey, &tls);
  15678. if (ctx->callbacks.init_thread) {
  15679. /* Callback for the master thread (type 0) */
  15680. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  15681. } else {
  15682. tls.user_ptr = NULL;
  15683. }
  15684. /* Server starts *now* */
  15685. ctx->start_time = time(NULL);
  15686. /* Start the server */
  15687. pfd = ctx->listening_socket_fds;
  15688. while (ctx->stop_flag == 0) {
  15689. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15690. pfd[i].fd = ctx->listening_sockets[i].sock;
  15691. pfd[i].events = POLLIN;
  15692. }
  15693. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15694. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15695. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15696. * successful poll, and POLLIN is defined as
  15697. * (POLLRDNORM | POLLRDBAND)
  15698. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15699. * pfd[i].revents == POLLIN. */
  15700. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15701. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15702. }
  15703. }
  15704. }
  15705. }
  15706. /* Here stop_flag is 1 - Initiate shutdown. */
  15707. DEBUG_TRACE("%s", "stopping workers");
  15708. /* Stop signal received: somebody called mg_stop. Quit. */
  15709. close_all_listening_sockets(ctx);
  15710. /* Wakeup workers that are waiting for connections to handle. */
  15711. #if defined(ALTERNATIVE_QUEUE)
  15712. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15713. event_signal(ctx->client_wait_events[i]);
  15714. }
  15715. #else
  15716. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15717. pthread_cond_broadcast(&ctx->sq_full);
  15718. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15719. #endif
  15720. /* Join all worker threads to avoid leaking threads. */
  15721. workerthreadcount = ctx->cfg_worker_threads;
  15722. for (i = 0; i < workerthreadcount; i++) {
  15723. if (ctx->worker_threadids[i] != 0) {
  15724. mg_join_thread(ctx->worker_threadids[i]);
  15725. }
  15726. }
  15727. #if defined(USE_LUA)
  15728. /* Free Lua state of lua background task */
  15729. if (ctx->lua_background_state) {
  15730. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15731. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15732. if (lua_istable(lstate, -1)) {
  15733. reg_boolean(lstate, "shutdown", 1);
  15734. lua_pop(lstate, 1);
  15735. mg_sleep(2);
  15736. }
  15737. lua_close(lstate);
  15738. ctx->lua_background_state = 0;
  15739. }
  15740. #endif
  15741. DEBUG_TRACE("%s", "exiting");
  15742. /* call exit thread callback */
  15743. if (ctx->callbacks.exit_thread) {
  15744. /* Callback for the master thread (type 0) */
  15745. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  15746. }
  15747. #if defined(_WIN32)
  15748. CloseHandle(tls.pthread_cond_helper_mutex);
  15749. #endif
  15750. pthread_setspecific(sTlsKey, NULL);
  15751. /* Signal mg_stop() that we're done.
  15752. * WARNING: This must be the very last thing this
  15753. * thread does, as ctx becomes invalid after this line. */
  15754. ctx->stop_flag = 2;
  15755. }
  15756. /* Threads have different return types on Windows and Unix. */
  15757. #if defined(_WIN32)
  15758. static unsigned __stdcall master_thread(void *thread_func_param)
  15759. {
  15760. master_thread_run((struct mg_context *)thread_func_param);
  15761. return 0;
  15762. }
  15763. #else
  15764. static void *
  15765. master_thread(void *thread_func_param)
  15766. {
  15767. struct sigaction sa;
  15768. /* Ignore SIGPIPE */
  15769. memset(&sa, 0, sizeof(sa));
  15770. sa.sa_handler = SIG_IGN;
  15771. sigaction(SIGPIPE, &sa, NULL);
  15772. master_thread_run((struct mg_context *)thread_func_param);
  15773. return NULL;
  15774. }
  15775. #endif /* _WIN32 */
  15776. static void
  15777. free_context(struct mg_context *ctx)
  15778. {
  15779. int i;
  15780. struct mg_handler_info *tmp_rh;
  15781. if (ctx == NULL) {
  15782. return;
  15783. }
  15784. if (ctx->callbacks.exit_context) {
  15785. ctx->callbacks.exit_context(ctx);
  15786. }
  15787. /* All threads exited, no sync is needed. Destroy thread mutex and
  15788. * condvars
  15789. */
  15790. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15791. #if defined(ALTERNATIVE_QUEUE)
  15792. mg_free(ctx->client_socks);
  15793. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15794. event_destroy(ctx->client_wait_events[i]);
  15795. }
  15796. mg_free(ctx->client_wait_events);
  15797. #else
  15798. (void)pthread_cond_destroy(&ctx->sq_empty);
  15799. (void)pthread_cond_destroy(&ctx->sq_full);
  15800. #endif
  15801. /* Destroy other context global data structures mutex */
  15802. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15803. #if defined(USE_TIMERS)
  15804. timers_exit(ctx);
  15805. #endif
  15806. /* Deallocate config parameters */
  15807. for (i = 0; i < NUM_OPTIONS; i++) {
  15808. if (ctx->dd.config[i] != NULL) {
  15809. #if defined(_MSC_VER)
  15810. #pragma warning(suppress : 6001)
  15811. #endif
  15812. mg_free(ctx->dd.config[i]);
  15813. }
  15814. }
  15815. /* Deallocate request handlers */
  15816. while (ctx->dd.handlers) {
  15817. tmp_rh = ctx->dd.handlers;
  15818. ctx->dd.handlers = tmp_rh->next;
  15819. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15820. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15821. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15822. }
  15823. mg_free(tmp_rh->uri);
  15824. mg_free(tmp_rh);
  15825. }
  15826. #if !defined(NO_SSL)
  15827. /* Deallocate SSL context */
  15828. if (ctx->dd.ssl_ctx != NULL) {
  15829. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15830. int callback_ret =
  15831. (ctx->callbacks.external_ssl_ctx == NULL)
  15832. ? 0
  15833. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15834. if (callback_ret == 0) {
  15835. SSL_CTX_free(ctx->dd.ssl_ctx);
  15836. }
  15837. /* else: ignore error and ommit SSL_CTX_free in case
  15838. * callback_ret is 1 */
  15839. }
  15840. #endif /* !NO_SSL */
  15841. /* Deallocate worker thread ID array */
  15842. mg_free(ctx->worker_threadids);
  15843. /* Deallocate worker thread ID array */
  15844. mg_free(ctx->worker_connections);
  15845. /* deallocate system name string */
  15846. mg_free(ctx->systemName);
  15847. /* Deallocate context itself */
  15848. mg_free(ctx);
  15849. }
  15850. void
  15851. mg_stop(struct mg_context *ctx)
  15852. {
  15853. pthread_t mt;
  15854. if (!ctx) {
  15855. return;
  15856. }
  15857. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15858. * two threads is not allowed. */
  15859. mt = ctx->masterthreadid;
  15860. if (mt == 0) {
  15861. return;
  15862. }
  15863. ctx->masterthreadid = 0;
  15864. /* Set stop flag, so all threads know they have to exit. */
  15865. ctx->stop_flag = 1;
  15866. /* Wait until everything has stopped. */
  15867. while (ctx->stop_flag != 2) {
  15868. (void)mg_sleep(10);
  15869. }
  15870. mg_join_thread(mt);
  15871. free_context(ctx);
  15872. #if defined(_WIN32)
  15873. (void)WSACleanup();
  15874. #endif /* _WIN32 */
  15875. }
  15876. static void
  15877. get_system_name(char **sysName)
  15878. {
  15879. #if defined(_WIN32)
  15880. #if !defined(__SYMBIAN32__)
  15881. #if defined(_WIN32_WCE)
  15882. *sysName = mg_strdup("WinCE");
  15883. #else
  15884. char name[128];
  15885. DWORD dwVersion = 0;
  15886. DWORD dwMajorVersion = 0;
  15887. DWORD dwMinorVersion = 0;
  15888. DWORD dwBuild = 0;
  15889. BOOL wowRet, isWoW = FALSE;
  15890. #if defined(_MSC_VER)
  15891. #pragma warning(push)
  15892. /* GetVersion was declared deprecated */
  15893. #pragma warning(disable : 4996)
  15894. #endif
  15895. dwVersion = GetVersion();
  15896. #if defined(_MSC_VER)
  15897. #pragma warning(pop)
  15898. #endif
  15899. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15900. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15901. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15902. (void)dwBuild;
  15903. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15904. sprintf(name,
  15905. "Windows %u.%u%s",
  15906. (unsigned)dwMajorVersion,
  15907. (unsigned)dwMinorVersion,
  15908. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15909. *sysName = mg_strdup(name);
  15910. #endif
  15911. #else
  15912. *sysName = mg_strdup("Symbian");
  15913. #endif
  15914. #else
  15915. struct utsname name;
  15916. memset(&name, 0, sizeof(name));
  15917. uname(&name);
  15918. *sysName = mg_strdup(name.sysname);
  15919. #endif
  15920. }
  15921. struct mg_context *
  15922. mg_start(const struct mg_callbacks *callbacks,
  15923. void *user_data,
  15924. const char **options)
  15925. {
  15926. struct mg_context *ctx;
  15927. const char *name, *value, *default_value;
  15928. int idx, ok, workerthreadcount;
  15929. unsigned int i;
  15930. int itmp;
  15931. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15932. struct mg_workerTLS tls;
  15933. #if defined(_WIN32)
  15934. WSADATA data;
  15935. WSAStartup(MAKEWORD(2, 2), &data);
  15936. #endif /* _WIN32 */
  15937. /* Allocate context and initialize reasonable general case defaults. */
  15938. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15939. return NULL;
  15940. }
  15941. /* Random number generator will initialize at the first call */
  15942. ctx->dd.auth_nonce_mask =
  15943. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15944. if (mg_init_library_called == 0) {
  15945. /* Legacy INIT, if mg_start is called without mg_init_library.
  15946. * Note: This may cause a memory leak */
  15947. const char *ports_option =
  15948. config_options[LISTENING_PORTS].default_value;
  15949. if (options) {
  15950. const char **run_options = options;
  15951. const char *optname = config_options[LISTENING_PORTS].name;
  15952. /* Try to find the "listening_ports" option */
  15953. while (*run_options) {
  15954. if (!strcmp(*run_options, optname)) {
  15955. ports_option = run_options[1];
  15956. }
  15957. run_options += 2;
  15958. }
  15959. }
  15960. if (is_ssl_port_used(ports_option)) {
  15961. /* Initialize with SSL support */
  15962. mg_init_library(MG_FEATURES_TLS);
  15963. } else {
  15964. /* Initialize without SSL support */
  15965. mg_init_library(MG_FEATURES_DEFAULT);
  15966. }
  15967. }
  15968. tls.is_master = -1;
  15969. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15970. #if defined(_WIN32)
  15971. tls.pthread_cond_helper_mutex = NULL;
  15972. #endif
  15973. pthread_setspecific(sTlsKey, &tls);
  15974. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  15975. #if !defined(ALTERNATIVE_QUEUE)
  15976. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  15977. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  15978. #endif
  15979. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  15980. if (!ok) {
  15981. /* Fatal error - abort start. However, this situation should never
  15982. * occur in practice. */
  15983. mg_cry_internal(fc(ctx),
  15984. "%s",
  15985. "Cannot initialize thread synchronization objects");
  15986. mg_free(ctx);
  15987. pthread_setspecific(sTlsKey, NULL);
  15988. return NULL;
  15989. }
  15990. if (callbacks) {
  15991. ctx->callbacks = *callbacks;
  15992. exit_callback = callbacks->exit_context;
  15993. ctx->callbacks.exit_context = 0;
  15994. }
  15995. ctx->user_data = user_data;
  15996. ctx->dd.handlers = NULL;
  15997. ctx->dd.next = NULL;
  15998. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15999. ctx->dd.shared_lua_websockets = NULL;
  16000. #endif
  16001. /* Store options */
  16002. while (options && (name = *options++) != NULL) {
  16003. if ((idx = get_option_index(name)) == -1) {
  16004. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  16005. free_context(ctx);
  16006. pthread_setspecific(sTlsKey, NULL);
  16007. return NULL;
  16008. } else if ((value = *options++) == NULL) {
  16009. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  16010. free_context(ctx);
  16011. pthread_setspecific(sTlsKey, NULL);
  16012. return NULL;
  16013. }
  16014. if (ctx->dd.config[idx] != NULL) {
  16015. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  16016. mg_free(ctx->dd.config[idx]);
  16017. }
  16018. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16019. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16020. }
  16021. /* Set default value if needed */
  16022. for (i = 0; config_options[i].name != NULL; i++) {
  16023. default_value = config_options[i].default_value;
  16024. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16025. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16026. }
  16027. }
  16028. /* Request size option */
  16029. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16030. if (itmp < 1024) {
  16031. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  16032. free_context(ctx);
  16033. pthread_setspecific(sTlsKey, NULL);
  16034. return NULL;
  16035. }
  16036. ctx->max_request_size = (unsigned)itmp;
  16037. /* Worker thread count option */
  16038. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16039. if (workerthreadcount > MAX_WORKER_THREADS) {
  16040. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  16041. free_context(ctx);
  16042. pthread_setspecific(sTlsKey, NULL);
  16043. return NULL;
  16044. }
  16045. if (workerthreadcount <= 0) {
  16046. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  16047. free_context(ctx);
  16048. pthread_setspecific(sTlsKey, NULL);
  16049. return NULL;
  16050. }
  16051. /* Document root */
  16052. #if defined(NO_FILES)
  16053. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16054. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  16055. free_context(ctx);
  16056. pthread_setspecific(sTlsKey, NULL);
  16057. return NULL;
  16058. }
  16059. #endif
  16060. get_system_name(&ctx->systemName);
  16061. #if defined(USE_LUA)
  16062. /* If a Lua background script has been configured, start it. */
  16063. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16064. char ebuf[256];
  16065. struct vec opt_vec;
  16066. struct vec eq_vec;
  16067. const char *sparams;
  16068. lua_State *state = mg_prepare_lua_context_script(
  16069. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16070. if (!state) {
  16071. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  16072. free_context(ctx);
  16073. pthread_setspecific(sTlsKey, NULL);
  16074. return NULL;
  16075. }
  16076. ctx->lua_background_state = (void *)state;
  16077. lua_newtable(state);
  16078. reg_boolean(state, "shutdown", 0);
  16079. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16080. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16081. reg_llstring(
  16082. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16083. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16084. break;
  16085. }
  16086. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16087. } else {
  16088. ctx->lua_background_state = 0;
  16089. }
  16090. #endif
  16091. /* NOTE(lsm): order is important here. SSL certificates must
  16092. * be initialized before listening ports. UID must be set last. */
  16093. if (!set_gpass_option(ctx, NULL) ||
  16094. #if !defined(NO_SSL)
  16095. !init_ssl_ctx(ctx, NULL) ||
  16096. #endif
  16097. !set_ports_option(ctx) ||
  16098. #if !defined(_WIN32)
  16099. !set_uid_option(ctx) ||
  16100. #endif
  16101. !set_acl_option(ctx)) {
  16102. free_context(ctx);
  16103. pthread_setspecific(sTlsKey, NULL);
  16104. return NULL;
  16105. }
  16106. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16107. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16108. sizeof(pthread_t),
  16109. ctx);
  16110. if (ctx->worker_threadids == NULL) {
  16111. mg_cry_internal(fc(ctx),
  16112. "%s",
  16113. "Not enough memory for worker thread ID array");
  16114. free_context(ctx);
  16115. pthread_setspecific(sTlsKey, NULL);
  16116. return NULL;
  16117. }
  16118. ctx->worker_connections =
  16119. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16120. sizeof(struct mg_connection),
  16121. ctx);
  16122. if (ctx->worker_connections == NULL) {
  16123. mg_cry_internal(fc(ctx),
  16124. "%s",
  16125. "Not enough memory for worker thread connection array");
  16126. free_context(ctx);
  16127. pthread_setspecific(sTlsKey, NULL);
  16128. return NULL;
  16129. }
  16130. #if defined(ALTERNATIVE_QUEUE)
  16131. ctx->client_wait_events =
  16132. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  16133. ctx->cfg_worker_threads,
  16134. ctx);
  16135. if (ctx->client_wait_events == NULL) {
  16136. mg_cry_internal(fc(ctx),
  16137. "%s",
  16138. "Not enough memory for worker event array");
  16139. mg_free(ctx->worker_threadids);
  16140. free_context(ctx);
  16141. pthread_setspecific(sTlsKey, NULL);
  16142. return NULL;
  16143. }
  16144. ctx->client_socks =
  16145. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  16146. ctx->cfg_worker_threads,
  16147. ctx);
  16148. if (ctx->client_socks == NULL) {
  16149. mg_cry_internal(fc(ctx),
  16150. "%s",
  16151. "Not enough memory for worker socket array");
  16152. mg_free(ctx->client_wait_events);
  16153. mg_free(ctx->worker_threadids);
  16154. free_context(ctx);
  16155. pthread_setspecific(sTlsKey, NULL);
  16156. return NULL;
  16157. }
  16158. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16159. ctx->client_wait_events[i] = event_create();
  16160. if (ctx->client_wait_events[i] == 0) {
  16161. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  16162. while (i > 0) {
  16163. i--;
  16164. event_destroy(ctx->client_wait_events[i]);
  16165. }
  16166. mg_free(ctx->client_socks);
  16167. mg_free(ctx->client_wait_events);
  16168. mg_free(ctx->worker_threadids);
  16169. free_context(ctx);
  16170. pthread_setspecific(sTlsKey, NULL);
  16171. return NULL;
  16172. }
  16173. }
  16174. #endif
  16175. #if defined(USE_TIMERS)
  16176. if (timers_init(ctx) != 0) {
  16177. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  16178. free_context(ctx);
  16179. pthread_setspecific(sTlsKey, NULL);
  16180. return NULL;
  16181. }
  16182. #endif
  16183. /* Context has been created - init user libraries */
  16184. if (ctx->callbacks.init_context) {
  16185. ctx->callbacks.init_context(ctx);
  16186. }
  16187. ctx->callbacks.exit_context = exit_callback;
  16188. ctx->context_type = CONTEXT_SERVER; /* server context */
  16189. /* Start master (listening) thread */
  16190. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16191. /* Start worker threads */
  16192. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16193. /* worker_thread sets up the other fields */
  16194. ctx->worker_connections[i].phys_ctx = ctx;
  16195. if (mg_start_thread_with_id(worker_thread,
  16196. &ctx->worker_connections[i],
  16197. &ctx->worker_threadids[i])
  16198. != 0) {
  16199. /* thread was not created */
  16200. if (i > 0) {
  16201. mg_cry_internal(fc(ctx),
  16202. "Cannot start worker thread %i: error %ld",
  16203. i + 1,
  16204. (long)ERRNO);
  16205. } else {
  16206. mg_cry_internal(fc(ctx),
  16207. "Cannot create threads: error %ld",
  16208. (long)ERRNO);
  16209. free_context(ctx);
  16210. pthread_setspecific(sTlsKey, NULL);
  16211. return NULL;
  16212. }
  16213. break;
  16214. }
  16215. }
  16216. pthread_setspecific(sTlsKey, NULL);
  16217. return ctx;
  16218. }
  16219. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16220. /* Add an additional domain to an already running web server. */
  16221. int
  16222. mg_start_domain(struct mg_context *ctx, const char **options)
  16223. {
  16224. const char *name;
  16225. const char *value;
  16226. const char *default_value;
  16227. struct mg_domain_context *new_dom;
  16228. struct mg_domain_context *dom;
  16229. int idx, i;
  16230. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  16231. return -1;
  16232. }
  16233. new_dom = (struct mg_domain_context *)
  16234. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16235. if (!new_dom) {
  16236. /* Out of memory */
  16237. return -6;
  16238. }
  16239. /* Store options - TODO: unite duplicate code */
  16240. while (options && (name = *options++) != NULL) {
  16241. if ((idx = get_option_index(name)) == -1) {
  16242. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  16243. mg_free(new_dom);
  16244. return -2;
  16245. } else if ((value = *options++) == NULL) {
  16246. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  16247. mg_free(new_dom);
  16248. return -2;
  16249. }
  16250. if (new_dom->config[idx] != NULL) {
  16251. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  16252. mg_free(new_dom->config[idx]);
  16253. }
  16254. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16255. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16256. }
  16257. /* Authentication domain is mandatory */
  16258. /* TODO: Maybe use a new option hostname? */
  16259. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16260. mg_cry_internal(fc(ctx), "%s", "authentication domain required");
  16261. mg_free(new_dom);
  16262. return -4;
  16263. }
  16264. /* Set default value if needed. Take the config value from
  16265. * ctx as a default value. */
  16266. for (i = 0; config_options[i].name != NULL; i++) {
  16267. default_value = ctx->dd.config[i];
  16268. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16269. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16270. }
  16271. }
  16272. new_dom->handlers = NULL;
  16273. new_dom->next = NULL;
  16274. new_dom->nonce_count = 0;
  16275. new_dom->auth_nonce_mask =
  16276. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16277. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16278. new_dom->shared_lua_websockets = NULL;
  16279. #endif
  16280. if (!init_ssl_ctx(ctx, new_dom)) {
  16281. /* Init SSL failed */
  16282. mg_free(new_dom);
  16283. return -3;
  16284. }
  16285. /* Add element to linked list. */
  16286. mg_lock_context(ctx);
  16287. idx = 0;
  16288. dom = &(ctx->dd);
  16289. for (;;) {
  16290. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16291. dom->config[AUTHENTICATION_DOMAIN])) {
  16292. /* Domain collision */
  16293. mg_cry_internal(fc(ctx),
  16294. "domain %s already in use",
  16295. new_dom->config[AUTHENTICATION_DOMAIN]);
  16296. mg_free(new_dom);
  16297. return -5;
  16298. }
  16299. /* Count number of domains */
  16300. idx++;
  16301. if (dom->next == NULL) {
  16302. dom->next = new_dom;
  16303. break;
  16304. }
  16305. dom = dom->next;
  16306. }
  16307. mg_unlock_context(ctx);
  16308. /* Return domain number */
  16309. return idx;
  16310. }
  16311. #endif
  16312. /* Feature check API function */
  16313. unsigned
  16314. mg_check_feature(unsigned feature)
  16315. {
  16316. static const unsigned feature_set = 0
  16317. /* Set bits for available features according to API documentation.
  16318. * This bit mask is created at compile time, according to the active
  16319. * preprocessor defines. It is a single const value at runtime. */
  16320. #if !defined(NO_FILES)
  16321. | MG_FEATURES_FILES
  16322. #endif
  16323. #if !defined(NO_SSL)
  16324. | MG_FEATURES_SSL
  16325. #endif
  16326. #if !defined(NO_CGI)
  16327. | MG_FEATURES_CGI
  16328. #endif
  16329. #if defined(USE_IPV6)
  16330. | MG_FEATURES_IPV6
  16331. #endif
  16332. #if defined(USE_WEBSOCKET)
  16333. | MG_FEATURES_WEBSOCKET
  16334. #endif
  16335. #if defined(USE_LUA)
  16336. | MG_FEATURES_LUA
  16337. #endif
  16338. #if defined(USE_DUKTAPE)
  16339. | MG_FEATURES_SSJS
  16340. #endif
  16341. #if !defined(NO_CACHING)
  16342. | MG_FEATURES_CACHE
  16343. #endif
  16344. #if defined(USE_SERVER_STATS)
  16345. | MG_FEATURES_STATS
  16346. #endif
  16347. #if defined(USE_ZLIB)
  16348. | MG_FEATURES_COMPRESSION
  16349. #endif
  16350. /* Set some extra bits not defined in the API documentation.
  16351. * These bits may change without further notice. */
  16352. #if defined(MG_LEGACY_INTERFACE)
  16353. | 0x00008000u
  16354. #endif
  16355. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16356. | 0x00004000u
  16357. #endif
  16358. #if defined(MEMORY_DEBUGGING)
  16359. | 0x00001000u
  16360. #endif
  16361. #if defined(USE_TIMERS)
  16362. | 0x00020000u
  16363. #endif
  16364. #if !defined(NO_NONCE_CHECK)
  16365. | 0x00040000u
  16366. #endif
  16367. #if !defined(NO_POPEN)
  16368. | 0x00080000u
  16369. #endif
  16370. ;
  16371. return (feature & feature_set);
  16372. }
  16373. static size_t
  16374. mg_str_append(char **dst, char *end, const char *src)
  16375. {
  16376. size_t len = strlen(src);
  16377. if (*dst != end) {
  16378. /* Append src if enough space, or close dst. */
  16379. if ((size_t)(end - *dst) > len) {
  16380. strcpy(*dst, src);
  16381. *dst += len;
  16382. } else {
  16383. *dst = end;
  16384. }
  16385. }
  16386. return len;
  16387. }
  16388. /* Get system information. It can be printed or stored by the caller.
  16389. * Return the size of available information. */
  16390. int
  16391. mg_get_system_info(char *buffer, int buflen)
  16392. {
  16393. char *end, *append_eoobj = NULL, block[256];
  16394. size_t system_info_length = 0;
  16395. #if defined(_WIN32)
  16396. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16397. #else
  16398. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16399. #endif
  16400. if ((buffer == NULL) || (buflen < 1)) {
  16401. buflen = 0;
  16402. end = buffer;
  16403. } else {
  16404. *buffer = 0;
  16405. end = buffer + buflen;
  16406. }
  16407. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16408. /* has enough space to append eoobj */
  16409. append_eoobj = buffer;
  16410. end -= sizeof(eoobj) - 1;
  16411. }
  16412. system_info_length += mg_str_append(&buffer, end, "{");
  16413. /* Server version */
  16414. {
  16415. const char *version = mg_version();
  16416. mg_snprintf(NULL,
  16417. NULL,
  16418. block,
  16419. sizeof(block),
  16420. "%s\"version\" : \"%s\"",
  16421. eol,
  16422. version);
  16423. system_info_length += mg_str_append(&buffer, end, block);
  16424. }
  16425. /* System info */
  16426. {
  16427. #if defined(_WIN32)
  16428. DWORD dwVersion = 0;
  16429. DWORD dwMajorVersion = 0;
  16430. DWORD dwMinorVersion = 0;
  16431. SYSTEM_INFO si;
  16432. GetSystemInfo(&si);
  16433. #if defined(_MSC_VER)
  16434. #pragma warning(push)
  16435. /* GetVersion was declared deprecated */
  16436. #pragma warning(disable : 4996)
  16437. #endif
  16438. dwVersion = GetVersion();
  16439. #if defined(_MSC_VER)
  16440. #pragma warning(pop)
  16441. #endif
  16442. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16443. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16444. mg_snprintf(NULL,
  16445. NULL,
  16446. block,
  16447. sizeof(block),
  16448. ",%s\"os\" : \"Windows %u.%u\"",
  16449. eol,
  16450. (unsigned)dwMajorVersion,
  16451. (unsigned)dwMinorVersion);
  16452. system_info_length += mg_str_append(&buffer, end, block);
  16453. mg_snprintf(NULL,
  16454. NULL,
  16455. block,
  16456. sizeof(block),
  16457. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  16458. eol,
  16459. (unsigned)si.wProcessorArchitecture,
  16460. (unsigned)si.dwNumberOfProcessors,
  16461. (unsigned)si.dwActiveProcessorMask);
  16462. system_info_length += mg_str_append(&buffer, end, block);
  16463. #else
  16464. struct utsname name;
  16465. memset(&name, 0, sizeof(name));
  16466. uname(&name);
  16467. mg_snprintf(NULL,
  16468. NULL,
  16469. block,
  16470. sizeof(block),
  16471. ",%s\"os\" : \"%s %s (%s) - %s\"",
  16472. eol,
  16473. name.sysname,
  16474. name.version,
  16475. name.release,
  16476. name.machine);
  16477. system_info_length += mg_str_append(&buffer, end, block);
  16478. #endif
  16479. }
  16480. /* Features */
  16481. {
  16482. mg_snprintf(NULL,
  16483. NULL,
  16484. block,
  16485. sizeof(block),
  16486. ",%s\"features\" : %lu"
  16487. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  16488. eol,
  16489. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16490. eol,
  16491. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16492. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16493. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16494. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16495. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16496. : "",
  16497. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16498. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16499. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16500. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  16501. system_info_length += mg_str_append(&buffer, end, block);
  16502. #if defined(USE_LUA)
  16503. mg_snprintf(NULL,
  16504. NULL,
  16505. block,
  16506. sizeof(block),
  16507. ",%s\"lua_version\" : \"%u (%s)\"",
  16508. eol,
  16509. (unsigned)LUA_VERSION_NUM,
  16510. LUA_RELEASE);
  16511. system_info_length += mg_str_append(&buffer, end, block);
  16512. #endif
  16513. #if defined(USE_DUKTAPE)
  16514. mg_snprintf(NULL,
  16515. NULL,
  16516. block,
  16517. sizeof(block),
  16518. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  16519. eol,
  16520. (unsigned)DUK_VERSION / 10000,
  16521. ((unsigned)DUK_VERSION / 100) % 100,
  16522. (unsigned)DUK_VERSION % 100);
  16523. system_info_length += mg_str_append(&buffer, end, block);
  16524. #endif
  16525. }
  16526. /* Build date */
  16527. {
  16528. #if defined(GCC_DIAGNOSTIC)
  16529. #if GCC_VERSION >= 40900
  16530. #pragma GCC diagnostic push
  16531. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  16532. #pragma GCC diagnostic ignored "-Wdate-time"
  16533. #endif
  16534. #endif
  16535. mg_snprintf(NULL,
  16536. NULL,
  16537. block,
  16538. sizeof(block),
  16539. ",%s\"build\" : \"%s\"",
  16540. eol,
  16541. __DATE__);
  16542. #if defined(GCC_DIAGNOSTIC)
  16543. #if GCC_VERSION >= 40900
  16544. #pragma GCC diagnostic pop
  16545. #endif
  16546. #endif
  16547. system_info_length += mg_str_append(&buffer, end, block);
  16548. }
  16549. /* Compiler information */
  16550. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16551. {
  16552. #if defined(_MSC_VER)
  16553. mg_snprintf(NULL,
  16554. NULL,
  16555. block,
  16556. sizeof(block),
  16557. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  16558. eol,
  16559. (unsigned)_MSC_VER,
  16560. (unsigned)_MSC_FULL_VER);
  16561. system_info_length += mg_str_append(&buffer, end, block);
  16562. #elif defined(__MINGW64__)
  16563. mg_snprintf(NULL,
  16564. NULL,
  16565. block,
  16566. sizeof(block),
  16567. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  16568. eol,
  16569. (unsigned)__MINGW64_VERSION_MAJOR,
  16570. (unsigned)__MINGW64_VERSION_MINOR);
  16571. system_info_length += mg_str_append(&buffer, end, block);
  16572. mg_snprintf(NULL,
  16573. NULL,
  16574. block,
  16575. sizeof(block),
  16576. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16577. eol,
  16578. (unsigned)__MINGW32_MAJOR_VERSION,
  16579. (unsigned)__MINGW32_MINOR_VERSION);
  16580. system_info_length += mg_str_append(&buffer, end, block);
  16581. #elif defined(__MINGW32__)
  16582. mg_snprintf(NULL,
  16583. NULL,
  16584. block,
  16585. sizeof(block),
  16586. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16587. eol,
  16588. (unsigned)__MINGW32_MAJOR_VERSION,
  16589. (unsigned)__MINGW32_MINOR_VERSION);
  16590. system_info_length += mg_str_append(&buffer, end, block);
  16591. #elif defined(__clang__)
  16592. mg_snprintf(NULL,
  16593. NULL,
  16594. block,
  16595. sizeof(block),
  16596. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  16597. eol,
  16598. __clang_major__,
  16599. __clang_minor__,
  16600. __clang_patchlevel__,
  16601. __clang_version__);
  16602. system_info_length += mg_str_append(&buffer, end, block);
  16603. #elif defined(__GNUC__)
  16604. mg_snprintf(NULL,
  16605. NULL,
  16606. block,
  16607. sizeof(block),
  16608. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  16609. eol,
  16610. (unsigned)__GNUC__,
  16611. (unsigned)__GNUC_MINOR__,
  16612. (unsigned)__GNUC_PATCHLEVEL__);
  16613. system_info_length += mg_str_append(&buffer, end, block);
  16614. #elif defined(__INTEL_COMPILER)
  16615. mg_snprintf(NULL,
  16616. NULL,
  16617. block,
  16618. sizeof(block),
  16619. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  16620. eol,
  16621. (unsigned)__INTEL_COMPILER);
  16622. system_info_length += mg_str_append(&buffer, end, block);
  16623. #elif defined(__BORLANDC__)
  16624. mg_snprintf(NULL,
  16625. NULL,
  16626. block,
  16627. sizeof(block),
  16628. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  16629. eol,
  16630. (unsigned)__BORLANDC__);
  16631. system_info_length += mg_str_append(&buffer, end, block);
  16632. #elif defined(__SUNPRO_C)
  16633. mg_snprintf(NULL,
  16634. NULL,
  16635. block,
  16636. sizeof(block),
  16637. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  16638. eol,
  16639. (unsigned)__SUNPRO_C);
  16640. system_info_length += mg_str_append(&buffer, end, block);
  16641. #else
  16642. mg_snprintf(NULL,
  16643. NULL,
  16644. block,
  16645. sizeof(block),
  16646. ",%s\"compiler\" : \"other\"",
  16647. eol);
  16648. system_info_length += mg_str_append(&buffer, end, block);
  16649. #endif
  16650. }
  16651. /* Determine 32/64 bit data mode.
  16652. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16653. {
  16654. mg_snprintf(NULL,
  16655. NULL,
  16656. block,
  16657. sizeof(block),
  16658. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16659. "char:%u/%u, "
  16660. "ptr:%u, size:%u, time:%u\"",
  16661. eol,
  16662. (unsigned)sizeof(short),
  16663. (unsigned)sizeof(int),
  16664. (unsigned)sizeof(long),
  16665. (unsigned)sizeof(long long),
  16666. (unsigned)sizeof(float),
  16667. (unsigned)sizeof(double),
  16668. (unsigned)sizeof(long double),
  16669. (unsigned)sizeof(char),
  16670. (unsigned)sizeof(wchar_t),
  16671. (unsigned)sizeof(void *),
  16672. (unsigned)sizeof(size_t),
  16673. (unsigned)sizeof(time_t));
  16674. system_info_length += mg_str_append(&buffer, end, block);
  16675. }
  16676. /* Terminate string */
  16677. if (append_eoobj) {
  16678. strcat(append_eoobj, eoobj);
  16679. }
  16680. system_info_length += sizeof(eoobj) - 1;
  16681. return (int)system_info_length;
  16682. }
  16683. /* Get context information. It can be printed or stored by the caller.
  16684. * Return the size of available information. */
  16685. int
  16686. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16687. {
  16688. #if defined(USE_SERVER_STATS)
  16689. char *end, *append_eoobj = NULL, block[256];
  16690. size_t context_info_length = 0;
  16691. #if defined(_WIN32)
  16692. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16693. #else
  16694. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16695. #endif
  16696. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16697. if ((buffer == NULL) || (buflen < 1)) {
  16698. buflen = 0;
  16699. end = buffer;
  16700. } else {
  16701. *buffer = 0;
  16702. end = buffer + buflen;
  16703. }
  16704. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16705. /* has enough space to append eoobj */
  16706. append_eoobj = buffer;
  16707. end -= sizeof(eoobj) - 1;
  16708. }
  16709. context_info_length += mg_str_append(&buffer, end, "{");
  16710. if (ms) { /* <-- should be always true */
  16711. /* Memory information */
  16712. mg_snprintf(NULL,
  16713. NULL,
  16714. block,
  16715. sizeof(block),
  16716. "%s\"memory\" : {%s"
  16717. "\"blocks\" : %i,%s"
  16718. "\"used\" : %" INT64_FMT ",%s"
  16719. "\"maxUsed\" : %" INT64_FMT "%s"
  16720. "}",
  16721. eol,
  16722. eol,
  16723. ms->blockCount,
  16724. eol,
  16725. ms->totalMemUsed,
  16726. eol,
  16727. ms->maxMemUsed,
  16728. eol);
  16729. context_info_length += mg_str_append(&buffer, end, block);
  16730. }
  16731. if (ctx) {
  16732. /* Declare all variables at begin of the block, to comply
  16733. * with old C standards. */
  16734. char start_time_str[64] = {0};
  16735. char now_str[64] = {0};
  16736. time_t start_time = ctx->start_time;
  16737. time_t now = time(NULL);
  16738. /* Connections information */
  16739. mg_snprintf(NULL,
  16740. NULL,
  16741. block,
  16742. sizeof(block),
  16743. ",%s\"connections\" : {%s"
  16744. "\"active\" : %i,%s"
  16745. "\"maxActive\" : %i,%s"
  16746. "\"total\" : %" INT64_FMT "%s"
  16747. "}",
  16748. eol,
  16749. eol,
  16750. ctx->active_connections,
  16751. eol,
  16752. ctx->max_connections,
  16753. eol,
  16754. ctx->total_connections,
  16755. eol);
  16756. context_info_length += mg_str_append(&buffer, end, block);
  16757. /* Requests information */
  16758. mg_snprintf(NULL,
  16759. NULL,
  16760. block,
  16761. sizeof(block),
  16762. ",%s\"requests\" : {%s"
  16763. "\"total\" : %" INT64_FMT "%s"
  16764. "}",
  16765. eol,
  16766. eol,
  16767. ctx->total_requests,
  16768. eol);
  16769. context_info_length += mg_str_append(&buffer, end, block);
  16770. /* Data information */
  16771. mg_snprintf(NULL,
  16772. NULL,
  16773. block,
  16774. sizeof(block),
  16775. ",%s\"data\" : {%s"
  16776. "\"read\" : %" INT64_FMT ",%s"
  16777. "\"written\" : %" INT64_FMT "%s"
  16778. "}",
  16779. eol,
  16780. eol,
  16781. ctx->total_data_read,
  16782. eol,
  16783. ctx->total_data_written,
  16784. eol);
  16785. context_info_length += mg_str_append(&buffer, end, block);
  16786. /* Execution time information */
  16787. gmt_time_string(start_time_str,
  16788. sizeof(start_time_str) - 1,
  16789. &start_time);
  16790. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16791. mg_snprintf(NULL,
  16792. NULL,
  16793. block,
  16794. sizeof(block),
  16795. ",%s\"time\" : {%s"
  16796. "\"uptime\" : %.0f,%s"
  16797. "\"start\" : \"%s\",%s"
  16798. "\"now\" : \"%s\"%s"
  16799. "}",
  16800. eol,
  16801. eol,
  16802. difftime(now, start_time),
  16803. eol,
  16804. start_time_str,
  16805. eol,
  16806. now_str,
  16807. eol);
  16808. context_info_length += mg_str_append(&buffer, end, block);
  16809. }
  16810. /* Terminate string */
  16811. if (append_eoobj) {
  16812. strcat(append_eoobj, eoobj);
  16813. }
  16814. context_info_length += sizeof(eoobj) - 1;
  16815. return (int)context_info_length;
  16816. #else
  16817. (void)ctx;
  16818. if ((buffer != NULL) && (buflen > 0)) {
  16819. *buffer = 0;
  16820. }
  16821. return 0;
  16822. #endif
  16823. }
  16824. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16825. /* Get connection information. It can be printed or stored by the caller.
  16826. * Return the size of available information. */
  16827. int
  16828. mg_get_connection_info(const struct mg_context *ctx,
  16829. int idx,
  16830. char *buffer,
  16831. int buflen)
  16832. {
  16833. const struct mg_connection *conn;
  16834. const struct mg_request_info *ri;
  16835. char *end, *append_eoobj = NULL, block[256];
  16836. size_t connection_info_length = 0;
  16837. int state = 0;
  16838. const char *state_str = "unknown";
  16839. #if defined(_WIN32)
  16840. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16841. #else
  16842. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16843. #endif
  16844. if ((buffer == NULL) || (buflen < 1)) {
  16845. buflen = 0;
  16846. end = buffer;
  16847. } else {
  16848. *buffer = 0;
  16849. end = buffer + buflen;
  16850. }
  16851. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16852. /* has enough space to append eoobj */
  16853. append_eoobj = buffer;
  16854. end -= sizeof(eoobj) - 1;
  16855. }
  16856. if ((ctx == NULL) || (idx < 0)) {
  16857. /* Parameter error */
  16858. return 0;
  16859. }
  16860. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16861. /* Out of range */
  16862. return 0;
  16863. }
  16864. /* Take connection [idx]. This connection is not locked in
  16865. * any way, so some other thread might use it. */
  16866. conn = (ctx->worker_connections) + idx;
  16867. /* Initialize output string */
  16868. connection_info_length += mg_str_append(&buffer, end, "{");
  16869. /* Init variables */
  16870. ri = &(conn->request_info);
  16871. #if defined(USE_SERVER_STATS)
  16872. state = conn->conn_state;
  16873. /* State as string */
  16874. switch (state) {
  16875. case 0:
  16876. state_str = "undefined";
  16877. break;
  16878. case 1:
  16879. state_str = "not used";
  16880. break;
  16881. case 2:
  16882. state_str = "init";
  16883. break;
  16884. case 3:
  16885. state_str = "ready";
  16886. break;
  16887. case 4:
  16888. state_str = "processing";
  16889. break;
  16890. case 5:
  16891. state_str = "processed";
  16892. break;
  16893. case 6:
  16894. state_str = "to close";
  16895. break;
  16896. case 7:
  16897. state_str = "closing";
  16898. break;
  16899. case 8:
  16900. state_str = "closed";
  16901. break;
  16902. case 9:
  16903. state_str = "done";
  16904. break;
  16905. }
  16906. #endif
  16907. /* Connection info */
  16908. if ((state >= 3) && (state < 9)) {
  16909. mg_snprintf(NULL,
  16910. NULL,
  16911. block,
  16912. sizeof(block),
  16913. "%s\"connection\" : {%s"
  16914. "\"remote\" : {%s"
  16915. "\"protocol\" : \"%s\",%s"
  16916. "\"addr\" : \"%s\",%s"
  16917. "\"port\" : %u%s"
  16918. "},%s"
  16919. "\"handled_requests\" : %u%s"
  16920. "}",
  16921. eol,
  16922. eol,
  16923. eol,
  16924. get_proto_name(conn),
  16925. eol,
  16926. ri->remote_addr,
  16927. eol,
  16928. ri->remote_port,
  16929. eol,
  16930. eol,
  16931. conn->handled_requests,
  16932. eol);
  16933. connection_info_length += mg_str_append(&buffer, end, block);
  16934. }
  16935. /* Request info */
  16936. if ((state >= 4) && (state < 6)) {
  16937. mg_snprintf(NULL,
  16938. NULL,
  16939. block,
  16940. sizeof(block),
  16941. "%s%s\"request_info\" : {%s"
  16942. "\"method\" : \"%s\",%s"
  16943. "\"uri\" : \"%s\",%s"
  16944. "\"query\" : %s%s%s%s"
  16945. "}",
  16946. (connection_info_length > 1 ? "," : ""),
  16947. eol,
  16948. eol,
  16949. ri->request_method,
  16950. eol,
  16951. ri->request_uri,
  16952. eol,
  16953. ri->query_string ? "\"" : "",
  16954. ri->query_string ? ri->query_string : "null",
  16955. ri->query_string ? "\"" : "",
  16956. eol);
  16957. connection_info_length += mg_str_append(&buffer, end, block);
  16958. }
  16959. /* Execution time information */
  16960. if ((state >= 2) && (state < 9)) {
  16961. char start_time_str[64] = {0};
  16962. char now_str[64] = {0};
  16963. time_t start_time = conn->conn_birth_time;
  16964. time_t now = time(NULL);
  16965. gmt_time_string(start_time_str,
  16966. sizeof(start_time_str) - 1,
  16967. &start_time);
  16968. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16969. mg_snprintf(NULL,
  16970. NULL,
  16971. block,
  16972. sizeof(block),
  16973. "%s%s\"time\" : {%s"
  16974. "\"uptime\" : %.0f,%s"
  16975. "\"start\" : \"%s\",%s"
  16976. "\"now\" : \"%s\"%s"
  16977. "}",
  16978. (connection_info_length > 1 ? "," : ""),
  16979. eol,
  16980. eol,
  16981. difftime(now, start_time),
  16982. eol,
  16983. start_time_str,
  16984. eol,
  16985. now_str,
  16986. eol);
  16987. connection_info_length += mg_str_append(&buffer, end, block);
  16988. }
  16989. /* Remote user name */
  16990. if ((ri->remote_user) && (state < 9)) {
  16991. mg_snprintf(NULL,
  16992. NULL,
  16993. block,
  16994. sizeof(block),
  16995. "%s%s\"user\" : {%s"
  16996. "\"name\" : \"%s\",%s"
  16997. "}",
  16998. (connection_info_length > 1 ? "," : ""),
  16999. eol,
  17000. eol,
  17001. ri->remote_user,
  17002. eol);
  17003. connection_info_length += mg_str_append(&buffer, end, block);
  17004. }
  17005. /* Data block */
  17006. if (state >= 3) {
  17007. mg_snprintf(NULL,
  17008. NULL,
  17009. block,
  17010. sizeof(block),
  17011. "%s%s\"data\" : {%s"
  17012. "\"read\" : %" INT64_FMT ",%s"
  17013. "\"written\" : %" INT64_FMT "%s"
  17014. "}",
  17015. (connection_info_length > 1 ? "," : ""),
  17016. eol,
  17017. eol,
  17018. conn->consumed_content,
  17019. eol,
  17020. conn->num_bytes_sent,
  17021. eol);
  17022. connection_info_length += mg_str_append(&buffer, end, block);
  17023. }
  17024. /* State */
  17025. mg_snprintf(NULL,
  17026. NULL,
  17027. block,
  17028. sizeof(block),
  17029. "%s%s\"state\" : \"%s\"",
  17030. (connection_info_length > 1 ? "," : ""),
  17031. eol,
  17032. state_str);
  17033. connection_info_length += mg_str_append(&buffer, end, block);
  17034. /* Terminate string */
  17035. if (append_eoobj) {
  17036. strcat(append_eoobj, eoobj);
  17037. }
  17038. connection_info_length += sizeof(eoobj) - 1;
  17039. return (int)connection_info_length;
  17040. }
  17041. #endif
  17042. /* Initialize this library. This function does not need to be thread safe.
  17043. */
  17044. unsigned
  17045. mg_init_library(unsigned features)
  17046. {
  17047. #if !defined(NO_SSL)
  17048. char ebuf[128];
  17049. #endif
  17050. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17051. unsigned features_inited = features_to_init;
  17052. if (mg_init_library_called <= 0) {
  17053. /* Not initialized yet */
  17054. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17055. return 0;
  17056. }
  17057. }
  17058. mg_global_lock();
  17059. if (mg_init_library_called <= 0) {
  17060. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17061. /* Fatal error - abort start. However, this situation should
  17062. * never occur in practice. */
  17063. mg_global_unlock();
  17064. return 0;
  17065. }
  17066. #if defined(_WIN32)
  17067. InitializeCriticalSection(&global_log_file_lock);
  17068. #endif
  17069. #if !defined(_WIN32)
  17070. pthread_mutexattr_init(&pthread_mutex_attr);
  17071. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17072. #endif
  17073. #if defined(USE_LUA)
  17074. lua_init_optional_libraries();
  17075. #endif
  17076. }
  17077. mg_global_unlock();
  17078. #if !defined(NO_SSL)
  17079. if (features_to_init & MG_FEATURES_SSL) {
  17080. if (!mg_ssl_initialized) {
  17081. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17082. mg_ssl_initialized = 1;
  17083. } else {
  17084. (void)ebuf;
  17085. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17086. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17087. }
  17088. } else {
  17089. /* ssl already initialized */
  17090. }
  17091. }
  17092. #endif
  17093. /* Start WinSock for Windows */
  17094. mg_global_lock();
  17095. if (mg_init_library_called <= 0) {
  17096. #if defined(_WIN32)
  17097. WSADATA data;
  17098. WSAStartup(MAKEWORD(2, 2), &data);
  17099. #endif /* _WIN32 */
  17100. mg_init_library_called = 1;
  17101. } else {
  17102. mg_init_library_called++;
  17103. }
  17104. mg_global_unlock();
  17105. return features_inited;
  17106. }
  17107. /* Un-initialize this library. */
  17108. unsigned
  17109. mg_exit_library(void)
  17110. {
  17111. if (mg_init_library_called <= 0) {
  17112. return 0;
  17113. }
  17114. mg_global_lock();
  17115. mg_init_library_called--;
  17116. if (mg_init_library_called == 0) {
  17117. #if defined(_WIN32)
  17118. (void)WSACleanup();
  17119. #endif /* _WIN32 */
  17120. #if !defined(NO_SSL)
  17121. if (mg_ssl_initialized) {
  17122. uninitialize_ssl();
  17123. mg_ssl_initialized = 0;
  17124. }
  17125. #endif
  17126. #if defined(_WIN32)
  17127. (void)DeleteCriticalSection(&global_log_file_lock);
  17128. #endif /* _WIN32 */
  17129. #if !defined(_WIN32)
  17130. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17131. #endif
  17132. (void)pthread_key_delete(sTlsKey);
  17133. #if defined(USE_LUA)
  17134. lua_exit_optional_libraries();
  17135. #endif
  17136. mg_global_unlock();
  17137. (void)pthread_mutex_destroy(&global_lock_mutex);
  17138. return 1;
  17139. }
  17140. mg_global_unlock();
  17141. return 1;
  17142. }
  17143. /* End of civetweb.c */