civetweb.c 529 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861
  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 ((long)(0x80000BFFUL))
  1495. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1496. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1497. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1498. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1499. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1500. #define SSL_OP_NO_TLSv1_3 (0x20000000UL)
  1501. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1502. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1503. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1504. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1505. #define SSL_CB_HANDSHAKE_START (0x10)
  1506. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1507. #define SSL_ERROR_NONE (0)
  1508. #define SSL_ERROR_SSL (1)
  1509. #define SSL_ERROR_WANT_READ (2)
  1510. #define SSL_ERROR_WANT_WRITE (3)
  1511. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1512. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1513. #define SSL_ERROR_ZERO_RETURN (6)
  1514. #define SSL_ERROR_WANT_CONNECT (7)
  1515. #define SSL_ERROR_WANT_ACCEPT (8)
  1516. #define TLSEXT_TYPE_server_name (0)
  1517. #define TLSEXT_NAMETYPE_host_name (0)
  1518. #define SSL_TLSEXT_ERR_OK (0)
  1519. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1520. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1521. #define SSL_TLSEXT_ERR_NOACK (3)
  1522. struct ssl_func {
  1523. const char *name; /* SSL function name */
  1524. void (*ptr)(void); /* Function pointer */
  1525. };
  1526. #if defined(OPENSSL_API_1_1)
  1527. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1528. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1529. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1530. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1531. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1532. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1533. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1534. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1535. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1536. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1537. #define OPENSSL_init_ssl \
  1538. (*(int (*)(uint64_t opts, \
  1539. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1540. .ptr)
  1541. #define SSL_CTX_use_PrivateKey_file \
  1542. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1543. #define SSL_CTX_use_certificate_file \
  1544. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1545. #define SSL_CTX_set_default_passwd_cb \
  1546. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1547. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1548. #define SSL_CTX_use_certificate_chain_file \
  1549. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1550. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1551. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1552. #define SSL_CTX_set_verify \
  1553. (*(void (*)(SSL_CTX *, \
  1554. int, \
  1555. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1556. .ptr)
  1557. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1558. #define SSL_CTX_load_verify_locations \
  1559. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1560. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1561. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1562. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1563. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1564. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1565. #define SSL_CIPHER_get_name \
  1566. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1567. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1568. #define SSL_CTX_set_session_id_context \
  1569. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1570. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1571. #define SSL_CTX_set_cipher_list \
  1572. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1573. #define SSL_CTX_set_options \
  1574. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1575. #define SSL_CTX_set_info_callback \
  1576. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1577. ssl_sw[32] \
  1578. .ptr)
  1579. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1580. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1581. #define SSL_CTX_callback_ctrl \
  1582. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1583. #define SSL_get_servername \
  1584. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1585. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1586. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1587. #define SSL_CTX_clear_options(ctx, op) \
  1588. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1589. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1590. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1591. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1592. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1593. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1594. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1595. SSL_CTX_callback_ctrl(ctx, \
  1596. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1597. (void (*)(void))cb)
  1598. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1599. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1600. #define SSL_set_tlsext_host_name(ctx, arg) \
  1601. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1602. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1603. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1604. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1605. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1606. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1607. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1608. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1609. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1610. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1611. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1612. #define X509_NAME_oneline \
  1613. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1614. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1615. #define EVP_get_digestbyname \
  1616. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1617. #define EVP_Digest \
  1618. (*(int (*)( \
  1619. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1620. crypto_sw[9] \
  1621. .ptr)
  1622. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1623. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1624. #define ASN1_INTEGER_to_BN \
  1625. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1626. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1627. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1628. #define OPENSSL_free(a) CRYPTO_free(a)
  1629. #define OPENSSL_REMOVE_THREAD_STATE()
  1630. /* init_ssl_ctx() function updates this array.
  1631. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1632. * of respective functions. The macros above (like SSL_connect()) are really
  1633. * just calling these functions indirectly via the pointer. */
  1634. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1635. {"SSL_accept", NULL},
  1636. {"SSL_connect", NULL},
  1637. {"SSL_read", NULL},
  1638. {"SSL_write", NULL},
  1639. {"SSL_get_error", NULL},
  1640. {"SSL_set_fd", NULL},
  1641. {"SSL_new", NULL},
  1642. {"SSL_CTX_new", NULL},
  1643. {"TLS_server_method", NULL},
  1644. {"OPENSSL_init_ssl", NULL},
  1645. {"SSL_CTX_use_PrivateKey_file", NULL},
  1646. {"SSL_CTX_use_certificate_file", NULL},
  1647. {"SSL_CTX_set_default_passwd_cb", NULL},
  1648. {"SSL_CTX_free", NULL},
  1649. {"SSL_CTX_use_certificate_chain_file", NULL},
  1650. {"TLS_client_method", NULL},
  1651. {"SSL_pending", NULL},
  1652. {"SSL_CTX_set_verify", NULL},
  1653. {"SSL_shutdown", NULL},
  1654. {"SSL_CTX_load_verify_locations", NULL},
  1655. {"SSL_CTX_set_default_verify_paths", NULL},
  1656. {"SSL_CTX_set_verify_depth", NULL},
  1657. {"SSL_get_peer_certificate", NULL},
  1658. {"SSL_get_version", NULL},
  1659. {"SSL_get_current_cipher", NULL},
  1660. {"SSL_CIPHER_get_name", NULL},
  1661. {"SSL_CTX_check_private_key", NULL},
  1662. {"SSL_CTX_set_session_id_context", NULL},
  1663. {"SSL_CTX_ctrl", NULL},
  1664. {"SSL_CTX_set_cipher_list", NULL},
  1665. {"SSL_CTX_set_options", NULL},
  1666. {"SSL_CTX_set_info_callback", NULL},
  1667. {"SSL_get_ex_data", NULL},
  1668. {"SSL_set_ex_data", NULL},
  1669. {"SSL_CTX_callback_ctrl", NULL},
  1670. {"SSL_get_servername", NULL},
  1671. {"SSL_set_SSL_CTX", NULL},
  1672. {"SSL_ctrl", NULL},
  1673. {NULL, NULL}};
  1674. /* Similar array as ssl_sw. These functions could be located in different
  1675. * lib. */
  1676. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1677. {"ERR_error_string", NULL},
  1678. {"CONF_modules_unload", NULL},
  1679. {"X509_free", NULL},
  1680. {"X509_get_subject_name", NULL},
  1681. {"X509_get_issuer_name", NULL},
  1682. {"X509_NAME_oneline", NULL},
  1683. {"X509_get_serialNumber", NULL},
  1684. {"EVP_get_digestbyname", NULL},
  1685. {"EVP_Digest", NULL},
  1686. {"i2d_X509", NULL},
  1687. {"BN_bn2hex", NULL},
  1688. {"ASN1_INTEGER_to_BN", NULL},
  1689. {"BN_free", NULL},
  1690. {"CRYPTO_free", NULL},
  1691. {NULL, NULL}};
  1692. #else
  1693. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1694. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1695. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1696. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1697. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1698. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1699. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1700. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1701. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1702. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1703. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1704. #define SSL_CTX_use_PrivateKey_file \
  1705. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1706. #define SSL_CTX_use_certificate_file \
  1707. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1708. #define SSL_CTX_set_default_passwd_cb \
  1709. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1710. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1711. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1712. #define SSL_CTX_use_certificate_chain_file \
  1713. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1714. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1715. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1716. #define SSL_CTX_set_verify \
  1717. (*(void (*)(SSL_CTX *, \
  1718. int, \
  1719. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1720. .ptr)
  1721. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1722. #define SSL_CTX_load_verify_locations \
  1723. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1724. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1725. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1726. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1727. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1728. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1729. #define SSL_CIPHER_get_name \
  1730. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1731. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1732. #define SSL_CTX_set_session_id_context \
  1733. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1734. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1735. #define SSL_CTX_set_cipher_list \
  1736. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1737. #define SSL_CTX_set_info_callback \
  1738. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1739. .ptr)
  1740. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1741. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1742. #define SSL_CTX_callback_ctrl \
  1743. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1744. #define SSL_get_servername \
  1745. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1746. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1747. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1748. #define SSL_CTX_set_options(ctx, op) \
  1749. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1750. #define SSL_CTX_clear_options(ctx, op) \
  1751. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1752. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1753. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1754. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1755. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1756. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1757. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1758. SSL_CTX_callback_ctrl(ctx, \
  1759. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1760. (void (*)(void))cb)
  1761. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1762. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1763. #define SSL_set_tlsext_host_name(ctx, arg) \
  1764. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1765. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1766. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1767. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1768. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1769. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1770. #define CRYPTO_set_locking_callback \
  1771. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1772. #define CRYPTO_set_id_callback \
  1773. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1774. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1775. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1776. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1777. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1778. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1779. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1780. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1781. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1782. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1783. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1784. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1785. #define X509_NAME_oneline \
  1786. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1787. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1788. #define i2c_ASN1_INTEGER \
  1789. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1790. #define EVP_get_digestbyname \
  1791. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1792. #define EVP_Digest \
  1793. (*(int (*)( \
  1794. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1795. crypto_sw[18] \
  1796. .ptr)
  1797. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1798. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1799. #define ASN1_INTEGER_to_BN \
  1800. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1801. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1802. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1803. #define OPENSSL_free(a) CRYPTO_free(a)
  1804. /* use here ERR_remove_state,
  1805. * while on some platforms function is not included into library due to
  1806. * deprication */
  1807. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1808. /* init_ssl_ctx() function updates this array.
  1809. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1810. * of respective functions. The macros above (like SSL_connect()) are really
  1811. * just calling these functions indirectly via the pointer. */
  1812. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1813. {"SSL_accept", NULL},
  1814. {"SSL_connect", NULL},
  1815. {"SSL_read", NULL},
  1816. {"SSL_write", NULL},
  1817. {"SSL_get_error", NULL},
  1818. {"SSL_set_fd", NULL},
  1819. {"SSL_new", NULL},
  1820. {"SSL_CTX_new", NULL},
  1821. {"SSLv23_server_method", NULL},
  1822. {"SSL_library_init", NULL},
  1823. {"SSL_CTX_use_PrivateKey_file", NULL},
  1824. {"SSL_CTX_use_certificate_file", NULL},
  1825. {"SSL_CTX_set_default_passwd_cb", NULL},
  1826. {"SSL_CTX_free", NULL},
  1827. {"SSL_load_error_strings", NULL},
  1828. {"SSL_CTX_use_certificate_chain_file", NULL},
  1829. {"SSLv23_client_method", NULL},
  1830. {"SSL_pending", NULL},
  1831. {"SSL_CTX_set_verify", NULL},
  1832. {"SSL_shutdown", NULL},
  1833. {"SSL_CTX_load_verify_locations", NULL},
  1834. {"SSL_CTX_set_default_verify_paths", NULL},
  1835. {"SSL_CTX_set_verify_depth", NULL},
  1836. {"SSL_get_peer_certificate", NULL},
  1837. {"SSL_get_version", NULL},
  1838. {"SSL_get_current_cipher", NULL},
  1839. {"SSL_CIPHER_get_name", NULL},
  1840. {"SSL_CTX_check_private_key", NULL},
  1841. {"SSL_CTX_set_session_id_context", NULL},
  1842. {"SSL_CTX_ctrl", NULL},
  1843. {"SSL_CTX_set_cipher_list", NULL},
  1844. {"SSL_CTX_set_info_callback", NULL},
  1845. {"SSL_get_ex_data", NULL},
  1846. {"SSL_set_ex_data", NULL},
  1847. {"SSL_CTX_callback_ctrl", NULL},
  1848. {"SSL_get_servername", NULL},
  1849. {"SSL_set_SSL_CTX", NULL},
  1850. {"SSL_ctrl", NULL},
  1851. {NULL, NULL}};
  1852. /* Similar array as ssl_sw. These functions could be located in different
  1853. * lib. */
  1854. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1855. {"CRYPTO_set_locking_callback", NULL},
  1856. {"CRYPTO_set_id_callback", NULL},
  1857. {"ERR_get_error", NULL},
  1858. {"ERR_error_string", NULL},
  1859. {"ERR_remove_state", NULL},
  1860. {"ERR_free_strings", NULL},
  1861. {"ENGINE_cleanup", NULL},
  1862. {"CONF_modules_unload", NULL},
  1863. {"CRYPTO_cleanup_all_ex_data", NULL},
  1864. {"EVP_cleanup", NULL},
  1865. {"X509_free", NULL},
  1866. {"X509_get_subject_name", NULL},
  1867. {"X509_get_issuer_name", NULL},
  1868. {"X509_NAME_oneline", NULL},
  1869. {"X509_get_serialNumber", NULL},
  1870. {"i2c_ASN1_INTEGER", NULL},
  1871. {"EVP_get_digestbyname", NULL},
  1872. {"EVP_Digest", NULL},
  1873. {"i2d_X509", NULL},
  1874. {"BN_bn2hex", NULL},
  1875. {"ASN1_INTEGER_to_BN", NULL},
  1876. {"BN_free", NULL},
  1877. {"CRYPTO_free", NULL},
  1878. {NULL, NULL}};
  1879. #endif /* OPENSSL_API_1_1 */
  1880. #endif /* NO_SSL_DL */
  1881. #endif /* NO_SSL */
  1882. #if !defined(NO_CACHING)
  1883. static const char month_names[][4] = {"Jan",
  1884. "Feb",
  1885. "Mar",
  1886. "Apr",
  1887. "May",
  1888. "Jun",
  1889. "Jul",
  1890. "Aug",
  1891. "Sep",
  1892. "Oct",
  1893. "Nov",
  1894. "Dec"};
  1895. #endif /* !NO_CACHING */
  1896. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1897. * the
  1898. * union u. */
  1899. union usa {
  1900. struct sockaddr sa;
  1901. struct sockaddr_in sin;
  1902. #if defined(USE_IPV6)
  1903. struct sockaddr_in6 sin6;
  1904. #endif
  1905. };
  1906. /* Describes a string (chunk of memory). */
  1907. struct vec {
  1908. const char *ptr;
  1909. size_t len;
  1910. };
  1911. struct mg_file_stat {
  1912. /* File properties filled by mg_stat: */
  1913. uint64_t size;
  1914. time_t last_modified;
  1915. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1916. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1917. * case we need a "Content-Eencoding: gzip" header */
  1918. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1919. };
  1920. struct mg_file_in_memory {
  1921. char *p;
  1922. uint32_t pos;
  1923. char mode;
  1924. };
  1925. struct mg_file_access {
  1926. /* File properties filled by mg_fopen: */
  1927. FILE *fp;
  1928. #if defined(MG_USE_OPEN_FILE)
  1929. /* TODO (low): Remove obsolete "file in memory" implementation.
  1930. * In an "early 2017" discussion at Google groups
  1931. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1932. * we decided to get rid of this feature (after some fade-out
  1933. * phase). */
  1934. const char *membuf;
  1935. #endif
  1936. };
  1937. struct mg_file {
  1938. struct mg_file_stat stat;
  1939. struct mg_file_access access;
  1940. };
  1941. #if defined(MG_USE_OPEN_FILE)
  1942. #define STRUCT_FILE_INITIALIZER \
  1943. { \
  1944. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1945. { \
  1946. (FILE *)NULL, (const char *)NULL \
  1947. } \
  1948. }
  1949. #else
  1950. #define STRUCT_FILE_INITIALIZER \
  1951. { \
  1952. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1953. { \
  1954. (FILE *)NULL \
  1955. } \
  1956. }
  1957. #endif
  1958. /* Describes listening socket, or socket which was accept()-ed by the master
  1959. * thread and queued for future handling by the worker thread. */
  1960. struct socket {
  1961. SOCKET sock; /* Listening socket */
  1962. union usa lsa; /* Local socket address */
  1963. union usa rsa; /* Remote socket address */
  1964. unsigned char is_ssl; /* Is port SSL-ed */
  1965. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1966. * port */
  1967. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1968. };
  1969. /* Enum const for all options must be in sync with
  1970. * static struct mg_option config_options[]
  1971. * This is tested in the unit test (test/private.c)
  1972. * "Private Config Options"
  1973. */
  1974. enum {
  1975. /* Once for each server */
  1976. LISTENING_PORTS,
  1977. NUM_THREADS,
  1978. RUN_AS_USER,
  1979. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1980. * socket option typedef TCP_NODELAY. */
  1981. MAX_REQUEST_SIZE,
  1982. LINGER_TIMEOUT,
  1983. #if defined(__linux__)
  1984. ALLOW_SENDFILE_CALL,
  1985. #endif
  1986. #if defined(_WIN32)
  1987. CASE_SENSITIVE_FILES,
  1988. #endif
  1989. THROTTLE,
  1990. ACCESS_LOG_FILE,
  1991. ERROR_LOG_FILE,
  1992. ENABLE_KEEP_ALIVE,
  1993. REQUEST_TIMEOUT,
  1994. KEEP_ALIVE_TIMEOUT,
  1995. #if defined(USE_WEBSOCKET)
  1996. WEBSOCKET_TIMEOUT,
  1997. ENABLE_WEBSOCKET_PING_PONG,
  1998. #endif
  1999. DECODE_URL,
  2000. #if defined(USE_LUA)
  2001. LUA_BACKGROUND_SCRIPT,
  2002. LUA_BACKGROUND_SCRIPT_PARAMS,
  2003. #endif
  2004. #if defined(USE_TIMERS)
  2005. CGI_TIMEOUT,
  2006. #endif
  2007. /* Once for each domain */
  2008. DOCUMENT_ROOT,
  2009. CGI_EXTENSIONS,
  2010. CGI_ENVIRONMENT,
  2011. PUT_DELETE_PASSWORDS_FILE,
  2012. CGI_INTERPRETER,
  2013. PROTECT_URI,
  2014. AUTHENTICATION_DOMAIN,
  2015. ENABLE_AUTH_DOMAIN_CHECK,
  2016. SSI_EXTENSIONS,
  2017. ENABLE_DIRECTORY_LISTING,
  2018. GLOBAL_PASSWORDS_FILE,
  2019. INDEX_FILES,
  2020. ACCESS_CONTROL_LIST,
  2021. EXTRA_MIME_TYPES,
  2022. SSL_CERTIFICATE,
  2023. SSL_CERTIFICATE_CHAIN,
  2024. URL_REWRITE_PATTERN,
  2025. HIDE_FILES,
  2026. SSL_DO_VERIFY_PEER,
  2027. SSL_CA_PATH,
  2028. SSL_CA_FILE,
  2029. SSL_VERIFY_DEPTH,
  2030. SSL_DEFAULT_VERIFY_PATHS,
  2031. SSL_CIPHER_LIST,
  2032. SSL_PROTOCOL_VERSION,
  2033. SSL_SHORT_TRUST,
  2034. #if defined(USE_LUA)
  2035. LUA_PRELOAD_FILE,
  2036. LUA_SCRIPT_EXTENSIONS,
  2037. LUA_SERVER_PAGE_EXTENSIONS,
  2038. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2039. LUA_DEBUG_PARAMS,
  2040. #endif
  2041. #endif
  2042. #if defined(USE_DUKTAPE)
  2043. DUKTAPE_SCRIPT_EXTENSIONS,
  2044. #endif
  2045. #if defined(USE_WEBSOCKET)
  2046. WEBSOCKET_ROOT,
  2047. #endif
  2048. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2049. LUA_WEBSOCKET_EXTENSIONS,
  2050. #endif
  2051. ACCESS_CONTROL_ALLOW_ORIGIN,
  2052. ACCESS_CONTROL_ALLOW_METHODS,
  2053. ACCESS_CONTROL_ALLOW_HEADERS,
  2054. ERROR_PAGES,
  2055. #if !defined(NO_CACHING)
  2056. STATIC_FILE_MAX_AGE,
  2057. #endif
  2058. #if !defined(NO_SSL)
  2059. STRICT_HTTPS_MAX_AGE,
  2060. #endif
  2061. ADDITIONAL_HEADER,
  2062. ALLOW_INDEX_SCRIPT_SUB_RES,
  2063. #if defined(DAEMONIZE)
  2064. ENABLE_DAEMONIZE,
  2065. #endif
  2066. NUM_OPTIONS
  2067. };
  2068. /* Config option name, config types, default value.
  2069. * Must be in the same order as the enum const above.
  2070. */
  2071. static const struct mg_option config_options[] = {
  2072. /* Once for each server */
  2073. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2074. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2075. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2076. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2077. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2078. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2079. #if defined(__linux__)
  2080. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2081. #endif
  2082. #if defined(_WIN32)
  2083. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2084. #endif
  2085. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2086. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2087. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2088. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2089. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2090. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2091. #if defined(USE_WEBSOCKET)
  2092. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2093. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2094. #endif
  2095. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2096. #if defined(USE_LUA)
  2097. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2098. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2099. #endif
  2100. #if defined(USE_TIMERS)
  2101. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2102. #endif
  2103. /* Once for each domain */
  2104. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2105. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2106. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2107. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2108. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2109. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2110. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2111. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2112. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2113. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2114. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2115. {"index_files",
  2116. MG_CONFIG_TYPE_STRING_LIST,
  2117. #if defined(USE_LUA)
  2118. "index.xhtml,index.html,index.htm,"
  2119. "index.lp,index.lsp,index.lua,index.cgi,"
  2120. "index.shtml,index.php"},
  2121. #else
  2122. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2123. #endif
  2124. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2125. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2126. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2127. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2128. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2129. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2130. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2131. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2132. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2133. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2134. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2135. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2136. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2137. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2138. #if defined(USE_LUA)
  2139. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2140. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2141. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2142. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2143. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2144. #endif
  2145. #endif
  2146. #if defined(USE_DUKTAPE)
  2147. /* The support for duktape is still in alpha version state.
  2148. * The name of this config option might change. */
  2149. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2150. #endif
  2151. #if defined(USE_WEBSOCKET)
  2152. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2153. #endif
  2154. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2155. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2156. #endif
  2157. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2158. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2159. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2160. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2161. #if !defined(NO_CACHING)
  2162. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2163. #endif
  2164. #if !defined(NO_SSL)
  2165. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2166. #endif
  2167. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2168. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2169. #if defined(DAEMONIZE)
  2170. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2171. #endif
  2172. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2173. /* Check if the config_options and the corresponding enum have compatible
  2174. * sizes. */
  2175. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2176. == (NUM_OPTIONS + 1),
  2177. "config_options and enum not sync");
  2178. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2179. struct mg_handler_info {
  2180. /* Name/Pattern of the URI. */
  2181. char *uri;
  2182. size_t uri_len;
  2183. /* handler type */
  2184. int handler_type;
  2185. /* Handler for http/https or authorization requests. */
  2186. mg_request_handler handler;
  2187. unsigned int refcount;
  2188. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2189. pthread_cond_t
  2190. refcount_cond; /* Signaled when handler refcount is decremented */
  2191. /* Handler for ws/wss (websocket) requests. */
  2192. mg_websocket_connect_handler connect_handler;
  2193. mg_websocket_ready_handler ready_handler;
  2194. mg_websocket_data_handler data_handler;
  2195. mg_websocket_close_handler close_handler;
  2196. /* accepted subprotocols for ws/wss requests. */
  2197. struct mg_websocket_subprotocols *subprotocols;
  2198. /* Handler for authorization requests */
  2199. mg_authorization_handler auth_handler;
  2200. /* User supplied argument for the handler function. */
  2201. void *cbdata;
  2202. /* next handler in a linked list */
  2203. struct mg_handler_info *next;
  2204. };
  2205. enum {
  2206. CONTEXT_INVALID,
  2207. CONTEXT_SERVER,
  2208. CONTEXT_HTTP_CLIENT,
  2209. CONTEXT_WS_CLIENT
  2210. };
  2211. struct mg_domain_context {
  2212. SSL_CTX *ssl_ctx; /* SSL context */
  2213. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2214. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2215. /* Server nonce */
  2216. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2217. unsigned long nonce_count; /* Used nonces, used for authentication */
  2218. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2219. /* linked list of shared lua websockets */
  2220. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2221. #endif
  2222. /* Linked list of domains */
  2223. struct mg_domain_context *next;
  2224. };
  2225. struct mg_context {
  2226. /* Part 1 - Physical context:
  2227. * This holds threads, ports, timeouts, ...
  2228. * set for the entire server, independent from the
  2229. * addressed hostname.
  2230. */
  2231. /* Connection related */
  2232. int context_type; /* See CONTEXT_* above */
  2233. struct socket *listening_sockets;
  2234. struct mg_pollfd *listening_socket_fds;
  2235. unsigned int num_listening_sockets;
  2236. struct mg_connection *worker_connections; /* The connection struct, pre-
  2237. * allocated for each worker */
  2238. #if defined(USE_SERVER_STATS)
  2239. int active_connections;
  2240. int max_connections;
  2241. int64_t total_connections;
  2242. int64_t total_requests;
  2243. int64_t total_data_read;
  2244. int64_t total_data_written;
  2245. #endif
  2246. /* Thread related */
  2247. volatile int stop_flag; /* Should we stop event loop */
  2248. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2249. pthread_t masterthreadid; /* The master thread ID */
  2250. unsigned int
  2251. cfg_worker_threads; /* The number of configured worker threads. */
  2252. pthread_t *worker_threadids; /* The worker thread IDs */
  2253. /* Connection to thread dispatching */
  2254. #if defined(ALTERNATIVE_QUEUE)
  2255. struct socket *client_socks;
  2256. void **client_wait_events;
  2257. #else
  2258. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2259. volatile int sq_head; /* Head of the socket queue */
  2260. volatile int sq_tail; /* Tail of the socket queue */
  2261. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2262. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2263. #endif
  2264. /* Memory related */
  2265. unsigned int max_request_size; /* The max request size */
  2266. #if defined(USE_SERVER_STATS)
  2267. struct mg_memory_stat ctx_memory;
  2268. #endif
  2269. /* Operating system related */
  2270. char *systemName; /* What operating system is running */
  2271. time_t start_time; /* Server start time, used for authentication
  2272. * and for diagnstics. */
  2273. #if defined(USE_TIMERS)
  2274. struct ttimers *timers;
  2275. #endif
  2276. /* Lua specific: Background operations and shared websockets */
  2277. #if defined(USE_LUA)
  2278. void *lua_background_state;
  2279. #endif
  2280. /* Server nonce */
  2281. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2282. /* Server callbacks */
  2283. struct mg_callbacks callbacks; /* User-defined callback function */
  2284. void *user_data; /* User-defined data */
  2285. /* Part 2 - Logical domain:
  2286. * This holds hostname, TLS certificate, document root, ...
  2287. * set for a domain hosted at the server.
  2288. * There may be multiple domains hosted at one physical server.
  2289. * The default domain "dd" is the first element of a list of
  2290. * domains.
  2291. */
  2292. struct mg_domain_context dd; /* default domain */
  2293. };
  2294. #if defined(USE_SERVER_STATS)
  2295. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2296. static struct mg_memory_stat *
  2297. get_memory_stat(struct mg_context *ctx)
  2298. {
  2299. if (ctx) {
  2300. return &(ctx->ctx_memory);
  2301. }
  2302. return &mg_common_memory;
  2303. }
  2304. #endif
  2305. enum {
  2306. CONNECTION_TYPE_INVALID,
  2307. CONNECTION_TYPE_REQUEST,
  2308. CONNECTION_TYPE_RESPONSE
  2309. };
  2310. struct mg_connection {
  2311. int connection_type; /* see CONNECTION_TYPE_* above */
  2312. struct mg_request_info request_info;
  2313. struct mg_response_info response_info;
  2314. struct mg_context *phys_ctx;
  2315. struct mg_domain_context *dom_ctx;
  2316. #if defined(USE_SERVER_STATS)
  2317. int conn_state; /* 0 = undef, numerical value may change in different
  2318. * versions. For the current definition, see
  2319. * mg_get_connection_info_impl */
  2320. #endif
  2321. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2322. SSL *ssl; /* SSL descriptor */
  2323. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2324. struct socket client; /* Connected client */
  2325. time_t conn_birth_time; /* Time (wall clock) when connection was
  2326. * established */
  2327. struct timespec req_time; /* Time (since system start) when the request
  2328. * was received */
  2329. int64_t num_bytes_sent; /* Total bytes sent to client */
  2330. int64_t content_len; /* Content-Length header value */
  2331. int64_t consumed_content; /* How many bytes of content have been read */
  2332. int is_chunked; /* Transfer-Encoding is chunked:
  2333. * 0 = not chunked,
  2334. * 1 = chunked, do data read yet,
  2335. * 2 = chunked, some data read,
  2336. * 3 = chunked, all data read
  2337. */
  2338. size_t chunk_remainder; /* Unread data from the last chunk */
  2339. char *buf; /* Buffer for received data */
  2340. char *path_info; /* PATH_INFO part of the URL */
  2341. int must_close; /* 1 if connection must be closed */
  2342. int accept_gzip; /* 1 if gzip encoding is accepted */
  2343. int in_error_handler; /* 1 if in handler for user defined error
  2344. * pages */
  2345. #if defined(USE_WEBSOCKET)
  2346. int in_websocket_handling; /* 1 if in read_websocket */
  2347. #endif
  2348. int handled_requests; /* Number of requests handled by this connection
  2349. */
  2350. int buf_size; /* Buffer size */
  2351. int request_len; /* Size of the request + headers in a buffer */
  2352. int data_len; /* Total size of data in a buffer */
  2353. int status_code; /* HTTP reply status code, e.g. 200 */
  2354. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2355. * throttle */
  2356. time_t last_throttle_time; /* Last time throttled data was sent */
  2357. int last_throttle_bytes; /* Bytes sent this second */
  2358. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2359. * atomic transmissions for websockets */
  2360. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2361. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2362. #endif
  2363. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2364. * for quick access */
  2365. };
  2366. /* Directory entry */
  2367. struct de {
  2368. struct mg_connection *conn;
  2369. char *file_name;
  2370. struct mg_file_stat file;
  2371. };
  2372. #if defined(USE_WEBSOCKET)
  2373. static int is_websocket_protocol(const struct mg_connection *conn);
  2374. #else
  2375. #define is_websocket_protocol(conn) (0)
  2376. #endif
  2377. #define mg_cry_internal(conn, fmt, ...) \
  2378. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2379. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2380. const char *func,
  2381. unsigned line,
  2382. const char *fmt,
  2383. ...) PRINTF_ARGS(4, 5);
  2384. #if !defined(NO_THREAD_NAME)
  2385. #if defined(_WIN32) && defined(_MSC_VER)
  2386. /* Set the thread name for debugging purposes in Visual Studio
  2387. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2388. */
  2389. #pragma pack(push, 8)
  2390. typedef struct tagTHREADNAME_INFO {
  2391. DWORD dwType; /* Must be 0x1000. */
  2392. LPCSTR szName; /* Pointer to name (in user addr space). */
  2393. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2394. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2395. } THREADNAME_INFO;
  2396. #pragma pack(pop)
  2397. #elif defined(__linux__)
  2398. #include <sys/prctl.h>
  2399. #include <sys/sendfile.h>
  2400. #if defined(ALTERNATIVE_QUEUE)
  2401. #include <sys/eventfd.h>
  2402. #endif /* ALTERNATIVE_QUEUE */
  2403. #if defined(ALTERNATIVE_QUEUE)
  2404. static void *
  2405. event_create(void)
  2406. {
  2407. int evhdl = eventfd(0, EFD_CLOEXEC);
  2408. int *ret;
  2409. if (evhdl == -1) {
  2410. /* Linux uses -1 on error, Windows NULL. */
  2411. /* However, Linux does not return 0 on success either. */
  2412. return 0;
  2413. }
  2414. ret = (int *)mg_malloc(sizeof(int));
  2415. if (ret) {
  2416. *ret = evhdl;
  2417. } else {
  2418. (void)close(evhdl);
  2419. }
  2420. return (void *)ret;
  2421. }
  2422. static int
  2423. event_wait(void *eventhdl)
  2424. {
  2425. uint64_t u;
  2426. int evhdl, s;
  2427. if (!eventhdl) {
  2428. /* error */
  2429. return 0;
  2430. }
  2431. evhdl = *(int *)eventhdl;
  2432. s = (int)read(evhdl, &u, sizeof(u));
  2433. if (s != sizeof(u)) {
  2434. /* error */
  2435. return 0;
  2436. }
  2437. (void)u; /* the value is not required */
  2438. return 1;
  2439. }
  2440. static int
  2441. event_signal(void *eventhdl)
  2442. {
  2443. uint64_t u = 1;
  2444. int evhdl, s;
  2445. if (!eventhdl) {
  2446. /* error */
  2447. return 0;
  2448. }
  2449. evhdl = *(int *)eventhdl;
  2450. s = (int)write(evhdl, &u, sizeof(u));
  2451. if (s != sizeof(u)) {
  2452. /* error */
  2453. return 0;
  2454. }
  2455. return 1;
  2456. }
  2457. static void
  2458. event_destroy(void *eventhdl)
  2459. {
  2460. int evhdl;
  2461. if (!eventhdl) {
  2462. /* error */
  2463. return;
  2464. }
  2465. evhdl = *(int *)eventhdl;
  2466. close(evhdl);
  2467. mg_free(eventhdl);
  2468. }
  2469. #endif
  2470. #endif
  2471. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2472. struct posix_event {
  2473. pthread_mutex_t mutex;
  2474. pthread_cond_t cond;
  2475. int signaled;
  2476. };
  2477. static void *
  2478. event_create(void)
  2479. {
  2480. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2481. if (ret == 0) {
  2482. /* out of memory */
  2483. return 0;
  2484. }
  2485. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2486. /* pthread mutex not available */
  2487. mg_free(ret);
  2488. return 0;
  2489. }
  2490. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2491. /* pthread cond not available */
  2492. pthread_mutex_destroy(&(ret->mutex));
  2493. mg_free(ret);
  2494. return 0;
  2495. }
  2496. ret->signaled = 0;
  2497. return (void *)ret;
  2498. }
  2499. static int
  2500. event_wait(void *eventhdl)
  2501. {
  2502. struct posix_event *ev = (struct posix_event *)eventhdl;
  2503. pthread_mutex_lock(&(ev->mutex));
  2504. while (!ev->signaled) {
  2505. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2506. }
  2507. ev->signaled = 0;
  2508. pthread_mutex_unlock(&(ev->mutex));
  2509. return 1;
  2510. }
  2511. static int
  2512. event_signal(void *eventhdl)
  2513. {
  2514. struct posix_event *ev = (struct posix_event *)eventhdl;
  2515. pthread_mutex_lock(&(ev->mutex));
  2516. pthread_cond_signal(&(ev->cond));
  2517. ev->signaled = 1;
  2518. pthread_mutex_unlock(&(ev->mutex));
  2519. return 1;
  2520. }
  2521. static void
  2522. event_destroy(void *eventhdl)
  2523. {
  2524. struct posix_event *ev = (struct posix_event *)eventhdl;
  2525. pthread_cond_destroy(&(ev->cond));
  2526. pthread_mutex_destroy(&(ev->mutex));
  2527. mg_free(ev);
  2528. }
  2529. #endif
  2530. static void
  2531. mg_set_thread_name(const char *name)
  2532. {
  2533. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2534. mg_snprintf(
  2535. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2536. #if defined(_WIN32)
  2537. #if defined(_MSC_VER)
  2538. /* Windows and Visual Studio Compiler */
  2539. __try {
  2540. THREADNAME_INFO info;
  2541. info.dwType = 0x1000;
  2542. info.szName = threadName;
  2543. info.dwThreadID = ~0U;
  2544. info.dwFlags = 0;
  2545. RaiseException(0x406D1388,
  2546. 0,
  2547. sizeof(info) / sizeof(ULONG_PTR),
  2548. (ULONG_PTR *)&info);
  2549. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2550. }
  2551. #elif defined(__MINGW32__)
  2552. /* No option known to set thread name for MinGW */
  2553. #endif
  2554. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2555. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2556. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2557. #if defined(__MACH__)
  2558. /* OS X only current thread name can be changed */
  2559. (void)pthread_setname_np(threadName);
  2560. #else
  2561. (void)pthread_setname_np(pthread_self(), threadName);
  2562. #endif
  2563. #elif defined(__linux__)
  2564. /* on linux we can use the old prctl function */
  2565. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2566. #endif
  2567. }
  2568. #else /* !defined(NO_THREAD_NAME) */
  2569. void
  2570. mg_set_thread_name(const char *threadName)
  2571. {
  2572. }
  2573. #endif
  2574. #if defined(MG_LEGACY_INTERFACE)
  2575. const char **
  2576. mg_get_valid_option_names(void)
  2577. {
  2578. /* This function is deprecated. Use mg_get_valid_options instead. */
  2579. static const char
  2580. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2581. int i;
  2582. for (i = 0; config_options[i].name != NULL; i++) {
  2583. data[i * 2] = config_options[i].name;
  2584. data[i * 2 + 1] = config_options[i].default_value;
  2585. }
  2586. return data;
  2587. }
  2588. #endif
  2589. const struct mg_option *
  2590. mg_get_valid_options(void)
  2591. {
  2592. return config_options;
  2593. }
  2594. /* Do not open file (used in is_file_in_memory) */
  2595. #define MG_FOPEN_MODE_NONE (0)
  2596. /* Open file for read only access */
  2597. #define MG_FOPEN_MODE_READ (1)
  2598. /* Open file for writing, create and overwrite */
  2599. #define MG_FOPEN_MODE_WRITE (2)
  2600. /* Open file for writing, create and append */
  2601. #define MG_FOPEN_MODE_APPEND (4)
  2602. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2603. * output filep and return 1, otherwise return 0 and don't modify anything.
  2604. */
  2605. static int
  2606. open_file_in_memory(const struct mg_connection *conn,
  2607. const char *path,
  2608. struct mg_file *filep,
  2609. int mode)
  2610. {
  2611. #if defined(MG_USE_OPEN_FILE)
  2612. size_t size = 0;
  2613. const char *buf = NULL;
  2614. if (!conn) {
  2615. return 0;
  2616. }
  2617. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2618. return 0;
  2619. }
  2620. if (conn->phys_ctx->callbacks.open_file) {
  2621. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2622. if (buf != NULL) {
  2623. if (filep == NULL) {
  2624. /* This is a file in memory, but we cannot store the
  2625. * properties
  2626. * now.
  2627. * Called from "is_file_in_memory" function. */
  2628. return 1;
  2629. }
  2630. /* NOTE: override filep->size only on success. Otherwise, it
  2631. * might
  2632. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2633. filep->access.membuf = buf;
  2634. filep->access.fp = NULL;
  2635. /* Size was set by the callback */
  2636. filep->stat.size = size;
  2637. /* Assume the data may change during runtime by setting
  2638. * last_modified = now */
  2639. filep->stat.last_modified = time(NULL);
  2640. filep->stat.is_directory = 0;
  2641. filep->stat.is_gzipped = 0;
  2642. }
  2643. }
  2644. return (buf != NULL);
  2645. #else
  2646. (void)conn;
  2647. (void)path;
  2648. (void)filep;
  2649. (void)mode;
  2650. return 0;
  2651. #endif
  2652. }
  2653. static int
  2654. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2655. {
  2656. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2657. }
  2658. static int
  2659. is_file_opened(const struct mg_file_access *fileacc)
  2660. {
  2661. if (!fileacc) {
  2662. return 0;
  2663. }
  2664. #if defined(MG_USE_OPEN_FILE)
  2665. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2666. #else
  2667. return (fileacc->fp != NULL);
  2668. #endif
  2669. }
  2670. static int mg_stat(const struct mg_connection *conn,
  2671. const char *path,
  2672. struct mg_file_stat *filep);
  2673. /* mg_fopen will open a file either in memory or on the disk.
  2674. * The input parameter path is a string in UTF-8 encoding.
  2675. * The input parameter mode is MG_FOPEN_MODE_*
  2676. * On success, either fp or membuf will be set in the output
  2677. * struct file. All status members will also be set.
  2678. * The function returns 1 on success, 0 on error. */
  2679. static int
  2680. mg_fopen(const struct mg_connection *conn,
  2681. const char *path,
  2682. int mode,
  2683. struct mg_file *filep)
  2684. {
  2685. int found;
  2686. if (!filep) {
  2687. return 0;
  2688. }
  2689. filep->access.fp = NULL;
  2690. #if defined(MG_USE_OPEN_FILE)
  2691. filep->access.membuf = NULL;
  2692. #endif
  2693. if (!is_file_in_memory(conn, path)) {
  2694. /* filep is initialized in mg_stat: all fields with memset to,
  2695. * some fields like size and modification date with values */
  2696. found = mg_stat(conn, path, &(filep->stat));
  2697. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2698. /* file does not exist and will not be created */
  2699. return 0;
  2700. }
  2701. #if defined(_WIN32)
  2702. {
  2703. wchar_t wbuf[W_PATH_MAX];
  2704. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2705. switch (mode) {
  2706. case MG_FOPEN_MODE_READ:
  2707. filep->access.fp = _wfopen(wbuf, L"rb");
  2708. break;
  2709. case MG_FOPEN_MODE_WRITE:
  2710. filep->access.fp = _wfopen(wbuf, L"wb");
  2711. break;
  2712. case MG_FOPEN_MODE_APPEND:
  2713. filep->access.fp = _wfopen(wbuf, L"ab");
  2714. break;
  2715. }
  2716. }
  2717. #else
  2718. /* Linux et al already use unicode. No need to convert. */
  2719. switch (mode) {
  2720. case MG_FOPEN_MODE_READ:
  2721. filep->access.fp = fopen(path, "r");
  2722. break;
  2723. case MG_FOPEN_MODE_WRITE:
  2724. filep->access.fp = fopen(path, "w");
  2725. break;
  2726. case MG_FOPEN_MODE_APPEND:
  2727. filep->access.fp = fopen(path, "a");
  2728. break;
  2729. }
  2730. #endif
  2731. if (!found) {
  2732. /* File did not exist before fopen was called.
  2733. * Maybe it has been created now. Get stat info
  2734. * like creation time now. */
  2735. found = mg_stat(conn, path, &(filep->stat));
  2736. (void)found;
  2737. }
  2738. /* file is on disk */
  2739. return (filep->access.fp != NULL);
  2740. } else {
  2741. #if defined(MG_USE_OPEN_FILE)
  2742. /* is_file_in_memory returned true */
  2743. if (open_file_in_memory(conn, path, filep, mode)) {
  2744. /* file is in memory */
  2745. return (filep->access.membuf != NULL);
  2746. }
  2747. #endif
  2748. }
  2749. /* Open failed */
  2750. return 0;
  2751. }
  2752. /* return 0 on success, just like fclose */
  2753. static int
  2754. mg_fclose(struct mg_file_access *fileacc)
  2755. {
  2756. int ret = -1;
  2757. if (fileacc != NULL) {
  2758. if (fileacc->fp != NULL) {
  2759. ret = fclose(fileacc->fp);
  2760. #if defined(MG_USE_OPEN_FILE)
  2761. } else if (fileacc->membuf != NULL) {
  2762. ret = 0;
  2763. #endif
  2764. }
  2765. /* reset all members of fileacc */
  2766. memset(fileacc, 0, sizeof(*fileacc));
  2767. }
  2768. return ret;
  2769. }
  2770. static void
  2771. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2772. {
  2773. for (; *src != '\0' && n > 1; n--) {
  2774. *dst++ = *src++;
  2775. }
  2776. *dst = '\0';
  2777. }
  2778. static int
  2779. lowercase(const char *s)
  2780. {
  2781. return tolower((unsigned char)*s);
  2782. }
  2783. int
  2784. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2785. {
  2786. int diff = 0;
  2787. if (len > 0) {
  2788. do {
  2789. diff = lowercase(s1++) - lowercase(s2++);
  2790. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2791. }
  2792. return diff;
  2793. }
  2794. int
  2795. mg_strcasecmp(const char *s1, const char *s2)
  2796. {
  2797. int diff;
  2798. do {
  2799. diff = lowercase(s1++) - lowercase(s2++);
  2800. } while (diff == 0 && s1[-1] != '\0');
  2801. return diff;
  2802. }
  2803. static char *
  2804. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2805. {
  2806. char *p;
  2807. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2808. * defined */
  2809. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2810. mg_strlcpy(p, ptr, len + 1);
  2811. }
  2812. return p;
  2813. }
  2814. static char *
  2815. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2816. {
  2817. return mg_strndup_ctx(str, strlen(str), ctx);
  2818. }
  2819. static char *
  2820. mg_strdup(const char *str)
  2821. {
  2822. return mg_strndup_ctx(str, strlen(str), NULL);
  2823. }
  2824. static const char *
  2825. mg_strcasestr(const char *big_str, const char *small_str)
  2826. {
  2827. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2828. if (big_len >= small_len) {
  2829. for (i = 0; i <= (big_len - small_len); i++) {
  2830. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2831. return big_str + i;
  2832. }
  2833. }
  2834. }
  2835. return NULL;
  2836. }
  2837. /* Return null terminated string of given maximum length.
  2838. * Report errors if length is exceeded. */
  2839. static void
  2840. mg_vsnprintf(const struct mg_connection *conn,
  2841. int *truncated,
  2842. char *buf,
  2843. size_t buflen,
  2844. const char *fmt,
  2845. va_list ap)
  2846. {
  2847. int n, ok;
  2848. if (buflen == 0) {
  2849. if (truncated) {
  2850. *truncated = 1;
  2851. }
  2852. return;
  2853. }
  2854. #if defined(__clang__)
  2855. #pragma clang diagnostic push
  2856. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2857. /* Using fmt as a non-literal is intended here, since it is mostly called
  2858. * indirectly by mg_snprintf */
  2859. #endif
  2860. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2861. ok = (n >= 0) && ((size_t)n < buflen);
  2862. #if defined(__clang__)
  2863. #pragma clang diagnostic pop
  2864. #endif
  2865. if (ok) {
  2866. if (truncated) {
  2867. *truncated = 0;
  2868. }
  2869. } else {
  2870. if (truncated) {
  2871. *truncated = 1;
  2872. }
  2873. mg_cry_internal(conn,
  2874. "truncating vsnprintf buffer: [%.*s]",
  2875. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2876. buf);
  2877. n = (int)buflen - 1;
  2878. }
  2879. buf[n] = '\0';
  2880. }
  2881. static void
  2882. mg_snprintf(const struct mg_connection *conn,
  2883. int *truncated,
  2884. char *buf,
  2885. size_t buflen,
  2886. const char *fmt,
  2887. ...)
  2888. {
  2889. va_list ap;
  2890. va_start(ap, fmt);
  2891. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2892. va_end(ap);
  2893. }
  2894. static int
  2895. get_option_index(const char *name)
  2896. {
  2897. int i;
  2898. for (i = 0; config_options[i].name != NULL; i++) {
  2899. if (strcmp(config_options[i].name, name) == 0) {
  2900. return i;
  2901. }
  2902. }
  2903. return -1;
  2904. }
  2905. const char *
  2906. mg_get_option(const struct mg_context *ctx, const char *name)
  2907. {
  2908. int i;
  2909. if ((i = get_option_index(name)) == -1) {
  2910. return NULL;
  2911. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2912. return "";
  2913. } else {
  2914. return ctx->dd.config[i];
  2915. }
  2916. }
  2917. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2918. struct mg_context *
  2919. mg_get_context(const struct mg_connection *conn)
  2920. {
  2921. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2922. }
  2923. void *
  2924. mg_get_user_data(const struct mg_context *ctx)
  2925. {
  2926. return (ctx == NULL) ? NULL : ctx->user_data;
  2927. }
  2928. void *
  2929. mg_get_thread_pointer(const struct mg_connection *conn)
  2930. {
  2931. /* both methods should return the same pointer */
  2932. if (conn) {
  2933. /* quick access, in case conn is known */
  2934. return conn->tls_user_ptr;
  2935. } else {
  2936. /* otherwise get pointer from thread local storage (TLS) */
  2937. struct mg_workerTLS *tls =
  2938. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2939. return tls->user_ptr;
  2940. }
  2941. }
  2942. void
  2943. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2944. {
  2945. if (conn != NULL) {
  2946. conn->request_info.conn_data = data;
  2947. }
  2948. }
  2949. void *
  2950. mg_get_user_connection_data(const struct mg_connection *conn)
  2951. {
  2952. if (conn != NULL) {
  2953. return conn->request_info.conn_data;
  2954. }
  2955. return NULL;
  2956. }
  2957. #if defined(MG_LEGACY_INTERFACE)
  2958. /* Deprecated: Use mg_get_server_ports instead. */
  2959. size_t
  2960. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2961. {
  2962. size_t i;
  2963. if (!ctx) {
  2964. return 0;
  2965. }
  2966. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2967. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2968. ports[i] =
  2969. #if defined(USE_IPV6)
  2970. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2971. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2972. :
  2973. #endif
  2974. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2975. }
  2976. return i;
  2977. }
  2978. #endif
  2979. int
  2980. mg_get_server_ports(const struct mg_context *ctx,
  2981. int size,
  2982. struct mg_server_port *ports)
  2983. {
  2984. int i, cnt = 0;
  2985. if (size <= 0) {
  2986. return -1;
  2987. }
  2988. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2989. if (!ctx) {
  2990. return -1;
  2991. }
  2992. if (!ctx->listening_sockets) {
  2993. return -1;
  2994. }
  2995. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2996. ports[cnt].port =
  2997. #if defined(USE_IPV6)
  2998. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2999. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3000. :
  3001. #endif
  3002. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3003. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3004. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3005. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3006. /* IPv4 */
  3007. ports[cnt].protocol = 1;
  3008. cnt++;
  3009. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3010. /* IPv6 */
  3011. ports[cnt].protocol = 3;
  3012. cnt++;
  3013. }
  3014. }
  3015. return cnt;
  3016. }
  3017. static void
  3018. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3019. {
  3020. buf[0] = '\0';
  3021. if (!usa) {
  3022. return;
  3023. }
  3024. if (usa->sa.sa_family == AF_INET) {
  3025. getnameinfo(&usa->sa,
  3026. sizeof(usa->sin),
  3027. buf,
  3028. (unsigned)len,
  3029. NULL,
  3030. 0,
  3031. NI_NUMERICHOST);
  3032. }
  3033. #if defined(USE_IPV6)
  3034. else if (usa->sa.sa_family == AF_INET6) {
  3035. getnameinfo(&usa->sa,
  3036. sizeof(usa->sin6),
  3037. buf,
  3038. (unsigned)len,
  3039. NULL,
  3040. 0,
  3041. NI_NUMERICHOST);
  3042. }
  3043. #endif
  3044. }
  3045. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3046. * included in all responses other than 100, 101, 5xx. */
  3047. static void
  3048. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3049. {
  3050. #if !defined(REENTRANT_TIME)
  3051. struct tm *tm;
  3052. tm = ((t != NULL) ? gmtime(t) : NULL);
  3053. if (tm != NULL) {
  3054. #else
  3055. struct tm _tm;
  3056. struct tm *tm = &_tm;
  3057. if (t != NULL) {
  3058. gmtime_r(t, tm);
  3059. #endif
  3060. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3061. } else {
  3062. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3063. buf[buf_len - 1] = '\0';
  3064. }
  3065. }
  3066. /* difftime for struct timespec. Return value is in seconds. */
  3067. static double
  3068. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3069. {
  3070. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3071. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3072. }
  3073. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3074. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3075. const char *func,
  3076. unsigned line,
  3077. const char *fmt,
  3078. va_list ap);
  3079. #include "external_mg_cry_internal_impl.inl"
  3080. #else
  3081. /* Print error message to the opened error log stream. */
  3082. static void
  3083. mg_cry_internal_impl(const struct mg_connection *conn,
  3084. const char *func,
  3085. unsigned line,
  3086. const char *fmt,
  3087. va_list ap)
  3088. {
  3089. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3090. struct mg_file fi;
  3091. time_t timestamp;
  3092. /* Unused, in the RELEASE build */
  3093. (void)func;
  3094. (void)line;
  3095. #if defined(GCC_DIAGNOSTIC)
  3096. #pragma GCC diagnostic push
  3097. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3098. #endif
  3099. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3100. #if defined(GCC_DIAGNOSTIC)
  3101. #pragma GCC diagnostic pop
  3102. #endif
  3103. buf[sizeof(buf) - 1] = 0;
  3104. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3105. if (!conn) {
  3106. puts(buf);
  3107. return;
  3108. }
  3109. /* Do not lock when getting the callback value, here and below.
  3110. * I suppose this is fine, since function cannot disappear in the
  3111. * same way string option can. */
  3112. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3113. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3114. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3115. if (mg_fopen(conn,
  3116. conn->dom_ctx->config[ERROR_LOG_FILE],
  3117. MG_FOPEN_MODE_APPEND,
  3118. &fi)
  3119. == 0) {
  3120. fi.access.fp = NULL;
  3121. }
  3122. } else {
  3123. fi.access.fp = NULL;
  3124. }
  3125. if (fi.access.fp != NULL) {
  3126. flockfile(fi.access.fp);
  3127. timestamp = time(NULL);
  3128. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3129. fprintf(fi.access.fp,
  3130. "[%010lu] [error] [client %s] ",
  3131. (unsigned long)timestamp,
  3132. src_addr);
  3133. if (conn->request_info.request_method != NULL) {
  3134. fprintf(fi.access.fp,
  3135. "%s %s: ",
  3136. conn->request_info.request_method,
  3137. conn->request_info.request_uri
  3138. ? conn->request_info.request_uri
  3139. : "");
  3140. }
  3141. fprintf(fi.access.fp, "%s", buf);
  3142. fputc('\n', fi.access.fp);
  3143. fflush(fi.access.fp);
  3144. funlockfile(fi.access.fp);
  3145. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3146. * mg_cry here anyway ;-) */
  3147. }
  3148. }
  3149. }
  3150. #endif /* Externally provided function */
  3151. static void
  3152. mg_cry_internal_wrap(const struct mg_connection *conn,
  3153. const char *func,
  3154. unsigned line,
  3155. const char *fmt,
  3156. ...)
  3157. {
  3158. va_list ap;
  3159. va_start(ap, fmt);
  3160. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3161. va_end(ap);
  3162. }
  3163. void
  3164. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3165. {
  3166. va_list ap;
  3167. va_start(ap, fmt);
  3168. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3169. va_end(ap);
  3170. }
  3171. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3172. /* Return fake connection structure. Used for logging, if connection
  3173. * is not applicable at the moment of logging. */
  3174. static struct mg_connection *
  3175. fc(struct mg_context *ctx)
  3176. {
  3177. static struct mg_connection fake_connection;
  3178. fake_connection.phys_ctx = ctx;
  3179. fake_connection.dom_ctx = &(ctx->dd);
  3180. return &fake_connection;
  3181. }
  3182. const char *
  3183. mg_version(void)
  3184. {
  3185. return CIVETWEB_VERSION;
  3186. }
  3187. const struct mg_request_info *
  3188. mg_get_request_info(const struct mg_connection *conn)
  3189. {
  3190. if (!conn) {
  3191. return NULL;
  3192. }
  3193. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3194. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3195. char txt[16];
  3196. struct mg_workerTLS *tls =
  3197. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3198. sprintf(txt, "%03i", conn->response_info.status_code);
  3199. if (strlen(txt) == 3) {
  3200. memcpy(tls->txtbuf, txt, 4);
  3201. } else {
  3202. strcpy(tls->txtbuf, "ERR");
  3203. }
  3204. ((struct mg_connection *)conn)->request_info.local_uri =
  3205. ((struct mg_connection *)conn)->request_info.request_uri =
  3206. tls->txtbuf; /* use thread safe buffer */
  3207. ((struct mg_connection *)conn)->request_info.num_headers =
  3208. conn->response_info.num_headers;
  3209. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3210. conn->response_info.http_headers,
  3211. sizeof(conn->response_info.http_headers));
  3212. } else
  3213. #endif
  3214. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3215. return NULL;
  3216. }
  3217. return &conn->request_info;
  3218. }
  3219. const struct mg_response_info *
  3220. mg_get_response_info(const struct mg_connection *conn)
  3221. {
  3222. if (!conn) {
  3223. return NULL;
  3224. }
  3225. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3226. return NULL;
  3227. }
  3228. return &conn->response_info;
  3229. }
  3230. static const char *
  3231. get_proto_name(const struct mg_connection *conn)
  3232. {
  3233. #if defined(__clang__)
  3234. #pragma clang diagnostic push
  3235. #pragma clang diagnostic ignored "-Wunreachable-code"
  3236. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3237. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3238. * unreachable, but splitting into four different #ifdef clauses here is more
  3239. * complicated.
  3240. */
  3241. #endif
  3242. const struct mg_request_info *ri = &conn->request_info;
  3243. const char *proto =
  3244. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3245. : (ri->is_ssl ? "https" : "http"));
  3246. return proto;
  3247. #if defined(__clang__)
  3248. #pragma clang diagnostic pop
  3249. #endif
  3250. }
  3251. int
  3252. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3253. {
  3254. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3255. return -1;
  3256. } else {
  3257. int truncated = 0;
  3258. const struct mg_request_info *ri = &conn->request_info;
  3259. const char *proto = get_proto_name(conn);
  3260. if (ri->local_uri == NULL) {
  3261. return -1;
  3262. }
  3263. if ((ri->request_uri != NULL)
  3264. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3265. /* The request uri is different from the local uri.
  3266. * This is usually if an absolute URI, including server
  3267. * name has been provided. */
  3268. mg_snprintf(conn,
  3269. &truncated,
  3270. buf,
  3271. buflen,
  3272. "%s://%s",
  3273. proto,
  3274. ri->request_uri);
  3275. if (truncated) {
  3276. return -1;
  3277. }
  3278. return 0;
  3279. } else {
  3280. /* The common case is a relative URI, so we have to
  3281. * construct an absolute URI from server name and port */
  3282. #if defined(USE_IPV6)
  3283. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3284. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3285. : htons(conn->client.lsa.sin.sin_port);
  3286. #else
  3287. int port = htons(conn->client.lsa.sin.sin_port);
  3288. #endif
  3289. int def_port = ri->is_ssl ? 443 : 80;
  3290. int auth_domain_check_enabled =
  3291. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3292. && (!mg_strcasecmp(
  3293. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3294. const char *server_domain =
  3295. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3296. char portstr[16];
  3297. char server_ip[48];
  3298. if (port != def_port) {
  3299. sprintf(portstr, ":%u", (unsigned)port);
  3300. } else {
  3301. portstr[0] = 0;
  3302. }
  3303. if (!auth_domain_check_enabled || !server_domain) {
  3304. sockaddr_to_string(server_ip,
  3305. sizeof(server_ip),
  3306. &conn->client.lsa);
  3307. server_domain = server_ip;
  3308. }
  3309. mg_snprintf(conn,
  3310. &truncated,
  3311. buf,
  3312. buflen,
  3313. "%s://%s%s%s",
  3314. proto,
  3315. server_domain,
  3316. portstr,
  3317. ri->local_uri);
  3318. if (truncated) {
  3319. return -1;
  3320. }
  3321. return 0;
  3322. }
  3323. }
  3324. }
  3325. /* Skip the characters until one of the delimiters characters found.
  3326. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3327. * Advance pointer to buffer to the next word. Return found 0-terminated
  3328. * word.
  3329. * Delimiters can be quoted with quotechar. */
  3330. static char *
  3331. skip_quoted(char **buf,
  3332. const char *delimiters,
  3333. const char *whitespace,
  3334. char quotechar)
  3335. {
  3336. char *p, *begin_word, *end_word, *end_whitespace;
  3337. begin_word = *buf;
  3338. end_word = begin_word + strcspn(begin_word, delimiters);
  3339. /* Check for quotechar */
  3340. if (end_word > begin_word) {
  3341. p = end_word - 1;
  3342. while (*p == quotechar) {
  3343. /* While the delimiter is quoted, look for the next delimiter.
  3344. */
  3345. /* This happens, e.g., in calls from parse_auth_header,
  3346. * if the user name contains a " character. */
  3347. /* If there is anything beyond end_word, copy it. */
  3348. if (*end_word != '\0') {
  3349. size_t end_off = strcspn(end_word + 1, delimiters);
  3350. memmove(p, end_word, end_off + 1);
  3351. p += end_off; /* p must correspond to end_word - 1 */
  3352. end_word += end_off + 1;
  3353. } else {
  3354. *p = '\0';
  3355. break;
  3356. }
  3357. }
  3358. for (p++; p < end_word; p++) {
  3359. *p = '\0';
  3360. }
  3361. }
  3362. if (*end_word == '\0') {
  3363. *buf = end_word;
  3364. } else {
  3365. #if defined(GCC_DIAGNOSTIC)
  3366. /* Disable spurious conversion warning for GCC */
  3367. #pragma GCC diagnostic push
  3368. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3369. #endif /* defined(GCC_DIAGNOSTIC) */
  3370. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3371. #if defined(GCC_DIAGNOSTIC)
  3372. #pragma GCC diagnostic pop
  3373. #endif /* defined(GCC_DIAGNOSTIC) */
  3374. for (p = end_word; p < end_whitespace; p++) {
  3375. *p = '\0';
  3376. }
  3377. *buf = end_whitespace;
  3378. }
  3379. return begin_word;
  3380. }
  3381. /* Return HTTP header value, or NULL if not found. */
  3382. static const char *
  3383. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3384. {
  3385. int i;
  3386. for (i = 0; i < num_hdr; i++) {
  3387. if (!mg_strcasecmp(name, hdr[i].name)) {
  3388. return hdr[i].value;
  3389. }
  3390. }
  3391. return NULL;
  3392. }
  3393. #if defined(USE_WEBSOCKET)
  3394. /* Retrieve requested HTTP header multiple values, and return the number of
  3395. * found occurrences */
  3396. static int
  3397. get_req_headers(const struct mg_request_info *ri,
  3398. const char *name,
  3399. const char **output,
  3400. int output_max_size)
  3401. {
  3402. int i;
  3403. int cnt = 0;
  3404. if (ri) {
  3405. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3406. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3407. output[cnt++] = ri->http_headers[i].value;
  3408. }
  3409. }
  3410. }
  3411. return cnt;
  3412. }
  3413. #endif
  3414. const char *
  3415. mg_get_header(const struct mg_connection *conn, const char *name)
  3416. {
  3417. if (!conn) {
  3418. return NULL;
  3419. }
  3420. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3421. return get_header(conn->request_info.http_headers,
  3422. conn->request_info.num_headers,
  3423. name);
  3424. }
  3425. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3426. return get_header(conn->response_info.http_headers,
  3427. conn->response_info.num_headers,
  3428. name);
  3429. }
  3430. return NULL;
  3431. }
  3432. static const char *
  3433. get_http_version(const struct mg_connection *conn)
  3434. {
  3435. if (!conn) {
  3436. return NULL;
  3437. }
  3438. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3439. return conn->request_info.http_version;
  3440. }
  3441. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3442. return conn->response_info.http_version;
  3443. }
  3444. return NULL;
  3445. }
  3446. /* A helper function for traversing a comma separated list of values.
  3447. * It returns a list pointer shifted to the next value, or NULL if the end
  3448. * of the list found.
  3449. * Value is stored in val vector. If value has form "x=y", then eq_val
  3450. * vector is initialized to point to the "y" part, and val vector length
  3451. * is adjusted to point only to "x". */
  3452. static const char *
  3453. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3454. {
  3455. int end;
  3456. reparse:
  3457. if (val == NULL || list == NULL || *list == '\0') {
  3458. /* End of the list */
  3459. return NULL;
  3460. }
  3461. /* Skip over leading LWS */
  3462. while (*list == ' ' || *list == '\t')
  3463. list++;
  3464. val->ptr = list;
  3465. if ((list = strchr(val->ptr, ',')) != NULL) {
  3466. /* Comma found. Store length and shift the list ptr */
  3467. val->len = ((size_t)(list - val->ptr));
  3468. list++;
  3469. } else {
  3470. /* This value is the last one */
  3471. list = val->ptr + strlen(val->ptr);
  3472. val->len = ((size_t)(list - val->ptr));
  3473. }
  3474. /* Adjust length for trailing LWS */
  3475. end = (int)val->len - 1;
  3476. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3477. end--;
  3478. val->len = (size_t)(end) + (size_t)(1);
  3479. if (val->len == 0) {
  3480. /* Ignore any empty entries. */
  3481. goto reparse;
  3482. }
  3483. if (eq_val != NULL) {
  3484. /* Value has form "x=y", adjust pointers and lengths
  3485. * so that val points to "x", and eq_val points to "y". */
  3486. eq_val->len = 0;
  3487. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3488. if (eq_val->ptr != NULL) {
  3489. eq_val->ptr++; /* Skip over '=' character */
  3490. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3491. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3492. }
  3493. }
  3494. return list;
  3495. }
  3496. /* A helper function for checking if a comma separated list of values
  3497. * contains
  3498. * the given option (case insensitvely).
  3499. * 'header' can be NULL, in which case false is returned. */
  3500. static int
  3501. header_has_option(const char *header, const char *option)
  3502. {
  3503. struct vec opt_vec;
  3504. struct vec eq_vec;
  3505. DEBUG_ASSERT(option != NULL);
  3506. DEBUG_ASSERT(option[0] != '\0');
  3507. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3508. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3509. return 1;
  3510. }
  3511. return 0;
  3512. }
  3513. /* Perform case-insensitive match of string against pattern */
  3514. static ptrdiff_t
  3515. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3516. {
  3517. const char *or_str;
  3518. ptrdiff_t i, j, len, res;
  3519. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3520. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3521. return (res > 0) ? res
  3522. : match_prefix(or_str + 1,
  3523. (size_t)((pattern + pattern_len)
  3524. - (or_str + 1)),
  3525. str);
  3526. }
  3527. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3528. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3529. continue;
  3530. } else if (pattern[i] == '$') {
  3531. return (str[j] == '\0') ? j : -1;
  3532. } else if (pattern[i] == '*') {
  3533. i++;
  3534. if (pattern[i] == '*') {
  3535. i++;
  3536. len = strlen(str + j);
  3537. } else {
  3538. len = strcspn(str + j, "/");
  3539. }
  3540. if (i == (ptrdiff_t)pattern_len) {
  3541. return j + len;
  3542. }
  3543. do {
  3544. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3545. } while (res == -1 && len-- > 0);
  3546. return (res == -1) ? -1 : j + res + len;
  3547. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3548. return -1;
  3549. }
  3550. }
  3551. return (ptrdiff_t)j;
  3552. }
  3553. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3554. * This function must tolerate situations when connection info is not
  3555. * set up, for example if request parsing failed. */
  3556. static int
  3557. should_keep_alive(const struct mg_connection *conn)
  3558. {
  3559. const char *http_version;
  3560. const char *header;
  3561. /* First satisfy needs of the server */
  3562. if ((conn == NULL) || conn->must_close) {
  3563. /* Close, if civetweb framework needs to close */
  3564. return 0;
  3565. }
  3566. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3567. /* Close, if keep alive is not enabled */
  3568. return 0;
  3569. }
  3570. /* Check explicit wish of the client */
  3571. header = mg_get_header(conn, "Connection");
  3572. if (header) {
  3573. /* If there is a connection header from the client, obey */
  3574. if (header_has_option(header, "keep-alive")) {
  3575. return 1;
  3576. }
  3577. return 0;
  3578. }
  3579. /* Use default of the standard */
  3580. http_version = get_http_version(conn);
  3581. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3582. /* HTTP 1.1 default is keep alive */
  3583. return 1;
  3584. }
  3585. /* HTTP 1.0 (and earlier) default is to close the connection */
  3586. return 0;
  3587. }
  3588. static int
  3589. should_decode_url(const struct mg_connection *conn)
  3590. {
  3591. if (!conn || !conn->dom_ctx) {
  3592. return 0;
  3593. }
  3594. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3595. }
  3596. static const char *
  3597. suggest_connection_header(const struct mg_connection *conn)
  3598. {
  3599. return should_keep_alive(conn) ? "keep-alive" : "close";
  3600. }
  3601. static int
  3602. send_no_cache_header(struct mg_connection *conn)
  3603. {
  3604. /* Send all current and obsolete cache opt-out directives. */
  3605. return mg_printf(conn,
  3606. "Cache-Control: no-cache, no-store, "
  3607. "must-revalidate, private, max-age=0\r\n"
  3608. "Pragma: no-cache\r\n"
  3609. "Expires: 0\r\n");
  3610. }
  3611. static int
  3612. send_static_cache_header(struct mg_connection *conn)
  3613. {
  3614. #if !defined(NO_CACHING)
  3615. /* Read the server config to check how long a file may be cached.
  3616. * The configuration is in seconds. */
  3617. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3618. if (max_age <= 0) {
  3619. /* 0 means "do not cache". All values <0 are reserved
  3620. * and may be used differently in the future. */
  3621. /* If a file should not be cached, do not only send
  3622. * max-age=0, but also pragmas and Expires headers. */
  3623. return send_no_cache_header(conn);
  3624. }
  3625. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3626. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3627. /* See also https://www.mnot.net/cache_docs/ */
  3628. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3629. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3630. * leap
  3631. * year to 31622400 seconds. For the moment, we just send whatever has
  3632. * been configured, still the behavior for >1 year should be considered
  3633. * as undefined. */
  3634. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3635. #else /* NO_CACHING */
  3636. return send_no_cache_header(conn);
  3637. #endif /* !NO_CACHING */
  3638. }
  3639. static int
  3640. send_additional_header(struct mg_connection *conn)
  3641. {
  3642. int i = 0;
  3643. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3644. #if !defined(NO_SSL)
  3645. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3646. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3647. if (max_age >= 0) {
  3648. i += mg_printf(conn,
  3649. "Strict-Transport-Security: max-age=%u\r\n",
  3650. (unsigned)max_age);
  3651. }
  3652. }
  3653. #endif
  3654. if (header && header[0]) {
  3655. i += mg_printf(conn, "%s\r\n", header);
  3656. }
  3657. return i;
  3658. }
  3659. static void handle_file_based_request(struct mg_connection *conn,
  3660. const char *path,
  3661. struct mg_file *filep);
  3662. const char *
  3663. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3664. {
  3665. /* See IANA HTTP status code assignment:
  3666. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3667. */
  3668. switch (response_code) {
  3669. /* RFC2616 Section 10.1 - Informational 1xx */
  3670. case 100:
  3671. return "Continue"; /* RFC2616 Section 10.1.1 */
  3672. case 101:
  3673. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3674. case 102:
  3675. return "Processing"; /* RFC2518 Section 10.1 */
  3676. /* RFC2616 Section 10.2 - Successful 2xx */
  3677. case 200:
  3678. return "OK"; /* RFC2616 Section 10.2.1 */
  3679. case 201:
  3680. return "Created"; /* RFC2616 Section 10.2.2 */
  3681. case 202:
  3682. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3683. case 203:
  3684. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3685. case 204:
  3686. return "No Content"; /* RFC2616 Section 10.2.5 */
  3687. case 205:
  3688. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3689. case 206:
  3690. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3691. case 207:
  3692. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3693. */
  3694. case 208:
  3695. return "Already Reported"; /* RFC5842 Section 7.1 */
  3696. case 226:
  3697. return "IM used"; /* RFC3229 Section 10.4.1 */
  3698. /* RFC2616 Section 10.3 - Redirection 3xx */
  3699. case 300:
  3700. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3701. case 301:
  3702. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3703. case 302:
  3704. return "Found"; /* RFC2616 Section 10.3.3 */
  3705. case 303:
  3706. return "See Other"; /* RFC2616 Section 10.3.4 */
  3707. case 304:
  3708. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3709. case 305:
  3710. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3711. case 307:
  3712. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3713. case 308:
  3714. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3715. /* RFC2616 Section 10.4 - Client Error 4xx */
  3716. case 400:
  3717. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3718. case 401:
  3719. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3720. case 402:
  3721. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3722. case 403:
  3723. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3724. case 404:
  3725. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3726. case 405:
  3727. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3728. case 406:
  3729. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3730. case 407:
  3731. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3732. case 408:
  3733. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3734. case 409:
  3735. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3736. case 410:
  3737. return "Gone"; /* RFC2616 Section 10.4.11 */
  3738. case 411:
  3739. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3740. case 412:
  3741. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3742. case 413:
  3743. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3744. case 414:
  3745. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3746. case 415:
  3747. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3748. case 416:
  3749. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3750. */
  3751. case 417:
  3752. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3753. case 421:
  3754. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3755. case 422:
  3756. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3757. * Section 11.2 */
  3758. case 423:
  3759. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3760. case 424:
  3761. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3762. * Section 11.4 */
  3763. case 426:
  3764. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3765. case 428:
  3766. return "Precondition Required"; /* RFC 6585, Section 3 */
  3767. case 429:
  3768. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3769. case 431:
  3770. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3771. case 451:
  3772. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3773. * Section 3 */
  3774. /* RFC2616 Section 10.5 - Server Error 5xx */
  3775. case 500:
  3776. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3777. case 501:
  3778. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3779. case 502:
  3780. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3781. case 503:
  3782. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3783. case 504:
  3784. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3785. case 505:
  3786. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3787. case 506:
  3788. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3789. case 507:
  3790. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3791. * Section 11.5 */
  3792. case 508:
  3793. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3794. case 510:
  3795. return "Not Extended"; /* RFC 2774, Section 7 */
  3796. case 511:
  3797. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3798. /* Other status codes, not shown in the IANA HTTP status code
  3799. * assignment.
  3800. * E.g., "de facto" standards due to common use, ... */
  3801. case 418:
  3802. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3803. case 419:
  3804. return "Authentication Timeout"; /* common use */
  3805. case 420:
  3806. return "Enhance Your Calm"; /* common use */
  3807. case 440:
  3808. return "Login Timeout"; /* common use */
  3809. case 509:
  3810. return "Bandwidth Limit Exceeded"; /* common use */
  3811. default:
  3812. /* This error code is unknown. This should not happen. */
  3813. if (conn) {
  3814. mg_cry_internal(conn,
  3815. "Unknown HTTP response code: %u",
  3816. response_code);
  3817. }
  3818. /* Return at least a category according to RFC 2616 Section 10. */
  3819. if (response_code >= 100 && response_code < 200) {
  3820. /* Unknown informational status code */
  3821. return "Information";
  3822. }
  3823. if (response_code >= 200 && response_code < 300) {
  3824. /* Unknown success code */
  3825. return "Success";
  3826. }
  3827. if (response_code >= 300 && response_code < 400) {
  3828. /* Unknown redirection code */
  3829. return "Redirection";
  3830. }
  3831. if (response_code >= 400 && response_code < 500) {
  3832. /* Unknown request error code */
  3833. return "Client Error";
  3834. }
  3835. if (response_code >= 500 && response_code < 600) {
  3836. /* Unknown server error code */
  3837. return "Server Error";
  3838. }
  3839. /* Response code not even within reasonable range */
  3840. return "";
  3841. }
  3842. }
  3843. static int
  3844. mg_send_http_error_impl(struct mg_connection *conn,
  3845. int status,
  3846. const char *fmt,
  3847. va_list args)
  3848. {
  3849. char errmsg_buf[MG_BUF_LEN];
  3850. char path_buf[PATH_MAX];
  3851. va_list ap;
  3852. int len, i, page_handler_found, scope, truncated, has_body;
  3853. char date[64];
  3854. time_t curtime = time(NULL);
  3855. const char *error_handler = NULL;
  3856. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3857. const char *error_page_file_ext, *tstr;
  3858. int handled_by_callback = 0;
  3859. const char *status_text = mg_get_response_code_text(conn, status);
  3860. if ((conn == NULL) || (fmt == NULL)) {
  3861. return -2;
  3862. }
  3863. /* Set status (for log) */
  3864. conn->status_code = status;
  3865. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3866. has_body = ((status > 199) && (status != 204) && (status != 304));
  3867. /* Prepare message in buf, if required */
  3868. if (has_body
  3869. || (!conn->in_error_handler
  3870. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3871. /* Store error message in errmsg_buf */
  3872. va_copy(ap, args);
  3873. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3874. va_end(ap);
  3875. /* In a debug build, print all html errors */
  3876. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3877. }
  3878. /* If there is a http_error callback, call it.
  3879. * But don't do it recursively, if callback calls mg_send_http_error again.
  3880. */
  3881. if (!conn->in_error_handler
  3882. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3883. /* Mark in_error_handler to avoid recursion and call user callback. */
  3884. conn->in_error_handler = 1;
  3885. handled_by_callback =
  3886. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3887. == 0);
  3888. conn->in_error_handler = 0;
  3889. }
  3890. if (!handled_by_callback) {
  3891. /* Check for recursion */
  3892. if (conn->in_error_handler) {
  3893. DEBUG_TRACE(
  3894. "Recursion when handling error %u - fall back to default",
  3895. status);
  3896. } else {
  3897. /* Send user defined error pages, if defined */
  3898. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3899. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3900. page_handler_found = 0;
  3901. if (error_handler != NULL) {
  3902. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3903. switch (scope) {
  3904. case 1: /* Handler for specific error, e.g. 404 error */
  3905. mg_snprintf(conn,
  3906. &truncated,
  3907. path_buf,
  3908. sizeof(path_buf) - 32,
  3909. "%serror%03u.",
  3910. error_handler,
  3911. status);
  3912. break;
  3913. case 2: /* Handler for error group, e.g., 5xx error
  3914. * handler
  3915. * for all server errors (500-599) */
  3916. mg_snprintf(conn,
  3917. &truncated,
  3918. path_buf,
  3919. sizeof(path_buf) - 32,
  3920. "%serror%01uxx.",
  3921. error_handler,
  3922. status / 100);
  3923. break;
  3924. default: /* Handler for all errors */
  3925. mg_snprintf(conn,
  3926. &truncated,
  3927. path_buf,
  3928. sizeof(path_buf) - 32,
  3929. "%serror.",
  3930. error_handler);
  3931. break;
  3932. }
  3933. /* String truncation in buf may only occur if
  3934. * error_handler is too long. This string is
  3935. * from the config, not from a client. */
  3936. (void)truncated;
  3937. len = (int)strlen(path_buf);
  3938. tstr = strchr(error_page_file_ext, '.');
  3939. while (tstr) {
  3940. for (i = 1;
  3941. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3942. i++) {
  3943. /* buffer overrun is not possible here, since
  3944. * (i < 32) && (len < sizeof(path_buf) - 32)
  3945. * ==> (i + len) < sizeof(path_buf) */
  3946. path_buf[len + i - 1] = tstr[i];
  3947. }
  3948. /* buffer overrun is not possible here, since
  3949. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3950. * ==> (i + len) <= sizeof(path_buf) */
  3951. path_buf[len + i - 1] = 0;
  3952. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3953. DEBUG_TRACE("Check error page %s - found",
  3954. path_buf);
  3955. page_handler_found = 1;
  3956. break;
  3957. }
  3958. DEBUG_TRACE("Check error page %s - not found",
  3959. path_buf);
  3960. tstr = strchr(tstr + i, '.');
  3961. }
  3962. }
  3963. }
  3964. if (page_handler_found) {
  3965. conn->in_error_handler = 1;
  3966. handle_file_based_request(conn, path_buf, &error_page_file);
  3967. conn->in_error_handler = 0;
  3968. return 0;
  3969. }
  3970. }
  3971. /* No custom error page. Send default error page. */
  3972. gmt_time_string(date, sizeof(date), &curtime);
  3973. conn->must_close = 1;
  3974. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3975. send_no_cache_header(conn);
  3976. send_additional_header(conn);
  3977. if (has_body) {
  3978. mg_printf(conn,
  3979. "%s",
  3980. "Content-Type: text/plain; charset=utf-8\r\n");
  3981. }
  3982. mg_printf(conn,
  3983. "Date: %s\r\n"
  3984. "Connection: close\r\n\r\n",
  3985. date);
  3986. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3987. if (has_body) {
  3988. /* For other errors, send a generic error message. */
  3989. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3990. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3991. } else {
  3992. /* No body allowed. Close the connection. */
  3993. DEBUG_TRACE("Error %i", status);
  3994. }
  3995. }
  3996. return 0;
  3997. }
  3998. int
  3999. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4000. {
  4001. va_list ap;
  4002. int ret;
  4003. va_start(ap, fmt);
  4004. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4005. va_end(ap);
  4006. return ret;
  4007. }
  4008. int
  4009. mg_send_http_ok(struct mg_connection *conn,
  4010. const char *mime_type,
  4011. long long content_length)
  4012. {
  4013. char date[64];
  4014. time_t curtime = time(NULL);
  4015. if ((mime_type == NULL) || (*mime_type == 0)) {
  4016. /* Parameter error */
  4017. return -2;
  4018. }
  4019. gmt_time_string(date, sizeof(date), &curtime);
  4020. mg_printf(conn,
  4021. "HTTP/1.1 200 OK\r\n"
  4022. "Content-Type: %s\r\n"
  4023. "Date: %s\r\n"
  4024. "Connection: %s\r\n",
  4025. mime_type,
  4026. date,
  4027. suggest_connection_header(conn));
  4028. send_no_cache_header(conn);
  4029. send_additional_header(conn);
  4030. if (content_length < 0) {
  4031. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4032. } else {
  4033. mg_printf(conn,
  4034. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4035. (uint64_t)content_length);
  4036. }
  4037. return 0;
  4038. }
  4039. int
  4040. mg_send_http_redirect(struct mg_connection *conn,
  4041. const char *target_url,
  4042. int redirect_code)
  4043. {
  4044. /* Send a 30x redirect response.
  4045. *
  4046. * Redirect types (status codes):
  4047. *
  4048. * Status | Perm/Temp | Method | Version
  4049. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4050. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4051. * 303 | temporary | always use GET | HTTP/1.1
  4052. * 307 | temporary | always keep method | HTTP/1.1
  4053. * 308 | permanent | always keep method | HTTP/1.1
  4054. */
  4055. const char *redirect_text;
  4056. int ret;
  4057. size_t content_len = 0;
  4058. char reply[MG_BUF_LEN];
  4059. /* In case redirect_code=0, use 307. */
  4060. if (redirect_code == 0) {
  4061. redirect_code = 307;
  4062. }
  4063. /* In case redirect_code is none of the above, return error. */
  4064. if ((redirect_code != 301) && (redirect_code != 302)
  4065. && (redirect_code != 303) && (redirect_code != 307)
  4066. && (redirect_code != 308)) {
  4067. /* Parameter error */
  4068. return -2;
  4069. }
  4070. /* Get proper text for response code */
  4071. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4072. /* If target_url is not defined, redirect to "/". */
  4073. if ((target_url == NULL) || (*target_url == 0)) {
  4074. target_url = "/";
  4075. }
  4076. #if defined(MG_SEND_REDIRECT_BODY)
  4077. /* TODO: condition name? */
  4078. /* Prepare a response body with a hyperlink.
  4079. *
  4080. * According to RFC2616 (and RFC1945 before):
  4081. * Unless the request method was HEAD, the entity of the
  4082. * response SHOULD contain a short hypertext note with a hyperlink to
  4083. * the new URI(s).
  4084. *
  4085. * However, this response body is not useful in M2M communication.
  4086. * Probably the original reason in the RFC was, clients not supporting
  4087. * a 30x HTTP redirect could still show the HTML page and let the user
  4088. * press the link. Since current browsers support 30x HTTP, the additional
  4089. * HTML body does not seem to make sense anymore.
  4090. *
  4091. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4092. * but it only notes:
  4093. * The server's response payload usually contains a short
  4094. * hypertext note with a hyperlink to the new URI(s).
  4095. *
  4096. * Deactivated by default. If you need the 30x body, set the define.
  4097. */
  4098. mg_snprintf(
  4099. conn,
  4100. NULL /* ignore truncation */,
  4101. reply,
  4102. sizeof(reply),
  4103. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4104. redirect_text,
  4105. target_url,
  4106. target_url);
  4107. content_len = strlen(reply);
  4108. #else
  4109. reply[0] = 0;
  4110. #endif
  4111. /* Do not send any additional header. For all other options,
  4112. * including caching, there are suitable defaults. */
  4113. ret = mg_printf(conn,
  4114. "HTTP/1.1 %i %s\r\n"
  4115. "Location: %s\r\n"
  4116. "Content-Length: %u\r\n"
  4117. "Connection: %s\r\n\r\n",
  4118. redirect_code,
  4119. redirect_text,
  4120. target_url,
  4121. (unsigned int)content_len,
  4122. suggest_connection_header(conn));
  4123. /* Send response body */
  4124. if (ret > 0) {
  4125. /* ... unless it is a HEAD request */
  4126. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4127. ret = mg_write(conn, reply, content_len);
  4128. }
  4129. }
  4130. return (ret > 0) ? ret : -1;
  4131. }
  4132. #if defined(_WIN32)
  4133. /* Create substitutes for POSIX functions in Win32. */
  4134. #if defined(GCC_DIAGNOSTIC)
  4135. /* Show no warning in case system functions are not used. */
  4136. #pragma GCC diagnostic push
  4137. #pragma GCC diagnostic ignored "-Wunused-function"
  4138. #endif
  4139. FUNCTION_MAY_BE_UNUSED
  4140. static int
  4141. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4142. {
  4143. (void)unused;
  4144. *mutex = CreateMutex(NULL, FALSE, NULL);
  4145. return (*mutex == NULL) ? -1 : 0;
  4146. }
  4147. FUNCTION_MAY_BE_UNUSED
  4148. static int
  4149. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4150. {
  4151. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  4152. }
  4153. FUNCTION_MAY_BE_UNUSED
  4154. static int
  4155. pthread_mutex_lock(pthread_mutex_t *mutex)
  4156. {
  4157. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  4158. : -1;
  4159. }
  4160. #if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS)
  4161. FUNCTION_MAY_BE_UNUSED
  4162. static int
  4163. pthread_mutex_trylock(pthread_mutex_t *mutex)
  4164. {
  4165. switch (WaitForSingleObject(*mutex, 0)) {
  4166. case WAIT_OBJECT_0:
  4167. return 0;
  4168. case WAIT_TIMEOUT:
  4169. return -2; /* EBUSY */
  4170. }
  4171. return -1;
  4172. }
  4173. #endif
  4174. FUNCTION_MAY_BE_UNUSED
  4175. static int
  4176. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4177. {
  4178. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  4179. }
  4180. FUNCTION_MAY_BE_UNUSED
  4181. static int
  4182. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4183. {
  4184. (void)unused;
  4185. InitializeCriticalSection(&cv->threadIdSec);
  4186. cv->waiting_thread = NULL;
  4187. return 0;
  4188. }
  4189. FUNCTION_MAY_BE_UNUSED
  4190. static int
  4191. pthread_cond_timedwait(pthread_cond_t *cv,
  4192. pthread_mutex_t *mutex,
  4193. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4194. {
  4195. struct mg_workerTLS **ptls,
  4196. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4197. int ok;
  4198. int64_t nsnow, nswaitabs, nswaitrel;
  4199. DWORD mswaitrel;
  4200. EnterCriticalSection(&cv->threadIdSec);
  4201. /* Add this thread to cv's waiting list */
  4202. ptls = &cv->waiting_thread;
  4203. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4204. ;
  4205. tls->next_waiting_thread = NULL;
  4206. *ptls = tls;
  4207. LeaveCriticalSection(&cv->threadIdSec);
  4208. if (abstime) {
  4209. nsnow = mg_get_current_time_ns();
  4210. nswaitabs =
  4211. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4212. nswaitrel = nswaitabs - nsnow;
  4213. if (nswaitrel < 0) {
  4214. nswaitrel = 0;
  4215. }
  4216. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4217. } else {
  4218. mswaitrel = (DWORD)INFINITE;
  4219. }
  4220. pthread_mutex_unlock(mutex);
  4221. ok = (WAIT_OBJECT_0
  4222. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4223. if (!ok) {
  4224. ok = 1;
  4225. EnterCriticalSection(&cv->threadIdSec);
  4226. ptls = &cv->waiting_thread;
  4227. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4228. if (*ptls == tls) {
  4229. *ptls = tls->next_waiting_thread;
  4230. ok = 0;
  4231. break;
  4232. }
  4233. }
  4234. LeaveCriticalSection(&cv->threadIdSec);
  4235. if (ok) {
  4236. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4237. (DWORD)INFINITE);
  4238. }
  4239. }
  4240. /* This thread has been removed from cv's waiting list */
  4241. pthread_mutex_lock(mutex);
  4242. return ok ? 0 : -1;
  4243. }
  4244. FUNCTION_MAY_BE_UNUSED
  4245. static int
  4246. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4247. {
  4248. return pthread_cond_timedwait(cv, mutex, NULL);
  4249. }
  4250. FUNCTION_MAY_BE_UNUSED
  4251. static int
  4252. pthread_cond_signal(pthread_cond_t *cv)
  4253. {
  4254. HANDLE wkup = NULL;
  4255. BOOL ok = FALSE;
  4256. EnterCriticalSection(&cv->threadIdSec);
  4257. if (cv->waiting_thread) {
  4258. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4259. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4260. ok = SetEvent(wkup);
  4261. DEBUG_ASSERT(ok);
  4262. }
  4263. LeaveCriticalSection(&cv->threadIdSec);
  4264. return ok ? 0 : 1;
  4265. }
  4266. FUNCTION_MAY_BE_UNUSED
  4267. static int
  4268. pthread_cond_broadcast(pthread_cond_t *cv)
  4269. {
  4270. EnterCriticalSection(&cv->threadIdSec);
  4271. while (cv->waiting_thread) {
  4272. pthread_cond_signal(cv);
  4273. }
  4274. LeaveCriticalSection(&cv->threadIdSec);
  4275. return 0;
  4276. }
  4277. FUNCTION_MAY_BE_UNUSED
  4278. static int
  4279. pthread_cond_destroy(pthread_cond_t *cv)
  4280. {
  4281. EnterCriticalSection(&cv->threadIdSec);
  4282. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4283. LeaveCriticalSection(&cv->threadIdSec);
  4284. DeleteCriticalSection(&cv->threadIdSec);
  4285. return 0;
  4286. }
  4287. #if defined(ALTERNATIVE_QUEUE)
  4288. FUNCTION_MAY_BE_UNUSED
  4289. static void *
  4290. event_create(void)
  4291. {
  4292. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4293. }
  4294. FUNCTION_MAY_BE_UNUSED
  4295. static int
  4296. event_wait(void *eventhdl)
  4297. {
  4298. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4299. return (res == WAIT_OBJECT_0);
  4300. }
  4301. FUNCTION_MAY_BE_UNUSED
  4302. static int
  4303. event_signal(void *eventhdl)
  4304. {
  4305. return (int)SetEvent((HANDLE)eventhdl);
  4306. }
  4307. FUNCTION_MAY_BE_UNUSED
  4308. static void
  4309. event_destroy(void *eventhdl)
  4310. {
  4311. CloseHandle((HANDLE)eventhdl);
  4312. }
  4313. #endif
  4314. #if defined(GCC_DIAGNOSTIC)
  4315. /* Enable unused function warning again */
  4316. #pragma GCC diagnostic pop
  4317. #endif
  4318. /* For Windows, change all slashes to backslashes in path names. */
  4319. static void
  4320. change_slashes_to_backslashes(char *path)
  4321. {
  4322. int i;
  4323. for (i = 0; path[i] != '\0'; i++) {
  4324. if (path[i] == '/') {
  4325. path[i] = '\\';
  4326. }
  4327. /* remove double backslash (check i > 0 to preserve UNC paths,
  4328. * like \\server\file.txt) */
  4329. if ((path[i] == '\\') && (i > 0)) {
  4330. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4331. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4332. }
  4333. }
  4334. }
  4335. }
  4336. static int
  4337. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4338. {
  4339. int diff;
  4340. do {
  4341. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4342. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4343. s1++;
  4344. s2++;
  4345. } while ((diff == 0) && (s1[-1] != L'\0'));
  4346. return diff;
  4347. }
  4348. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4349. * wbuf and wbuf_len is a target buffer and its length. */
  4350. static void
  4351. path_to_unicode(const struct mg_connection *conn,
  4352. const char *path,
  4353. wchar_t *wbuf,
  4354. size_t wbuf_len)
  4355. {
  4356. char buf[PATH_MAX], buf2[PATH_MAX];
  4357. wchar_t wbuf2[W_PATH_MAX + 1];
  4358. DWORD long_len, err;
  4359. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4360. mg_strlcpy(buf, path, sizeof(buf));
  4361. change_slashes_to_backslashes(buf);
  4362. /* Convert to Unicode and back. If doubly-converted string does not
  4363. * match the original, something is fishy, reject. */
  4364. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4365. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4366. WideCharToMultiByte(
  4367. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4368. if (strcmp(buf, buf2) != 0) {
  4369. wbuf[0] = L'\0';
  4370. }
  4371. /* Windows file systems are not case sensitive, but you can still use
  4372. * uppercase and lowercase letters (on all modern file systems).
  4373. * The server can check if the URI uses the same upper/lowercase
  4374. * letters an the file system, effectively making Windows servers
  4375. * case sensitive (like Linux servers are). It is still not possible
  4376. * to use two files with the same name in different cases on Windows
  4377. * (like /a and /A) - this would be possible in Linux.
  4378. * As a default, Windows is not case sensitive, but the case sensitive
  4379. * file name check can be activated by an additional configuration. */
  4380. if (conn) {
  4381. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4382. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4383. "yes")) {
  4384. /* Use case sensitive compare function */
  4385. fcompare = wcscmp;
  4386. }
  4387. }
  4388. (void)conn; /* conn is currently unused */
  4389. #if !defined(_WIN32_WCE)
  4390. /* Only accept a full file path, not a Windows short (8.3) path. */
  4391. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4392. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4393. if (long_len == 0) {
  4394. err = GetLastError();
  4395. if (err == ERROR_FILE_NOT_FOUND) {
  4396. /* File does not exist. This is not always a problem here. */
  4397. return;
  4398. }
  4399. }
  4400. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4401. /* Short name is used. */
  4402. wbuf[0] = L'\0';
  4403. }
  4404. #else
  4405. (void)long_len;
  4406. (void)wbuf2;
  4407. (void)err;
  4408. if (strchr(path, '~')) {
  4409. wbuf[0] = L'\0';
  4410. }
  4411. #endif
  4412. }
  4413. static int
  4414. mg_stat(const struct mg_connection *conn,
  4415. const char *path,
  4416. struct mg_file_stat *filep)
  4417. {
  4418. wchar_t wbuf[W_PATH_MAX];
  4419. WIN32_FILE_ATTRIBUTE_DATA info;
  4420. time_t creation_time;
  4421. size_t len;
  4422. if (!filep) {
  4423. return 0;
  4424. }
  4425. memset(filep, 0, sizeof(*filep));
  4426. if (conn && is_file_in_memory(conn, path)) {
  4427. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4428. * memset */
  4429. /* Quick fix (for 1.9.x): */
  4430. /* mg_stat must fill all fields, also for files in memory */
  4431. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4432. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4433. filep->size = tmp_file.stat.size;
  4434. filep->location = 2;
  4435. /* TODO: for 1.10: restructure how files in memory are handled */
  4436. /* The "file in memory" feature is a candidate for deletion.
  4437. * Please join the discussion at
  4438. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4439. */
  4440. filep->last_modified = time(NULL); /* TODO */
  4441. /* last_modified = now ... assumes the file may change during
  4442. * runtime,
  4443. * so every mg_fopen call may return different data */
  4444. /* last_modified = conn->phys_ctx.start_time;
  4445. * May be used it the data does not change during runtime. This
  4446. * allows
  4447. * browser caching. Since we do not know, we have to assume the file
  4448. * in memory may change. */
  4449. return 1;
  4450. }
  4451. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4452. /* Windows happily opens files with some garbage at the end of file name.
  4453. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4454. * "a.cgi", despite one would expect an error back. */
  4455. len = strlen(path);
  4456. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4457. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4458. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4459. filep->last_modified =
  4460. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4461. info.ftLastWriteTime.dwHighDateTime);
  4462. /* On Windows, the file creation time can be higher than the
  4463. * modification time, e.g. when a file is copied.
  4464. * Since the Last-Modified timestamp is used for caching
  4465. * it should be based on the most recent timestamp. */
  4466. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4467. info.ftCreationTime.dwHighDateTime);
  4468. if (creation_time > filep->last_modified) {
  4469. filep->last_modified = creation_time;
  4470. }
  4471. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4472. return 1;
  4473. }
  4474. return 0;
  4475. }
  4476. static int
  4477. mg_remove(const struct mg_connection *conn, const char *path)
  4478. {
  4479. wchar_t wbuf[W_PATH_MAX];
  4480. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4481. return DeleteFileW(wbuf) ? 0 : -1;
  4482. }
  4483. static int
  4484. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4485. {
  4486. wchar_t wbuf[W_PATH_MAX];
  4487. (void)mode;
  4488. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4489. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4490. }
  4491. /* Create substitutes for POSIX functions in Win32. */
  4492. #if defined(GCC_DIAGNOSTIC)
  4493. /* Show no warning in case system functions are not used. */
  4494. #pragma GCC diagnostic push
  4495. #pragma GCC diagnostic ignored "-Wunused-function"
  4496. #endif
  4497. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4498. FUNCTION_MAY_BE_UNUSED
  4499. static DIR *
  4500. mg_opendir(const struct mg_connection *conn, const char *name)
  4501. {
  4502. DIR *dir = NULL;
  4503. wchar_t wpath[W_PATH_MAX];
  4504. DWORD attrs;
  4505. if (name == NULL) {
  4506. SetLastError(ERROR_BAD_ARGUMENTS);
  4507. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4508. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4509. } else {
  4510. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4511. attrs = GetFileAttributesW(wpath);
  4512. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4513. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4514. (void)wcscat(wpath, L"\\*");
  4515. dir->handle = FindFirstFileW(wpath, &dir->info);
  4516. dir->result.d_name[0] = '\0';
  4517. } else {
  4518. mg_free(dir);
  4519. dir = NULL;
  4520. }
  4521. }
  4522. return dir;
  4523. }
  4524. FUNCTION_MAY_BE_UNUSED
  4525. static int
  4526. mg_closedir(DIR *dir)
  4527. {
  4528. int result = 0;
  4529. if (dir != NULL) {
  4530. if (dir->handle != INVALID_HANDLE_VALUE)
  4531. result = FindClose(dir->handle) ? 0 : -1;
  4532. mg_free(dir);
  4533. } else {
  4534. result = -1;
  4535. SetLastError(ERROR_BAD_ARGUMENTS);
  4536. }
  4537. return result;
  4538. }
  4539. FUNCTION_MAY_BE_UNUSED
  4540. static struct dirent *
  4541. mg_readdir(DIR *dir)
  4542. {
  4543. struct dirent *result = 0;
  4544. if (dir) {
  4545. if (dir->handle != INVALID_HANDLE_VALUE) {
  4546. result = &dir->result;
  4547. (void)WideCharToMultiByte(CP_UTF8,
  4548. 0,
  4549. dir->info.cFileName,
  4550. -1,
  4551. result->d_name,
  4552. sizeof(result->d_name),
  4553. NULL,
  4554. NULL);
  4555. if (!FindNextFileW(dir->handle, &dir->info)) {
  4556. (void)FindClose(dir->handle);
  4557. dir->handle = INVALID_HANDLE_VALUE;
  4558. }
  4559. } else {
  4560. SetLastError(ERROR_FILE_NOT_FOUND);
  4561. }
  4562. } else {
  4563. SetLastError(ERROR_BAD_ARGUMENTS);
  4564. }
  4565. return result;
  4566. }
  4567. #if !defined(HAVE_POLL)
  4568. #undef POLLIN
  4569. #undef POLLPRI
  4570. #undef POLLOUT
  4571. #define POLLIN (1) /* Data ready - read will not block. */
  4572. #define POLLPRI (2) /* Priority data ready. */
  4573. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4574. FUNCTION_MAY_BE_UNUSED
  4575. static int
  4576. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4577. {
  4578. struct timeval tv;
  4579. fd_set rset;
  4580. fd_set wset;
  4581. unsigned int i;
  4582. int result;
  4583. SOCKET maxfd = 0;
  4584. memset(&tv, 0, sizeof(tv));
  4585. tv.tv_sec = milliseconds / 1000;
  4586. tv.tv_usec = (milliseconds % 1000) * 1000;
  4587. FD_ZERO(&rset);
  4588. FD_ZERO(&wset);
  4589. for (i = 0; i < n; i++) {
  4590. if (pfd[i].events & POLLIN) {
  4591. FD_SET(pfd[i].fd, &rset);
  4592. }
  4593. if (pfd[i].events & POLLOUT) {
  4594. FD_SET(pfd[i].fd, &wset);
  4595. }
  4596. pfd[i].revents = 0;
  4597. if (pfd[i].fd > maxfd) {
  4598. maxfd = pfd[i].fd;
  4599. }
  4600. }
  4601. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4602. for (i = 0; i < n; i++) {
  4603. if (FD_ISSET(pfd[i].fd, &rset)) {
  4604. pfd[i].revents |= POLLIN;
  4605. }
  4606. if (FD_ISSET(pfd[i].fd, &wset)) {
  4607. pfd[i].revents |= POLLOUT;
  4608. }
  4609. }
  4610. }
  4611. /* We should subtract the time used in select from remaining
  4612. * "milliseconds", in particular if called from mg_poll with a
  4613. * timeout quantum.
  4614. * Unfortunately, the remaining time is not stored in "tv" in all
  4615. * implementations, so the result in "tv" must be considered undefined.
  4616. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4617. return result;
  4618. }
  4619. #endif /* HAVE_POLL */
  4620. #if defined(GCC_DIAGNOSTIC)
  4621. /* Enable unused function warning again */
  4622. #pragma GCC diagnostic pop
  4623. #endif
  4624. static void
  4625. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4626. {
  4627. (void)conn; /* Unused. */
  4628. #if defined(_WIN32_WCE)
  4629. (void)sock;
  4630. #else
  4631. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4632. #endif
  4633. }
  4634. int
  4635. mg_start_thread(mg_thread_func_t f, void *p)
  4636. {
  4637. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4638. /* Compile-time option to control stack size, e.g.
  4639. * -DUSE_STACK_SIZE=16384
  4640. */
  4641. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4642. == ((uintptr_t)(-1L)))
  4643. ? -1
  4644. : 0);
  4645. #else
  4646. return (
  4647. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4648. ? -1
  4649. : 0);
  4650. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4651. }
  4652. /* Start a thread storing the thread context. */
  4653. static int
  4654. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4655. void *p,
  4656. pthread_t *threadidptr)
  4657. {
  4658. uintptr_t uip;
  4659. HANDLE threadhandle;
  4660. int result = -1;
  4661. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4662. threadhandle = (HANDLE)uip;
  4663. if ((uip != 0) && (threadidptr != NULL)) {
  4664. *threadidptr = threadhandle;
  4665. result = 0;
  4666. }
  4667. return result;
  4668. }
  4669. /* Wait for a thread to finish. */
  4670. static int
  4671. mg_join_thread(pthread_t threadid)
  4672. {
  4673. int result;
  4674. DWORD dwevent;
  4675. result = -1;
  4676. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4677. if (dwevent == WAIT_FAILED) {
  4678. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4679. } else {
  4680. if (dwevent == WAIT_OBJECT_0) {
  4681. CloseHandle(threadid);
  4682. result = 0;
  4683. }
  4684. }
  4685. return result;
  4686. }
  4687. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4688. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4689. /* Create substitutes for POSIX functions in Win32. */
  4690. #if defined(GCC_DIAGNOSTIC)
  4691. /* Show no warning in case system functions are not used. */
  4692. #pragma GCC diagnostic push
  4693. #pragma GCC diagnostic ignored "-Wunused-function"
  4694. #endif
  4695. FUNCTION_MAY_BE_UNUSED
  4696. static HANDLE
  4697. dlopen(const char *dll_name, int flags)
  4698. {
  4699. wchar_t wbuf[W_PATH_MAX];
  4700. (void)flags;
  4701. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4702. return LoadLibraryW(wbuf);
  4703. }
  4704. FUNCTION_MAY_BE_UNUSED
  4705. static int
  4706. dlclose(void *handle)
  4707. {
  4708. int result;
  4709. if (FreeLibrary((HMODULE)handle) != 0) {
  4710. result = 0;
  4711. } else {
  4712. result = -1;
  4713. }
  4714. return result;
  4715. }
  4716. #if defined(GCC_DIAGNOSTIC)
  4717. /* Enable unused function warning again */
  4718. #pragma GCC diagnostic pop
  4719. #endif
  4720. #endif
  4721. #if !defined(NO_CGI)
  4722. #define SIGKILL (0)
  4723. static int
  4724. kill(pid_t pid, int sig_num)
  4725. {
  4726. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4727. (void)CloseHandle((HANDLE)pid);
  4728. return 0;
  4729. }
  4730. #if !defined(WNOHANG)
  4731. #define WNOHANG (1)
  4732. #endif
  4733. static pid_t
  4734. waitpid(pid_t pid, int *status, int flags)
  4735. {
  4736. DWORD timeout = INFINITE;
  4737. DWORD waitres;
  4738. (void)status; /* Currently not used by any client here */
  4739. if ((flags | WNOHANG) == WNOHANG) {
  4740. timeout = 0;
  4741. }
  4742. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4743. if (waitres == WAIT_OBJECT_0) {
  4744. return pid;
  4745. }
  4746. if (waitres == WAIT_TIMEOUT) {
  4747. return 0;
  4748. }
  4749. return (pid_t)-1;
  4750. }
  4751. static void
  4752. trim_trailing_whitespaces(char *s)
  4753. {
  4754. char *e = s + strlen(s);
  4755. while ((e > s) && isspace((unsigned char)e[-1])) {
  4756. *(--e) = '\0';
  4757. }
  4758. }
  4759. static pid_t
  4760. spawn_process(struct mg_connection *conn,
  4761. const char *prog,
  4762. char *envblk,
  4763. char *envp[],
  4764. int fdin[2],
  4765. int fdout[2],
  4766. int fderr[2],
  4767. const char *dir)
  4768. {
  4769. HANDLE me;
  4770. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4771. cmdline[PATH_MAX], buf[PATH_MAX];
  4772. int truncated;
  4773. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4774. STARTUPINFOA si;
  4775. PROCESS_INFORMATION pi = {0};
  4776. (void)envp;
  4777. memset(&si, 0, sizeof(si));
  4778. si.cb = sizeof(si);
  4779. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4780. si.wShowWindow = SW_HIDE;
  4781. me = GetCurrentProcess();
  4782. DuplicateHandle(me,
  4783. (HANDLE)_get_osfhandle(fdin[0]),
  4784. me,
  4785. &si.hStdInput,
  4786. 0,
  4787. TRUE,
  4788. DUPLICATE_SAME_ACCESS);
  4789. DuplicateHandle(me,
  4790. (HANDLE)_get_osfhandle(fdout[1]),
  4791. me,
  4792. &si.hStdOutput,
  4793. 0,
  4794. TRUE,
  4795. DUPLICATE_SAME_ACCESS);
  4796. DuplicateHandle(me,
  4797. (HANDLE)_get_osfhandle(fderr[1]),
  4798. me,
  4799. &si.hStdError,
  4800. 0,
  4801. TRUE,
  4802. DUPLICATE_SAME_ACCESS);
  4803. /* Mark handles that should not be inherited. See
  4804. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4805. */
  4806. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4807. HANDLE_FLAG_INHERIT,
  4808. 0);
  4809. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4810. HANDLE_FLAG_INHERIT,
  4811. 0);
  4812. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4813. HANDLE_FLAG_INHERIT,
  4814. 0);
  4815. /* If CGI file is a script, try to read the interpreter line */
  4816. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4817. if (interp == NULL) {
  4818. buf[0] = buf[1] = '\0';
  4819. /* Read the first line of the script into the buffer */
  4820. mg_snprintf(
  4821. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4822. if (truncated) {
  4823. pi.hProcess = (pid_t)-1;
  4824. goto spawn_cleanup;
  4825. }
  4826. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4827. #if defined(MG_USE_OPEN_FILE)
  4828. p = (char *)file.access.membuf;
  4829. #else
  4830. p = (char *)NULL;
  4831. #endif
  4832. mg_fgets(buf, sizeof(buf), &file, &p);
  4833. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4834. buf[sizeof(buf) - 1] = '\0';
  4835. }
  4836. if ((buf[0] == '#') && (buf[1] == '!')) {
  4837. trim_trailing_whitespaces(buf + 2);
  4838. } else {
  4839. buf[2] = '\0';
  4840. }
  4841. interp = buf + 2;
  4842. }
  4843. if (interp[0] != '\0') {
  4844. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4845. interp = full_interp;
  4846. }
  4847. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4848. if (interp[0] != '\0') {
  4849. mg_snprintf(conn,
  4850. &truncated,
  4851. cmdline,
  4852. sizeof(cmdline),
  4853. "\"%s\" \"%s\\%s\"",
  4854. interp,
  4855. full_dir,
  4856. prog);
  4857. } else {
  4858. mg_snprintf(conn,
  4859. &truncated,
  4860. cmdline,
  4861. sizeof(cmdline),
  4862. "\"%s\\%s\"",
  4863. full_dir,
  4864. prog);
  4865. }
  4866. if (truncated) {
  4867. pi.hProcess = (pid_t)-1;
  4868. goto spawn_cleanup;
  4869. }
  4870. DEBUG_TRACE("Running [%s]", cmdline);
  4871. if (CreateProcessA(NULL,
  4872. cmdline,
  4873. NULL,
  4874. NULL,
  4875. TRUE,
  4876. CREATE_NEW_PROCESS_GROUP,
  4877. envblk,
  4878. NULL,
  4879. &si,
  4880. &pi)
  4881. == 0) {
  4882. mg_cry_internal(
  4883. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4884. pi.hProcess = (pid_t)-1;
  4885. /* goto spawn_cleanup; */
  4886. }
  4887. spawn_cleanup:
  4888. (void)CloseHandle(si.hStdOutput);
  4889. (void)CloseHandle(si.hStdError);
  4890. (void)CloseHandle(si.hStdInput);
  4891. if (pi.hThread != NULL) {
  4892. (void)CloseHandle(pi.hThread);
  4893. }
  4894. return (pid_t)pi.hProcess;
  4895. }
  4896. #endif /* !NO_CGI */
  4897. static int
  4898. set_blocking_mode(SOCKET sock)
  4899. {
  4900. unsigned long non_blocking = 0;
  4901. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4902. }
  4903. static int
  4904. set_non_blocking_mode(SOCKET sock)
  4905. {
  4906. unsigned long non_blocking = 1;
  4907. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4908. }
  4909. #else
  4910. static int
  4911. mg_stat(const struct mg_connection *conn,
  4912. const char *path,
  4913. struct mg_file_stat *filep)
  4914. {
  4915. struct stat st;
  4916. if (!filep) {
  4917. return 0;
  4918. }
  4919. memset(filep, 0, sizeof(*filep));
  4920. if (conn && is_file_in_memory(conn, path)) {
  4921. /* Quick fix (for 1.9.x): */
  4922. /* mg_stat must fill all fields, also for files in memory */
  4923. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4924. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4925. filep->size = tmp_file.stat.size;
  4926. filep->last_modified = time(NULL);
  4927. filep->location = 2;
  4928. /* TODO: remove legacy "files in memory" feature */
  4929. return 1;
  4930. }
  4931. if (0 == stat(path, &st)) {
  4932. filep->size = (uint64_t)(st.st_size);
  4933. filep->last_modified = st.st_mtime;
  4934. filep->is_directory = S_ISDIR(st.st_mode);
  4935. return 1;
  4936. }
  4937. return 0;
  4938. }
  4939. static void
  4940. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4941. {
  4942. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4943. if (conn) {
  4944. mg_cry_internal(conn,
  4945. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4946. __func__,
  4947. strerror(ERRNO));
  4948. }
  4949. }
  4950. }
  4951. int
  4952. mg_start_thread(mg_thread_func_t func, void *param)
  4953. {
  4954. pthread_t thread_id;
  4955. pthread_attr_t attr;
  4956. int result;
  4957. (void)pthread_attr_init(&attr);
  4958. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4959. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4960. /* Compile-time option to control stack size,
  4961. * e.g. -DUSE_STACK_SIZE=16384 */
  4962. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4963. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4964. result = pthread_create(&thread_id, &attr, func, param);
  4965. pthread_attr_destroy(&attr);
  4966. return result;
  4967. }
  4968. /* Start a thread storing the thread context. */
  4969. static int
  4970. mg_start_thread_with_id(mg_thread_func_t func,
  4971. void *param,
  4972. pthread_t *threadidptr)
  4973. {
  4974. pthread_t thread_id;
  4975. pthread_attr_t attr;
  4976. int result;
  4977. (void)pthread_attr_init(&attr);
  4978. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4979. /* Compile-time option to control stack size,
  4980. * e.g. -DUSE_STACK_SIZE=16384 */
  4981. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4982. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4983. result = pthread_create(&thread_id, &attr, func, param);
  4984. pthread_attr_destroy(&attr);
  4985. if ((result == 0) && (threadidptr != NULL)) {
  4986. *threadidptr = thread_id;
  4987. }
  4988. return result;
  4989. }
  4990. /* Wait for a thread to finish. */
  4991. static int
  4992. mg_join_thread(pthread_t threadid)
  4993. {
  4994. int result;
  4995. result = pthread_join(threadid, NULL);
  4996. return result;
  4997. }
  4998. #if !defined(NO_CGI)
  4999. static pid_t
  5000. spawn_process(struct mg_connection *conn,
  5001. const char *prog,
  5002. char *envblk,
  5003. char *envp[],
  5004. int fdin[2],
  5005. int fdout[2],
  5006. int fderr[2],
  5007. const char *dir)
  5008. {
  5009. pid_t pid;
  5010. const char *interp;
  5011. (void)envblk;
  5012. if (conn == NULL) {
  5013. return 0;
  5014. }
  5015. if ((pid = fork()) == -1) {
  5016. /* Parent */
  5017. mg_send_http_error(conn,
  5018. 500,
  5019. "Error: Creating CGI process\nfork(): %s",
  5020. strerror(ERRNO));
  5021. } else if (pid == 0) {
  5022. /* Child */
  5023. if (chdir(dir) != 0) {
  5024. mg_cry_internal(
  5025. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5026. } else if (dup2(fdin[0], 0) == -1) {
  5027. mg_cry_internal(conn,
  5028. "%s: dup2(%d, 0): %s",
  5029. __func__,
  5030. fdin[0],
  5031. strerror(ERRNO));
  5032. } else if (dup2(fdout[1], 1) == -1) {
  5033. mg_cry_internal(conn,
  5034. "%s: dup2(%d, 1): %s",
  5035. __func__,
  5036. fdout[1],
  5037. strerror(ERRNO));
  5038. } else if (dup2(fderr[1], 2) == -1) {
  5039. mg_cry_internal(conn,
  5040. "%s: dup2(%d, 2): %s",
  5041. __func__,
  5042. fderr[1],
  5043. strerror(ERRNO));
  5044. } else {
  5045. struct sigaction sa;
  5046. /* Keep stderr and stdout in two different pipes.
  5047. * Stdout will be sent back to the client,
  5048. * stderr should go into a server error log. */
  5049. (void)close(fdin[0]);
  5050. (void)close(fdout[1]);
  5051. (void)close(fderr[1]);
  5052. /* Close write end fdin and read end fdout and fderr */
  5053. (void)close(fdin[1]);
  5054. (void)close(fdout[0]);
  5055. (void)close(fderr[0]);
  5056. /* After exec, all signal handlers are restored to their default
  5057. * values, with one exception of SIGCHLD. According to
  5058. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5059. * will leave unchanged after exec if it was set to be ignored.
  5060. * Restore it to default action. */
  5061. memset(&sa, 0, sizeof(sa));
  5062. sa.sa_handler = SIG_DFL;
  5063. sigaction(SIGCHLD, &sa, NULL);
  5064. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5065. if (interp == NULL) {
  5066. (void)execle(prog, prog, NULL, envp);
  5067. mg_cry_internal(conn,
  5068. "%s: execle(%s): %s",
  5069. __func__,
  5070. prog,
  5071. strerror(ERRNO));
  5072. } else {
  5073. (void)execle(interp, interp, prog, NULL, envp);
  5074. mg_cry_internal(conn,
  5075. "%s: execle(%s %s): %s",
  5076. __func__,
  5077. interp,
  5078. prog,
  5079. strerror(ERRNO));
  5080. }
  5081. }
  5082. exit(EXIT_FAILURE);
  5083. }
  5084. return pid;
  5085. }
  5086. #endif /* !NO_CGI */
  5087. static int
  5088. set_non_blocking_mode(SOCKET sock)
  5089. {
  5090. int flags = fcntl(sock, F_GETFL, 0);
  5091. if (flags < 0) {
  5092. return -1;
  5093. }
  5094. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5095. return -1;
  5096. }
  5097. return 0;
  5098. }
  5099. static int
  5100. set_blocking_mode(SOCKET sock)
  5101. {
  5102. int flags = fcntl(sock, F_GETFL, 0);
  5103. if (flags < 0) {
  5104. return -1;
  5105. }
  5106. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5107. return -1;
  5108. }
  5109. return 0;
  5110. }
  5111. #endif /* _WIN32 / else */
  5112. /* End of initial operating system specific define block. */
  5113. /* Get a random number (independent of C rand function) */
  5114. static uint64_t
  5115. get_random(void)
  5116. {
  5117. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5118. static uint64_t lcg = 0; /* Linear congruential generator */
  5119. uint64_t now = mg_get_current_time_ns();
  5120. if (lfsr == 0) {
  5121. /* lfsr will be only 0 if has not been initialized,
  5122. * so this code is called only once. */
  5123. lfsr = mg_get_current_time_ns();
  5124. lcg = mg_get_current_time_ns();
  5125. } else {
  5126. /* Get the next step of both random number generators. */
  5127. lfsr = (lfsr >> 1)
  5128. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5129. << 63);
  5130. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5131. }
  5132. /* Combining two pseudo-random number generators and a high resolution
  5133. * part
  5134. * of the current server time will make it hard (impossible?) to guess
  5135. * the
  5136. * next number. */
  5137. return (lfsr ^ lcg ^ now);
  5138. }
  5139. static int
  5140. mg_poll(struct mg_pollfd *pfd,
  5141. unsigned int n,
  5142. int milliseconds,
  5143. volatile int *stop_server)
  5144. {
  5145. /* Call poll, but only for a maximum time of a few seconds.
  5146. * This will allow to stop the server after some seconds, instead
  5147. * of having to wait for a long socket timeout. */
  5148. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5149. do {
  5150. int result;
  5151. if (*stop_server) {
  5152. /* Shut down signal */
  5153. return -2;
  5154. }
  5155. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5156. ms_now = milliseconds;
  5157. }
  5158. result = poll(pfd, n, ms_now);
  5159. if (result != 0) {
  5160. /* Poll returned either success (1) or error (-1).
  5161. * Forward both to the caller. */
  5162. return result;
  5163. }
  5164. /* Poll returned timeout (0). */
  5165. if (milliseconds > 0) {
  5166. milliseconds -= ms_now;
  5167. }
  5168. } while (milliseconds != 0);
  5169. /* timeout: return 0 */
  5170. return 0;
  5171. }
  5172. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5173. * descriptor.
  5174. * Return value:
  5175. * >=0 .. number of bytes successfully written
  5176. * -1 .. timeout
  5177. * -2 .. error
  5178. */
  5179. static int
  5180. push_inner(struct mg_context *ctx,
  5181. FILE *fp,
  5182. SOCKET sock,
  5183. SSL *ssl,
  5184. const char *buf,
  5185. int len,
  5186. double timeout)
  5187. {
  5188. uint64_t start = 0, now = 0, timeout_ns = 0;
  5189. int n, err;
  5190. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5191. #if defined(_WIN32)
  5192. typedef int len_t;
  5193. #else
  5194. typedef size_t len_t;
  5195. #endif
  5196. if (timeout > 0) {
  5197. now = mg_get_current_time_ns();
  5198. start = now;
  5199. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5200. }
  5201. if (ctx == NULL) {
  5202. return -2;
  5203. }
  5204. #if defined(NO_SSL)
  5205. if (ssl) {
  5206. return -2;
  5207. }
  5208. #endif
  5209. /* Try to read until it succeeds, fails, times out, or the server
  5210. * shuts down. */
  5211. for (;;) {
  5212. #if !defined(NO_SSL)
  5213. if (ssl != NULL) {
  5214. n = SSL_write(ssl, buf, len);
  5215. if (n <= 0) {
  5216. err = SSL_get_error(ssl, n);
  5217. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5218. err = ERRNO;
  5219. } else if ((err == SSL_ERROR_WANT_READ)
  5220. || (err == SSL_ERROR_WANT_WRITE)) {
  5221. n = 0;
  5222. } else {
  5223. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5224. return -2;
  5225. }
  5226. } else {
  5227. err = 0;
  5228. }
  5229. } else
  5230. #endif
  5231. if (fp != NULL) {
  5232. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5233. if (ferror(fp)) {
  5234. n = -1;
  5235. err = ERRNO;
  5236. } else {
  5237. err = 0;
  5238. }
  5239. } else {
  5240. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5241. err = (n < 0) ? ERRNO : 0;
  5242. #if defined(_WIN32)
  5243. if (err == WSAEWOULDBLOCK) {
  5244. err = 0;
  5245. n = 0;
  5246. }
  5247. #else
  5248. if (err == EWOULDBLOCK) {
  5249. err = 0;
  5250. n = 0;
  5251. }
  5252. #endif
  5253. if (n < 0) {
  5254. /* shutdown of the socket at client side */
  5255. return -2;
  5256. }
  5257. }
  5258. if (ctx->stop_flag) {
  5259. return -2;
  5260. }
  5261. if ((n > 0) || ((n == 0) && (len == 0))) {
  5262. /* some data has been read, or no data was requested */
  5263. return n;
  5264. }
  5265. if (n < 0) {
  5266. /* socket error - check errno */
  5267. DEBUG_TRACE("send() failed, error %d", err);
  5268. /* TODO (mid): error handling depending on the error code.
  5269. * These codes are different between Windows and Linux.
  5270. * Currently there is no problem with failing send calls,
  5271. * if there is a reproducible situation, it should be
  5272. * investigated in detail.
  5273. */
  5274. return -2;
  5275. }
  5276. /* Only in case n=0 (timeout), repeat calling the write function */
  5277. /* If send failed, wait before retry */
  5278. if (fp != NULL) {
  5279. /* For files, just wait a fixed time.
  5280. * Maybe it helps, maybe not. */
  5281. mg_sleep(5);
  5282. } else {
  5283. /* For sockets, wait for the socket using poll */
  5284. struct mg_pollfd pfd[1];
  5285. int pollres;
  5286. pfd[0].fd = sock;
  5287. pfd[0].events = POLLOUT;
  5288. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5289. if (ctx->stop_flag) {
  5290. return -2;
  5291. }
  5292. if (pollres > 0) {
  5293. continue;
  5294. }
  5295. }
  5296. if (timeout > 0) {
  5297. now = mg_get_current_time_ns();
  5298. if ((now - start) > timeout_ns) {
  5299. /* Timeout */
  5300. break;
  5301. }
  5302. }
  5303. }
  5304. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5305. used */
  5306. return -1;
  5307. }
  5308. static int
  5309. push_all(struct mg_context *ctx,
  5310. FILE *fp,
  5311. SOCKET sock,
  5312. SSL *ssl,
  5313. const char *buf,
  5314. int len)
  5315. {
  5316. double timeout = -1.0;
  5317. int n, nwritten = 0;
  5318. if (ctx == NULL) {
  5319. return -1;
  5320. }
  5321. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5322. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5323. }
  5324. while ((len > 0) && (ctx->stop_flag == 0)) {
  5325. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5326. if (n < 0) {
  5327. if (nwritten == 0) {
  5328. nwritten = -1; /* Propagate the error */
  5329. }
  5330. break;
  5331. } else if (n == 0) {
  5332. break; /* No more data to write */
  5333. } else {
  5334. nwritten += n;
  5335. len -= n;
  5336. }
  5337. }
  5338. return nwritten;
  5339. }
  5340. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5341. * Return value:
  5342. * >=0 .. number of bytes successfully read
  5343. * -1 .. timeout
  5344. * -2 .. error
  5345. */
  5346. static int
  5347. pull_inner(FILE *fp,
  5348. struct mg_connection *conn,
  5349. char *buf,
  5350. int len,
  5351. double timeout)
  5352. {
  5353. int nread, err = 0;
  5354. #if defined(_WIN32)
  5355. typedef int len_t;
  5356. #else
  5357. typedef size_t len_t;
  5358. #endif
  5359. #if !defined(NO_SSL)
  5360. int ssl_pending;
  5361. #endif
  5362. /* We need an additional wait loop around this, because in some cases
  5363. * with TLSwe may get data from the socket but not from SSL_read.
  5364. * In this case we need to repeat at least once.
  5365. */
  5366. if (fp != NULL) {
  5367. #if !defined(_WIN32_WCE)
  5368. /* Use read() instead of fread(), because if we're reading from the
  5369. * CGI pipe, fread() may block until IO buffer is filled up. We
  5370. * cannot afford to block and must pass all read bytes immediately
  5371. * to the client. */
  5372. nread = (int)read(fileno(fp), buf, (size_t)len);
  5373. #else
  5374. /* WinCE does not support CGI pipes */
  5375. nread = (int)fread(buf, 1, (size_t)len, fp);
  5376. #endif
  5377. err = (nread < 0) ? ERRNO : 0;
  5378. if ((nread == 0) && (len > 0)) {
  5379. /* Should get data, but got EOL */
  5380. return -2;
  5381. }
  5382. #if !defined(NO_SSL)
  5383. } else if ((conn->ssl != NULL)
  5384. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5385. /* We already know there is no more data buffered in conn->buf
  5386. * but there is more available in the SSL layer. So don't poll
  5387. * conn->client.sock yet. */
  5388. if (ssl_pending > len) {
  5389. ssl_pending = len;
  5390. }
  5391. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5392. if (nread <= 0) {
  5393. err = SSL_get_error(conn->ssl, nread);
  5394. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5395. err = ERRNO;
  5396. } else if ((err == SSL_ERROR_WANT_READ)
  5397. || (err == SSL_ERROR_WANT_WRITE)) {
  5398. nread = 0;
  5399. } else {
  5400. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5401. return -1;
  5402. }
  5403. } else {
  5404. err = 0;
  5405. }
  5406. } else if (conn->ssl != NULL) {
  5407. struct mg_pollfd pfd[1];
  5408. int pollres;
  5409. pfd[0].fd = conn->client.sock;
  5410. pfd[0].events = POLLIN;
  5411. pollres = mg_poll(pfd,
  5412. 1,
  5413. (int)(timeout * 1000.0),
  5414. &(conn->phys_ctx->stop_flag));
  5415. if (conn->phys_ctx->stop_flag) {
  5416. return -2;
  5417. }
  5418. if (pollres > 0) {
  5419. nread = SSL_read(conn->ssl, buf, len);
  5420. if (nread <= 0) {
  5421. err = SSL_get_error(conn->ssl, nread);
  5422. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5423. err = ERRNO;
  5424. } else if ((err == SSL_ERROR_WANT_READ)
  5425. || (err == SSL_ERROR_WANT_WRITE)) {
  5426. nread = 0;
  5427. } else {
  5428. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5429. return -2;
  5430. }
  5431. } else {
  5432. err = 0;
  5433. }
  5434. } else if (pollres < 0) {
  5435. /* Error */
  5436. return -2;
  5437. } else {
  5438. /* pollres = 0 means timeout */
  5439. nread = 0;
  5440. }
  5441. #endif
  5442. } else {
  5443. struct mg_pollfd pfd[1];
  5444. int pollres;
  5445. pfd[0].fd = conn->client.sock;
  5446. pfd[0].events = POLLIN;
  5447. pollres = mg_poll(pfd,
  5448. 1,
  5449. (int)(timeout * 1000.0),
  5450. &(conn->phys_ctx->stop_flag));
  5451. if (conn->phys_ctx->stop_flag) {
  5452. return -2;
  5453. }
  5454. if (pollres > 0) {
  5455. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5456. err = (nread < 0) ? ERRNO : 0;
  5457. if (nread <= 0) {
  5458. /* shutdown of the socket at client side */
  5459. return -2;
  5460. }
  5461. } else if (pollres < 0) {
  5462. /* error callint poll */
  5463. return -2;
  5464. } else {
  5465. /* pollres = 0 means timeout */
  5466. nread = 0;
  5467. }
  5468. }
  5469. if (conn->phys_ctx->stop_flag) {
  5470. return -2;
  5471. }
  5472. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5473. /* some data has been read, or no data was requested */
  5474. return nread;
  5475. }
  5476. if (nread < 0) {
  5477. /* socket error - check errno */
  5478. #if defined(_WIN32)
  5479. if (err == WSAEWOULDBLOCK) {
  5480. /* TODO (low): check if this is still required */
  5481. /* standard case if called from close_socket_gracefully */
  5482. return -2;
  5483. } else if (err == WSAETIMEDOUT) {
  5484. /* TODO (low): check if this is still required */
  5485. /* timeout is handled by the while loop */
  5486. return 0;
  5487. } else if (err == WSAECONNABORTED) {
  5488. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5489. return -2;
  5490. } else {
  5491. DEBUG_TRACE("recv() failed, error %d", err);
  5492. return -2;
  5493. }
  5494. #else
  5495. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5496. * if the timeout is reached and if the socket was set to non-
  5497. * blocking in close_socket_gracefully, so we can not distinguish
  5498. * here. We have to wait for the timeout in both cases for now.
  5499. */
  5500. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5501. /* TODO (low): check if this is still required */
  5502. /* EAGAIN/EWOULDBLOCK:
  5503. * standard case if called from close_socket_gracefully
  5504. * => should return -1 */
  5505. /* or timeout occurred
  5506. * => the code must stay in the while loop */
  5507. /* EINTR can be generated on a socket with a timeout set even
  5508. * when SA_RESTART is effective for all relevant signals
  5509. * (see signal(7)).
  5510. * => stay in the while loop */
  5511. } else {
  5512. DEBUG_TRACE("recv() failed, error %d", err);
  5513. return -2;
  5514. }
  5515. #endif
  5516. }
  5517. /* Timeout occurred, but no data available. */
  5518. return -1;
  5519. }
  5520. static int
  5521. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5522. {
  5523. int n, nread = 0;
  5524. double timeout = -1.0;
  5525. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5526. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5527. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5528. }
  5529. if (timeout >= 0.0) {
  5530. start_time = mg_get_current_time_ns();
  5531. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5532. }
  5533. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5534. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5535. if (n == -2) {
  5536. if (nread == 0) {
  5537. nread = -1; /* Propagate the error */
  5538. }
  5539. break;
  5540. } else if (n == -1) {
  5541. /* timeout */
  5542. if (timeout >= 0.0) {
  5543. now = mg_get_current_time_ns();
  5544. if ((now - start_time) <= timeout_ns) {
  5545. continue;
  5546. }
  5547. }
  5548. break;
  5549. } else if (n == 0) {
  5550. break; /* No more data to read */
  5551. } else {
  5552. conn->consumed_content += n;
  5553. nread += n;
  5554. len -= n;
  5555. }
  5556. }
  5557. return nread;
  5558. }
  5559. static void
  5560. discard_unread_request_data(struct mg_connection *conn)
  5561. {
  5562. char buf[MG_BUF_LEN];
  5563. size_t to_read;
  5564. int nread;
  5565. if (conn == NULL) {
  5566. return;
  5567. }
  5568. to_read = sizeof(buf);
  5569. if (conn->is_chunked) {
  5570. /* Chunked encoding: 3=chunk read completely
  5571. * completely */
  5572. while (conn->is_chunked != 3) {
  5573. nread = mg_read(conn, buf, to_read);
  5574. if (nread <= 0) {
  5575. break;
  5576. }
  5577. }
  5578. } else {
  5579. /* Not chunked: content length is known */
  5580. while (conn->consumed_content < conn->content_len) {
  5581. if (to_read
  5582. > (size_t)(conn->content_len - conn->consumed_content)) {
  5583. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5584. }
  5585. nread = mg_read(conn, buf, to_read);
  5586. if (nread <= 0) {
  5587. break;
  5588. }
  5589. }
  5590. }
  5591. }
  5592. static int
  5593. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5594. {
  5595. int64_t n, buffered_len, nread;
  5596. int64_t len64 =
  5597. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5598. * int, we may not read more
  5599. * bytes */
  5600. const char *body;
  5601. if (conn == NULL) {
  5602. return 0;
  5603. }
  5604. /* If Content-Length is not set for a request with body data
  5605. * (e.g., a PUT or POST request), we do not know in advance
  5606. * how much data should be read. */
  5607. if (conn->consumed_content == 0) {
  5608. if (conn->is_chunked == 1) {
  5609. conn->content_len = len64;
  5610. conn->is_chunked = 2;
  5611. } else if (conn->content_len == -1) {
  5612. /* The body data is completed when the connection
  5613. * is closed. */
  5614. conn->content_len = INT64_MAX;
  5615. conn->must_close = 1;
  5616. }
  5617. }
  5618. nread = 0;
  5619. if (conn->consumed_content < conn->content_len) {
  5620. /* Adjust number of bytes to read. */
  5621. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5622. if (left_to_read < len64) {
  5623. /* Do not read more than the total content length of the
  5624. * request.
  5625. */
  5626. len64 = left_to_read;
  5627. }
  5628. /* Return buffered data */
  5629. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5630. - conn->consumed_content;
  5631. if (buffered_len > 0) {
  5632. if (len64 < buffered_len) {
  5633. buffered_len = len64;
  5634. }
  5635. body = conn->buf + conn->request_len + conn->consumed_content;
  5636. memcpy(buf, body, (size_t)buffered_len);
  5637. len64 -= buffered_len;
  5638. conn->consumed_content += buffered_len;
  5639. nread += buffered_len;
  5640. buf = (char *)buf + buffered_len;
  5641. }
  5642. /* We have returned all buffered data. Read new data from the remote
  5643. * socket.
  5644. */
  5645. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5646. nread += n;
  5647. } else {
  5648. nread = ((nread > 0) ? nread : n);
  5649. }
  5650. }
  5651. return (int)nread;
  5652. }
  5653. static char
  5654. mg_getc(struct mg_connection *conn)
  5655. {
  5656. char c;
  5657. if (conn == NULL) {
  5658. return 0;
  5659. }
  5660. if (mg_read_inner(conn, &c, 1) <= 0) {
  5661. return (char)0;
  5662. }
  5663. return c;
  5664. }
  5665. int
  5666. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5667. {
  5668. if (len > INT_MAX) {
  5669. len = INT_MAX;
  5670. }
  5671. if (conn == NULL) {
  5672. return 0;
  5673. }
  5674. if (conn->is_chunked) {
  5675. size_t all_read = 0;
  5676. while (len > 0) {
  5677. if (conn->is_chunked == 3) {
  5678. /* No more data left to read */
  5679. return 0;
  5680. }
  5681. if (conn->chunk_remainder) {
  5682. /* copy from the remainder of the last received chunk */
  5683. long read_ret;
  5684. size_t read_now =
  5685. ((conn->chunk_remainder > len) ? (len)
  5686. : (conn->chunk_remainder));
  5687. conn->content_len += (int)read_now;
  5688. read_ret =
  5689. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5690. if (read_ret < 1) {
  5691. /* read error */
  5692. return -1;
  5693. }
  5694. all_read += (size_t)read_ret;
  5695. conn->chunk_remainder -= (size_t)read_ret;
  5696. len -= (size_t)read_ret;
  5697. if (conn->chunk_remainder == 0) {
  5698. /* Add data bytes in the current chunk have been read,
  5699. * so we are expecting \r\n now. */
  5700. char x1, x2;
  5701. conn->content_len += 2;
  5702. x1 = mg_getc(conn);
  5703. x2 = mg_getc(conn);
  5704. if ((x1 != '\r') || (x2 != '\n')) {
  5705. /* Protocol violation */
  5706. return -1;
  5707. }
  5708. }
  5709. } else {
  5710. /* fetch a new chunk */
  5711. int i = 0;
  5712. char lenbuf[64];
  5713. char *end = 0;
  5714. unsigned long chunkSize = 0;
  5715. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5716. conn->content_len++;
  5717. lenbuf[i] = mg_getc(conn);
  5718. if ((i > 0) && (lenbuf[i] == '\r')
  5719. && (lenbuf[i - 1] != '\r')) {
  5720. continue;
  5721. }
  5722. if ((i > 1) && (lenbuf[i] == '\n')
  5723. && (lenbuf[i - 1] == '\r')) {
  5724. lenbuf[i + 1] = 0;
  5725. chunkSize = strtoul(lenbuf, &end, 16);
  5726. if (chunkSize == 0) {
  5727. /* regular end of content */
  5728. conn->is_chunked = 3;
  5729. }
  5730. break;
  5731. }
  5732. if (!isxdigit((unsigned char)lenbuf[i])) {
  5733. /* illegal character for chunk length */
  5734. return -1;
  5735. }
  5736. }
  5737. if ((end == NULL) || (*end != '\r')) {
  5738. /* chunksize not set correctly */
  5739. return -1;
  5740. }
  5741. if (chunkSize == 0) {
  5742. break;
  5743. }
  5744. conn->chunk_remainder = chunkSize;
  5745. }
  5746. }
  5747. return (int)all_read;
  5748. }
  5749. return mg_read_inner(conn, buf, len);
  5750. }
  5751. int
  5752. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5753. {
  5754. time_t now;
  5755. int n, total, allowed;
  5756. if (conn == NULL) {
  5757. return 0;
  5758. }
  5759. if (len > INT_MAX) {
  5760. return -1;
  5761. }
  5762. if (conn->throttle > 0) {
  5763. if ((now = time(NULL)) != conn->last_throttle_time) {
  5764. conn->last_throttle_time = now;
  5765. conn->last_throttle_bytes = 0;
  5766. }
  5767. allowed = conn->throttle - conn->last_throttle_bytes;
  5768. if (allowed > (int)len) {
  5769. allowed = (int)len;
  5770. }
  5771. if ((total = push_all(conn->phys_ctx,
  5772. NULL,
  5773. conn->client.sock,
  5774. conn->ssl,
  5775. (const char *)buf,
  5776. allowed))
  5777. == allowed) {
  5778. buf = (const char *)buf + total;
  5779. conn->last_throttle_bytes += total;
  5780. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5781. allowed = (conn->throttle > ((int)len - total))
  5782. ? (int)len - total
  5783. : conn->throttle;
  5784. if ((n = push_all(conn->phys_ctx,
  5785. NULL,
  5786. conn->client.sock,
  5787. conn->ssl,
  5788. (const char *)buf,
  5789. allowed))
  5790. != allowed) {
  5791. break;
  5792. }
  5793. sleep(1);
  5794. conn->last_throttle_bytes = allowed;
  5795. conn->last_throttle_time = time(NULL);
  5796. buf = (const char *)buf + n;
  5797. total += n;
  5798. }
  5799. }
  5800. } else {
  5801. total = push_all(conn->phys_ctx,
  5802. NULL,
  5803. conn->client.sock,
  5804. conn->ssl,
  5805. (const char *)buf,
  5806. (int)len);
  5807. }
  5808. if (total > 0) {
  5809. conn->num_bytes_sent += total;
  5810. }
  5811. return total;
  5812. }
  5813. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5814. int
  5815. mg_send_chunk(struct mg_connection *conn,
  5816. const char *chunk,
  5817. unsigned int chunk_len)
  5818. {
  5819. char lenbuf[16];
  5820. size_t lenbuf_len;
  5821. int ret;
  5822. int t;
  5823. /* First store the length information in a text buffer. */
  5824. sprintf(lenbuf, "%x\r\n", chunk_len);
  5825. lenbuf_len = strlen(lenbuf);
  5826. /* Then send length information, chunk and terminating \r\n. */
  5827. ret = mg_write(conn, lenbuf, lenbuf_len);
  5828. if (ret != (int)lenbuf_len) {
  5829. return -1;
  5830. }
  5831. t = ret;
  5832. ret = mg_write(conn, chunk, chunk_len);
  5833. if (ret != (int)chunk_len) {
  5834. return -1;
  5835. }
  5836. t += ret;
  5837. ret = mg_write(conn, "\r\n", 2);
  5838. if (ret != 2) {
  5839. return -1;
  5840. }
  5841. t += ret;
  5842. return t;
  5843. }
  5844. #if defined(GCC_DIAGNOSTIC)
  5845. /* This block forwards format strings to printf implementations,
  5846. * so we need to disable the format-nonliteral warning. */
  5847. #pragma GCC diagnostic push
  5848. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5849. #endif
  5850. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5851. static int
  5852. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5853. {
  5854. va_list ap_copy;
  5855. size_t size = MG_BUF_LEN / 4;
  5856. int len = -1;
  5857. *buf = NULL;
  5858. while (len < 0) {
  5859. if (*buf) {
  5860. mg_free(*buf);
  5861. }
  5862. size *= 4;
  5863. *buf = (char *)mg_malloc(size);
  5864. if (!*buf) {
  5865. break;
  5866. }
  5867. va_copy(ap_copy, ap);
  5868. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5869. va_end(ap_copy);
  5870. (*buf)[size - 1] = 0;
  5871. }
  5872. return len;
  5873. }
  5874. /* Print message to buffer. If buffer is large enough to hold the message,
  5875. * return buffer. If buffer is to small, allocate large enough buffer on
  5876. * heap,
  5877. * and return allocated buffer. */
  5878. static int
  5879. alloc_vprintf(char **out_buf,
  5880. char *prealloc_buf,
  5881. size_t prealloc_size,
  5882. const char *fmt,
  5883. va_list ap)
  5884. {
  5885. va_list ap_copy;
  5886. int len;
  5887. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5888. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5889. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5890. * Therefore, we make two passes: on first pass, get required message
  5891. * length.
  5892. * On second pass, actually print the message. */
  5893. va_copy(ap_copy, ap);
  5894. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5895. va_end(ap_copy);
  5896. if (len < 0) {
  5897. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5898. * Switch to alternative code path that uses incremental
  5899. * allocations.
  5900. */
  5901. va_copy(ap_copy, ap);
  5902. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5903. va_end(ap_copy);
  5904. } else if ((size_t)(len) >= prealloc_size) {
  5905. /* The pre-allocated buffer not large enough. */
  5906. /* Allocate a new buffer. */
  5907. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5908. if (!*out_buf) {
  5909. /* Allocation failed. Return -1 as "out of memory" error. */
  5910. return -1;
  5911. }
  5912. /* Buffer allocation successful. Store the string there. */
  5913. va_copy(ap_copy, ap);
  5914. IGNORE_UNUSED_RESULT(
  5915. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5916. va_end(ap_copy);
  5917. } else {
  5918. /* The pre-allocated buffer is large enough.
  5919. * Use it to store the string and return the address. */
  5920. va_copy(ap_copy, ap);
  5921. IGNORE_UNUSED_RESULT(
  5922. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5923. va_end(ap_copy);
  5924. *out_buf = prealloc_buf;
  5925. }
  5926. return len;
  5927. }
  5928. #if defined(GCC_DIAGNOSTIC)
  5929. /* Enable format-nonliteral warning again. */
  5930. #pragma GCC diagnostic pop
  5931. #endif
  5932. static int
  5933. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5934. {
  5935. char mem[MG_BUF_LEN];
  5936. char *buf = NULL;
  5937. int len;
  5938. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5939. len = mg_write(conn, buf, (size_t)len);
  5940. }
  5941. if (buf != mem) {
  5942. mg_free(buf);
  5943. }
  5944. return len;
  5945. }
  5946. int
  5947. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5948. {
  5949. va_list ap;
  5950. int result;
  5951. va_start(ap, fmt);
  5952. result = mg_vprintf(conn, fmt, ap);
  5953. va_end(ap);
  5954. return result;
  5955. }
  5956. int
  5957. mg_url_decode(const char *src,
  5958. int src_len,
  5959. char *dst,
  5960. int dst_len,
  5961. int is_form_url_encoded)
  5962. {
  5963. int i, j, a, b;
  5964. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5965. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5966. if ((i < src_len - 2) && (src[i] == '%')
  5967. && isxdigit((unsigned char)src[i + 1])
  5968. && isxdigit((unsigned char)src[i + 2])) {
  5969. a = tolower((unsigned char)src[i + 1]);
  5970. b = tolower((unsigned char)src[i + 2]);
  5971. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5972. i += 2;
  5973. } else if (is_form_url_encoded && (src[i] == '+')) {
  5974. dst[j] = ' ';
  5975. } else {
  5976. dst[j] = src[i];
  5977. }
  5978. }
  5979. dst[j] = '\0'; /* Null-terminate the destination */
  5980. return (i >= src_len) ? j : -1;
  5981. }
  5982. int
  5983. mg_get_var(const char *data,
  5984. size_t data_len,
  5985. const char *name,
  5986. char *dst,
  5987. size_t dst_len)
  5988. {
  5989. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5990. }
  5991. int
  5992. mg_get_var2(const char *data,
  5993. size_t data_len,
  5994. const char *name,
  5995. char *dst,
  5996. size_t dst_len,
  5997. size_t occurrence)
  5998. {
  5999. const char *p, *e, *s;
  6000. size_t name_len;
  6001. int len;
  6002. if ((dst == NULL) || (dst_len == 0)) {
  6003. len = -2;
  6004. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  6005. len = -1;
  6006. dst[0] = '\0';
  6007. } else {
  6008. name_len = strlen(name);
  6009. e = data + data_len;
  6010. len = -1;
  6011. dst[0] = '\0';
  6012. /* data is "var1=val1&var2=val2...". Find variable first */
  6013. for (p = data; p + name_len < e; p++) {
  6014. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6015. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6016. /* Point p to variable value */
  6017. p += name_len + 1;
  6018. /* Point s to the end of the value */
  6019. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6020. if (s == NULL) {
  6021. s = e;
  6022. }
  6023. DEBUG_ASSERT(s >= p);
  6024. if (s < p) {
  6025. return -3;
  6026. }
  6027. /* Decode variable into destination buffer */
  6028. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6029. /* Redirect error code from -1 to -2 (destination buffer too
  6030. * small). */
  6031. if (len == -1) {
  6032. len = -2;
  6033. }
  6034. break;
  6035. }
  6036. }
  6037. }
  6038. return len;
  6039. }
  6040. /* HCP24: some changes to compare hole var_name */
  6041. int
  6042. mg_get_cookie(const char *cookie_header,
  6043. const char *var_name,
  6044. char *dst,
  6045. size_t dst_size)
  6046. {
  6047. const char *s, *p, *end;
  6048. int name_len, len = -1;
  6049. if ((dst == NULL) || (dst_size == 0)) {
  6050. return -2;
  6051. }
  6052. dst[0] = '\0';
  6053. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6054. return -1;
  6055. }
  6056. name_len = (int)strlen(var_name);
  6057. end = s + strlen(s);
  6058. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6059. if (s[name_len] == '=') {
  6060. /* HCP24: now check is it a substring or a full cookie name */
  6061. if ((s == cookie_header) || (s[-1] == ' ')) {
  6062. s += name_len + 1;
  6063. if ((p = strchr(s, ' ')) == NULL) {
  6064. p = end;
  6065. }
  6066. if (p[-1] == ';') {
  6067. p--;
  6068. }
  6069. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6070. s++;
  6071. p--;
  6072. }
  6073. if ((size_t)(p - s) < dst_size) {
  6074. len = (int)(p - s);
  6075. mg_strlcpy(dst, s, (size_t)len + 1);
  6076. } else {
  6077. len = -3;
  6078. }
  6079. break;
  6080. }
  6081. }
  6082. }
  6083. return len;
  6084. }
  6085. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6086. static void
  6087. base64_encode(const unsigned char *src, int src_len, char *dst)
  6088. {
  6089. static const char *b64 =
  6090. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6091. int i, j, a, b, c;
  6092. for (i = j = 0; i < src_len; i += 3) {
  6093. a = src[i];
  6094. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6095. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6096. dst[j++] = b64[a >> 2];
  6097. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6098. if (i + 1 < src_len) {
  6099. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6100. }
  6101. if (i + 2 < src_len) {
  6102. dst[j++] = b64[c & 63];
  6103. }
  6104. }
  6105. while (j % 4 != 0) {
  6106. dst[j++] = '=';
  6107. }
  6108. dst[j++] = '\0';
  6109. }
  6110. #endif
  6111. #if defined(USE_LUA)
  6112. static unsigned char
  6113. b64reverse(char letter)
  6114. {
  6115. if ((letter >= 'A') && (letter <= 'Z')) {
  6116. return letter - 'A';
  6117. }
  6118. if ((letter >= 'a') && (letter <= 'z')) {
  6119. return letter - 'a' + 26;
  6120. }
  6121. if ((letter >= '0') && (letter <= '9')) {
  6122. return letter - '0' + 52;
  6123. }
  6124. if (letter == '+') {
  6125. return 62;
  6126. }
  6127. if (letter == '/') {
  6128. return 63;
  6129. }
  6130. if (letter == '=') {
  6131. return 255; /* normal end */
  6132. }
  6133. return 254; /* error */
  6134. }
  6135. static int
  6136. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6137. {
  6138. int i;
  6139. unsigned char a, b, c, d;
  6140. *dst_len = 0;
  6141. for (i = 0; i < src_len; i += 4) {
  6142. a = b64reverse(src[i]);
  6143. if (a >= 254) {
  6144. return i;
  6145. }
  6146. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6147. if (b >= 254) {
  6148. return i + 1;
  6149. }
  6150. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6151. if (c == 254) {
  6152. return i + 2;
  6153. }
  6154. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6155. if (d == 254) {
  6156. return i + 3;
  6157. }
  6158. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6159. if (c != 255) {
  6160. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6161. if (d != 255) {
  6162. dst[(*dst_len)++] = (c << 6) + d;
  6163. }
  6164. }
  6165. }
  6166. return -1;
  6167. }
  6168. #endif
  6169. static int
  6170. is_put_or_delete_method(const struct mg_connection *conn)
  6171. {
  6172. if (conn) {
  6173. const char *s = conn->request_info.request_method;
  6174. return (s != NULL)
  6175. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6176. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6177. }
  6178. return 0;
  6179. }
  6180. #if !defined(NO_FILES)
  6181. static int
  6182. extention_matches_script(
  6183. struct mg_connection *conn, /* in: request (must be valid) */
  6184. const char *filename /* in: filename (must be valid) */
  6185. )
  6186. {
  6187. #if !defined(NO_CGI)
  6188. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6189. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6190. filename)
  6191. > 0) {
  6192. return 1;
  6193. }
  6194. #endif
  6195. #if defined(USE_LUA)
  6196. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6197. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6198. filename)
  6199. > 0) {
  6200. return 1;
  6201. }
  6202. #endif
  6203. #if defined(USE_DUKTAPE)
  6204. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6205. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6206. filename)
  6207. > 0) {
  6208. return 1;
  6209. }
  6210. #endif
  6211. /* filename and conn could be unused, if all preocessor conditions
  6212. * are false (no script language supported). */
  6213. (void)filename;
  6214. (void)conn;
  6215. return 0;
  6216. }
  6217. /* For given directory path, substitute it to valid index file.
  6218. * Return 1 if index file has been found, 0 if not found.
  6219. * If the file is found, it's stats is returned in stp. */
  6220. static int
  6221. substitute_index_file(struct mg_connection *conn,
  6222. char *path,
  6223. size_t path_len,
  6224. struct mg_file_stat *filestat)
  6225. {
  6226. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6227. struct vec filename_vec;
  6228. size_t n = strlen(path);
  6229. int found = 0;
  6230. /* The 'path' given to us points to the directory. Remove all trailing
  6231. * directory separator characters from the end of the path, and
  6232. * then append single directory separator character. */
  6233. while ((n > 0) && (path[n - 1] == '/')) {
  6234. n--;
  6235. }
  6236. path[n] = '/';
  6237. /* Traverse index files list. For each entry, append it to the given
  6238. * path and see if the file exists. If it exists, break the loop */
  6239. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6240. /* Ignore too long entries that may overflow path buffer */
  6241. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6242. continue;
  6243. }
  6244. /* Prepare full path to the index file */
  6245. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6246. /* Does it exist? */
  6247. if (mg_stat(conn, path, filestat)) {
  6248. /* Yes it does, break the loop */
  6249. found = 1;
  6250. break;
  6251. }
  6252. }
  6253. /* If no index file exists, restore directory path */
  6254. if (!found) {
  6255. path[n] = '\0';
  6256. }
  6257. return found;
  6258. }
  6259. #endif
  6260. static void
  6261. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6262. char *filename, /* out: filename */
  6263. size_t filename_buf_len, /* in: size of filename buffer */
  6264. struct mg_file_stat *filestat, /* out: file status structure */
  6265. int *is_found, /* out: file found (directly) */
  6266. int *is_script_resource, /* out: handled by a script? */
  6267. int *is_websocket_request, /* out: websocket connetion? */
  6268. int *is_put_or_delete_request /* out: put/delete a file? */
  6269. )
  6270. {
  6271. char const *accept_encoding;
  6272. #if !defined(NO_FILES)
  6273. const char *uri = conn->request_info.local_uri;
  6274. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6275. const char *rewrite;
  6276. struct vec a, b;
  6277. ptrdiff_t match_len;
  6278. char gz_path[PATH_MAX];
  6279. int truncated;
  6280. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6281. char *tmp_str;
  6282. size_t tmp_str_len, sep_pos;
  6283. int allow_substitute_script_subresources;
  6284. #endif
  6285. #else
  6286. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6287. #endif
  6288. /* Step 1: Set all initially unknown outputs to zero */
  6289. memset(filestat, 0, sizeof(*filestat));
  6290. *filename = 0;
  6291. *is_found = 0;
  6292. *is_script_resource = 0;
  6293. /* Step 2: Check if the request attempts to modify the file system */
  6294. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6295. /* Step 3: Check if it is a websocket request, and modify the document
  6296. * root if required */
  6297. #if defined(USE_WEBSOCKET)
  6298. *is_websocket_request = is_websocket_protocol(conn);
  6299. #if !defined(NO_FILES)
  6300. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6301. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6302. }
  6303. #endif /* !NO_FILES */
  6304. #else /* USE_WEBSOCKET */
  6305. *is_websocket_request = 0;
  6306. #endif /* USE_WEBSOCKET */
  6307. /* Step 4: Check if gzip encoded response is allowed */
  6308. conn->accept_gzip = 0;
  6309. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6310. if (strstr(accept_encoding, "gzip") != NULL) {
  6311. conn->accept_gzip = 1;
  6312. }
  6313. }
  6314. #if !defined(NO_FILES)
  6315. /* Step 5: If there is no root directory, don't look for files. */
  6316. /* Note that root == NULL is a regular use case here. This occurs,
  6317. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6318. * config is not required. */
  6319. if (root == NULL) {
  6320. /* all file related outputs have already been set to 0, just return
  6321. */
  6322. return;
  6323. }
  6324. /* Step 6: Determine the local file path from the root path and the
  6325. * request uri. */
  6326. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6327. * part of the path one byte on the right. */
  6328. mg_snprintf(
  6329. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6330. if (truncated) {
  6331. goto interpret_cleanup;
  6332. }
  6333. /* Step 7: URI rewriting */
  6334. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6335. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6336. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6337. mg_snprintf(conn,
  6338. &truncated,
  6339. filename,
  6340. filename_buf_len - 1,
  6341. "%.*s%s",
  6342. (int)b.len,
  6343. b.ptr,
  6344. uri + match_len);
  6345. break;
  6346. }
  6347. }
  6348. if (truncated) {
  6349. goto interpret_cleanup;
  6350. }
  6351. /* Step 8: Check if the file exists at the server */
  6352. /* Local file path and name, corresponding to requested URI
  6353. * is now stored in "filename" variable. */
  6354. if (mg_stat(conn, filename, filestat)) {
  6355. int uri_len = (int)strlen(uri);
  6356. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6357. /* 8.1: File exists. */
  6358. *is_found = 1;
  6359. /* 8.2: Check if it is a script type. */
  6360. if (extention_matches_script(conn, filename)) {
  6361. /* The request addresses a CGI resource, Lua script or
  6362. * server-side javascript.
  6363. * The URI corresponds to the script itself (like
  6364. * /path/script.cgi), and there is no additional resource
  6365. * path (like /path/script.cgi/something).
  6366. * Requests that modify (replace or delete) a resource, like
  6367. * PUT and DELETE requests, should replace/delete the script
  6368. * file.
  6369. * Requests that read or write from/to a resource, like GET and
  6370. * POST requests, should call the script and return the
  6371. * generated response. */
  6372. *is_script_resource = (!*is_put_or_delete_request);
  6373. }
  6374. /* 8.3: If the request target is a directory, there could be
  6375. * a substitute file (index.html, index.cgi, ...). */
  6376. if (filestat->is_directory && is_uri_end_slash) {
  6377. /* Use a local copy here, since substitute_index_file will
  6378. * change the content of the file status */
  6379. struct mg_file_stat tmp_filestat;
  6380. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6381. if (substitute_index_file(
  6382. conn, filename, filename_buf_len, &tmp_filestat)) {
  6383. /* Substitute file found. Copy stat to the output, then
  6384. * check if the file is a script file */
  6385. *filestat = tmp_filestat;
  6386. if (extention_matches_script(conn, filename)) {
  6387. /* Substitute file is a script file */
  6388. *is_script_resource = 1;
  6389. } else {
  6390. /* Substitute file is a regular file */
  6391. *is_script_resource = 0;
  6392. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6393. }
  6394. }
  6395. /* If there is no substitute file, the server could return
  6396. * a directory listing in a later step */
  6397. }
  6398. return;
  6399. }
  6400. /* Step 9: Check for zipped files: */
  6401. /* If we can't find the actual file, look for the file
  6402. * with the same name but a .gz extension. If we find it,
  6403. * use that and set the gzipped flag in the file struct
  6404. * to indicate that the response need to have the content-
  6405. * encoding: gzip header.
  6406. * We can only do this if the browser declares support. */
  6407. if (conn->accept_gzip) {
  6408. mg_snprintf(
  6409. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6410. if (truncated) {
  6411. goto interpret_cleanup;
  6412. }
  6413. if (mg_stat(conn, gz_path, filestat)) {
  6414. if (filestat) {
  6415. filestat->is_gzipped = 1;
  6416. *is_found = 1;
  6417. }
  6418. /* Currently gz files can not be scripts. */
  6419. return;
  6420. }
  6421. }
  6422. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6423. /* Step 10: Script resources may handle sub-resources */
  6424. /* Support PATH_INFO for CGI scripts. */
  6425. tmp_str_len = strlen(filename);
  6426. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6427. if (!tmp_str) {
  6428. /* Out of memory */
  6429. goto interpret_cleanup;
  6430. }
  6431. memcpy(tmp_str, filename, tmp_str_len + 1);
  6432. /* Check config, if index scripts may have sub-resources */
  6433. allow_substitute_script_subresources =
  6434. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6435. "yes");
  6436. sep_pos = tmp_str_len;
  6437. while (sep_pos > 0) {
  6438. sep_pos--;
  6439. if (tmp_str[sep_pos] == '/') {
  6440. int is_script = 0, does_exist = 0;
  6441. tmp_str[sep_pos] = 0;
  6442. if (tmp_str[0]) {
  6443. is_script = extention_matches_script(conn, tmp_str);
  6444. does_exist = mg_stat(conn, tmp_str, filestat);
  6445. }
  6446. if (does_exist && is_script) {
  6447. filename[sep_pos] = 0;
  6448. memmove(filename + sep_pos + 2,
  6449. filename + sep_pos + 1,
  6450. strlen(filename + sep_pos + 1) + 1);
  6451. conn->path_info = filename + sep_pos + 1;
  6452. filename[sep_pos + 1] = '/';
  6453. *is_script_resource = 1;
  6454. *is_found = 1;
  6455. break;
  6456. }
  6457. if (allow_substitute_script_subresources) {
  6458. if (substitute_index_file(
  6459. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6460. /* some intermediate directory has an index file */
  6461. if (extention_matches_script(conn, tmp_str)) {
  6462. char *tmp_str2;
  6463. DEBUG_TRACE("Substitute script %s serving path %s",
  6464. tmp_str,
  6465. filename);
  6466. /* this index file is a script */
  6467. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6468. conn->phys_ctx);
  6469. mg_snprintf(conn,
  6470. &truncated,
  6471. filename,
  6472. filename_buf_len,
  6473. "%s//%s",
  6474. tmp_str,
  6475. tmp_str2);
  6476. mg_free(tmp_str2);
  6477. if (truncated) {
  6478. mg_free(tmp_str);
  6479. goto interpret_cleanup;
  6480. }
  6481. sep_pos = strlen(tmp_str);
  6482. filename[sep_pos] = 0;
  6483. conn->path_info = filename + sep_pos + 1;
  6484. *is_script_resource = 1;
  6485. *is_found = 1;
  6486. break;
  6487. } else {
  6488. DEBUG_TRACE("Substitute file %s serving path %s",
  6489. tmp_str,
  6490. filename);
  6491. /* non-script files will not have sub-resources */
  6492. filename[sep_pos] = 0;
  6493. conn->path_info = 0;
  6494. *is_script_resource = 0;
  6495. *is_found = 0;
  6496. break;
  6497. }
  6498. }
  6499. }
  6500. tmp_str[sep_pos] = '/';
  6501. }
  6502. }
  6503. mg_free(tmp_str);
  6504. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6505. #endif /* !defined(NO_FILES) */
  6506. return;
  6507. #if !defined(NO_FILES)
  6508. /* Reset all outputs */
  6509. interpret_cleanup:
  6510. memset(filestat, 0, sizeof(*filestat));
  6511. *filename = 0;
  6512. *is_found = 0;
  6513. *is_script_resource = 0;
  6514. *is_websocket_request = 0;
  6515. *is_put_or_delete_request = 0;
  6516. #endif /* !defined(NO_FILES) */
  6517. }
  6518. /* Check whether full request is buffered. Return:
  6519. * -1 if request or response is malformed
  6520. * 0 if request or response is not yet fully buffered
  6521. * >0 actual request length, including last \r\n\r\n */
  6522. static int
  6523. get_http_header_len(const char *buf, int buflen)
  6524. {
  6525. int i;
  6526. for (i = 0; i < buflen; i++) {
  6527. /* Do an unsigned comparison in some conditions below */
  6528. const unsigned char c = (unsigned char)buf[i];
  6529. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6530. && !isprint(c)) {
  6531. /* abort scan as soon as one malformed character is found */
  6532. return -1;
  6533. }
  6534. if (i < buflen - 1) {
  6535. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6536. /* Two newline, no carriage return - not standard compliant,
  6537. * but
  6538. * it
  6539. * should be accepted */
  6540. return i + 2;
  6541. }
  6542. }
  6543. if (i < buflen - 3) {
  6544. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6545. && (buf[i + 3] == '\n')) {
  6546. /* Two \r\n - standard compliant */
  6547. return i + 4;
  6548. }
  6549. }
  6550. }
  6551. return 0;
  6552. }
  6553. #if !defined(NO_CACHING)
  6554. /* Convert month to the month number. Return -1 on error, or month number */
  6555. static int
  6556. get_month_index(const char *s)
  6557. {
  6558. size_t i;
  6559. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6560. if (!strcmp(s, month_names[i])) {
  6561. return (int)i;
  6562. }
  6563. }
  6564. return -1;
  6565. }
  6566. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6567. static time_t
  6568. parse_date_string(const char *datetime)
  6569. {
  6570. char month_str[32] = {0};
  6571. int second, minute, hour, day, month, year;
  6572. time_t result = (time_t)0;
  6573. struct tm tm;
  6574. if ((sscanf(datetime,
  6575. "%d/%3s/%d %d:%d:%d",
  6576. &day,
  6577. month_str,
  6578. &year,
  6579. &hour,
  6580. &minute,
  6581. &second)
  6582. == 6)
  6583. || (sscanf(datetime,
  6584. "%d %3s %d %d:%d:%d",
  6585. &day,
  6586. month_str,
  6587. &year,
  6588. &hour,
  6589. &minute,
  6590. &second)
  6591. == 6)
  6592. || (sscanf(datetime,
  6593. "%*3s, %d %3s %d %d:%d:%d",
  6594. &day,
  6595. month_str,
  6596. &year,
  6597. &hour,
  6598. &minute,
  6599. &second)
  6600. == 6)
  6601. || (sscanf(datetime,
  6602. "%d-%3s-%d %d:%d:%d",
  6603. &day,
  6604. month_str,
  6605. &year,
  6606. &hour,
  6607. &minute,
  6608. &second)
  6609. == 6)) {
  6610. month = get_month_index(month_str);
  6611. if ((month >= 0) && (year >= 1970)) {
  6612. memset(&tm, 0, sizeof(tm));
  6613. tm.tm_year = year - 1900;
  6614. tm.tm_mon = month;
  6615. tm.tm_mday = day;
  6616. tm.tm_hour = hour;
  6617. tm.tm_min = minute;
  6618. tm.tm_sec = second;
  6619. result = timegm(&tm);
  6620. }
  6621. }
  6622. return result;
  6623. }
  6624. #endif /* !NO_CACHING */
  6625. /* Protect against directory disclosure attack by removing '..',
  6626. * excessive '/' and '\' characters */
  6627. static void
  6628. remove_double_dots_and_double_slashes(char *s)
  6629. {
  6630. char *p = s;
  6631. while ((s[0] == '.') && (s[1] == '.')) {
  6632. s++;
  6633. }
  6634. while (*s != '\0') {
  6635. *p++ = *s++;
  6636. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6637. /* Skip all following slashes, backslashes and double-dots */
  6638. while (s[0] != '\0') {
  6639. if ((s[0] == '/') || (s[0] == '\\')) {
  6640. s++;
  6641. } else if ((s[0] == '.') && (s[1] == '.')) {
  6642. s += 2;
  6643. } else {
  6644. break;
  6645. }
  6646. }
  6647. }
  6648. }
  6649. *p = '\0';
  6650. }
  6651. static const struct {
  6652. const char *extension;
  6653. size_t ext_len;
  6654. const char *mime_type;
  6655. } builtin_mime_types[] = {
  6656. /* IANA registered MIME types
  6657. * (http://www.iana.org/assignments/media-types)
  6658. * application types */
  6659. {".doc", 4, "application/msword"},
  6660. {".eps", 4, "application/postscript"},
  6661. {".exe", 4, "application/octet-stream"},
  6662. {".js", 3, "application/javascript"},
  6663. {".json", 5, "application/json"},
  6664. {".pdf", 4, "application/pdf"},
  6665. {".ps", 3, "application/postscript"},
  6666. {".rtf", 4, "application/rtf"},
  6667. {".xhtml", 6, "application/xhtml+xml"},
  6668. {".xsl", 4, "application/xml"},
  6669. {".xslt", 5, "application/xml"},
  6670. /* fonts */
  6671. {".ttf", 4, "application/font-sfnt"},
  6672. {".cff", 4, "application/font-sfnt"},
  6673. {".otf", 4, "application/font-sfnt"},
  6674. {".aat", 4, "application/font-sfnt"},
  6675. {".sil", 4, "application/font-sfnt"},
  6676. {".pfr", 4, "application/font-tdpfr"},
  6677. {".woff", 5, "application/font-woff"},
  6678. /* audio */
  6679. {".mp3", 4, "audio/mpeg"},
  6680. {".oga", 4, "audio/ogg"},
  6681. {".ogg", 4, "audio/ogg"},
  6682. /* image */
  6683. {".gif", 4, "image/gif"},
  6684. {".ief", 4, "image/ief"},
  6685. {".jpeg", 5, "image/jpeg"},
  6686. {".jpg", 4, "image/jpeg"},
  6687. {".jpm", 4, "image/jpm"},
  6688. {".jpx", 4, "image/jpx"},
  6689. {".png", 4, "image/png"},
  6690. {".svg", 4, "image/svg+xml"},
  6691. {".tif", 4, "image/tiff"},
  6692. {".tiff", 5, "image/tiff"},
  6693. /* model */
  6694. {".wrl", 4, "model/vrml"},
  6695. /* text */
  6696. {".css", 4, "text/css"},
  6697. {".csv", 4, "text/csv"},
  6698. {".htm", 4, "text/html"},
  6699. {".html", 5, "text/html"},
  6700. {".sgm", 4, "text/sgml"},
  6701. {".shtm", 5, "text/html"},
  6702. {".shtml", 6, "text/html"},
  6703. {".txt", 4, "text/plain"},
  6704. {".xml", 4, "text/xml"},
  6705. /* video */
  6706. {".mov", 4, "video/quicktime"},
  6707. {".mp4", 4, "video/mp4"},
  6708. {".mpeg", 5, "video/mpeg"},
  6709. {".mpg", 4, "video/mpeg"},
  6710. {".ogv", 4, "video/ogg"},
  6711. {".qt", 3, "video/quicktime"},
  6712. /* not registered types
  6713. * (http://reference.sitepoint.com/html/mime-types-full,
  6714. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6715. {".arj", 4, "application/x-arj-compressed"},
  6716. {".gz", 3, "application/x-gunzip"},
  6717. {".rar", 4, "application/x-arj-compressed"},
  6718. {".swf", 4, "application/x-shockwave-flash"},
  6719. {".tar", 4, "application/x-tar"},
  6720. {".tgz", 4, "application/x-tar-gz"},
  6721. {".torrent", 8, "application/x-bittorrent"},
  6722. {".ppt", 4, "application/x-mspowerpoint"},
  6723. {".xls", 4, "application/x-msexcel"},
  6724. {".zip", 4, "application/x-zip-compressed"},
  6725. {".aac",
  6726. 4,
  6727. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6728. {".aif", 4, "audio/x-aif"},
  6729. {".m3u", 4, "audio/x-mpegurl"},
  6730. {".mid", 4, "audio/x-midi"},
  6731. {".ra", 3, "audio/x-pn-realaudio"},
  6732. {".ram", 4, "audio/x-pn-realaudio"},
  6733. {".wav", 4, "audio/x-wav"},
  6734. {".bmp", 4, "image/bmp"},
  6735. {".ico", 4, "image/x-icon"},
  6736. {".pct", 4, "image/x-pct"},
  6737. {".pict", 5, "image/pict"},
  6738. {".rgb", 4, "image/x-rgb"},
  6739. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6740. {".asf", 4, "video/x-ms-asf"},
  6741. {".avi", 4, "video/x-msvideo"},
  6742. {".m4v", 4, "video/x-m4v"},
  6743. {NULL, 0, NULL}};
  6744. const char *
  6745. mg_get_builtin_mime_type(const char *path)
  6746. {
  6747. const char *ext;
  6748. size_t i, path_len;
  6749. path_len = strlen(path);
  6750. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6751. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6752. if ((path_len > builtin_mime_types[i].ext_len)
  6753. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6754. return builtin_mime_types[i].mime_type;
  6755. }
  6756. }
  6757. return "text/plain";
  6758. }
  6759. /* Look at the "path" extension and figure what mime type it has.
  6760. * Store mime type in the vector. */
  6761. static void
  6762. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6763. {
  6764. struct vec ext_vec, mime_vec;
  6765. const char *list, *ext;
  6766. size_t path_len;
  6767. path_len = strlen(path);
  6768. if ((conn == NULL) || (vec == NULL)) {
  6769. if (vec != NULL) {
  6770. memset(vec, '\0', sizeof(struct vec));
  6771. }
  6772. return;
  6773. }
  6774. /* Scan user-defined mime types first, in case user wants to
  6775. * override default mime types. */
  6776. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6777. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6778. /* ext now points to the path suffix */
  6779. ext = path + path_len - ext_vec.len;
  6780. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6781. *vec = mime_vec;
  6782. return;
  6783. }
  6784. }
  6785. vec->ptr = mg_get_builtin_mime_type(path);
  6786. vec->len = strlen(vec->ptr);
  6787. }
  6788. /* Stringify binary data. Output buffer must be twice as big as input,
  6789. * because each byte takes 2 bytes in string representation */
  6790. static void
  6791. bin2str(char *to, const unsigned char *p, size_t len)
  6792. {
  6793. static const char *hex = "0123456789abcdef";
  6794. for (; len--; p++) {
  6795. *to++ = hex[p[0] >> 4];
  6796. *to++ = hex[p[0] & 0x0f];
  6797. }
  6798. *to = '\0';
  6799. }
  6800. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6801. */
  6802. char *
  6803. mg_md5(char buf[33], ...)
  6804. {
  6805. md5_byte_t hash[16];
  6806. const char *p;
  6807. va_list ap;
  6808. md5_state_t ctx;
  6809. md5_init(&ctx);
  6810. va_start(ap, buf);
  6811. while ((p = va_arg(ap, const char *)) != NULL) {
  6812. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6813. }
  6814. va_end(ap);
  6815. md5_finish(&ctx, hash);
  6816. bin2str(buf, hash, sizeof(hash));
  6817. return buf;
  6818. }
  6819. /* Check the user's password, return 1 if OK */
  6820. static int
  6821. check_password(const char *method,
  6822. const char *ha1,
  6823. const char *uri,
  6824. const char *nonce,
  6825. const char *nc,
  6826. const char *cnonce,
  6827. const char *qop,
  6828. const char *response)
  6829. {
  6830. char ha2[32 + 1], expected_response[32 + 1];
  6831. /* Some of the parameters may be NULL */
  6832. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6833. || (qop == NULL) || (response == NULL)) {
  6834. return 0;
  6835. }
  6836. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6837. if (strlen(response) != 32) {
  6838. return 0;
  6839. }
  6840. mg_md5(ha2, method, ":", uri, NULL);
  6841. mg_md5(expected_response,
  6842. ha1,
  6843. ":",
  6844. nonce,
  6845. ":",
  6846. nc,
  6847. ":",
  6848. cnonce,
  6849. ":",
  6850. qop,
  6851. ":",
  6852. ha2,
  6853. NULL);
  6854. return mg_strcasecmp(response, expected_response) == 0;
  6855. }
  6856. /* Use the global passwords file, if specified by auth_gpass option,
  6857. * or search for .htpasswd in the requested directory. */
  6858. static void
  6859. open_auth_file(struct mg_connection *conn,
  6860. const char *path,
  6861. struct mg_file *filep)
  6862. {
  6863. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6864. char name[PATH_MAX];
  6865. const char *p, *e,
  6866. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6867. int truncated;
  6868. if (gpass != NULL) {
  6869. /* Use global passwords file */
  6870. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6871. #if defined(DEBUG)
  6872. /* Use mg_cry_internal here, since gpass has been configured. */
  6873. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6874. #endif
  6875. }
  6876. /* Important: using local struct mg_file to test path for
  6877. * is_directory flag. If filep is used, mg_stat() makes it
  6878. * appear as if auth file was opened.
  6879. * TODO(mid): Check if this is still required after rewriting
  6880. * mg_stat */
  6881. } else if (mg_stat(conn, path, &filep->stat)
  6882. && filep->stat.is_directory) {
  6883. mg_snprintf(conn,
  6884. &truncated,
  6885. name,
  6886. sizeof(name),
  6887. "%s/%s",
  6888. path,
  6889. PASSWORDS_FILE_NAME);
  6890. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6891. #if defined(DEBUG)
  6892. /* Don't use mg_cry_internal here, but only a trace, since this
  6893. * is
  6894. * a typical case. It will occur for every directory
  6895. * without a password file. */
  6896. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6897. #endif
  6898. }
  6899. } else {
  6900. /* Try to find .htpasswd in requested directory. */
  6901. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6902. if (e[0] == '/') {
  6903. break;
  6904. }
  6905. }
  6906. mg_snprintf(conn,
  6907. &truncated,
  6908. name,
  6909. sizeof(name),
  6910. "%.*s/%s",
  6911. (int)(e - p),
  6912. p,
  6913. PASSWORDS_FILE_NAME);
  6914. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6915. #if defined(DEBUG)
  6916. /* Don't use mg_cry_internal here, but only a trace, since this
  6917. * is
  6918. * a typical case. It will occur for every directory
  6919. * without a password file. */
  6920. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6921. #endif
  6922. }
  6923. }
  6924. }
  6925. }
  6926. /* Parsed Authorization header */
  6927. struct ah {
  6928. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6929. };
  6930. /* Return 1 on success. Always initializes the ah structure. */
  6931. static int
  6932. parse_auth_header(struct mg_connection *conn,
  6933. char *buf,
  6934. size_t buf_size,
  6935. struct ah *ah)
  6936. {
  6937. char *name, *value, *s;
  6938. const char *auth_header;
  6939. uint64_t nonce;
  6940. if (!ah || !conn) {
  6941. return 0;
  6942. }
  6943. (void)memset(ah, 0, sizeof(*ah));
  6944. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6945. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6946. return 0;
  6947. }
  6948. /* Make modifiable copy of the auth header */
  6949. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6950. s = buf;
  6951. /* Parse authorization header */
  6952. for (;;) {
  6953. /* Gobble initial spaces */
  6954. while (isspace((unsigned char)*s)) {
  6955. s++;
  6956. }
  6957. name = skip_quoted(&s, "=", " ", 0);
  6958. /* Value is either quote-delimited, or ends at first comma or space.
  6959. */
  6960. if (s[0] == '\"') {
  6961. s++;
  6962. value = skip_quoted(&s, "\"", " ", '\\');
  6963. if (s[0] == ',') {
  6964. s++;
  6965. }
  6966. } else {
  6967. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6968. * spaces */
  6969. }
  6970. if (*name == '\0') {
  6971. break;
  6972. }
  6973. if (!strcmp(name, "username")) {
  6974. ah->user = value;
  6975. } else if (!strcmp(name, "cnonce")) {
  6976. ah->cnonce = value;
  6977. } else if (!strcmp(name, "response")) {
  6978. ah->response = value;
  6979. } else if (!strcmp(name, "uri")) {
  6980. ah->uri = value;
  6981. } else if (!strcmp(name, "qop")) {
  6982. ah->qop = value;
  6983. } else if (!strcmp(name, "nc")) {
  6984. ah->nc = value;
  6985. } else if (!strcmp(name, "nonce")) {
  6986. ah->nonce = value;
  6987. }
  6988. }
  6989. #if !defined(NO_NONCE_CHECK)
  6990. /* Read the nonce from the response. */
  6991. if (ah->nonce == NULL) {
  6992. return 0;
  6993. }
  6994. s = NULL;
  6995. nonce = strtoull(ah->nonce, &s, 10);
  6996. if ((s == NULL) || (*s != 0)) {
  6997. return 0;
  6998. }
  6999. /* Convert the nonce from the client to a number. */
  7000. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7001. /* The converted number corresponds to the time the nounce has been
  7002. * created. This should not be earlier than the server start. */
  7003. /* Server side nonce check is valuable in all situations but one:
  7004. * if the server restarts frequently, but the client should not see
  7005. * that, so the server should accept nonces from previous starts. */
  7006. /* However, the reasonable default is to not accept a nonce from a
  7007. * previous start, so if anyone changed the access rights between
  7008. * two restarts, a new login is required. */
  7009. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7010. /* nonce is from a previous start of the server and no longer valid
  7011. * (replay attack?) */
  7012. return 0;
  7013. }
  7014. /* Check if the nonce is too high, so it has not (yet) been used by the
  7015. * server. */
  7016. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7017. + conn->dom_ctx->nonce_count)) {
  7018. return 0;
  7019. }
  7020. #else
  7021. (void)nonce;
  7022. #endif
  7023. /* CGI needs it as REMOTE_USER */
  7024. if (ah->user != NULL) {
  7025. conn->request_info.remote_user =
  7026. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7027. } else {
  7028. return 0;
  7029. }
  7030. return 1;
  7031. }
  7032. static const char *
  7033. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7034. {
  7035. #if defined(MG_USE_OPEN_FILE)
  7036. const char *eof;
  7037. size_t len;
  7038. const char *memend;
  7039. #else
  7040. (void)p; /* parameter is unused */
  7041. #endif
  7042. if (!filep) {
  7043. return NULL;
  7044. }
  7045. #if defined(MG_USE_OPEN_FILE)
  7046. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7047. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7048. /* Search for \n from p till the end of stream */
  7049. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7050. if (eof != NULL) {
  7051. eof += 1; /* Include \n */
  7052. } else {
  7053. eof = memend; /* Copy remaining data */
  7054. }
  7055. len =
  7056. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7057. memcpy(buf, *p, len);
  7058. buf[len] = '\0';
  7059. *p += len;
  7060. return len ? eof : NULL;
  7061. } else /* filep->access.fp block below */
  7062. #endif
  7063. if (filep->access.fp != NULL) {
  7064. return fgets(buf, (int)size, filep->access.fp);
  7065. } else {
  7066. return NULL;
  7067. }
  7068. }
  7069. /* Define the initial recursion depth for procesesing htpasswd files that
  7070. * include other htpasswd
  7071. * (or even the same) files. It is not difficult to provide a file or files
  7072. * s.t. they force civetweb
  7073. * to infinitely recurse and then crash.
  7074. */
  7075. #define INITIAL_DEPTH 9
  7076. #if INITIAL_DEPTH <= 0
  7077. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7078. #endif
  7079. struct read_auth_file_struct {
  7080. struct mg_connection *conn;
  7081. struct ah ah;
  7082. const char *domain;
  7083. char buf[256 + 256 + 40];
  7084. const char *f_user;
  7085. const char *f_domain;
  7086. const char *f_ha1;
  7087. };
  7088. static int
  7089. read_auth_file(struct mg_file *filep,
  7090. struct read_auth_file_struct *workdata,
  7091. int depth)
  7092. {
  7093. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7094. int is_authorized = 0;
  7095. struct mg_file fp;
  7096. size_t l;
  7097. if (!filep || !workdata || (0 == depth)) {
  7098. return 0;
  7099. }
  7100. /* Loop over passwords file */
  7101. #if defined(MG_USE_OPEN_FILE)
  7102. p = (char *)filep->access.membuf;
  7103. #endif
  7104. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7105. l = strlen(workdata->buf);
  7106. while (l > 0) {
  7107. if (isspace((unsigned char)workdata->buf[l - 1])
  7108. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7109. l--;
  7110. workdata->buf[l] = 0;
  7111. } else
  7112. break;
  7113. }
  7114. if (l < 1) {
  7115. continue;
  7116. }
  7117. workdata->f_user = workdata->buf;
  7118. if (workdata->f_user[0] == ':') {
  7119. /* user names may not contain a ':' and may not be empty,
  7120. * so lines starting with ':' may be used for a special purpose
  7121. */
  7122. if (workdata->f_user[1] == '#') {
  7123. /* :# is a comment */
  7124. continue;
  7125. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7126. if (mg_fopen(workdata->conn,
  7127. workdata->f_user + 9,
  7128. MG_FOPEN_MODE_READ,
  7129. &fp)) {
  7130. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7131. (void)mg_fclose(
  7132. &fp.access); /* ignore error on read only file */
  7133. /* No need to continue processing files once we have a
  7134. * match, since nothing will reset it back
  7135. * to 0.
  7136. */
  7137. if (is_authorized) {
  7138. return is_authorized;
  7139. }
  7140. } else {
  7141. mg_cry_internal(workdata->conn,
  7142. "%s: cannot open authorization file: %s",
  7143. __func__,
  7144. workdata->buf);
  7145. }
  7146. continue;
  7147. }
  7148. /* everything is invalid for the moment (might change in the
  7149. * future) */
  7150. mg_cry_internal(workdata->conn,
  7151. "%s: syntax error in authorization file: %s",
  7152. __func__,
  7153. workdata->buf);
  7154. continue;
  7155. }
  7156. workdata->f_domain = strchr(workdata->f_user, ':');
  7157. if (workdata->f_domain == NULL) {
  7158. mg_cry_internal(workdata->conn,
  7159. "%s: syntax error in authorization file: %s",
  7160. __func__,
  7161. workdata->buf);
  7162. continue;
  7163. }
  7164. *(char *)(workdata->f_domain) = 0;
  7165. (workdata->f_domain)++;
  7166. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7167. if (workdata->f_ha1 == NULL) {
  7168. mg_cry_internal(workdata->conn,
  7169. "%s: syntax error in authorization file: %s",
  7170. __func__,
  7171. workdata->buf);
  7172. continue;
  7173. }
  7174. *(char *)(workdata->f_ha1) = 0;
  7175. (workdata->f_ha1)++;
  7176. if (!strcmp(workdata->ah.user, workdata->f_user)
  7177. && !strcmp(workdata->domain, workdata->f_domain)) {
  7178. return check_password(workdata->conn->request_info.request_method,
  7179. workdata->f_ha1,
  7180. workdata->ah.uri,
  7181. workdata->ah.nonce,
  7182. workdata->ah.nc,
  7183. workdata->ah.cnonce,
  7184. workdata->ah.qop,
  7185. workdata->ah.response);
  7186. }
  7187. }
  7188. return is_authorized;
  7189. }
  7190. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7191. static int
  7192. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7193. {
  7194. struct read_auth_file_struct workdata;
  7195. char buf[MG_BUF_LEN];
  7196. if (!conn || !conn->dom_ctx) {
  7197. return 0;
  7198. }
  7199. memset(&workdata, 0, sizeof(workdata));
  7200. workdata.conn = conn;
  7201. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7202. return 0;
  7203. }
  7204. if (realm) {
  7205. workdata.domain = realm;
  7206. } else {
  7207. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7208. }
  7209. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7210. }
  7211. /* Public function to check http digest authentication header */
  7212. int
  7213. mg_check_digest_access_authentication(struct mg_connection *conn,
  7214. const char *realm,
  7215. const char *filename)
  7216. {
  7217. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7218. int auth;
  7219. if (!conn || !filename) {
  7220. return -1;
  7221. }
  7222. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7223. return -2;
  7224. }
  7225. auth = authorize(conn, &file, realm);
  7226. mg_fclose(&file.access);
  7227. return auth;
  7228. }
  7229. /* Return 1 if request is authorised, 0 otherwise. */
  7230. static int
  7231. check_authorization(struct mg_connection *conn, const char *path)
  7232. {
  7233. char fname[PATH_MAX];
  7234. struct vec uri_vec, filename_vec;
  7235. const char *list;
  7236. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7237. int authorized = 1, truncated;
  7238. if (!conn || !conn->dom_ctx) {
  7239. return 0;
  7240. }
  7241. list = conn->dom_ctx->config[PROTECT_URI];
  7242. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7243. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7244. mg_snprintf(conn,
  7245. &truncated,
  7246. fname,
  7247. sizeof(fname),
  7248. "%.*s",
  7249. (int)filename_vec.len,
  7250. filename_vec.ptr);
  7251. if (truncated
  7252. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7253. mg_cry_internal(conn,
  7254. "%s: cannot open %s: %s",
  7255. __func__,
  7256. fname,
  7257. strerror(errno));
  7258. }
  7259. break;
  7260. }
  7261. }
  7262. if (!is_file_opened(&file.access)) {
  7263. open_auth_file(conn, path, &file);
  7264. }
  7265. if (is_file_opened(&file.access)) {
  7266. authorized = authorize(conn, &file, NULL);
  7267. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7268. }
  7269. return authorized;
  7270. }
  7271. /* Internal function. Assumes conn is valid */
  7272. static void
  7273. send_authorization_request(struct mg_connection *conn, const char *realm)
  7274. {
  7275. char date[64];
  7276. time_t curtime = time(NULL);
  7277. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7278. if (!realm) {
  7279. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7280. }
  7281. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7282. nonce += conn->dom_ctx->nonce_count;
  7283. ++conn->dom_ctx->nonce_count;
  7284. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7285. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7286. conn->status_code = 401;
  7287. conn->must_close = 1;
  7288. gmt_time_string(date, sizeof(date), &curtime);
  7289. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7290. send_no_cache_header(conn);
  7291. send_additional_header(conn);
  7292. mg_printf(conn,
  7293. "Date: %s\r\n"
  7294. "Connection: %s\r\n"
  7295. "Content-Length: 0\r\n"
  7296. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7297. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7298. date,
  7299. suggest_connection_header(conn),
  7300. realm,
  7301. nonce);
  7302. }
  7303. /* Interface function. Parameters are provided by the user, so do
  7304. * at least some basic checks.
  7305. */
  7306. int
  7307. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7308. const char *realm)
  7309. {
  7310. if (conn && conn->dom_ctx) {
  7311. send_authorization_request(conn, realm);
  7312. return 0;
  7313. }
  7314. return -1;
  7315. }
  7316. #if !defined(NO_FILES)
  7317. static int
  7318. is_authorized_for_put(struct mg_connection *conn)
  7319. {
  7320. if (conn) {
  7321. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7322. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7323. int ret = 0;
  7324. if (passfile != NULL
  7325. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7326. ret = authorize(conn, &file, NULL);
  7327. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7328. }
  7329. return ret;
  7330. }
  7331. return 0;
  7332. }
  7333. #endif
  7334. int
  7335. mg_modify_passwords_file(const char *fname,
  7336. const char *domain,
  7337. const char *user,
  7338. const char *pass)
  7339. {
  7340. int found, i;
  7341. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7342. FILE *fp, *fp2;
  7343. found = 0;
  7344. fp = fp2 = NULL;
  7345. /* Regard empty password as no password - remove user record. */
  7346. if ((pass != NULL) && (pass[0] == '\0')) {
  7347. pass = NULL;
  7348. }
  7349. /* Other arguments must not be empty */
  7350. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7351. return 0;
  7352. }
  7353. /* Using the given file format, user name and domain must not contain
  7354. * ':'
  7355. */
  7356. if (strchr(user, ':') != NULL) {
  7357. return 0;
  7358. }
  7359. if (strchr(domain, ':') != NULL) {
  7360. return 0;
  7361. }
  7362. /* Do not allow control characters like newline in user name and domain.
  7363. * Do not allow excessively long names either. */
  7364. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7365. if (iscntrl((unsigned char)user[i])) {
  7366. return 0;
  7367. }
  7368. }
  7369. if (user[i]) {
  7370. return 0;
  7371. }
  7372. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7373. if (iscntrl((unsigned char)domain[i])) {
  7374. return 0;
  7375. }
  7376. }
  7377. if (domain[i]) {
  7378. return 0;
  7379. }
  7380. /* The maximum length of the path to the password file is limited */
  7381. if ((strlen(fname) + 4) >= PATH_MAX) {
  7382. return 0;
  7383. }
  7384. /* Create a temporary file name. Length has been checked before. */
  7385. strcpy(tmp, fname);
  7386. strcat(tmp, ".tmp");
  7387. /* Create the file if does not exist */
  7388. /* Use of fopen here is OK, since fname is only ASCII */
  7389. if ((fp = fopen(fname, "a+")) != NULL) {
  7390. (void)fclose(fp);
  7391. }
  7392. /* Open the given file and temporary file */
  7393. if ((fp = fopen(fname, "r")) == NULL) {
  7394. return 0;
  7395. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7396. fclose(fp);
  7397. return 0;
  7398. }
  7399. /* Copy the stuff to temporary file */
  7400. while (fgets(line, sizeof(line), fp) != NULL) {
  7401. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7402. continue;
  7403. }
  7404. u[255] = 0;
  7405. d[255] = 0;
  7406. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7407. found++;
  7408. if (pass != NULL) {
  7409. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7410. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7411. }
  7412. } else {
  7413. fprintf(fp2, "%s", line);
  7414. }
  7415. }
  7416. /* If new user, just add it */
  7417. if (!found && (pass != NULL)) {
  7418. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7419. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7420. }
  7421. /* Close files */
  7422. fclose(fp);
  7423. fclose(fp2);
  7424. /* Put the temp file in place of real file */
  7425. IGNORE_UNUSED_RESULT(remove(fname));
  7426. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7427. return 1;
  7428. }
  7429. static int
  7430. is_valid_port(unsigned long port)
  7431. {
  7432. return (port <= 0xffff);
  7433. }
  7434. static int
  7435. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7436. {
  7437. struct addrinfo hints, *res, *ressave;
  7438. int func_ret = 0;
  7439. int gai_ret;
  7440. memset(&hints, 0, sizeof(struct addrinfo));
  7441. hints.ai_family = af;
  7442. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7443. if (gai_ret != 0) {
  7444. /* gai_strerror could be used to convert gai_ret to a string */
  7445. /* POSIX return values: see
  7446. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7447. */
  7448. /* Windows return values: see
  7449. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7450. */
  7451. return 0;
  7452. }
  7453. ressave = res;
  7454. while (res) {
  7455. if (dstlen >= (size_t)res->ai_addrlen) {
  7456. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7457. func_ret = 1;
  7458. }
  7459. res = res->ai_next;
  7460. }
  7461. freeaddrinfo(ressave);
  7462. return func_ret;
  7463. }
  7464. static int
  7465. connect_socket(struct mg_context *ctx /* may be NULL */,
  7466. const char *host,
  7467. int port,
  7468. int use_ssl,
  7469. char *ebuf,
  7470. size_t ebuf_len,
  7471. SOCKET *sock /* output: socket, must not be NULL */,
  7472. union usa *sa /* output: socket address, must not be NULL */
  7473. )
  7474. {
  7475. int ip_ver = 0;
  7476. int conn_ret = -1;
  7477. int sockerr = 0;
  7478. *sock = INVALID_SOCKET;
  7479. memset(sa, 0, sizeof(*sa));
  7480. if (ebuf_len > 0) {
  7481. *ebuf = 0;
  7482. }
  7483. if (host == NULL) {
  7484. mg_snprintf(NULL,
  7485. NULL, /* No truncation check for ebuf */
  7486. ebuf,
  7487. ebuf_len,
  7488. "%s",
  7489. "NULL host");
  7490. return 0;
  7491. }
  7492. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7493. mg_snprintf(NULL,
  7494. NULL, /* No truncation check for ebuf */
  7495. ebuf,
  7496. ebuf_len,
  7497. "%s",
  7498. "invalid port");
  7499. return 0;
  7500. }
  7501. #if !defined(NO_SSL)
  7502. #if !defined(NO_SSL_DL)
  7503. #if defined(OPENSSL_API_1_1)
  7504. if (use_ssl && (TLS_client_method == NULL)) {
  7505. mg_snprintf(NULL,
  7506. NULL, /* No truncation check for ebuf */
  7507. ebuf,
  7508. ebuf_len,
  7509. "%s",
  7510. "SSL is not initialized");
  7511. return 0;
  7512. }
  7513. #else
  7514. if (use_ssl && (SSLv23_client_method == NULL)) {
  7515. mg_snprintf(NULL,
  7516. NULL, /* No truncation check for ebuf */
  7517. ebuf,
  7518. ebuf_len,
  7519. "%s",
  7520. "SSL is not initialized");
  7521. return 0;
  7522. }
  7523. #endif /* OPENSSL_API_1_1 */
  7524. #else
  7525. (void)use_ssl;
  7526. #endif /* NO_SSL_DL */
  7527. #else
  7528. (void)use_ssl;
  7529. #endif /* !defined(NO_SSL) */
  7530. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7531. sa->sin.sin_family = AF_INET;
  7532. sa->sin.sin_port = htons((uint16_t)port);
  7533. ip_ver = 4;
  7534. #if defined(USE_IPV6)
  7535. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7536. sa->sin6.sin6_family = AF_INET6;
  7537. sa->sin6.sin6_port = htons((uint16_t)port);
  7538. ip_ver = 6;
  7539. } else if (host[0] == '[') {
  7540. /* While getaddrinfo on Windows will work with [::1],
  7541. * getaddrinfo on Linux only works with ::1 (without []). */
  7542. size_t l = strlen(host + 1);
  7543. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7544. if (h) {
  7545. h[l - 1] = 0;
  7546. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7547. sa->sin6.sin6_family = AF_INET6;
  7548. sa->sin6.sin6_port = htons((uint16_t)port);
  7549. ip_ver = 6;
  7550. }
  7551. mg_free(h);
  7552. }
  7553. #endif
  7554. }
  7555. if (ip_ver == 0) {
  7556. mg_snprintf(NULL,
  7557. NULL, /* No truncation check for ebuf */
  7558. ebuf,
  7559. ebuf_len,
  7560. "%s",
  7561. "host not found");
  7562. return 0;
  7563. }
  7564. if (ip_ver == 4) {
  7565. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7566. }
  7567. #if defined(USE_IPV6)
  7568. else if (ip_ver == 6) {
  7569. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7570. }
  7571. #endif
  7572. if (*sock == INVALID_SOCKET) {
  7573. mg_snprintf(NULL,
  7574. NULL, /* No truncation check for ebuf */
  7575. ebuf,
  7576. ebuf_len,
  7577. "socket(): %s",
  7578. strerror(ERRNO));
  7579. return 0;
  7580. }
  7581. if (0 != set_non_blocking_mode(*sock)) {
  7582. mg_snprintf(NULL,
  7583. NULL, /* No truncation check for ebuf */
  7584. ebuf,
  7585. ebuf_len,
  7586. "Cannot set socket to non-blocking: %s",
  7587. strerror(ERRNO));
  7588. closesocket(*sock);
  7589. *sock = INVALID_SOCKET;
  7590. return 0;
  7591. }
  7592. set_close_on_exec(*sock, fc(ctx));
  7593. if (ip_ver == 4) {
  7594. /* connected with IPv4 */
  7595. conn_ret = connect(*sock,
  7596. (struct sockaddr *)((void *)&sa->sin),
  7597. sizeof(sa->sin));
  7598. }
  7599. #if defined(USE_IPV6)
  7600. else if (ip_ver == 6) {
  7601. /* connected with IPv6 */
  7602. conn_ret = connect(*sock,
  7603. (struct sockaddr *)((void *)&sa->sin6),
  7604. sizeof(sa->sin6));
  7605. }
  7606. #endif
  7607. if (conn_ret != 0) {
  7608. sockerr = ERRNO;
  7609. }
  7610. #if defined(_WIN32)
  7611. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7612. #else
  7613. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7614. #endif
  7615. /* Data for getsockopt */
  7616. void *psockerr = &sockerr;
  7617. int ret;
  7618. #if defined(_WIN32)
  7619. int len = (int)sizeof(sockerr);
  7620. #else
  7621. socklen_t len = (socklen_t)sizeof(sockerr);
  7622. #endif
  7623. /* Data for poll */
  7624. struct mg_pollfd pfd[1];
  7625. int pollres;
  7626. int ms_wait = 10000; /* 10 second timeout */
  7627. int nonstop = 0;
  7628. /* For a non-blocking socket, the connect sequence is:
  7629. * 1) call connect (will not block)
  7630. * 2) wait until the socket is ready for writing (select or poll)
  7631. * 3) check connection state with getsockopt
  7632. */
  7633. pfd[0].fd = *sock;
  7634. pfd[0].events = POLLOUT;
  7635. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7636. if (pollres != 1) {
  7637. /* Not connected */
  7638. mg_snprintf(NULL,
  7639. NULL, /* No truncation check for ebuf */
  7640. ebuf,
  7641. ebuf_len,
  7642. "connect(%s:%d): timeout",
  7643. host,
  7644. port);
  7645. closesocket(*sock);
  7646. *sock = INVALID_SOCKET;
  7647. return 0;
  7648. }
  7649. #if defined(_WIN32)
  7650. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7651. #else
  7652. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7653. #endif
  7654. if ((ret == 0) && (sockerr == 0)) {
  7655. conn_ret = 0;
  7656. }
  7657. }
  7658. if (conn_ret != 0) {
  7659. /* Not connected */
  7660. mg_snprintf(NULL,
  7661. NULL, /* No truncation check for ebuf */
  7662. ebuf,
  7663. ebuf_len,
  7664. "connect(%s:%d): error %s",
  7665. host,
  7666. port,
  7667. strerror(sockerr));
  7668. closesocket(*sock);
  7669. *sock = INVALID_SOCKET;
  7670. return 0;
  7671. }
  7672. return 1;
  7673. }
  7674. int
  7675. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7676. {
  7677. static const char *dont_escape = "._-$,;~()";
  7678. static const char *hex = "0123456789abcdef";
  7679. char *pos = dst;
  7680. const char *end = dst + dst_len - 1;
  7681. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7682. if (isalnum((unsigned char)*src)
  7683. || (strchr(dont_escape, *src) != NULL)) {
  7684. *pos = *src;
  7685. } else if (pos + 2 < end) {
  7686. pos[0] = '%';
  7687. pos[1] = hex[(unsigned char)*src >> 4];
  7688. pos[2] = hex[(unsigned char)*src & 0xf];
  7689. pos += 2;
  7690. } else {
  7691. break;
  7692. }
  7693. }
  7694. *pos = '\0';
  7695. return (*src == '\0') ? (int)(pos - dst) : -1;
  7696. }
  7697. /* Return 0 on success, non-zero if an error occurs. */
  7698. static int
  7699. print_dir_entry(struct de *de)
  7700. {
  7701. size_t namesize, escsize, i;
  7702. char *href, *esc, *p;
  7703. char size[64], mod[64];
  7704. #if defined(REENTRANT_TIME)
  7705. struct tm _tm;
  7706. struct tm *tm = &_tm;
  7707. #else
  7708. struct tm *tm;
  7709. #endif
  7710. /* Estimate worst case size for encoding and escaping */
  7711. namesize = strlen(de->file_name) + 1;
  7712. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7713. href = (char *)mg_malloc(namesize * 3 + escsize);
  7714. if (href == NULL) {
  7715. return -1;
  7716. }
  7717. mg_url_encode(de->file_name, href, namesize * 3);
  7718. esc = NULL;
  7719. if (escsize > 0) {
  7720. /* HTML escaping needed */
  7721. esc = href + namesize * 3;
  7722. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7723. mg_strlcpy(p, de->file_name + i, 2);
  7724. if (*p == '&') {
  7725. strcpy(p, "&amp;");
  7726. } else if (*p == '<') {
  7727. strcpy(p, "&lt;");
  7728. } else if (*p == '>') {
  7729. strcpy(p, "&gt;");
  7730. }
  7731. }
  7732. }
  7733. if (de->file.is_directory) {
  7734. mg_snprintf(de->conn,
  7735. NULL, /* Buffer is big enough */
  7736. size,
  7737. sizeof(size),
  7738. "%s",
  7739. "[DIRECTORY]");
  7740. } else {
  7741. /* We use (signed) cast below because MSVC 6 compiler cannot
  7742. * convert unsigned __int64 to double. Sigh. */
  7743. if (de->file.size < 1024) {
  7744. mg_snprintf(de->conn,
  7745. NULL, /* Buffer is big enough */
  7746. size,
  7747. sizeof(size),
  7748. "%d",
  7749. (int)de->file.size);
  7750. } else if (de->file.size < 0x100000) {
  7751. mg_snprintf(de->conn,
  7752. NULL, /* Buffer is big enough */
  7753. size,
  7754. sizeof(size),
  7755. "%.1fk",
  7756. (double)de->file.size / 1024.0);
  7757. } else if (de->file.size < 0x40000000) {
  7758. mg_snprintf(de->conn,
  7759. NULL, /* Buffer is big enough */
  7760. size,
  7761. sizeof(size),
  7762. "%.1fM",
  7763. (double)de->file.size / 1048576);
  7764. } else {
  7765. mg_snprintf(de->conn,
  7766. NULL, /* Buffer is big enough */
  7767. size,
  7768. sizeof(size),
  7769. "%.1fG",
  7770. (double)de->file.size / 1073741824);
  7771. }
  7772. }
  7773. /* Note: mg_snprintf will not cause a buffer overflow above.
  7774. * So, string truncation checks are not required here. */
  7775. #if defined(REENTRANT_TIME)
  7776. localtime_r(&de->file.last_modified, tm);
  7777. #else
  7778. tm = localtime(&de->file.last_modified);
  7779. #endif
  7780. if (tm != NULL) {
  7781. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7782. } else {
  7783. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7784. mod[sizeof(mod) - 1] = '\0';
  7785. }
  7786. mg_printf(de->conn,
  7787. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7788. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7789. href,
  7790. de->file.is_directory ? "/" : "",
  7791. esc ? esc : de->file_name,
  7792. de->file.is_directory ? "/" : "",
  7793. mod,
  7794. size);
  7795. mg_free(href);
  7796. return 0;
  7797. }
  7798. /* This function is called from send_directory() and used for
  7799. * sorting directory entries by size, or name, or modification time.
  7800. * On windows, __cdecl specification is needed in case if project is built
  7801. * with __stdcall convention. qsort always requires __cdels callback. */
  7802. static int WINCDECL
  7803. compare_dir_entries(const void *p1, const void *p2)
  7804. {
  7805. if (p1 && p2) {
  7806. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7807. const char *query_string = a->conn->request_info.query_string;
  7808. int cmp_result = 0;
  7809. if ((query_string == NULL) || (query_string[0] == '\0')) {
  7810. query_string = "n";
  7811. }
  7812. if (a->file.is_directory && !b->file.is_directory) {
  7813. return -1; /* Always put directories on top */
  7814. } else if (!a->file.is_directory && b->file.is_directory) {
  7815. return 1; /* Always put directories on top */
  7816. } else if (*query_string == 'n') {
  7817. cmp_result = strcmp(a->file_name, b->file_name);
  7818. } else if (*query_string == 's') {
  7819. cmp_result = (a->file.size == b->file.size)
  7820. ? 0
  7821. : ((a->file.size > b->file.size) ? 1 : -1);
  7822. } else if (*query_string == 'd') {
  7823. cmp_result =
  7824. (a->file.last_modified == b->file.last_modified)
  7825. ? 0
  7826. : ((a->file.last_modified > b->file.last_modified) ? 1
  7827. : -1);
  7828. }
  7829. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7830. }
  7831. return 0;
  7832. }
  7833. static int
  7834. must_hide_file(struct mg_connection *conn, const char *path)
  7835. {
  7836. if (conn && conn->dom_ctx) {
  7837. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7838. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7839. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7840. || ((pattern != NULL)
  7841. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7842. }
  7843. return 0;
  7844. }
  7845. static int
  7846. scan_directory(struct mg_connection *conn,
  7847. const char *dir,
  7848. void *data,
  7849. int (*cb)(struct de *, void *))
  7850. {
  7851. char path[PATH_MAX];
  7852. struct dirent *dp;
  7853. DIR *dirp;
  7854. struct de de;
  7855. int truncated;
  7856. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7857. return 0;
  7858. } else {
  7859. de.conn = conn;
  7860. while ((dp = mg_readdir(dirp)) != NULL) {
  7861. /* Do not show current dir and hidden files */
  7862. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7863. || must_hide_file(conn, dp->d_name)) {
  7864. continue;
  7865. }
  7866. mg_snprintf(
  7867. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7868. /* If we don't memset stat structure to zero, mtime will have
  7869. * garbage and strftime() will segfault later on in
  7870. * print_dir_entry(). memset is required only if mg_stat()
  7871. * fails. For more details, see
  7872. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7873. memset(&de.file, 0, sizeof(de.file));
  7874. if (truncated) {
  7875. /* If the path is not complete, skip processing. */
  7876. continue;
  7877. }
  7878. if (!mg_stat(conn, path, &de.file)) {
  7879. mg_cry_internal(conn,
  7880. "%s: mg_stat(%s) failed: %s",
  7881. __func__,
  7882. path,
  7883. strerror(ERRNO));
  7884. }
  7885. de.file_name = dp->d_name;
  7886. cb(&de, data);
  7887. }
  7888. (void)mg_closedir(dirp);
  7889. }
  7890. return 1;
  7891. }
  7892. #if !defined(NO_FILES)
  7893. static int
  7894. remove_directory(struct mg_connection *conn, const char *dir)
  7895. {
  7896. char path[PATH_MAX];
  7897. struct dirent *dp;
  7898. DIR *dirp;
  7899. struct de de;
  7900. int truncated;
  7901. int ok = 1;
  7902. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7903. return 0;
  7904. } else {
  7905. de.conn = conn;
  7906. while ((dp = mg_readdir(dirp)) != NULL) {
  7907. /* Do not show current dir (but show hidden files as they will
  7908. * also be removed) */
  7909. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7910. continue;
  7911. }
  7912. mg_snprintf(
  7913. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7914. /* If we don't memset stat structure to zero, mtime will have
  7915. * garbage and strftime() will segfault later on in
  7916. * print_dir_entry(). memset is required only if mg_stat()
  7917. * fails. For more details, see
  7918. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7919. memset(&de.file, 0, sizeof(de.file));
  7920. if (truncated) {
  7921. /* Do not delete anything shorter */
  7922. ok = 0;
  7923. continue;
  7924. }
  7925. if (!mg_stat(conn, path, &de.file)) {
  7926. mg_cry_internal(conn,
  7927. "%s: mg_stat(%s) failed: %s",
  7928. __func__,
  7929. path,
  7930. strerror(ERRNO));
  7931. ok = 0;
  7932. }
  7933. if (de.file.is_directory) {
  7934. if (remove_directory(conn, path) == 0) {
  7935. ok = 0;
  7936. }
  7937. } else {
  7938. /* This will fail file is the file is in memory */
  7939. if (mg_remove(conn, path) == 0) {
  7940. ok = 0;
  7941. }
  7942. }
  7943. }
  7944. (void)mg_closedir(dirp);
  7945. IGNORE_UNUSED_RESULT(rmdir(dir));
  7946. }
  7947. return ok;
  7948. }
  7949. #endif
  7950. struct dir_scan_data {
  7951. struct de *entries;
  7952. unsigned int num_entries;
  7953. unsigned int arr_size;
  7954. };
  7955. /* Behaves like realloc(), but frees original pointer on failure */
  7956. static void *
  7957. realloc2(void *ptr, size_t size)
  7958. {
  7959. void *new_ptr = mg_realloc(ptr, size);
  7960. if (new_ptr == NULL) {
  7961. mg_free(ptr);
  7962. }
  7963. return new_ptr;
  7964. }
  7965. static int
  7966. dir_scan_callback(struct de *de, void *data)
  7967. {
  7968. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7969. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7970. dsd->arr_size *= 2;
  7971. dsd->entries =
  7972. (struct de *)realloc2(dsd->entries,
  7973. dsd->arr_size * sizeof(dsd->entries[0]));
  7974. }
  7975. if (dsd->entries == NULL) {
  7976. /* TODO(lsm, low): propagate an error to the caller */
  7977. dsd->num_entries = 0;
  7978. } else {
  7979. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7980. dsd->entries[dsd->num_entries].file = de->file;
  7981. dsd->entries[dsd->num_entries].conn = de->conn;
  7982. dsd->num_entries++;
  7983. }
  7984. return 0;
  7985. }
  7986. static void
  7987. handle_directory_request(struct mg_connection *conn, const char *dir)
  7988. {
  7989. unsigned int i;
  7990. int sort_direction;
  7991. struct dir_scan_data data = {NULL, 0, 128};
  7992. char date[64], *esc, *p;
  7993. const char *title;
  7994. time_t curtime = time(NULL);
  7995. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7996. mg_send_http_error(conn,
  7997. 500,
  7998. "Error: Cannot open directory\nopendir(%s): %s",
  7999. dir,
  8000. strerror(ERRNO));
  8001. return;
  8002. }
  8003. gmt_time_string(date, sizeof(date), &curtime);
  8004. if (!conn) {
  8005. return;
  8006. }
  8007. esc = NULL;
  8008. title = conn->request_info.local_uri;
  8009. if (title[strcspn(title, "&<>")]) {
  8010. /* HTML escaping needed */
  8011. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8012. if (esc) {
  8013. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8014. mg_strlcpy(p, title + i, 2);
  8015. if (*p == '&') {
  8016. strcpy(p, "&amp;");
  8017. } else if (*p == '<') {
  8018. strcpy(p, "&lt;");
  8019. } else if (*p == '>') {
  8020. strcpy(p, "&gt;");
  8021. }
  8022. }
  8023. } else {
  8024. title = "";
  8025. }
  8026. }
  8027. sort_direction = ((conn->request_info.query_string != NULL)
  8028. && (conn->request_info.query_string[0] != '\0')
  8029. && (conn->request_info.query_string[1] == 'd'))
  8030. ? 'a'
  8031. : 'd';
  8032. conn->must_close = 1;
  8033. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8034. send_static_cache_header(conn);
  8035. send_additional_header(conn);
  8036. mg_printf(conn,
  8037. "Date: %s\r\n"
  8038. "Connection: close\r\n"
  8039. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8040. date);
  8041. mg_printf(conn,
  8042. "<html><head><title>Index of %s</title>"
  8043. "<style>th {text-align: left;}</style></head>"
  8044. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8045. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8046. "<th><a href=\"?d%c\">Modified</a></th>"
  8047. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8048. "<tr><td colspan=\"3\"><hr></td></tr>",
  8049. esc ? esc : title,
  8050. esc ? esc : title,
  8051. sort_direction,
  8052. sort_direction,
  8053. sort_direction);
  8054. mg_free(esc);
  8055. /* Print first entry - link to a parent directory */
  8056. mg_printf(conn,
  8057. "<tr><td><a href=\"%s\">%s</a></td>"
  8058. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8059. "..",
  8060. "Parent directory",
  8061. "-",
  8062. "-");
  8063. /* Sort and print directory entries */
  8064. if (data.entries != NULL) {
  8065. qsort(data.entries,
  8066. (size_t)data.num_entries,
  8067. sizeof(data.entries[0]),
  8068. compare_dir_entries);
  8069. for (i = 0; i < data.num_entries; i++) {
  8070. print_dir_entry(&data.entries[i]);
  8071. mg_free(data.entries[i].file_name);
  8072. }
  8073. mg_free(data.entries);
  8074. }
  8075. mg_printf(conn, "%s", "</table></pre></body></html>");
  8076. conn->status_code = 200;
  8077. }
  8078. /* Send len bytes from the opened file to the client. */
  8079. static void
  8080. send_file_data(struct mg_connection *conn,
  8081. struct mg_file *filep,
  8082. int64_t offset,
  8083. int64_t len)
  8084. {
  8085. char buf[MG_BUF_LEN];
  8086. int to_read, num_read, num_written;
  8087. int64_t size;
  8088. if (!filep || !conn) {
  8089. return;
  8090. }
  8091. /* Sanity check the offset */
  8092. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8093. : (int64_t)(filep->stat.size);
  8094. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8095. #if defined(MG_USE_OPEN_FILE)
  8096. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8097. /* file stored in memory */
  8098. if (len > size - offset) {
  8099. len = size - offset;
  8100. }
  8101. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8102. } else /* else block below */
  8103. #endif
  8104. if (len > 0 && filep->access.fp != NULL) {
  8105. /* file stored on disk */
  8106. #if defined(__linux__)
  8107. /* sendfile is only available for Linux */
  8108. if ((conn->ssl == 0) && (conn->throttle == 0)
  8109. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8110. "yes"))) {
  8111. off_t sf_offs = (off_t)offset;
  8112. ssize_t sf_sent;
  8113. int sf_file = fileno(filep->access.fp);
  8114. int loop_cnt = 0;
  8115. do {
  8116. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8117. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8118. size_t sf_tosend =
  8119. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8120. sf_sent =
  8121. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8122. if (sf_sent > 0) {
  8123. len -= sf_sent;
  8124. offset += sf_sent;
  8125. } else if (loop_cnt == 0) {
  8126. /* This file can not be sent using sendfile.
  8127. * This might be the case for pseudo-files in the
  8128. * /sys/ and /proc/ file system.
  8129. * Use the regular user mode copy code instead. */
  8130. break;
  8131. } else if (sf_sent == 0) {
  8132. /* No error, but 0 bytes sent. May be EOF? */
  8133. return;
  8134. }
  8135. loop_cnt++;
  8136. } while ((len > 0) && (sf_sent >= 0));
  8137. if (sf_sent > 0) {
  8138. return; /* OK */
  8139. }
  8140. /* sf_sent<0 means error, thus fall back to the classic way */
  8141. /* This is always the case, if sf_file is not a "normal" file,
  8142. * e.g., for sending data from the output of a CGI process. */
  8143. offset = (int64_t)sf_offs;
  8144. }
  8145. #endif
  8146. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8147. mg_cry_internal(conn,
  8148. "%s: fseeko() failed: %s",
  8149. __func__,
  8150. strerror(ERRNO));
  8151. mg_send_http_error(
  8152. conn,
  8153. 500,
  8154. "%s",
  8155. "Error: Unable to access file at requested position.");
  8156. } else {
  8157. while (len > 0) {
  8158. /* Calculate how much to read from the file in the buffer */
  8159. to_read = sizeof(buf);
  8160. if ((int64_t)to_read > len) {
  8161. to_read = (int)len;
  8162. }
  8163. /* Read from file, exit the loop on error */
  8164. if ((num_read =
  8165. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8166. <= 0) {
  8167. break;
  8168. }
  8169. /* Send read bytes to the client, exit the loop on error */
  8170. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8171. != num_read) {
  8172. break;
  8173. }
  8174. /* Both read and were successful, adjust counters */
  8175. len -= num_written;
  8176. }
  8177. }
  8178. }
  8179. }
  8180. static int
  8181. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8182. {
  8183. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8184. }
  8185. static void
  8186. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8187. {
  8188. if ((filestat != NULL) && (buf != NULL)) {
  8189. mg_snprintf(NULL,
  8190. NULL, /* All calls to construct_etag use 64 byte buffer */
  8191. buf,
  8192. buf_len,
  8193. "\"%lx.%" INT64_FMT "\"",
  8194. (unsigned long)filestat->last_modified,
  8195. filestat->size);
  8196. }
  8197. }
  8198. static void
  8199. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8200. {
  8201. if (filep != NULL && filep->fp != NULL) {
  8202. #if defined(_WIN32)
  8203. (void)conn; /* Unused. */
  8204. #else
  8205. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8206. mg_cry_internal(conn,
  8207. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8208. __func__,
  8209. strerror(ERRNO));
  8210. }
  8211. #endif
  8212. }
  8213. }
  8214. #if defined(USE_ZLIB)
  8215. #include "mod_zlib.inl"
  8216. #endif
  8217. static void
  8218. handle_static_file_request(struct mg_connection *conn,
  8219. const char *path,
  8220. struct mg_file *filep,
  8221. const char *mime_type,
  8222. const char *additional_headers)
  8223. {
  8224. char date[64], lm[64], etag[64];
  8225. char range[128]; /* large enough, so there will be no overflow */
  8226. const char *msg = "OK";
  8227. const char *range_hdr;
  8228. time_t curtime = time(NULL);
  8229. int64_t cl, r1, r2;
  8230. struct vec mime_vec;
  8231. int n, truncated;
  8232. char gz_path[PATH_MAX];
  8233. const char *encoding = "";
  8234. const char *origin_hdr;
  8235. const char *cors_orig_cfg;
  8236. const char *cors1, *cors2, *cors3;
  8237. int is_head_request;
  8238. #if defined(USE_ZLIB)
  8239. /* Compression is allowed, unless there is a reason not to use compression.
  8240. * If the file is already compressed, too small or a "range" request was
  8241. * made, on the fly compression is not possible. */
  8242. int allow_on_the_fly_compression = 1;
  8243. #endif
  8244. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8245. return;
  8246. }
  8247. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8248. if (mime_type == NULL) {
  8249. get_mime_type(conn, path, &mime_vec);
  8250. } else {
  8251. mime_vec.ptr = mime_type;
  8252. mime_vec.len = strlen(mime_type);
  8253. }
  8254. if (filep->stat.size > INT64_MAX) {
  8255. mg_send_http_error(conn,
  8256. 500,
  8257. "Error: File size is too large to send\n%" INT64_FMT,
  8258. filep->stat.size);
  8259. return;
  8260. }
  8261. cl = (int64_t)filep->stat.size;
  8262. conn->status_code = 200;
  8263. range[0] = '\0';
  8264. #if defined(USE_ZLIB)
  8265. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8266. * it's important to rewrite the filename after resolving
  8267. * the mime type from it, to preserve the actual file's type */
  8268. if (!conn->accept_gzip) {
  8269. allow_on_the_fly_compression = 0;
  8270. }
  8271. #endif
  8272. /* Check if there is a range header */
  8273. range_hdr = mg_get_header(conn, "Range");
  8274. /* For gzipped files, add *.gz */
  8275. if (filep->stat.is_gzipped) {
  8276. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8277. if (truncated) {
  8278. mg_send_http_error(conn,
  8279. 500,
  8280. "Error: Path of zipped file too long (%s)",
  8281. path);
  8282. return;
  8283. }
  8284. path = gz_path;
  8285. encoding = "Content-Encoding: gzip\r\n";
  8286. #if defined(USE_ZLIB)
  8287. /* File is already compressed. No "on the fly" compression. */
  8288. allow_on_the_fly_compression = 0;
  8289. #endif
  8290. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8291. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8292. struct mg_file_stat file_stat;
  8293. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8294. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8295. && !file_stat.is_directory) {
  8296. file_stat.is_gzipped = 1;
  8297. filep->stat = file_stat;
  8298. cl = (int64_t)filep->stat.size;
  8299. path = gz_path;
  8300. encoding = "Content-Encoding: gzip\r\n";
  8301. #if defined(USE_ZLIB)
  8302. /* File is already compressed. No "on the fly" compression. */
  8303. allow_on_the_fly_compression = 0;
  8304. #endif
  8305. }
  8306. }
  8307. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8308. mg_send_http_error(conn,
  8309. 500,
  8310. "Error: Cannot open file\nfopen(%s): %s",
  8311. path,
  8312. strerror(ERRNO));
  8313. return;
  8314. }
  8315. fclose_on_exec(&filep->access, conn);
  8316. /* If "Range" request was made: parse header, send only selected part
  8317. * of the file. */
  8318. r1 = r2 = 0;
  8319. if ((range_hdr != NULL)
  8320. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8321. && (r2 >= 0)) {
  8322. /* actually, range requests don't play well with a pre-gzipped
  8323. * file (since the range is specified in the uncompressed space) */
  8324. if (filep->stat.is_gzipped) {
  8325. mg_send_http_error(
  8326. conn,
  8327. 416, /* 416 = Range Not Satisfiable */
  8328. "%s",
  8329. "Error: Range requests in gzipped files are not supported");
  8330. (void)mg_fclose(
  8331. &filep->access); /* ignore error on read only file */
  8332. return;
  8333. }
  8334. conn->status_code = 206;
  8335. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8336. mg_snprintf(conn,
  8337. NULL, /* range buffer is big enough */
  8338. range,
  8339. sizeof(range),
  8340. "Content-Range: bytes "
  8341. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8342. r1,
  8343. r1 + cl - 1,
  8344. filep->stat.size);
  8345. msg = "Partial Content";
  8346. #if defined(USE_ZLIB)
  8347. /* Do not compress ranges. */
  8348. allow_on_the_fly_compression = 0;
  8349. #endif
  8350. }
  8351. /* Do not compress small files. Small files do not benefit from file
  8352. * compression, but there is still some overhead. */
  8353. #if defined(USE_ZLIB)
  8354. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8355. /* File is below the size limit. */
  8356. allow_on_the_fly_compression = 0;
  8357. }
  8358. #endif
  8359. /* Standard CORS header */
  8360. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8361. origin_hdr = mg_get_header(conn, "Origin");
  8362. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8363. /* Cross-origin resource sharing (CORS), see
  8364. * http://www.html5rocks.com/en/tutorials/cors/,
  8365. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8366. * -
  8367. * preflight is not supported for files. */
  8368. cors1 = "Access-Control-Allow-Origin: ";
  8369. cors2 = cors_orig_cfg;
  8370. cors3 = "\r\n";
  8371. } else {
  8372. cors1 = cors2 = cors3 = "";
  8373. }
  8374. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8375. * according to
  8376. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8377. gmt_time_string(date, sizeof(date), &curtime);
  8378. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8379. construct_etag(etag, sizeof(etag), &filep->stat);
  8380. /* Send header */
  8381. (void)mg_printf(conn,
  8382. "HTTP/1.1 %d %s\r\n"
  8383. "%s%s%s" /* CORS */
  8384. "Date: %s\r\n"
  8385. "Last-Modified: %s\r\n"
  8386. "Etag: %s\r\n"
  8387. "Content-Type: %.*s\r\n"
  8388. "Connection: %s\r\n",
  8389. conn->status_code,
  8390. msg,
  8391. cors1,
  8392. cors2,
  8393. cors3,
  8394. date,
  8395. lm,
  8396. etag,
  8397. (int)mime_vec.len,
  8398. mime_vec.ptr,
  8399. suggest_connection_header(conn));
  8400. send_static_cache_header(conn);
  8401. send_additional_header(conn);
  8402. #if defined(USE_ZLIB)
  8403. /* On the fly compression allowed */
  8404. if (allow_on_the_fly_compression) {
  8405. /* For on the fly compression, we don't know the content size in
  8406. * advance, so we have to use chunked encoding */
  8407. (void)mg_printf(conn,
  8408. "Content-Encoding: gzip\r\n"
  8409. "Transfer-Encoding: chunked\r\n");
  8410. } else
  8411. #endif
  8412. {
  8413. /* Without on-the-fly compression, we know the content-length
  8414. * and we can use ranges (with on-the-fly compression we cannot).
  8415. * So we send these response headers only in this case. */
  8416. (void)mg_printf(conn,
  8417. "Content-Length: %" INT64_FMT "\r\n"
  8418. "Accept-Ranges: bytes\r\n"
  8419. "%s" /* range */
  8420. "%s" /* encoding */,
  8421. cl,
  8422. range,
  8423. encoding);
  8424. }
  8425. /* The previous code must not add any header starting with X- to make
  8426. * sure no one of the additional_headers is included twice */
  8427. if (additional_headers != NULL) {
  8428. (void)mg_printf(conn,
  8429. "%.*s\r\n\r\n",
  8430. (int)strlen(additional_headers),
  8431. additional_headers);
  8432. } else {
  8433. (void)mg_printf(conn, "\r\n");
  8434. }
  8435. if (!is_head_request) {
  8436. #if defined(USE_ZLIB)
  8437. if (allow_on_the_fly_compression) {
  8438. /* Compress and send */
  8439. send_compressed_data(conn, filep);
  8440. } else
  8441. #endif
  8442. {
  8443. /* Send file directly */
  8444. send_file_data(conn, filep, r1, cl);
  8445. }
  8446. }
  8447. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8448. }
  8449. int
  8450. mg_send_file_body(struct mg_connection *conn, const char *path)
  8451. {
  8452. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8453. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8454. return -1;
  8455. }
  8456. fclose_on_exec(&file.access, conn);
  8457. send_file_data(conn, &file, 0, INT64_MAX);
  8458. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8459. return 0; /* >= 0 for OK */
  8460. }
  8461. #if !defined(NO_CACHING)
  8462. /* Return True if we should reply 304 Not Modified. */
  8463. static int
  8464. is_not_modified(const struct mg_connection *conn,
  8465. const struct mg_file_stat *filestat)
  8466. {
  8467. char etag[64];
  8468. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8469. const char *inm = mg_get_header(conn, "If-None-Match");
  8470. construct_etag(etag, sizeof(etag), filestat);
  8471. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8472. || ((ims != NULL)
  8473. && (filestat->last_modified <= parse_date_string(ims)));
  8474. }
  8475. static void
  8476. handle_not_modified_static_file_request(struct mg_connection *conn,
  8477. struct mg_file *filep)
  8478. {
  8479. char date[64], lm[64], etag[64];
  8480. time_t curtime = time(NULL);
  8481. if ((conn == NULL) || (filep == NULL)) {
  8482. return;
  8483. }
  8484. conn->status_code = 304;
  8485. gmt_time_string(date, sizeof(date), &curtime);
  8486. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8487. construct_etag(etag, sizeof(etag), &filep->stat);
  8488. (void)mg_printf(conn,
  8489. "HTTP/1.1 %d %s\r\n"
  8490. "Date: %s\r\n",
  8491. conn->status_code,
  8492. mg_get_response_code_text(conn, conn->status_code),
  8493. date);
  8494. send_static_cache_header(conn);
  8495. send_additional_header(conn);
  8496. (void)mg_printf(conn,
  8497. "Last-Modified: %s\r\n"
  8498. "Etag: %s\r\n"
  8499. "Connection: %s\r\n"
  8500. "\r\n",
  8501. lm,
  8502. etag,
  8503. suggest_connection_header(conn));
  8504. }
  8505. #endif
  8506. void
  8507. mg_send_file(struct mg_connection *conn, const char *path)
  8508. {
  8509. mg_send_mime_file2(conn, path, NULL, NULL);
  8510. }
  8511. void
  8512. mg_send_mime_file(struct mg_connection *conn,
  8513. const char *path,
  8514. const char *mime_type)
  8515. {
  8516. mg_send_mime_file2(conn, path, mime_type, NULL);
  8517. }
  8518. void
  8519. mg_send_mime_file2(struct mg_connection *conn,
  8520. const char *path,
  8521. const char *mime_type,
  8522. const char *additional_headers)
  8523. {
  8524. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8525. if (!conn) {
  8526. /* No conn */
  8527. return;
  8528. }
  8529. if (mg_stat(conn, path, &file.stat)) {
  8530. #if !defined(NO_CACHING)
  8531. if (is_not_modified(conn, &file.stat)) {
  8532. /* Send 304 "Not Modified" - this must not send any body data */
  8533. handle_not_modified_static_file_request(conn, &file);
  8534. } else
  8535. #endif /* NO_CACHING */
  8536. if (file.stat.is_directory) {
  8537. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8538. "yes")) {
  8539. handle_directory_request(conn, path);
  8540. } else {
  8541. mg_send_http_error(conn,
  8542. 403,
  8543. "%s",
  8544. "Error: Directory listing denied");
  8545. }
  8546. } else {
  8547. handle_static_file_request(
  8548. conn, path, &file, mime_type, additional_headers);
  8549. }
  8550. } else {
  8551. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8552. }
  8553. }
  8554. /* For a given PUT path, create all intermediate subdirectories.
  8555. * Return 0 if the path itself is a directory.
  8556. * Return 1 if the path leads to a file.
  8557. * Return -1 for if the path is too long.
  8558. * Return -2 if path can not be created.
  8559. */
  8560. static int
  8561. put_dir(struct mg_connection *conn, const char *path)
  8562. {
  8563. char buf[PATH_MAX];
  8564. const char *s, *p;
  8565. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8566. size_t len;
  8567. int res = 1;
  8568. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8569. len = (size_t)(p - path);
  8570. if (len >= sizeof(buf)) {
  8571. /* path too long */
  8572. res = -1;
  8573. break;
  8574. }
  8575. memcpy(buf, path, len);
  8576. buf[len] = '\0';
  8577. /* Try to create intermediate directory */
  8578. DEBUG_TRACE("mkdir(%s)", buf);
  8579. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8580. /* path does not exixt and can not be created */
  8581. res = -2;
  8582. break;
  8583. }
  8584. /* Is path itself a directory? */
  8585. if (p[1] == '\0') {
  8586. res = 0;
  8587. }
  8588. }
  8589. return res;
  8590. }
  8591. static void
  8592. remove_bad_file(const struct mg_connection *conn, const char *path)
  8593. {
  8594. int r = mg_remove(conn, path);
  8595. if (r != 0) {
  8596. mg_cry_internal(conn,
  8597. "%s: Cannot remove invalid file %s",
  8598. __func__,
  8599. path);
  8600. }
  8601. }
  8602. long long
  8603. mg_store_body(struct mg_connection *conn, const char *path)
  8604. {
  8605. char buf[MG_BUF_LEN];
  8606. long long len = 0;
  8607. int ret, n;
  8608. struct mg_file fi;
  8609. if (conn->consumed_content != 0) {
  8610. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8611. return -11;
  8612. }
  8613. ret = put_dir(conn, path);
  8614. if (ret < 0) {
  8615. /* -1 for path too long,
  8616. * -2 for path can not be created. */
  8617. return ret;
  8618. }
  8619. if (ret != 1) {
  8620. /* Return 0 means, path itself is a directory. */
  8621. return 0;
  8622. }
  8623. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8624. return -12;
  8625. }
  8626. ret = mg_read(conn, buf, sizeof(buf));
  8627. while (ret > 0) {
  8628. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8629. if (n != ret) {
  8630. (void)mg_fclose(
  8631. &fi.access); /* File is bad and will be removed anyway. */
  8632. remove_bad_file(conn, path);
  8633. return -13;
  8634. }
  8635. len += ret;
  8636. ret = mg_read(conn, buf, sizeof(buf));
  8637. }
  8638. /* File is open for writing. If fclose fails, there was probably an
  8639. * error flushing the buffer to disk, so the file on disk might be
  8640. * broken. Delete it and return an error to the caller. */
  8641. if (mg_fclose(&fi.access) != 0) {
  8642. remove_bad_file(conn, path);
  8643. return -14;
  8644. }
  8645. return len;
  8646. }
  8647. /* Parse a buffer:
  8648. * Forward the string pointer till the end of a word, then
  8649. * terminate it and forward till the begin of the next word.
  8650. */
  8651. static int
  8652. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8653. {
  8654. /* Forward until a space is found - use isgraph here */
  8655. /* See http://www.cplusplus.com/reference/cctype/ */
  8656. while (isgraph((unsigned char)**ppw)) {
  8657. (*ppw)++;
  8658. }
  8659. /* Check end of word */
  8660. if (eol) {
  8661. /* must be a end of line */
  8662. if ((**ppw != '\r') && (**ppw != '\n')) {
  8663. return -1;
  8664. }
  8665. } else {
  8666. /* must be a end of a word, but not a line */
  8667. if (**ppw != ' ') {
  8668. return -1;
  8669. }
  8670. }
  8671. /* Terminate and forward to the next word */
  8672. do {
  8673. **ppw = 0;
  8674. (*ppw)++;
  8675. } while (isspace((unsigned char)**ppw));
  8676. /* Check after term */
  8677. if (!eol) {
  8678. /* if it's not the end of line, there must be a next word */
  8679. if (!isgraph((unsigned char)**ppw)) {
  8680. return -1;
  8681. }
  8682. }
  8683. /* ok */
  8684. return 1;
  8685. }
  8686. /* Parse HTTP headers from the given buffer, advance buf pointer
  8687. * to the point where parsing stopped.
  8688. * All parameters must be valid pointers (not NULL).
  8689. * Return <0 on error. */
  8690. static int
  8691. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8692. {
  8693. int i;
  8694. int num_headers = 0;
  8695. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8696. char *dp = *buf;
  8697. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8698. dp++;
  8699. }
  8700. if (dp == *buf) {
  8701. /* End of headers reached. */
  8702. break;
  8703. }
  8704. if (*dp != ':') {
  8705. /* This is not a valid field. */
  8706. return -1;
  8707. }
  8708. /* End of header key (*dp == ':') */
  8709. /* Truncate here and set the key name */
  8710. *dp = 0;
  8711. hdr[i].name = *buf;
  8712. do {
  8713. dp++;
  8714. } while (*dp == ' ');
  8715. /* The rest of the line is the value */
  8716. hdr[i].value = dp;
  8717. *buf = dp + strcspn(dp, "\r\n");
  8718. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8719. *buf = NULL;
  8720. }
  8721. num_headers = i + 1;
  8722. if (*buf) {
  8723. (*buf)[0] = 0;
  8724. (*buf)[1] = 0;
  8725. *buf += 2;
  8726. } else {
  8727. *buf = dp;
  8728. break;
  8729. }
  8730. if ((*buf)[0] == '\r') {
  8731. /* This is the end of the header */
  8732. break;
  8733. }
  8734. }
  8735. return num_headers;
  8736. }
  8737. struct mg_http_method_info {
  8738. const char *name;
  8739. int request_has_body;
  8740. int response_has_body;
  8741. int is_safe;
  8742. int is_idempotent;
  8743. int is_cacheable;
  8744. };
  8745. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8746. static struct mg_http_method_info http_methods[] = {
  8747. /* HTTP (RFC 2616) */
  8748. {"GET", 0, 1, 1, 1, 1},
  8749. {"POST", 1, 1, 0, 0, 0},
  8750. {"PUT", 1, 0, 0, 1, 0},
  8751. {"DELETE", 0, 0, 0, 1, 0},
  8752. {"HEAD", 0, 0, 1, 1, 1},
  8753. {"OPTIONS", 0, 0, 1, 1, 0},
  8754. {"CONNECT", 1, 1, 0, 0, 0},
  8755. /* TRACE method (RFC 2616) is not supported for security reasons */
  8756. /* PATCH method (RFC 5789) */
  8757. {"PATCH", 1, 0, 0, 0, 0},
  8758. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8759. /* WEBDAV (RFC 2518) */
  8760. {"PROPFIND", 0, 1, 1, 1, 0},
  8761. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8762. * Some PROPFIND results MAY be cached, with care,
  8763. * as there is no cache validation mechanism for
  8764. * most properties. This method is both safe and
  8765. * idempotent (see Section 9.1 of [RFC2616]). */
  8766. {"MKCOL", 0, 0, 0, 1, 0},
  8767. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8768. * When MKCOL is invoked without a request body,
  8769. * the newly created collection SHOULD have no
  8770. * members. A MKCOL request message may contain
  8771. * a message body. The precise behavior of a MKCOL
  8772. * request when the body is present is undefined,
  8773. * ... ==> We do not support MKCOL with body data.
  8774. * This method is idempotent, but not safe (see
  8775. * Section 9.1 of [RFC2616]). Responses to this
  8776. * method MUST NOT be cached. */
  8777. /* Unsupported WEBDAV Methods: */
  8778. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8779. /* + 11 methods from RFC 3253 */
  8780. /* ORDERPATCH (RFC 3648) */
  8781. /* ACL (RFC 3744) */
  8782. /* SEARCH (RFC 5323) */
  8783. /* + MicroSoft extensions
  8784. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8785. /* REPORT method (RFC 3253) */
  8786. {"REPORT", 1, 1, 1, 1, 1},
  8787. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8788. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8789. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8790. * to be useful for REST in case a "GET request with body" is
  8791. * required. */
  8792. {NULL, 0, 0, 0, 0, 0}
  8793. /* end of list */
  8794. };
  8795. static const struct mg_http_method_info *
  8796. get_http_method_info(const char *method)
  8797. {
  8798. /* Check if the method is known to the server. The list of all known
  8799. * HTTP methods can be found here at
  8800. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8801. */
  8802. const struct mg_http_method_info *m = http_methods;
  8803. while (m->name) {
  8804. if (!strcmp(m->name, method)) {
  8805. return m;
  8806. }
  8807. m++;
  8808. }
  8809. return NULL;
  8810. }
  8811. static int
  8812. is_valid_http_method(const char *method)
  8813. {
  8814. return (get_http_method_info(method) != NULL);
  8815. }
  8816. /* Parse HTTP request, fill in mg_request_info structure.
  8817. * This function modifies the buffer by NUL-terminating
  8818. * HTTP request components, header names and header values.
  8819. * Parameters:
  8820. * buf (in/out): pointer to the HTTP header to parse and split
  8821. * len (in): length of HTTP header buffer
  8822. * re (out): parsed header as mg_request_info
  8823. * buf and ri must be valid pointers (not NULL), len>0.
  8824. * Returns <0 on error. */
  8825. static int
  8826. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8827. {
  8828. int request_length;
  8829. int init_skip = 0;
  8830. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8831. * remote_port */
  8832. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8833. NULL;
  8834. ri->num_headers = 0;
  8835. /* RFC says that all initial whitespaces should be ingored */
  8836. /* This included all leading \r and \n (isspace) */
  8837. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8838. while ((len > 0) && isspace((unsigned char)*buf)) {
  8839. buf++;
  8840. len--;
  8841. init_skip++;
  8842. }
  8843. if (len == 0) {
  8844. /* Incomplete request */
  8845. return 0;
  8846. }
  8847. /* Control characters are not allowed, including zero */
  8848. if (iscntrl((unsigned char)*buf)) {
  8849. return -1;
  8850. }
  8851. /* Find end of HTTP header */
  8852. request_length = get_http_header_len(buf, len);
  8853. if (request_length <= 0) {
  8854. return request_length;
  8855. }
  8856. buf[request_length - 1] = '\0';
  8857. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8858. return -1;
  8859. }
  8860. /* The first word has to be the HTTP method */
  8861. ri->request_method = buf;
  8862. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8863. return -1;
  8864. }
  8865. /* Check for a valid http method */
  8866. if (!is_valid_http_method(ri->request_method)) {
  8867. return -1;
  8868. }
  8869. /* The second word is the URI */
  8870. ri->request_uri = buf;
  8871. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8872. return -1;
  8873. }
  8874. /* Next would be the HTTP version */
  8875. ri->http_version = buf;
  8876. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8877. return -1;
  8878. }
  8879. /* Check for a valid HTTP version key */
  8880. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8881. /* Invalid request */
  8882. return -1;
  8883. }
  8884. ri->http_version += 5;
  8885. /* Parse all HTTP headers */
  8886. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8887. if (ri->num_headers < 0) {
  8888. /* Error while parsing headers */
  8889. return -1;
  8890. }
  8891. return request_length + init_skip;
  8892. }
  8893. static int
  8894. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8895. {
  8896. int response_length;
  8897. int init_skip = 0;
  8898. char *tmp, *tmp2;
  8899. long l;
  8900. /* Initialize elements. */
  8901. ri->http_version = ri->status_text = NULL;
  8902. ri->num_headers = ri->status_code = 0;
  8903. /* RFC says that all initial whitespaces should be ingored */
  8904. /* This included all leading \r and \n (isspace) */
  8905. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8906. while ((len > 0) && isspace((unsigned char)*buf)) {
  8907. buf++;
  8908. len--;
  8909. init_skip++;
  8910. }
  8911. if (len == 0) {
  8912. /* Incomplete request */
  8913. return 0;
  8914. }
  8915. /* Control characters are not allowed, including zero */
  8916. if (iscntrl((unsigned char)*buf)) {
  8917. return -1;
  8918. }
  8919. /* Find end of HTTP header */
  8920. response_length = get_http_header_len(buf, len);
  8921. if (response_length <= 0) {
  8922. return response_length;
  8923. }
  8924. buf[response_length - 1] = '\0';
  8925. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8926. return -1;
  8927. }
  8928. /* The first word is the HTTP version */
  8929. /* Check for a valid HTTP version key */
  8930. if (strncmp(buf, "HTTP/", 5) != 0) {
  8931. /* Invalid request */
  8932. return -1;
  8933. }
  8934. buf += 5;
  8935. if (!isgraph((unsigned char)buf[0])) {
  8936. /* Invalid request */
  8937. return -1;
  8938. }
  8939. ri->http_version = buf;
  8940. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8941. return -1;
  8942. }
  8943. /* The second word is the status as a number */
  8944. tmp = buf;
  8945. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8946. return -1;
  8947. }
  8948. l = strtol(tmp, &tmp2, 10);
  8949. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8950. /* Everything else but a 3 digit code is invalid */
  8951. return -1;
  8952. }
  8953. ri->status_code = (int)l;
  8954. /* The rest of the line is the status text */
  8955. ri->status_text = buf;
  8956. /* Find end of status text */
  8957. /* isgraph or isspace = isprint */
  8958. while (isprint((unsigned char)*buf)) {
  8959. buf++;
  8960. }
  8961. if ((*buf != '\r') && (*buf != '\n')) {
  8962. return -1;
  8963. }
  8964. /* Terminate string and forward buf to next line */
  8965. do {
  8966. *buf = 0;
  8967. buf++;
  8968. } while (isspace((unsigned char)*buf));
  8969. /* Parse all HTTP headers */
  8970. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8971. if (ri->num_headers < 0) {
  8972. /* Error while parsing headers */
  8973. return -1;
  8974. }
  8975. return response_length + init_skip;
  8976. }
  8977. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8978. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8979. * buffer (which marks the end of HTTP request). Buffer buf may already
  8980. * have some data. The length of the data is stored in nread.
  8981. * Upon every read operation, increase nread by the number of bytes read. */
  8982. static int
  8983. read_message(FILE *fp,
  8984. struct mg_connection *conn,
  8985. char *buf,
  8986. int bufsiz,
  8987. int *nread)
  8988. {
  8989. int request_len, n = 0;
  8990. struct timespec last_action_time;
  8991. double request_timeout;
  8992. if (!conn) {
  8993. return 0;
  8994. }
  8995. memset(&last_action_time, 0, sizeof(last_action_time));
  8996. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8997. /* value of request_timeout is in seconds, config in milliseconds */
  8998. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8999. } else {
  9000. request_timeout = -1.0;
  9001. }
  9002. if (conn->handled_requests > 0) {
  9003. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9004. request_timeout =
  9005. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9006. }
  9007. }
  9008. request_len = get_http_header_len(buf, *nread);
  9009. /* first time reading from this connection */
  9010. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9011. while (request_len == 0) {
  9012. /* Full request not yet received */
  9013. if (conn->phys_ctx->stop_flag != 0) {
  9014. /* Server is to be stopped. */
  9015. return -1;
  9016. }
  9017. if (*nread >= bufsiz) {
  9018. /* Request too long */
  9019. return -2;
  9020. }
  9021. n = pull_inner(
  9022. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9023. if (n == -2) {
  9024. /* Receive error */
  9025. return -1;
  9026. }
  9027. if (n > 0) {
  9028. *nread += n;
  9029. request_len = get_http_header_len(buf, *nread);
  9030. } else {
  9031. request_len = 0;
  9032. }
  9033. if ((request_len == 0) && (request_timeout >= 0)) {
  9034. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9035. > request_timeout) {
  9036. /* Timeout */
  9037. return -1;
  9038. }
  9039. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9040. }
  9041. }
  9042. return request_len;
  9043. }
  9044. #if !defined(NO_CGI) || !defined(NO_FILES)
  9045. static int
  9046. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9047. {
  9048. const char *expect, *body;
  9049. char buf[MG_BUF_LEN];
  9050. int to_read, nread, success = 0;
  9051. int buffered_len;
  9052. double timeout = -1.0;
  9053. if (!conn) {
  9054. return 0;
  9055. }
  9056. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9057. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9058. }
  9059. expect = mg_get_header(conn, "Expect");
  9060. DEBUG_ASSERT(fp != NULL);
  9061. if (!fp) {
  9062. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9063. return 0;
  9064. }
  9065. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  9066. /* Content length is not specified by the client. */
  9067. mg_send_http_error(conn,
  9068. 411,
  9069. "%s",
  9070. "Error: Client did not specify content length");
  9071. } else if ((expect != NULL)
  9072. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9073. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9074. */
  9075. mg_send_http_error(conn,
  9076. 417,
  9077. "Error: Can not fulfill expectation %s",
  9078. expect);
  9079. } else {
  9080. if (expect != NULL) {
  9081. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9082. conn->status_code = 100;
  9083. } else {
  9084. conn->status_code = 200;
  9085. }
  9086. buffered_len = conn->data_len - conn->request_len;
  9087. DEBUG_ASSERT(buffered_len >= 0);
  9088. DEBUG_ASSERT(conn->consumed_content == 0);
  9089. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  9090. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9091. return 0;
  9092. }
  9093. if (buffered_len > 0) {
  9094. if ((int64_t)buffered_len > conn->content_len) {
  9095. buffered_len = (int)conn->content_len;
  9096. }
  9097. body = conn->buf + conn->request_len;
  9098. push_all(conn->phys_ctx, fp, sock, ssl, body, buffered_len);
  9099. conn->consumed_content += buffered_len;
  9100. }
  9101. nread = 0;
  9102. while (conn->consumed_content < conn->content_len) {
  9103. to_read = sizeof(buf);
  9104. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  9105. to_read = (int)(conn->content_len - conn->consumed_content);
  9106. }
  9107. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  9108. if (nread == -2) {
  9109. /* error */
  9110. break;
  9111. }
  9112. if (nread > 0) {
  9113. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  9114. != nread) {
  9115. break;
  9116. }
  9117. conn->consumed_content += nread;
  9118. }
  9119. }
  9120. if (conn->consumed_content == conn->content_len) {
  9121. success = (nread >= 0);
  9122. }
  9123. /* Each error code path in this function must send an error */
  9124. if (!success) {
  9125. /* NOTE: Maybe some data has already been sent. */
  9126. /* TODO (low): If some data has been sent, a correct error
  9127. * reply can no longer be sent, so just close the connection */
  9128. mg_send_http_error(conn, 500, "%s", "");
  9129. }
  9130. }
  9131. return success;
  9132. }
  9133. #endif
  9134. #if defined(USE_TIMERS)
  9135. #define TIMER_API static
  9136. #include "timer.inl"
  9137. #endif /* USE_TIMERS */
  9138. #if !defined(NO_CGI)
  9139. /* This structure helps to create an environment for the spawned CGI
  9140. * program.
  9141. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9142. * last element must be NULL.
  9143. * However, on Windows there is a requirement that all these
  9144. * VARIABLE=VALUE\0
  9145. * strings must reside in a contiguous buffer. The end of the buffer is
  9146. * marked by two '\0' characters.
  9147. * We satisfy both worlds: we create an envp array (which is vars), all
  9148. * entries are actually pointers inside buf. */
  9149. struct cgi_environment {
  9150. struct mg_connection *conn;
  9151. /* Data block */
  9152. char *buf; /* Environment buffer */
  9153. size_t buflen; /* Space available in buf */
  9154. size_t bufused; /* Space taken in buf */
  9155. /* Index block */
  9156. char **var; /* char **envp */
  9157. size_t varlen; /* Number of variables available in var */
  9158. size_t varused; /* Number of variables stored in var */
  9159. };
  9160. static void addenv(struct cgi_environment *env,
  9161. PRINTF_FORMAT_STRING(const char *fmt),
  9162. ...) PRINTF_ARGS(2, 3);
  9163. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9164. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9165. static void
  9166. addenv(struct cgi_environment *env, const char *fmt, ...)
  9167. {
  9168. size_t i, n, space;
  9169. int truncated = 0;
  9170. char *added;
  9171. va_list ap;
  9172. if ((env->varlen - env->varused) < 2) {
  9173. mg_cry_internal(env->conn,
  9174. "%s: Cannot register CGI variable [%s]",
  9175. __func__,
  9176. fmt);
  9177. return;
  9178. }
  9179. /* Calculate how much space is left in the buffer */
  9180. space = (env->buflen - env->bufused);
  9181. do {
  9182. /* Space for "\0\0" is always needed. */
  9183. if (space <= 2) {
  9184. /* Allocate new buffer */
  9185. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9186. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9187. if (!added) {
  9188. /* Out of memory */
  9189. mg_cry_internal(
  9190. env->conn,
  9191. "%s: Cannot allocate memory for CGI variable [%s]",
  9192. __func__,
  9193. fmt);
  9194. return;
  9195. }
  9196. /* Retarget pointers */
  9197. env->buf = added;
  9198. env->buflen = n;
  9199. for (i = 0, n = 0; i < env->varused; i++) {
  9200. env->var[i] = added + n;
  9201. n += strlen(added + n) + 1;
  9202. }
  9203. space = (env->buflen - env->bufused);
  9204. }
  9205. /* Make a pointer to the free space int the buffer */
  9206. added = env->buf + env->bufused;
  9207. /* Copy VARIABLE=VALUE\0 string into the free space */
  9208. va_start(ap, fmt);
  9209. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9210. va_end(ap);
  9211. /* Do not add truncated strings to the environment */
  9212. if (truncated) {
  9213. /* Reallocate the buffer */
  9214. space = 0;
  9215. }
  9216. } while (truncated);
  9217. /* Calculate number of bytes added to the environment */
  9218. n = strlen(added) + 1;
  9219. env->bufused += n;
  9220. /* Append a pointer to the added string into the envp array */
  9221. env->var[env->varused] = added;
  9222. env->varused++;
  9223. }
  9224. /* Return 0 on success, non-zero if an error occurs. */
  9225. static int
  9226. prepare_cgi_environment(struct mg_connection *conn,
  9227. const char *prog,
  9228. struct cgi_environment *env)
  9229. {
  9230. const char *s;
  9231. struct vec var_vec;
  9232. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9233. int i, truncated, uri_len;
  9234. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9235. return -1;
  9236. }
  9237. env->conn = conn;
  9238. env->buflen = CGI_ENVIRONMENT_SIZE;
  9239. env->bufused = 0;
  9240. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9241. if (env->buf == NULL) {
  9242. mg_cry_internal(conn,
  9243. "%s: Not enough memory for environmental buffer",
  9244. __func__);
  9245. return -1;
  9246. }
  9247. env->varlen = MAX_CGI_ENVIR_VARS;
  9248. env->varused = 0;
  9249. env->var =
  9250. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9251. if (env->var == NULL) {
  9252. mg_cry_internal(conn,
  9253. "%s: Not enough memory for environmental variables",
  9254. __func__);
  9255. mg_free(env->buf);
  9256. return -1;
  9257. }
  9258. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9259. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9260. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9261. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9262. /* Prepare the environment block */
  9263. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9264. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9265. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9266. #if defined(USE_IPV6)
  9267. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9268. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9269. } else
  9270. #endif
  9271. {
  9272. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9273. }
  9274. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9275. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9276. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9277. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9278. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9279. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9280. /* SCRIPT_NAME */
  9281. uri_len = (int)strlen(conn->request_info.local_uri);
  9282. if (conn->path_info == NULL) {
  9283. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9284. /* URI: /path_to_script/script.cgi */
  9285. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9286. } else {
  9287. /* URI: /path_to_script/ ... using index.cgi */
  9288. const char *index_file = strrchr(prog, '/');
  9289. if (index_file) {
  9290. addenv(env,
  9291. "SCRIPT_NAME=%s%s",
  9292. conn->request_info.local_uri,
  9293. index_file + 1);
  9294. }
  9295. }
  9296. } else {
  9297. /* URI: /path_to_script/script.cgi/path_info */
  9298. addenv(env,
  9299. "SCRIPT_NAME=%.*s",
  9300. uri_len - (int)strlen(conn->path_info),
  9301. conn->request_info.local_uri);
  9302. }
  9303. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9304. if (conn->path_info == NULL) {
  9305. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9306. } else {
  9307. addenv(env,
  9308. "PATH_TRANSLATED=%s%s",
  9309. conn->dom_ctx->config[DOCUMENT_ROOT],
  9310. conn->path_info);
  9311. }
  9312. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9313. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9314. addenv(env, "CONTENT_TYPE=%s", s);
  9315. }
  9316. if (conn->request_info.query_string != NULL) {
  9317. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9318. }
  9319. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9320. addenv(env, "CONTENT_LENGTH=%s", s);
  9321. }
  9322. if ((s = getenv("PATH")) != NULL) {
  9323. addenv(env, "PATH=%s", s);
  9324. }
  9325. if (conn->path_info != NULL) {
  9326. addenv(env, "PATH_INFO=%s", conn->path_info);
  9327. }
  9328. if (conn->status_code > 0) {
  9329. /* CGI error handler should show the status code */
  9330. addenv(env, "STATUS=%d", conn->status_code);
  9331. }
  9332. #if defined(_WIN32)
  9333. if ((s = getenv("COMSPEC")) != NULL) {
  9334. addenv(env, "COMSPEC=%s", s);
  9335. }
  9336. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9337. addenv(env, "SYSTEMROOT=%s", s);
  9338. }
  9339. if ((s = getenv("SystemDrive")) != NULL) {
  9340. addenv(env, "SystemDrive=%s", s);
  9341. }
  9342. if ((s = getenv("ProgramFiles")) != NULL) {
  9343. addenv(env, "ProgramFiles=%s", s);
  9344. }
  9345. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9346. addenv(env, "ProgramFiles(x86)=%s", s);
  9347. }
  9348. #else
  9349. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9350. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9351. }
  9352. #endif /* _WIN32 */
  9353. if ((s = getenv("PERLLIB")) != NULL) {
  9354. addenv(env, "PERLLIB=%s", s);
  9355. }
  9356. if (conn->request_info.remote_user != NULL) {
  9357. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9358. addenv(env, "%s", "AUTH_TYPE=Digest");
  9359. }
  9360. /* Add all headers as HTTP_* variables */
  9361. for (i = 0; i < conn->request_info.num_headers; i++) {
  9362. (void)mg_snprintf(conn,
  9363. &truncated,
  9364. http_var_name,
  9365. sizeof(http_var_name),
  9366. "HTTP_%s",
  9367. conn->request_info.http_headers[i].name);
  9368. if (truncated) {
  9369. mg_cry_internal(conn,
  9370. "%s: HTTP header variable too long [%s]",
  9371. __func__,
  9372. conn->request_info.http_headers[i].name);
  9373. continue;
  9374. }
  9375. /* Convert variable name into uppercase, and change - to _ */
  9376. for (p = http_var_name; *p != '\0'; p++) {
  9377. if (*p == '-') {
  9378. *p = '_';
  9379. }
  9380. *p = (char)toupper((unsigned char)*p);
  9381. }
  9382. addenv(env,
  9383. "%s=%s",
  9384. http_var_name,
  9385. conn->request_info.http_headers[i].value);
  9386. }
  9387. /* Add user-specified variables */
  9388. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9389. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9390. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9391. }
  9392. env->var[env->varused] = NULL;
  9393. env->buf[env->bufused] = '\0';
  9394. return 0;
  9395. }
  9396. /* Data for CGI process control: PID and number of references */
  9397. struct process_control_data {
  9398. pid_t pid;
  9399. int references;
  9400. };
  9401. static int
  9402. abort_process(void *data)
  9403. {
  9404. /* Waitpid checks for child status and won't work for a pid that does not
  9405. * identify a child of the current process. Thus, if the pid is reused,
  9406. * we will not affect a different process. */
  9407. struct process_control_data *proc = (struct process_control_data *)data;
  9408. int status = 0;
  9409. int refs;
  9410. pid_t ret_pid;
  9411. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9412. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9413. /* Stop child process */
  9414. DEBUG_TRACE("CGI timer: Stop child process %p\n", proc->pid);
  9415. kill(proc->pid, SIGABRT);
  9416. /* Wait until process is terminated (don't leave zombies) */
  9417. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9418. ;
  9419. } else {
  9420. DEBUG_TRACE("CGI timer: Child process %p already stopped\n", proc->pid);
  9421. }
  9422. /* Dec reference counter */
  9423. refs = mg_atomic_dec(&proc->references);
  9424. if (refs == 0) {
  9425. /* no more references - free data */
  9426. mg_free(data);
  9427. }
  9428. return 0;
  9429. }
  9430. /* Local (static) function assumes all arguments are valid. */
  9431. static void
  9432. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9433. {
  9434. char *buf;
  9435. size_t buflen;
  9436. int headers_len, data_len, i, truncated;
  9437. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9438. const char *status, *status_text, *connection_state;
  9439. char *pbuf, dir[PATH_MAX], *p;
  9440. struct mg_request_info ri;
  9441. struct cgi_environment blk;
  9442. FILE *in = NULL, *out = NULL, *err = NULL;
  9443. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9444. pid_t pid = (pid_t)-1;
  9445. struct process_control_data *proc = NULL;
  9446. #if defined(USE_TIMERS)
  9447. double cgi_timeout = -1.0;
  9448. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9449. /* Get timeout in seconds */
  9450. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9451. }
  9452. #endif
  9453. buf = NULL;
  9454. buflen = conn->phys_ctx->max_request_size;
  9455. i = prepare_cgi_environment(conn, prog, &blk);
  9456. if (i != 0) {
  9457. blk.buf = NULL;
  9458. blk.var = NULL;
  9459. goto done;
  9460. }
  9461. /* CGI must be executed in its own directory. 'dir' must point to the
  9462. * directory containing executable program, 'p' must point to the
  9463. * executable program name relative to 'dir'. */
  9464. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9465. if (truncated) {
  9466. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9467. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9468. goto done;
  9469. }
  9470. if ((p = strrchr(dir, '/')) != NULL) {
  9471. *p++ = '\0';
  9472. } else {
  9473. dir[0] = '.';
  9474. dir[1] = '\0';
  9475. p = (char *)prog;
  9476. }
  9477. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9478. status = strerror(ERRNO);
  9479. mg_cry_internal(
  9480. conn,
  9481. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9482. prog,
  9483. status);
  9484. mg_send_http_error(conn,
  9485. 500,
  9486. "Error: Cannot create CGI pipe: %s",
  9487. status);
  9488. goto done;
  9489. }
  9490. proc = (struct process_control_data *)
  9491. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9492. if (proc == NULL) {
  9493. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9494. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9495. goto done;
  9496. }
  9497. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9498. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9499. if (pid == (pid_t)-1) {
  9500. status = strerror(ERRNO);
  9501. mg_cry_internal(
  9502. conn,
  9503. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9504. prog,
  9505. status);
  9506. mg_send_http_error(conn,
  9507. 500,
  9508. "Error: Cannot spawn CGI process [%s]: %s",
  9509. prog,
  9510. status);
  9511. mg_free(proc);
  9512. proc = NULL;
  9513. goto done;
  9514. }
  9515. /* Store data in shared process_control_data */
  9516. proc->pid = pid;
  9517. proc->references = 1;
  9518. #if defined(USE_TIMERS)
  9519. if (cgi_timeout > 0.0) {
  9520. proc->references = 2;
  9521. // Start a timer for CGI
  9522. timer_add(conn->phys_ctx,
  9523. cgi_timeout /* in seconds */,
  9524. 0.0,
  9525. 1,
  9526. abort_process,
  9527. (void *)proc);
  9528. }
  9529. #endif
  9530. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  9531. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  9532. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  9533. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  9534. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  9535. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  9536. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  9537. /* Parent closes only one side of the pipes.
  9538. * If we don't mark them as closed, close() attempt before
  9539. * return from this function throws an exception on Windows.
  9540. * Windows does not like when closed descriptor is closed again. */
  9541. (void)close(fdin[0]);
  9542. (void)close(fdout[1]);
  9543. (void)close(fderr[1]);
  9544. fdin[0] = fdout[1] = fderr[1] = -1;
  9545. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  9546. status = strerror(ERRNO);
  9547. mg_cry_internal(conn,
  9548. "Error: CGI program \"%s\": Can not open stdin: %s",
  9549. prog,
  9550. status);
  9551. mg_send_http_error(conn,
  9552. 500,
  9553. "Error: CGI can not open fdin\nfopen: %s",
  9554. status);
  9555. goto done;
  9556. }
  9557. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  9558. status = strerror(ERRNO);
  9559. mg_cry_internal(conn,
  9560. "Error: CGI program \"%s\": Can not open stdout: %s",
  9561. prog,
  9562. status);
  9563. mg_send_http_error(conn,
  9564. 500,
  9565. "Error: CGI can not open fdout\nfopen: %s",
  9566. status);
  9567. goto done;
  9568. }
  9569. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  9570. status = strerror(ERRNO);
  9571. mg_cry_internal(conn,
  9572. "Error: CGI program \"%s\": Can not open stderr: %s",
  9573. prog,
  9574. status);
  9575. mg_send_http_error(conn,
  9576. 500,
  9577. "Error: CGI can not open fderr\nfopen: %s",
  9578. status);
  9579. goto done;
  9580. }
  9581. setbuf(in, NULL);
  9582. setbuf(out, NULL);
  9583. setbuf(err, NULL);
  9584. fout.access.fp = out;
  9585. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  9586. DEBUG_TRACE("CGI: send body data (%lli)\n",
  9587. (signed long long)conn->request_info.content_length);
  9588. /* This is a POST/PUT request, or another request with body data. */
  9589. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9590. /* Error sending the body data */
  9591. mg_cry_internal(
  9592. conn,
  9593. "Error: CGI program \"%s\": Forward body data failed",
  9594. prog);
  9595. goto done;
  9596. }
  9597. }
  9598. /* Close so child gets an EOF. */
  9599. fclose(in);
  9600. in = NULL;
  9601. fdin[1] = -1;
  9602. /* Now read CGI reply into a buffer. We need to set correct
  9603. * status code, thus we need to see all HTTP headers first.
  9604. * Do not send anything back to client, until we buffer in all
  9605. * HTTP headers. */
  9606. data_len = 0;
  9607. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9608. if (buf == NULL) {
  9609. mg_send_http_error(conn,
  9610. 500,
  9611. "Error: Not enough memory for CGI buffer (%u bytes)",
  9612. (unsigned int)buflen);
  9613. mg_cry_internal(
  9614. conn,
  9615. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9616. "bytes)",
  9617. prog,
  9618. (unsigned int)buflen);
  9619. goto done;
  9620. }
  9621. DEBUG_TRACE("CGI: %s", "wait for response");
  9622. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9623. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9624. if (headers_len <= 0) {
  9625. /* Could not parse the CGI response. Check if some error message on
  9626. * stderr. */
  9627. i = pull_all(err, conn, buf, (int)buflen);
  9628. if (i > 0) {
  9629. /* CGI program explicitly sent an error */
  9630. /* Write the error message to the internal log */
  9631. mg_cry_internal(conn,
  9632. "Error: CGI program \"%s\" sent error "
  9633. "message: [%.*s]",
  9634. prog,
  9635. i,
  9636. buf);
  9637. /* Don't send the error message back to the client */
  9638. mg_send_http_error(conn,
  9639. 500,
  9640. "Error: CGI program \"%s\" failed.",
  9641. prog);
  9642. } else {
  9643. /* CGI program did not explicitly send an error, but a broken
  9644. * respon header */
  9645. mg_cry_internal(conn,
  9646. "Error: CGI program sent malformed or too big "
  9647. "(>%u bytes) HTTP headers: [%.*s]",
  9648. (unsigned)buflen,
  9649. data_len,
  9650. buf);
  9651. mg_send_http_error(conn,
  9652. 500,
  9653. "Error: CGI program sent malformed or too big "
  9654. "(>%u bytes) HTTP headers: [%.*s]",
  9655. (unsigned)buflen,
  9656. data_len,
  9657. buf);
  9658. }
  9659. /* in both cases, abort processing CGI */
  9660. goto done;
  9661. }
  9662. pbuf = buf;
  9663. buf[headers_len - 1] = '\0';
  9664. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9665. /* Make up and send the status line */
  9666. status_text = "OK";
  9667. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9668. != NULL) {
  9669. conn->status_code = atoi(status);
  9670. status_text = status;
  9671. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9672. status_text++;
  9673. }
  9674. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9675. != NULL) {
  9676. conn->status_code = 307;
  9677. } else {
  9678. conn->status_code = 200;
  9679. }
  9680. connection_state =
  9681. get_header(ri.http_headers, ri.num_headers, "Connection");
  9682. if (!header_has_option(connection_state, "keep-alive")) {
  9683. conn->must_close = 1;
  9684. }
  9685. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9686. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9687. /* Send headers */
  9688. for (i = 0; i < ri.num_headers; i++) {
  9689. mg_printf(conn,
  9690. "%s: %s\r\n",
  9691. ri.http_headers[i].name,
  9692. ri.http_headers[i].value);
  9693. }
  9694. mg_write(conn, "\r\n", 2);
  9695. /* Send chunk of data that may have been read after the headers */
  9696. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9697. /* Read the rest of CGI output and send to the client */
  9698. DEBUG_TRACE("CGI: %s", "forward all data");
  9699. send_file_data(conn, &fout, 0, INT64_MAX);
  9700. DEBUG_TRACE("CGI: %s", "all data sent");
  9701. done:
  9702. mg_free(blk.var);
  9703. mg_free(blk.buf);
  9704. if (pid != (pid_t)-1) {
  9705. abort_process((void *)proc);
  9706. }
  9707. if (fdin[0] != -1) {
  9708. close(fdin[0]);
  9709. }
  9710. if (fdout[1] != -1) {
  9711. close(fdout[1]);
  9712. }
  9713. if (in != NULL) {
  9714. fclose(in);
  9715. } else if (fdin[1] != -1) {
  9716. close(fdin[1]);
  9717. }
  9718. if (out != NULL) {
  9719. fclose(out);
  9720. } else if (fdout[0] != -1) {
  9721. close(fdout[0]);
  9722. }
  9723. if (err != NULL) {
  9724. fclose(err);
  9725. } else if (fderr[0] != -1) {
  9726. close(fderr[0]);
  9727. }
  9728. mg_free(buf);
  9729. }
  9730. #endif /* !NO_CGI */
  9731. #if !defined(NO_FILES)
  9732. static void
  9733. mkcol(struct mg_connection *conn, const char *path)
  9734. {
  9735. int rc, body_len;
  9736. struct de de;
  9737. char date[64];
  9738. time_t curtime = time(NULL);
  9739. if (conn == NULL) {
  9740. return;
  9741. }
  9742. /* TODO (mid): Check the mg_send_http_error situations in this function
  9743. */
  9744. memset(&de.file, 0, sizeof(de.file));
  9745. if (!mg_stat(conn, path, &de.file)) {
  9746. mg_cry_internal(conn,
  9747. "%s: mg_stat(%s) failed: %s",
  9748. __func__,
  9749. path,
  9750. strerror(ERRNO));
  9751. }
  9752. if (de.file.last_modified) {
  9753. /* TODO (mid): This check does not seem to make any sense ! */
  9754. /* TODO (mid): Add a webdav unit test first, before changing
  9755. * anything here. */
  9756. mg_send_http_error(
  9757. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9758. return;
  9759. }
  9760. body_len = conn->data_len - conn->request_len;
  9761. if (body_len > 0) {
  9762. mg_send_http_error(
  9763. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9764. return;
  9765. }
  9766. rc = mg_mkdir(conn, path, 0755);
  9767. if (rc == 0) {
  9768. conn->status_code = 201;
  9769. gmt_time_string(date, sizeof(date), &curtime);
  9770. mg_printf(conn,
  9771. "HTTP/1.1 %d Created\r\n"
  9772. "Date: %s\r\n",
  9773. conn->status_code,
  9774. date);
  9775. send_static_cache_header(conn);
  9776. send_additional_header(conn);
  9777. mg_printf(conn,
  9778. "Content-Length: 0\r\n"
  9779. "Connection: %s\r\n\r\n",
  9780. suggest_connection_header(conn));
  9781. } else {
  9782. if (errno == EEXIST) {
  9783. mg_send_http_error(
  9784. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9785. } else if (errno == EACCES) {
  9786. mg_send_http_error(
  9787. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9788. } else if (errno == ENOENT) {
  9789. mg_send_http_error(
  9790. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9791. } else {
  9792. mg_send_http_error(
  9793. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9794. }
  9795. }
  9796. }
  9797. static void
  9798. put_file(struct mg_connection *conn, const char *path)
  9799. {
  9800. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9801. const char *range;
  9802. int64_t r1, r2;
  9803. int rc;
  9804. char date[64];
  9805. time_t curtime = time(NULL);
  9806. if (conn == NULL) {
  9807. return;
  9808. }
  9809. if (mg_stat(conn, path, &file.stat)) {
  9810. /* File already exists */
  9811. conn->status_code = 200;
  9812. if (file.stat.is_directory) {
  9813. /* This is an already existing directory,
  9814. * so there is nothing to do for the server. */
  9815. rc = 0;
  9816. } else {
  9817. /* File exists and is not a directory. */
  9818. /* Can it be replaced? */
  9819. #if defined(MG_USE_OPEN_FILE)
  9820. if (file.access.membuf != NULL) {
  9821. /* This is an "in-memory" file, that can not be replaced */
  9822. mg_send_http_error(conn,
  9823. 405,
  9824. "Error: Put not possible\nReplacing %s "
  9825. "is not supported",
  9826. path);
  9827. return;
  9828. }
  9829. #endif
  9830. /* Check if the server may write this file */
  9831. if (access(path, W_OK) == 0) {
  9832. /* Access granted */
  9833. conn->status_code = 200;
  9834. rc = 1;
  9835. } else {
  9836. mg_send_http_error(
  9837. conn,
  9838. 403,
  9839. "Error: Put not possible\nReplacing %s is not allowed",
  9840. path);
  9841. return;
  9842. }
  9843. }
  9844. } else {
  9845. /* File should be created */
  9846. conn->status_code = 201;
  9847. rc = put_dir(conn, path);
  9848. }
  9849. if (rc == 0) {
  9850. /* put_dir returns 0 if path is a directory */
  9851. gmt_time_string(date, sizeof(date), &curtime);
  9852. mg_printf(conn,
  9853. "HTTP/1.1 %d %s\r\n",
  9854. conn->status_code,
  9855. mg_get_response_code_text(NULL, conn->status_code));
  9856. send_no_cache_header(conn);
  9857. send_additional_header(conn);
  9858. mg_printf(conn,
  9859. "Date: %s\r\n"
  9860. "Content-Length: 0\r\n"
  9861. "Connection: %s\r\n\r\n",
  9862. date,
  9863. suggest_connection_header(conn));
  9864. /* Request to create a directory has been fulfilled successfully.
  9865. * No need to put a file. */
  9866. return;
  9867. }
  9868. if (rc == -1) {
  9869. /* put_dir returns -1 if the path is too long */
  9870. mg_send_http_error(conn,
  9871. 414,
  9872. "Error: Path too long\nput_dir(%s): %s",
  9873. path,
  9874. strerror(ERRNO));
  9875. return;
  9876. }
  9877. if (rc == -2) {
  9878. /* put_dir returns -2 if the directory can not be created */
  9879. mg_send_http_error(conn,
  9880. 500,
  9881. "Error: Can not create directory\nput_dir(%s): %s",
  9882. path,
  9883. strerror(ERRNO));
  9884. return;
  9885. }
  9886. /* A file should be created or overwritten. */
  9887. /* Currently CivetWeb does not nead read+write access. */
  9888. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9889. || file.access.fp == NULL) {
  9890. (void)mg_fclose(&file.access);
  9891. mg_send_http_error(conn,
  9892. 500,
  9893. "Error: Can not create file\nfopen(%s): %s",
  9894. path,
  9895. strerror(ERRNO));
  9896. return;
  9897. }
  9898. fclose_on_exec(&file.access, conn);
  9899. range = mg_get_header(conn, "Content-Range");
  9900. r1 = r2 = 0;
  9901. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9902. conn->status_code = 206; /* Partial content */
  9903. fseeko(file.access.fp, r1, SEEK_SET);
  9904. }
  9905. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9906. /* forward_body_data failed.
  9907. * The error code has already been sent to the client,
  9908. * and conn->status_code is already set. */
  9909. (void)mg_fclose(&file.access);
  9910. return;
  9911. }
  9912. if (mg_fclose(&file.access) != 0) {
  9913. /* fclose failed. This might have different reasons, but a likely
  9914. * one is "no space on disk", http 507. */
  9915. conn->status_code = 507;
  9916. }
  9917. gmt_time_string(date, sizeof(date), &curtime);
  9918. mg_printf(conn,
  9919. "HTTP/1.1 %d %s\r\n",
  9920. conn->status_code,
  9921. mg_get_response_code_text(NULL, conn->status_code));
  9922. send_no_cache_header(conn);
  9923. send_additional_header(conn);
  9924. mg_printf(conn,
  9925. "Date: %s\r\n"
  9926. "Content-Length: 0\r\n"
  9927. "Connection: %s\r\n\r\n",
  9928. date,
  9929. suggest_connection_header(conn));
  9930. }
  9931. static void
  9932. delete_file(struct mg_connection *conn, const char *path)
  9933. {
  9934. struct de de;
  9935. memset(&de.file, 0, sizeof(de.file));
  9936. if (!mg_stat(conn, path, &de.file)) {
  9937. /* mg_stat returns 0 if the file does not exist */
  9938. mg_send_http_error(conn,
  9939. 404,
  9940. "Error: Cannot delete file\nFile %s not found",
  9941. path);
  9942. return;
  9943. }
  9944. #if 0 /* Ignore if a file in memory is inside a folder */
  9945. if (de.access.membuf != NULL) {
  9946. /* the file is cached in memory */
  9947. mg_send_http_error(
  9948. conn,
  9949. 405,
  9950. "Error: Delete not possible\nDeleting %s is not supported",
  9951. path);
  9952. return;
  9953. }
  9954. #endif
  9955. if (de.file.is_directory) {
  9956. if (remove_directory(conn, path)) {
  9957. /* Delete is successful: Return 204 without content. */
  9958. mg_send_http_error(conn, 204, "%s", "");
  9959. } else {
  9960. /* Delete is not successful: Return 500 (Server error). */
  9961. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9962. }
  9963. return;
  9964. }
  9965. /* This is an existing file (not a directory).
  9966. * Check if write permission is granted. */
  9967. if (access(path, W_OK) != 0) {
  9968. /* File is read only */
  9969. mg_send_http_error(
  9970. conn,
  9971. 403,
  9972. "Error: Delete not possible\nDeleting %s is not allowed",
  9973. path);
  9974. return;
  9975. }
  9976. /* Try to delete it. */
  9977. if (mg_remove(conn, path) == 0) {
  9978. /* Delete was successful: Return 204 without content. */
  9979. mg_send_http_error(conn, 204, "%s", "");
  9980. } else {
  9981. /* Delete not successful (file locked). */
  9982. mg_send_http_error(conn,
  9983. 423,
  9984. "Error: Cannot delete file\nremove(%s): %s",
  9985. path,
  9986. strerror(ERRNO));
  9987. }
  9988. }
  9989. #endif /* !NO_FILES */
  9990. static void
  9991. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9992. static void
  9993. do_ssi_include(struct mg_connection *conn,
  9994. const char *ssi,
  9995. char *tag,
  9996. int include_level)
  9997. {
  9998. char file_name[MG_BUF_LEN], path[512], *p;
  9999. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10000. size_t len;
  10001. int truncated = 0;
  10002. if (conn == NULL) {
  10003. return;
  10004. }
  10005. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  10006. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  10007. * always < MG_BUF_LEN. */
  10008. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  10009. /* File name is relative to the webserver root */
  10010. file_name[511] = 0;
  10011. (void)mg_snprintf(conn,
  10012. &truncated,
  10013. path,
  10014. sizeof(path),
  10015. "%s/%s",
  10016. conn->dom_ctx->config[DOCUMENT_ROOT],
  10017. file_name);
  10018. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  10019. /* File name is relative to the webserver working directory
  10020. * or it is absolute system path */
  10021. file_name[511] = 0;
  10022. (void)
  10023. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  10024. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  10025. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  10026. /* File name is relative to the currect document */
  10027. file_name[511] = 0;
  10028. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  10029. if (!truncated) {
  10030. if ((p = strrchr(path, '/')) != NULL) {
  10031. p[1] = '\0';
  10032. }
  10033. len = strlen(path);
  10034. (void)mg_snprintf(conn,
  10035. &truncated,
  10036. path + len,
  10037. sizeof(path) - len,
  10038. "%s",
  10039. file_name);
  10040. }
  10041. } else {
  10042. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10043. return;
  10044. }
  10045. if (truncated) {
  10046. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10047. return;
  10048. }
  10049. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10050. mg_cry_internal(conn,
  10051. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10052. tag,
  10053. path,
  10054. strerror(ERRNO));
  10055. } else {
  10056. fclose_on_exec(&file.access, conn);
  10057. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10058. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10059. path)
  10060. > 0) {
  10061. send_ssi_file(conn, path, &file, include_level + 1);
  10062. } else {
  10063. send_file_data(conn, &file, 0, INT64_MAX);
  10064. }
  10065. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10066. }
  10067. }
  10068. #if !defined(NO_POPEN)
  10069. static void
  10070. do_ssi_exec(struct mg_connection *conn, char *tag)
  10071. {
  10072. char cmd[1024] = "";
  10073. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10074. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10075. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10076. } else {
  10077. cmd[1023] = 0;
  10078. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10079. mg_cry_internal(conn,
  10080. "Cannot SSI #exec: [%s]: %s",
  10081. cmd,
  10082. strerror(ERRNO));
  10083. } else {
  10084. send_file_data(conn, &file, 0, INT64_MAX);
  10085. pclose(file.access.fp);
  10086. }
  10087. }
  10088. }
  10089. #endif /* !NO_POPEN */
  10090. static int
  10091. mg_fgetc(struct mg_file *filep, int offset)
  10092. {
  10093. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10094. if (filep == NULL) {
  10095. return EOF;
  10096. }
  10097. #if defined(MG_USE_OPEN_FILE)
  10098. if ((filep->access.membuf != NULL) && (offset >= 0)
  10099. && (((unsigned int)(offset)) < filep->stat.size)) {
  10100. return ((const unsigned char *)filep->access.membuf)[offset];
  10101. } else /* else block below */
  10102. #endif
  10103. if (filep->access.fp != NULL) {
  10104. return fgetc(filep->access.fp);
  10105. } else {
  10106. return EOF;
  10107. }
  10108. }
  10109. static void
  10110. send_ssi_file(struct mg_connection *conn,
  10111. const char *path,
  10112. struct mg_file *filep,
  10113. int include_level)
  10114. {
  10115. char buf[MG_BUF_LEN];
  10116. int ch, offset, len, in_tag, in_ssi_tag;
  10117. if (include_level > 10) {
  10118. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10119. return;
  10120. }
  10121. in_tag = in_ssi_tag = len = offset = 0;
  10122. /* Read file, byte by byte, and look for SSI include tags */
  10123. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10124. if (in_tag) {
  10125. /* We are in a tag, either SSI tag or html tag */
  10126. if (ch == '>') {
  10127. /* Tag is closing */
  10128. buf[len++] = '>';
  10129. if (in_ssi_tag) {
  10130. /* Handle SSI tag */
  10131. buf[len] = 0;
  10132. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10133. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10134. #if !defined(NO_POPEN)
  10135. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10136. do_ssi_exec(conn, buf + 9);
  10137. #endif /* !NO_POPEN */
  10138. } else {
  10139. mg_cry_internal(conn,
  10140. "%s: unknown SSI "
  10141. "command: \"%s\"",
  10142. path,
  10143. buf);
  10144. }
  10145. len = 0;
  10146. in_ssi_tag = in_tag = 0;
  10147. } else {
  10148. /* Not an SSI tag */
  10149. /* Flush buffer */
  10150. (void)mg_write(conn, buf, (size_t)len);
  10151. len = 0;
  10152. in_tag = 0;
  10153. }
  10154. } else {
  10155. /* Tag is still open */
  10156. buf[len++] = (char)(ch & 0xff);
  10157. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10158. /* All SSI tags start with <!--# */
  10159. in_ssi_tag = 1;
  10160. }
  10161. if ((len + 2) > (int)sizeof(buf)) {
  10162. /* Tag to long for buffer */
  10163. mg_cry_internal(conn, "%s: tag is too large", path);
  10164. return;
  10165. }
  10166. }
  10167. } else {
  10168. /* We are not in a tag yet. */
  10169. if (ch == '<') {
  10170. /* Tag is opening */
  10171. in_tag = 1;
  10172. if (len > 0) {
  10173. /* Flush current buffer.
  10174. * Buffer is filled with "len" bytes. */
  10175. (void)mg_write(conn, buf, (size_t)len);
  10176. }
  10177. /* Store the < */
  10178. len = 1;
  10179. buf[0] = '<';
  10180. } else {
  10181. /* No Tag */
  10182. /* Add data to buffer */
  10183. buf[len++] = (char)(ch & 0xff);
  10184. /* Flush if buffer is full */
  10185. if (len == (int)sizeof(buf)) {
  10186. mg_write(conn, buf, (size_t)len);
  10187. len = 0;
  10188. }
  10189. }
  10190. }
  10191. }
  10192. /* Send the rest of buffered data */
  10193. if (len > 0) {
  10194. mg_write(conn, buf, (size_t)len);
  10195. }
  10196. }
  10197. static void
  10198. handle_ssi_file_request(struct mg_connection *conn,
  10199. const char *path,
  10200. struct mg_file *filep)
  10201. {
  10202. char date[64];
  10203. time_t curtime = time(NULL);
  10204. const char *cors_orig_cfg;
  10205. const char *cors1, *cors2, *cors3;
  10206. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10207. return;
  10208. }
  10209. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10210. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10211. /* Cross-origin resource sharing (CORS). */
  10212. cors1 = "Access-Control-Allow-Origin: ";
  10213. cors2 = cors_orig_cfg;
  10214. cors3 = "\r\n";
  10215. } else {
  10216. cors1 = cors2 = cors3 = "";
  10217. }
  10218. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10219. /* File exists (precondition for calling this function),
  10220. * but can not be opened by the server. */
  10221. mg_send_http_error(conn,
  10222. 500,
  10223. "Error: Cannot read file\nfopen(%s): %s",
  10224. path,
  10225. strerror(ERRNO));
  10226. } else {
  10227. conn->must_close = 1;
  10228. gmt_time_string(date, sizeof(date), &curtime);
  10229. fclose_on_exec(&filep->access, conn);
  10230. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10231. send_no_cache_header(conn);
  10232. send_additional_header(conn);
  10233. mg_printf(conn,
  10234. "%s%s%s"
  10235. "Date: %s\r\n"
  10236. "Content-Type: text/html\r\n"
  10237. "Connection: %s\r\n\r\n",
  10238. cors1,
  10239. cors2,
  10240. cors3,
  10241. date,
  10242. suggest_connection_header(conn));
  10243. send_ssi_file(conn, path, filep, 0);
  10244. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10245. }
  10246. }
  10247. #if !defined(NO_FILES)
  10248. static void
  10249. send_options(struct mg_connection *conn)
  10250. {
  10251. char date[64];
  10252. time_t curtime = time(NULL);
  10253. if (!conn) {
  10254. return;
  10255. }
  10256. conn->status_code = 200;
  10257. conn->must_close = 1;
  10258. gmt_time_string(date, sizeof(date), &curtime);
  10259. /* We do not set a "Cache-Control" header here, but leave the default.
  10260. * Since browsers do not send an OPTIONS request, we can not test the
  10261. * effect anyway. */
  10262. mg_printf(conn,
  10263. "HTTP/1.1 200 OK\r\n"
  10264. "Date: %s\r\n"
  10265. "Connection: %s\r\n"
  10266. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10267. "PROPFIND, MKCOL\r\n"
  10268. "DAV: 1\r\n",
  10269. date,
  10270. suggest_connection_header(conn));
  10271. send_additional_header(conn);
  10272. mg_printf(conn, "\r\n");
  10273. }
  10274. /* Writes PROPFIND properties for a collection element */
  10275. static int
  10276. print_props(struct mg_connection *conn,
  10277. const char *uri,
  10278. const char *name,
  10279. struct mg_file_stat *filep)
  10280. {
  10281. size_t href_size, i, j;
  10282. int len;
  10283. char *href, mtime[64];
  10284. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10285. return 0;
  10286. }
  10287. /* Estimate worst case size for encoding */
  10288. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10289. href = (char *)mg_malloc(href_size);
  10290. if (href == NULL) {
  10291. return 0;
  10292. }
  10293. len = mg_url_encode(uri, href, href_size);
  10294. if (len >= 0) {
  10295. /* Append an extra string */
  10296. mg_url_encode(name, href + len, href_size - (size_t)len);
  10297. }
  10298. /* Directory separator should be preserved. */
  10299. for (i = j = 0; href[i]; j++) {
  10300. if (!strncmp(href + i, "%2f", 3)) {
  10301. href[j] = '/';
  10302. i += 3;
  10303. } else {
  10304. href[j] = href[i++];
  10305. }
  10306. }
  10307. href[j] = '\0';
  10308. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10309. mg_printf(conn,
  10310. "<d:response>"
  10311. "<d:href>%s</d:href>"
  10312. "<d:propstat>"
  10313. "<d:prop>"
  10314. "<d:resourcetype>%s</d:resourcetype>"
  10315. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10316. "<d:getlastmodified>%s</d:getlastmodified>"
  10317. "</d:prop>"
  10318. "<d:status>HTTP/1.1 200 OK</d:status>"
  10319. "</d:propstat>"
  10320. "</d:response>\n",
  10321. href,
  10322. filep->is_directory ? "<d:collection/>" : "",
  10323. filep->size,
  10324. mtime);
  10325. mg_free(href);
  10326. return 1;
  10327. }
  10328. static int
  10329. print_dav_dir_entry(struct de *de, void *data)
  10330. {
  10331. struct mg_connection *conn = (struct mg_connection *)data;
  10332. if (!de || !conn
  10333. || !print_props(
  10334. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10335. return -1;
  10336. }
  10337. return 0;
  10338. }
  10339. static void
  10340. handle_propfind(struct mg_connection *conn,
  10341. const char *path,
  10342. struct mg_file_stat *filep)
  10343. {
  10344. const char *depth = mg_get_header(conn, "Depth");
  10345. char date[64];
  10346. time_t curtime = time(NULL);
  10347. gmt_time_string(date, sizeof(date), &curtime);
  10348. if (!conn || !path || !filep || !conn->dom_ctx) {
  10349. return;
  10350. }
  10351. conn->must_close = 1;
  10352. conn->status_code = 207;
  10353. mg_printf(conn,
  10354. "HTTP/1.1 207 Multi-Status\r\n"
  10355. "Date: %s\r\n",
  10356. date);
  10357. send_static_cache_header(conn);
  10358. send_additional_header(conn);
  10359. mg_printf(conn,
  10360. "Connection: %s\r\n"
  10361. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10362. suggest_connection_header(conn));
  10363. mg_printf(conn,
  10364. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10365. "<d:multistatus xmlns:d='DAV:'>\n");
  10366. /* Print properties for the requested resource itself */
  10367. print_props(conn, conn->request_info.local_uri, "", filep);
  10368. /* If it is a directory, print directory entries too if Depth is not 0
  10369. */
  10370. if (filep->is_directory
  10371. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10372. "yes")
  10373. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10374. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10375. }
  10376. mg_printf(conn, "%s\n", "</d:multistatus>");
  10377. }
  10378. #endif
  10379. void
  10380. mg_lock_connection(struct mg_connection *conn)
  10381. {
  10382. if (conn) {
  10383. (void)pthread_mutex_lock(&conn->mutex);
  10384. }
  10385. }
  10386. void
  10387. mg_unlock_connection(struct mg_connection *conn)
  10388. {
  10389. if (conn) {
  10390. (void)pthread_mutex_unlock(&conn->mutex);
  10391. }
  10392. }
  10393. void
  10394. mg_lock_context(struct mg_context *ctx)
  10395. {
  10396. if (ctx) {
  10397. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10398. }
  10399. }
  10400. void
  10401. mg_unlock_context(struct mg_context *ctx)
  10402. {
  10403. if (ctx) {
  10404. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10405. }
  10406. }
  10407. #if defined(USE_LUA)
  10408. #include "mod_lua.inl"
  10409. #endif /* USE_LUA */
  10410. #if defined(USE_DUKTAPE)
  10411. #include "mod_duktape.inl"
  10412. #endif /* USE_DUKTAPE */
  10413. #if defined(USE_WEBSOCKET)
  10414. #if !defined(NO_SSL_DL)
  10415. #define SHA_API static
  10416. #include "sha1.inl"
  10417. #endif
  10418. static int
  10419. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10420. {
  10421. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10422. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10423. SHA_CTX sha_ctx;
  10424. int truncated;
  10425. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10426. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10427. if (truncated) {
  10428. conn->must_close = 1;
  10429. return 0;
  10430. }
  10431. DEBUG_TRACE("%s", "Send websocket handshake");
  10432. SHA1_Init(&sha_ctx);
  10433. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10434. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10435. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10436. mg_printf(conn,
  10437. "HTTP/1.1 101 Switching Protocols\r\n"
  10438. "Upgrade: websocket\r\n"
  10439. "Connection: Upgrade\r\n"
  10440. "Sec-WebSocket-Accept: %s\r\n",
  10441. b64_sha);
  10442. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10443. mg_printf(conn,
  10444. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10445. conn->request_info.acceptedWebSocketSubprotocol);
  10446. } else {
  10447. mg_printf(conn, "%s", "\r\n");
  10448. }
  10449. return 1;
  10450. }
  10451. #if !defined(MG_MAX_UNANSWERED_PING)
  10452. /* Configuration of the maximum number of websocket PINGs that might
  10453. * stay unanswered before the connection is considered broken.
  10454. * Note: The name of this define may still change (until it is
  10455. * defined as a compile parameter in a documentation).
  10456. */
  10457. #define MG_MAX_UNANSWERED_PING (5)
  10458. #endif
  10459. static void
  10460. read_websocket(struct mg_connection *conn,
  10461. mg_websocket_data_handler ws_data_handler,
  10462. void *callback_data)
  10463. {
  10464. /* Pointer to the beginning of the portion of the incoming websocket
  10465. * message queue.
  10466. * The original websocket upgrade request is never removed, so the queue
  10467. * begins after it. */
  10468. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10469. int n, error, exit_by_callback;
  10470. int ret;
  10471. /* body_len is the length of the entire queue in bytes
  10472. * len is the length of the current message
  10473. * data_len is the length of the current message's data payload
  10474. * header_len is the length of the current message's header */
  10475. size_t i, len, mask_len = 0, header_len, body_len;
  10476. uint64_t data_len = 0;
  10477. /* "The masking key is a 32-bit value chosen at random by the client."
  10478. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10479. */
  10480. unsigned char mask[4];
  10481. /* data points to the place where the message is stored when passed to
  10482. * the websocket_data callback. This is either mem on the stack, or a
  10483. * dynamically allocated buffer if it is too large. */
  10484. unsigned char mem[4096];
  10485. unsigned char mop; /* mask flag and opcode */
  10486. /* Variables used for connection monitoring */
  10487. double timeout = -1.0;
  10488. int enable_ping_pong = 0;
  10489. int ping_count = 0;
  10490. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10491. enable_ping_pong =
  10492. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10493. "yes");
  10494. }
  10495. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10496. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10497. }
  10498. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10499. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10500. }
  10501. /* Enter data processing loop */
  10502. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10503. conn->request_info.remote_addr,
  10504. conn->request_info.remote_port);
  10505. conn->in_websocket_handling = 1;
  10506. mg_set_thread_name("wsock");
  10507. /* Loop continuously, reading messages from the socket, invoking the
  10508. * callback, and waiting repeatedly until an error occurs. */
  10509. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10510. header_len = 0;
  10511. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10512. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10513. len = buf[1] & 127;
  10514. mask_len = (buf[1] & 128) ? 4 : 0;
  10515. if ((len < 126) && (body_len >= mask_len)) {
  10516. /* inline 7-bit length field */
  10517. data_len = len;
  10518. header_len = 2 + mask_len;
  10519. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10520. /* 16-bit length field */
  10521. header_len = 4 + mask_len;
  10522. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10523. } else if (body_len >= (10 + mask_len)) {
  10524. /* 64-bit length field */
  10525. uint32_t l1, l2;
  10526. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10527. memcpy(&l2, &buf[6], 4);
  10528. header_len = 10 + mask_len;
  10529. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10530. if (data_len > (uint64_t)0x7FFF0000ul) {
  10531. /* no can do */
  10532. mg_cry_internal(
  10533. conn,
  10534. "%s",
  10535. "websocket out of memory; closing connection");
  10536. break;
  10537. }
  10538. }
  10539. }
  10540. if ((header_len > 0) && (body_len >= header_len)) {
  10541. /* Allocate space to hold websocket payload */
  10542. unsigned char *data = mem;
  10543. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10544. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10545. conn->phys_ctx);
  10546. if (data == NULL) {
  10547. /* Allocation failed, exit the loop and then close the
  10548. * connection */
  10549. mg_cry_internal(
  10550. conn,
  10551. "%s",
  10552. "websocket out of memory; closing connection");
  10553. break;
  10554. }
  10555. }
  10556. /* Copy the mask before we shift the queue and destroy it */
  10557. if (mask_len > 0) {
  10558. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10559. } else {
  10560. memset(mask, 0, sizeof(mask));
  10561. }
  10562. /* Read frame payload from the first message in the queue into
  10563. * data and advance the queue by moving the memory in place. */
  10564. DEBUG_ASSERT(body_len >= header_len);
  10565. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10566. mop = buf[0]; /* current mask and opcode */
  10567. /* Overflow case */
  10568. len = body_len - header_len;
  10569. memcpy(data, buf + header_len, len);
  10570. error = 0;
  10571. while ((uint64_t)len < data_len) {
  10572. n = pull_inner(NULL,
  10573. conn,
  10574. (char *)(data + len),
  10575. (int)(data_len - len),
  10576. timeout);
  10577. if (n <= -2) {
  10578. error = 1;
  10579. break;
  10580. } else if (n > 0) {
  10581. len += (size_t)n;
  10582. } else {
  10583. /* Timeout: should retry */
  10584. /* TODO: retry condition */
  10585. }
  10586. }
  10587. if (error) {
  10588. mg_cry_internal(
  10589. conn,
  10590. "%s",
  10591. "Websocket pull failed; closing connection");
  10592. if (data != mem) {
  10593. mg_free(data);
  10594. }
  10595. break;
  10596. }
  10597. conn->data_len = conn->request_len;
  10598. } else {
  10599. mop = buf[0]; /* current mask and opcode, overwritten by
  10600. * memmove() */
  10601. /* Length of the message being read at the front of the
  10602. * queue. Cast to 31 bit is OK, since we limited
  10603. * data_len before. */
  10604. len = (size_t)data_len + header_len;
  10605. /* Copy the data payload into the data pointer for the
  10606. * callback. Cast to 31 bit is OK, since we
  10607. * limited data_len */
  10608. memcpy(data, buf + header_len, (size_t)data_len);
  10609. /* Move the queue forward len bytes */
  10610. memmove(buf, buf + len, body_len - len);
  10611. /* Mark the queue as advanced */
  10612. conn->data_len -= (int)len;
  10613. }
  10614. /* Apply mask if necessary */
  10615. if (mask_len > 0) {
  10616. for (i = 0; i < (size_t)data_len; i++) {
  10617. data[i] ^= mask[i & 3];
  10618. }
  10619. }
  10620. exit_by_callback = 0;
  10621. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10622. /* filter PONG messages */
  10623. DEBUG_TRACE("PONG from %s:%u",
  10624. conn->request_info.remote_addr,
  10625. conn->request_info.remote_port);
  10626. /* No unanwered PINGs left */
  10627. ping_count = 0;
  10628. } else if (enable_ping_pong
  10629. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10630. /* reply PING messages */
  10631. DEBUG_TRACE("Reply PING from %s:%u",
  10632. conn->request_info.remote_addr,
  10633. conn->request_info.remote_port);
  10634. ret = mg_websocket_write(conn,
  10635. MG_WEBSOCKET_OPCODE_PONG,
  10636. (char *)data,
  10637. (size_t)data_len);
  10638. if (ret <= 0) {
  10639. /* Error: send failed */
  10640. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10641. break;
  10642. }
  10643. } else {
  10644. /* Exit the loop if callback signals to exit (server side),
  10645. * or "connection close" opcode received (client side). */
  10646. if ((ws_data_handler != NULL)
  10647. && !ws_data_handler(conn,
  10648. mop,
  10649. (char *)data,
  10650. (size_t)data_len,
  10651. callback_data)) {
  10652. exit_by_callback = 1;
  10653. }
  10654. }
  10655. /* It a buffer has been allocated, free it again */
  10656. if (data != mem) {
  10657. mg_free(data);
  10658. }
  10659. if (exit_by_callback) {
  10660. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10661. conn->request_info.remote_addr,
  10662. conn->request_info.remote_port);
  10663. break;
  10664. }
  10665. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10666. /* Opcode == 8, connection close */
  10667. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10668. conn->request_info.remote_addr,
  10669. conn->request_info.remote_port);
  10670. break;
  10671. }
  10672. /* Not breaking the loop, process next websocket frame. */
  10673. } else {
  10674. /* Read from the socket into the next available location in the
  10675. * message queue. */
  10676. n = pull_inner(NULL,
  10677. conn,
  10678. conn->buf + conn->data_len,
  10679. conn->buf_size - conn->data_len,
  10680. timeout);
  10681. if (n <= -2) {
  10682. /* Error, no bytes read */
  10683. DEBUG_TRACE("PULL from %s:%u failed",
  10684. conn->request_info.remote_addr,
  10685. conn->request_info.remote_port);
  10686. break;
  10687. }
  10688. if (n > 0) {
  10689. conn->data_len += n;
  10690. /* Reset open PING count */
  10691. ping_count = 0;
  10692. } else {
  10693. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10694. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10695. /* Stop sending PING */
  10696. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10697. "- closing connection",
  10698. ping_count,
  10699. conn->request_info.remote_addr,
  10700. conn->request_info.remote_port);
  10701. break;
  10702. }
  10703. if (enable_ping_pong) {
  10704. /* Send Websocket PING message */
  10705. DEBUG_TRACE("PING to %s:%u",
  10706. conn->request_info.remote_addr,
  10707. conn->request_info.remote_port);
  10708. ret = mg_websocket_write(conn,
  10709. MG_WEBSOCKET_OPCODE_PING,
  10710. NULL,
  10711. 0);
  10712. if (ret <= 0) {
  10713. /* Error: send failed */
  10714. DEBUG_TRACE("Send PING failed (%i)", ret);
  10715. break;
  10716. }
  10717. ping_count++;
  10718. }
  10719. }
  10720. /* Timeout: should retry */
  10721. /* TODO: get timeout def */
  10722. }
  10723. }
  10724. }
  10725. /* Leave data processing loop */
  10726. mg_set_thread_name("worker");
  10727. conn->in_websocket_handling = 0;
  10728. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10729. conn->request_info.remote_addr,
  10730. conn->request_info.remote_port);
  10731. }
  10732. static int
  10733. mg_websocket_write_exec(struct mg_connection *conn,
  10734. int opcode,
  10735. const char *data,
  10736. size_t dataLen,
  10737. uint32_t masking_key)
  10738. {
  10739. unsigned char header[14];
  10740. size_t headerLen;
  10741. int retval;
  10742. #if defined(GCC_DIAGNOSTIC)
  10743. /* Disable spurious conversion warning for GCC */
  10744. #pragma GCC diagnostic push
  10745. #pragma GCC diagnostic ignored "-Wconversion"
  10746. #endif
  10747. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10748. #if defined(GCC_DIAGNOSTIC)
  10749. #pragma GCC diagnostic pop
  10750. #endif
  10751. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10752. if (dataLen < 126) {
  10753. /* inline 7-bit length field */
  10754. header[1] = (unsigned char)dataLen;
  10755. headerLen = 2;
  10756. } else if (dataLen <= 0xFFFF) {
  10757. /* 16-bit length field */
  10758. uint16_t len = htons((uint16_t)dataLen);
  10759. header[1] = 126;
  10760. memcpy(header + 2, &len, 2);
  10761. headerLen = 4;
  10762. } else {
  10763. /* 64-bit length field */
  10764. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10765. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10766. header[1] = 127;
  10767. memcpy(header + 2, &len1, 4);
  10768. memcpy(header + 6, &len2, 4);
  10769. headerLen = 10;
  10770. }
  10771. if (masking_key) {
  10772. /* add mask */
  10773. header[1] |= 0x80;
  10774. memcpy(header + headerLen, &masking_key, 4);
  10775. headerLen += 4;
  10776. }
  10777. /* Note that POSIX/Winsock's send() is threadsafe
  10778. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10779. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10780. * push(), although that is only a problem if the packet is large or
  10781. * outgoing buffer is full). */
  10782. /* TODO: Check if this lock should be moved to user land.
  10783. * Currently the server sets this lock for websockets, but
  10784. * not for any other connection. It must be set for every
  10785. * conn read/written by more than one thread, no matter if
  10786. * it is a websocket or regular connection. */
  10787. (void)mg_lock_connection(conn);
  10788. retval = mg_write(conn, header, headerLen);
  10789. if (retval != (int)headerLen) {
  10790. /* Did not send complete header */
  10791. retval = -1;
  10792. } else {
  10793. if (dataLen > 0) {
  10794. retval = mg_write(conn, data, dataLen);
  10795. }
  10796. /* if dataLen == 0, the header length (2) is returned */
  10797. }
  10798. /* TODO: Remove this unlock as well, when lock is removed. */
  10799. mg_unlock_connection(conn);
  10800. return retval;
  10801. }
  10802. int
  10803. mg_websocket_write(struct mg_connection *conn,
  10804. int opcode,
  10805. const char *data,
  10806. size_t dataLen)
  10807. {
  10808. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10809. }
  10810. static void
  10811. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10812. {
  10813. size_t i = 0;
  10814. i = 0;
  10815. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10816. /* Convert in 32 bit words, if data is 4 byte aligned */
  10817. while (i < (in_len - 3)) {
  10818. *(uint32_t *)(void *)(out + i) =
  10819. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10820. i += 4;
  10821. }
  10822. }
  10823. if (i != in_len) {
  10824. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10825. while (i < in_len) {
  10826. *(uint8_t *)(void *)(out + i) =
  10827. *(uint8_t *)(void *)(in + i)
  10828. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10829. i++;
  10830. }
  10831. }
  10832. }
  10833. int
  10834. mg_websocket_client_write(struct mg_connection *conn,
  10835. int opcode,
  10836. const char *data,
  10837. size_t dataLen)
  10838. {
  10839. int retval = -1;
  10840. char *masked_data =
  10841. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10842. uint32_t masking_key = 0;
  10843. if (masked_data == NULL) {
  10844. /* Return -1 in an error case */
  10845. mg_cry_internal(conn,
  10846. "%s",
  10847. "Cannot allocate buffer for masked websocket response: "
  10848. "Out of memory");
  10849. return -1;
  10850. }
  10851. do {
  10852. /* Get a masking key - but not 0 */
  10853. masking_key = (uint32_t)get_random();
  10854. } while (masking_key == 0);
  10855. mask_data(data, dataLen, masking_key, masked_data);
  10856. retval = mg_websocket_write_exec(
  10857. conn, opcode, masked_data, dataLen, masking_key);
  10858. mg_free(masked_data);
  10859. return retval;
  10860. }
  10861. static void
  10862. handle_websocket_request(struct mg_connection *conn,
  10863. const char *path,
  10864. int is_callback_resource,
  10865. struct mg_websocket_subprotocols *subprotocols,
  10866. mg_websocket_connect_handler ws_connect_handler,
  10867. mg_websocket_ready_handler ws_ready_handler,
  10868. mg_websocket_data_handler ws_data_handler,
  10869. mg_websocket_close_handler ws_close_handler,
  10870. void *cbData)
  10871. {
  10872. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10873. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10874. ptrdiff_t lua_websock = 0;
  10875. #if !defined(USE_LUA)
  10876. (void)path;
  10877. #endif
  10878. /* Step 1: Check websocket protocol version. */
  10879. /* Step 1.1: Check Sec-WebSocket-Key. */
  10880. if (!websock_key) {
  10881. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10882. * requires a Sec-WebSocket-Key header.
  10883. */
  10884. /* It could be the hixie draft version
  10885. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10886. */
  10887. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10888. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10889. char key3[8];
  10890. if ((key1 != NULL) && (key2 != NULL)) {
  10891. /* This version uses 8 byte body data in a GET request */
  10892. conn->content_len = 8;
  10893. if (8 == mg_read(conn, key3, 8)) {
  10894. /* This is the hixie version */
  10895. mg_send_http_error(conn,
  10896. 426,
  10897. "%s",
  10898. "Protocol upgrade to RFC 6455 required");
  10899. return;
  10900. }
  10901. }
  10902. /* This is an unknown version */
  10903. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10904. return;
  10905. }
  10906. /* Step 1.2: Check websocket protocol version. */
  10907. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10908. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10909. /* Reject wrong versions */
  10910. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10911. return;
  10912. }
  10913. /* Step 1.3: Could check for "Host", but we do not really nead this
  10914. * value for anything, so just ignore it. */
  10915. /* Step 2: If a callback is responsible, call it. */
  10916. if (is_callback_resource) {
  10917. /* Step 2.1 check and select subprotocol */
  10918. const char *protocols[64]; // max 64 headers
  10919. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10920. "Sec-WebSocket-Protocol",
  10921. protocols,
  10922. 64);
  10923. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10924. int cnt = 0;
  10925. int idx;
  10926. unsigned long len;
  10927. const char *sep, *curSubProtocol,
  10928. *acceptedWebSocketSubprotocol = NULL;
  10929. /* look for matching subprotocol */
  10930. do {
  10931. const char *protocol = protocols[cnt];
  10932. do {
  10933. sep = strchr(protocol, ',');
  10934. curSubProtocol = protocol;
  10935. len = sep ? (unsigned long)(sep - protocol)
  10936. : (unsigned long)strlen(protocol);
  10937. while (sep && isspace((unsigned char)*++sep))
  10938. ; // ignore leading whitespaces
  10939. protocol = sep;
  10940. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10941. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10942. && (strncmp(curSubProtocol,
  10943. subprotocols->subprotocols[idx],
  10944. len)
  10945. == 0)) {
  10946. acceptedWebSocketSubprotocol =
  10947. subprotocols->subprotocols[idx];
  10948. break;
  10949. }
  10950. }
  10951. } while (sep && !acceptedWebSocketSubprotocol);
  10952. } while (++cnt < nbSubprotocolHeader
  10953. && !acceptedWebSocketSubprotocol);
  10954. conn->request_info.acceptedWebSocketSubprotocol =
  10955. acceptedWebSocketSubprotocol;
  10956. } else if (nbSubprotocolHeader > 0) {
  10957. /* keep legacy behavior */
  10958. const char *protocol = protocols[0];
  10959. /* The protocol is a comma separated list of names. */
  10960. /* The server must only return one value from this list. */
  10961. /* First check if it is a list or just a single value. */
  10962. const char *sep = strrchr(protocol, ',');
  10963. if (sep == NULL) {
  10964. /* Just a single protocol -> accept it. */
  10965. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10966. } else {
  10967. /* Multiple protocols -> accept the last one. */
  10968. /* This is just a quick fix if the client offers multiple
  10969. * protocols. The handler should have a list of accepted
  10970. * protocols on his own
  10971. * and use it to select one protocol among those the client
  10972. * has
  10973. * offered.
  10974. */
  10975. while (isspace((unsigned char)*++sep)) {
  10976. ; /* ignore leading whitespaces */
  10977. }
  10978. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10979. }
  10980. }
  10981. if ((ws_connect_handler != NULL)
  10982. && (ws_connect_handler(conn, cbData) != 0)) {
  10983. /* C callback has returned non-zero, do not proceed with
  10984. * handshake.
  10985. */
  10986. /* Note that C callbacks are no longer called when Lua is
  10987. * responsible, so C can no longer filter callbacks for Lua. */
  10988. return;
  10989. }
  10990. }
  10991. #if defined(USE_LUA)
  10992. /* Step 3: No callback. Check if Lua is responsible. */
  10993. else {
  10994. /* Step 3.1: Check if Lua is responsible. */
  10995. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10996. lua_websock = match_prefix(
  10997. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10998. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10999. path);
  11000. }
  11001. if (lua_websock) {
  11002. /* Step 3.2: Lua is responsible: call it. */
  11003. conn->lua_websocket_state = lua_websocket_new(path, conn);
  11004. if (!conn->lua_websocket_state) {
  11005. /* Lua rejected the new client */
  11006. return;
  11007. }
  11008. }
  11009. }
  11010. #endif
  11011. /* Step 4: Check if there is a responsible websocket handler. */
  11012. if (!is_callback_resource && !lua_websock) {
  11013. /* There is no callback, and Lua is not responsible either. */
  11014. /* Reply with a 404 Not Found. We are still at a standard
  11015. * HTTP request here, before the websocket handshake, so
  11016. * we can still send standard HTTP error replies. */
  11017. mg_send_http_error(conn, 404, "%s", "Not found");
  11018. return;
  11019. }
  11020. /* Step 5: The websocket connection has been accepted */
  11021. if (!send_websocket_handshake(conn, websock_key)) {
  11022. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  11023. return;
  11024. }
  11025. /* Step 6: Call the ready handler */
  11026. if (is_callback_resource) {
  11027. if (ws_ready_handler != NULL) {
  11028. ws_ready_handler(conn, cbData);
  11029. }
  11030. #if defined(USE_LUA)
  11031. } else if (lua_websock) {
  11032. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  11033. /* the ready handler returned false */
  11034. return;
  11035. }
  11036. #endif
  11037. }
  11038. /* Step 7: Enter the read loop */
  11039. if (is_callback_resource) {
  11040. read_websocket(conn, ws_data_handler, cbData);
  11041. #if defined(USE_LUA)
  11042. } else if (lua_websock) {
  11043. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11044. #endif
  11045. }
  11046. /* Step 8: Call the close handler */
  11047. if (ws_close_handler) {
  11048. ws_close_handler(conn, cbData);
  11049. }
  11050. }
  11051. static int
  11052. is_websocket_protocol(const struct mg_connection *conn)
  11053. {
  11054. const char *upgrade, *connection;
  11055. /* A websocket protocoll has the following HTTP headers:
  11056. *
  11057. * Connection: Upgrade
  11058. * Upgrade: Websocket
  11059. */
  11060. upgrade = mg_get_header(conn, "Upgrade");
  11061. if (upgrade == NULL) {
  11062. return 0; /* fail early, don't waste time checking other header
  11063. * fields
  11064. */
  11065. }
  11066. if (!mg_strcasestr(upgrade, "websocket")) {
  11067. return 0;
  11068. }
  11069. connection = mg_get_header(conn, "Connection");
  11070. if (connection == NULL) {
  11071. return 0;
  11072. }
  11073. if (!mg_strcasestr(connection, "upgrade")) {
  11074. return 0;
  11075. }
  11076. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11077. * "Sec-WebSocket-Version" are also required.
  11078. * Don't check them here, since even an unsupported websocket protocol
  11079. * request still IS a websocket request (in contrast to a standard HTTP
  11080. * request). It will fail later in handle_websocket_request.
  11081. */
  11082. return 1;
  11083. }
  11084. #endif /* !USE_WEBSOCKET */
  11085. static int
  11086. isbyte(int n)
  11087. {
  11088. return (n >= 0) && (n <= 255);
  11089. }
  11090. static int
  11091. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11092. {
  11093. int n, a, b, c, d, slash = 32, len = 0;
  11094. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11095. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11096. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11097. && (slash < 33)) {
  11098. len = n;
  11099. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11100. | (uint32_t)d;
  11101. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11102. }
  11103. return len;
  11104. }
  11105. static int
  11106. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11107. {
  11108. int throttle = 0;
  11109. struct vec vec, val;
  11110. uint32_t net, mask;
  11111. char mult;
  11112. double v;
  11113. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11114. mult = ',';
  11115. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11116. || (v < 0)
  11117. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11118. && (mult != ','))) {
  11119. continue;
  11120. }
  11121. v *= (lowercase(&mult) == 'k')
  11122. ? 1024
  11123. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11124. if (vec.len == 1 && vec.ptr[0] == '*') {
  11125. throttle = (int)v;
  11126. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11127. if ((remote_ip & mask) == net) {
  11128. throttle = (int)v;
  11129. }
  11130. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11131. throttle = (int)v;
  11132. }
  11133. }
  11134. return throttle;
  11135. }
  11136. static uint32_t
  11137. get_remote_ip(const struct mg_connection *conn)
  11138. {
  11139. if (!conn) {
  11140. return 0;
  11141. }
  11142. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11143. }
  11144. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11145. #include "handle_form.inl"
  11146. #if defined(MG_LEGACY_INTERFACE)
  11147. /* Implement the deprecated mg_upload function by calling the new
  11148. * mg_handle_form_request function. While mg_upload could only handle
  11149. * HTML forms sent as POST request in multipart/form-data format
  11150. * containing only file input elements, mg_handle_form_request can
  11151. * handle all form input elements and all standard request methods. */
  11152. struct mg_upload_user_data {
  11153. struct mg_connection *conn;
  11154. const char *destination_dir;
  11155. int num_uploaded_files;
  11156. };
  11157. /* Helper function for deprecated mg_upload. */
  11158. static int
  11159. mg_upload_field_found(const char *key,
  11160. const char *filename,
  11161. char *path,
  11162. size_t pathlen,
  11163. void *user_data)
  11164. {
  11165. int truncated = 0;
  11166. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11167. (void)key;
  11168. if (!filename) {
  11169. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11170. return FORM_FIELD_STORAGE_ABORT;
  11171. }
  11172. mg_snprintf(fud->conn,
  11173. &truncated,
  11174. path,
  11175. pathlen - 1,
  11176. "%s/%s",
  11177. fud->destination_dir,
  11178. filename);
  11179. if (truncated) {
  11180. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11181. return FORM_FIELD_STORAGE_ABORT;
  11182. }
  11183. return FORM_FIELD_STORAGE_STORE;
  11184. }
  11185. /* Helper function for deprecated mg_upload. */
  11186. static int
  11187. mg_upload_field_get(const char *key,
  11188. const char *value,
  11189. size_t value_size,
  11190. void *user_data)
  11191. {
  11192. /* Function should never be called */
  11193. (void)key;
  11194. (void)value;
  11195. (void)value_size;
  11196. (void)user_data;
  11197. return 0;
  11198. }
  11199. /* Helper function for deprecated mg_upload. */
  11200. static int
  11201. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11202. {
  11203. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11204. (void)file_size;
  11205. fud->num_uploaded_files++;
  11206. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11207. return 0;
  11208. }
  11209. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11210. int
  11211. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11212. {
  11213. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11214. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11215. mg_upload_field_get,
  11216. mg_upload_field_stored,
  11217. 0};
  11218. int ret;
  11219. fdh.user_data = (void *)&fud;
  11220. ret = mg_handle_form_request(conn, &fdh);
  11221. if (ret < 0) {
  11222. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11223. }
  11224. return fud.num_uploaded_files;
  11225. }
  11226. #endif
  11227. static int
  11228. get_first_ssl_listener_index(const struct mg_context *ctx)
  11229. {
  11230. unsigned int i;
  11231. int idx = -1;
  11232. if (ctx) {
  11233. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11234. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11235. }
  11236. }
  11237. return idx;
  11238. }
  11239. /* Return host (without port) */
  11240. /* Use mg_free to free the result */
  11241. static const char *
  11242. alloc_get_host(struct mg_connection *conn)
  11243. {
  11244. char buf[1025];
  11245. size_t buflen = sizeof(buf);
  11246. const char *host_header = get_header(conn->request_info.http_headers,
  11247. conn->request_info.num_headers,
  11248. "Host");
  11249. char *host;
  11250. if (host_header != NULL) {
  11251. char *pos;
  11252. /* Create a local copy of the "Host" header, since it might be
  11253. * modified here. */
  11254. mg_strlcpy(buf, host_header, buflen);
  11255. buf[buflen - 1] = '\0';
  11256. host = buf;
  11257. while (isspace((unsigned char)*host)) {
  11258. host++;
  11259. }
  11260. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11261. * is found. */
  11262. if (*host == '[') {
  11263. pos = strchr(host, ']');
  11264. if (!pos) {
  11265. /* Malformed hostname starts with '[', but no ']' found */
  11266. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11267. return NULL;
  11268. }
  11269. /* terminate after ']' */
  11270. pos[1] = 0;
  11271. } else {
  11272. /* Otherwise, a ':' separates hostname and port number */
  11273. pos = strchr(host, ':');
  11274. if (pos != NULL) {
  11275. *pos = '\0';
  11276. }
  11277. }
  11278. if (conn->ssl) {
  11279. /* This is a HTTPS connection, maybe we have a hostname
  11280. * from SNI (set in ssl_servername_callback). */
  11281. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11282. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11283. /* We are not using the default domain */
  11284. if (mg_strcasecmp(host, sslhost)) {
  11285. /* Mismatch between SNI domain and HTTP domain */
  11286. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11287. sslhost,
  11288. host);
  11289. return NULL;
  11290. }
  11291. }
  11292. DEBUG_TRACE("HTTPS Host: %s", host);
  11293. } else {
  11294. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11295. while (dom) {
  11296. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11297. /* Found matching domain */
  11298. DEBUG_TRACE("HTTP domain %s found",
  11299. dom->config[AUTHENTICATION_DOMAIN]);
  11300. /* TODO: Check if this is a HTTP or HTTPS domain */
  11301. conn->dom_ctx = dom;
  11302. break;
  11303. }
  11304. dom = dom->next;
  11305. }
  11306. DEBUG_TRACE("HTTP Host: %s", host);
  11307. }
  11308. } else {
  11309. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11310. host = buf;
  11311. DEBUG_TRACE("IP: %s", host);
  11312. }
  11313. return mg_strdup_ctx(host, conn->phys_ctx);
  11314. }
  11315. static void
  11316. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11317. {
  11318. char target_url[MG_BUF_LEN];
  11319. int truncated = 0;
  11320. conn->must_close = 1;
  11321. /* Send host, port, uri and (if it exists) ?query_string */
  11322. if (conn->host) {
  11323. /* Use "308 Permanent Redirect" */
  11324. int redirect_code = 308;
  11325. /* Create target URL */
  11326. mg_snprintf(
  11327. conn,
  11328. &truncated,
  11329. target_url,
  11330. sizeof(target_url),
  11331. "https://%s:%d%s%s%s",
  11332. conn->host,
  11333. #if defined(USE_IPV6)
  11334. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11335. == AF_INET6)
  11336. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11337. .lsa.sin6.sin6_port)
  11338. :
  11339. #endif
  11340. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11341. .lsa.sin.sin_port),
  11342. conn->request_info.local_uri,
  11343. (conn->request_info.query_string == NULL) ? "" : "?",
  11344. (conn->request_info.query_string == NULL)
  11345. ? ""
  11346. : conn->request_info.query_string);
  11347. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11348. * is used as buffer size) */
  11349. if (truncated) {
  11350. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11351. return;
  11352. }
  11353. /* Use redirect helper function */
  11354. mg_send_http_redirect(conn, target_url, redirect_code);
  11355. }
  11356. }
  11357. static void
  11358. handler_info_acquire(struct mg_handler_info *handler_info)
  11359. {
  11360. pthread_mutex_lock(&handler_info->refcount_mutex);
  11361. handler_info->refcount++;
  11362. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11363. }
  11364. static void
  11365. handler_info_release(struct mg_handler_info *handler_info)
  11366. {
  11367. pthread_mutex_lock(&handler_info->refcount_mutex);
  11368. handler_info->refcount--;
  11369. pthread_cond_signal(&handler_info->refcount_cond);
  11370. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11371. }
  11372. static void
  11373. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11374. {
  11375. pthread_mutex_lock(&handler_info->refcount_mutex);
  11376. while (handler_info->refcount) {
  11377. pthread_cond_wait(&handler_info->refcount_cond,
  11378. &handler_info->refcount_mutex);
  11379. }
  11380. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11381. }
  11382. static void
  11383. mg_set_handler_type(struct mg_context *phys_ctx,
  11384. struct mg_domain_context *dom_ctx,
  11385. const char *uri,
  11386. int handler_type,
  11387. int is_delete_request,
  11388. mg_request_handler handler,
  11389. struct mg_websocket_subprotocols *subprotocols,
  11390. mg_websocket_connect_handler connect_handler,
  11391. mg_websocket_ready_handler ready_handler,
  11392. mg_websocket_data_handler data_handler,
  11393. mg_websocket_close_handler close_handler,
  11394. mg_authorization_handler auth_handler,
  11395. void *cbdata)
  11396. {
  11397. struct mg_handler_info *tmp_rh, **lastref;
  11398. size_t urilen = strlen(uri);
  11399. if (handler_type == WEBSOCKET_HANDLER) {
  11400. DEBUG_ASSERT(handler == NULL);
  11401. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11402. || ready_handler != NULL || data_handler != NULL
  11403. || close_handler != NULL);
  11404. DEBUG_ASSERT(auth_handler == NULL);
  11405. if (handler != NULL) {
  11406. return;
  11407. }
  11408. if (!is_delete_request && (connect_handler == NULL)
  11409. && (ready_handler == NULL) && (data_handler == NULL)
  11410. && (close_handler == NULL)) {
  11411. return;
  11412. }
  11413. if (auth_handler != NULL) {
  11414. return;
  11415. }
  11416. } else if (handler_type == REQUEST_HANDLER) {
  11417. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11418. && data_handler == NULL && close_handler == NULL);
  11419. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11420. DEBUG_ASSERT(auth_handler == NULL);
  11421. if ((connect_handler != NULL) || (ready_handler != NULL)
  11422. || (data_handler != NULL) || (close_handler != NULL)) {
  11423. return;
  11424. }
  11425. if (!is_delete_request && (handler == NULL)) {
  11426. return;
  11427. }
  11428. if (auth_handler != NULL) {
  11429. return;
  11430. }
  11431. } else { /* AUTH_HANDLER */
  11432. DEBUG_ASSERT(handler == NULL);
  11433. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11434. && data_handler == NULL && close_handler == NULL);
  11435. DEBUG_ASSERT(auth_handler != NULL);
  11436. if (handler != NULL) {
  11437. return;
  11438. }
  11439. if ((connect_handler != NULL) || (ready_handler != NULL)
  11440. || (data_handler != NULL) || (close_handler != NULL)) {
  11441. return;
  11442. }
  11443. if (!is_delete_request && (auth_handler == NULL)) {
  11444. return;
  11445. }
  11446. }
  11447. if (!phys_ctx || !dom_ctx) {
  11448. return;
  11449. }
  11450. mg_lock_context(phys_ctx);
  11451. /* first try to find an existing handler */
  11452. lastref = &(dom_ctx->handlers);
  11453. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11454. if (tmp_rh->handler_type == handler_type) {
  11455. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11456. if (!is_delete_request) {
  11457. /* update existing handler */
  11458. if (handler_type == REQUEST_HANDLER) {
  11459. /* Wait for end of use before updating */
  11460. handler_info_wait_unused(tmp_rh);
  11461. /* Ok, the handler is no more use -> Update it */
  11462. tmp_rh->handler = handler;
  11463. } else if (handler_type == WEBSOCKET_HANDLER) {
  11464. tmp_rh->subprotocols = subprotocols;
  11465. tmp_rh->connect_handler = connect_handler;
  11466. tmp_rh->ready_handler = ready_handler;
  11467. tmp_rh->data_handler = data_handler;
  11468. tmp_rh->close_handler = close_handler;
  11469. } else { /* AUTH_HANDLER */
  11470. tmp_rh->auth_handler = auth_handler;
  11471. }
  11472. tmp_rh->cbdata = cbdata;
  11473. } else {
  11474. /* remove existing handler */
  11475. if (handler_type == REQUEST_HANDLER) {
  11476. /* Wait for end of use before removing */
  11477. handler_info_wait_unused(tmp_rh);
  11478. /* Ok, the handler is no more used -> Destroy resources
  11479. */
  11480. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11481. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11482. }
  11483. *lastref = tmp_rh->next;
  11484. mg_free(tmp_rh->uri);
  11485. mg_free(tmp_rh);
  11486. }
  11487. mg_unlock_context(phys_ctx);
  11488. return;
  11489. }
  11490. }
  11491. lastref = &(tmp_rh->next);
  11492. }
  11493. if (is_delete_request) {
  11494. /* no handler to set, this was a remove request to a non-existing
  11495. * handler */
  11496. mg_unlock_context(phys_ctx);
  11497. return;
  11498. }
  11499. tmp_rh =
  11500. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11501. 1,
  11502. phys_ctx);
  11503. if (tmp_rh == NULL) {
  11504. mg_unlock_context(phys_ctx);
  11505. mg_cry_internal(fc(phys_ctx),
  11506. "%s",
  11507. "Cannot create new request handler struct, OOM");
  11508. return;
  11509. }
  11510. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11511. if (!tmp_rh->uri) {
  11512. mg_unlock_context(phys_ctx);
  11513. mg_free(tmp_rh);
  11514. mg_cry_internal(fc(phys_ctx),
  11515. "%s",
  11516. "Cannot create new request handler struct, OOM");
  11517. return;
  11518. }
  11519. tmp_rh->uri_len = urilen;
  11520. if (handler_type == REQUEST_HANDLER) {
  11521. /* Init refcount mutex and condition */
  11522. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11523. mg_unlock_context(phys_ctx);
  11524. mg_free(tmp_rh);
  11525. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");
  11526. return;
  11527. }
  11528. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11529. mg_unlock_context(phys_ctx);
  11530. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11531. mg_free(tmp_rh);
  11532. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");
  11533. return;
  11534. }
  11535. tmp_rh->refcount = 0;
  11536. tmp_rh->handler = handler;
  11537. } else if (handler_type == WEBSOCKET_HANDLER) {
  11538. tmp_rh->subprotocols = subprotocols;
  11539. tmp_rh->connect_handler = connect_handler;
  11540. tmp_rh->ready_handler = ready_handler;
  11541. tmp_rh->data_handler = data_handler;
  11542. tmp_rh->close_handler = close_handler;
  11543. } else { /* AUTH_HANDLER */
  11544. tmp_rh->auth_handler = auth_handler;
  11545. }
  11546. tmp_rh->cbdata = cbdata;
  11547. tmp_rh->handler_type = handler_type;
  11548. tmp_rh->next = NULL;
  11549. *lastref = tmp_rh;
  11550. mg_unlock_context(phys_ctx);
  11551. }
  11552. void
  11553. mg_set_request_handler(struct mg_context *ctx,
  11554. const char *uri,
  11555. mg_request_handler handler,
  11556. void *cbdata)
  11557. {
  11558. mg_set_handler_type(ctx,
  11559. &(ctx->dd),
  11560. uri,
  11561. REQUEST_HANDLER,
  11562. handler == NULL,
  11563. handler,
  11564. NULL,
  11565. NULL,
  11566. NULL,
  11567. NULL,
  11568. NULL,
  11569. NULL,
  11570. cbdata);
  11571. }
  11572. void
  11573. mg_set_websocket_handler(struct mg_context *ctx,
  11574. const char *uri,
  11575. mg_websocket_connect_handler connect_handler,
  11576. mg_websocket_ready_handler ready_handler,
  11577. mg_websocket_data_handler data_handler,
  11578. mg_websocket_close_handler close_handler,
  11579. void *cbdata)
  11580. {
  11581. mg_set_websocket_handler_with_subprotocols(ctx,
  11582. uri,
  11583. NULL,
  11584. connect_handler,
  11585. ready_handler,
  11586. data_handler,
  11587. close_handler,
  11588. cbdata);
  11589. }
  11590. void
  11591. mg_set_websocket_handler_with_subprotocols(
  11592. struct mg_context *ctx,
  11593. const char *uri,
  11594. struct mg_websocket_subprotocols *subprotocols,
  11595. mg_websocket_connect_handler connect_handler,
  11596. mg_websocket_ready_handler ready_handler,
  11597. mg_websocket_data_handler data_handler,
  11598. mg_websocket_close_handler close_handler,
  11599. void *cbdata)
  11600. {
  11601. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11602. && (data_handler == NULL)
  11603. && (close_handler == NULL);
  11604. mg_set_handler_type(ctx,
  11605. &(ctx->dd),
  11606. uri,
  11607. WEBSOCKET_HANDLER,
  11608. is_delete_request,
  11609. NULL,
  11610. subprotocols,
  11611. connect_handler,
  11612. ready_handler,
  11613. data_handler,
  11614. close_handler,
  11615. NULL,
  11616. cbdata);
  11617. }
  11618. void
  11619. mg_set_auth_handler(struct mg_context *ctx,
  11620. const char *uri,
  11621. mg_authorization_handler handler,
  11622. void *cbdata)
  11623. {
  11624. mg_set_handler_type(ctx,
  11625. &(ctx->dd),
  11626. uri,
  11627. AUTH_HANDLER,
  11628. handler == NULL,
  11629. NULL,
  11630. NULL,
  11631. NULL,
  11632. NULL,
  11633. NULL,
  11634. NULL,
  11635. handler,
  11636. cbdata);
  11637. }
  11638. static int
  11639. get_request_handler(struct mg_connection *conn,
  11640. int handler_type,
  11641. mg_request_handler *handler,
  11642. struct mg_websocket_subprotocols **subprotocols,
  11643. mg_websocket_connect_handler *connect_handler,
  11644. mg_websocket_ready_handler *ready_handler,
  11645. mg_websocket_data_handler *data_handler,
  11646. mg_websocket_close_handler *close_handler,
  11647. mg_authorization_handler *auth_handler,
  11648. void **cbdata,
  11649. struct mg_handler_info **handler_info)
  11650. {
  11651. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11652. if (request_info) {
  11653. const char *uri = request_info->local_uri;
  11654. size_t urilen = strlen(uri);
  11655. struct mg_handler_info *tmp_rh;
  11656. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11657. return 0;
  11658. }
  11659. mg_lock_context(conn->phys_ctx);
  11660. /* first try for an exact match */
  11661. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11662. tmp_rh = tmp_rh->next) {
  11663. if (tmp_rh->handler_type == handler_type) {
  11664. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11665. if (handler_type == WEBSOCKET_HANDLER) {
  11666. *subprotocols = tmp_rh->subprotocols;
  11667. *connect_handler = tmp_rh->connect_handler;
  11668. *ready_handler = tmp_rh->ready_handler;
  11669. *data_handler = tmp_rh->data_handler;
  11670. *close_handler = tmp_rh->close_handler;
  11671. } else if (handler_type == REQUEST_HANDLER) {
  11672. *handler = tmp_rh->handler;
  11673. /* Acquire handler and give it back */
  11674. handler_info_acquire(tmp_rh);
  11675. *handler_info = tmp_rh;
  11676. } else { /* AUTH_HANDLER */
  11677. *auth_handler = tmp_rh->auth_handler;
  11678. }
  11679. *cbdata = tmp_rh->cbdata;
  11680. mg_unlock_context(conn->phys_ctx);
  11681. return 1;
  11682. }
  11683. }
  11684. }
  11685. /* next try for a partial match, we will accept uri/something */
  11686. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11687. tmp_rh = tmp_rh->next) {
  11688. if (tmp_rh->handler_type == handler_type) {
  11689. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11690. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11691. if (handler_type == WEBSOCKET_HANDLER) {
  11692. *subprotocols = tmp_rh->subprotocols;
  11693. *connect_handler = tmp_rh->connect_handler;
  11694. *ready_handler = tmp_rh->ready_handler;
  11695. *data_handler = tmp_rh->data_handler;
  11696. *close_handler = tmp_rh->close_handler;
  11697. } else if (handler_type == REQUEST_HANDLER) {
  11698. *handler = tmp_rh->handler;
  11699. /* Acquire handler and give it back */
  11700. handler_info_acquire(tmp_rh);
  11701. *handler_info = tmp_rh;
  11702. } else { /* AUTH_HANDLER */
  11703. *auth_handler = tmp_rh->auth_handler;
  11704. }
  11705. *cbdata = tmp_rh->cbdata;
  11706. mg_unlock_context(conn->phys_ctx);
  11707. return 1;
  11708. }
  11709. }
  11710. }
  11711. /* finally try for pattern match */
  11712. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11713. tmp_rh = tmp_rh->next) {
  11714. if (tmp_rh->handler_type == handler_type) {
  11715. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11716. if (handler_type == WEBSOCKET_HANDLER) {
  11717. *subprotocols = tmp_rh->subprotocols;
  11718. *connect_handler = tmp_rh->connect_handler;
  11719. *ready_handler = tmp_rh->ready_handler;
  11720. *data_handler = tmp_rh->data_handler;
  11721. *close_handler = tmp_rh->close_handler;
  11722. } else if (handler_type == REQUEST_HANDLER) {
  11723. *handler = tmp_rh->handler;
  11724. /* Acquire handler and give it back */
  11725. handler_info_acquire(tmp_rh);
  11726. *handler_info = tmp_rh;
  11727. } else { /* AUTH_HANDLER */
  11728. *auth_handler = tmp_rh->auth_handler;
  11729. }
  11730. *cbdata = tmp_rh->cbdata;
  11731. mg_unlock_context(conn->phys_ctx);
  11732. return 1;
  11733. }
  11734. }
  11735. }
  11736. mg_unlock_context(conn->phys_ctx);
  11737. }
  11738. return 0; /* none found */
  11739. }
  11740. /* Check if the script file is in a path, allowed for script files.
  11741. * This can be used if uploading files is possible not only for the server
  11742. * admin, and the upload mechanism does not check the file extension.
  11743. */
  11744. static int
  11745. is_in_script_path(const struct mg_connection *conn, const char *path)
  11746. {
  11747. /* TODO (Feature): Add config value for allowed script path.
  11748. * Default: All allowed. */
  11749. (void)conn;
  11750. (void)path;
  11751. return 1;
  11752. }
  11753. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11754. static int
  11755. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11756. void *cbdata)
  11757. {
  11758. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11759. if (pcallbacks->websocket_connect) {
  11760. return pcallbacks->websocket_connect(conn);
  11761. }
  11762. /* No handler set - assume "OK" */
  11763. return 0;
  11764. }
  11765. static void
  11766. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11767. {
  11768. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11769. if (pcallbacks->websocket_ready) {
  11770. pcallbacks->websocket_ready(conn);
  11771. }
  11772. }
  11773. static int
  11774. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11775. int bits,
  11776. char *data,
  11777. size_t len,
  11778. void *cbdata)
  11779. {
  11780. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11781. if (pcallbacks->websocket_data) {
  11782. return pcallbacks->websocket_data(conn, bits, data, len);
  11783. }
  11784. /* No handler set - assume "OK" */
  11785. return 1;
  11786. }
  11787. #endif
  11788. /* This is the heart of the Civetweb's logic.
  11789. * This function is called when the request is read, parsed and validated,
  11790. * and Civetweb must decide what action to take: serve a file, or
  11791. * a directory, or call embedded function, etcetera. */
  11792. static void
  11793. handle_request(struct mg_connection *conn)
  11794. {
  11795. struct mg_request_info *ri = &conn->request_info;
  11796. char path[PATH_MAX];
  11797. int uri_len, ssl_index;
  11798. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11799. is_put_or_delete_request = 0, is_callback_resource = 0;
  11800. int i;
  11801. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11802. mg_request_handler callback_handler = NULL;
  11803. struct mg_handler_info *handler_info = NULL;
  11804. struct mg_websocket_subprotocols *subprotocols;
  11805. mg_websocket_connect_handler ws_connect_handler = NULL;
  11806. mg_websocket_ready_handler ws_ready_handler = NULL;
  11807. mg_websocket_data_handler ws_data_handler = NULL;
  11808. mg_websocket_close_handler ws_close_handler = NULL;
  11809. void *callback_data = NULL;
  11810. mg_authorization_handler auth_handler = NULL;
  11811. void *auth_callback_data = NULL;
  11812. int handler_type;
  11813. time_t curtime = time(NULL);
  11814. char date[64];
  11815. path[0] = 0;
  11816. /* 1. get the request url */
  11817. /* 1.1. split into url and query string */
  11818. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11819. != NULL) {
  11820. *((char *)conn->request_info.query_string++) = '\0';
  11821. }
  11822. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11823. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11824. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11825. if (ssl_index >= 0) {
  11826. redirect_to_https_port(conn, ssl_index);
  11827. } else {
  11828. /* A http to https forward port has been specified,
  11829. * but no https port to forward to. */
  11830. mg_send_http_error(conn,
  11831. 503,
  11832. "%s",
  11833. "Error: SSL forward not configured properly");
  11834. mg_cry_internal(conn,
  11835. "%s",
  11836. "Can not redirect to SSL, no SSL port available");
  11837. }
  11838. return;
  11839. }
  11840. uri_len = (int)strlen(ri->local_uri);
  11841. /* 1.3. decode url (if config says so) */
  11842. if (should_decode_url(conn)) {
  11843. mg_url_decode(
  11844. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11845. }
  11846. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11847. * not possible */
  11848. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11849. /* step 1. completed, the url is known now */
  11850. uri_len = (int)strlen(ri->local_uri);
  11851. DEBUG_TRACE("URL: %s", ri->local_uri);
  11852. /* 2. if this ip has limited speed, set it for this connection */
  11853. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11854. get_remote_ip(conn),
  11855. ri->local_uri);
  11856. /* 3. call a "handle everything" callback, if registered */
  11857. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11858. /* Note that since V1.7 the "begin_request" function is called
  11859. * before an authorization check. If an authorization check is
  11860. * required, use a request_handler instead. */
  11861. i = conn->phys_ctx->callbacks.begin_request(conn);
  11862. if (i > 0) {
  11863. /* callback already processed the request. Store the
  11864. return value as a status code for the access log. */
  11865. conn->status_code = i;
  11866. discard_unread_request_data(conn);
  11867. return;
  11868. } else if (i == 0) {
  11869. /* civetweb should process the request */
  11870. } else {
  11871. /* unspecified - may change with the next version */
  11872. return;
  11873. }
  11874. }
  11875. /* request not yet handled by a handler or redirect, so the request
  11876. * is processed here */
  11877. /* 4. Check for CORS preflight requests and handle them (if configured).
  11878. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11879. */
  11880. if (!strcmp(ri->request_method, "OPTIONS")) {
  11881. /* Send a response to CORS preflights only if
  11882. * access_control_allow_methods is not NULL and not an empty string.
  11883. * In this case, scripts can still handle CORS. */
  11884. const char *cors_meth_cfg =
  11885. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11886. const char *cors_orig_cfg =
  11887. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11888. const char *cors_origin =
  11889. get_header(ri->http_headers, ri->num_headers, "Origin");
  11890. const char *cors_acrm = get_header(ri->http_headers,
  11891. ri->num_headers,
  11892. "Access-Control-Request-Method");
  11893. /* Todo: check if cors_origin is in cors_orig_cfg.
  11894. * Or, let the client check this. */
  11895. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11896. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11897. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11898. /* This is a valid CORS preflight, and the server is configured
  11899. * to
  11900. * handle it automatically. */
  11901. const char *cors_acrh =
  11902. get_header(ri->http_headers,
  11903. ri->num_headers,
  11904. "Access-Control-Request-Headers");
  11905. gmt_time_string(date, sizeof(date), &curtime);
  11906. mg_printf(conn,
  11907. "HTTP/1.1 200 OK\r\n"
  11908. "Date: %s\r\n"
  11909. "Access-Control-Allow-Origin: %s\r\n"
  11910. "Access-Control-Allow-Methods: %s\r\n"
  11911. "Content-Length: 0\r\n"
  11912. "Connection: %s\r\n",
  11913. date,
  11914. cors_orig_cfg,
  11915. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11916. suggest_connection_header(conn));
  11917. if (cors_acrh != NULL) {
  11918. /* CORS request is asking for additional headers */
  11919. const char *cors_hdr_cfg =
  11920. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11921. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11922. /* Allow only if access_control_allow_headers is
  11923. * not NULL and not an empty string. If this
  11924. * configuration is set to *, allow everything.
  11925. * Otherwise this configuration must be a list
  11926. * of allowed HTTP header names. */
  11927. mg_printf(conn,
  11928. "Access-Control-Allow-Headers: %s\r\n",
  11929. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11930. : cors_hdr_cfg));
  11931. }
  11932. }
  11933. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11934. mg_printf(conn, "\r\n");
  11935. return;
  11936. }
  11937. }
  11938. /* 5. interpret the url to find out how the request must be handled
  11939. */
  11940. /* 5.1. first test, if the request targets the regular http(s)://
  11941. * protocol namespace or the websocket ws(s):// protocol namespace.
  11942. */
  11943. is_websocket_request = is_websocket_protocol(conn);
  11944. #if defined(USE_WEBSOCKET)
  11945. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11946. #else
  11947. handler_type = REQUEST_HANDLER;
  11948. #endif /* defined(USE_WEBSOCKET) */
  11949. /* 5.2. check if the request will be handled by a callback */
  11950. if (get_request_handler(conn,
  11951. handler_type,
  11952. &callback_handler,
  11953. &subprotocols,
  11954. &ws_connect_handler,
  11955. &ws_ready_handler,
  11956. &ws_data_handler,
  11957. &ws_close_handler,
  11958. NULL,
  11959. &callback_data,
  11960. &handler_info)) {
  11961. /* 5.2.1. A callback will handle this request. All requests
  11962. * handled
  11963. * by a callback have to be considered as requests to a script
  11964. * resource. */
  11965. is_callback_resource = 1;
  11966. is_script_resource = 1;
  11967. is_put_or_delete_request = is_put_or_delete_method(conn);
  11968. } else {
  11969. no_callback_resource:
  11970. /* 5.2.2. No callback is responsible for this request. The URI
  11971. * addresses a file based resource (static content or Lua/cgi
  11972. * scripts in the file system). */
  11973. is_callback_resource = 0;
  11974. interpret_uri(conn,
  11975. path,
  11976. sizeof(path),
  11977. &file.stat,
  11978. &is_found,
  11979. &is_script_resource,
  11980. &is_websocket_request,
  11981. &is_put_or_delete_request);
  11982. }
  11983. /* 6. authorization check */
  11984. /* 6.1. a custom authorization handler is installed */
  11985. if (get_request_handler(conn,
  11986. AUTH_HANDLER,
  11987. NULL,
  11988. NULL,
  11989. NULL,
  11990. NULL,
  11991. NULL,
  11992. NULL,
  11993. &auth_handler,
  11994. &auth_callback_data,
  11995. NULL)) {
  11996. if (!auth_handler(conn, auth_callback_data)) {
  11997. return;
  11998. }
  11999. } else if (is_put_or_delete_request && !is_script_resource
  12000. && !is_callback_resource) {
  12001. /* 6.2. this request is a PUT/DELETE to a real file */
  12002. /* 6.2.1. thus, the server must have real files */
  12003. #if defined(NO_FILES)
  12004. if (1) {
  12005. #else
  12006. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12007. #endif
  12008. /* This server does not have any real files, thus the
  12009. * PUT/DELETE methods are not valid. */
  12010. mg_send_http_error(conn,
  12011. 405,
  12012. "%s method not allowed",
  12013. conn->request_info.request_method);
  12014. return;
  12015. }
  12016. #if !defined(NO_FILES)
  12017. /* 6.2.2. Check if put authorization for static files is
  12018. * available.
  12019. */
  12020. if (!is_authorized_for_put(conn)) {
  12021. send_authorization_request(conn, NULL);
  12022. return;
  12023. }
  12024. #endif
  12025. } else {
  12026. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  12027. * or it is a PUT or DELETE request to a resource that does not
  12028. * correspond to a file. Check authorization. */
  12029. if (!check_authorization(conn, path)) {
  12030. send_authorization_request(conn, NULL);
  12031. return;
  12032. }
  12033. }
  12034. /* request is authorized or does not need authorization */
  12035. /* 7. check if there are request handlers for this uri */
  12036. if (is_callback_resource) {
  12037. if (!is_websocket_request) {
  12038. i = callback_handler(conn, callback_data);
  12039. /* Callback handler will not be used anymore. Release it */
  12040. handler_info_release(handler_info);
  12041. if (i > 0) {
  12042. /* Do nothing, callback has served the request. Store
  12043. * then return value as status code for the log and discard
  12044. * all data from the client not used by the callback. */
  12045. conn->status_code = i;
  12046. discard_unread_request_data(conn);
  12047. } else {
  12048. /* The handler did NOT handle the request. */
  12049. /* Some proper reactions would be:
  12050. * a) close the connections without sending anything
  12051. * b) send a 404 not found
  12052. * c) try if there is a file matching the URI
  12053. * It would be possible to do a, b or c in the callback
  12054. * implementation, and return 1 - we cannot do anything
  12055. * here, that is not possible in the callback.
  12056. *
  12057. * TODO: What would be the best reaction here?
  12058. * (Note: The reaction may change, if there is a better
  12059. *idea.)
  12060. */
  12061. /* For the moment, use option c: We look for a proper file,
  12062. * but since a file request is not always a script resource,
  12063. * the authorization check might be different. */
  12064. interpret_uri(conn,
  12065. path,
  12066. sizeof(path),
  12067. &file.stat,
  12068. &is_found,
  12069. &is_script_resource,
  12070. &is_websocket_request,
  12071. &is_put_or_delete_request);
  12072. callback_handler = NULL;
  12073. /* Here we are at a dead end:
  12074. * According to URI matching, a callback should be
  12075. * responsible for handling the request,
  12076. * we called it, but the callback declared itself
  12077. * not responsible.
  12078. * We use a goto here, to get out of this dead end,
  12079. * and continue with the default handling.
  12080. * A goto here is simpler and better to understand
  12081. * than some curious loop. */
  12082. goto no_callback_resource;
  12083. }
  12084. } else {
  12085. #if defined(USE_WEBSOCKET)
  12086. handle_websocket_request(conn,
  12087. path,
  12088. is_callback_resource,
  12089. subprotocols,
  12090. ws_connect_handler,
  12091. ws_ready_handler,
  12092. ws_data_handler,
  12093. ws_close_handler,
  12094. callback_data);
  12095. #endif
  12096. }
  12097. return;
  12098. }
  12099. /* 8. handle websocket requests */
  12100. #if defined(USE_WEBSOCKET)
  12101. if (is_websocket_request) {
  12102. if (is_script_resource) {
  12103. if (is_in_script_path(conn, path)) {
  12104. /* Websocket Lua script */
  12105. handle_websocket_request(conn,
  12106. path,
  12107. 0 /* Lua Script */,
  12108. NULL,
  12109. NULL,
  12110. NULL,
  12111. NULL,
  12112. NULL,
  12113. conn->phys_ctx->user_data);
  12114. } else {
  12115. /* Script was in an illegal path */
  12116. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12117. }
  12118. } else {
  12119. #if defined(MG_LEGACY_INTERFACE)
  12120. handle_websocket_request(
  12121. conn,
  12122. path,
  12123. !is_script_resource /* could be deprecated global callback */,
  12124. NULL,
  12125. deprecated_websocket_connect_wrapper,
  12126. deprecated_websocket_ready_wrapper,
  12127. deprecated_websocket_data_wrapper,
  12128. NULL,
  12129. conn->phys_ctx->user_data);
  12130. #else
  12131. mg_send_http_error(conn, 404, "%s", "Not found");
  12132. #endif
  12133. }
  12134. return;
  12135. } else
  12136. #endif
  12137. #if defined(NO_FILES)
  12138. /* 9a. In case the server uses only callbacks, this uri is
  12139. * unknown.
  12140. * Then, all request handling ends here. */
  12141. mg_send_http_error(conn, 404, "%s", "Not Found");
  12142. #else
  12143. /* 9b. This request is either for a static file or resource handled
  12144. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12145. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12146. mg_send_http_error(conn, 404, "%s", "Not Found");
  12147. return;
  12148. }
  12149. /* 10. Request is handled by a script */
  12150. if (is_script_resource) {
  12151. handle_file_based_request(conn, path, &file);
  12152. return;
  12153. }
  12154. /* 11. Handle put/delete/mkcol requests */
  12155. if (is_put_or_delete_request) {
  12156. /* 11.1. PUT method */
  12157. if (!strcmp(ri->request_method, "PUT")) {
  12158. put_file(conn, path);
  12159. return;
  12160. }
  12161. /* 11.2. DELETE method */
  12162. if (!strcmp(ri->request_method, "DELETE")) {
  12163. delete_file(conn, path);
  12164. return;
  12165. }
  12166. /* 11.3. MKCOL method */
  12167. if (!strcmp(ri->request_method, "MKCOL")) {
  12168. mkcol(conn, path);
  12169. return;
  12170. }
  12171. /* 11.4. PATCH method
  12172. * This method is not supported for static resources,
  12173. * only for scripts (Lua, CGI) and callbacks. */
  12174. mg_send_http_error(conn,
  12175. 405,
  12176. "%s method not allowed",
  12177. conn->request_info.request_method);
  12178. return;
  12179. }
  12180. /* 11. File does not exist, or it was configured that it should be
  12181. * hidden */
  12182. if (!is_found || (must_hide_file(conn, path))) {
  12183. mg_send_http_error(conn, 404, "%s", "Not found");
  12184. return;
  12185. }
  12186. /* 12. Directory uris should end with a slash */
  12187. if (file.stat.is_directory && (uri_len > 0)
  12188. && (ri->local_uri[uri_len - 1] != '/')) {
  12189. gmt_time_string(date, sizeof(date), &curtime);
  12190. mg_printf(conn,
  12191. "HTTP/1.1 301 Moved Permanently\r\n"
  12192. "Location: %s/\r\n"
  12193. "Date: %s\r\n"
  12194. /* "Cache-Control: private\r\n" (= default) */
  12195. "Content-Length: 0\r\n"
  12196. "Connection: %s\r\n",
  12197. ri->request_uri,
  12198. date,
  12199. suggest_connection_header(conn));
  12200. send_additional_header(conn);
  12201. mg_printf(conn, "\r\n");
  12202. return;
  12203. }
  12204. /* 13. Handle other methods than GET/HEAD */
  12205. /* 13.1. Handle PROPFIND */
  12206. if (!strcmp(ri->request_method, "PROPFIND")) {
  12207. handle_propfind(conn, path, &file.stat);
  12208. return;
  12209. }
  12210. /* 13.2. Handle OPTIONS for files */
  12211. if (!strcmp(ri->request_method, "OPTIONS")) {
  12212. /* This standard handler is only used for real files.
  12213. * Scripts should support the OPTIONS method themselves, to allow a
  12214. * maximum flexibility.
  12215. * Lua and CGI scripts may fully support CORS this way (including
  12216. * preflights). */
  12217. send_options(conn);
  12218. return;
  12219. }
  12220. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12221. if ((0 != strcmp(ri->request_method, "GET"))
  12222. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12223. mg_send_http_error(conn,
  12224. 405,
  12225. "%s method not allowed",
  12226. conn->request_info.request_method);
  12227. return;
  12228. }
  12229. /* 14. directories */
  12230. if (file.stat.is_directory) {
  12231. /* Substitute files have already been handled above. */
  12232. /* Here we can either generate and send a directory listing,
  12233. * or send an "access denied" error. */
  12234. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12235. "yes")) {
  12236. handle_directory_request(conn, path);
  12237. } else {
  12238. mg_send_http_error(conn,
  12239. 403,
  12240. "%s",
  12241. "Error: Directory listing denied");
  12242. }
  12243. return;
  12244. }
  12245. /* 15. read a normal file with GET or HEAD */
  12246. handle_file_based_request(conn, path, &file);
  12247. #endif /* !defined(NO_FILES) */
  12248. }
  12249. static void
  12250. handle_file_based_request(struct mg_connection *conn,
  12251. const char *path,
  12252. struct mg_file *file)
  12253. {
  12254. if (!conn || !conn->dom_ctx) {
  12255. return;
  12256. }
  12257. if (0) {
  12258. #if defined(USE_LUA)
  12259. } else if (match_prefix(
  12260. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12261. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12262. path)
  12263. > 0) {
  12264. if (is_in_script_path(conn, path)) {
  12265. /* Lua server page: an SSI like page containing mostly plain
  12266. * html
  12267. * code
  12268. * plus some tags with server generated contents. */
  12269. handle_lsp_request(conn, path, file, NULL);
  12270. } else {
  12271. /* Script was in an illegal path */
  12272. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12273. }
  12274. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12275. strlen(
  12276. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12277. path)
  12278. > 0) {
  12279. if (is_in_script_path(conn, path)) {
  12280. /* Lua in-server module script: a CGI like script used to
  12281. * generate
  12282. * the
  12283. * entire reply. */
  12284. mg_exec_lua_script(conn, path, NULL);
  12285. } else {
  12286. /* Script was in an illegal path */
  12287. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12288. }
  12289. #endif
  12290. #if defined(USE_DUKTAPE)
  12291. } else if (match_prefix(
  12292. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12293. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12294. path)
  12295. > 0) {
  12296. if (is_in_script_path(conn, path)) {
  12297. /* Call duktape to generate the page */
  12298. mg_exec_duktape_script(conn, path);
  12299. } else {
  12300. /* Script was in an illegal path */
  12301. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12302. }
  12303. #endif
  12304. #if !defined(NO_CGI)
  12305. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12306. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12307. path)
  12308. > 0) {
  12309. if (is_in_script_path(conn, path)) {
  12310. /* CGI scripts may support all HTTP methods */
  12311. handle_cgi_request(conn, path);
  12312. } else {
  12313. /* Script was in an illegal path */
  12314. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12315. }
  12316. #endif /* !NO_CGI */
  12317. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12318. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12319. path)
  12320. > 0) {
  12321. if (is_in_script_path(conn, path)) {
  12322. handle_ssi_file_request(conn, path, file);
  12323. } else {
  12324. /* Script was in an illegal path */
  12325. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12326. }
  12327. #if !defined(NO_CACHING)
  12328. } else if ((!conn->in_error_handler)
  12329. && is_not_modified(conn, &file->stat)) {
  12330. /* Send 304 "Not Modified" - this must not send any body data */
  12331. handle_not_modified_static_file_request(conn, file);
  12332. #endif /* !NO_CACHING */
  12333. } else {
  12334. handle_static_file_request(conn, path, file, NULL, NULL);
  12335. }
  12336. }
  12337. static void
  12338. close_all_listening_sockets(struct mg_context *ctx)
  12339. {
  12340. unsigned int i;
  12341. if (!ctx) {
  12342. return;
  12343. }
  12344. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12345. closesocket(ctx->listening_sockets[i].sock);
  12346. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12347. }
  12348. mg_free(ctx->listening_sockets);
  12349. ctx->listening_sockets = NULL;
  12350. mg_free(ctx->listening_socket_fds);
  12351. ctx->listening_socket_fds = NULL;
  12352. }
  12353. /* Valid listening port specification is: [ip_address:]port[s]
  12354. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12355. * Examples for IPv6: [::]:80, [::1]:80,
  12356. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12357. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12358. * In order to bind to both, IPv4 and IPv6, you can either add
  12359. * both ports using 8080,[::]:8080, or the short form +8080.
  12360. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12361. * one only accepting IPv4 the other only IPv6. +8080 creates
  12362. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12363. * environment, they might work differently, or might not work
  12364. * at all - it must be tested what options work best in the
  12365. * relevant network environment.
  12366. */
  12367. static int
  12368. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12369. {
  12370. unsigned int a, b, c, d, port;
  12371. int ch, len;
  12372. const char *cb;
  12373. #if defined(USE_IPV6)
  12374. char buf[100] = {0};
  12375. #endif
  12376. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12377. * Also, all-zeroes in the socket address means binding to all addresses
  12378. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12379. memset(so, 0, sizeof(*so));
  12380. so->lsa.sin.sin_family = AF_INET;
  12381. *ip_version = 0;
  12382. /* Initialize port and len as invalid. */
  12383. port = 0;
  12384. len = 0;
  12385. /* Test for different ways to format this string */
  12386. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12387. == 5) {
  12388. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12389. so->lsa.sin.sin_addr.s_addr =
  12390. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12391. so->lsa.sin.sin_port = htons((uint16_t)port);
  12392. *ip_version = 4;
  12393. #if defined(USE_IPV6)
  12394. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12395. && mg_inet_pton(
  12396. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12397. /* IPv6 address, examples: see above */
  12398. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12399. */
  12400. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12401. *ip_version = 6;
  12402. #endif
  12403. } else if ((vec->ptr[0] == '+')
  12404. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12405. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12406. /* Add 1 to len for the + character we skipped before */
  12407. len++;
  12408. #if defined(USE_IPV6)
  12409. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12410. so->lsa.sin6.sin6_family = AF_INET6;
  12411. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12412. *ip_version = 4 + 6;
  12413. #else
  12414. /* Bind to IPv4 only, since IPv6 is not built in. */
  12415. so->lsa.sin.sin_port = htons((uint16_t)port);
  12416. *ip_version = 4;
  12417. #endif
  12418. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  12419. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12420. so->lsa.sin.sin_port = htons((uint16_t)port);
  12421. *ip_version = 4;
  12422. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12423. /* String could be a hostname. This check algotithm
  12424. * will only work for RFC 952 compliant hostnames,
  12425. * starting with a letter, containing only letters,
  12426. * digits and hyphen ('-'). Newer specs may allow
  12427. * more, but this is not guaranteed here, since it
  12428. * may interfere with rules for port option lists. */
  12429. /* According to RFC 1035, hostnames are restricted to 255 characters
  12430. * in total (63 between two dots). */
  12431. char hostname[256];
  12432. size_t hostnlen = (size_t)(cb - vec->ptr);
  12433. if (hostnlen >= sizeof(hostname)) {
  12434. /* This would be invalid in any case */
  12435. *ip_version = 0;
  12436. return 0;
  12437. }
  12438. memcpy(hostname, vec->ptr, hostnlen);
  12439. hostname[hostnlen] = 0;
  12440. if (mg_inet_pton(
  12441. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12442. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12443. *ip_version = 4;
  12444. so->lsa.sin.sin_family = AF_INET;
  12445. so->lsa.sin.sin_port = htons((uint16_t)port);
  12446. len += (int)(hostnlen + 1);
  12447. } else {
  12448. port = 0;
  12449. len = 0;
  12450. }
  12451. #if defined(USE_IPV6)
  12452. } else if (mg_inet_pton(AF_INET6,
  12453. vec->ptr,
  12454. &so->lsa.sin6,
  12455. sizeof(so->lsa.sin6))) {
  12456. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12457. *ip_version = 6;
  12458. so->lsa.sin6.sin6_family = AF_INET6;
  12459. so->lsa.sin.sin_port = htons((uint16_t)port);
  12460. len += (int)(hostnlen + 1);
  12461. } else {
  12462. port = 0;
  12463. len = 0;
  12464. }
  12465. #endif
  12466. }
  12467. } else {
  12468. /* Parsing failure. */
  12469. }
  12470. /* sscanf and the option splitting code ensure the following condition
  12471. */
  12472. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12473. *ip_version = 0;
  12474. return 0;
  12475. }
  12476. ch = vec->ptr[len]; /* Next character after the port number */
  12477. so->is_ssl = (ch == 's');
  12478. so->ssl_redir = (ch == 'r');
  12479. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12480. if (is_valid_port(port)
  12481. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12482. return 1;
  12483. }
  12484. /* Reset ip_version to 0 if there is an error */
  12485. *ip_version = 0;
  12486. return 0;
  12487. }
  12488. /* Is there any SSL port in use? */
  12489. static int
  12490. is_ssl_port_used(const char *ports)
  12491. {
  12492. if (ports) {
  12493. /* There are several different allowed syntax variants:
  12494. * - "80" for a single port using every network interface
  12495. * - "localhost:80" for a single port using only localhost
  12496. * - "80,localhost:8080" for two ports, one bound to localhost
  12497. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12498. * to IPv4 localhost, one to IPv6 localhost
  12499. * - "+80" use port 80 for IPv4 and IPv6
  12500. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12501. * for both: IPv4 and IPv4
  12502. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12503. * additionally port 8080 bound to localhost connections
  12504. *
  12505. * If we just look for 's' anywhere in the string, "localhost:80"
  12506. * will be detected as SSL (false positive).
  12507. * Looking for 's' after a digit may cause false positives in
  12508. * "my24service:8080".
  12509. * Looking from 's' backward if there are only ':' and numbers
  12510. * before will not work for "24service:8080" (non SSL, port 8080)
  12511. * or "24s" (SSL, port 24).
  12512. *
  12513. * Remark: Initially hostnames were not allowed to start with a
  12514. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12515. * Section 2.1).
  12516. *
  12517. * To get this correct, the entire string must be parsed as a whole,
  12518. * reading it as a list element for element and parsing with an
  12519. * algorithm equivalent to parse_port_string.
  12520. *
  12521. * In fact, we use local interface names here, not arbitrary hostnames,
  12522. * so in most cases the only name will be "localhost".
  12523. *
  12524. * So, for now, we use this simple algorithm, that may still return
  12525. * a false positive in bizarre cases.
  12526. */
  12527. int i;
  12528. int portslen = (int)strlen(ports);
  12529. char prevIsNumber = 0;
  12530. for (i = 0; i < portslen; i++) {
  12531. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12532. return 1;
  12533. }
  12534. if (ports[i] >= '0' && ports[i] <= '9') {
  12535. prevIsNumber = 1;
  12536. } else {
  12537. prevIsNumber = 0;
  12538. }
  12539. }
  12540. }
  12541. return 0;
  12542. }
  12543. static int
  12544. set_ports_option(struct mg_context *phys_ctx)
  12545. {
  12546. const char *list;
  12547. int on = 1;
  12548. #if defined(USE_IPV6)
  12549. int off = 0;
  12550. #endif
  12551. struct vec vec;
  12552. struct socket so, *ptr;
  12553. struct mg_pollfd *pfd;
  12554. union usa usa;
  12555. socklen_t len;
  12556. int ip_version;
  12557. int portsTotal = 0;
  12558. int portsOk = 0;
  12559. if (!phys_ctx) {
  12560. return 0;
  12561. }
  12562. memset(&so, 0, sizeof(so));
  12563. memset(&usa, 0, sizeof(usa));
  12564. len = sizeof(usa);
  12565. list = phys_ctx->dd.config[LISTENING_PORTS];
  12566. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12567. portsTotal++;
  12568. if (!parse_port_string(&vec, &so, &ip_version)) {
  12569. mg_cry_internal(
  12570. fc(phys_ctx),
  12571. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12572. (int)vec.len,
  12573. vec.ptr,
  12574. portsTotal,
  12575. "[IP_ADDRESS:]PORT[s|r]");
  12576. continue;
  12577. }
  12578. #if !defined(NO_SSL)
  12579. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12580. mg_cry_internal(fc(phys_ctx),
  12581. "Cannot add SSL socket (entry %i)",
  12582. portsTotal);
  12583. continue;
  12584. }
  12585. #endif
  12586. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12587. == INVALID_SOCKET) {
  12588. mg_cry_internal(fc(phys_ctx),
  12589. "cannot create socket (entry %i)",
  12590. portsTotal);
  12591. continue;
  12592. }
  12593. #if defined(_WIN32)
  12594. /* Windows SO_REUSEADDR lets many procs binds to a
  12595. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12596. * if someone already has the socket -- DTL */
  12597. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12598. * Windows might need a few seconds before
  12599. * the same port can be used again in the
  12600. * same process, so a short Sleep may be
  12601. * required between mg_stop and mg_start.
  12602. */
  12603. if (setsockopt(so.sock,
  12604. SOL_SOCKET,
  12605. SO_EXCLUSIVEADDRUSE,
  12606. (SOCK_OPT_TYPE)&on,
  12607. sizeof(on))
  12608. != 0) {
  12609. /* Set reuse option, but don't abort on errors. */
  12610. mg_cry_internal(
  12611. fc(phys_ctx),
  12612. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12613. portsTotal);
  12614. }
  12615. #else
  12616. if (setsockopt(so.sock,
  12617. SOL_SOCKET,
  12618. SO_REUSEADDR,
  12619. (SOCK_OPT_TYPE)&on,
  12620. sizeof(on))
  12621. != 0) {
  12622. /* Set reuse option, but don't abort on errors. */
  12623. mg_cry_internal(fc(phys_ctx),
  12624. "cannot set socket option SO_REUSEADDR (entry %i)",
  12625. portsTotal);
  12626. }
  12627. #endif
  12628. if (ip_version > 4) {
  12629. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12630. #if defined(USE_IPV6)
  12631. if (ip_version > 6) {
  12632. if (so.lsa.sa.sa_family == AF_INET6
  12633. && setsockopt(so.sock,
  12634. IPPROTO_IPV6,
  12635. IPV6_V6ONLY,
  12636. (void *)&off,
  12637. sizeof(off))
  12638. != 0) {
  12639. /* Set IPv6 only option, but don't abort on errors. */
  12640. mg_cry_internal(
  12641. fc(phys_ctx),
  12642. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12643. portsTotal);
  12644. }
  12645. } else {
  12646. if (so.lsa.sa.sa_family == AF_INET6
  12647. && setsockopt(so.sock,
  12648. IPPROTO_IPV6,
  12649. IPV6_V6ONLY,
  12650. (void *)&on,
  12651. sizeof(on))
  12652. != 0) {
  12653. /* Set IPv6 only option, but don't abort on errors. */
  12654. mg_cry_internal(
  12655. fc(phys_ctx),
  12656. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12657. portsTotal);
  12658. }
  12659. }
  12660. #else
  12661. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  12662. closesocket(so.sock);
  12663. so.sock = INVALID_SOCKET;
  12664. continue;
  12665. #endif
  12666. }
  12667. if (so.lsa.sa.sa_family == AF_INET) {
  12668. len = sizeof(so.lsa.sin);
  12669. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12670. mg_cry_internal(fc(phys_ctx),
  12671. "cannot bind to %.*s: %d (%s)",
  12672. (int)vec.len,
  12673. vec.ptr,
  12674. (int)ERRNO,
  12675. strerror(errno));
  12676. closesocket(so.sock);
  12677. so.sock = INVALID_SOCKET;
  12678. continue;
  12679. }
  12680. }
  12681. #if defined(USE_IPV6)
  12682. else if (so.lsa.sa.sa_family == AF_INET6) {
  12683. len = sizeof(so.lsa.sin6);
  12684. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12685. mg_cry_internal(fc(phys_ctx),
  12686. "cannot bind to IPv6 %.*s: %d (%s)",
  12687. (int)vec.len,
  12688. vec.ptr,
  12689. (int)ERRNO,
  12690. strerror(errno));
  12691. closesocket(so.sock);
  12692. so.sock = INVALID_SOCKET;
  12693. continue;
  12694. }
  12695. }
  12696. #endif
  12697. else {
  12698. mg_cry_internal(
  12699. fc(phys_ctx),
  12700. "cannot bind: address family not supported (entry %i)",
  12701. portsTotal);
  12702. closesocket(so.sock);
  12703. so.sock = INVALID_SOCKET;
  12704. continue;
  12705. }
  12706. if (listen(so.sock, SOMAXCONN) != 0) {
  12707. mg_cry_internal(fc(phys_ctx),
  12708. "cannot listen to %.*s: %d (%s)",
  12709. (int)vec.len,
  12710. vec.ptr,
  12711. (int)ERRNO,
  12712. strerror(errno));
  12713. closesocket(so.sock);
  12714. so.sock = INVALID_SOCKET;
  12715. continue;
  12716. }
  12717. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12718. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12719. int err = (int)ERRNO;
  12720. mg_cry_internal(fc(phys_ctx),
  12721. "call to getsockname failed %.*s: %d (%s)",
  12722. (int)vec.len,
  12723. vec.ptr,
  12724. err,
  12725. strerror(errno));
  12726. closesocket(so.sock);
  12727. so.sock = INVALID_SOCKET;
  12728. continue;
  12729. }
  12730. /* Update lsa port in case of random free ports */
  12731. #if defined(USE_IPV6)
  12732. if (so.lsa.sa.sa_family == AF_INET6) {
  12733. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12734. } else
  12735. #endif
  12736. {
  12737. so.lsa.sin.sin_port = usa.sin.sin_port;
  12738. }
  12739. if ((ptr = (struct socket *)
  12740. mg_realloc_ctx(phys_ctx->listening_sockets,
  12741. (phys_ctx->num_listening_sockets + 1)
  12742. * sizeof(phys_ctx->listening_sockets[0]),
  12743. phys_ctx))
  12744. == NULL) {
  12745. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12746. closesocket(so.sock);
  12747. so.sock = INVALID_SOCKET;
  12748. continue;
  12749. }
  12750. if ((pfd = (struct mg_pollfd *)
  12751. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12752. (phys_ctx->num_listening_sockets + 1)
  12753. * sizeof(phys_ctx->listening_socket_fds[0]),
  12754. phys_ctx))
  12755. == NULL) {
  12756. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12757. closesocket(so.sock);
  12758. so.sock = INVALID_SOCKET;
  12759. mg_free(ptr);
  12760. continue;
  12761. }
  12762. set_close_on_exec(so.sock, fc(phys_ctx));
  12763. phys_ctx->listening_sockets = ptr;
  12764. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12765. phys_ctx->listening_socket_fds = pfd;
  12766. phys_ctx->num_listening_sockets++;
  12767. portsOk++;
  12768. }
  12769. if (portsOk != portsTotal) {
  12770. close_all_listening_sockets(phys_ctx);
  12771. portsOk = 0;
  12772. }
  12773. return portsOk;
  12774. }
  12775. static const char *
  12776. header_val(const struct mg_connection *conn, const char *header)
  12777. {
  12778. const char *header_value;
  12779. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12780. return "-";
  12781. } else {
  12782. return header_value;
  12783. }
  12784. }
  12785. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12786. static void log_access(const struct mg_connection *conn);
  12787. #include "external_log_access.inl"
  12788. #else
  12789. static void
  12790. log_access(const struct mg_connection *conn)
  12791. {
  12792. const struct mg_request_info *ri;
  12793. struct mg_file fi;
  12794. char date[64], src_addr[IP_ADDR_STR_LEN];
  12795. struct tm *tm;
  12796. const char *referer;
  12797. const char *user_agent;
  12798. char buf[4096];
  12799. if (!conn || !conn->dom_ctx) {
  12800. return;
  12801. }
  12802. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12803. if (mg_fopen(conn,
  12804. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12805. MG_FOPEN_MODE_APPEND,
  12806. &fi)
  12807. == 0) {
  12808. fi.access.fp = NULL;
  12809. }
  12810. } else {
  12811. fi.access.fp = NULL;
  12812. }
  12813. /* Log is written to a file and/or a callback. If both are not set,
  12814. * executing the rest of the function is pointless. */
  12815. if ((fi.access.fp == NULL)
  12816. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12817. return;
  12818. }
  12819. tm = localtime(&conn->conn_birth_time);
  12820. if (tm != NULL) {
  12821. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12822. } else {
  12823. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12824. date[sizeof(date) - 1] = '\0';
  12825. }
  12826. ri = &conn->request_info;
  12827. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12828. referer = header_val(conn, "Referer");
  12829. user_agent = header_val(conn, "User-Agent");
  12830. mg_snprintf(conn,
  12831. NULL, /* Ignore truncation in access log */
  12832. buf,
  12833. sizeof(buf),
  12834. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12835. src_addr,
  12836. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12837. date,
  12838. ri->request_method ? ri->request_method : "-",
  12839. ri->request_uri ? ri->request_uri : "-",
  12840. ri->query_string ? "?" : "",
  12841. ri->query_string ? ri->query_string : "",
  12842. ri->http_version,
  12843. conn->status_code,
  12844. conn->num_bytes_sent,
  12845. referer,
  12846. user_agent);
  12847. if (conn->phys_ctx->callbacks.log_access) {
  12848. conn->phys_ctx->callbacks.log_access(conn, buf);
  12849. }
  12850. if (fi.access.fp) {
  12851. int ok = 1;
  12852. flockfile(fi.access.fp);
  12853. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12854. ok = 0;
  12855. }
  12856. if (fflush(fi.access.fp) != 0) {
  12857. ok = 0;
  12858. }
  12859. funlockfile(fi.access.fp);
  12860. if (mg_fclose(&fi.access) != 0) {
  12861. ok = 0;
  12862. }
  12863. if (!ok) {
  12864. mg_cry_internal(conn,
  12865. "Error writing log file %s",
  12866. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12867. }
  12868. }
  12869. }
  12870. #endif /* Externally provided function */
  12871. /* Verify given socket address against the ACL.
  12872. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12873. */
  12874. static int
  12875. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12876. {
  12877. int allowed, flag;
  12878. uint32_t net, mask;
  12879. struct vec vec;
  12880. if (phys_ctx) {
  12881. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12882. /* If any ACL is set, deny by default */
  12883. allowed = (list == NULL) ? '+' : '-';
  12884. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12885. flag = vec.ptr[0];
  12886. if ((flag != '+' && flag != '-')
  12887. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12888. mg_cry_internal(fc(phys_ctx),
  12889. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12890. __func__);
  12891. return -1;
  12892. }
  12893. if (net == (remote_ip & mask)) {
  12894. allowed = flag;
  12895. }
  12896. }
  12897. return allowed == '+';
  12898. }
  12899. return -1;
  12900. }
  12901. #if !defined(_WIN32)
  12902. static int
  12903. set_uid_option(struct mg_context *phys_ctx)
  12904. {
  12905. int success = 0;
  12906. if (phys_ctx) {
  12907. /* We are currently running as curr_uid. */
  12908. const uid_t curr_uid = getuid();
  12909. /* If set, we want to run as run_as_user. */
  12910. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12911. const struct passwd *to_pw = NULL;
  12912. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12913. /* run_as_user does not exist on the system. We can't proceed
  12914. * further. */
  12915. mg_cry_internal(fc(phys_ctx),
  12916. "%s: unknown user [%s]",
  12917. __func__,
  12918. run_as_user);
  12919. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12920. /* There was either no request to change user, or we're already
  12921. * running as run_as_user. Nothing else to do.
  12922. */
  12923. success = 1;
  12924. } else {
  12925. /* Valid change request. */
  12926. if (setgid(to_pw->pw_gid) == -1) {
  12927. mg_cry_internal(fc(phys_ctx),
  12928. "%s: setgid(%s): %s",
  12929. __func__,
  12930. run_as_user,
  12931. strerror(errno));
  12932. } else if (setgroups(0, NULL) == -1) {
  12933. mg_cry_internal(fc(phys_ctx),
  12934. "%s: setgroups(): %s",
  12935. __func__,
  12936. strerror(errno));
  12937. } else if (setuid(to_pw->pw_uid) == -1) {
  12938. mg_cry_internal(fc(phys_ctx),
  12939. "%s: setuid(%s): %s",
  12940. __func__,
  12941. run_as_user,
  12942. strerror(errno));
  12943. } else {
  12944. success = 1;
  12945. }
  12946. }
  12947. }
  12948. return success;
  12949. }
  12950. #endif /* !_WIN32 */
  12951. static void
  12952. tls_dtor(void *key)
  12953. {
  12954. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12955. /* key == pthread_getspecific(sTlsKey); */
  12956. if (tls) {
  12957. if (tls->is_master == 2) {
  12958. tls->is_master = -3; /* Mark memory as dead */
  12959. mg_free(tls);
  12960. }
  12961. }
  12962. pthread_setspecific(sTlsKey, NULL);
  12963. }
  12964. #if !defined(NO_SSL)
  12965. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12966. struct mg_domain_context *dom_ctx,
  12967. const char *pem,
  12968. const char *chain);
  12969. static const char *ssl_error(void);
  12970. static int
  12971. refresh_trust(struct mg_connection *conn)
  12972. {
  12973. static int reload_lock = 0;
  12974. static long int data_check = 0;
  12975. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12976. struct stat cert_buf;
  12977. long int t;
  12978. const char *pem;
  12979. const char *chain;
  12980. int should_verify_peer;
  12981. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12982. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12983. * refresh_trust still can not work. */
  12984. return 0;
  12985. }
  12986. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12987. if (chain == NULL) {
  12988. /* pem is not NULL here */
  12989. chain = pem;
  12990. }
  12991. if (*chain == 0) {
  12992. chain = NULL;
  12993. }
  12994. t = data_check;
  12995. if (stat(pem, &cert_buf) != -1) {
  12996. t = (long int)cert_buf.st_mtime;
  12997. }
  12998. if (data_check != t) {
  12999. data_check = t;
  13000. should_verify_peer = 0;
  13001. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13002. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  13003. == 0) {
  13004. should_verify_peer = 1;
  13005. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  13006. "optional")
  13007. == 0) {
  13008. should_verify_peer = 1;
  13009. }
  13010. }
  13011. if (should_verify_peer) {
  13012. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  13013. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  13014. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  13015. ca_file,
  13016. ca_path)
  13017. != 1) {
  13018. mg_cry_internal(
  13019. fc(conn->phys_ctx),
  13020. "SSL_CTX_load_verify_locations error: %s "
  13021. "ssl_verify_peer requires setting "
  13022. "either ssl_ca_path or ssl_ca_file. Is any of them "
  13023. "present in "
  13024. "the .conf file?",
  13025. ssl_error());
  13026. return 0;
  13027. }
  13028. }
  13029. if (1 == mg_atomic_inc(p_reload_lock)) {
  13030. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  13031. == 0) {
  13032. return 0;
  13033. }
  13034. *p_reload_lock = 0;
  13035. }
  13036. }
  13037. /* lock while cert is reloading */
  13038. while (*p_reload_lock) {
  13039. sleep(1);
  13040. }
  13041. return 1;
  13042. }
  13043. #if defined(OPENSSL_API_1_1)
  13044. #else
  13045. static pthread_mutex_t *ssl_mutexes;
  13046. #endif /* OPENSSL_API_1_1 */
  13047. static int
  13048. sslize(struct mg_connection *conn,
  13049. SSL_CTX *s,
  13050. int (*func)(SSL *),
  13051. volatile int *stop_server,
  13052. const struct mg_client_options *client_options)
  13053. {
  13054. int ret, err;
  13055. int short_trust;
  13056. unsigned timeout = 1024;
  13057. unsigned i;
  13058. if (!conn) {
  13059. return 0;
  13060. }
  13061. short_trust =
  13062. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13063. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13064. if (short_trust) {
  13065. int trust_ret = refresh_trust(conn);
  13066. if (!trust_ret) {
  13067. return trust_ret;
  13068. }
  13069. }
  13070. conn->ssl = SSL_new(s);
  13071. if (conn->ssl == NULL) {
  13072. return 0;
  13073. }
  13074. SSL_set_app_data(conn->ssl, (char *)conn);
  13075. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13076. if (ret != 1) {
  13077. err = SSL_get_error(conn->ssl, ret);
  13078. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13079. SSL_free(conn->ssl);
  13080. conn->ssl = NULL;
  13081. OPENSSL_REMOVE_THREAD_STATE();
  13082. return 0;
  13083. }
  13084. if (client_options) {
  13085. if (client_options->host_name) {
  13086. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13087. }
  13088. }
  13089. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13090. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13091. /* NOTE: The loop below acts as a back-off, so we can end
  13092. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13093. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13094. }
  13095. /* SSL functions may fail and require to be called again:
  13096. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13097. * Here "func" could be SSL_connect or SSL_accept. */
  13098. for (i = 0; i <= timeout; i += 50) {
  13099. ret = func(conn->ssl);
  13100. if (ret != 1) {
  13101. err = SSL_get_error(conn->ssl, ret);
  13102. if ((err == SSL_ERROR_WANT_CONNECT)
  13103. || (err == SSL_ERROR_WANT_ACCEPT)
  13104. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13105. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13106. if (*stop_server) {
  13107. /* Don't wait if the server is going to be stopped. */
  13108. break;
  13109. }
  13110. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13111. /* Simply retry the function call. */
  13112. mg_sleep(50);
  13113. } else {
  13114. /* Need to retry the function call "later".
  13115. * See https://linux.die.net/man/3/ssl_get_error
  13116. * This is typical for non-blocking sockets. */
  13117. struct mg_pollfd pfd;
  13118. pfd.fd = conn->client.sock;
  13119. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13120. || (err == SSL_ERROR_WANT_WRITE))
  13121. ? POLLOUT
  13122. : POLLIN;
  13123. mg_poll(&pfd, 1, 50, stop_server);
  13124. }
  13125. } else if (err == SSL_ERROR_SYSCALL) {
  13126. /* This is an IO error. Look at errno. */
  13127. err = errno;
  13128. mg_cry_internal(conn, "SSL syscall error %i", err);
  13129. break;
  13130. } else {
  13131. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13132. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13133. break;
  13134. }
  13135. } else {
  13136. /* success */
  13137. break;
  13138. }
  13139. }
  13140. if (ret != 1) {
  13141. SSL_free(conn->ssl);
  13142. conn->ssl = NULL;
  13143. OPENSSL_REMOVE_THREAD_STATE();
  13144. return 0;
  13145. }
  13146. return 1;
  13147. }
  13148. /* Return OpenSSL error message (from CRYPTO lib) */
  13149. static const char *
  13150. ssl_error(void)
  13151. {
  13152. unsigned long err;
  13153. err = ERR_get_error();
  13154. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13155. }
  13156. static int
  13157. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13158. {
  13159. int i;
  13160. const char hexdigit[] = "0123456789abcdef";
  13161. if ((memlen <= 0) || (buflen <= 0)) {
  13162. return 0;
  13163. }
  13164. if (buflen < (3 * memlen)) {
  13165. return 0;
  13166. }
  13167. for (i = 0; i < memlen; i++) {
  13168. if (i > 0) {
  13169. buf[3 * i - 1] = ' ';
  13170. }
  13171. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13172. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13173. }
  13174. buf[3 * memlen - 1] = 0;
  13175. return 1;
  13176. }
  13177. static void
  13178. ssl_get_client_cert_info(struct mg_connection *conn)
  13179. {
  13180. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13181. if (cert) {
  13182. char str_subject[1024];
  13183. char str_issuer[1024];
  13184. char str_finger[1024];
  13185. unsigned char buf[256];
  13186. char *str_serial = NULL;
  13187. unsigned int ulen;
  13188. int ilen;
  13189. unsigned char *tmp_buf;
  13190. unsigned char *tmp_p;
  13191. /* Handle to algorithm used for fingerprint */
  13192. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13193. /* Get Subject and issuer */
  13194. X509_NAME *subj = X509_get_subject_name(cert);
  13195. X509_NAME *iss = X509_get_issuer_name(cert);
  13196. /* Get serial number */
  13197. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13198. /* Translate serial number to a hex string */
  13199. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13200. str_serial = BN_bn2hex(serial_bn);
  13201. BN_free(serial_bn);
  13202. /* Translate subject and issuer to a string */
  13203. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13204. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13205. /* Calculate SHA1 fingerprint and store as a hex string */
  13206. ulen = 0;
  13207. /* ASN1_digest is deprecated. Do the calculation manually,
  13208. * using EVP_Digest. */
  13209. ilen = i2d_X509(cert, NULL);
  13210. tmp_buf = (ilen > 0)
  13211. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13212. conn->phys_ctx)
  13213. : NULL;
  13214. if (tmp_buf) {
  13215. tmp_p = tmp_buf;
  13216. (void)i2d_X509(cert, &tmp_p);
  13217. if (!EVP_Digest(
  13218. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13219. ulen = 0;
  13220. }
  13221. mg_free(tmp_buf);
  13222. }
  13223. if (!hexdump2string(
  13224. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13225. *str_finger = 0;
  13226. }
  13227. conn->request_info.client_cert = (struct mg_client_cert *)
  13228. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13229. if (conn->request_info.client_cert) {
  13230. conn->request_info.client_cert->peer_cert = (void *)cert;
  13231. conn->request_info.client_cert->subject =
  13232. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13233. conn->request_info.client_cert->issuer =
  13234. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13235. conn->request_info.client_cert->serial =
  13236. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13237. conn->request_info.client_cert->finger =
  13238. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13239. } else {
  13240. mg_cry_internal(conn,
  13241. "%s",
  13242. "Out of memory: Cannot allocate memory for client "
  13243. "certificate");
  13244. }
  13245. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13246. * see https://linux.die.net/man/3/bn_bn2hex */
  13247. OPENSSL_free(str_serial);
  13248. }
  13249. }
  13250. #if defined(OPENSSL_API_1_1)
  13251. #else
  13252. static void
  13253. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13254. {
  13255. (void)line;
  13256. (void)file;
  13257. if (mode & 1) {
  13258. /* 1 is CRYPTO_LOCK */
  13259. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13260. } else {
  13261. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13262. }
  13263. }
  13264. #endif /* OPENSSL_API_1_1 */
  13265. #if !defined(NO_SSL_DL)
  13266. static void *
  13267. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13268. {
  13269. union {
  13270. void *p;
  13271. void (*fp)(void);
  13272. } u;
  13273. void *dll_handle;
  13274. struct ssl_func *fp;
  13275. int ok;
  13276. int truncated = 0;
  13277. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13278. mg_snprintf(NULL,
  13279. NULL, /* No truncation check for ebuf */
  13280. ebuf,
  13281. ebuf_len,
  13282. "%s: cannot load %s",
  13283. __func__,
  13284. dll_name);
  13285. return NULL;
  13286. }
  13287. ok = 1;
  13288. for (fp = sw; fp->name != NULL; fp++) {
  13289. #if defined(_WIN32)
  13290. /* GetProcAddress() returns pointer to function */
  13291. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13292. #else
  13293. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13294. * pointers to function pointers. We need to use a union to make a
  13295. * cast. */
  13296. u.p = dlsym(dll_handle, fp->name);
  13297. #endif /* _WIN32 */
  13298. if (u.fp == NULL) {
  13299. if (ok) {
  13300. mg_snprintf(NULL,
  13301. &truncated,
  13302. ebuf,
  13303. ebuf_len,
  13304. "%s: %s: cannot find %s",
  13305. __func__,
  13306. dll_name,
  13307. fp->name);
  13308. ok = 0;
  13309. } else {
  13310. size_t cur_len = strlen(ebuf);
  13311. if (!truncated) {
  13312. mg_snprintf(NULL,
  13313. &truncated,
  13314. ebuf + cur_len,
  13315. ebuf_len - cur_len - 3,
  13316. ", %s",
  13317. fp->name);
  13318. if (truncated) {
  13319. /* If truncated, add "..." */
  13320. strcat(ebuf, "...");
  13321. }
  13322. }
  13323. }
  13324. /* Debug:
  13325. * printf("Missing function: %s\n", fp->name); */
  13326. } else {
  13327. fp->ptr = u.fp;
  13328. }
  13329. }
  13330. if (!ok) {
  13331. (void)dlclose(dll_handle);
  13332. return NULL;
  13333. }
  13334. return dll_handle;
  13335. }
  13336. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13337. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13338. #endif /* NO_SSL_DL */
  13339. #if defined(SSL_ALREADY_INITIALIZED)
  13340. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13341. #else
  13342. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13343. #endif
  13344. static int
  13345. initialize_ssl(char *ebuf, size_t ebuf_len)
  13346. {
  13347. #if defined(OPENSSL_API_1_1)
  13348. if (ebuf_len > 0) {
  13349. ebuf[0] = 0;
  13350. }
  13351. #if !defined(NO_SSL_DL)
  13352. if (!cryptolib_dll_handle) {
  13353. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13354. if (!cryptolib_dll_handle) {
  13355. mg_snprintf(NULL,
  13356. NULL, /* No truncation check for ebuf */
  13357. ebuf,
  13358. ebuf_len,
  13359. "%s: error loading library %s",
  13360. __func__,
  13361. CRYPTO_LIB);
  13362. DEBUG_TRACE("%s", ebuf);
  13363. return 0;
  13364. }
  13365. }
  13366. #endif /* NO_SSL_DL */
  13367. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13368. return 1;
  13369. }
  13370. #else /* not OPENSSL_API_1_1 */
  13371. int i, num_locks;
  13372. size_t size;
  13373. if (ebuf_len > 0) {
  13374. ebuf[0] = 0;
  13375. }
  13376. #if !defined(NO_SSL_DL)
  13377. if (!cryptolib_dll_handle) {
  13378. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13379. if (!cryptolib_dll_handle) {
  13380. mg_snprintf(NULL,
  13381. NULL, /* No truncation check for ebuf */
  13382. ebuf,
  13383. ebuf_len,
  13384. "%s: error loading library %s",
  13385. __func__,
  13386. CRYPTO_LIB);
  13387. DEBUG_TRACE("%s", ebuf);
  13388. return 0;
  13389. }
  13390. }
  13391. #endif /* NO_SSL_DL */
  13392. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13393. return 1;
  13394. }
  13395. /* Initialize locking callbacks, needed for thread safety.
  13396. * http://www.openssl.org/support/faq.html#PROG1
  13397. */
  13398. num_locks = CRYPTO_num_locks();
  13399. if (num_locks < 0) {
  13400. num_locks = 0;
  13401. }
  13402. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13403. /* allocate mutex array, if required */
  13404. if (num_locks == 0) {
  13405. /* No mutex array required */
  13406. ssl_mutexes = NULL;
  13407. } else {
  13408. /* Mutex array required - allocate it */
  13409. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13410. /* Check OOM */
  13411. if (ssl_mutexes == NULL) {
  13412. mg_snprintf(NULL,
  13413. NULL, /* No truncation check for ebuf */
  13414. ebuf,
  13415. ebuf_len,
  13416. "%s: cannot allocate mutexes: %s",
  13417. __func__,
  13418. ssl_error());
  13419. DEBUG_TRACE("%s", ebuf);
  13420. return 0;
  13421. }
  13422. /* initialize mutex array */
  13423. for (i = 0; i < num_locks; i++) {
  13424. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13425. mg_snprintf(NULL,
  13426. NULL, /* No truncation check for ebuf */
  13427. ebuf,
  13428. ebuf_len,
  13429. "%s: error initializing mutex %i of %i",
  13430. __func__,
  13431. i,
  13432. num_locks);
  13433. DEBUG_TRACE("%s", ebuf);
  13434. mg_free(ssl_mutexes);
  13435. return 0;
  13436. }
  13437. }
  13438. }
  13439. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13440. CRYPTO_set_id_callback(&mg_current_thread_id);
  13441. #endif /* OPENSSL_API_1_1 */
  13442. #if !defined(NO_SSL_DL)
  13443. if (!ssllib_dll_handle) {
  13444. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13445. if (!ssllib_dll_handle) {
  13446. #if !defined(OPENSSL_API_1_1)
  13447. mg_free(ssl_mutexes);
  13448. #endif
  13449. DEBUG_TRACE("%s", ebuf);
  13450. return 0;
  13451. }
  13452. }
  13453. #endif /* NO_SSL_DL */
  13454. #if defined(OPENSSL_API_1_1)
  13455. /* Initialize SSL library */
  13456. OPENSSL_init_ssl(0, NULL);
  13457. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13458. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13459. NULL);
  13460. #else
  13461. /* Initialize SSL library */
  13462. SSL_library_init();
  13463. SSL_load_error_strings();
  13464. #endif
  13465. return 1;
  13466. }
  13467. static int
  13468. ssl_use_pem_file(struct mg_context *phys_ctx,
  13469. struct mg_domain_context *dom_ctx,
  13470. const char *pem,
  13471. const char *chain)
  13472. {
  13473. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13474. mg_cry_internal(fc(phys_ctx),
  13475. "%s: cannot open certificate file %s: %s",
  13476. __func__,
  13477. pem,
  13478. ssl_error());
  13479. return 0;
  13480. }
  13481. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13482. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13483. mg_cry_internal(fc(phys_ctx),
  13484. "%s: cannot open private key file %s: %s",
  13485. __func__,
  13486. pem,
  13487. ssl_error());
  13488. return 0;
  13489. }
  13490. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13491. mg_cry_internal(fc(phys_ctx),
  13492. "%s: certificate and private key do not match: %s",
  13493. __func__,
  13494. pem);
  13495. return 0;
  13496. }
  13497. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13498. * chain files that contain private keys and certificates in
  13499. * SSL_CTX_use_certificate_chain_file.
  13500. * The CivetWeb-Server used pem-Files that contained both information.
  13501. * In order to make wolfSSL work, it is split in two files.
  13502. * One file that contains key and certificate used by the server and
  13503. * an optional chain file for the ssl stack.
  13504. */
  13505. if (chain) {
  13506. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13507. mg_cry_internal(fc(phys_ctx),
  13508. "%s: cannot use certificate chain file %s: %s",
  13509. __func__,
  13510. pem,
  13511. ssl_error());
  13512. return 0;
  13513. }
  13514. }
  13515. return 1;
  13516. }
  13517. #if defined(OPENSSL_API_1_1)
  13518. static unsigned long
  13519. ssl_get_protocol(int version_id)
  13520. {
  13521. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13522. if (version_id > 0)
  13523. ret |= SSL_OP_NO_SSLv2;
  13524. if (version_id > 1)
  13525. ret |= SSL_OP_NO_SSLv3;
  13526. if (version_id > 2)
  13527. ret |= SSL_OP_NO_TLSv1;
  13528. if (version_id > 3)
  13529. ret |= SSL_OP_NO_TLSv1_1;
  13530. if (version_id > 4)
  13531. ret |= SSL_OP_NO_TLSv1_2;
  13532. if (version_id > 5)
  13533. ret |= SSL_OP_NO_TLSv1_3;
  13534. return ret;
  13535. }
  13536. #else
  13537. static long
  13538. ssl_get_protocol(int version_id)
  13539. {
  13540. long ret = (long)SSL_OP_ALL;
  13541. if (version_id > 0)
  13542. ret |= SSL_OP_NO_SSLv2;
  13543. if (version_id > 1)
  13544. ret |= SSL_OP_NO_SSLv3;
  13545. if (version_id > 2)
  13546. ret |= SSL_OP_NO_TLSv1;
  13547. if (version_id > 3)
  13548. ret |= SSL_OP_NO_TLSv1_1;
  13549. return ret;
  13550. }
  13551. #endif /* OPENSSL_API_1_1 */
  13552. /* SSL callback documentation:
  13553. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13554. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13555. * https://linux.die.net/man/3/ssl_set_info_callback */
  13556. /* Note: There is no "const" for the first argument in the documentation
  13557. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13558. * / OpenSSL compatibility layers have it. Having a different definition will
  13559. * cause a warning in C and an error in C++. Use "const SSL *", while
  13560. * automatical conversion from "SSL *" works for all compilers, but not other
  13561. * way around */
  13562. static void
  13563. ssl_info_callback(const SSL *ssl, int what, int ret)
  13564. {
  13565. (void)ret;
  13566. if (what & SSL_CB_HANDSHAKE_START) {
  13567. SSL_get_app_data(ssl);
  13568. }
  13569. if (what & SSL_CB_HANDSHAKE_DONE) {
  13570. /* TODO: check for openSSL 1.1 */
  13571. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13572. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13573. }
  13574. }
  13575. static int
  13576. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13577. {
  13578. struct mg_context *ctx = (struct mg_context *)arg;
  13579. struct mg_domain_context *dom =
  13580. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13581. #if defined(GCC_DIAGNOSTIC)
  13582. #pragma GCC diagnostic push
  13583. #pragma GCC diagnostic ignored "-Wcast-align"
  13584. #endif /* defined(GCC_DIAGNOSTIC) */
  13585. /* We used an aligned pointer in SSL_set_app_data */
  13586. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13587. #if defined(GCC_DIAGNOSTIC)
  13588. #pragma GCC diagnostic pop
  13589. #endif /* defined(GCC_DIAGNOSTIC) */
  13590. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13591. (void)ad;
  13592. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13593. DEBUG_TRACE("%s", "internal error - assertion failed");
  13594. return SSL_TLSEXT_ERR_NOACK;
  13595. }
  13596. /* Old clients (Win XP) will not support SNI. Then, there
  13597. * is no server name available in the request - we can
  13598. * only work with the default certificate.
  13599. * Multiple HTTPS hosts on one IP+port are only possible
  13600. * with a certificate containing all alternative names.
  13601. */
  13602. if ((servername == NULL) || (*servername == 0)) {
  13603. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13604. conn->dom_ctx = &(ctx->dd);
  13605. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13606. return SSL_TLSEXT_ERR_NOACK;
  13607. }
  13608. DEBUG_TRACE("TLS connection to host %s", servername);
  13609. while (dom) {
  13610. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13611. /* Found matching domain */
  13612. DEBUG_TRACE("TLS domain %s found",
  13613. dom->config[AUTHENTICATION_DOMAIN]);
  13614. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13615. conn->dom_ctx = dom;
  13616. return SSL_TLSEXT_ERR_OK;
  13617. }
  13618. dom = dom->next;
  13619. }
  13620. /* Default domain */
  13621. DEBUG_TRACE("TLS default domain %s used",
  13622. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13623. conn->dom_ctx = &(ctx->dd);
  13624. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13625. return SSL_TLSEXT_ERR_OK;
  13626. }
  13627. /* Setup SSL CTX as required by CivetWeb */
  13628. static int
  13629. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13630. struct mg_domain_context *dom_ctx,
  13631. const char *pem,
  13632. const char *chain)
  13633. {
  13634. int callback_ret;
  13635. int should_verify_peer;
  13636. int peer_certificate_optional;
  13637. const char *ca_path;
  13638. const char *ca_file;
  13639. int use_default_verify_paths;
  13640. int verify_depth;
  13641. struct timespec now_mt;
  13642. md5_byte_t ssl_context_id[16];
  13643. md5_state_t md5state;
  13644. int protocol_ver;
  13645. #if defined(OPENSSL_API_1_1)
  13646. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13647. mg_cry_internal(fc(phys_ctx),
  13648. "SSL_CTX_new (server) error: %s",
  13649. ssl_error());
  13650. return 0;
  13651. }
  13652. #else
  13653. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13654. mg_cry_internal(fc(phys_ctx),
  13655. "SSL_CTX_new (server) error: %s",
  13656. ssl_error());
  13657. return 0;
  13658. }
  13659. #endif /* OPENSSL_API_1_1 */
  13660. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13661. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13662. | SSL_OP_NO_TLSv1_1);
  13663. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13664. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13665. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13666. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13667. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13668. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13669. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13670. #if !defined(NO_SSL_DL)
  13671. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13672. #endif /* NO_SSL_DL */
  13673. /* In SSL documentation examples callback defined without const specifier
  13674. * 'void (*)(SSL *, int, int)' See:
  13675. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13676. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13677. * But in the source code const SSL is used:
  13678. * 'void (*)(const SSL *, int, int)' See:
  13679. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13680. * Problem about wrong documentation described, but not resolved:
  13681. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13682. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13683. * But when compiled with modern C++ compiler, correct const should be
  13684. * provided
  13685. */
  13686. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13687. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13688. ssl_servername_callback);
  13689. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13690. /* If a callback has been specified, call it. */
  13691. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13692. ? 0
  13693. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13694. phys_ctx->user_data));
  13695. /* If callback returns 0, civetweb sets up the SSL certificate.
  13696. * If it returns 1, civetweb assumes the calback already did this.
  13697. * If it returns -1, initializing ssl fails. */
  13698. if (callback_ret < 0) {
  13699. mg_cry_internal(fc(phys_ctx),
  13700. "SSL callback returned error: %i",
  13701. callback_ret);
  13702. return 0;
  13703. }
  13704. if (callback_ret > 0) {
  13705. /* Callback did everything. */
  13706. return 1;
  13707. }
  13708. /* Use some combination of start time, domain and port as a SSL
  13709. * context ID. This should be unique on the current machine. */
  13710. md5_init(&md5state);
  13711. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13712. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13713. md5_append(&md5state,
  13714. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13715. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13716. md5_append(&md5state,
  13717. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13718. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13719. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13720. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13721. md5_finish(&md5state, ssl_context_id);
  13722. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13723. (unsigned char *)ssl_context_id,
  13724. sizeof(ssl_context_id));
  13725. if (pem != NULL) {
  13726. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13727. return 0;
  13728. }
  13729. }
  13730. /* Should we support client certificates? */
  13731. /* Default is "no". */
  13732. should_verify_peer = 0;
  13733. peer_certificate_optional = 0;
  13734. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13735. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13736. /* Yes, they are mandatory */
  13737. should_verify_peer = 1;
  13738. peer_certificate_optional = 0;
  13739. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13740. "optional")
  13741. == 0) {
  13742. /* Yes, they are optional */
  13743. should_verify_peer = 1;
  13744. peer_certificate_optional = 1;
  13745. }
  13746. }
  13747. use_default_verify_paths =
  13748. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13749. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13750. == 0);
  13751. if (should_verify_peer) {
  13752. ca_path = dom_ctx->config[SSL_CA_PATH];
  13753. ca_file = dom_ctx->config[SSL_CA_FILE];
  13754. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13755. != 1) {
  13756. mg_cry_internal(fc(phys_ctx),
  13757. "SSL_CTX_load_verify_locations error: %s "
  13758. "ssl_verify_peer requires setting "
  13759. "either ssl_ca_path or ssl_ca_file. "
  13760. "Is any of them present in the "
  13761. ".conf file?",
  13762. ssl_error());
  13763. return 0;
  13764. }
  13765. if (peer_certificate_optional) {
  13766. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13767. } else {
  13768. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13769. SSL_VERIFY_PEER
  13770. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13771. NULL);
  13772. }
  13773. if (use_default_verify_paths
  13774. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13775. mg_cry_internal(fc(phys_ctx),
  13776. "SSL_CTX_set_default_verify_paths error: %s",
  13777. ssl_error());
  13778. return 0;
  13779. }
  13780. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13781. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13782. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13783. }
  13784. }
  13785. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13786. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13787. dom_ctx->config[SSL_CIPHER_LIST])
  13788. != 1) {
  13789. mg_cry_internal(fc(phys_ctx),
  13790. "SSL_CTX_set_cipher_list error: %s",
  13791. ssl_error());
  13792. }
  13793. }
  13794. return 1;
  13795. }
  13796. /* Check if SSL is required.
  13797. * If so, dynamically load SSL library
  13798. * and set up ctx->ssl_ctx pointer. */
  13799. static int
  13800. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13801. {
  13802. void *ssl_ctx = 0;
  13803. int callback_ret;
  13804. const char *pem;
  13805. const char *chain;
  13806. char ebuf[128];
  13807. if (!phys_ctx) {
  13808. return 0;
  13809. }
  13810. if (!dom_ctx) {
  13811. dom_ctx = &(phys_ctx->dd);
  13812. }
  13813. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13814. /* No SSL port is set. No need to setup SSL. */
  13815. return 1;
  13816. }
  13817. /* Check for external SSL_CTX */
  13818. callback_ret =
  13819. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13820. ? 0
  13821. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13822. phys_ctx->user_data));
  13823. if (callback_ret < 0) {
  13824. mg_cry_internal(fc(phys_ctx),
  13825. "external_ssl_ctx callback returned error: %i",
  13826. callback_ret);
  13827. return 0;
  13828. } else if (callback_ret > 0) {
  13829. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13830. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13831. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13832. return 0;
  13833. }
  13834. return 1;
  13835. }
  13836. /* else: external_ssl_ctx does not exist or returns 0,
  13837. * CivetWeb should continue initializing SSL */
  13838. /* If PEM file is not specified and the init_ssl callback
  13839. * is not specified, setup will fail. */
  13840. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13841. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13842. /* No certificate and no callback:
  13843. * Essential data to set up TLS is missing.
  13844. */
  13845. mg_cry_internal(fc(phys_ctx),
  13846. "Initializing SSL failed: -%s is not set",
  13847. config_options[SSL_CERTIFICATE].name);
  13848. return 0;
  13849. }
  13850. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13851. if (chain == NULL) {
  13852. chain = pem;
  13853. }
  13854. if ((chain != NULL) && (*chain == 0)) {
  13855. chain = NULL;
  13856. }
  13857. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13858. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13859. return 0;
  13860. }
  13861. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13862. }
  13863. static void
  13864. uninitialize_ssl(void)
  13865. {
  13866. #if defined(OPENSSL_API_1_1)
  13867. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13868. /* Shutdown according to
  13869. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13870. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13871. */
  13872. CONF_modules_unload(1);
  13873. #else
  13874. int i;
  13875. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13876. /* Shutdown according to
  13877. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13878. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13879. */
  13880. CRYPTO_set_locking_callback(NULL);
  13881. CRYPTO_set_id_callback(NULL);
  13882. ENGINE_cleanup();
  13883. CONF_modules_unload(1);
  13884. ERR_free_strings();
  13885. EVP_cleanup();
  13886. CRYPTO_cleanup_all_ex_data();
  13887. OPENSSL_REMOVE_THREAD_STATE();
  13888. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13889. pthread_mutex_destroy(&ssl_mutexes[i]);
  13890. }
  13891. mg_free(ssl_mutexes);
  13892. ssl_mutexes = NULL;
  13893. #endif /* OPENSSL_API_1_1 */
  13894. }
  13895. }
  13896. #endif /* !NO_SSL */
  13897. static int
  13898. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13899. {
  13900. if (phys_ctx) {
  13901. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13902. const char *path;
  13903. if (!dom_ctx) {
  13904. dom_ctx = &(phys_ctx->dd);
  13905. }
  13906. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13907. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  13908. mg_cry_internal(fc(phys_ctx),
  13909. "Cannot open %s: %s",
  13910. path,
  13911. strerror(ERRNO));
  13912. return 0;
  13913. }
  13914. return 1;
  13915. }
  13916. return 0;
  13917. }
  13918. static int
  13919. set_acl_option(struct mg_context *phys_ctx)
  13920. {
  13921. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13922. }
  13923. static void
  13924. reset_per_request_attributes(struct mg_connection *conn)
  13925. {
  13926. if (!conn) {
  13927. return;
  13928. }
  13929. conn->connection_type =
  13930. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13931. conn->num_bytes_sent = conn->consumed_content = 0;
  13932. conn->path_info = NULL;
  13933. conn->status_code = -1;
  13934. conn->content_len = -1;
  13935. conn->is_chunked = 0;
  13936. conn->must_close = 0;
  13937. conn->request_len = 0;
  13938. conn->throttle = 0;
  13939. conn->data_len = 0;
  13940. conn->chunk_remainder = 0;
  13941. conn->accept_gzip = 0;
  13942. conn->response_info.content_length = conn->request_info.content_length = -1;
  13943. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13944. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13945. conn->response_info.status_text = NULL;
  13946. conn->response_info.status_code = 0;
  13947. conn->request_info.remote_user = NULL;
  13948. conn->request_info.request_method = NULL;
  13949. conn->request_info.request_uri = NULL;
  13950. conn->request_info.local_uri = NULL;
  13951. #if defined(MG_LEGACY_INTERFACE)
  13952. /* Legacy before split into local_uri and request_uri */
  13953. conn->request_info.uri = NULL;
  13954. #endif
  13955. }
  13956. #if 0
  13957. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13958. * Leave this function here (commented out) for reference until
  13959. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13960. * no longer required.
  13961. */
  13962. static int
  13963. set_sock_timeout(SOCKET sock, int milliseconds)
  13964. {
  13965. int r0 = 0, r1, r2;
  13966. #if defined(_WIN32)
  13967. /* Windows specific */
  13968. DWORD tv = (DWORD)milliseconds;
  13969. #else
  13970. /* Linux, ... (not Windows) */
  13971. struct timeval tv;
  13972. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13973. * max. time waiting for the acknowledged of TCP data before the connection
  13974. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13975. * If this option is not set, the default timeout of 20-30 minutes is used.
  13976. */
  13977. /* #define TCP_USER_TIMEOUT (18) */
  13978. #if defined(TCP_USER_TIMEOUT)
  13979. unsigned int uto = (unsigned int)milliseconds;
  13980. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13981. #endif
  13982. memset(&tv, 0, sizeof(tv));
  13983. tv.tv_sec = milliseconds / 1000;
  13984. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13985. #endif /* _WIN32 */
  13986. r1 = setsockopt(
  13987. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13988. r2 = setsockopt(
  13989. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13990. return r0 || r1 || r2;
  13991. }
  13992. #endif
  13993. static int
  13994. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13995. {
  13996. if (setsockopt(sock,
  13997. IPPROTO_TCP,
  13998. TCP_NODELAY,
  13999. (SOCK_OPT_TYPE)&nodelay_on,
  14000. sizeof(nodelay_on))
  14001. != 0) {
  14002. /* Error */
  14003. return 1;
  14004. }
  14005. /* OK */
  14006. return 0;
  14007. }
  14008. static void
  14009. close_socket_gracefully(struct mg_connection *conn)
  14010. {
  14011. #if defined(_WIN32)
  14012. char buf[MG_BUF_LEN];
  14013. int n;
  14014. #endif
  14015. struct linger linger;
  14016. int error_code = 0;
  14017. int linger_timeout = -2;
  14018. socklen_t opt_len = sizeof(error_code);
  14019. if (!conn) {
  14020. return;
  14021. }
  14022. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  14023. * "Note that enabling a nonzero timeout on a nonblocking socket
  14024. * is not recommended.", so set it to blocking now */
  14025. set_blocking_mode(conn->client.sock);
  14026. /* Send FIN to the client */
  14027. shutdown(conn->client.sock, SHUTDOWN_WR);
  14028. #if defined(_WIN32)
  14029. /* Read and discard pending incoming data. If we do not do that and
  14030. * close
  14031. * the socket, the data in the send buffer may be discarded. This
  14032. * behaviour is seen on Windows, when client keeps sending data
  14033. * when server decides to close the connection; then when client
  14034. * does recv() it gets no data back. */
  14035. do {
  14036. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  14037. } while (n > 0);
  14038. #endif
  14039. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  14040. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  14041. }
  14042. /* Set linger option according to configuration */
  14043. if (linger_timeout >= 0) {
  14044. /* Set linger option to avoid socket hanging out after close. This
  14045. * prevent ephemeral port exhaust problem under high QPS. */
  14046. linger.l_onoff = 1;
  14047. #if defined(_MSC_VER)
  14048. #pragma warning(push)
  14049. #pragma warning(disable : 4244)
  14050. #endif
  14051. #if defined(GCC_DIAGNOSTIC)
  14052. #pragma GCC diagnostic push
  14053. #pragma GCC diagnostic ignored "-Wconversion"
  14054. #endif
  14055. /* Data type of linger structure elements may differ,
  14056. * so we don't know what cast we need here.
  14057. * Disable type conversion warnings. */
  14058. linger.l_linger = (linger_timeout + 999) / 1000;
  14059. #if defined(GCC_DIAGNOSTIC)
  14060. #pragma GCC diagnostic pop
  14061. #endif
  14062. #if defined(_MSC_VER)
  14063. #pragma warning(pop)
  14064. #endif
  14065. } else {
  14066. linger.l_onoff = 0;
  14067. linger.l_linger = 0;
  14068. }
  14069. if (linger_timeout < -1) {
  14070. /* Default: don't configure any linger */
  14071. } else if (getsockopt(conn->client.sock,
  14072. SOL_SOCKET,
  14073. SO_ERROR,
  14074. #if defined(_WIN32) /* WinSock uses different data type here */
  14075. (char *)&error_code,
  14076. #else
  14077. &error_code,
  14078. #endif
  14079. &opt_len)
  14080. != 0) {
  14081. /* Cannot determine if socket is already closed. This should
  14082. * not occur and never did in a test. Log an error message
  14083. * and continue. */
  14084. mg_cry_internal(conn,
  14085. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14086. __func__,
  14087. strerror(ERRNO));
  14088. #if defined(_WIN32)
  14089. } else if (error_code == WSAECONNRESET) {
  14090. #else
  14091. } else if (error_code == ECONNRESET) {
  14092. #endif
  14093. /* Socket already closed by client/peer, close socket without linger
  14094. */
  14095. } else {
  14096. /* Set linger timeout */
  14097. if (setsockopt(conn->client.sock,
  14098. SOL_SOCKET,
  14099. SO_LINGER,
  14100. (char *)&linger,
  14101. sizeof(linger))
  14102. != 0) {
  14103. mg_cry_internal(
  14104. conn,
  14105. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14106. __func__,
  14107. linger.l_onoff,
  14108. linger.l_linger,
  14109. strerror(ERRNO));
  14110. }
  14111. }
  14112. /* Now we know that our FIN is ACK-ed, safe to close */
  14113. closesocket(conn->client.sock);
  14114. conn->client.sock = INVALID_SOCKET;
  14115. }
  14116. static void
  14117. close_connection(struct mg_connection *conn)
  14118. {
  14119. #if defined(USE_SERVER_STATS)
  14120. conn->conn_state = 6; /* to close */
  14121. #endif
  14122. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14123. if (conn->lua_websocket_state) {
  14124. lua_websocket_close(conn, conn->lua_websocket_state);
  14125. conn->lua_websocket_state = NULL;
  14126. }
  14127. #endif
  14128. mg_lock_connection(conn);
  14129. /* Set close flag, so keep-alive loops will stop */
  14130. conn->must_close = 1;
  14131. /* call the connection_close callback if assigned */
  14132. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14133. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14134. conn->phys_ctx->callbacks.connection_close(conn);
  14135. }
  14136. }
  14137. /* Reset user data, after close callback is called.
  14138. * Do not reuse it. If the user needs a destructor,
  14139. * it must be done in the connection_close callback. */
  14140. mg_set_user_connection_data(conn, NULL);
  14141. #if defined(USE_SERVER_STATS)
  14142. conn->conn_state = 7; /* closing */
  14143. #endif
  14144. #if !defined(NO_SSL)
  14145. if (conn->ssl != NULL) {
  14146. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14147. */
  14148. SSL_shutdown(conn->ssl);
  14149. SSL_free(conn->ssl);
  14150. OPENSSL_REMOVE_THREAD_STATE();
  14151. conn->ssl = NULL;
  14152. }
  14153. #endif
  14154. if (conn->client.sock != INVALID_SOCKET) {
  14155. close_socket_gracefully(conn);
  14156. conn->client.sock = INVALID_SOCKET;
  14157. }
  14158. if (conn->host) {
  14159. mg_free((void *)conn->host);
  14160. conn->host = NULL;
  14161. }
  14162. mg_unlock_connection(conn);
  14163. #if defined(USE_SERVER_STATS)
  14164. conn->conn_state = 8; /* closed */
  14165. #endif
  14166. }
  14167. void
  14168. mg_close_connection(struct mg_connection *conn)
  14169. {
  14170. #if defined(USE_WEBSOCKET)
  14171. struct mg_context *client_ctx = NULL;
  14172. #endif /* defined(USE_WEBSOCKET) */
  14173. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14174. return;
  14175. }
  14176. #if defined(USE_WEBSOCKET)
  14177. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14178. if (conn->in_websocket_handling) {
  14179. /* Set close flag, so the server thread can exit. */
  14180. conn->must_close = 1;
  14181. return;
  14182. }
  14183. }
  14184. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14185. unsigned int i;
  14186. /* ws/wss client */
  14187. client_ctx = conn->phys_ctx;
  14188. /* client context: loops must end */
  14189. client_ctx->stop_flag = 1;
  14190. conn->must_close = 1;
  14191. /* We need to get the client thread out of the select/recv call
  14192. * here. */
  14193. /* Since we use a sleep quantum of some seconds to check for recv
  14194. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14195. /* join worker thread */
  14196. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  14197. if (client_ctx->worker_threadids[i] != 0) {
  14198. mg_join_thread(client_ctx->worker_threadids[i]);
  14199. }
  14200. }
  14201. }
  14202. #endif /* defined(USE_WEBSOCKET) */
  14203. close_connection(conn);
  14204. #if !defined(NO_SSL)
  14205. if (conn->client_ssl_ctx != NULL) {
  14206. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  14207. }
  14208. #endif
  14209. #if defined(USE_WEBSOCKET)
  14210. if (client_ctx != NULL) {
  14211. /* free context */
  14212. mg_free(client_ctx->worker_threadids);
  14213. mg_free(client_ctx);
  14214. (void)pthread_mutex_destroy(&conn->mutex);
  14215. mg_free(conn);
  14216. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14217. mg_free(conn);
  14218. }
  14219. #else
  14220. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14221. mg_free(conn);
  14222. }
  14223. #endif /* defined(USE_WEBSOCKET) */
  14224. }
  14225. /* Only for memory statistics */
  14226. static struct mg_context common_client_context;
  14227. static struct mg_connection *
  14228. mg_connect_client_impl(const struct mg_client_options *client_options,
  14229. int use_ssl,
  14230. char *ebuf,
  14231. size_t ebuf_len)
  14232. {
  14233. struct mg_connection *conn = NULL;
  14234. SOCKET sock;
  14235. union usa sa;
  14236. struct sockaddr *psa;
  14237. socklen_t len;
  14238. unsigned max_req_size =
  14239. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14240. /* Size of structures, aligned to 8 bytes */
  14241. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14242. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14243. conn = (struct mg_connection *)mg_calloc_ctx(
  14244. 1, conn_size + ctx_size + max_req_size, &common_client_context);
  14245. if (conn == NULL) {
  14246. mg_snprintf(NULL,
  14247. NULL, /* No truncation check for ebuf */
  14248. ebuf,
  14249. ebuf_len,
  14250. "calloc(): %s",
  14251. strerror(ERRNO));
  14252. return NULL;
  14253. }
  14254. #if defined(GCC_DIAGNOSTIC)
  14255. #pragma GCC diagnostic push
  14256. #pragma GCC diagnostic ignored "-Wcast-align"
  14257. #endif /* defined(GCC_DIAGNOSTIC) */
  14258. /* conn_size is aligned to 8 bytes */
  14259. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14260. #if defined(GCC_DIAGNOSTIC)
  14261. #pragma GCC diagnostic pop
  14262. #endif /* defined(GCC_DIAGNOSTIC) */
  14263. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14264. conn->buf_size = (int)max_req_size;
  14265. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14266. conn->dom_ctx = &(conn->phys_ctx->dd);
  14267. if (!connect_socket(&common_client_context,
  14268. client_options->host,
  14269. client_options->port,
  14270. use_ssl,
  14271. ebuf,
  14272. ebuf_len,
  14273. &sock,
  14274. &sa)) {
  14275. /* ebuf is set by connect_socket,
  14276. * free all memory and return NULL; */
  14277. mg_free(conn);
  14278. return NULL;
  14279. }
  14280. #if !defined(NO_SSL)
  14281. #if defined(OPENSSL_API_1_1)
  14282. if (use_ssl
  14283. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  14284. mg_snprintf(NULL,
  14285. NULL, /* No truncation check for ebuf */
  14286. ebuf,
  14287. ebuf_len,
  14288. "SSL_CTX_new error: %s",
  14289. ssl_error());
  14290. closesocket(sock);
  14291. mg_free(conn);
  14292. return NULL;
  14293. }
  14294. #else
  14295. if (use_ssl
  14296. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14297. == NULL) {
  14298. mg_snprintf(NULL,
  14299. NULL, /* No truncation check for ebuf */
  14300. ebuf,
  14301. ebuf_len,
  14302. "SSL_CTX_new error: %s",
  14303. ssl_error());
  14304. closesocket(sock);
  14305. mg_free(conn);
  14306. return NULL;
  14307. }
  14308. #endif /* OPENSSL_API_1_1 */
  14309. #endif /* NO_SSL */
  14310. #if defined(USE_IPV6)
  14311. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14312. : sizeof(conn->client.rsa.sin6);
  14313. psa = (sa.sa.sa_family == AF_INET)
  14314. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14315. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14316. #else
  14317. len = sizeof(conn->client.rsa.sin);
  14318. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14319. #endif
  14320. conn->client.sock = sock;
  14321. conn->client.lsa = sa;
  14322. if (getsockname(sock, psa, &len) != 0) {
  14323. mg_cry_internal(conn,
  14324. "%s: getsockname() failed: %s",
  14325. __func__,
  14326. strerror(ERRNO));
  14327. }
  14328. conn->client.is_ssl = use_ssl ? 1 : 0;
  14329. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14330. mg_snprintf(NULL,
  14331. NULL, /* No truncation check for ebuf */
  14332. ebuf,
  14333. ebuf_len,
  14334. "Can not create mutex");
  14335. #if !defined(NO_SSL)
  14336. SSL_CTX_free(conn->client_ssl_ctx);
  14337. #endif
  14338. closesocket(sock);
  14339. mg_free(conn);
  14340. return NULL;
  14341. }
  14342. #if !defined(NO_SSL)
  14343. if (use_ssl) {
  14344. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  14345. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14346. * SSL_CTX_set_verify call is needed to switch off server
  14347. * certificate checking, which is off by default in OpenSSL and
  14348. * on in yaSSL. */
  14349. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  14350. * SSL_VERIFY_PEER, verify_ssl_server); */
  14351. if (client_options->client_cert) {
  14352. if (!ssl_use_pem_file(&common_client_context,
  14353. &(common_client_context.dd),
  14354. client_options->client_cert,
  14355. NULL)) {
  14356. mg_snprintf(NULL,
  14357. NULL, /* No truncation check for ebuf */
  14358. ebuf,
  14359. ebuf_len,
  14360. "Can not use SSL client certificate");
  14361. SSL_CTX_free(conn->client_ssl_ctx);
  14362. closesocket(sock);
  14363. mg_free(conn);
  14364. return NULL;
  14365. }
  14366. }
  14367. if (client_options->server_cert) {
  14368. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  14369. client_options->server_cert,
  14370. NULL);
  14371. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  14372. } else {
  14373. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  14374. }
  14375. if (!sslize(conn,
  14376. conn->client_ssl_ctx,
  14377. SSL_connect,
  14378. &(conn->phys_ctx->stop_flag),
  14379. client_options)) {
  14380. mg_snprintf(NULL,
  14381. NULL, /* No truncation check for ebuf */
  14382. ebuf,
  14383. ebuf_len,
  14384. "SSL connection error");
  14385. SSL_CTX_free(conn->client_ssl_ctx);
  14386. closesocket(sock);
  14387. mg_free(conn);
  14388. return NULL;
  14389. }
  14390. }
  14391. #endif
  14392. if (0 != set_non_blocking_mode(sock)) {
  14393. mg_cry_internal(conn,
  14394. "Cannot set non-blocking mode for client %s:%i",
  14395. client_options->host,
  14396. client_options->port);
  14397. }
  14398. return conn;
  14399. }
  14400. CIVETWEB_API struct mg_connection *
  14401. mg_connect_client_secure(const struct mg_client_options *client_options,
  14402. char *error_buffer,
  14403. size_t error_buffer_size)
  14404. {
  14405. return mg_connect_client_impl(client_options,
  14406. 1,
  14407. error_buffer,
  14408. error_buffer_size);
  14409. }
  14410. struct mg_connection *
  14411. mg_connect_client(const char *host,
  14412. int port,
  14413. int use_ssl,
  14414. char *error_buffer,
  14415. size_t error_buffer_size)
  14416. {
  14417. struct mg_client_options opts;
  14418. memset(&opts, 0, sizeof(opts));
  14419. opts.host = host;
  14420. opts.port = port;
  14421. return mg_connect_client_impl(&opts,
  14422. use_ssl,
  14423. error_buffer,
  14424. error_buffer_size);
  14425. }
  14426. static const struct {
  14427. const char *proto;
  14428. size_t proto_len;
  14429. unsigned default_port;
  14430. } abs_uri_protocols[] = {{"http://", 7, 80},
  14431. {"https://", 8, 443},
  14432. {"ws://", 5, 80},
  14433. {"wss://", 6, 443},
  14434. {NULL, 0, 0}};
  14435. /* Check if the uri is valid.
  14436. * return 0 for invalid uri,
  14437. * return 1 for *,
  14438. * return 2 for relative uri,
  14439. * return 3 for absolute uri without port,
  14440. * return 4 for absolute uri with port */
  14441. static int
  14442. get_uri_type(const char *uri)
  14443. {
  14444. int i;
  14445. const char *hostend, *portbegin;
  14446. char *portend;
  14447. unsigned long port;
  14448. /* According to the HTTP standard
  14449. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14450. * URI can be an asterisk (*) or should start with slash (relative uri),
  14451. * or it should start with the protocol (absolute uri). */
  14452. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14453. /* asterisk */
  14454. return 1;
  14455. }
  14456. /* Valid URIs according to RFC 3986
  14457. * (https://www.ietf.org/rfc/rfc3986.txt)
  14458. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14459. * and unreserved characters A-Z a-z 0-9 and -._~
  14460. * and % encoded symbols.
  14461. */
  14462. for (i = 0; uri[i] != 0; i++) {
  14463. if (uri[i] < 33) {
  14464. /* control characters and spaces are invalid */
  14465. return 0;
  14466. }
  14467. if (uri[i] > 126) {
  14468. /* non-ascii characters must be % encoded */
  14469. return 0;
  14470. } else {
  14471. switch (uri[i]) {
  14472. case '"': /* 34 */
  14473. case '<': /* 60 */
  14474. case '>': /* 62 */
  14475. case '\\': /* 92 */
  14476. case '^': /* 94 */
  14477. case '`': /* 96 */
  14478. case '{': /* 123 */
  14479. case '|': /* 124 */
  14480. case '}': /* 125 */
  14481. return 0;
  14482. default:
  14483. /* character is ok */
  14484. break;
  14485. }
  14486. }
  14487. }
  14488. /* A relative uri starts with a / character */
  14489. if (uri[0] == '/') {
  14490. /* relative uri */
  14491. return 2;
  14492. }
  14493. /* It could be an absolute uri: */
  14494. /* This function only checks if the uri is valid, not if it is
  14495. * addressing the current server. So civetweb can also be used
  14496. * as a proxy server. */
  14497. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14498. if (mg_strncasecmp(uri,
  14499. abs_uri_protocols[i].proto,
  14500. abs_uri_protocols[i].proto_len)
  14501. == 0) {
  14502. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14503. if (!hostend) {
  14504. return 0;
  14505. }
  14506. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14507. if (!portbegin) {
  14508. return 3;
  14509. }
  14510. port = strtoul(portbegin + 1, &portend, 10);
  14511. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14512. return 0;
  14513. }
  14514. return 4;
  14515. }
  14516. }
  14517. return 0;
  14518. }
  14519. /* Return NULL or the relative uri at the current server */
  14520. static const char *
  14521. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14522. {
  14523. const char *server_domain;
  14524. size_t server_domain_len;
  14525. size_t request_domain_len = 0;
  14526. unsigned long port = 0;
  14527. int i, auth_domain_check_enabled;
  14528. const char *hostbegin = NULL;
  14529. const char *hostend = NULL;
  14530. const char *portbegin;
  14531. char *portend;
  14532. auth_domain_check_enabled =
  14533. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14534. /* DNS is case insensitive, so use case insensitive string compare here
  14535. */
  14536. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14537. if (mg_strncasecmp(uri,
  14538. abs_uri_protocols[i].proto,
  14539. abs_uri_protocols[i].proto_len)
  14540. == 0) {
  14541. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14542. hostend = strchr(hostbegin, '/');
  14543. if (!hostend) {
  14544. return 0;
  14545. }
  14546. portbegin = strchr(hostbegin, ':');
  14547. if ((!portbegin) || (portbegin > hostend)) {
  14548. port = abs_uri_protocols[i].default_port;
  14549. request_domain_len = (size_t)(hostend - hostbegin);
  14550. } else {
  14551. port = strtoul(portbegin + 1, &portend, 10);
  14552. if ((portend != hostend) || (port <= 0)
  14553. || !is_valid_port(port)) {
  14554. return 0;
  14555. }
  14556. request_domain_len = (size_t)(portbegin - hostbegin);
  14557. }
  14558. /* protocol found, port set */
  14559. break;
  14560. }
  14561. }
  14562. if (!port) {
  14563. /* port remains 0 if the protocol is not found */
  14564. return 0;
  14565. }
  14566. /* Check if the request is directed to a different server. */
  14567. /* First check if the port is the same (IPv4 and IPv6). */
  14568. #if defined(USE_IPV6)
  14569. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14570. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14571. /* Request is directed to a different port */
  14572. return 0;
  14573. }
  14574. } else
  14575. #endif
  14576. {
  14577. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14578. /* Request is directed to a different port */
  14579. return 0;
  14580. }
  14581. }
  14582. /* Finally check if the server corresponds to the authentication
  14583. * domain of the server (the server domain).
  14584. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14585. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14586. * but do not allow substrings (like
  14587. * http://notmydomain.com/path/file.ext
  14588. * or http://mydomain.com.fake/path/file.ext).
  14589. */
  14590. if (auth_domain_check_enabled) {
  14591. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14592. server_domain_len = strlen(server_domain);
  14593. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14594. return 0;
  14595. }
  14596. if ((request_domain_len == server_domain_len)
  14597. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14598. /* Request is directed to this server - full name match. */
  14599. } else {
  14600. if (request_domain_len < (server_domain_len + 2)) {
  14601. /* Request is directed to another server: The server name
  14602. * is longer than the request name.
  14603. * Drop this case here to avoid overflows in the
  14604. * following checks. */
  14605. return 0;
  14606. }
  14607. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14608. /* Request is directed to another server: It could be a
  14609. * substring
  14610. * like notmyserver.com */
  14611. return 0;
  14612. }
  14613. if (0
  14614. != memcmp(server_domain,
  14615. hostbegin + request_domain_len - server_domain_len,
  14616. server_domain_len)) {
  14617. /* Request is directed to another server:
  14618. * The server name is different. */
  14619. return 0;
  14620. }
  14621. }
  14622. }
  14623. return hostend;
  14624. }
  14625. static int
  14626. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14627. {
  14628. if (ebuf_len > 0) {
  14629. ebuf[0] = '\0';
  14630. }
  14631. *err = 0;
  14632. reset_per_request_attributes(conn);
  14633. if (!conn) {
  14634. mg_snprintf(conn,
  14635. NULL, /* No truncation check for ebuf */
  14636. ebuf,
  14637. ebuf_len,
  14638. "%s",
  14639. "Internal error");
  14640. *err = 500;
  14641. return 0;
  14642. }
  14643. /* Set the time the request was received. This value should be used for
  14644. * timeouts. */
  14645. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14646. conn->request_len =
  14647. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14648. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14649. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14650. mg_snprintf(conn,
  14651. NULL, /* No truncation check for ebuf */
  14652. ebuf,
  14653. ebuf_len,
  14654. "%s",
  14655. "Invalid message size");
  14656. *err = 500;
  14657. return 0;
  14658. }
  14659. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14660. mg_snprintf(conn,
  14661. NULL, /* No truncation check for ebuf */
  14662. ebuf,
  14663. ebuf_len,
  14664. "%s",
  14665. "Message too large");
  14666. *err = 413;
  14667. return 0;
  14668. }
  14669. if (conn->request_len <= 0) {
  14670. if (conn->data_len > 0) {
  14671. mg_snprintf(conn,
  14672. NULL, /* No truncation check for ebuf */
  14673. ebuf,
  14674. ebuf_len,
  14675. "%s",
  14676. "Malformed message");
  14677. *err = 400;
  14678. } else {
  14679. /* Server did not recv anything -> just close the connection */
  14680. conn->must_close = 1;
  14681. mg_snprintf(conn,
  14682. NULL, /* No truncation check for ebuf */
  14683. ebuf,
  14684. ebuf_len,
  14685. "%s",
  14686. "No data received");
  14687. *err = 0;
  14688. }
  14689. return 0;
  14690. }
  14691. return 1;
  14692. }
  14693. static int
  14694. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14695. {
  14696. const char *cl;
  14697. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14698. return 0;
  14699. }
  14700. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14701. <= 0) {
  14702. mg_snprintf(conn,
  14703. NULL, /* No truncation check for ebuf */
  14704. ebuf,
  14705. ebuf_len,
  14706. "%s",
  14707. "Bad request");
  14708. *err = 400;
  14709. return 0;
  14710. }
  14711. /* Message is a valid request */
  14712. /* Is there a "host" ? */
  14713. if (conn->host != NULL) {
  14714. mg_free((void *)conn->host);
  14715. }
  14716. conn->host = alloc_get_host(conn);
  14717. if (!conn->host) {
  14718. mg_snprintf(conn,
  14719. NULL, /* No truncation check for ebuf */
  14720. ebuf,
  14721. ebuf_len,
  14722. "%s",
  14723. "Bad request: Host mismatch");
  14724. *err = 400;
  14725. return 0;
  14726. }
  14727. /* Do we know the content length? */
  14728. if ((cl = get_header(conn->request_info.http_headers,
  14729. conn->request_info.num_headers,
  14730. "Content-Length"))
  14731. != NULL) {
  14732. /* Request/response has content length set */
  14733. char *endptr = NULL;
  14734. conn->content_len = strtoll(cl, &endptr, 10);
  14735. if (endptr == cl) {
  14736. mg_snprintf(conn,
  14737. NULL, /* No truncation check for ebuf */
  14738. ebuf,
  14739. ebuf_len,
  14740. "%s",
  14741. "Bad request");
  14742. *err = 411;
  14743. return 0;
  14744. }
  14745. /* Publish the content length back to the request info. */
  14746. conn->request_info.content_length = conn->content_len;
  14747. } else if ((cl = get_header(conn->request_info.http_headers,
  14748. conn->request_info.num_headers,
  14749. "Transfer-Encoding"))
  14750. != NULL
  14751. && !mg_strcasecmp(cl, "chunked")) {
  14752. conn->is_chunked = 1;
  14753. conn->content_len = -1; /* unknown content length */
  14754. } else {
  14755. const struct mg_http_method_info *meth =
  14756. get_http_method_info(conn->request_info.request_method);
  14757. if (!meth) {
  14758. /* No valid HTTP method */
  14759. mg_snprintf(conn,
  14760. NULL, /* No truncation check for ebuf */
  14761. ebuf,
  14762. ebuf_len,
  14763. "%s",
  14764. "Bad request");
  14765. *err = 411;
  14766. return 0;
  14767. }
  14768. if (meth->request_has_body) {
  14769. /* POST or PUT request without content length set */
  14770. conn->content_len = -1; /* unknown content length */
  14771. } else {
  14772. /* Other request */
  14773. conn->content_len = 0; /* No content */
  14774. }
  14775. }
  14776. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14777. return 1;
  14778. }
  14779. /* conn is assumed to be valid in this internal function */
  14780. static int
  14781. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14782. {
  14783. const char *cl;
  14784. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14785. return 0;
  14786. }
  14787. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14788. <= 0) {
  14789. mg_snprintf(conn,
  14790. NULL, /* No truncation check for ebuf */
  14791. ebuf,
  14792. ebuf_len,
  14793. "%s",
  14794. "Bad response");
  14795. *err = 400;
  14796. return 0;
  14797. }
  14798. /* Message is a valid response */
  14799. /* Do we know the content length? */
  14800. if ((cl = get_header(conn->response_info.http_headers,
  14801. conn->response_info.num_headers,
  14802. "Content-Length"))
  14803. != NULL) {
  14804. /* Request/response has content length set */
  14805. char *endptr = NULL;
  14806. conn->content_len = strtoll(cl, &endptr, 10);
  14807. if (endptr == cl) {
  14808. mg_snprintf(conn,
  14809. NULL, /* No truncation check for ebuf */
  14810. ebuf,
  14811. ebuf_len,
  14812. "%s",
  14813. "Bad request");
  14814. *err = 411;
  14815. return 0;
  14816. }
  14817. /* Publish the content length back to the response info. */
  14818. conn->response_info.content_length = conn->content_len;
  14819. /* TODO: check if it is still used in response_info */
  14820. conn->request_info.content_length = conn->content_len;
  14821. } else if ((cl = get_header(conn->response_info.http_headers,
  14822. conn->response_info.num_headers,
  14823. "Transfer-Encoding"))
  14824. != NULL
  14825. && !mg_strcasecmp(cl, "chunked")) {
  14826. conn->is_chunked = 1;
  14827. conn->content_len = -1; /* unknown content length */
  14828. } else {
  14829. conn->content_len = -1; /* unknown content length */
  14830. }
  14831. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14832. return 1;
  14833. }
  14834. int
  14835. mg_get_response(struct mg_connection *conn,
  14836. char *ebuf,
  14837. size_t ebuf_len,
  14838. int timeout)
  14839. {
  14840. int err, ret;
  14841. char txt[32]; /* will not overflow */
  14842. char *save_timeout;
  14843. char *new_timeout;
  14844. if (ebuf_len > 0) {
  14845. ebuf[0] = '\0';
  14846. }
  14847. if (!conn) {
  14848. mg_snprintf(conn,
  14849. NULL, /* No truncation check for ebuf */
  14850. ebuf,
  14851. ebuf_len,
  14852. "%s",
  14853. "Parameter error");
  14854. return -1;
  14855. }
  14856. /* Implementation of API function for HTTP clients */
  14857. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14858. if (timeout >= 0) {
  14859. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14860. new_timeout = txt;
  14861. /* Not required for non-blocking sockets.
  14862. set_sock_timeout(conn->client.sock, timeout);
  14863. */
  14864. } else {
  14865. new_timeout = NULL;
  14866. }
  14867. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14868. ret = get_response(conn, ebuf, ebuf_len, &err);
  14869. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14870. #if defined(MG_LEGACY_INTERFACE)
  14871. /* TODO: 1) uri is deprecated;
  14872. * 2) here, ri.uri is the http response code */
  14873. conn->request_info.uri = conn->request_info.request_uri;
  14874. #endif
  14875. conn->request_info.local_uri = conn->request_info.request_uri;
  14876. /* TODO (mid): Define proper return values - maybe return length?
  14877. * For the first test use <0 for error and >0 for OK */
  14878. return (ret == 0) ? -1 : +1;
  14879. }
  14880. struct mg_connection *
  14881. mg_download(const char *host,
  14882. int port,
  14883. int use_ssl,
  14884. char *ebuf,
  14885. size_t ebuf_len,
  14886. const char *fmt,
  14887. ...)
  14888. {
  14889. struct mg_connection *conn;
  14890. va_list ap;
  14891. int i;
  14892. int reqerr;
  14893. if (ebuf_len > 0) {
  14894. ebuf[0] = '\0';
  14895. }
  14896. va_start(ap, fmt);
  14897. /* open a connection */
  14898. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14899. if (conn != NULL) {
  14900. i = mg_vprintf(conn, fmt, ap);
  14901. if (i <= 0) {
  14902. mg_snprintf(conn,
  14903. NULL, /* No truncation check for ebuf */
  14904. ebuf,
  14905. ebuf_len,
  14906. "%s",
  14907. "Error sending request");
  14908. } else {
  14909. get_response(conn, ebuf, ebuf_len, &reqerr);
  14910. #if defined(MG_LEGACY_INTERFACE)
  14911. /* TODO: 1) uri is deprecated;
  14912. * 2) here, ri.uri is the http response code */
  14913. conn->request_info.uri = conn->request_info.request_uri;
  14914. #endif
  14915. conn->request_info.local_uri = conn->request_info.request_uri;
  14916. }
  14917. }
  14918. /* if an error occurred, close the connection */
  14919. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14920. mg_close_connection(conn);
  14921. conn = NULL;
  14922. }
  14923. va_end(ap);
  14924. return conn;
  14925. }
  14926. struct websocket_client_thread_data {
  14927. struct mg_connection *conn;
  14928. mg_websocket_data_handler data_handler;
  14929. mg_websocket_close_handler close_handler;
  14930. void *callback_data;
  14931. };
  14932. #if defined(USE_WEBSOCKET)
  14933. #if defined(_WIN32)
  14934. static unsigned __stdcall websocket_client_thread(void *data)
  14935. #else
  14936. static void *
  14937. websocket_client_thread(void *data)
  14938. #endif
  14939. {
  14940. struct websocket_client_thread_data *cdata =
  14941. (struct websocket_client_thread_data *)data;
  14942. void *user_thread_ptr = NULL;
  14943. #if !defined(_WIN32)
  14944. struct sigaction sa;
  14945. /* Ignore SIGPIPE */
  14946. memset(&sa, 0, sizeof(sa));
  14947. sa.sa_handler = SIG_IGN;
  14948. sigaction(SIGPIPE, &sa, NULL);
  14949. #endif
  14950. mg_set_thread_name("ws-clnt");
  14951. if (cdata->conn->phys_ctx) {
  14952. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14953. /* 3 indicates a websocket client thread */
  14954. /* TODO: check if conn->phys_ctx can be set */
  14955. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  14956. cdata->conn->phys_ctx, 3);
  14957. }
  14958. }
  14959. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14960. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14961. if (cdata->close_handler != NULL) {
  14962. cdata->close_handler(cdata->conn, cdata->callback_data);
  14963. }
  14964. /* The websocket_client context has only this thread. If it runs out,
  14965. set the stop_flag to 2 (= "stopped"). */
  14966. cdata->conn->phys_ctx->stop_flag = 2;
  14967. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  14968. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  14969. 3,
  14970. user_thread_ptr);
  14971. }
  14972. mg_free((void *)cdata);
  14973. #if defined(_WIN32)
  14974. return 0;
  14975. #else
  14976. return NULL;
  14977. #endif
  14978. }
  14979. #endif
  14980. struct mg_connection *
  14981. mg_connect_websocket_client(const char *host,
  14982. int port,
  14983. int use_ssl,
  14984. char *error_buffer,
  14985. size_t error_buffer_size,
  14986. const char *path,
  14987. const char *origin,
  14988. mg_websocket_data_handler data_func,
  14989. mg_websocket_close_handler close_func,
  14990. void *user_data)
  14991. {
  14992. struct mg_connection *conn = NULL;
  14993. #if defined(USE_WEBSOCKET)
  14994. struct mg_context *newctx = NULL;
  14995. struct websocket_client_thread_data *thread_data;
  14996. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14997. static const char *handshake_req;
  14998. if (origin != NULL) {
  14999. handshake_req = "GET %s HTTP/1.1\r\n"
  15000. "Host: %s\r\n"
  15001. "Upgrade: websocket\r\n"
  15002. "Connection: Upgrade\r\n"
  15003. "Sec-WebSocket-Key: %s\r\n"
  15004. "Sec-WebSocket-Version: 13\r\n"
  15005. "Origin: %s\r\n"
  15006. "\r\n";
  15007. } else {
  15008. handshake_req = "GET %s HTTP/1.1\r\n"
  15009. "Host: %s\r\n"
  15010. "Upgrade: websocket\r\n"
  15011. "Connection: Upgrade\r\n"
  15012. "Sec-WebSocket-Key: %s\r\n"
  15013. "Sec-WebSocket-Version: 13\r\n"
  15014. "\r\n";
  15015. }
  15016. #if defined(__clang__)
  15017. #pragma clang diagnostic push
  15018. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  15019. #endif
  15020. /* Establish the client connection and request upgrade */
  15021. conn = mg_download(host,
  15022. port,
  15023. use_ssl,
  15024. error_buffer,
  15025. error_buffer_size,
  15026. handshake_req,
  15027. path,
  15028. host,
  15029. magic,
  15030. origin);
  15031. #if defined(__clang__)
  15032. #pragma clang diagnostic pop
  15033. #endif
  15034. /* Connection object will be null if something goes wrong */
  15035. if (conn == NULL) {
  15036. if (!*error_buffer) {
  15037. /* There should be already an error message */
  15038. mg_snprintf(conn,
  15039. NULL, /* No truncation check for ebuf */
  15040. error_buffer,
  15041. error_buffer_size,
  15042. "Unexpected error");
  15043. }
  15044. return NULL;
  15045. }
  15046. if (conn->response_info.status_code != 101) {
  15047. /* We sent an "upgrade" request. For a correct websocket
  15048. * protocol handshake, we expect a "101 Continue" response.
  15049. * Otherwise it is a protocol violation. Maybe the HTTP
  15050. * Server does not know websockets. */
  15051. if (!*error_buffer) {
  15052. /* set an error, if not yet set */
  15053. mg_snprintf(conn,
  15054. NULL, /* No truncation check for ebuf */
  15055. error_buffer,
  15056. error_buffer_size,
  15057. "Unexpected server reply");
  15058. }
  15059. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15060. mg_free(conn);
  15061. return NULL;
  15062. }
  15063. /* For client connections, mg_context is fake. Since we need to set a
  15064. * callback function, we need to create a copy and modify it. */
  15065. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  15066. if (!newctx) {
  15067. DEBUG_TRACE("%s\r\n", "Out of memory");
  15068. mg_free(conn);
  15069. return NULL;
  15070. }
  15071. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  15072. newctx->user_data = user_data;
  15073. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  15074. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  15075. newctx->worker_threadids =
  15076. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  15077. sizeof(pthread_t),
  15078. newctx);
  15079. conn->phys_ctx = newctx;
  15080. conn->dom_ctx = &(newctx->dd);
  15081. thread_data = (struct websocket_client_thread_data *)
  15082. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  15083. if (!thread_data) {
  15084. DEBUG_TRACE("%s\r\n", "Out of memory");
  15085. mg_free(newctx);
  15086. mg_free(conn);
  15087. return NULL;
  15088. }
  15089. thread_data->conn = conn;
  15090. thread_data->data_handler = data_func;
  15091. thread_data->close_handler = close_func;
  15092. thread_data->callback_data = user_data;
  15093. /* Start a thread to read the websocket client connection
  15094. * This thread will automatically stop when mg_disconnect is
  15095. * called on the client connection */
  15096. if (mg_start_thread_with_id(websocket_client_thread,
  15097. (void *)thread_data,
  15098. newctx->worker_threadids)
  15099. != 0) {
  15100. mg_free((void *)thread_data);
  15101. mg_free((void *)newctx->worker_threadids);
  15102. mg_free((void *)newctx);
  15103. mg_free((void *)conn);
  15104. conn = NULL;
  15105. DEBUG_TRACE("%s",
  15106. "Websocket client connect thread could not be started\r\n");
  15107. }
  15108. #else
  15109. /* Appease "unused parameter" warnings */
  15110. (void)host;
  15111. (void)port;
  15112. (void)use_ssl;
  15113. (void)error_buffer;
  15114. (void)error_buffer_size;
  15115. (void)path;
  15116. (void)origin;
  15117. (void)user_data;
  15118. (void)data_func;
  15119. (void)close_func;
  15120. #endif
  15121. return conn;
  15122. }
  15123. /* Prepare connection data structure */
  15124. static void
  15125. init_connection(struct mg_connection *conn)
  15126. {
  15127. /* Is keep alive allowed by the server */
  15128. int keep_alive_enabled =
  15129. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15130. if (!keep_alive_enabled) {
  15131. conn->must_close = 1;
  15132. }
  15133. /* Important: on new connection, reset the receiving buffer. Credit
  15134. * goes to crule42. */
  15135. conn->data_len = 0;
  15136. conn->handled_requests = 0;
  15137. mg_set_user_connection_data(conn, NULL);
  15138. #if defined(USE_SERVER_STATS)
  15139. conn->conn_state = 2; /* init */
  15140. #endif
  15141. /* call the init_connection callback if assigned */
  15142. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15143. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15144. void *conn_data = NULL;
  15145. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15146. mg_set_user_connection_data(conn, conn_data);
  15147. }
  15148. }
  15149. }
  15150. /* Process a connection - may handle multiple requests
  15151. * using the same connection.
  15152. * Must be called with a valid connection (conn and
  15153. * conn->phys_ctx must be valid).
  15154. */
  15155. static void
  15156. process_new_connection(struct mg_connection *conn)
  15157. {
  15158. struct mg_request_info *ri = &conn->request_info;
  15159. int keep_alive, discard_len;
  15160. char ebuf[100];
  15161. const char *hostend;
  15162. int reqerr, uri_type;
  15163. #if defined(USE_SERVER_STATS)
  15164. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15165. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15166. if (mcon > (conn->phys_ctx->max_connections)) {
  15167. /* could use atomic compare exchange, but this
  15168. * seems overkill for statistics data */
  15169. conn->phys_ctx->max_connections = mcon;
  15170. }
  15171. #endif
  15172. init_connection(conn);
  15173. DEBUG_TRACE("Start processing connection from %s",
  15174. conn->request_info.remote_addr);
  15175. /* Loop over multiple requests sent using the same connection
  15176. * (while "keep alive"). */
  15177. do {
  15178. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15179. conn->handled_requests + 1);
  15180. #if defined(USE_SERVER_STATS)
  15181. conn->conn_state = 3; /* ready */
  15182. #endif
  15183. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15184. /* The request sent by the client could not be understood by
  15185. * the server, or it was incomplete or a timeout. Send an
  15186. * error message and close the connection. */
  15187. if (reqerr > 0) {
  15188. DEBUG_ASSERT(ebuf[0] != '\0');
  15189. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15190. }
  15191. } else if (strcmp(ri->http_version, "1.0")
  15192. && strcmp(ri->http_version, "1.1")) {
  15193. mg_snprintf(conn,
  15194. NULL, /* No truncation check for ebuf */
  15195. ebuf,
  15196. sizeof(ebuf),
  15197. "Bad HTTP version: [%s]",
  15198. ri->http_version);
  15199. mg_send_http_error(conn, 505, "%s", ebuf);
  15200. }
  15201. if (ebuf[0] == '\0') {
  15202. uri_type = get_uri_type(conn->request_info.request_uri);
  15203. switch (uri_type) {
  15204. case 1:
  15205. /* Asterisk */
  15206. conn->request_info.local_uri = NULL;
  15207. break;
  15208. case 2:
  15209. /* relative uri */
  15210. conn->request_info.local_uri = conn->request_info.request_uri;
  15211. break;
  15212. case 3:
  15213. case 4:
  15214. /* absolute uri (with/without port) */
  15215. hostend = get_rel_url_at_current_server(
  15216. conn->request_info.request_uri, conn);
  15217. if (hostend) {
  15218. conn->request_info.local_uri = hostend;
  15219. } else {
  15220. conn->request_info.local_uri = NULL;
  15221. }
  15222. break;
  15223. default:
  15224. mg_snprintf(conn,
  15225. NULL, /* No truncation check for ebuf */
  15226. ebuf,
  15227. sizeof(ebuf),
  15228. "Invalid URI");
  15229. mg_send_http_error(conn, 400, "%s", ebuf);
  15230. conn->request_info.local_uri = NULL;
  15231. break;
  15232. }
  15233. #if defined(MG_LEGACY_INTERFACE)
  15234. /* Legacy before split into local_uri and request_uri */
  15235. conn->request_info.uri = conn->request_info.local_uri;
  15236. #endif
  15237. }
  15238. DEBUG_TRACE("http: %s, error: %s",
  15239. (ri->http_version ? ri->http_version : "none"),
  15240. (ebuf[0] ? ebuf : "none"));
  15241. if (ebuf[0] == '\0') {
  15242. if (conn->request_info.local_uri) {
  15243. /* handle request to local server */
  15244. #if defined(USE_SERVER_STATS)
  15245. conn->conn_state = 4; /* processing */
  15246. #endif
  15247. handle_request(conn);
  15248. #if defined(USE_SERVER_STATS)
  15249. conn->conn_state = 5; /* processed */
  15250. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15251. conn->consumed_content);
  15252. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15253. conn->num_bytes_sent);
  15254. #endif
  15255. DEBUG_TRACE("%s", "handle_request done");
  15256. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15257. conn->phys_ctx->callbacks.end_request(conn,
  15258. conn->status_code);
  15259. DEBUG_TRACE("%s", "end_request callback done");
  15260. }
  15261. log_access(conn);
  15262. } else {
  15263. /* TODO: handle non-local request (PROXY) */
  15264. conn->must_close = 1;
  15265. }
  15266. } else {
  15267. conn->must_close = 1;
  15268. }
  15269. if (ri->remote_user != NULL) {
  15270. mg_free((void *)ri->remote_user);
  15271. /* Important! When having connections with and without auth
  15272. * would cause double free and then crash */
  15273. ri->remote_user = NULL;
  15274. }
  15275. /* NOTE(lsm): order is important here. should_keep_alive() call
  15276. * is using parsed request, which will be invalid after
  15277. * memmove's below.
  15278. * Therefore, memorize should_keep_alive() result now for later
  15279. * use in loop exit condition. */
  15280. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15281. && (conn->content_len >= 0);
  15282. /* Discard all buffered data for this request */
  15283. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  15284. && ((conn->request_len + conn->content_len)
  15285. < (int64_t)conn->data_len))
  15286. ? (int)(conn->request_len + conn->content_len)
  15287. : conn->data_len;
  15288. DEBUG_ASSERT(discard_len >= 0);
  15289. if (discard_len < 0) {
  15290. DEBUG_TRACE("internal error: discard_len = %li",
  15291. (long int)discard_len);
  15292. break;
  15293. }
  15294. conn->data_len -= discard_len;
  15295. if (conn->data_len > 0) {
  15296. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  15297. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  15298. }
  15299. DEBUG_ASSERT(conn->data_len >= 0);
  15300. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15301. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15302. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15303. (long int)conn->data_len,
  15304. (long int)conn->buf_size);
  15305. break;
  15306. }
  15307. conn->handled_requests++;
  15308. } while (keep_alive);
  15309. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15310. conn->request_info.remote_addr,
  15311. difftime(time(NULL), conn->conn_birth_time));
  15312. close_connection(conn);
  15313. #if defined(USE_SERVER_STATS)
  15314. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15315. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15316. #endif
  15317. }
  15318. #if defined(ALTERNATIVE_QUEUE)
  15319. static void
  15320. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15321. {
  15322. unsigned int i;
  15323. while (!ctx->stop_flag) {
  15324. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15325. /* find a free worker slot and signal it */
  15326. if (ctx->client_socks[i].in_use == 2) {
  15327. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15328. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15329. ctx->client_socks[i] = *sp;
  15330. ctx->client_socks[i].in_use = 1;
  15331. /* socket has been moved to the consumer */
  15332. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15333. (void)event_signal(ctx->client_wait_events[i]);
  15334. return;
  15335. }
  15336. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15337. }
  15338. }
  15339. /* queue is full */
  15340. mg_sleep(1);
  15341. }
  15342. /* must consume */
  15343. set_blocking_mode(sp->sock);
  15344. closesocket(sp->sock);
  15345. }
  15346. static int
  15347. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15348. {
  15349. DEBUG_TRACE("%s", "going idle");
  15350. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15351. ctx->client_socks[thread_index].in_use = 2;
  15352. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15353. event_wait(ctx->client_wait_events[thread_index]);
  15354. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15355. *sp = ctx->client_socks[thread_index];
  15356. if (ctx->stop_flag) {
  15357. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15358. if (sp->in_use == 1) {
  15359. /* must consume */
  15360. set_blocking_mode(sp->sock);
  15361. closesocket(sp->sock);
  15362. }
  15363. return 0;
  15364. }
  15365. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15366. if (sp->in_use == 1) {
  15367. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15368. return 1;
  15369. }
  15370. /* must not reach here */
  15371. DEBUG_ASSERT(0);
  15372. return 0;
  15373. }
  15374. #else /* ALTERNATIVE_QUEUE */
  15375. /* Worker threads take accepted socket from the queue */
  15376. static int
  15377. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15378. {
  15379. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15380. (void)thread_index;
  15381. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15382. DEBUG_TRACE("%s", "going idle");
  15383. /* If the queue is empty, wait. We're idle at this point. */
  15384. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15385. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15386. }
  15387. /* If we're stopping, sq_head may be equal to sq_tail. */
  15388. if (ctx->sq_head > ctx->sq_tail) {
  15389. /* Copy socket from the queue and increment tail */
  15390. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15391. ctx->sq_tail++;
  15392. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15393. /* Wrap pointers if needed */
  15394. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15395. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15396. ctx->sq_head -= QUEUE_SIZE(ctx);
  15397. }
  15398. }
  15399. (void)pthread_cond_signal(&ctx->sq_empty);
  15400. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15401. return !ctx->stop_flag;
  15402. #undef QUEUE_SIZE
  15403. }
  15404. /* Master thread adds accepted socket to a queue */
  15405. static void
  15406. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15407. {
  15408. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15409. if (!ctx) {
  15410. return;
  15411. }
  15412. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15413. /* If the queue is full, wait */
  15414. while ((ctx->stop_flag == 0)
  15415. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15416. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15417. }
  15418. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15419. /* Copy socket to the queue and increment head */
  15420. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15421. ctx->sq_head++;
  15422. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15423. }
  15424. (void)pthread_cond_signal(&ctx->sq_full);
  15425. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15426. #undef QUEUE_SIZE
  15427. }
  15428. #endif /* ALTERNATIVE_QUEUE */
  15429. static void
  15430. worker_thread_run(struct mg_connection *conn)
  15431. {
  15432. struct mg_context *ctx = conn->phys_ctx;
  15433. int thread_index;
  15434. struct mg_workerTLS tls;
  15435. #if defined(MG_LEGACY_INTERFACE)
  15436. uint32_t addr;
  15437. #endif
  15438. mg_set_thread_name("worker");
  15439. tls.is_master = 0;
  15440. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15441. #if defined(_WIN32)
  15442. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15443. #endif
  15444. /* Initialize thread local storage before calling any callback */
  15445. pthread_setspecific(sTlsKey, &tls);
  15446. /* Check if there is a user callback */
  15447. if (ctx->callbacks.init_thread) {
  15448. /* call init_thread for a worker thread (type 1), and store the return
  15449. * value */
  15450. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  15451. } else {
  15452. /* No callback: set user pointer to NULL */
  15453. tls.user_ptr = NULL;
  15454. }
  15455. /* Connection structure has been pre-allocated */
  15456. thread_index = (int)(conn - ctx->worker_connections);
  15457. if ((thread_index < 0)
  15458. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  15459. mg_cry_internal(fc(ctx),
  15460. "Internal error: Invalid worker index %i",
  15461. thread_index);
  15462. return;
  15463. }
  15464. /* Request buffers are not pre-allocated. They are private to the
  15465. * request and do not contain any state information that might be
  15466. * of interest to anyone observing a server status. */
  15467. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15468. if (conn->buf == NULL) {
  15469. mg_cry_internal(fc(ctx),
  15470. "Out of memory: Cannot allocate buffer for worker %i",
  15471. thread_index);
  15472. return;
  15473. }
  15474. conn->buf_size = (int)ctx->max_request_size;
  15475. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15476. conn->host = NULL; /* until we have more information. */
  15477. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  15478. conn->request_info.user_data = ctx->user_data;
  15479. /* Allocate a mutex for this connection to allow communication both
  15480. * within the request handler and from elsewhere in the application
  15481. */
  15482. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15483. mg_free(conn->buf);
  15484. mg_cry_internal(fc(ctx), "%s", "Cannot create mutex");
  15485. return;
  15486. }
  15487. #if defined(USE_SERVER_STATS)
  15488. conn->conn_state = 1; /* not consumed */
  15489. #endif
  15490. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15491. * signal sq_empty condvar to wake up the master waiting in
  15492. * produce_socket() */
  15493. while (consume_socket(ctx, &conn->client, thread_index)) {
  15494. conn->conn_birth_time = time(NULL);
  15495. /* Fill in IP, port info early so even if SSL setup below fails,
  15496. * error handler would have the corresponding info.
  15497. * Thanks to Johannes Winkelmann for the patch.
  15498. */
  15499. #if defined(USE_IPV6)
  15500. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15501. conn->request_info.remote_port =
  15502. ntohs(conn->client.rsa.sin6.sin6_port);
  15503. } else
  15504. #endif
  15505. {
  15506. conn->request_info.remote_port =
  15507. ntohs(conn->client.rsa.sin.sin_port);
  15508. }
  15509. sockaddr_to_string(conn->request_info.remote_addr,
  15510. sizeof(conn->request_info.remote_addr),
  15511. &conn->client.rsa);
  15512. DEBUG_TRACE("Start processing connection from %s",
  15513. conn->request_info.remote_addr);
  15514. conn->request_info.is_ssl = conn->client.is_ssl;
  15515. if (conn->client.is_ssl) {
  15516. #if !defined(NO_SSL)
  15517. /* HTTPS connection */
  15518. if (sslize(conn,
  15519. conn->dom_ctx->ssl_ctx,
  15520. SSL_accept,
  15521. &(conn->phys_ctx->stop_flag),
  15522. NULL)) {
  15523. /* conn->dom_ctx is set in get_request */
  15524. /* Get SSL client certificate information (if set) */
  15525. ssl_get_client_cert_info(conn);
  15526. /* process HTTPS connection */
  15527. process_new_connection(conn);
  15528. /* Free client certificate info */
  15529. if (conn->request_info.client_cert) {
  15530. mg_free((void *)(conn->request_info.client_cert->subject));
  15531. mg_free((void *)(conn->request_info.client_cert->issuer));
  15532. mg_free((void *)(conn->request_info.client_cert->serial));
  15533. mg_free((void *)(conn->request_info.client_cert->finger));
  15534. /* Free certificate memory */
  15535. X509_free(
  15536. (X509 *)conn->request_info.client_cert->peer_cert);
  15537. conn->request_info.client_cert->peer_cert = 0;
  15538. conn->request_info.client_cert->subject = 0;
  15539. conn->request_info.client_cert->issuer = 0;
  15540. conn->request_info.client_cert->serial = 0;
  15541. conn->request_info.client_cert->finger = 0;
  15542. mg_free(conn->request_info.client_cert);
  15543. conn->request_info.client_cert = 0;
  15544. }
  15545. } else {
  15546. /* make sure the connection is cleaned up on SSL failure */
  15547. close_connection(conn);
  15548. }
  15549. #endif
  15550. } else {
  15551. /* process HTTP connection */
  15552. process_new_connection(conn);
  15553. }
  15554. DEBUG_TRACE("%s", "Connection closed");
  15555. }
  15556. /* Call exit thread user callback */
  15557. if (ctx->callbacks.exit_thread) {
  15558. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  15559. }
  15560. /* delete thread local storage objects */
  15561. pthread_setspecific(sTlsKey, NULL);
  15562. #if defined(_WIN32)
  15563. CloseHandle(tls.pthread_cond_helper_mutex);
  15564. #endif
  15565. pthread_mutex_destroy(&conn->mutex);
  15566. /* Free the request buffer. */
  15567. conn->buf_size = 0;
  15568. mg_free(conn->buf);
  15569. conn->buf = NULL;
  15570. #if defined(USE_SERVER_STATS)
  15571. conn->conn_state = 9; /* done */
  15572. #endif
  15573. DEBUG_TRACE("%s", "exiting");
  15574. }
  15575. /* Threads have different return types on Windows and Unix. */
  15576. #if defined(_WIN32)
  15577. static unsigned __stdcall worker_thread(void *thread_func_param)
  15578. {
  15579. worker_thread_run((struct mg_connection *)thread_func_param);
  15580. return 0;
  15581. }
  15582. #else
  15583. static void *
  15584. worker_thread(void *thread_func_param)
  15585. {
  15586. struct sigaction sa;
  15587. /* Ignore SIGPIPE */
  15588. memset(&sa, 0, sizeof(sa));
  15589. sa.sa_handler = SIG_IGN;
  15590. sigaction(SIGPIPE, &sa, NULL);
  15591. worker_thread_run((struct mg_connection *)thread_func_param);
  15592. return NULL;
  15593. }
  15594. #endif /* _WIN32 */
  15595. /* This is an internal function, thus all arguments are expected to be
  15596. * valid - a NULL check is not required. */
  15597. static void
  15598. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15599. {
  15600. struct socket so;
  15601. char src_addr[IP_ADDR_STR_LEN];
  15602. socklen_t len = sizeof(so.rsa);
  15603. int on = 1;
  15604. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15605. == INVALID_SOCKET) {
  15606. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15607. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15608. mg_cry_internal(fc(ctx),
  15609. "%s: %s is not allowed to connect",
  15610. __func__,
  15611. src_addr);
  15612. closesocket(so.sock);
  15613. } else {
  15614. /* Put so socket structure into the queue */
  15615. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15616. set_close_on_exec(so.sock, fc(ctx));
  15617. so.is_ssl = listener->is_ssl;
  15618. so.ssl_redir = listener->ssl_redir;
  15619. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15620. mg_cry_internal(fc(ctx),
  15621. "%s: getsockname() failed: %s",
  15622. __func__,
  15623. strerror(ERRNO));
  15624. }
  15625. /* Set TCP keep-alive. This is needed because if HTTP-level
  15626. * keep-alive
  15627. * is enabled, and client resets the connection, server won't get
  15628. * TCP FIN or RST and will keep the connection open forever. With
  15629. * TCP keep-alive, next keep-alive handshake will figure out that
  15630. * the client is down and will close the server end.
  15631. * Thanks to Igor Klopov who suggested the patch. */
  15632. if (setsockopt(so.sock,
  15633. SOL_SOCKET,
  15634. SO_KEEPALIVE,
  15635. (SOCK_OPT_TYPE)&on,
  15636. sizeof(on))
  15637. != 0) {
  15638. mg_cry_internal(
  15639. fc(ctx),
  15640. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15641. __func__,
  15642. strerror(ERRNO));
  15643. }
  15644. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15645. * to effectively fill up the underlying IP packet payload and
  15646. * reduce the overhead of sending lots of small buffers. However
  15647. * this hurts the server's throughput (ie. operations per second)
  15648. * when HTTP 1.1 persistent connections are used and the responses
  15649. * are relatively small (eg. less than 1400 bytes).
  15650. */
  15651. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15652. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15653. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15654. mg_cry_internal(
  15655. fc(ctx),
  15656. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15657. __func__,
  15658. strerror(ERRNO));
  15659. }
  15660. }
  15661. /* We are using non-blocking sockets. Thus, the
  15662. * set_sock_timeout(so.sock, timeout);
  15663. * call is no longer required. */
  15664. /* The "non blocking" property should already be
  15665. * inherited from the parent socket. Set it for
  15666. * non-compliant socket implementations. */
  15667. set_non_blocking_mode(so.sock);
  15668. so.in_use = 0;
  15669. produce_socket(ctx, &so);
  15670. }
  15671. }
  15672. static void
  15673. master_thread_run(struct mg_context *ctx)
  15674. {
  15675. struct mg_workerTLS tls;
  15676. struct mg_pollfd *pfd;
  15677. unsigned int i;
  15678. unsigned int workerthreadcount;
  15679. if (!ctx) {
  15680. return;
  15681. }
  15682. mg_set_thread_name("master");
  15683. /* Increase priority of the master thread */
  15684. #if defined(_WIN32)
  15685. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15686. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15687. int min_prio = sched_get_priority_min(SCHED_RR);
  15688. int max_prio = sched_get_priority_max(SCHED_RR);
  15689. if ((min_prio >= 0) && (max_prio >= 0)
  15690. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15691. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15692. struct sched_param sched_param = {0};
  15693. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15694. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15695. }
  15696. #endif
  15697. /* Initialize thread local storage */
  15698. #if defined(_WIN32)
  15699. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15700. #endif
  15701. tls.is_master = 1;
  15702. pthread_setspecific(sTlsKey, &tls);
  15703. if (ctx->callbacks.init_thread) {
  15704. /* Callback for the master thread (type 0) */
  15705. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  15706. } else {
  15707. tls.user_ptr = NULL;
  15708. }
  15709. /* Server starts *now* */
  15710. ctx->start_time = time(NULL);
  15711. /* Start the server */
  15712. pfd = ctx->listening_socket_fds;
  15713. while (ctx->stop_flag == 0) {
  15714. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15715. pfd[i].fd = ctx->listening_sockets[i].sock;
  15716. pfd[i].events = POLLIN;
  15717. }
  15718. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15719. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15720. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15721. * successful poll, and POLLIN is defined as
  15722. * (POLLRDNORM | POLLRDBAND)
  15723. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15724. * pfd[i].revents == POLLIN. */
  15725. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15726. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15727. }
  15728. }
  15729. }
  15730. }
  15731. /* Here stop_flag is 1 - Initiate shutdown. */
  15732. DEBUG_TRACE("%s", "stopping workers");
  15733. /* Stop signal received: somebody called mg_stop. Quit. */
  15734. close_all_listening_sockets(ctx);
  15735. /* Wakeup workers that are waiting for connections to handle. */
  15736. #if defined(ALTERNATIVE_QUEUE)
  15737. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15738. event_signal(ctx->client_wait_events[i]);
  15739. }
  15740. #else
  15741. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15742. pthread_cond_broadcast(&ctx->sq_full);
  15743. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15744. #endif
  15745. /* Join all worker threads to avoid leaking threads. */
  15746. workerthreadcount = ctx->cfg_worker_threads;
  15747. for (i = 0; i < workerthreadcount; i++) {
  15748. if (ctx->worker_threadids[i] != 0) {
  15749. mg_join_thread(ctx->worker_threadids[i]);
  15750. }
  15751. }
  15752. #if defined(USE_LUA)
  15753. /* Free Lua state of lua background task */
  15754. if (ctx->lua_background_state) {
  15755. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15756. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15757. if (lua_istable(lstate, -1)) {
  15758. reg_boolean(lstate, "shutdown", 1);
  15759. lua_pop(lstate, 1);
  15760. mg_sleep(2);
  15761. }
  15762. lua_close(lstate);
  15763. ctx->lua_background_state = 0;
  15764. }
  15765. #endif
  15766. DEBUG_TRACE("%s", "exiting");
  15767. /* call exit thread callback */
  15768. if (ctx->callbacks.exit_thread) {
  15769. /* Callback for the master thread (type 0) */
  15770. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  15771. }
  15772. #if defined(_WIN32)
  15773. CloseHandle(tls.pthread_cond_helper_mutex);
  15774. #endif
  15775. pthread_setspecific(sTlsKey, NULL);
  15776. /* Signal mg_stop() that we're done.
  15777. * WARNING: This must be the very last thing this
  15778. * thread does, as ctx becomes invalid after this line. */
  15779. ctx->stop_flag = 2;
  15780. }
  15781. /* Threads have different return types on Windows and Unix. */
  15782. #if defined(_WIN32)
  15783. static unsigned __stdcall master_thread(void *thread_func_param)
  15784. {
  15785. master_thread_run((struct mg_context *)thread_func_param);
  15786. return 0;
  15787. }
  15788. #else
  15789. static void *
  15790. master_thread(void *thread_func_param)
  15791. {
  15792. struct sigaction sa;
  15793. /* Ignore SIGPIPE */
  15794. memset(&sa, 0, sizeof(sa));
  15795. sa.sa_handler = SIG_IGN;
  15796. sigaction(SIGPIPE, &sa, NULL);
  15797. master_thread_run((struct mg_context *)thread_func_param);
  15798. return NULL;
  15799. }
  15800. #endif /* _WIN32 */
  15801. static void
  15802. free_context(struct mg_context *ctx)
  15803. {
  15804. int i;
  15805. struct mg_handler_info *tmp_rh;
  15806. if (ctx == NULL) {
  15807. return;
  15808. }
  15809. if (ctx->callbacks.exit_context) {
  15810. ctx->callbacks.exit_context(ctx);
  15811. }
  15812. /* All threads exited, no sync is needed. Destroy thread mutex and
  15813. * condvars
  15814. */
  15815. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15816. #if defined(ALTERNATIVE_QUEUE)
  15817. mg_free(ctx->client_socks);
  15818. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15819. event_destroy(ctx->client_wait_events[i]);
  15820. }
  15821. mg_free(ctx->client_wait_events);
  15822. #else
  15823. (void)pthread_cond_destroy(&ctx->sq_empty);
  15824. (void)pthread_cond_destroy(&ctx->sq_full);
  15825. #endif
  15826. /* Destroy other context global data structures mutex */
  15827. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15828. #if defined(USE_TIMERS)
  15829. timers_exit(ctx);
  15830. #endif
  15831. /* Deallocate config parameters */
  15832. for (i = 0; i < NUM_OPTIONS; i++) {
  15833. if (ctx->dd.config[i] != NULL) {
  15834. #if defined(_MSC_VER)
  15835. #pragma warning(suppress : 6001)
  15836. #endif
  15837. mg_free(ctx->dd.config[i]);
  15838. }
  15839. }
  15840. /* Deallocate request handlers */
  15841. while (ctx->dd.handlers) {
  15842. tmp_rh = ctx->dd.handlers;
  15843. ctx->dd.handlers = tmp_rh->next;
  15844. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15845. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15846. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15847. }
  15848. mg_free(tmp_rh->uri);
  15849. mg_free(tmp_rh);
  15850. }
  15851. #if !defined(NO_SSL)
  15852. /* Deallocate SSL context */
  15853. if (ctx->dd.ssl_ctx != NULL) {
  15854. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15855. int callback_ret =
  15856. (ctx->callbacks.external_ssl_ctx == NULL)
  15857. ? 0
  15858. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15859. if (callback_ret == 0) {
  15860. SSL_CTX_free(ctx->dd.ssl_ctx);
  15861. }
  15862. /* else: ignore error and ommit SSL_CTX_free in case
  15863. * callback_ret is 1 */
  15864. }
  15865. #endif /* !NO_SSL */
  15866. /* Deallocate worker thread ID array */
  15867. mg_free(ctx->worker_threadids);
  15868. /* Deallocate worker thread ID array */
  15869. mg_free(ctx->worker_connections);
  15870. /* deallocate system name string */
  15871. mg_free(ctx->systemName);
  15872. /* Deallocate context itself */
  15873. mg_free(ctx);
  15874. }
  15875. void
  15876. mg_stop(struct mg_context *ctx)
  15877. {
  15878. pthread_t mt;
  15879. if (!ctx) {
  15880. return;
  15881. }
  15882. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15883. * two threads is not allowed. */
  15884. mt = ctx->masterthreadid;
  15885. if (mt == 0) {
  15886. return;
  15887. }
  15888. ctx->masterthreadid = 0;
  15889. /* Set stop flag, so all threads know they have to exit. */
  15890. ctx->stop_flag = 1;
  15891. /* Wait until everything has stopped. */
  15892. while (ctx->stop_flag != 2) {
  15893. (void)mg_sleep(10);
  15894. }
  15895. mg_join_thread(mt);
  15896. free_context(ctx);
  15897. #if defined(_WIN32)
  15898. (void)WSACleanup();
  15899. #endif /* _WIN32 */
  15900. }
  15901. static void
  15902. get_system_name(char **sysName)
  15903. {
  15904. #if defined(_WIN32)
  15905. #if !defined(__SYMBIAN32__)
  15906. #if defined(_WIN32_WCE)
  15907. *sysName = mg_strdup("WinCE");
  15908. #else
  15909. char name[128];
  15910. DWORD dwVersion = 0;
  15911. DWORD dwMajorVersion = 0;
  15912. DWORD dwMinorVersion = 0;
  15913. DWORD dwBuild = 0;
  15914. BOOL wowRet, isWoW = FALSE;
  15915. #if defined(_MSC_VER)
  15916. #pragma warning(push)
  15917. /* GetVersion was declared deprecated */
  15918. #pragma warning(disable : 4996)
  15919. #endif
  15920. dwVersion = GetVersion();
  15921. #if defined(_MSC_VER)
  15922. #pragma warning(pop)
  15923. #endif
  15924. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15925. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15926. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15927. (void)dwBuild;
  15928. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15929. sprintf(name,
  15930. "Windows %u.%u%s",
  15931. (unsigned)dwMajorVersion,
  15932. (unsigned)dwMinorVersion,
  15933. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15934. *sysName = mg_strdup(name);
  15935. #endif
  15936. #else
  15937. *sysName = mg_strdup("Symbian");
  15938. #endif
  15939. #else
  15940. struct utsname name;
  15941. memset(&name, 0, sizeof(name));
  15942. uname(&name);
  15943. *sysName = mg_strdup(name.sysname);
  15944. #endif
  15945. }
  15946. struct mg_context *
  15947. mg_start(const struct mg_callbacks *callbacks,
  15948. void *user_data,
  15949. const char **options)
  15950. {
  15951. struct mg_context *ctx;
  15952. const char *name, *value, *default_value;
  15953. int idx, ok, workerthreadcount;
  15954. unsigned int i;
  15955. int itmp;
  15956. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15957. struct mg_workerTLS tls;
  15958. #if defined(_WIN32)
  15959. WSADATA data;
  15960. WSAStartup(MAKEWORD(2, 2), &data);
  15961. #endif /* _WIN32 */
  15962. /* Allocate context and initialize reasonable general case defaults. */
  15963. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15964. return NULL;
  15965. }
  15966. /* Random number generator will initialize at the first call */
  15967. ctx->dd.auth_nonce_mask =
  15968. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15969. if (mg_init_library_called == 0) {
  15970. /* Legacy INIT, if mg_start is called without mg_init_library.
  15971. * Note: This may cause a memory leak */
  15972. const char *ports_option =
  15973. config_options[LISTENING_PORTS].default_value;
  15974. if (options) {
  15975. const char **run_options = options;
  15976. const char *optname = config_options[LISTENING_PORTS].name;
  15977. /* Try to find the "listening_ports" option */
  15978. while (*run_options) {
  15979. if (!strcmp(*run_options, optname)) {
  15980. ports_option = run_options[1];
  15981. }
  15982. run_options += 2;
  15983. }
  15984. }
  15985. if (is_ssl_port_used(ports_option)) {
  15986. /* Initialize with SSL support */
  15987. mg_init_library(MG_FEATURES_TLS);
  15988. } else {
  15989. /* Initialize without SSL support */
  15990. mg_init_library(MG_FEATURES_DEFAULT);
  15991. }
  15992. }
  15993. tls.is_master = -1;
  15994. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15995. #if defined(_WIN32)
  15996. tls.pthread_cond_helper_mutex = NULL;
  15997. #endif
  15998. pthread_setspecific(sTlsKey, &tls);
  15999. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  16000. #if !defined(ALTERNATIVE_QUEUE)
  16001. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  16002. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  16003. #endif
  16004. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  16005. if (!ok) {
  16006. /* Fatal error - abort start. However, this situation should never
  16007. * occur in practice. */
  16008. mg_cry_internal(fc(ctx),
  16009. "%s",
  16010. "Cannot initialize thread synchronization objects");
  16011. mg_free(ctx);
  16012. pthread_setspecific(sTlsKey, NULL);
  16013. return NULL;
  16014. }
  16015. if (callbacks) {
  16016. ctx->callbacks = *callbacks;
  16017. exit_callback = callbacks->exit_context;
  16018. ctx->callbacks.exit_context = 0;
  16019. }
  16020. ctx->user_data = user_data;
  16021. ctx->dd.handlers = NULL;
  16022. ctx->dd.next = NULL;
  16023. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16024. ctx->dd.shared_lua_websockets = NULL;
  16025. #endif
  16026. /* Store options */
  16027. while (options && (name = *options++) != NULL) {
  16028. if ((idx = get_option_index(name)) == -1) {
  16029. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  16030. free_context(ctx);
  16031. pthread_setspecific(sTlsKey, NULL);
  16032. return NULL;
  16033. } else if ((value = *options++) == NULL) {
  16034. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  16035. free_context(ctx);
  16036. pthread_setspecific(sTlsKey, NULL);
  16037. return NULL;
  16038. }
  16039. if (ctx->dd.config[idx] != NULL) {
  16040. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  16041. mg_free(ctx->dd.config[idx]);
  16042. }
  16043. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  16044. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16045. }
  16046. /* Set default value if needed */
  16047. for (i = 0; config_options[i].name != NULL; i++) {
  16048. default_value = config_options[i].default_value;
  16049. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  16050. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  16051. }
  16052. }
  16053. /* Request size option */
  16054. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  16055. if (itmp < 1024) {
  16056. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  16057. free_context(ctx);
  16058. pthread_setspecific(sTlsKey, NULL);
  16059. return NULL;
  16060. }
  16061. ctx->max_request_size = (unsigned)itmp;
  16062. /* Worker thread count option */
  16063. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  16064. if (workerthreadcount > MAX_WORKER_THREADS) {
  16065. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  16066. free_context(ctx);
  16067. pthread_setspecific(sTlsKey, NULL);
  16068. return NULL;
  16069. }
  16070. if (workerthreadcount <= 0) {
  16071. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  16072. free_context(ctx);
  16073. pthread_setspecific(sTlsKey, NULL);
  16074. return NULL;
  16075. }
  16076. /* Document root */
  16077. #if defined(NO_FILES)
  16078. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16079. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  16080. free_context(ctx);
  16081. pthread_setspecific(sTlsKey, NULL);
  16082. return NULL;
  16083. }
  16084. #endif
  16085. get_system_name(&ctx->systemName);
  16086. #if defined(USE_LUA)
  16087. /* If a Lua background script has been configured, start it. */
  16088. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16089. char ebuf[256];
  16090. struct vec opt_vec;
  16091. struct vec eq_vec;
  16092. const char *sparams;
  16093. lua_State *state = mg_prepare_lua_context_script(
  16094. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16095. if (!state) {
  16096. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  16097. free_context(ctx);
  16098. pthread_setspecific(sTlsKey, NULL);
  16099. return NULL;
  16100. }
  16101. ctx->lua_background_state = (void *)state;
  16102. lua_newtable(state);
  16103. reg_boolean(state, "shutdown", 0);
  16104. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16105. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16106. reg_llstring(
  16107. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16108. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16109. break;
  16110. }
  16111. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16112. } else {
  16113. ctx->lua_background_state = 0;
  16114. }
  16115. #endif
  16116. /* NOTE(lsm): order is important here. SSL certificates must
  16117. * be initialized before listening ports. UID must be set last. */
  16118. if (!set_gpass_option(ctx, NULL) ||
  16119. #if !defined(NO_SSL)
  16120. !init_ssl_ctx(ctx, NULL) ||
  16121. #endif
  16122. !set_ports_option(ctx) ||
  16123. #if !defined(_WIN32)
  16124. !set_uid_option(ctx) ||
  16125. #endif
  16126. !set_acl_option(ctx)) {
  16127. free_context(ctx);
  16128. pthread_setspecific(sTlsKey, NULL);
  16129. return NULL;
  16130. }
  16131. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16132. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16133. sizeof(pthread_t),
  16134. ctx);
  16135. if (ctx->worker_threadids == NULL) {
  16136. mg_cry_internal(fc(ctx),
  16137. "%s",
  16138. "Not enough memory for worker thread ID array");
  16139. free_context(ctx);
  16140. pthread_setspecific(sTlsKey, NULL);
  16141. return NULL;
  16142. }
  16143. ctx->worker_connections =
  16144. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16145. sizeof(struct mg_connection),
  16146. ctx);
  16147. if (ctx->worker_connections == NULL) {
  16148. mg_cry_internal(fc(ctx),
  16149. "%s",
  16150. "Not enough memory for worker thread connection array");
  16151. free_context(ctx);
  16152. pthread_setspecific(sTlsKey, NULL);
  16153. return NULL;
  16154. }
  16155. #if defined(ALTERNATIVE_QUEUE)
  16156. ctx->client_wait_events =
  16157. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  16158. ctx->cfg_worker_threads,
  16159. ctx);
  16160. if (ctx->client_wait_events == NULL) {
  16161. mg_cry_internal(fc(ctx),
  16162. "%s",
  16163. "Not enough memory for worker event array");
  16164. mg_free(ctx->worker_threadids);
  16165. free_context(ctx);
  16166. pthread_setspecific(sTlsKey, NULL);
  16167. return NULL;
  16168. }
  16169. ctx->client_socks =
  16170. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  16171. ctx->cfg_worker_threads,
  16172. ctx);
  16173. if (ctx->client_socks == NULL) {
  16174. mg_cry_internal(fc(ctx),
  16175. "%s",
  16176. "Not enough memory for worker socket array");
  16177. mg_free(ctx->client_wait_events);
  16178. mg_free(ctx->worker_threadids);
  16179. free_context(ctx);
  16180. pthread_setspecific(sTlsKey, NULL);
  16181. return NULL;
  16182. }
  16183. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16184. ctx->client_wait_events[i] = event_create();
  16185. if (ctx->client_wait_events[i] == 0) {
  16186. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  16187. while (i > 0) {
  16188. i--;
  16189. event_destroy(ctx->client_wait_events[i]);
  16190. }
  16191. mg_free(ctx->client_socks);
  16192. mg_free(ctx->client_wait_events);
  16193. mg_free(ctx->worker_threadids);
  16194. free_context(ctx);
  16195. pthread_setspecific(sTlsKey, NULL);
  16196. return NULL;
  16197. }
  16198. }
  16199. #endif
  16200. #if defined(USE_TIMERS)
  16201. if (timers_init(ctx) != 0) {
  16202. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  16203. free_context(ctx);
  16204. pthread_setspecific(sTlsKey, NULL);
  16205. return NULL;
  16206. }
  16207. #endif
  16208. /* Context has been created - init user libraries */
  16209. if (ctx->callbacks.init_context) {
  16210. ctx->callbacks.init_context(ctx);
  16211. }
  16212. ctx->callbacks.exit_context = exit_callback;
  16213. ctx->context_type = CONTEXT_SERVER; /* server context */
  16214. /* Start master (listening) thread */
  16215. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16216. /* Start worker threads */
  16217. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16218. /* worker_thread sets up the other fields */
  16219. ctx->worker_connections[i].phys_ctx = ctx;
  16220. if (mg_start_thread_with_id(worker_thread,
  16221. &ctx->worker_connections[i],
  16222. &ctx->worker_threadids[i])
  16223. != 0) {
  16224. /* thread was not created */
  16225. if (i > 0) {
  16226. mg_cry_internal(fc(ctx),
  16227. "Cannot start worker thread %i: error %ld",
  16228. i + 1,
  16229. (long)ERRNO);
  16230. } else {
  16231. mg_cry_internal(fc(ctx),
  16232. "Cannot create threads: error %ld",
  16233. (long)ERRNO);
  16234. free_context(ctx);
  16235. pthread_setspecific(sTlsKey, NULL);
  16236. return NULL;
  16237. }
  16238. break;
  16239. }
  16240. }
  16241. pthread_setspecific(sTlsKey, NULL);
  16242. return ctx;
  16243. }
  16244. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16245. /* Add an additional domain to an already running web server. */
  16246. int
  16247. mg_start_domain(struct mg_context *ctx, const char **options)
  16248. {
  16249. const char *name;
  16250. const char *value;
  16251. const char *default_value;
  16252. struct mg_domain_context *new_dom;
  16253. struct mg_domain_context *dom;
  16254. int idx, i;
  16255. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  16256. return -1;
  16257. }
  16258. new_dom = (struct mg_domain_context *)
  16259. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16260. if (!new_dom) {
  16261. /* Out of memory */
  16262. return -6;
  16263. }
  16264. /* Store options - TODO: unite duplicate code */
  16265. while (options && (name = *options++) != NULL) {
  16266. if ((idx = get_option_index(name)) == -1) {
  16267. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  16268. mg_free(new_dom);
  16269. return -2;
  16270. } else if ((value = *options++) == NULL) {
  16271. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  16272. mg_free(new_dom);
  16273. return -2;
  16274. }
  16275. if (new_dom->config[idx] != NULL) {
  16276. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  16277. mg_free(new_dom->config[idx]);
  16278. }
  16279. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16280. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16281. }
  16282. /* Authentication domain is mandatory */
  16283. /* TODO: Maybe use a new option hostname? */
  16284. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16285. mg_cry_internal(fc(ctx), "%s", "authentication domain required");
  16286. mg_free(new_dom);
  16287. return -4;
  16288. }
  16289. /* Set default value if needed. Take the config value from
  16290. * ctx as a default value. */
  16291. for (i = 0; config_options[i].name != NULL; i++) {
  16292. default_value = ctx->dd.config[i];
  16293. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16294. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16295. }
  16296. }
  16297. new_dom->handlers = NULL;
  16298. new_dom->next = NULL;
  16299. new_dom->nonce_count = 0;
  16300. new_dom->auth_nonce_mask =
  16301. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16302. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16303. new_dom->shared_lua_websockets = NULL;
  16304. #endif
  16305. if (!init_ssl_ctx(ctx, new_dom)) {
  16306. /* Init SSL failed */
  16307. mg_free(new_dom);
  16308. return -3;
  16309. }
  16310. /* Add element to linked list. */
  16311. mg_lock_context(ctx);
  16312. idx = 0;
  16313. dom = &(ctx->dd);
  16314. for (;;) {
  16315. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16316. dom->config[AUTHENTICATION_DOMAIN])) {
  16317. /* Domain collision */
  16318. mg_cry_internal(fc(ctx),
  16319. "domain %s already in use",
  16320. new_dom->config[AUTHENTICATION_DOMAIN]);
  16321. mg_free(new_dom);
  16322. return -5;
  16323. }
  16324. /* Count number of domains */
  16325. idx++;
  16326. if (dom->next == NULL) {
  16327. dom->next = new_dom;
  16328. break;
  16329. }
  16330. dom = dom->next;
  16331. }
  16332. mg_unlock_context(ctx);
  16333. /* Return domain number */
  16334. return idx;
  16335. }
  16336. #endif
  16337. /* Feature check API function */
  16338. unsigned
  16339. mg_check_feature(unsigned feature)
  16340. {
  16341. static const unsigned feature_set = 0
  16342. /* Set bits for available features according to API documentation.
  16343. * This bit mask is created at compile time, according to the active
  16344. * preprocessor defines. It is a single const value at runtime. */
  16345. #if !defined(NO_FILES)
  16346. | MG_FEATURES_FILES
  16347. #endif
  16348. #if !defined(NO_SSL)
  16349. | MG_FEATURES_SSL
  16350. #endif
  16351. #if !defined(NO_CGI)
  16352. | MG_FEATURES_CGI
  16353. #endif
  16354. #if defined(USE_IPV6)
  16355. | MG_FEATURES_IPV6
  16356. #endif
  16357. #if defined(USE_WEBSOCKET)
  16358. | MG_FEATURES_WEBSOCKET
  16359. #endif
  16360. #if defined(USE_LUA)
  16361. | MG_FEATURES_LUA
  16362. #endif
  16363. #if defined(USE_DUKTAPE)
  16364. | MG_FEATURES_SSJS
  16365. #endif
  16366. #if !defined(NO_CACHING)
  16367. | MG_FEATURES_CACHE
  16368. #endif
  16369. #if defined(USE_SERVER_STATS)
  16370. | MG_FEATURES_STATS
  16371. #endif
  16372. #if defined(USE_ZLIB)
  16373. | MG_FEATURES_COMPRESSION
  16374. #endif
  16375. /* Set some extra bits not defined in the API documentation.
  16376. * These bits may change without further notice. */
  16377. #if defined(MG_LEGACY_INTERFACE)
  16378. | 0x00008000u
  16379. #endif
  16380. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16381. | 0x00004000u
  16382. #endif
  16383. #if defined(MEMORY_DEBUGGING)
  16384. | 0x00001000u
  16385. #endif
  16386. #if defined(USE_TIMERS)
  16387. | 0x00020000u
  16388. #endif
  16389. #if !defined(NO_NONCE_CHECK)
  16390. | 0x00040000u
  16391. #endif
  16392. #if !defined(NO_POPEN)
  16393. | 0x00080000u
  16394. #endif
  16395. ;
  16396. return (feature & feature_set);
  16397. }
  16398. static size_t
  16399. mg_str_append(char **dst, char *end, const char *src)
  16400. {
  16401. size_t len = strlen(src);
  16402. if (*dst != end) {
  16403. /* Append src if enough space, or close dst. */
  16404. if ((size_t)(end - *dst) > len) {
  16405. strcpy(*dst, src);
  16406. *dst += len;
  16407. } else {
  16408. *dst = end;
  16409. }
  16410. }
  16411. return len;
  16412. }
  16413. /* Get system information. It can be printed or stored by the caller.
  16414. * Return the size of available information. */
  16415. int
  16416. mg_get_system_info(char *buffer, int buflen)
  16417. {
  16418. char *end, *append_eoobj = NULL, block[256];
  16419. size_t system_info_length = 0;
  16420. #if defined(_WIN32)
  16421. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16422. #else
  16423. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16424. #endif
  16425. if ((buffer == NULL) || (buflen < 1)) {
  16426. buflen = 0;
  16427. end = buffer;
  16428. } else {
  16429. *buffer = 0;
  16430. end = buffer + buflen;
  16431. }
  16432. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16433. /* has enough space to append eoobj */
  16434. append_eoobj = buffer;
  16435. end -= sizeof(eoobj) - 1;
  16436. }
  16437. system_info_length += mg_str_append(&buffer, end, "{");
  16438. /* Server version */
  16439. {
  16440. const char *version = mg_version();
  16441. mg_snprintf(NULL,
  16442. NULL,
  16443. block,
  16444. sizeof(block),
  16445. "%s\"version\" : \"%s\"",
  16446. eol,
  16447. version);
  16448. system_info_length += mg_str_append(&buffer, end, block);
  16449. }
  16450. /* System info */
  16451. {
  16452. #if defined(_WIN32)
  16453. DWORD dwVersion = 0;
  16454. DWORD dwMajorVersion = 0;
  16455. DWORD dwMinorVersion = 0;
  16456. SYSTEM_INFO si;
  16457. GetSystemInfo(&si);
  16458. #if defined(_MSC_VER)
  16459. #pragma warning(push)
  16460. /* GetVersion was declared deprecated */
  16461. #pragma warning(disable : 4996)
  16462. #endif
  16463. dwVersion = GetVersion();
  16464. #if defined(_MSC_VER)
  16465. #pragma warning(pop)
  16466. #endif
  16467. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16468. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16469. mg_snprintf(NULL,
  16470. NULL,
  16471. block,
  16472. sizeof(block),
  16473. ",%s\"os\" : \"Windows %u.%u\"",
  16474. eol,
  16475. (unsigned)dwMajorVersion,
  16476. (unsigned)dwMinorVersion);
  16477. system_info_length += mg_str_append(&buffer, end, block);
  16478. mg_snprintf(NULL,
  16479. NULL,
  16480. block,
  16481. sizeof(block),
  16482. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  16483. eol,
  16484. (unsigned)si.wProcessorArchitecture,
  16485. (unsigned)si.dwNumberOfProcessors,
  16486. (unsigned)si.dwActiveProcessorMask);
  16487. system_info_length += mg_str_append(&buffer, end, block);
  16488. #else
  16489. struct utsname name;
  16490. memset(&name, 0, sizeof(name));
  16491. uname(&name);
  16492. mg_snprintf(NULL,
  16493. NULL,
  16494. block,
  16495. sizeof(block),
  16496. ",%s\"os\" : \"%s %s (%s) - %s\"",
  16497. eol,
  16498. name.sysname,
  16499. name.version,
  16500. name.release,
  16501. name.machine);
  16502. system_info_length += mg_str_append(&buffer, end, block);
  16503. #endif
  16504. }
  16505. /* Features */
  16506. {
  16507. mg_snprintf(NULL,
  16508. NULL,
  16509. block,
  16510. sizeof(block),
  16511. ",%s\"features\" : %lu"
  16512. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  16513. eol,
  16514. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16515. eol,
  16516. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16517. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16518. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16519. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16520. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16521. : "",
  16522. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16523. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16524. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16525. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  16526. system_info_length += mg_str_append(&buffer, end, block);
  16527. #if defined(USE_LUA)
  16528. mg_snprintf(NULL,
  16529. NULL,
  16530. block,
  16531. sizeof(block),
  16532. ",%s\"lua_version\" : \"%u (%s)\"",
  16533. eol,
  16534. (unsigned)LUA_VERSION_NUM,
  16535. LUA_RELEASE);
  16536. system_info_length += mg_str_append(&buffer, end, block);
  16537. #endif
  16538. #if defined(USE_DUKTAPE)
  16539. mg_snprintf(NULL,
  16540. NULL,
  16541. block,
  16542. sizeof(block),
  16543. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  16544. eol,
  16545. (unsigned)DUK_VERSION / 10000,
  16546. ((unsigned)DUK_VERSION / 100) % 100,
  16547. (unsigned)DUK_VERSION % 100);
  16548. system_info_length += mg_str_append(&buffer, end, block);
  16549. #endif
  16550. }
  16551. /* Build date */
  16552. {
  16553. #if defined(GCC_DIAGNOSTIC)
  16554. #if GCC_VERSION >= 40900
  16555. #pragma GCC diagnostic push
  16556. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  16557. #pragma GCC diagnostic ignored "-Wdate-time"
  16558. #endif
  16559. #endif
  16560. mg_snprintf(NULL,
  16561. NULL,
  16562. block,
  16563. sizeof(block),
  16564. ",%s\"build\" : \"%s\"",
  16565. eol,
  16566. __DATE__);
  16567. #if defined(GCC_DIAGNOSTIC)
  16568. #if GCC_VERSION >= 40900
  16569. #pragma GCC diagnostic pop
  16570. #endif
  16571. #endif
  16572. system_info_length += mg_str_append(&buffer, end, block);
  16573. }
  16574. /* Compiler information */
  16575. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16576. {
  16577. #if defined(_MSC_VER)
  16578. mg_snprintf(NULL,
  16579. NULL,
  16580. block,
  16581. sizeof(block),
  16582. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  16583. eol,
  16584. (unsigned)_MSC_VER,
  16585. (unsigned)_MSC_FULL_VER);
  16586. system_info_length += mg_str_append(&buffer, end, block);
  16587. #elif defined(__MINGW64__)
  16588. mg_snprintf(NULL,
  16589. NULL,
  16590. block,
  16591. sizeof(block),
  16592. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  16593. eol,
  16594. (unsigned)__MINGW64_VERSION_MAJOR,
  16595. (unsigned)__MINGW64_VERSION_MINOR);
  16596. system_info_length += mg_str_append(&buffer, end, block);
  16597. mg_snprintf(NULL,
  16598. NULL,
  16599. block,
  16600. sizeof(block),
  16601. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16602. eol,
  16603. (unsigned)__MINGW32_MAJOR_VERSION,
  16604. (unsigned)__MINGW32_MINOR_VERSION);
  16605. system_info_length += mg_str_append(&buffer, end, block);
  16606. #elif defined(__MINGW32__)
  16607. mg_snprintf(NULL,
  16608. NULL,
  16609. block,
  16610. sizeof(block),
  16611. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16612. eol,
  16613. (unsigned)__MINGW32_MAJOR_VERSION,
  16614. (unsigned)__MINGW32_MINOR_VERSION);
  16615. system_info_length += mg_str_append(&buffer, end, block);
  16616. #elif defined(__clang__)
  16617. mg_snprintf(NULL,
  16618. NULL,
  16619. block,
  16620. sizeof(block),
  16621. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  16622. eol,
  16623. __clang_major__,
  16624. __clang_minor__,
  16625. __clang_patchlevel__,
  16626. __clang_version__);
  16627. system_info_length += mg_str_append(&buffer, end, block);
  16628. #elif defined(__GNUC__)
  16629. mg_snprintf(NULL,
  16630. NULL,
  16631. block,
  16632. sizeof(block),
  16633. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  16634. eol,
  16635. (unsigned)__GNUC__,
  16636. (unsigned)__GNUC_MINOR__,
  16637. (unsigned)__GNUC_PATCHLEVEL__);
  16638. system_info_length += mg_str_append(&buffer, end, block);
  16639. #elif defined(__INTEL_COMPILER)
  16640. mg_snprintf(NULL,
  16641. NULL,
  16642. block,
  16643. sizeof(block),
  16644. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  16645. eol,
  16646. (unsigned)__INTEL_COMPILER);
  16647. system_info_length += mg_str_append(&buffer, end, block);
  16648. #elif defined(__BORLANDC__)
  16649. mg_snprintf(NULL,
  16650. NULL,
  16651. block,
  16652. sizeof(block),
  16653. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  16654. eol,
  16655. (unsigned)__BORLANDC__);
  16656. system_info_length += mg_str_append(&buffer, end, block);
  16657. #elif defined(__SUNPRO_C)
  16658. mg_snprintf(NULL,
  16659. NULL,
  16660. block,
  16661. sizeof(block),
  16662. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  16663. eol,
  16664. (unsigned)__SUNPRO_C);
  16665. system_info_length += mg_str_append(&buffer, end, block);
  16666. #else
  16667. mg_snprintf(NULL,
  16668. NULL,
  16669. block,
  16670. sizeof(block),
  16671. ",%s\"compiler\" : \"other\"",
  16672. eol);
  16673. system_info_length += mg_str_append(&buffer, end, block);
  16674. #endif
  16675. }
  16676. /* Determine 32/64 bit data mode.
  16677. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16678. {
  16679. mg_snprintf(NULL,
  16680. NULL,
  16681. block,
  16682. sizeof(block),
  16683. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16684. "char:%u/%u, "
  16685. "ptr:%u, size:%u, time:%u\"",
  16686. eol,
  16687. (unsigned)sizeof(short),
  16688. (unsigned)sizeof(int),
  16689. (unsigned)sizeof(long),
  16690. (unsigned)sizeof(long long),
  16691. (unsigned)sizeof(float),
  16692. (unsigned)sizeof(double),
  16693. (unsigned)sizeof(long double),
  16694. (unsigned)sizeof(char),
  16695. (unsigned)sizeof(wchar_t),
  16696. (unsigned)sizeof(void *),
  16697. (unsigned)sizeof(size_t),
  16698. (unsigned)sizeof(time_t));
  16699. system_info_length += mg_str_append(&buffer, end, block);
  16700. }
  16701. /* Terminate string */
  16702. if (append_eoobj) {
  16703. strcat(append_eoobj, eoobj);
  16704. }
  16705. system_info_length += sizeof(eoobj) - 1;
  16706. return (int)system_info_length;
  16707. }
  16708. /* Get context information. It can be printed or stored by the caller.
  16709. * Return the size of available information. */
  16710. int
  16711. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16712. {
  16713. #if defined(USE_SERVER_STATS)
  16714. char *end, *append_eoobj = NULL, block[256];
  16715. size_t context_info_length = 0;
  16716. #if defined(_WIN32)
  16717. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16718. #else
  16719. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16720. #endif
  16721. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16722. if ((buffer == NULL) || (buflen < 1)) {
  16723. buflen = 0;
  16724. end = buffer;
  16725. } else {
  16726. *buffer = 0;
  16727. end = buffer + buflen;
  16728. }
  16729. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16730. /* has enough space to append eoobj */
  16731. append_eoobj = buffer;
  16732. end -= sizeof(eoobj) - 1;
  16733. }
  16734. context_info_length += mg_str_append(&buffer, end, "{");
  16735. if (ms) { /* <-- should be always true */
  16736. /* Memory information */
  16737. mg_snprintf(NULL,
  16738. NULL,
  16739. block,
  16740. sizeof(block),
  16741. "%s\"memory\" : {%s"
  16742. "\"blocks\" : %i,%s"
  16743. "\"used\" : %" INT64_FMT ",%s"
  16744. "\"maxUsed\" : %" INT64_FMT "%s"
  16745. "}",
  16746. eol,
  16747. eol,
  16748. ms->blockCount,
  16749. eol,
  16750. ms->totalMemUsed,
  16751. eol,
  16752. ms->maxMemUsed,
  16753. eol);
  16754. context_info_length += mg_str_append(&buffer, end, block);
  16755. }
  16756. if (ctx) {
  16757. /* Declare all variables at begin of the block, to comply
  16758. * with old C standards. */
  16759. char start_time_str[64] = {0};
  16760. char now_str[64] = {0};
  16761. time_t start_time = ctx->start_time;
  16762. time_t now = time(NULL);
  16763. /* Connections information */
  16764. mg_snprintf(NULL,
  16765. NULL,
  16766. block,
  16767. sizeof(block),
  16768. ",%s\"connections\" : {%s"
  16769. "\"active\" : %i,%s"
  16770. "\"maxActive\" : %i,%s"
  16771. "\"total\" : %" INT64_FMT "%s"
  16772. "}",
  16773. eol,
  16774. eol,
  16775. ctx->active_connections,
  16776. eol,
  16777. ctx->max_connections,
  16778. eol,
  16779. ctx->total_connections,
  16780. eol);
  16781. context_info_length += mg_str_append(&buffer, end, block);
  16782. /* Requests information */
  16783. mg_snprintf(NULL,
  16784. NULL,
  16785. block,
  16786. sizeof(block),
  16787. ",%s\"requests\" : {%s"
  16788. "\"total\" : %" INT64_FMT "%s"
  16789. "}",
  16790. eol,
  16791. eol,
  16792. ctx->total_requests,
  16793. eol);
  16794. context_info_length += mg_str_append(&buffer, end, block);
  16795. /* Data information */
  16796. mg_snprintf(NULL,
  16797. NULL,
  16798. block,
  16799. sizeof(block),
  16800. ",%s\"data\" : {%s"
  16801. "\"read\" : %" INT64_FMT ",%s"
  16802. "\"written\" : %" INT64_FMT "%s"
  16803. "}",
  16804. eol,
  16805. eol,
  16806. ctx->total_data_read,
  16807. eol,
  16808. ctx->total_data_written,
  16809. eol);
  16810. context_info_length += mg_str_append(&buffer, end, block);
  16811. /* Execution time information */
  16812. gmt_time_string(start_time_str,
  16813. sizeof(start_time_str) - 1,
  16814. &start_time);
  16815. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16816. mg_snprintf(NULL,
  16817. NULL,
  16818. block,
  16819. sizeof(block),
  16820. ",%s\"time\" : {%s"
  16821. "\"uptime\" : %.0f,%s"
  16822. "\"start\" : \"%s\",%s"
  16823. "\"now\" : \"%s\"%s"
  16824. "}",
  16825. eol,
  16826. eol,
  16827. difftime(now, start_time),
  16828. eol,
  16829. start_time_str,
  16830. eol,
  16831. now_str,
  16832. eol);
  16833. context_info_length += mg_str_append(&buffer, end, block);
  16834. }
  16835. /* Terminate string */
  16836. if (append_eoobj) {
  16837. strcat(append_eoobj, eoobj);
  16838. }
  16839. context_info_length += sizeof(eoobj) - 1;
  16840. return (int)context_info_length;
  16841. #else
  16842. (void)ctx;
  16843. if ((buffer != NULL) && (buflen > 0)) {
  16844. *buffer = 0;
  16845. }
  16846. return 0;
  16847. #endif
  16848. }
  16849. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16850. /* Get connection information. It can be printed or stored by the caller.
  16851. * Return the size of available information. */
  16852. int
  16853. mg_get_connection_info(const struct mg_context *ctx,
  16854. int idx,
  16855. char *buffer,
  16856. int buflen)
  16857. {
  16858. const struct mg_connection *conn;
  16859. const struct mg_request_info *ri;
  16860. char *end, *append_eoobj = NULL, block[256];
  16861. size_t connection_info_length = 0;
  16862. int state = 0;
  16863. const char *state_str = "unknown";
  16864. #if defined(_WIN32)
  16865. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16866. #else
  16867. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16868. #endif
  16869. if ((buffer == NULL) || (buflen < 1)) {
  16870. buflen = 0;
  16871. end = buffer;
  16872. } else {
  16873. *buffer = 0;
  16874. end = buffer + buflen;
  16875. }
  16876. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16877. /* has enough space to append eoobj */
  16878. append_eoobj = buffer;
  16879. end -= sizeof(eoobj) - 1;
  16880. }
  16881. if ((ctx == NULL) || (idx < 0)) {
  16882. /* Parameter error */
  16883. return 0;
  16884. }
  16885. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16886. /* Out of range */
  16887. return 0;
  16888. }
  16889. /* Take connection [idx]. This connection is not locked in
  16890. * any way, so some other thread might use it. */
  16891. conn = (ctx->worker_connections) + idx;
  16892. /* Initialize output string */
  16893. connection_info_length += mg_str_append(&buffer, end, "{");
  16894. /* Init variables */
  16895. ri = &(conn->request_info);
  16896. #if defined(USE_SERVER_STATS)
  16897. state = conn->conn_state;
  16898. /* State as string */
  16899. switch (state) {
  16900. case 0:
  16901. state_str = "undefined";
  16902. break;
  16903. case 1:
  16904. state_str = "not used";
  16905. break;
  16906. case 2:
  16907. state_str = "init";
  16908. break;
  16909. case 3:
  16910. state_str = "ready";
  16911. break;
  16912. case 4:
  16913. state_str = "processing";
  16914. break;
  16915. case 5:
  16916. state_str = "processed";
  16917. break;
  16918. case 6:
  16919. state_str = "to close";
  16920. break;
  16921. case 7:
  16922. state_str = "closing";
  16923. break;
  16924. case 8:
  16925. state_str = "closed";
  16926. break;
  16927. case 9:
  16928. state_str = "done";
  16929. break;
  16930. }
  16931. #endif
  16932. /* Connection info */
  16933. if ((state >= 3) && (state < 9)) {
  16934. mg_snprintf(NULL,
  16935. NULL,
  16936. block,
  16937. sizeof(block),
  16938. "%s\"connection\" : {%s"
  16939. "\"remote\" : {%s"
  16940. "\"protocol\" : \"%s\",%s"
  16941. "\"addr\" : \"%s\",%s"
  16942. "\"port\" : %u%s"
  16943. "},%s"
  16944. "\"handled_requests\" : %u%s"
  16945. "}",
  16946. eol,
  16947. eol,
  16948. eol,
  16949. get_proto_name(conn),
  16950. eol,
  16951. ri->remote_addr,
  16952. eol,
  16953. ri->remote_port,
  16954. eol,
  16955. eol,
  16956. conn->handled_requests,
  16957. eol);
  16958. connection_info_length += mg_str_append(&buffer, end, block);
  16959. }
  16960. /* Request info */
  16961. if ((state >= 4) && (state < 6)) {
  16962. mg_snprintf(NULL,
  16963. NULL,
  16964. block,
  16965. sizeof(block),
  16966. "%s%s\"request_info\" : {%s"
  16967. "\"method\" : \"%s\",%s"
  16968. "\"uri\" : \"%s\",%s"
  16969. "\"query\" : %s%s%s%s"
  16970. "}",
  16971. (connection_info_length > 1 ? "," : ""),
  16972. eol,
  16973. eol,
  16974. ri->request_method,
  16975. eol,
  16976. ri->request_uri,
  16977. eol,
  16978. ri->query_string ? "\"" : "",
  16979. ri->query_string ? ri->query_string : "null",
  16980. ri->query_string ? "\"" : "",
  16981. eol);
  16982. connection_info_length += mg_str_append(&buffer, end, block);
  16983. }
  16984. /* Execution time information */
  16985. if ((state >= 2) && (state < 9)) {
  16986. char start_time_str[64] = {0};
  16987. char now_str[64] = {0};
  16988. time_t start_time = conn->conn_birth_time;
  16989. time_t now = time(NULL);
  16990. gmt_time_string(start_time_str,
  16991. sizeof(start_time_str) - 1,
  16992. &start_time);
  16993. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16994. mg_snprintf(NULL,
  16995. NULL,
  16996. block,
  16997. sizeof(block),
  16998. "%s%s\"time\" : {%s"
  16999. "\"uptime\" : %.0f,%s"
  17000. "\"start\" : \"%s\",%s"
  17001. "\"now\" : \"%s\"%s"
  17002. "}",
  17003. (connection_info_length > 1 ? "," : ""),
  17004. eol,
  17005. eol,
  17006. difftime(now, start_time),
  17007. eol,
  17008. start_time_str,
  17009. eol,
  17010. now_str,
  17011. eol);
  17012. connection_info_length += mg_str_append(&buffer, end, block);
  17013. }
  17014. /* Remote user name */
  17015. if ((ri->remote_user) && (state < 9)) {
  17016. mg_snprintf(NULL,
  17017. NULL,
  17018. block,
  17019. sizeof(block),
  17020. "%s%s\"user\" : {%s"
  17021. "\"name\" : \"%s\",%s"
  17022. "}",
  17023. (connection_info_length > 1 ? "," : ""),
  17024. eol,
  17025. eol,
  17026. ri->remote_user,
  17027. eol);
  17028. connection_info_length += mg_str_append(&buffer, end, block);
  17029. }
  17030. /* Data block */
  17031. if (state >= 3) {
  17032. mg_snprintf(NULL,
  17033. NULL,
  17034. block,
  17035. sizeof(block),
  17036. "%s%s\"data\" : {%s"
  17037. "\"read\" : %" INT64_FMT ",%s"
  17038. "\"written\" : %" INT64_FMT "%s"
  17039. "}",
  17040. (connection_info_length > 1 ? "," : ""),
  17041. eol,
  17042. eol,
  17043. conn->consumed_content,
  17044. eol,
  17045. conn->num_bytes_sent,
  17046. eol);
  17047. connection_info_length += mg_str_append(&buffer, end, block);
  17048. }
  17049. /* State */
  17050. mg_snprintf(NULL,
  17051. NULL,
  17052. block,
  17053. sizeof(block),
  17054. "%s%s\"state\" : \"%s\"",
  17055. (connection_info_length > 1 ? "," : ""),
  17056. eol,
  17057. state_str);
  17058. connection_info_length += mg_str_append(&buffer, end, block);
  17059. /* Terminate string */
  17060. if (append_eoobj) {
  17061. strcat(append_eoobj, eoobj);
  17062. }
  17063. connection_info_length += sizeof(eoobj) - 1;
  17064. return (int)connection_info_length;
  17065. }
  17066. #endif
  17067. /* Initialize this library. This function does not need to be thread safe.
  17068. */
  17069. unsigned
  17070. mg_init_library(unsigned features)
  17071. {
  17072. #if !defined(NO_SSL)
  17073. char ebuf[128];
  17074. #endif
  17075. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17076. unsigned features_inited = features_to_init;
  17077. if (mg_init_library_called <= 0) {
  17078. /* Not initialized yet */
  17079. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17080. return 0;
  17081. }
  17082. }
  17083. mg_global_lock();
  17084. if (mg_init_library_called <= 0) {
  17085. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17086. /* Fatal error - abort start. However, this situation should
  17087. * never occur in practice. */
  17088. mg_global_unlock();
  17089. return 0;
  17090. }
  17091. #if defined(_WIN32)
  17092. InitializeCriticalSection(&global_log_file_lock);
  17093. #endif
  17094. #if !defined(_WIN32)
  17095. pthread_mutexattr_init(&pthread_mutex_attr);
  17096. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17097. #endif
  17098. #if defined(USE_LUA)
  17099. lua_init_optional_libraries();
  17100. #endif
  17101. }
  17102. mg_global_unlock();
  17103. #if !defined(NO_SSL)
  17104. if (features_to_init & MG_FEATURES_SSL) {
  17105. if (!mg_ssl_initialized) {
  17106. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17107. mg_ssl_initialized = 1;
  17108. } else {
  17109. (void)ebuf;
  17110. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17111. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17112. }
  17113. } else {
  17114. /* ssl already initialized */
  17115. }
  17116. }
  17117. #endif
  17118. /* Start WinSock for Windows */
  17119. mg_global_lock();
  17120. if (mg_init_library_called <= 0) {
  17121. #if defined(_WIN32)
  17122. WSADATA data;
  17123. WSAStartup(MAKEWORD(2, 2), &data);
  17124. #endif /* _WIN32 */
  17125. mg_init_library_called = 1;
  17126. } else {
  17127. mg_init_library_called++;
  17128. }
  17129. mg_global_unlock();
  17130. return features_inited;
  17131. }
  17132. /* Un-initialize this library. */
  17133. unsigned
  17134. mg_exit_library(void)
  17135. {
  17136. if (mg_init_library_called <= 0) {
  17137. return 0;
  17138. }
  17139. mg_global_lock();
  17140. mg_init_library_called--;
  17141. if (mg_init_library_called == 0) {
  17142. #if defined(_WIN32)
  17143. (void)WSACleanup();
  17144. #endif /* _WIN32 */
  17145. #if !defined(NO_SSL)
  17146. if (mg_ssl_initialized) {
  17147. uninitialize_ssl();
  17148. mg_ssl_initialized = 0;
  17149. }
  17150. #endif
  17151. #if defined(_WIN32)
  17152. (void)DeleteCriticalSection(&global_log_file_lock);
  17153. #endif /* _WIN32 */
  17154. #if !defined(_WIN32)
  17155. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17156. #endif
  17157. (void)pthread_key_delete(sTlsKey);
  17158. #if defined(USE_LUA)
  17159. lua_exit_optional_libraries();
  17160. #endif
  17161. mg_global_unlock();
  17162. (void)pthread_mutex_destroy(&global_lock_mutex);
  17163. return 1;
  17164. }
  17165. mg_global_unlock();
  17166. return 1;
  17167. }
  17168. /* End of civetweb.c */