civetweb.c 530 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931
  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(_LARGEFILE_SOURCE)
  59. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  60. #endif
  61. #if !defined(_FILE_OFFSET_BITS)
  62. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  63. #endif
  64. #if !defined(__STDC_FORMAT_MACROS)
  65. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  66. #endif
  67. #if !defined(__STDC_LIMIT_MACROS)
  68. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  69. #endif
  70. #if !defined(_DARWIN_UNLIMITED_SELECT)
  71. #define _DARWIN_UNLIMITED_SELECT
  72. #endif
  73. #if defined(__sun)
  74. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  75. #define __inline inline /* not recognized on older compiler versions */
  76. #endif
  77. #endif
  78. #if defined(__clang__)
  79. /* Enable reserved-id-macro warning again. */
  80. #pragma GCC diagnostic pop
  81. #endif
  82. #if defined(USE_LUA)
  83. #define USE_TIMERS
  84. #endif
  85. #if defined(_MSC_VER)
  86. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  87. #pragma warning(disable : 4306)
  88. /* conditional expression is constant: introduced by FD_SET(..) */
  89. #pragma warning(disable : 4127)
  90. /* non-constant aggregate initializer: issued due to missing C99 support */
  91. #pragma warning(disable : 4204)
  92. /* padding added after data member */
  93. #pragma warning(disable : 4820)
  94. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  95. #pragma warning(disable : 4668)
  96. /* no function prototype given: converting '()' to '(void)' */
  97. #pragma warning(disable : 4255)
  98. /* function has been selected for automatic inline expansion */
  99. #pragma warning(disable : 4711)
  100. #endif
  101. /* This code uses static_assert to check some conditions.
  102. * Unfortunately some compilers still do not support it, so we have a
  103. * replacement function here. */
  104. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  105. #define mg_static_assert _Static_assert
  106. #elif defined(__cplusplus) && __cplusplus >= 201103L
  107. #define mg_static_assert static_assert
  108. #else
  109. char static_assert_replacement[1];
  110. #define mg_static_assert(cond, txt) \
  111. extern char static_assert_replacement[(cond) ? 1 : -1]
  112. #endif
  113. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  114. "int data type size check");
  115. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  116. "pointer data type size check");
  117. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  118. /* Alternative queue is well tested and should be the new default */
  119. #if defined(NO_ALTERNATIVE_QUEUE)
  120. #if defined(ALTERNATIVE_QUEUE)
  121. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  122. #endif
  123. #else
  124. #define ALTERNATIVE_QUEUE
  125. #endif
  126. /* DTL -- including winsock2.h works better if lean and mean */
  127. #if !defined(WIN32_LEAN_AND_MEAN)
  128. #define WIN32_LEAN_AND_MEAN
  129. #endif
  130. #if defined(__SYMBIAN32__)
  131. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  132. * Symbian is no longer maintained since 2014-01-01.
  133. * Recent versions of CivetWeb are no longer tested for Symbian.
  134. * It makes no sense, to support an abandoned operating system.
  135. */
  136. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  137. #define NO_SSL /* SSL is not supported */
  138. #define NO_CGI /* CGI is not supported */
  139. #define PATH_MAX FILENAME_MAX
  140. #endif /* __SYMBIAN32__ */
  141. #if !defined(CIVETWEB_HEADER_INCLUDED)
  142. /* Include the header file here, so the CivetWeb interface is defined for the
  143. * entire implementation, including the following forward definitions. */
  144. #include "civetweb.h"
  145. #endif
  146. #if !defined(DEBUG_TRACE)
  147. #if defined(DEBUG)
  148. static void DEBUG_TRACE_FUNC(const char *func,
  149. unsigned line,
  150. PRINTF_FORMAT_STRING(const char *fmt),
  151. ...) PRINTF_ARGS(3, 4);
  152. #define DEBUG_TRACE(fmt, ...) \
  153. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  154. #define NEED_DEBUG_TRACE_FUNC
  155. #else
  156. #define DEBUG_TRACE(fmt, ...) \
  157. do { \
  158. } while (0)
  159. #endif /* DEBUG */
  160. #endif /* DEBUG_TRACE */
  161. #if !defined(DEBUG_ASSERT)
  162. #if defined(DEBUG)
  163. #define DEBUG_ASSERT(cond) \
  164. do { \
  165. if (!(cond)) { \
  166. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  167. exit(2); /* Exit with error */ \
  168. } \
  169. } while (0)
  170. #else
  171. #define DEBUG_ASSERT(cond)
  172. #endif /* DEBUG */
  173. #endif
  174. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  175. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  176. __attribute__((no_instrument_function));
  177. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  178. __attribute__((no_instrument_function));
  179. void
  180. __cyg_profile_func_enter(void *this_fn, void *call_site)
  181. {
  182. if ((void *)this_fn != (void *)printf) {
  183. printf("E %p %p\n", this_fn, call_site);
  184. }
  185. }
  186. void
  187. __cyg_profile_func_exit(void *this_fn, void *call_site)
  188. {
  189. if ((void *)this_fn != (void *)printf) {
  190. printf("X %p %p\n", this_fn, call_site);
  191. }
  192. }
  193. #endif
  194. #if !defined(IGNORE_UNUSED_RESULT)
  195. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  196. #endif
  197. #if defined(__GNUC__) || defined(__MINGW32__)
  198. /* GCC unused function attribute seems fundamentally broken.
  199. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  200. * OR UNUSED" for individual functions failed.
  201. * Either the compiler creates an "unused-function" warning if a
  202. * function is not marked with __attribute__((unused)).
  203. * On the other hand, if the function is marked with this attribute,
  204. * but is used, the compiler raises a completely idiotic
  205. * "used-but-marked-unused" warning - and
  206. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  207. * raises error: unknown option after "#pragma GCC diagnostic".
  208. * Disable this warning completely, until the GCC guys sober up
  209. * again.
  210. */
  211. #pragma GCC diagnostic ignored "-Wunused-function"
  212. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  213. #else
  214. #define FUNCTION_MAY_BE_UNUSED
  215. #endif
  216. /* Some ANSI #includes are not available on Windows CE */
  217. #if !defined(_WIN32_WCE)
  218. #include <errno.h>
  219. #include <fcntl.h>
  220. #include <signal.h>
  221. #include <sys/stat.h>
  222. #include <sys/types.h>
  223. #endif /* !_WIN32_WCE */
  224. #if defined(__clang__)
  225. /* When using -Weverything, clang does not accept it's own headers
  226. * in a release build configuration. Disable what is too much in
  227. * -Weverything. */
  228. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  229. #endif
  230. #if defined(__GNUC__) || defined(__MINGW32__)
  231. /* Who on earth came to the conclusion, using __DATE__ should rise
  232. * an "expansion of date or time macro is not reproducible"
  233. * warning. That's exactly what was intended by using this macro.
  234. * Just disable this nonsense warning. */
  235. /* And disabling them does not work either:
  236. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  237. * #pragma clang diagnostic ignored "-Wdate-time"
  238. * So we just have to disable ALL warnings for some lines
  239. * of code.
  240. * This seems to be a known GCC bug, not resolved since 2012:
  241. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  242. */
  243. #endif
  244. #if defined(__MACH__) /* Apple OSX section */
  245. #if defined(__clang__)
  246. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  247. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  248. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  249. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  250. #endif
  251. #endif
  252. #define CLOCK_MONOTONIC (1)
  253. #define CLOCK_REALTIME (2)
  254. #include <mach/clock.h>
  255. #include <mach/mach.h>
  256. #include <mach/mach_time.h>
  257. #include <sys/errno.h>
  258. #include <sys/time.h>
  259. /* clock_gettime is not implemented on OSX prior to 10.12 */
  260. static int
  261. _civet_clock_gettime(int clk_id, struct timespec *t)
  262. {
  263. memset(t, 0, sizeof(*t));
  264. if (clk_id == CLOCK_REALTIME) {
  265. struct timeval now;
  266. int rv = gettimeofday(&now, NULL);
  267. if (rv) {
  268. return rv;
  269. }
  270. t->tv_sec = now.tv_sec;
  271. t->tv_nsec = now.tv_usec * 1000;
  272. return 0;
  273. } else if (clk_id == CLOCK_MONOTONIC) {
  274. static uint64_t clock_start_time = 0;
  275. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  276. uint64_t now = mach_absolute_time();
  277. if (clock_start_time == 0) {
  278. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  279. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  280. /* appease "unused variable" warning for release builds */
  281. (void)mach_status;
  282. clock_start_time = now;
  283. }
  284. now = (uint64_t)((double)(now - clock_start_time)
  285. * (double)timebase_ifo.numer
  286. / (double)timebase_ifo.denom);
  287. t->tv_sec = now / 1000000000;
  288. t->tv_nsec = now % 1000000000;
  289. return 0;
  290. }
  291. return -1; /* EINVAL - Clock ID is unknown */
  292. }
  293. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  294. #if defined(__CLOCK_AVAILABILITY)
  295. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  296. * declared but it may be NULL at runtime. So we need to check before using
  297. * it. */
  298. static int
  299. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  300. {
  301. if (clock_gettime) {
  302. return clock_gettime(clk_id, t);
  303. }
  304. return _civet_clock_gettime(clk_id, t);
  305. }
  306. #define clock_gettime _civet_safe_clock_gettime
  307. #else
  308. #define clock_gettime _civet_clock_gettime
  309. #endif
  310. #endif
  311. #include <ctype.h>
  312. #include <limits.h>
  313. #include <stdarg.h>
  314. #include <stddef.h>
  315. #include <stdint.h>
  316. #include <stdio.h>
  317. #include <stdlib.h>
  318. #include <string.h>
  319. #include <time.h>
  320. /********************************************************************/
  321. /* CivetWeb configuration defines */
  322. /********************************************************************/
  323. /* Maximum number of threads that can be configured.
  324. * The number of threads actually created depends on the "num_threads"
  325. * configuration parameter, but this is the upper limit. */
  326. #if !defined(MAX_WORKER_THREADS)
  327. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  328. #endif
  329. /* Timeout interval for select/poll calls.
  330. * The timeouts depend on "*_timeout_ms" configuration values, but long
  331. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  332. * This reduces the time required to stop the server. */
  333. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  334. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  335. #endif
  336. /* Do not try to compress files smaller than this limit. */
  337. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  338. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  339. #endif
  340. #if !defined(PASSWORDS_FILE_NAME)
  341. #define PASSWORDS_FILE_NAME ".htpasswd"
  342. #endif
  343. /* Initial buffer size for all CGI environment variables. In case there is
  344. * not enough space, another block is allocated. */
  345. #if !defined(CGI_ENVIRONMENT_SIZE)
  346. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  347. #endif
  348. /* Maximum number of environment variables. */
  349. #if !defined(MAX_CGI_ENVIR_VARS)
  350. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  351. #endif
  352. /* General purpose buffer size. */
  353. #if !defined(MG_BUF_LEN) /* in bytes */
  354. #define MG_BUF_LEN (1024 * 8)
  355. #endif
  356. /* Size of the accepted socket queue (in case the old queue implementation
  357. * is used). */
  358. #if !defined(MGSQLEN)
  359. #define MGSQLEN (20) /* count */
  360. #endif
  361. /********************************************************************/
  362. /* Helper makros */
  363. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  364. /* Standard defines */
  365. #if !defined(INT64_MAX)
  366. #define INT64_MAX (9223372036854775807)
  367. #endif
  368. #define SHUTDOWN_RD (0)
  369. #define SHUTDOWN_WR (1)
  370. #define SHUTDOWN_BOTH (2)
  371. mg_static_assert(MAX_WORKER_THREADS >= 1,
  372. "worker threads must be a positive number");
  373. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  374. "size_t data type size check");
  375. #if defined(_WIN32) /* WINDOWS include block */
  376. #include <windows.h>
  377. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  378. #include <ws2tcpip.h>
  379. typedef const char *SOCK_OPT_TYPE;
  380. #if !defined(PATH_MAX)
  381. #define W_PATH_MAX (MAX_PATH)
  382. /* at most three UTF-8 chars per wchar_t */
  383. #define PATH_MAX (W_PATH_MAX * 3)
  384. #else
  385. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  386. #endif
  387. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  388. #if !defined(_IN_PORT_T)
  389. #if !defined(in_port_t)
  390. #define in_port_t u_short
  391. #endif
  392. #endif
  393. #if !defined(_WIN32_WCE)
  394. #include <direct.h>
  395. #include <io.h>
  396. #include <process.h>
  397. #else /* _WIN32_WCE */
  398. #define NO_CGI /* WinCE has no pipes */
  399. #define NO_POPEN /* WinCE has no popen */
  400. typedef long off_t;
  401. #define errno ((int)(GetLastError()))
  402. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  403. #endif /* _WIN32_WCE */
  404. #define MAKEUQUAD(lo, hi) \
  405. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  406. #define RATE_DIFF (10000000) /* 100 nsecs */
  407. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  408. #define SYS2UNIX_TIME(lo, hi) \
  409. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  410. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  411. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  412. * Also use _strtoui64 on modern M$ compilers */
  413. #if defined(_MSC_VER)
  414. #if (_MSC_VER < 1300)
  415. #define STRX(x) #x
  416. #define STR(x) STRX(x)
  417. #define __func__ __FILE__ ":" STR(__LINE__)
  418. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  419. #define strtoll(x, y, z) (_atoi64(x))
  420. #else
  421. #define __func__ __FUNCTION__
  422. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  423. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  424. #endif
  425. #endif /* _MSC_VER */
  426. #define ERRNO ((int)(GetLastError()))
  427. #define NO_SOCKLEN_T
  428. #if defined(_WIN64) || defined(__MINGW64__)
  429. #if !defined(SSL_LIB)
  430. #define SSL_LIB "ssleay64.dll"
  431. #endif
  432. #if !defined(CRYPTO_LIB)
  433. #define CRYPTO_LIB "libeay64.dll"
  434. #endif
  435. #else
  436. #if !defined(SSL_LIB)
  437. #define SSL_LIB "ssleay32.dll"
  438. #endif
  439. #if !defined(CRYPTO_LIB)
  440. #define CRYPTO_LIB "libeay32.dll"
  441. #endif
  442. #endif
  443. #define O_NONBLOCK (0)
  444. #if !defined(W_OK)
  445. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  446. #endif
  447. #if !defined(EWOULDBLOCK)
  448. #define EWOULDBLOCK WSAEWOULDBLOCK
  449. #endif /* !EWOULDBLOCK */
  450. #define _POSIX_
  451. #define INT64_FMT "I64d"
  452. #define UINT64_FMT "I64u"
  453. #define WINCDECL __cdecl
  454. #define vsnprintf_impl _vsnprintf
  455. #define access _access
  456. #define mg_sleep(x) (Sleep(x))
  457. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  458. #if !defined(popen)
  459. #define popen(x, y) (_popen(x, y))
  460. #endif
  461. #if !defined(pclose)
  462. #define pclose(x) (_pclose(x))
  463. #endif
  464. #define close(x) (_close(x))
  465. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  466. #define RTLD_LAZY (0)
  467. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  468. #define fdopen(x, y) (_fdopen((x), (y)))
  469. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  470. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  471. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  472. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  473. #define sleep(x) (Sleep((x)*1000))
  474. #define rmdir(x) (_rmdir(x))
  475. #if defined(_WIN64) || !defined(__MINGW32__)
  476. /* Only MinGW 32 bit is missing this function */
  477. #define timegm(x) (_mkgmtime(x))
  478. #else
  479. time_t timegm(struct tm *tm);
  480. #define NEED_TIMEGM
  481. #endif
  482. #if !defined(fileno)
  483. #define fileno(x) (_fileno(x))
  484. #endif /* !fileno MINGW #defines fileno */
  485. typedef HANDLE pthread_mutex_t;
  486. typedef DWORD pthread_key_t;
  487. typedef HANDLE pthread_t;
  488. typedef struct {
  489. CRITICAL_SECTION threadIdSec;
  490. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  491. } pthread_cond_t;
  492. #if !defined(__clockid_t_defined)
  493. typedef DWORD clockid_t;
  494. #endif
  495. #if !defined(CLOCK_MONOTONIC)
  496. #define CLOCK_MONOTONIC (1)
  497. #endif
  498. #if !defined(CLOCK_REALTIME)
  499. #define CLOCK_REALTIME (2)
  500. #endif
  501. #if !defined(CLOCK_THREAD)
  502. #define CLOCK_THREAD (3)
  503. #endif
  504. #if !defined(CLOCK_PROCESS)
  505. #define CLOCK_PROCESS (4)
  506. #endif
  507. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  508. #define _TIMESPEC_DEFINED
  509. #endif
  510. #if !defined(_TIMESPEC_DEFINED)
  511. struct timespec {
  512. time_t tv_sec; /* seconds */
  513. long tv_nsec; /* nanoseconds */
  514. };
  515. #endif
  516. #if !defined(WIN_PTHREADS_TIME_H)
  517. #define MUST_IMPLEMENT_CLOCK_GETTIME
  518. #endif
  519. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  520. #define clock_gettime mg_clock_gettime
  521. static int
  522. clock_gettime(clockid_t clk_id, struct timespec *tp)
  523. {
  524. FILETIME ft;
  525. ULARGE_INTEGER li, li2;
  526. BOOL ok = FALSE;
  527. double d;
  528. static double perfcnt_per_sec = 0.0;
  529. static BOOL initialized = FALSE;
  530. if (!initialized) {
  531. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  532. perfcnt_per_sec = 1.0 / li.QuadPart;
  533. initialized = TRUE;
  534. }
  535. if (tp) {
  536. memset(tp, 0, sizeof(*tp));
  537. if (clk_id == CLOCK_REALTIME) {
  538. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  539. GetSystemTimeAsFileTime(&ft);
  540. li.LowPart = ft.dwLowDateTime;
  541. li.HighPart = ft.dwHighDateTime;
  542. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  543. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  544. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  545. ok = TRUE;
  546. /* END: CLOCK_REALTIME */
  547. } else if (clk_id == CLOCK_MONOTONIC) {
  548. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  549. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  550. d = li.QuadPart * perfcnt_per_sec;
  551. tp->tv_sec = (time_t)d;
  552. d -= (double)tp->tv_sec;
  553. tp->tv_nsec = (long)(d * 1.0E9);
  554. ok = TRUE;
  555. /* END: CLOCK_MONOTONIC */
  556. } else if (clk_id == CLOCK_THREAD) {
  557. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  558. FILETIME t_create, t_exit, t_kernel, t_user;
  559. if (GetThreadTimes(GetCurrentThread(),
  560. &t_create,
  561. &t_exit,
  562. &t_kernel,
  563. &t_user)) {
  564. li.LowPart = t_user.dwLowDateTime;
  565. li.HighPart = t_user.dwHighDateTime;
  566. li2.LowPart = t_kernel.dwLowDateTime;
  567. li2.HighPart = t_kernel.dwHighDateTime;
  568. li.QuadPart += li2.QuadPart;
  569. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  570. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  571. ok = TRUE;
  572. }
  573. /* END: CLOCK_THREAD */
  574. } else if (clk_id == CLOCK_PROCESS) {
  575. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  576. FILETIME t_create, t_exit, t_kernel, t_user;
  577. if (GetProcessTimes(GetCurrentProcess(),
  578. &t_create,
  579. &t_exit,
  580. &t_kernel,
  581. &t_user)) {
  582. li.LowPart = t_user.dwLowDateTime;
  583. li.HighPart = t_user.dwHighDateTime;
  584. li2.LowPart = t_kernel.dwLowDateTime;
  585. li2.HighPart = t_kernel.dwHighDateTime;
  586. li.QuadPart += li2.QuadPart;
  587. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  588. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  589. ok = TRUE;
  590. }
  591. /* END: CLOCK_PROCESS */
  592. } else {
  593. /* BEGIN: unknown clock */
  594. /* ok = FALSE; already set by init */
  595. /* END: unknown clock */
  596. }
  597. }
  598. return ok ? 0 : -1;
  599. }
  600. #endif
  601. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  602. static int pthread_mutex_lock(pthread_mutex_t *);
  603. static int pthread_mutex_unlock(pthread_mutex_t *);
  604. static void path_to_unicode(const struct mg_connection *conn,
  605. const char *path,
  606. wchar_t *wbuf,
  607. size_t wbuf_len);
  608. /* All file operations need to be rewritten to solve #246. */
  609. struct mg_file;
  610. static const char *
  611. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  612. /* POSIX dirent interface */
  613. struct dirent {
  614. char d_name[PATH_MAX];
  615. };
  616. typedef struct DIR {
  617. HANDLE handle;
  618. WIN32_FIND_DATAW info;
  619. struct dirent result;
  620. } DIR;
  621. #if defined(HAVE_POLL)
  622. #define mg_pollfd pollfd
  623. #else
  624. struct mg_pollfd {
  625. SOCKET fd;
  626. short events;
  627. short revents;
  628. };
  629. #endif
  630. /* Mark required libraries */
  631. #if defined(_MSC_VER)
  632. #pragma comment(lib, "Ws2_32.lib")
  633. #endif
  634. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  635. #include <arpa/inet.h>
  636. #include <inttypes.h>
  637. #include <netdb.h>
  638. #include <netinet/in.h>
  639. #include <netinet/tcp.h>
  640. #include <stdint.h>
  641. #include <sys/poll.h>
  642. #include <sys/socket.h>
  643. #include <sys/time.h>
  644. #include <sys/utsname.h>
  645. #include <sys/wait.h>
  646. typedef const void *SOCK_OPT_TYPE;
  647. #if defined(ANDROID)
  648. typedef unsigned short int in_port_t;
  649. #endif
  650. #include <dirent.h>
  651. #include <grp.h>
  652. #include <pwd.h>
  653. #include <unistd.h>
  654. #define vsnprintf_impl vsnprintf
  655. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  656. #include <dlfcn.h>
  657. #endif
  658. #include <pthread.h>
  659. #if defined(__MACH__)
  660. #define SSL_LIB "libssl.dylib"
  661. #define CRYPTO_LIB "libcrypto.dylib"
  662. #else
  663. #if !defined(SSL_LIB)
  664. #define SSL_LIB "libssl.so"
  665. #endif
  666. #if !defined(CRYPTO_LIB)
  667. #define CRYPTO_LIB "libcrypto.so"
  668. #endif
  669. #endif
  670. #if !defined(O_BINARY)
  671. #define O_BINARY (0)
  672. #endif /* O_BINARY */
  673. #define closesocket(a) (close(a))
  674. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  675. #define mg_remove(conn, x) (remove(x))
  676. #define mg_sleep(x) (usleep((x)*1000))
  677. #define mg_opendir(conn, x) (opendir(x))
  678. #define mg_closedir(x) (closedir(x))
  679. #define mg_readdir(x) (readdir(x))
  680. #define ERRNO (errno)
  681. #define INVALID_SOCKET (-1)
  682. #define INT64_FMT PRId64
  683. #define UINT64_FMT PRIu64
  684. typedef int SOCKET;
  685. #define WINCDECL
  686. #if defined(__hpux)
  687. /* HPUX 11 does not have monotonic, fall back to realtime */
  688. #if !defined(CLOCK_MONOTONIC)
  689. #define CLOCK_MONOTONIC CLOCK_REALTIME
  690. #endif
  691. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  692. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  693. * the prototypes use int* rather than socklen_t* which matches the
  694. * actual library expectation. When called with the wrong size arg
  695. * accept() returns a zero client inet addr and check_acl() always
  696. * fails. Since socklen_t is widely used below, just force replace
  697. * their typedef with int. - DTL
  698. */
  699. #define socklen_t int
  700. #endif /* hpux */
  701. #define mg_pollfd pollfd
  702. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  703. /* Maximum queue length for pending connections. This value is passed as
  704. * parameter to the "listen" socket call. */
  705. #if !defined(SOMAXCONN)
  706. /* This symbol may be defined in winsock2.h so this must after that include */
  707. #define SOMAXCONN (100) /* in pending connections (count) */
  708. #endif
  709. /* In case our C library is missing "timegm", provide an implementation */
  710. #if defined(NEED_TIMEGM)
  711. static inline int
  712. is_leap(int y)
  713. {
  714. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  715. }
  716. static inline int
  717. count_leap(int y)
  718. {
  719. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  720. }
  721. time_t
  722. timegm(struct tm *tm)
  723. {
  724. static const unsigned short ydays[] = {
  725. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  726. int year = tm->tm_year + 1900;
  727. int mon = tm->tm_mon;
  728. int mday = tm->tm_mday - 1;
  729. int hour = tm->tm_hour;
  730. int min = tm->tm_min;
  731. int sec = tm->tm_sec;
  732. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  733. || (mday >= ydays[mon + 1] - ydays[mon]
  734. + (mon == 1 && is_leap(year) ? 1 : 0))
  735. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  736. return -1;
  737. time_t res = year - 1970;
  738. res *= 365;
  739. res += mday;
  740. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  741. res += count_leap(year);
  742. res *= 24;
  743. res += hour;
  744. res *= 60;
  745. res += min;
  746. res *= 60;
  747. res += sec;
  748. return res;
  749. }
  750. #endif /* NEED_TIMEGM */
  751. /* va_copy should always be a macro, C99 and C++11 - DTL */
  752. #if !defined(va_copy)
  753. #define va_copy(x, y) ((x) = (y))
  754. #endif
  755. #if defined(_WIN32)
  756. /* Create substitutes for POSIX functions in Win32. */
  757. #if defined(GCC_DIAGNOSTIC)
  758. /* Show no warning in case system functions are not used. */
  759. #pragma GCC diagnostic push
  760. #pragma GCC diagnostic ignored "-Wunused-function"
  761. #endif
  762. static CRITICAL_SECTION global_log_file_lock;
  763. FUNCTION_MAY_BE_UNUSED
  764. static DWORD
  765. pthread_self(void)
  766. {
  767. return GetCurrentThreadId();
  768. }
  769. FUNCTION_MAY_BE_UNUSED
  770. static int
  771. pthread_key_create(
  772. pthread_key_t *key,
  773. void (*_ignored)(void *) /* destructor not supported for Windows */
  774. )
  775. {
  776. (void)_ignored;
  777. if ((key != 0)) {
  778. *key = TlsAlloc();
  779. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  780. }
  781. return -2;
  782. }
  783. FUNCTION_MAY_BE_UNUSED
  784. static int
  785. pthread_key_delete(pthread_key_t key)
  786. {
  787. return TlsFree(key) ? 0 : 1;
  788. }
  789. FUNCTION_MAY_BE_UNUSED
  790. static int
  791. pthread_setspecific(pthread_key_t key, void *value)
  792. {
  793. return TlsSetValue(key, value) ? 0 : 1;
  794. }
  795. FUNCTION_MAY_BE_UNUSED
  796. static void *
  797. pthread_getspecific(pthread_key_t key)
  798. {
  799. return TlsGetValue(key);
  800. }
  801. #if defined(GCC_DIAGNOSTIC)
  802. /* Enable unused function warning again */
  803. #pragma GCC diagnostic pop
  804. #endif
  805. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  806. #else
  807. static pthread_mutexattr_t pthread_mutex_attr;
  808. #endif /* _WIN32 */
  809. #if defined(_WIN32_WCE)
  810. /* Create substitutes for POSIX functions in Win32. */
  811. #if defined(GCC_DIAGNOSTIC)
  812. /* Show no warning in case system functions are not used. */
  813. #pragma GCC diagnostic push
  814. #pragma GCC diagnostic ignored "-Wunused-function"
  815. #endif
  816. FUNCTION_MAY_BE_UNUSED
  817. static time_t
  818. time(time_t *ptime)
  819. {
  820. time_t t;
  821. SYSTEMTIME st;
  822. FILETIME ft;
  823. GetSystemTime(&st);
  824. SystemTimeToFileTime(&st, &ft);
  825. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  826. if (ptime != NULL) {
  827. *ptime = t;
  828. }
  829. return t;
  830. }
  831. FUNCTION_MAY_BE_UNUSED
  832. static struct tm *
  833. localtime_s(const time_t *ptime, struct tm *ptm)
  834. {
  835. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  836. FILETIME ft, lft;
  837. SYSTEMTIME st;
  838. TIME_ZONE_INFORMATION tzinfo;
  839. if (ptm == NULL) {
  840. return NULL;
  841. }
  842. *(int64_t *)&ft = t;
  843. FileTimeToLocalFileTime(&ft, &lft);
  844. FileTimeToSystemTime(&lft, &st);
  845. ptm->tm_year = st.wYear - 1900;
  846. ptm->tm_mon = st.wMonth - 1;
  847. ptm->tm_wday = st.wDayOfWeek;
  848. ptm->tm_mday = st.wDay;
  849. ptm->tm_hour = st.wHour;
  850. ptm->tm_min = st.wMinute;
  851. ptm->tm_sec = st.wSecond;
  852. ptm->tm_yday = 0; /* hope nobody uses this */
  853. ptm->tm_isdst =
  854. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  855. return ptm;
  856. }
  857. FUNCTION_MAY_BE_UNUSED
  858. static struct tm *
  859. gmtime_s(const time_t *ptime, struct tm *ptm)
  860. {
  861. /* FIXME(lsm): fix this. */
  862. return localtime_s(ptime, ptm);
  863. }
  864. static int mg_atomic_inc(volatile int *addr);
  865. static struct tm tm_array[MAX_WORKER_THREADS];
  866. static int tm_index = 0;
  867. FUNCTION_MAY_BE_UNUSED
  868. static struct tm *
  869. localtime(const time_t *ptime)
  870. {
  871. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  872. return localtime_s(ptime, tm_array + i);
  873. }
  874. FUNCTION_MAY_BE_UNUSED
  875. static struct tm *
  876. gmtime(const time_t *ptime)
  877. {
  878. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  879. return gmtime_s(ptime, tm_array + i);
  880. }
  881. FUNCTION_MAY_BE_UNUSED
  882. static size_t
  883. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  884. {
  885. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  886. * for WinCE"); */
  887. return 0;
  888. }
  889. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  890. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  891. #define remove(f) mg_remove(NULL, f)
  892. FUNCTION_MAY_BE_UNUSED
  893. static int
  894. rename(const char *a, const char *b)
  895. {
  896. wchar_t wa[W_PATH_MAX];
  897. wchar_t wb[W_PATH_MAX];
  898. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  899. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  900. return MoveFileW(wa, wb) ? 0 : -1;
  901. }
  902. struct stat {
  903. int64_t st_size;
  904. time_t st_mtime;
  905. };
  906. FUNCTION_MAY_BE_UNUSED
  907. static int
  908. stat(const char *name, struct stat *st)
  909. {
  910. wchar_t wbuf[W_PATH_MAX];
  911. WIN32_FILE_ATTRIBUTE_DATA attr;
  912. time_t creation_time, write_time;
  913. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  914. memset(&attr, 0, sizeof(attr));
  915. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  916. st->st_size =
  917. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  918. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  919. attr.ftLastWriteTime.dwHighDateTime);
  920. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  921. attr.ftCreationTime.dwHighDateTime);
  922. if (creation_time > write_time) {
  923. st->st_mtime = creation_time;
  924. } else {
  925. st->st_mtime = write_time;
  926. }
  927. return 0;
  928. }
  929. #define access(x, a) 1 /* not required anyway */
  930. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  931. /* Values from errno.h in Windows SDK (Visual Studio). */
  932. #define EEXIST 17
  933. #define EACCES 13
  934. #define ENOENT 2
  935. #if defined(GCC_DIAGNOSTIC)
  936. /* Enable unused function warning again */
  937. #pragma GCC diagnostic pop
  938. #endif
  939. #endif /* defined(_WIN32_WCE) */
  940. #if defined(GCC_DIAGNOSTIC)
  941. /* Show no warning in case system functions are not used. */
  942. #pragma GCC diagnostic push
  943. #pragma GCC diagnostic ignored "-Wunused-function"
  944. #endif /* defined(GCC_DIAGNOSTIC) */
  945. #if defined(__clang__)
  946. /* Show no warning in case system functions are not used. */
  947. #pragma clang diagnostic push
  948. #pragma clang diagnostic ignored "-Wunused-function"
  949. #endif
  950. static pthread_mutex_t global_lock_mutex;
  951. #if defined(_WIN32)
  952. /* Forward declaration for Windows */
  953. FUNCTION_MAY_BE_UNUSED
  954. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  955. FUNCTION_MAY_BE_UNUSED
  956. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  957. #endif
  958. FUNCTION_MAY_BE_UNUSED
  959. static void
  960. mg_global_lock(void)
  961. {
  962. (void)pthread_mutex_lock(&global_lock_mutex);
  963. }
  964. FUNCTION_MAY_BE_UNUSED
  965. static void
  966. mg_global_unlock(void)
  967. {
  968. (void)pthread_mutex_unlock(&global_lock_mutex);
  969. }
  970. FUNCTION_MAY_BE_UNUSED
  971. static int
  972. mg_atomic_inc(volatile int *addr)
  973. {
  974. int ret;
  975. #if defined(_WIN32) && !defined(NO_ATOMICS)
  976. /* Depending on the SDK, this function uses either
  977. * (volatile unsigned int *) or (volatile LONG *),
  978. * so whatever you use, the other SDK is likely to raise a warning. */
  979. ret = InterlockedIncrement((volatile long *)addr);
  980. #elif defined(__GNUC__) \
  981. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  982. && !defined(NO_ATOMICS)
  983. ret = __sync_add_and_fetch(addr, 1);
  984. #else
  985. mg_global_lock();
  986. ret = (++(*addr));
  987. mg_global_unlock();
  988. #endif
  989. return ret;
  990. }
  991. FUNCTION_MAY_BE_UNUSED
  992. static int
  993. mg_atomic_dec(volatile int *addr)
  994. {
  995. int ret;
  996. #if defined(_WIN32) && !defined(NO_ATOMICS)
  997. /* Depending on the SDK, this function uses either
  998. * (volatile unsigned int *) or (volatile LONG *),
  999. * so whatever you use, the other SDK is likely to raise a warning. */
  1000. ret = InterlockedDecrement((volatile long *)addr);
  1001. #elif defined(__GNUC__) \
  1002. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1003. && !defined(NO_ATOMICS)
  1004. ret = __sync_sub_and_fetch(addr, 1);
  1005. #else
  1006. mg_global_lock();
  1007. ret = (--(*addr));
  1008. mg_global_unlock();
  1009. #endif
  1010. return ret;
  1011. }
  1012. #if defined(USE_SERVER_STATS)
  1013. static int64_t
  1014. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1015. {
  1016. int64_t ret;
  1017. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1018. ret = InterlockedAdd64(addr, value);
  1019. #elif defined(__GNUC__) \
  1020. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1021. && !defined(NO_ATOMICS)
  1022. ret = __sync_add_and_fetch(addr, value);
  1023. #else
  1024. mg_global_lock();
  1025. *addr += value;
  1026. ret = (*addr);
  1027. mg_global_unlock();
  1028. #endif
  1029. return ret;
  1030. }
  1031. #endif
  1032. #if defined(GCC_DIAGNOSTIC)
  1033. /* Show no warning in case system functions are not used. */
  1034. #pragma GCC diagnostic pop
  1035. #endif /* defined(GCC_DIAGNOSTIC) */
  1036. #if defined(__clang__)
  1037. /* Show no warning in case system functions are not used. */
  1038. #pragma clang diagnostic pop
  1039. #endif
  1040. #if defined(USE_SERVER_STATS)
  1041. struct mg_memory_stat {
  1042. volatile int64_t totalMemUsed;
  1043. volatile int64_t maxMemUsed;
  1044. volatile int blockCount;
  1045. };
  1046. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1047. static void *
  1048. mg_malloc_ex(size_t size,
  1049. struct mg_context *ctx,
  1050. const char *file,
  1051. unsigned line)
  1052. {
  1053. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1054. void *memory = 0;
  1055. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1056. #if defined(MEMORY_DEBUGGING)
  1057. char mallocStr[256];
  1058. #else
  1059. (void)file;
  1060. (void)line;
  1061. #endif
  1062. if (data) {
  1063. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1064. if (mmem > mstat->maxMemUsed) {
  1065. /* could use atomic compare exchange, but this
  1066. * seems overkill for statistics data */
  1067. mstat->maxMemUsed = mmem;
  1068. }
  1069. mg_atomic_inc(&mstat->blockCount);
  1070. ((uintptr_t *)data)[0] = size;
  1071. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1072. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1073. }
  1074. #if defined(MEMORY_DEBUGGING)
  1075. sprintf(mallocStr,
  1076. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1077. memory,
  1078. (unsigned long)size,
  1079. (unsigned long)mstat->totalMemUsed,
  1080. (unsigned long)mstat->blockCount,
  1081. file,
  1082. line);
  1083. #if defined(_WIN32)
  1084. OutputDebugStringA(mallocStr);
  1085. #else
  1086. DEBUG_TRACE("%s", mallocStr);
  1087. #endif
  1088. #endif
  1089. return memory;
  1090. }
  1091. static void *
  1092. mg_calloc_ex(size_t count,
  1093. size_t size,
  1094. struct mg_context *ctx,
  1095. const char *file,
  1096. unsigned line)
  1097. {
  1098. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1099. if (data) {
  1100. memset(data, 0, size * count);
  1101. }
  1102. return data;
  1103. }
  1104. static void
  1105. mg_free_ex(void *memory, const char *file, unsigned line)
  1106. {
  1107. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1108. #if defined(MEMORY_DEBUGGING)
  1109. char mallocStr[256];
  1110. #else
  1111. (void)file;
  1112. (void)line;
  1113. #endif
  1114. if (memory) {
  1115. uintptr_t size = ((uintptr_t *)data)[0];
  1116. struct mg_memory_stat *mstat =
  1117. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1118. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1119. mg_atomic_dec(&mstat->blockCount);
  1120. #if defined(MEMORY_DEBUGGING)
  1121. sprintf(mallocStr,
  1122. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1123. memory,
  1124. (unsigned long)size,
  1125. (unsigned long)mstat->totalMemUsed,
  1126. (unsigned long)mstat->blockCount,
  1127. file,
  1128. line);
  1129. #if defined(_WIN32)
  1130. OutputDebugStringA(mallocStr);
  1131. #else
  1132. DEBUG_TRACE("%s", mallocStr);
  1133. #endif
  1134. #endif
  1135. free(data);
  1136. }
  1137. }
  1138. static void *
  1139. mg_realloc_ex(void *memory,
  1140. size_t newsize,
  1141. struct mg_context *ctx,
  1142. const char *file,
  1143. unsigned line)
  1144. {
  1145. void *data;
  1146. void *_realloc;
  1147. uintptr_t oldsize;
  1148. #if defined(MEMORY_DEBUGGING)
  1149. char mallocStr[256];
  1150. #else
  1151. (void)file;
  1152. (void)line;
  1153. #endif
  1154. if (newsize) {
  1155. if (memory) {
  1156. /* Reallocate existing block */
  1157. struct mg_memory_stat *mstat;
  1158. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1159. oldsize = ((uintptr_t *)data)[0];
  1160. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1161. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1162. if (_realloc) {
  1163. data = _realloc;
  1164. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1165. #if defined(MEMORY_DEBUGGING)
  1166. sprintf(mallocStr,
  1167. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1168. memory,
  1169. (unsigned long)oldsize,
  1170. (unsigned long)mstat->totalMemUsed,
  1171. (unsigned long)mstat->blockCount,
  1172. file,
  1173. line);
  1174. #if defined(_WIN32)
  1175. OutputDebugStringA(mallocStr);
  1176. #else
  1177. DEBUG_TRACE("%s", mallocStr);
  1178. #endif
  1179. #endif
  1180. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1181. #if defined(MEMORY_DEBUGGING)
  1182. sprintf(mallocStr,
  1183. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1184. memory,
  1185. (unsigned long)newsize,
  1186. (unsigned long)mstat->totalMemUsed,
  1187. (unsigned long)mstat->blockCount,
  1188. file,
  1189. line);
  1190. #if defined(_WIN32)
  1191. OutputDebugStringA(mallocStr);
  1192. #else
  1193. DEBUG_TRACE("%s", mallocStr);
  1194. #endif
  1195. #endif
  1196. *(uintptr_t *)data = newsize;
  1197. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1198. } else {
  1199. #if defined(MEMORY_DEBUGGING)
  1200. #if defined(_WIN32)
  1201. OutputDebugStringA("MEM: realloc failed\n");
  1202. #else
  1203. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1204. #endif
  1205. #endif
  1206. return _realloc;
  1207. }
  1208. } else {
  1209. /* Allocate new block */
  1210. data = mg_malloc_ex(newsize, ctx, file, line);
  1211. }
  1212. } else {
  1213. /* Free existing block */
  1214. data = 0;
  1215. mg_free_ex(memory, file, line);
  1216. }
  1217. return data;
  1218. }
  1219. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1220. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1221. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1222. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1223. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1224. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1225. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1226. #else /* USE_SERVER_STATS */
  1227. static __inline void *
  1228. mg_malloc(size_t a)
  1229. {
  1230. return malloc(a);
  1231. }
  1232. static __inline void *
  1233. mg_calloc(size_t a, size_t b)
  1234. {
  1235. return calloc(a, b);
  1236. }
  1237. static __inline void *
  1238. mg_realloc(void *a, size_t b)
  1239. {
  1240. return realloc(a, b);
  1241. }
  1242. static __inline void
  1243. mg_free(void *a)
  1244. {
  1245. free(a);
  1246. }
  1247. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1248. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1249. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1250. #define mg_free_ctx(a, c) mg_free(a)
  1251. #endif /* USE_SERVER_STATS */
  1252. static void mg_vsnprintf(const struct mg_connection *conn,
  1253. int *truncated,
  1254. char *buf,
  1255. size_t buflen,
  1256. const char *fmt,
  1257. va_list ap);
  1258. static void mg_snprintf(const struct mg_connection *conn,
  1259. int *truncated,
  1260. char *buf,
  1261. size_t buflen,
  1262. PRINTF_FORMAT_STRING(const char *fmt),
  1263. ...) PRINTF_ARGS(5, 6);
  1264. /* This following lines are just meant as a reminder to use the mg-functions
  1265. * for memory management */
  1266. #if defined(malloc)
  1267. #undef malloc
  1268. #endif
  1269. #if defined(calloc)
  1270. #undef calloc
  1271. #endif
  1272. #if defined(realloc)
  1273. #undef realloc
  1274. #endif
  1275. #if defined(free)
  1276. #undef free
  1277. #endif
  1278. #if defined(snprintf)
  1279. #undef snprintf
  1280. #endif
  1281. #if defined(vsnprintf)
  1282. #undef vsnprintf
  1283. #endif
  1284. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1285. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1286. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1287. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1288. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1289. #if defined(_WIN32)
  1290. /* vsnprintf must not be used in any system,
  1291. * but this define only works well for Windows. */
  1292. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1293. #endif
  1294. /* mg_init_library counter */
  1295. static int mg_init_library_called = 0;
  1296. #if !defined(NO_SSL)
  1297. static int mg_ssl_initialized = 0;
  1298. #endif
  1299. static pthread_key_t sTlsKey; /* Thread local storage index */
  1300. static int thread_idx_max = 0;
  1301. #if defined(MG_LEGACY_INTERFACE)
  1302. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1303. #endif
  1304. struct mg_workerTLS {
  1305. int is_master;
  1306. unsigned long thread_idx;
  1307. #if defined(_WIN32)
  1308. HANDLE pthread_cond_helper_mutex;
  1309. struct mg_workerTLS *next_waiting_thread;
  1310. #endif
  1311. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1312. char txtbuf[4];
  1313. #endif
  1314. };
  1315. #if defined(GCC_DIAGNOSTIC)
  1316. /* Show no warning in case system functions are not used. */
  1317. #pragma GCC diagnostic push
  1318. #pragma GCC diagnostic ignored "-Wunused-function"
  1319. #endif /* defined(GCC_DIAGNOSTIC) */
  1320. #if defined(__clang__)
  1321. /* Show no warning in case system functions are not used. */
  1322. #pragma clang diagnostic push
  1323. #pragma clang diagnostic ignored "-Wunused-function"
  1324. #endif
  1325. /* Get a unique thread ID as unsigned long, independent from the data type
  1326. * of thread IDs defined by the operating system API.
  1327. * If two calls to mg_current_thread_id return the same value, they calls
  1328. * are done from the same thread. If they return different values, they are
  1329. * done from different threads. (Provided this function is used in the same
  1330. * process context and threads are not repeatedly created and deleted, but
  1331. * CivetWeb does not do that).
  1332. * This function must match the signature required for SSL id callbacks:
  1333. * CRYPTO_set_id_callback
  1334. */
  1335. FUNCTION_MAY_BE_UNUSED
  1336. static unsigned long
  1337. mg_current_thread_id(void)
  1338. {
  1339. #if defined(_WIN32)
  1340. return GetCurrentThreadId();
  1341. #else
  1342. #if defined(__clang__)
  1343. #pragma clang diagnostic push
  1344. #pragma clang diagnostic ignored "-Wunreachable-code"
  1345. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1346. * or not, so one of the two conditions will be unreachable by construction.
  1347. * Unfortunately the C standard does not define a way to check this at
  1348. * compile time, since the #if preprocessor conditions can not use the sizeof
  1349. * operator as an argument. */
  1350. #endif
  1351. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1352. /* This is the problematic case for CRYPTO_set_id_callback:
  1353. * The OS pthread_t can not be cast to unsigned long. */
  1354. struct mg_workerTLS *tls =
  1355. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1356. if (tls == NULL) {
  1357. /* SSL called from an unknown thread: Create some thread index.
  1358. */
  1359. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1360. tls->is_master = -2; /* -2 means "3rd party thread" */
  1361. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1362. pthread_setspecific(sTlsKey, tls);
  1363. }
  1364. return tls->thread_idx;
  1365. } else {
  1366. /* pthread_t may be any data type, so a simple cast to unsigned long
  1367. * can rise a warning/error, depending on the platform.
  1368. * Here memcpy is used as an anything-to-anything cast. */
  1369. unsigned long ret = 0;
  1370. pthread_t t = pthread_self();
  1371. memcpy(&ret, &t, sizeof(pthread_t));
  1372. return ret;
  1373. }
  1374. #if defined(__clang__)
  1375. #pragma clang diagnostic pop
  1376. #endif
  1377. #endif
  1378. }
  1379. FUNCTION_MAY_BE_UNUSED
  1380. static uint64_t
  1381. mg_get_current_time_ns(void)
  1382. {
  1383. struct timespec tsnow;
  1384. clock_gettime(CLOCK_REALTIME, &tsnow);
  1385. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1386. }
  1387. #if defined(GCC_DIAGNOSTIC)
  1388. /* Show no warning in case system functions are not used. */
  1389. #pragma GCC diagnostic pop
  1390. #endif /* defined(GCC_DIAGNOSTIC) */
  1391. #if defined(__clang__)
  1392. /* Show no warning in case system functions are not used. */
  1393. #pragma clang diagnostic pop
  1394. #endif
  1395. #if defined(NEED_DEBUG_TRACE_FUNC)
  1396. static void
  1397. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1398. {
  1399. va_list args;
  1400. uint64_t nsnow;
  1401. static uint64_t nslast;
  1402. struct timespec tsnow;
  1403. /* Get some operating system independent thread id */
  1404. unsigned long thread_id = mg_current_thread_id();
  1405. clock_gettime(CLOCK_REALTIME, &tsnow);
  1406. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1407. + ((uint64_t)tsnow.tv_nsec);
  1408. if (!nslast) {
  1409. nslast = nsnow;
  1410. }
  1411. flockfile(stdout);
  1412. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1413. (unsigned long)tsnow.tv_sec,
  1414. (unsigned long)tsnow.tv_nsec,
  1415. nsnow - nslast,
  1416. thread_id,
  1417. func,
  1418. line);
  1419. va_start(args, fmt);
  1420. vprintf(fmt, args);
  1421. va_end(args);
  1422. putchar('\n');
  1423. fflush(stdout);
  1424. funlockfile(stdout);
  1425. nslast = nsnow;
  1426. }
  1427. #endif /* NEED_DEBUG_TRACE_FUNC */
  1428. #define MD5_STATIC static
  1429. #include "md5.inl"
  1430. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1431. #if defined(NO_SOCKLEN_T)
  1432. typedef int socklen_t;
  1433. #endif /* NO_SOCKLEN_T */
  1434. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1435. #if !defined(MSG_NOSIGNAL)
  1436. #define MSG_NOSIGNAL (0)
  1437. #endif
  1438. #if defined(NO_SSL)
  1439. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1440. typedef struct SSL_CTX SSL_CTX;
  1441. #else
  1442. #if defined(NO_SSL_DL)
  1443. #include <openssl/bn.h>
  1444. #include <openssl/conf.h>
  1445. #include <openssl/crypto.h>
  1446. #include <openssl/dh.h>
  1447. #include <openssl/engine.h>
  1448. #include <openssl/err.h>
  1449. #include <openssl/opensslv.h>
  1450. #include <openssl/pem.h>
  1451. #include <openssl/ssl.h>
  1452. #include <openssl/tls1.h>
  1453. #include <openssl/x509.h>
  1454. #if defined(WOLFSSL_VERSION)
  1455. /* Additional defines for WolfSSL, see
  1456. * https://github.com/civetweb/civetweb/issues/583 */
  1457. #include "wolfssl_extras.inl"
  1458. #endif
  1459. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  1460. /* If OpenSSL headers are included, automatically select the API version */
  1461. #if !defined(OPENSSL_API_1_1)
  1462. #define OPENSSL_API_1_1
  1463. #endif
  1464. #define OPENSSL_REMOVE_THREAD_STATE()
  1465. #else
  1466. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_thread_state(NULL)
  1467. #endif
  1468. #else
  1469. /* SSL loaded dynamically from DLL.
  1470. * I put the prototypes here to be independent from OpenSSL source
  1471. * installation. */
  1472. typedef struct ssl_st SSL;
  1473. typedef struct ssl_method_st SSL_METHOD;
  1474. typedef struct ssl_ctx_st SSL_CTX;
  1475. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1476. typedef struct x509_name X509_NAME;
  1477. typedef struct asn1_integer ASN1_INTEGER;
  1478. typedef struct bignum BIGNUM;
  1479. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1480. typedef struct evp_md EVP_MD;
  1481. typedef struct x509 X509;
  1482. #define SSL_CTRL_OPTIONS (32)
  1483. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1484. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1485. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1486. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1487. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1488. #define SSL_VERIFY_NONE (0)
  1489. #define SSL_VERIFY_PEER (1)
  1490. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1491. #define SSL_VERIFY_CLIENT_ONCE (4)
  1492. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1493. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1494. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1495. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1496. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1497. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1498. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1499. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1500. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1501. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1502. #define SSL_CB_HANDSHAKE_START (0x10)
  1503. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1504. #define SSL_ERROR_NONE (0)
  1505. #define SSL_ERROR_SSL (1)
  1506. #define SSL_ERROR_WANT_READ (2)
  1507. #define SSL_ERROR_WANT_WRITE (3)
  1508. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1509. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1510. #define SSL_ERROR_ZERO_RETURN (6)
  1511. #define SSL_ERROR_WANT_CONNECT (7)
  1512. #define SSL_ERROR_WANT_ACCEPT (8)
  1513. #define TLSEXT_TYPE_server_name (0)
  1514. #define TLSEXT_NAMETYPE_host_name (0)
  1515. #define SSL_TLSEXT_ERR_OK (0)
  1516. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1517. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1518. #define SSL_TLSEXT_ERR_NOACK (3)
  1519. struct ssl_func {
  1520. const char *name; /* SSL function name */
  1521. void (*ptr)(void); /* Function pointer */
  1522. };
  1523. #if defined(OPENSSL_API_1_1)
  1524. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1525. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1526. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1527. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1528. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1529. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1530. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1531. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1532. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1533. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1534. #define OPENSSL_init_ssl \
  1535. (*(int (*)(uint64_t opts, \
  1536. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1537. .ptr)
  1538. #define SSL_CTX_use_PrivateKey_file \
  1539. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1540. #define SSL_CTX_use_certificate_file \
  1541. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1542. #define SSL_CTX_set_default_passwd_cb \
  1543. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1544. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1545. #define SSL_CTX_use_certificate_chain_file \
  1546. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1547. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1548. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1549. #define SSL_CTX_set_verify \
  1550. (*(void (*)(SSL_CTX *, \
  1551. int, \
  1552. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1553. .ptr)
  1554. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1555. #define SSL_CTX_load_verify_locations \
  1556. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1557. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1558. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1559. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1560. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1561. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1562. #define SSL_CIPHER_get_name \
  1563. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1564. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1565. #define SSL_CTX_set_session_id_context \
  1566. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1567. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1568. #define SSL_CTX_set_cipher_list \
  1569. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1570. #define SSL_CTX_set_options \
  1571. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1572. #define SSL_CTX_set_info_callback \
  1573. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1574. ssl_sw[32] \
  1575. .ptr)
  1576. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1577. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1578. #define SSL_CTX_callback_ctrl \
  1579. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1580. #define SSL_get_servername \
  1581. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1582. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1583. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1584. #define SSL_CTX_clear_options(ctx, op) \
  1585. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1586. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1587. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1588. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1589. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1590. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1591. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1592. SSL_CTX_callback_ctrl(ctx, \
  1593. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1594. (void (*)(void))cb)
  1595. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1596. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1597. #define SSL_set_tlsext_host_name(ctx, arg) \
  1598. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1599. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1600. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1601. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1602. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1603. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1604. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1605. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1606. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1607. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1608. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1609. #define X509_NAME_oneline \
  1610. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1611. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1612. #define EVP_get_digestbyname \
  1613. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1614. #define EVP_Digest \
  1615. (*(int (*)( \
  1616. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1617. crypto_sw[9] \
  1618. .ptr)
  1619. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1620. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1621. #define ASN1_INTEGER_to_BN \
  1622. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1623. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1624. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1625. #define OPENSSL_free(a) CRYPTO_free(a)
  1626. #define OPENSSL_REMOVE_THREAD_STATE()
  1627. /* init_ssl_ctx() function updates this array.
  1628. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1629. * of respective functions. The macros above (like SSL_connect()) are really
  1630. * just calling these functions indirectly via the pointer. */
  1631. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1632. {"SSL_accept", NULL},
  1633. {"SSL_connect", NULL},
  1634. {"SSL_read", NULL},
  1635. {"SSL_write", NULL},
  1636. {"SSL_get_error", NULL},
  1637. {"SSL_set_fd", NULL},
  1638. {"SSL_new", NULL},
  1639. {"SSL_CTX_new", NULL},
  1640. {"TLS_server_method", NULL},
  1641. {"OPENSSL_init_ssl", NULL},
  1642. {"SSL_CTX_use_PrivateKey_file", NULL},
  1643. {"SSL_CTX_use_certificate_file", NULL},
  1644. {"SSL_CTX_set_default_passwd_cb", NULL},
  1645. {"SSL_CTX_free", NULL},
  1646. {"SSL_CTX_use_certificate_chain_file", NULL},
  1647. {"TLS_client_method", NULL},
  1648. {"SSL_pending", NULL},
  1649. {"SSL_CTX_set_verify", NULL},
  1650. {"SSL_shutdown", NULL},
  1651. {"SSL_CTX_load_verify_locations", NULL},
  1652. {"SSL_CTX_set_default_verify_paths", NULL},
  1653. {"SSL_CTX_set_verify_depth", NULL},
  1654. {"SSL_get_peer_certificate", NULL},
  1655. {"SSL_get_version", NULL},
  1656. {"SSL_get_current_cipher", NULL},
  1657. {"SSL_CIPHER_get_name", NULL},
  1658. {"SSL_CTX_check_private_key", NULL},
  1659. {"SSL_CTX_set_session_id_context", NULL},
  1660. {"SSL_CTX_ctrl", NULL},
  1661. {"SSL_CTX_set_cipher_list", NULL},
  1662. {"SSL_CTX_set_options", NULL},
  1663. {"SSL_CTX_set_info_callback", NULL},
  1664. {"SSL_get_ex_data", NULL},
  1665. {"SSL_set_ex_data", NULL},
  1666. {"SSL_CTX_callback_ctrl", NULL},
  1667. {"SSL_get_servername", NULL},
  1668. {"SSL_set_SSL_CTX", NULL},
  1669. {"SSL_ctrl", NULL},
  1670. {NULL, NULL}};
  1671. /* Similar array as ssl_sw. These functions could be located in different
  1672. * lib. */
  1673. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1674. {"ERR_error_string", NULL},
  1675. {"CONF_modules_unload", NULL},
  1676. {"X509_free", NULL},
  1677. {"X509_get_subject_name", NULL},
  1678. {"X509_get_issuer_name", NULL},
  1679. {"X509_NAME_oneline", NULL},
  1680. {"X509_get_serialNumber", NULL},
  1681. {"EVP_get_digestbyname", NULL},
  1682. {"EVP_Digest", NULL},
  1683. {"i2d_X509", NULL},
  1684. {"BN_bn2hex", NULL},
  1685. {"ASN1_INTEGER_to_BN", NULL},
  1686. {"BN_free", NULL},
  1687. {"CRYPTO_free", NULL},
  1688. {NULL, NULL}};
  1689. #else
  1690. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1691. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1692. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1693. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1694. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1695. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1696. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1697. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1698. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1699. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1700. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1701. #define SSL_CTX_use_PrivateKey_file \
  1702. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1703. #define SSL_CTX_use_certificate_file \
  1704. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1705. #define SSL_CTX_set_default_passwd_cb \
  1706. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1707. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1708. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1709. #define SSL_CTX_use_certificate_chain_file \
  1710. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1711. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1712. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1713. #define SSL_CTX_set_verify \
  1714. (*(void (*)(SSL_CTX *, \
  1715. int, \
  1716. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1717. .ptr)
  1718. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1719. #define SSL_CTX_load_verify_locations \
  1720. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1721. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1722. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1723. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1724. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1725. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1726. #define SSL_CIPHER_get_name \
  1727. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1728. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1729. #define SSL_CTX_set_session_id_context \
  1730. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1731. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1732. #define SSL_CTX_set_cipher_list \
  1733. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1734. #define SSL_CTX_set_info_callback \
  1735. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1736. .ptr)
  1737. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1738. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1739. #define SSL_CTX_callback_ctrl \
  1740. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1741. #define SSL_get_servername \
  1742. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1743. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1744. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1745. #define SSL_CTX_set_options(ctx, op) \
  1746. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1747. #define SSL_CTX_clear_options(ctx, op) \
  1748. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1749. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1750. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1751. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1752. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1753. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1754. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1755. SSL_CTX_callback_ctrl(ctx, \
  1756. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1757. (void (*)(void))cb)
  1758. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1759. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1760. #define SSL_set_tlsext_host_name(ctx, arg) \
  1761. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1762. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1763. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1764. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1765. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1766. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1767. #define CRYPTO_set_locking_callback \
  1768. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1769. #define CRYPTO_set_id_callback \
  1770. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1771. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1772. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1773. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1774. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1775. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1776. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1777. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1778. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1779. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1780. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1781. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1782. #define X509_NAME_oneline \
  1783. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1784. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1785. #define i2c_ASN1_INTEGER \
  1786. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1787. #define EVP_get_digestbyname \
  1788. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1789. #define EVP_Digest \
  1790. (*(int (*)( \
  1791. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1792. crypto_sw[18] \
  1793. .ptr)
  1794. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1795. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1796. #define ASN1_INTEGER_to_BN \
  1797. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1798. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1799. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1800. #define OPENSSL_free(a) CRYPTO_free(a)
  1801. /* use here ERR_remove_state,
  1802. * while on some platforms function is not included into library due to
  1803. * deprication */
  1804. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1805. /* init_ssl_ctx() function updates this array.
  1806. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1807. * of respective functions. The macros above (like SSL_connect()) are really
  1808. * just calling these functions indirectly via the pointer. */
  1809. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1810. {"SSL_accept", NULL},
  1811. {"SSL_connect", NULL},
  1812. {"SSL_read", NULL},
  1813. {"SSL_write", NULL},
  1814. {"SSL_get_error", NULL},
  1815. {"SSL_set_fd", NULL},
  1816. {"SSL_new", NULL},
  1817. {"SSL_CTX_new", NULL},
  1818. {"SSLv23_server_method", NULL},
  1819. {"SSL_library_init", NULL},
  1820. {"SSL_CTX_use_PrivateKey_file", NULL},
  1821. {"SSL_CTX_use_certificate_file", NULL},
  1822. {"SSL_CTX_set_default_passwd_cb", NULL},
  1823. {"SSL_CTX_free", NULL},
  1824. {"SSL_load_error_strings", NULL},
  1825. {"SSL_CTX_use_certificate_chain_file", NULL},
  1826. {"SSLv23_client_method", NULL},
  1827. {"SSL_pending", NULL},
  1828. {"SSL_CTX_set_verify", NULL},
  1829. {"SSL_shutdown", NULL},
  1830. {"SSL_CTX_load_verify_locations", NULL},
  1831. {"SSL_CTX_set_default_verify_paths", NULL},
  1832. {"SSL_CTX_set_verify_depth", NULL},
  1833. {"SSL_get_peer_certificate", NULL},
  1834. {"SSL_get_version", NULL},
  1835. {"SSL_get_current_cipher", NULL},
  1836. {"SSL_CIPHER_get_name", NULL},
  1837. {"SSL_CTX_check_private_key", NULL},
  1838. {"SSL_CTX_set_session_id_context", NULL},
  1839. {"SSL_CTX_ctrl", NULL},
  1840. {"SSL_CTX_set_cipher_list", NULL},
  1841. {"SSL_CTX_set_info_callback", NULL},
  1842. {"SSL_get_ex_data", NULL},
  1843. {"SSL_set_ex_data", NULL},
  1844. {"SSL_CTX_callback_ctrl", NULL},
  1845. {"SSL_get_servername", NULL},
  1846. {"SSL_set_SSL_CTX", NULL},
  1847. {"SSL_ctrl", NULL},
  1848. {NULL, NULL}};
  1849. /* Similar array as ssl_sw. These functions could be located in different
  1850. * lib. */
  1851. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1852. {"CRYPTO_set_locking_callback", NULL},
  1853. {"CRYPTO_set_id_callback", NULL},
  1854. {"ERR_get_error", NULL},
  1855. {"ERR_error_string", NULL},
  1856. {"ERR_remove_state", NULL},
  1857. {"ERR_free_strings", NULL},
  1858. {"ENGINE_cleanup", NULL},
  1859. {"CONF_modules_unload", NULL},
  1860. {"CRYPTO_cleanup_all_ex_data", NULL},
  1861. {"EVP_cleanup", NULL},
  1862. {"X509_free", NULL},
  1863. {"X509_get_subject_name", NULL},
  1864. {"X509_get_issuer_name", NULL},
  1865. {"X509_NAME_oneline", NULL},
  1866. {"X509_get_serialNumber", NULL},
  1867. {"i2c_ASN1_INTEGER", NULL},
  1868. {"EVP_get_digestbyname", NULL},
  1869. {"EVP_Digest", NULL},
  1870. {"i2d_X509", NULL},
  1871. {"BN_bn2hex", NULL},
  1872. {"ASN1_INTEGER_to_BN", NULL},
  1873. {"BN_free", NULL},
  1874. {"CRYPTO_free", NULL},
  1875. {NULL, NULL}};
  1876. #endif /* OPENSSL_API_1_1 */
  1877. #endif /* NO_SSL_DL */
  1878. #endif /* NO_SSL */
  1879. #if !defined(NO_CACHING)
  1880. static const char month_names[][4] = {"Jan",
  1881. "Feb",
  1882. "Mar",
  1883. "Apr",
  1884. "May",
  1885. "Jun",
  1886. "Jul",
  1887. "Aug",
  1888. "Sep",
  1889. "Oct",
  1890. "Nov",
  1891. "Dec"};
  1892. #endif /* !NO_CACHING */
  1893. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1894. * the
  1895. * union u. */
  1896. union usa {
  1897. struct sockaddr sa;
  1898. struct sockaddr_in sin;
  1899. #if defined(USE_IPV6)
  1900. struct sockaddr_in6 sin6;
  1901. #endif
  1902. };
  1903. /* Describes a string (chunk of memory). */
  1904. struct vec {
  1905. const char *ptr;
  1906. size_t len;
  1907. };
  1908. struct mg_file_stat {
  1909. /* File properties filled by mg_stat: */
  1910. uint64_t size;
  1911. time_t last_modified;
  1912. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1913. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1914. * case we need a "Content-Eencoding: gzip" header */
  1915. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1916. };
  1917. struct mg_file_in_memory {
  1918. char *p;
  1919. uint32_t pos;
  1920. char mode;
  1921. };
  1922. struct mg_file_access {
  1923. /* File properties filled by mg_fopen: */
  1924. FILE *fp;
  1925. #if defined(MG_USE_OPEN_FILE)
  1926. /* TODO (low): Remove obsolete "file in memory" implementation.
  1927. * In an "early 2017" discussion at Google groups
  1928. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1929. * we decided to get rid of this feature (after some fade-out
  1930. * phase). */
  1931. const char *membuf;
  1932. #endif
  1933. };
  1934. struct mg_file {
  1935. struct mg_file_stat stat;
  1936. struct mg_file_access access;
  1937. };
  1938. #if defined(MG_USE_OPEN_FILE)
  1939. #define STRUCT_FILE_INITIALIZER \
  1940. { \
  1941. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1942. { \
  1943. (FILE *)NULL, (const char *)NULL \
  1944. } \
  1945. }
  1946. #else
  1947. #define STRUCT_FILE_INITIALIZER \
  1948. { \
  1949. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1950. { \
  1951. (FILE *)NULL \
  1952. } \
  1953. }
  1954. #endif
  1955. /* Describes listening socket, or socket which was accept()-ed by the master
  1956. * thread and queued for future handling by the worker thread. */
  1957. struct socket {
  1958. SOCKET sock; /* Listening socket */
  1959. union usa lsa; /* Local socket address */
  1960. union usa rsa; /* Remote socket address */
  1961. unsigned char is_ssl; /* Is port SSL-ed */
  1962. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1963. * port */
  1964. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1965. };
  1966. /* Enum const for all options must be in sync with
  1967. * static struct mg_option config_options[]
  1968. * This is tested in the unit test (test/private.c)
  1969. * "Private Config Options"
  1970. */
  1971. enum {
  1972. /* Once for each server */
  1973. LISTENING_PORTS,
  1974. NUM_THREADS,
  1975. RUN_AS_USER,
  1976. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1977. * socket option typedef TCP_NODELAY. */
  1978. MAX_REQUEST_SIZE,
  1979. LINGER_TIMEOUT,
  1980. #if defined(__linux__)
  1981. ALLOW_SENDFILE_CALL,
  1982. #endif
  1983. #if defined(_WIN32)
  1984. CASE_SENSITIVE_FILES,
  1985. #endif
  1986. THROTTLE,
  1987. ACCESS_LOG_FILE,
  1988. ERROR_LOG_FILE,
  1989. ENABLE_KEEP_ALIVE,
  1990. REQUEST_TIMEOUT,
  1991. KEEP_ALIVE_TIMEOUT,
  1992. #if defined(USE_WEBSOCKET)
  1993. WEBSOCKET_TIMEOUT,
  1994. ENABLE_WEBSOCKET_PING_PONG,
  1995. #endif
  1996. DECODE_URL,
  1997. #if defined(USE_LUA)
  1998. LUA_BACKGROUND_SCRIPT,
  1999. LUA_BACKGROUND_SCRIPT_PARAMS,
  2000. #endif
  2001. #if defined(USE_TIMERS)
  2002. CGI_TIMEOUT,
  2003. #endif
  2004. /* Once for each domain */
  2005. DOCUMENT_ROOT,
  2006. CGI_EXTENSIONS,
  2007. CGI_ENVIRONMENT,
  2008. PUT_DELETE_PASSWORDS_FILE,
  2009. CGI_INTERPRETER,
  2010. PROTECT_URI,
  2011. AUTHENTICATION_DOMAIN,
  2012. ENABLE_AUTH_DOMAIN_CHECK,
  2013. SSI_EXTENSIONS,
  2014. ENABLE_DIRECTORY_LISTING,
  2015. GLOBAL_PASSWORDS_FILE,
  2016. INDEX_FILES,
  2017. ACCESS_CONTROL_LIST,
  2018. EXTRA_MIME_TYPES,
  2019. SSL_CERTIFICATE,
  2020. SSL_CERTIFICATE_CHAIN,
  2021. URL_REWRITE_PATTERN,
  2022. HIDE_FILES,
  2023. SSL_DO_VERIFY_PEER,
  2024. SSL_CA_PATH,
  2025. SSL_CA_FILE,
  2026. SSL_VERIFY_DEPTH,
  2027. SSL_DEFAULT_VERIFY_PATHS,
  2028. SSL_CIPHER_LIST,
  2029. SSL_PROTOCOL_VERSION,
  2030. SSL_SHORT_TRUST,
  2031. #if defined(USE_LUA)
  2032. LUA_PRELOAD_FILE,
  2033. LUA_SCRIPT_EXTENSIONS,
  2034. LUA_SERVER_PAGE_EXTENSIONS,
  2035. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2036. LUA_DEBUG_PARAMS,
  2037. #endif
  2038. #endif
  2039. #if defined(USE_DUKTAPE)
  2040. DUKTAPE_SCRIPT_EXTENSIONS,
  2041. #endif
  2042. #if defined(USE_WEBSOCKET)
  2043. WEBSOCKET_ROOT,
  2044. #endif
  2045. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2046. LUA_WEBSOCKET_EXTENSIONS,
  2047. #endif
  2048. ACCESS_CONTROL_ALLOW_ORIGIN,
  2049. ACCESS_CONTROL_ALLOW_METHODS,
  2050. ACCESS_CONTROL_ALLOW_HEADERS,
  2051. ERROR_PAGES,
  2052. #if !defined(NO_CACHING)
  2053. STATIC_FILE_MAX_AGE,
  2054. #endif
  2055. #if !defined(NO_SSL)
  2056. STRICT_HTTPS_MAX_AGE,
  2057. #endif
  2058. ADDITIONAL_HEADER,
  2059. ALLOW_INDEX_SCRIPT_SUB_RES,
  2060. #if defined(DAEMONIZE)
  2061. ENABLE_DAEMONIZE,
  2062. #endif
  2063. NUM_OPTIONS
  2064. };
  2065. /* Config option name, config types, default value.
  2066. * Must be in the same order as the enum const above.
  2067. */
  2068. static const struct mg_option config_options[] = {
  2069. /* Once for each server */
  2070. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2071. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2072. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2073. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2074. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2075. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2076. #if defined(__linux__)
  2077. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2078. #endif
  2079. #if defined(_WIN32)
  2080. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2081. #endif
  2082. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2083. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2084. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2085. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2086. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2087. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2088. #if defined(USE_WEBSOCKET)
  2089. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2090. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2091. #endif
  2092. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2093. #if defined(USE_LUA)
  2094. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2095. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2096. #endif
  2097. #if defined(USE_TIMERS)
  2098. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2099. #endif
  2100. /* Once for each domain */
  2101. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2102. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2103. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2104. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2105. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2106. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2107. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2108. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2109. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2110. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2111. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2112. {"index_files",
  2113. MG_CONFIG_TYPE_STRING_LIST,
  2114. #if defined(USE_LUA)
  2115. "index.xhtml,index.html,index.htm,"
  2116. "index.lp,index.lsp,index.lua,index.cgi,"
  2117. "index.shtml,index.php"},
  2118. #else
  2119. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2120. #endif
  2121. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2122. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2123. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2124. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2125. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2126. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2127. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2128. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2129. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2130. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2131. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2132. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2133. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2134. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2135. #if defined(USE_LUA)
  2136. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2137. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2138. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2139. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2140. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2141. #endif
  2142. #endif
  2143. #if defined(USE_DUKTAPE)
  2144. /* The support for duktape is still in alpha version state.
  2145. * The name of this config option might change. */
  2146. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2147. #endif
  2148. #if defined(USE_WEBSOCKET)
  2149. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2150. #endif
  2151. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2152. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2153. #endif
  2154. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2155. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2156. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2157. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2158. #if !defined(NO_CACHING)
  2159. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2160. #endif
  2161. #if !defined(NO_SSL)
  2162. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2163. #endif
  2164. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2165. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2166. #if defined(DAEMONIZE)
  2167. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2168. #endif
  2169. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2170. /* Check if the config_options and the corresponding enum have compatible
  2171. * sizes. */
  2172. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2173. == (NUM_OPTIONS + 1),
  2174. "config_options and enum not sync");
  2175. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2176. struct mg_handler_info {
  2177. /* Name/Pattern of the URI. */
  2178. char *uri;
  2179. size_t uri_len;
  2180. /* handler type */
  2181. int handler_type;
  2182. /* Handler for http/https or authorization requests. */
  2183. mg_request_handler handler;
  2184. unsigned int refcount;
  2185. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2186. pthread_cond_t
  2187. refcount_cond; /* Signaled when handler refcount is decremented */
  2188. /* Handler for ws/wss (websocket) requests. */
  2189. mg_websocket_connect_handler connect_handler;
  2190. mg_websocket_ready_handler ready_handler;
  2191. mg_websocket_data_handler data_handler;
  2192. mg_websocket_close_handler close_handler;
  2193. /* accepted subprotocols for ws/wss requests. */
  2194. struct mg_websocket_subprotocols *subprotocols;
  2195. /* Handler for authorization requests */
  2196. mg_authorization_handler auth_handler;
  2197. /* User supplied argument for the handler function. */
  2198. void *cbdata;
  2199. /* next handler in a linked list */
  2200. struct mg_handler_info *next;
  2201. };
  2202. enum {
  2203. CONTEXT_INVALID,
  2204. CONTEXT_SERVER,
  2205. CONTEXT_HTTP_CLIENT,
  2206. CONTEXT_WS_CLIENT
  2207. };
  2208. struct mg_domain_context {
  2209. SSL_CTX *ssl_ctx; /* SSL context */
  2210. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2211. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2212. /* Server nonce */
  2213. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2214. unsigned long nonce_count; /* Used nonces, used for authentication */
  2215. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2216. /* linked list of shared lua websockets */
  2217. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2218. #endif
  2219. /* Linked list of domains */
  2220. struct mg_domain_context *next;
  2221. };
  2222. struct mg_context {
  2223. /* Part 1 - Physical context:
  2224. * This holds threads, ports, timeouts, ...
  2225. * set for the entire server, independent from the
  2226. * addressed hostname.
  2227. */
  2228. /* Connection related */
  2229. int context_type; /* See CONTEXT_* above */
  2230. struct socket *listening_sockets;
  2231. struct mg_pollfd *listening_socket_fds;
  2232. unsigned int num_listening_sockets;
  2233. struct mg_connection *worker_connections; /* The connection struct, pre-
  2234. * allocated for each worker */
  2235. #if defined(USE_SERVER_STATS)
  2236. int active_connections;
  2237. int max_connections;
  2238. int64_t total_connections;
  2239. int64_t total_requests;
  2240. int64_t total_data_read;
  2241. int64_t total_data_written;
  2242. #endif
  2243. /* Thread related */
  2244. volatile int stop_flag; /* Should we stop event loop */
  2245. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2246. pthread_t masterthreadid; /* The master thread ID */
  2247. unsigned int
  2248. cfg_worker_threads; /* The number of configured worker threads. */
  2249. pthread_t *worker_threadids; /* The worker thread IDs */
  2250. /* Connection to thread dispatching */
  2251. #if defined(ALTERNATIVE_QUEUE)
  2252. struct socket *client_socks;
  2253. void **client_wait_events;
  2254. #else
  2255. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2256. volatile int sq_head; /* Head of the socket queue */
  2257. volatile int sq_tail; /* Tail of the socket queue */
  2258. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2259. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2260. #endif
  2261. /* Memory related */
  2262. unsigned int max_request_size; /* The max request size */
  2263. #if defined(USE_SERVER_STATS)
  2264. struct mg_memory_stat ctx_memory;
  2265. #endif
  2266. /* Operating system related */
  2267. char *systemName; /* What operating system is running */
  2268. time_t start_time; /* Server start time, used for authentication
  2269. * and for diagnstics. */
  2270. #if defined(USE_TIMERS)
  2271. struct ttimers *timers;
  2272. #endif
  2273. /* Lua specific: Background operations and shared websockets */
  2274. #if defined(USE_LUA)
  2275. void *lua_background_state;
  2276. #endif
  2277. /* Server nonce */
  2278. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2279. /* Server callbacks */
  2280. struct mg_callbacks callbacks; /* User-defined callback function */
  2281. void *user_data; /* User-defined data */
  2282. /* Part 2 - Logical domain:
  2283. * This holds hostname, TLS certificate, document root, ...
  2284. * set for a domain hosted at the server.
  2285. * There may be multiple domains hosted at one physical server.
  2286. * The default domain "dd" is the first element of a list of
  2287. * domains.
  2288. */
  2289. struct mg_domain_context dd; /* default domain */
  2290. };
  2291. #if defined(USE_SERVER_STATS)
  2292. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2293. static struct mg_memory_stat *
  2294. get_memory_stat(struct mg_context *ctx)
  2295. {
  2296. if (ctx) {
  2297. return &(ctx->ctx_memory);
  2298. }
  2299. return &mg_common_memory;
  2300. }
  2301. #endif
  2302. enum {
  2303. CONNECTION_TYPE_INVALID,
  2304. CONNECTION_TYPE_REQUEST,
  2305. CONNECTION_TYPE_RESPONSE
  2306. };
  2307. struct mg_connection {
  2308. int connection_type; /* see CONNECTION_TYPE_* above */
  2309. struct mg_request_info request_info;
  2310. struct mg_response_info response_info;
  2311. struct mg_context *phys_ctx;
  2312. struct mg_domain_context *dom_ctx;
  2313. #if defined(USE_SERVER_STATS)
  2314. int conn_state; /* 0 = undef, numerical value may change in different
  2315. * versions. For the current definition, see
  2316. * mg_get_connection_info_impl */
  2317. #endif
  2318. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2319. SSL *ssl; /* SSL descriptor */
  2320. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2321. struct socket client; /* Connected client */
  2322. time_t conn_birth_time; /* Time (wall clock) when connection was
  2323. * established */
  2324. struct timespec req_time; /* Time (since system start) when the request
  2325. * was received */
  2326. int64_t num_bytes_sent; /* Total bytes sent to client */
  2327. int64_t content_len; /* Content-Length header value */
  2328. int64_t consumed_content; /* How many bytes of content have been read */
  2329. int is_chunked; /* Transfer-Encoding is chunked:
  2330. * 0 = not chunked,
  2331. * 1 = chunked, do data read yet,
  2332. * 2 = chunked, some data read,
  2333. * 3 = chunked, all data read
  2334. */
  2335. size_t chunk_remainder; /* Unread data from the last chunk */
  2336. char *buf; /* Buffer for received data */
  2337. char *path_info; /* PATH_INFO part of the URL */
  2338. int must_close; /* 1 if connection must be closed */
  2339. int accept_gzip; /* 1 if gzip encoding is accepted */
  2340. int in_error_handler; /* 1 if in handler for user defined error
  2341. * pages */
  2342. #if defined(USE_WEBSOCKET)
  2343. int in_websocket_handling; /* 1 if in read_websocket */
  2344. #endif
  2345. int handled_requests; /* Number of requests handled by this connection
  2346. */
  2347. int buf_size; /* Buffer size */
  2348. int request_len; /* Size of the request + headers in a buffer */
  2349. int data_len; /* Total size of data in a buffer */
  2350. int status_code; /* HTTP reply status code, e.g. 200 */
  2351. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2352. * throttle */
  2353. time_t last_throttle_time; /* Last time throttled data was sent */
  2354. int last_throttle_bytes; /* Bytes sent this second */
  2355. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2356. * atomic transmissions for websockets */
  2357. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2358. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2359. #endif
  2360. };
  2361. /* Directory entry */
  2362. struct de {
  2363. struct mg_connection *conn;
  2364. char *file_name;
  2365. struct mg_file_stat file;
  2366. };
  2367. #if defined(USE_WEBSOCKET)
  2368. static int is_websocket_protocol(const struct mg_connection *conn);
  2369. #else
  2370. #define is_websocket_protocol(conn) (0)
  2371. #endif
  2372. #define mg_cry_internal(conn, fmt, ...) \
  2373. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2374. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2375. const char *func,
  2376. unsigned line,
  2377. const char *fmt,
  2378. ...) PRINTF_ARGS(4, 5);
  2379. #if !defined(NO_THREAD_NAME)
  2380. #if defined(_WIN32) && defined(_MSC_VER)
  2381. /* Set the thread name for debugging purposes in Visual Studio
  2382. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2383. */
  2384. #pragma pack(push, 8)
  2385. typedef struct tagTHREADNAME_INFO {
  2386. DWORD dwType; /* Must be 0x1000. */
  2387. LPCSTR szName; /* Pointer to name (in user addr space). */
  2388. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2389. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2390. } THREADNAME_INFO;
  2391. #pragma pack(pop)
  2392. #elif defined(__linux__)
  2393. #include <sys/prctl.h>
  2394. #include <sys/sendfile.h>
  2395. #if defined(ALTERNATIVE_QUEUE)
  2396. #include <sys/eventfd.h>
  2397. #endif /* ALTERNATIVE_QUEUE */
  2398. #if defined(ALTERNATIVE_QUEUE)
  2399. static void *
  2400. event_create(void)
  2401. {
  2402. int evhdl = eventfd(0, EFD_CLOEXEC);
  2403. int *ret;
  2404. if (evhdl == -1) {
  2405. /* Linux uses -1 on error, Windows NULL. */
  2406. /* However, Linux does not return 0 on success either. */
  2407. return 0;
  2408. }
  2409. ret = (int *)mg_malloc(sizeof(int));
  2410. if (ret) {
  2411. *ret = evhdl;
  2412. } else {
  2413. (void)close(evhdl);
  2414. }
  2415. return (void *)ret;
  2416. }
  2417. static int
  2418. event_wait(void *eventhdl)
  2419. {
  2420. uint64_t u;
  2421. int evhdl, s;
  2422. if (!eventhdl) {
  2423. /* error */
  2424. return 0;
  2425. }
  2426. evhdl = *(int *)eventhdl;
  2427. s = (int)read(evhdl, &u, sizeof(u));
  2428. if (s != sizeof(u)) {
  2429. /* error */
  2430. return 0;
  2431. }
  2432. (void)u; /* the value is not required */
  2433. return 1;
  2434. }
  2435. static int
  2436. event_signal(void *eventhdl)
  2437. {
  2438. uint64_t u = 1;
  2439. int evhdl, s;
  2440. if (!eventhdl) {
  2441. /* error */
  2442. return 0;
  2443. }
  2444. evhdl = *(int *)eventhdl;
  2445. s = (int)write(evhdl, &u, sizeof(u));
  2446. if (s != sizeof(u)) {
  2447. /* error */
  2448. return 0;
  2449. }
  2450. return 1;
  2451. }
  2452. static void
  2453. event_destroy(void *eventhdl)
  2454. {
  2455. int evhdl;
  2456. if (!eventhdl) {
  2457. /* error */
  2458. return;
  2459. }
  2460. evhdl = *(int *)eventhdl;
  2461. close(evhdl);
  2462. mg_free(eventhdl);
  2463. }
  2464. #endif
  2465. #endif
  2466. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2467. struct posix_event {
  2468. pthread_mutex_t mutex;
  2469. pthread_cond_t cond;
  2470. int signaled;
  2471. };
  2472. static void *
  2473. event_create(void)
  2474. {
  2475. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2476. if (ret == 0) {
  2477. /* out of memory */
  2478. return 0;
  2479. }
  2480. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2481. /* pthread mutex not available */
  2482. mg_free(ret);
  2483. return 0;
  2484. }
  2485. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2486. /* pthread cond not available */
  2487. pthread_mutex_destroy(&(ret->mutex));
  2488. mg_free(ret);
  2489. return 0;
  2490. }
  2491. ret->signaled = 0;
  2492. return (void *)ret;
  2493. }
  2494. static int
  2495. event_wait(void *eventhdl)
  2496. {
  2497. struct posix_event *ev = (struct posix_event *)eventhdl;
  2498. pthread_mutex_lock(&(ev->mutex));
  2499. while (!ev->signaled) {
  2500. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2501. }
  2502. ev->signaled = 0;
  2503. pthread_mutex_unlock(&(ev->mutex));
  2504. return 1;
  2505. }
  2506. static int
  2507. event_signal(void *eventhdl)
  2508. {
  2509. struct posix_event *ev = (struct posix_event *)eventhdl;
  2510. pthread_mutex_lock(&(ev->mutex));
  2511. pthread_cond_signal(&(ev->cond));
  2512. ev->signaled = 1;
  2513. pthread_mutex_unlock(&(ev->mutex));
  2514. return 1;
  2515. }
  2516. static void
  2517. event_destroy(void *eventhdl)
  2518. {
  2519. struct posix_event *ev = (struct posix_event *)eventhdl;
  2520. pthread_cond_destroy(&(ev->cond));
  2521. pthread_mutex_destroy(&(ev->mutex));
  2522. mg_free(ev);
  2523. }
  2524. #endif
  2525. static void
  2526. mg_set_thread_name(const char *name)
  2527. {
  2528. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2529. mg_snprintf(
  2530. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2531. #if defined(_WIN32)
  2532. #if defined(_MSC_VER)
  2533. /* Windows and Visual Studio Compiler */
  2534. __try {
  2535. THREADNAME_INFO info;
  2536. info.dwType = 0x1000;
  2537. info.szName = threadName;
  2538. info.dwThreadID = ~0U;
  2539. info.dwFlags = 0;
  2540. RaiseException(0x406D1388,
  2541. 0,
  2542. sizeof(info) / sizeof(ULONG_PTR),
  2543. (ULONG_PTR *)&info);
  2544. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2545. }
  2546. #elif defined(__MINGW32__)
  2547. /* No option known to set thread name for MinGW */
  2548. #endif
  2549. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2550. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2551. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2552. #if defined(__MACH__)
  2553. /* OS X only current thread name can be changed */
  2554. (void)pthread_setname_np(threadName);
  2555. #else
  2556. (void)pthread_setname_np(pthread_self(), threadName);
  2557. #endif
  2558. #elif defined(__linux__)
  2559. /* on linux we can use the old prctl function */
  2560. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2561. #endif
  2562. }
  2563. #else /* !defined(NO_THREAD_NAME) */
  2564. void
  2565. mg_set_thread_name(const char *threadName)
  2566. {
  2567. }
  2568. #endif
  2569. #if defined(MG_LEGACY_INTERFACE)
  2570. const char **
  2571. mg_get_valid_option_names(void)
  2572. {
  2573. /* This function is deprecated. Use mg_get_valid_options instead. */
  2574. static const char
  2575. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2576. int i;
  2577. for (i = 0; config_options[i].name != NULL; i++) {
  2578. data[i * 2] = config_options[i].name;
  2579. data[i * 2 + 1] = config_options[i].default_value;
  2580. }
  2581. return data;
  2582. }
  2583. #endif
  2584. const struct mg_option *
  2585. mg_get_valid_options(void)
  2586. {
  2587. return config_options;
  2588. }
  2589. /* Do not open file (used in is_file_in_memory) */
  2590. #define MG_FOPEN_MODE_NONE (0)
  2591. /* Open file for read only access */
  2592. #define MG_FOPEN_MODE_READ (1)
  2593. /* Open file for writing, create and overwrite */
  2594. #define MG_FOPEN_MODE_WRITE (2)
  2595. /* Open file for writing, create and append */
  2596. #define MG_FOPEN_MODE_APPEND (4)
  2597. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2598. * output filep and return 1, otherwise return 0 and don't modify anything.
  2599. */
  2600. static int
  2601. open_file_in_memory(const struct mg_connection *conn,
  2602. const char *path,
  2603. struct mg_file *filep,
  2604. int mode)
  2605. {
  2606. #if defined(MG_USE_OPEN_FILE)
  2607. size_t size = 0;
  2608. const char *buf = NULL;
  2609. if (!conn) {
  2610. return 0;
  2611. }
  2612. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2613. return 0;
  2614. }
  2615. if (conn->phys_ctx->callbacks.open_file) {
  2616. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2617. if (buf != NULL) {
  2618. if (filep == NULL) {
  2619. /* This is a file in memory, but we cannot store the
  2620. * properties
  2621. * now.
  2622. * Called from "is_file_in_memory" function. */
  2623. return 1;
  2624. }
  2625. /* NOTE: override filep->size only on success. Otherwise, it
  2626. * might
  2627. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2628. filep->access.membuf = buf;
  2629. filep->access.fp = NULL;
  2630. /* Size was set by the callback */
  2631. filep->stat.size = size;
  2632. /* Assume the data may change during runtime by setting
  2633. * last_modified = now */
  2634. filep->stat.last_modified = time(NULL);
  2635. filep->stat.is_directory = 0;
  2636. filep->stat.is_gzipped = 0;
  2637. }
  2638. }
  2639. return (buf != NULL);
  2640. #else
  2641. (void)conn;
  2642. (void)path;
  2643. (void)filep;
  2644. (void)mode;
  2645. return 0;
  2646. #endif
  2647. }
  2648. static int
  2649. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2650. {
  2651. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2652. }
  2653. static int
  2654. is_file_opened(const struct mg_file_access *fileacc)
  2655. {
  2656. if (!fileacc) {
  2657. return 0;
  2658. }
  2659. #if defined(MG_USE_OPEN_FILE)
  2660. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2661. #else
  2662. return (fileacc->fp != NULL);
  2663. #endif
  2664. }
  2665. static int mg_stat(const struct mg_connection *conn,
  2666. const char *path,
  2667. struct mg_file_stat *filep);
  2668. /* mg_fopen will open a file either in memory or on the disk.
  2669. * The input parameter path is a string in UTF-8 encoding.
  2670. * The input parameter mode is MG_FOPEN_MODE_*
  2671. * On success, either fp or membuf will be set in the output
  2672. * struct file. All status members will also be set.
  2673. * The function returns 1 on success, 0 on error. */
  2674. static int
  2675. mg_fopen(const struct mg_connection *conn,
  2676. const char *path,
  2677. int mode,
  2678. struct mg_file *filep)
  2679. {
  2680. int found;
  2681. if (!filep) {
  2682. return 0;
  2683. }
  2684. filep->access.fp = NULL;
  2685. #if defined(MG_USE_OPEN_FILE)
  2686. filep->access.membuf = NULL;
  2687. #endif
  2688. if (!is_file_in_memory(conn, path)) {
  2689. /* filep is initialized in mg_stat: all fields with memset to,
  2690. * some fields like size and modification date with values */
  2691. found = mg_stat(conn, path, &(filep->stat));
  2692. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2693. /* file does not exist and will not be created */
  2694. return 0;
  2695. }
  2696. #if defined(_WIN32)
  2697. {
  2698. wchar_t wbuf[W_PATH_MAX];
  2699. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2700. switch (mode) {
  2701. case MG_FOPEN_MODE_READ:
  2702. filep->access.fp = _wfopen(wbuf, L"rb");
  2703. break;
  2704. case MG_FOPEN_MODE_WRITE:
  2705. filep->access.fp = _wfopen(wbuf, L"wb");
  2706. break;
  2707. case MG_FOPEN_MODE_APPEND:
  2708. filep->access.fp = _wfopen(wbuf, L"ab");
  2709. break;
  2710. }
  2711. }
  2712. #else
  2713. /* Linux et al already use unicode. No need to convert. */
  2714. switch (mode) {
  2715. case MG_FOPEN_MODE_READ:
  2716. filep->access.fp = fopen(path, "r");
  2717. break;
  2718. case MG_FOPEN_MODE_WRITE:
  2719. filep->access.fp = fopen(path, "w");
  2720. break;
  2721. case MG_FOPEN_MODE_APPEND:
  2722. filep->access.fp = fopen(path, "a");
  2723. break;
  2724. }
  2725. #endif
  2726. if (!found) {
  2727. /* File did not exist before fopen was called.
  2728. * Maybe it has been created now. Get stat info
  2729. * like creation time now. */
  2730. found = mg_stat(conn, path, &(filep->stat));
  2731. (void)found;
  2732. }
  2733. /* file is on disk */
  2734. return (filep->access.fp != NULL);
  2735. } else {
  2736. #if defined(MG_USE_OPEN_FILE)
  2737. /* is_file_in_memory returned true */
  2738. if (open_file_in_memory(conn, path, filep, mode)) {
  2739. /* file is in memory */
  2740. return (filep->access.membuf != NULL);
  2741. }
  2742. #endif
  2743. }
  2744. /* Open failed */
  2745. return 0;
  2746. }
  2747. /* return 0 on success, just like fclose */
  2748. static int
  2749. mg_fclose(struct mg_file_access *fileacc)
  2750. {
  2751. int ret = -1;
  2752. if (fileacc != NULL) {
  2753. if (fileacc->fp != NULL) {
  2754. ret = fclose(fileacc->fp);
  2755. #if defined(MG_USE_OPEN_FILE)
  2756. } else if (fileacc->membuf != NULL) {
  2757. ret = 0;
  2758. #endif
  2759. }
  2760. /* reset all members of fileacc */
  2761. memset(fileacc, 0, sizeof(*fileacc));
  2762. }
  2763. return ret;
  2764. }
  2765. static void
  2766. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2767. {
  2768. for (; *src != '\0' && n > 1; n--) {
  2769. *dst++ = *src++;
  2770. }
  2771. *dst = '\0';
  2772. }
  2773. static int
  2774. lowercase(const char *s)
  2775. {
  2776. return tolower((unsigned char)*s);
  2777. }
  2778. int
  2779. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2780. {
  2781. int diff = 0;
  2782. if (len > 0) {
  2783. do {
  2784. diff = lowercase(s1++) - lowercase(s2++);
  2785. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2786. }
  2787. return diff;
  2788. }
  2789. int
  2790. mg_strcasecmp(const char *s1, const char *s2)
  2791. {
  2792. int diff;
  2793. do {
  2794. diff = lowercase(s1++) - lowercase(s2++);
  2795. } while (diff == 0 && s1[-1] != '\0');
  2796. return diff;
  2797. }
  2798. static char *
  2799. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2800. {
  2801. char *p;
  2802. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2803. * defined */
  2804. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2805. mg_strlcpy(p, ptr, len + 1);
  2806. }
  2807. return p;
  2808. }
  2809. static char *
  2810. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2811. {
  2812. return mg_strndup_ctx(str, strlen(str), ctx);
  2813. }
  2814. static char *
  2815. mg_strdup(const char *str)
  2816. {
  2817. return mg_strndup_ctx(str, strlen(str), NULL);
  2818. }
  2819. static const char *
  2820. mg_strcasestr(const char *big_str, const char *small_str)
  2821. {
  2822. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2823. if (big_len >= small_len) {
  2824. for (i = 0; i <= (big_len - small_len); i++) {
  2825. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2826. return big_str + i;
  2827. }
  2828. }
  2829. }
  2830. return NULL;
  2831. }
  2832. /* Return null terminated string of given maximum length.
  2833. * Report errors if length is exceeded. */
  2834. static void
  2835. mg_vsnprintf(const struct mg_connection *conn,
  2836. int *truncated,
  2837. char *buf,
  2838. size_t buflen,
  2839. const char *fmt,
  2840. va_list ap)
  2841. {
  2842. int n, ok;
  2843. if (buflen == 0) {
  2844. if (truncated) {
  2845. *truncated = 1;
  2846. }
  2847. return;
  2848. }
  2849. #if defined(__clang__)
  2850. #pragma clang diagnostic push
  2851. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2852. /* Using fmt as a non-literal is intended here, since it is mostly called
  2853. * indirectly by mg_snprintf */
  2854. #endif
  2855. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2856. ok = (n >= 0) && ((size_t)n < buflen);
  2857. #if defined(__clang__)
  2858. #pragma clang diagnostic pop
  2859. #endif
  2860. if (ok) {
  2861. if (truncated) {
  2862. *truncated = 0;
  2863. }
  2864. } else {
  2865. if (truncated) {
  2866. *truncated = 1;
  2867. }
  2868. mg_cry_internal(conn,
  2869. "truncating vsnprintf buffer: [%.*s]",
  2870. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2871. buf);
  2872. n = (int)buflen - 1;
  2873. }
  2874. buf[n] = '\0';
  2875. }
  2876. static void
  2877. mg_snprintf(const struct mg_connection *conn,
  2878. int *truncated,
  2879. char *buf,
  2880. size_t buflen,
  2881. const char *fmt,
  2882. ...)
  2883. {
  2884. va_list ap;
  2885. va_start(ap, fmt);
  2886. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2887. va_end(ap);
  2888. }
  2889. static int
  2890. get_option_index(const char *name)
  2891. {
  2892. int i;
  2893. for (i = 0; config_options[i].name != NULL; i++) {
  2894. if (strcmp(config_options[i].name, name) == 0) {
  2895. return i;
  2896. }
  2897. }
  2898. return -1;
  2899. }
  2900. const char *
  2901. mg_get_option(const struct mg_context *ctx, const char *name)
  2902. {
  2903. int i;
  2904. if ((i = get_option_index(name)) == -1) {
  2905. return NULL;
  2906. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2907. return "";
  2908. } else {
  2909. return ctx->dd.config[i];
  2910. }
  2911. }
  2912. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2913. struct mg_context *
  2914. mg_get_context(const struct mg_connection *conn)
  2915. {
  2916. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2917. }
  2918. void *
  2919. mg_get_user_data(const struct mg_context *ctx)
  2920. {
  2921. return (ctx == NULL) ? NULL : ctx->user_data;
  2922. }
  2923. void
  2924. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2925. {
  2926. if (conn != NULL) {
  2927. conn->request_info.conn_data = data;
  2928. }
  2929. }
  2930. void *
  2931. mg_get_user_connection_data(const struct mg_connection *conn)
  2932. {
  2933. if (conn != NULL) {
  2934. return conn->request_info.conn_data;
  2935. }
  2936. return NULL;
  2937. }
  2938. #if defined(MG_LEGACY_INTERFACE)
  2939. /* Deprecated: Use mg_get_server_ports instead. */
  2940. size_t
  2941. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2942. {
  2943. size_t i;
  2944. if (!ctx) {
  2945. return 0;
  2946. }
  2947. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2948. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2949. ports[i] =
  2950. #if defined(USE_IPV6)
  2951. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2952. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2953. :
  2954. #endif
  2955. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2956. }
  2957. return i;
  2958. }
  2959. #endif
  2960. int
  2961. mg_get_server_ports(const struct mg_context *ctx,
  2962. int size,
  2963. struct mg_server_port *ports)
  2964. {
  2965. int i, cnt = 0;
  2966. if (size <= 0) {
  2967. return -1;
  2968. }
  2969. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2970. if (!ctx) {
  2971. return -1;
  2972. }
  2973. if (!ctx->listening_sockets) {
  2974. return -1;
  2975. }
  2976. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2977. ports[cnt].port =
  2978. #if defined(USE_IPV6)
  2979. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2980. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2981. :
  2982. #endif
  2983. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2984. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2985. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2986. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2987. /* IPv4 */
  2988. ports[cnt].protocol = 1;
  2989. cnt++;
  2990. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2991. /* IPv6 */
  2992. ports[cnt].protocol = 3;
  2993. cnt++;
  2994. }
  2995. }
  2996. return cnt;
  2997. }
  2998. static void
  2999. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3000. {
  3001. buf[0] = '\0';
  3002. if (!usa) {
  3003. return;
  3004. }
  3005. if (usa->sa.sa_family == AF_INET) {
  3006. getnameinfo(&usa->sa,
  3007. sizeof(usa->sin),
  3008. buf,
  3009. (unsigned)len,
  3010. NULL,
  3011. 0,
  3012. NI_NUMERICHOST);
  3013. }
  3014. #if defined(USE_IPV6)
  3015. else if (usa->sa.sa_family == AF_INET6) {
  3016. getnameinfo(&usa->sa,
  3017. sizeof(usa->sin6),
  3018. buf,
  3019. (unsigned)len,
  3020. NULL,
  3021. 0,
  3022. NI_NUMERICHOST);
  3023. }
  3024. #endif
  3025. }
  3026. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3027. * included in all responses other than 100, 101, 5xx. */
  3028. static void
  3029. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3030. {
  3031. #if !defined(REENTRANT_TIME)
  3032. struct tm *tm;
  3033. tm = ((t != NULL) ? gmtime(t) : NULL);
  3034. if (tm != NULL) {
  3035. #else
  3036. struct tm _tm;
  3037. struct tm *tm = &_tm;
  3038. if (t != NULL) {
  3039. gmtime_r(t, tm);
  3040. #endif
  3041. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3042. } else {
  3043. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3044. buf[buf_len - 1] = '\0';
  3045. }
  3046. }
  3047. /* difftime for struct timespec. Return value is in seconds. */
  3048. static double
  3049. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3050. {
  3051. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3052. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3053. }
  3054. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3055. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3056. const char *func,
  3057. unsigned line,
  3058. const char *fmt,
  3059. va_list ap);
  3060. #include "external_mg_cry_internal_impl.inl"
  3061. #else
  3062. /* Print error message to the opened error log stream. */
  3063. static void
  3064. mg_cry_internal_impl(const struct mg_connection *conn,
  3065. const char *func,
  3066. unsigned line,
  3067. const char *fmt,
  3068. va_list ap)
  3069. {
  3070. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3071. struct mg_file fi;
  3072. time_t timestamp;
  3073. /* Unused, in the RELEASE build */
  3074. (void)func;
  3075. (void)line;
  3076. #if defined(GCC_DIAGNOSTIC)
  3077. #pragma GCC diagnostic push
  3078. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3079. #endif
  3080. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3081. #if defined(GCC_DIAGNOSTIC)
  3082. #pragma GCC diagnostic pop
  3083. #endif
  3084. buf[sizeof(buf) - 1] = 0;
  3085. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3086. if (!conn) {
  3087. puts(buf);
  3088. return;
  3089. }
  3090. /* Do not lock when getting the callback value, here and below.
  3091. * I suppose this is fine, since function cannot disappear in the
  3092. * same way string option can. */
  3093. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3094. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3095. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3096. if (mg_fopen(conn,
  3097. conn->dom_ctx->config[ERROR_LOG_FILE],
  3098. MG_FOPEN_MODE_APPEND,
  3099. &fi)
  3100. == 0) {
  3101. fi.access.fp = NULL;
  3102. }
  3103. } else {
  3104. fi.access.fp = NULL;
  3105. }
  3106. if (fi.access.fp != NULL) {
  3107. flockfile(fi.access.fp);
  3108. timestamp = time(NULL);
  3109. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3110. fprintf(fi.access.fp,
  3111. "[%010lu] [error] [client %s] ",
  3112. (unsigned long)timestamp,
  3113. src_addr);
  3114. if (conn->request_info.request_method != NULL) {
  3115. fprintf(fi.access.fp,
  3116. "%s %s: ",
  3117. conn->request_info.request_method,
  3118. conn->request_info.request_uri
  3119. ? conn->request_info.request_uri
  3120. : "");
  3121. }
  3122. fprintf(fi.access.fp, "%s", buf);
  3123. fputc('\n', fi.access.fp);
  3124. fflush(fi.access.fp);
  3125. funlockfile(fi.access.fp);
  3126. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3127. * mg_cry here anyway ;-) */
  3128. }
  3129. }
  3130. }
  3131. #endif /* Externally provided function */
  3132. static void
  3133. mg_cry_internal_wrap(const struct mg_connection *conn,
  3134. const char *func,
  3135. unsigned line,
  3136. const char *fmt,
  3137. ...)
  3138. {
  3139. va_list ap;
  3140. va_start(ap, fmt);
  3141. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3142. va_end(ap);
  3143. }
  3144. void
  3145. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3146. {
  3147. va_list ap;
  3148. va_start(ap, fmt);
  3149. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3150. va_end(ap);
  3151. }
  3152. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3153. /* Return fake connection structure. Used for logging, if connection
  3154. * is not applicable at the moment of logging. */
  3155. static struct mg_connection *
  3156. fc(struct mg_context *ctx)
  3157. {
  3158. static struct mg_connection fake_connection;
  3159. fake_connection.phys_ctx = ctx;
  3160. fake_connection.dom_ctx = &(ctx->dd);
  3161. return &fake_connection;
  3162. }
  3163. const char *
  3164. mg_version(void)
  3165. {
  3166. return CIVETWEB_VERSION;
  3167. }
  3168. const struct mg_request_info *
  3169. mg_get_request_info(const struct mg_connection *conn)
  3170. {
  3171. if (!conn) {
  3172. return NULL;
  3173. }
  3174. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3175. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3176. char txt[16];
  3177. struct mg_workerTLS *tls =
  3178. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3179. sprintf(txt, "%03i", conn->response_info.status_code);
  3180. if (strlen(txt) == 3) {
  3181. memcpy(tls->txtbuf, txt, 4);
  3182. } else {
  3183. strcpy(tls->txtbuf, "ERR");
  3184. }
  3185. ((struct mg_connection *)conn)->request_info.local_uri =
  3186. ((struct mg_connection *)conn)->request_info.request_uri =
  3187. tls->txtbuf; /* use thread safe buffer */
  3188. ((struct mg_connection *)conn)->request_info.num_headers =
  3189. conn->response_info.num_headers;
  3190. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3191. conn->response_info.http_headers,
  3192. sizeof(conn->response_info.http_headers));
  3193. } else
  3194. #endif
  3195. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3196. return NULL;
  3197. }
  3198. return &conn->request_info;
  3199. }
  3200. const struct mg_response_info *
  3201. mg_get_response_info(const struct mg_connection *conn)
  3202. {
  3203. if (!conn) {
  3204. return NULL;
  3205. }
  3206. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3207. return NULL;
  3208. }
  3209. return &conn->response_info;
  3210. }
  3211. static const char *
  3212. get_proto_name(const struct mg_connection *conn)
  3213. {
  3214. #if defined(__clang__)
  3215. #pragma clang diagnostic push
  3216. #pragma clang diagnostic ignored "-Wunreachable-code"
  3217. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3218. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3219. * unreachable, but splitting into four different #ifdef clauses here is more
  3220. * complicated.
  3221. */
  3222. #endif
  3223. const struct mg_request_info *ri = &conn->request_info;
  3224. const char *proto =
  3225. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3226. : (ri->is_ssl ? "https" : "http"));
  3227. return proto;
  3228. #if defined(__clang__)
  3229. #pragma clang diagnostic pop
  3230. #endif
  3231. }
  3232. int
  3233. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3234. {
  3235. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3236. return -1;
  3237. } else {
  3238. int truncated = 0;
  3239. const struct mg_request_info *ri = &conn->request_info;
  3240. const char *proto = get_proto_name(conn);
  3241. if (ri->local_uri == NULL) {
  3242. return -1;
  3243. }
  3244. if ((ri->request_uri != NULL)
  3245. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3246. /* The request uri is different from the local uri.
  3247. * This is usually if an absolute URI, including server
  3248. * name has been provided. */
  3249. mg_snprintf(conn,
  3250. &truncated,
  3251. buf,
  3252. buflen,
  3253. "%s://%s",
  3254. proto,
  3255. ri->request_uri);
  3256. if (truncated) {
  3257. return -1;
  3258. }
  3259. return 0;
  3260. } else {
  3261. /* The common case is a relative URI, so we have to
  3262. * construct an absolute URI from server name and port */
  3263. #if defined(USE_IPV6)
  3264. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3265. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3266. : htons(conn->client.lsa.sin.sin_port);
  3267. #else
  3268. int port = htons(conn->client.lsa.sin.sin_port);
  3269. #endif
  3270. int def_port = ri->is_ssl ? 443 : 80;
  3271. int auth_domain_check_enabled =
  3272. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3273. && (!mg_strcasecmp(
  3274. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3275. const char *server_domain =
  3276. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3277. char portstr[16];
  3278. char server_ip[48];
  3279. if (port != def_port) {
  3280. sprintf(portstr, ":%u", (unsigned)port);
  3281. } else {
  3282. portstr[0] = 0;
  3283. }
  3284. if (!auth_domain_check_enabled || !server_domain) {
  3285. sockaddr_to_string(server_ip,
  3286. sizeof(server_ip),
  3287. &conn->client.lsa);
  3288. server_domain = server_ip;
  3289. }
  3290. mg_snprintf(conn,
  3291. &truncated,
  3292. buf,
  3293. buflen,
  3294. "%s://%s%s%s",
  3295. proto,
  3296. server_domain,
  3297. portstr,
  3298. ri->local_uri);
  3299. if (truncated) {
  3300. return -1;
  3301. }
  3302. return 0;
  3303. }
  3304. }
  3305. }
  3306. /* Skip the characters until one of the delimiters characters found.
  3307. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3308. * Advance pointer to buffer to the next word. Return found 0-terminated
  3309. * word.
  3310. * Delimiters can be quoted with quotechar. */
  3311. static char *
  3312. skip_quoted(char **buf,
  3313. const char *delimiters,
  3314. const char *whitespace,
  3315. char quotechar)
  3316. {
  3317. char *p, *begin_word, *end_word, *end_whitespace;
  3318. begin_word = *buf;
  3319. end_word = begin_word + strcspn(begin_word, delimiters);
  3320. /* Check for quotechar */
  3321. if (end_word > begin_word) {
  3322. p = end_word - 1;
  3323. while (*p == quotechar) {
  3324. /* While the delimiter is quoted, look for the next delimiter.
  3325. */
  3326. /* This happens, e.g., in calls from parse_auth_header,
  3327. * if the user name contains a " character. */
  3328. /* If there is anything beyond end_word, copy it. */
  3329. if (*end_word != '\0') {
  3330. size_t end_off = strcspn(end_word + 1, delimiters);
  3331. memmove(p, end_word, end_off + 1);
  3332. p += end_off; /* p must correspond to end_word - 1 */
  3333. end_word += end_off + 1;
  3334. } else {
  3335. *p = '\0';
  3336. break;
  3337. }
  3338. }
  3339. for (p++; p < end_word; p++) {
  3340. *p = '\0';
  3341. }
  3342. }
  3343. if (*end_word == '\0') {
  3344. *buf = end_word;
  3345. } else {
  3346. #if defined(GCC_DIAGNOSTIC)
  3347. /* Disable spurious conversion warning for GCC */
  3348. #pragma GCC diagnostic push
  3349. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3350. #endif /* defined(GCC_DIAGNOSTIC) */
  3351. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3352. #if defined(GCC_DIAGNOSTIC)
  3353. #pragma GCC diagnostic pop
  3354. #endif /* defined(GCC_DIAGNOSTIC) */
  3355. for (p = end_word; p < end_whitespace; p++) {
  3356. *p = '\0';
  3357. }
  3358. *buf = end_whitespace;
  3359. }
  3360. return begin_word;
  3361. }
  3362. /* Return HTTP header value, or NULL if not found. */
  3363. static const char *
  3364. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3365. {
  3366. int i;
  3367. for (i = 0; i < num_hdr; i++) {
  3368. if (!mg_strcasecmp(name, hdr[i].name)) {
  3369. return hdr[i].value;
  3370. }
  3371. }
  3372. return NULL;
  3373. }
  3374. #if defined(USE_WEBSOCKET)
  3375. /* Retrieve requested HTTP header multiple values, and return the number of
  3376. * found occurrences */
  3377. static int
  3378. get_req_headers(const struct mg_request_info *ri,
  3379. const char *name,
  3380. const char **output,
  3381. int output_max_size)
  3382. {
  3383. int i;
  3384. int cnt = 0;
  3385. if (ri) {
  3386. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3387. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3388. output[cnt++] = ri->http_headers[i].value;
  3389. }
  3390. }
  3391. }
  3392. return cnt;
  3393. }
  3394. #endif
  3395. const char *
  3396. mg_get_header(const struct mg_connection *conn, const char *name)
  3397. {
  3398. if (!conn) {
  3399. return NULL;
  3400. }
  3401. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3402. return get_header(conn->request_info.http_headers,
  3403. conn->request_info.num_headers,
  3404. name);
  3405. }
  3406. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3407. return get_header(conn->response_info.http_headers,
  3408. conn->response_info.num_headers,
  3409. name);
  3410. }
  3411. return NULL;
  3412. }
  3413. static const char *
  3414. get_http_version(const struct mg_connection *conn)
  3415. {
  3416. if (!conn) {
  3417. return NULL;
  3418. }
  3419. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3420. return conn->request_info.http_version;
  3421. }
  3422. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3423. return conn->response_info.http_version;
  3424. }
  3425. return NULL;
  3426. }
  3427. /* A helper function for traversing a comma separated list of values.
  3428. * It returns a list pointer shifted to the next value, or NULL if the end
  3429. * of the list found.
  3430. * Value is stored in val vector. If value has form "x=y", then eq_val
  3431. * vector is initialized to point to the "y" part, and val vector length
  3432. * is adjusted to point only to "x". */
  3433. static const char *
  3434. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3435. {
  3436. int end;
  3437. reparse:
  3438. if (val == NULL || list == NULL || *list == '\0') {
  3439. /* End of the list */
  3440. return NULL;
  3441. }
  3442. /* Skip over leading LWS */
  3443. while (*list == ' ' || *list == '\t')
  3444. list++;
  3445. val->ptr = list;
  3446. if ((list = strchr(val->ptr, ',')) != NULL) {
  3447. /* Comma found. Store length and shift the list ptr */
  3448. val->len = ((size_t)(list - val->ptr));
  3449. list++;
  3450. } else {
  3451. /* This value is the last one */
  3452. list = val->ptr + strlen(val->ptr);
  3453. val->len = ((size_t)(list - val->ptr));
  3454. }
  3455. /* Adjust length for trailing LWS */
  3456. end = (int)val->len - 1;
  3457. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3458. end--;
  3459. val->len = (size_t)(end + 1);
  3460. if (val->len == 0) {
  3461. /* Ignore any empty entries. */
  3462. goto reparse;
  3463. }
  3464. if (eq_val != NULL) {
  3465. /* Value has form "x=y", adjust pointers and lengths
  3466. * so that val points to "x", and eq_val points to "y". */
  3467. eq_val->len = 0;
  3468. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3469. if (eq_val->ptr != NULL) {
  3470. eq_val->ptr++; /* Skip over '=' character */
  3471. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3472. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3473. }
  3474. }
  3475. return list;
  3476. }
  3477. /* A helper function for checking if a comma separated list of values
  3478. * contains
  3479. * the given option (case insensitvely).
  3480. * 'header' can be NULL, in which case false is returned. */
  3481. static int
  3482. header_has_option(const char *header, const char *option)
  3483. {
  3484. struct vec opt_vec;
  3485. struct vec eq_vec;
  3486. DEBUG_ASSERT(option != NULL);
  3487. DEBUG_ASSERT(option[0] != '\0');
  3488. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3489. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3490. return 1;
  3491. }
  3492. return 0;
  3493. }
  3494. /* Perform case-insensitive match of string against pattern */
  3495. static ptrdiff_t
  3496. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3497. {
  3498. const char *or_str;
  3499. ptrdiff_t i, j, len, res;
  3500. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3501. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3502. return (res > 0) ? res
  3503. : match_prefix(or_str + 1,
  3504. (size_t)((pattern + pattern_len)
  3505. - (or_str + 1)),
  3506. str);
  3507. }
  3508. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3509. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3510. continue;
  3511. } else if (pattern[i] == '$') {
  3512. return (str[j] == '\0') ? j : -1;
  3513. } else if (pattern[i] == '*') {
  3514. i++;
  3515. if (pattern[i] == '*') {
  3516. i++;
  3517. len = strlen(str + j);
  3518. } else {
  3519. len = strcspn(str + j, "/");
  3520. }
  3521. if (i == (ptrdiff_t)pattern_len) {
  3522. return j + len;
  3523. }
  3524. do {
  3525. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3526. } while (res == -1 && len-- > 0);
  3527. return (res == -1) ? -1 : j + res + len;
  3528. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3529. return -1;
  3530. }
  3531. }
  3532. return (ptrdiff_t)j;
  3533. }
  3534. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3535. * This function must tolerate situations when connection info is not
  3536. * set up, for example if request parsing failed. */
  3537. static int
  3538. should_keep_alive(const struct mg_connection *conn)
  3539. {
  3540. const char *http_version;
  3541. const char *header;
  3542. /* First satisfy needs of the server */
  3543. if ((conn == NULL) || conn->must_close) {
  3544. /* Close, if civetweb framework needs to close */
  3545. return 0;
  3546. }
  3547. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3548. /* Close, if keep alive is not enabled */
  3549. return 0;
  3550. }
  3551. /* Check explicit wish of the client */
  3552. header = mg_get_header(conn, "Connection");
  3553. if (header) {
  3554. /* If there is a connection header from the client, obey */
  3555. if (header_has_option(header, "keep-alive")) {
  3556. return 1;
  3557. }
  3558. return 0;
  3559. }
  3560. /* Use default of the standard */
  3561. http_version = get_http_version(conn);
  3562. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3563. /* HTTP 1.1 default is keep alive */
  3564. return 1;
  3565. }
  3566. /* HTTP 1.0 (and earlier) default is to close the connection */
  3567. return 0;
  3568. }
  3569. static int
  3570. should_decode_url(const struct mg_connection *conn)
  3571. {
  3572. if (!conn || !conn->dom_ctx) {
  3573. return 0;
  3574. }
  3575. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3576. }
  3577. static const char *
  3578. suggest_connection_header(const struct mg_connection *conn)
  3579. {
  3580. return should_keep_alive(conn) ? "keep-alive" : "close";
  3581. }
  3582. static int
  3583. send_no_cache_header(struct mg_connection *conn)
  3584. {
  3585. /* Send all current and obsolete cache opt-out directives. */
  3586. return mg_printf(conn,
  3587. "Cache-Control: no-cache, no-store, "
  3588. "must-revalidate, private, max-age=0\r\n"
  3589. "Pragma: no-cache\r\n"
  3590. "Expires: 0\r\n");
  3591. }
  3592. static int
  3593. send_static_cache_header(struct mg_connection *conn)
  3594. {
  3595. #if !defined(NO_CACHING)
  3596. /* Read the server config to check how long a file may be cached.
  3597. * The configuration is in seconds. */
  3598. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3599. if (max_age <= 0) {
  3600. /* 0 means "do not cache". All values <0 are reserved
  3601. * and may be used differently in the future. */
  3602. /* If a file should not be cached, do not only send
  3603. * max-age=0, but also pragmas and Expires headers. */
  3604. return send_no_cache_header(conn);
  3605. }
  3606. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3607. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3608. /* See also https://www.mnot.net/cache_docs/ */
  3609. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3610. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3611. * leap
  3612. * year to 31622400 seconds. For the moment, we just send whatever has
  3613. * been configured, still the behavior for >1 year should be considered
  3614. * as undefined. */
  3615. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3616. #else /* NO_CACHING */
  3617. return send_no_cache_header(conn);
  3618. #endif /* !NO_CACHING */
  3619. }
  3620. static int
  3621. send_additional_header(struct mg_connection *conn)
  3622. {
  3623. int i = 0;
  3624. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3625. #if !defined(NO_SSL)
  3626. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3627. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3628. if (max_age >= 0) {
  3629. i += mg_printf(conn,
  3630. "Strict-Transport-Security: max-age=%u\r\n",
  3631. (unsigned)max_age);
  3632. }
  3633. }
  3634. #endif
  3635. if (header && header[0]) {
  3636. i += mg_printf(conn, "%s\r\n", header);
  3637. }
  3638. return i;
  3639. }
  3640. static void handle_file_based_request(struct mg_connection *conn,
  3641. const char *path,
  3642. struct mg_file *filep);
  3643. const char *
  3644. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3645. {
  3646. /* See IANA HTTP status code assignment:
  3647. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3648. */
  3649. switch (response_code) {
  3650. /* RFC2616 Section 10.1 - Informational 1xx */
  3651. case 100:
  3652. return "Continue"; /* RFC2616 Section 10.1.1 */
  3653. case 101:
  3654. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3655. case 102:
  3656. return "Processing"; /* RFC2518 Section 10.1 */
  3657. /* RFC2616 Section 10.2 - Successful 2xx */
  3658. case 200:
  3659. return "OK"; /* RFC2616 Section 10.2.1 */
  3660. case 201:
  3661. return "Created"; /* RFC2616 Section 10.2.2 */
  3662. case 202:
  3663. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3664. case 203:
  3665. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3666. case 204:
  3667. return "No Content"; /* RFC2616 Section 10.2.5 */
  3668. case 205:
  3669. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3670. case 206:
  3671. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3672. case 207:
  3673. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3674. */
  3675. case 208:
  3676. return "Already Reported"; /* RFC5842 Section 7.1 */
  3677. case 226:
  3678. return "IM used"; /* RFC3229 Section 10.4.1 */
  3679. /* RFC2616 Section 10.3 - Redirection 3xx */
  3680. case 300:
  3681. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3682. case 301:
  3683. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3684. case 302:
  3685. return "Found"; /* RFC2616 Section 10.3.3 */
  3686. case 303:
  3687. return "See Other"; /* RFC2616 Section 10.3.4 */
  3688. case 304:
  3689. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3690. case 305:
  3691. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3692. case 307:
  3693. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3694. case 308:
  3695. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3696. /* RFC2616 Section 10.4 - Client Error 4xx */
  3697. case 400:
  3698. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3699. case 401:
  3700. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3701. case 402:
  3702. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3703. case 403:
  3704. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3705. case 404:
  3706. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3707. case 405:
  3708. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3709. case 406:
  3710. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3711. case 407:
  3712. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3713. case 408:
  3714. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3715. case 409:
  3716. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3717. case 410:
  3718. return "Gone"; /* RFC2616 Section 10.4.11 */
  3719. case 411:
  3720. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3721. case 412:
  3722. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3723. case 413:
  3724. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3725. case 414:
  3726. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3727. case 415:
  3728. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3729. case 416:
  3730. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3731. */
  3732. case 417:
  3733. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3734. case 421:
  3735. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3736. case 422:
  3737. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3738. * Section 11.2 */
  3739. case 423:
  3740. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3741. case 424:
  3742. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3743. * Section 11.4 */
  3744. case 426:
  3745. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3746. case 428:
  3747. return "Precondition Required"; /* RFC 6585, Section 3 */
  3748. case 429:
  3749. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3750. case 431:
  3751. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3752. case 451:
  3753. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3754. * Section 3 */
  3755. /* RFC2616 Section 10.5 - Server Error 5xx */
  3756. case 500:
  3757. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3758. case 501:
  3759. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3760. case 502:
  3761. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3762. case 503:
  3763. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3764. case 504:
  3765. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3766. case 505:
  3767. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3768. case 506:
  3769. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3770. case 507:
  3771. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3772. * Section 11.5 */
  3773. case 508:
  3774. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3775. case 510:
  3776. return "Not Extended"; /* RFC 2774, Section 7 */
  3777. case 511:
  3778. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3779. /* Other status codes, not shown in the IANA HTTP status code
  3780. * assignment.
  3781. * E.g., "de facto" standards due to common use, ... */
  3782. case 418:
  3783. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3784. case 419:
  3785. return "Authentication Timeout"; /* common use */
  3786. case 420:
  3787. return "Enhance Your Calm"; /* common use */
  3788. case 440:
  3789. return "Login Timeout"; /* common use */
  3790. case 509:
  3791. return "Bandwidth Limit Exceeded"; /* common use */
  3792. default:
  3793. /* This error code is unknown. This should not happen. */
  3794. if (conn) {
  3795. mg_cry_internal(conn,
  3796. "Unknown HTTP response code: %u",
  3797. response_code);
  3798. }
  3799. /* Return at least a category according to RFC 2616 Section 10. */
  3800. if (response_code >= 100 && response_code < 200) {
  3801. /* Unknown informational status code */
  3802. return "Information";
  3803. }
  3804. if (response_code >= 200 && response_code < 300) {
  3805. /* Unknown success code */
  3806. return "Success";
  3807. }
  3808. if (response_code >= 300 && response_code < 400) {
  3809. /* Unknown redirection code */
  3810. return "Redirection";
  3811. }
  3812. if (response_code >= 400 && response_code < 500) {
  3813. /* Unknown request error code */
  3814. return "Client Error";
  3815. }
  3816. if (response_code >= 500 && response_code < 600) {
  3817. /* Unknown server error code */
  3818. return "Server Error";
  3819. }
  3820. /* Response code not even within reasonable range */
  3821. return "";
  3822. }
  3823. }
  3824. static int
  3825. mg_send_http_error_impl(struct mg_connection *conn,
  3826. int status,
  3827. const char *fmt,
  3828. va_list args)
  3829. {
  3830. char errmsg_buf[MG_BUF_LEN];
  3831. char path_buf[PATH_MAX];
  3832. va_list ap;
  3833. int len, i, page_handler_found, scope, truncated, has_body;
  3834. char date[64];
  3835. time_t curtime = time(NULL);
  3836. const char *error_handler = NULL;
  3837. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3838. const char *error_page_file_ext, *tstr;
  3839. int handled_by_callback = 0;
  3840. const char *status_text = mg_get_response_code_text(conn, status);
  3841. if ((conn == NULL) || (fmt == NULL)) {
  3842. return -2;
  3843. }
  3844. /* Set status (for log) */
  3845. conn->status_code = status;
  3846. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3847. has_body = ((status > 199) && (status != 204) && (status != 304));
  3848. /* Prepare message in buf, if required */
  3849. if (has_body
  3850. || (!conn->in_error_handler
  3851. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3852. /* Store error message in errmsg_buf */
  3853. va_copy(ap, args);
  3854. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3855. va_end(ap);
  3856. /* In a debug build, print all html errors */
  3857. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3858. }
  3859. /* If there is a http_error callback, call it.
  3860. * But don't do it recursively, if callback calls mg_send_http_error again.
  3861. */
  3862. if (!conn->in_error_handler
  3863. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3864. /* Mark in_error_handler to avoid recursion and call user callback. */
  3865. conn->in_error_handler = 1;
  3866. handled_by_callback =
  3867. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3868. == 0);
  3869. conn->in_error_handler = 0;
  3870. }
  3871. if (!handled_by_callback) {
  3872. /* Check for recursion */
  3873. if (conn->in_error_handler) {
  3874. DEBUG_TRACE(
  3875. "Recursion when handling error %u - fall back to default",
  3876. status);
  3877. } else {
  3878. /* Send user defined error pages, if defined */
  3879. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3880. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3881. page_handler_found = 0;
  3882. if (error_handler != NULL) {
  3883. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3884. switch (scope) {
  3885. case 1: /* Handler for specific error, e.g. 404 error */
  3886. mg_snprintf(conn,
  3887. &truncated,
  3888. path_buf,
  3889. sizeof(path_buf) - 32,
  3890. "%serror%03u.",
  3891. error_handler,
  3892. status);
  3893. break;
  3894. case 2: /* Handler for error group, e.g., 5xx error
  3895. * handler
  3896. * for all server errors (500-599) */
  3897. mg_snprintf(conn,
  3898. &truncated,
  3899. path_buf,
  3900. sizeof(path_buf) - 32,
  3901. "%serror%01uxx.",
  3902. error_handler,
  3903. status / 100);
  3904. break;
  3905. default: /* Handler for all errors */
  3906. mg_snprintf(conn,
  3907. &truncated,
  3908. path_buf,
  3909. sizeof(path_buf) - 32,
  3910. "%serror.",
  3911. error_handler);
  3912. break;
  3913. }
  3914. /* String truncation in buf may only occur if
  3915. * error_handler is too long. This string is
  3916. * from the config, not from a client. */
  3917. (void)truncated;
  3918. len = (int)strlen(path_buf);
  3919. tstr = strchr(error_page_file_ext, '.');
  3920. while (tstr) {
  3921. for (i = 1;
  3922. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3923. i++) {
  3924. /* buffer overrun is not possible here, since
  3925. * (i < 32) && (len < sizeof(path_buf) - 32)
  3926. * ==> (i + len) < sizeof(path_buf) */
  3927. path_buf[len + i - 1] = tstr[i];
  3928. }
  3929. /* buffer overrun is not possible here, since
  3930. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3931. * ==> (i + len) <= sizeof(path_buf) */
  3932. path_buf[len + i - 1] = 0;
  3933. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3934. DEBUG_TRACE("Check error page %s - found",
  3935. path_buf);
  3936. page_handler_found = 1;
  3937. break;
  3938. }
  3939. DEBUG_TRACE("Check error page %s - not found",
  3940. path_buf);
  3941. tstr = strchr(tstr + i, '.');
  3942. }
  3943. }
  3944. }
  3945. if (page_handler_found) {
  3946. conn->in_error_handler = 1;
  3947. handle_file_based_request(conn, path_buf, &error_page_file);
  3948. conn->in_error_handler = 0;
  3949. return 0;
  3950. }
  3951. }
  3952. /* No custom error page. Send default error page. */
  3953. gmt_time_string(date, sizeof(date), &curtime);
  3954. conn->must_close = 1;
  3955. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3956. send_no_cache_header(conn);
  3957. send_additional_header(conn);
  3958. if (has_body) {
  3959. mg_printf(conn,
  3960. "%s",
  3961. "Content-Type: text/plain; charset=utf-8\r\n");
  3962. }
  3963. mg_printf(conn,
  3964. "Date: %s\r\n"
  3965. "Connection: close\r\n\r\n",
  3966. date);
  3967. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  3968. if (has_body) {
  3969. /* For other errors, send a generic error message. */
  3970. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3971. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3972. } else {
  3973. /* No body allowed. Close the connection. */
  3974. DEBUG_TRACE("Error %i", status);
  3975. }
  3976. }
  3977. return 0;
  3978. }
  3979. int
  3980. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3981. {
  3982. va_list ap;
  3983. int ret;
  3984. va_start(ap, fmt);
  3985. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  3986. va_end(ap);
  3987. return ret;
  3988. }
  3989. int
  3990. mg_send_http_ok(struct mg_connection *conn,
  3991. const char *mime_type,
  3992. long long content_length)
  3993. {
  3994. char date[64];
  3995. time_t curtime = time(NULL);
  3996. if ((mime_type == NULL) || (*mime_type == 0)) {
  3997. /* Parameter error */
  3998. return -2;
  3999. }
  4000. gmt_time_string(date, sizeof(date), &curtime);
  4001. mg_printf(conn,
  4002. "HTTP/1.1 200 OK\r\n"
  4003. "Content-Type: %s\r\n"
  4004. "Date: %s\r\n"
  4005. "Connection: %s\r\n",
  4006. mime_type,
  4007. date,
  4008. suggest_connection_header(conn));
  4009. send_no_cache_header(conn);
  4010. send_additional_header(conn);
  4011. if (content_length < 0) {
  4012. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4013. } else {
  4014. mg_printf(conn,
  4015. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4016. (uint64_t)content_length);
  4017. }
  4018. return 0;
  4019. }
  4020. int
  4021. mg_send_http_redirect(struct mg_connection *conn,
  4022. const char *target_url,
  4023. int redirect_code)
  4024. {
  4025. /* Send a 30x redirect response.
  4026. *
  4027. * Redirect types (status codes):
  4028. *
  4029. * Status | Perm/Temp | Method | Version
  4030. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4031. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4032. * 303 | temporary | always use GET | HTTP/1.1
  4033. * 307 | temporary | always keep method | HTTP/1.1
  4034. * 308 | permanent | always keep method | HTTP/1.1
  4035. */
  4036. const char *redirect_text;
  4037. int ret;
  4038. size_t content_len = 0;
  4039. char reply[MG_BUF_LEN];
  4040. /* In case redirect_code=0, use 307. */
  4041. if (redirect_code == 0) {
  4042. redirect_code = 307;
  4043. }
  4044. /* In case redirect_code is none of the above, return error. */
  4045. if ((redirect_code != 301) && (redirect_code != 302)
  4046. && (redirect_code != 303) && (redirect_code != 307)
  4047. && (redirect_code != 308)) {
  4048. /* Parameter error */
  4049. return -2;
  4050. }
  4051. /* Get proper text for response code */
  4052. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4053. /* If target_url is not defined, redirect to "/". */
  4054. if ((target_url == NULL) || (*target_url == 0)) {
  4055. target_url = "/";
  4056. }
  4057. #if defined(MG_SEND_REDIRECT_BODY)
  4058. /* TODO: condition name? */
  4059. /* Prepare a response body with a hyperlink.
  4060. *
  4061. * According to RFC2616 (and RFC1945 before):
  4062. * Unless the request method was HEAD, the entity of the
  4063. * response SHOULD contain a short hypertext note with a hyperlink to
  4064. * the new URI(s).
  4065. *
  4066. * However, this response body is not useful in M2M communication.
  4067. * Probably the original reason in the RFC was, clients not supporting
  4068. * a 30x HTTP redirect could still show the HTML page and let the user
  4069. * press the link. Since current browsers support 30x HTTP, the additional
  4070. * HTML body does not seem to make sense anymore.
  4071. *
  4072. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4073. * but it only notes:
  4074. * The server's response payload usually contains a short
  4075. * hypertext note with a hyperlink to the new URI(s).
  4076. *
  4077. * Deactivated by default. If you need the 30x body, set the define.
  4078. */
  4079. mg_snprintf(
  4080. conn,
  4081. NULL /* ignore truncation */,
  4082. reply,
  4083. sizeof(reply),
  4084. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4085. redirect_text,
  4086. target_url,
  4087. target_url);
  4088. content_len = strlen(reply);
  4089. #else
  4090. reply[0] = 0;
  4091. #endif
  4092. /* Do not send any additional header. For all other options,
  4093. * including caching, there are suitable defaults. */
  4094. ret = mg_printf(conn,
  4095. "HTTP/1.1 %i %s\r\n"
  4096. "Location: %s\r\n"
  4097. "Content-Length: %u\r\n"
  4098. "Connection: %s\r\n\r\n",
  4099. redirect_code,
  4100. redirect_text,
  4101. target_url,
  4102. (unsigned int)content_len,
  4103. suggest_connection_header(conn));
  4104. /* Send response body */
  4105. if (ret > 0) {
  4106. /* ... unless it is a HEAD request */
  4107. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4108. ret = mg_write(conn, reply, content_len);
  4109. }
  4110. }
  4111. return (ret > 0) ? ret : -1;
  4112. }
  4113. #if defined(_WIN32)
  4114. /* Create substitutes for POSIX functions in Win32. */
  4115. #if defined(GCC_DIAGNOSTIC)
  4116. /* Show no warning in case system functions are not used. */
  4117. #pragma GCC diagnostic push
  4118. #pragma GCC diagnostic ignored "-Wunused-function"
  4119. #endif
  4120. FUNCTION_MAY_BE_UNUSED
  4121. static int
  4122. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4123. {
  4124. (void)unused;
  4125. *mutex = CreateMutex(NULL, FALSE, NULL);
  4126. return (*mutex == NULL) ? -1 : 0;
  4127. }
  4128. FUNCTION_MAY_BE_UNUSED
  4129. static int
  4130. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4131. {
  4132. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  4133. }
  4134. FUNCTION_MAY_BE_UNUSED
  4135. static int
  4136. pthread_mutex_lock(pthread_mutex_t *mutex)
  4137. {
  4138. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  4139. : -1;
  4140. }
  4141. #if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS)
  4142. FUNCTION_MAY_BE_UNUSED
  4143. static int
  4144. pthread_mutex_trylock(pthread_mutex_t *mutex)
  4145. {
  4146. switch (WaitForSingleObject(*mutex, 0)) {
  4147. case WAIT_OBJECT_0:
  4148. return 0;
  4149. case WAIT_TIMEOUT:
  4150. return -2; /* EBUSY */
  4151. }
  4152. return -1;
  4153. }
  4154. #endif
  4155. FUNCTION_MAY_BE_UNUSED
  4156. static int
  4157. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4158. {
  4159. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  4160. }
  4161. FUNCTION_MAY_BE_UNUSED
  4162. static int
  4163. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4164. {
  4165. (void)unused;
  4166. InitializeCriticalSection(&cv->threadIdSec);
  4167. cv->waiting_thread = NULL;
  4168. return 0;
  4169. }
  4170. FUNCTION_MAY_BE_UNUSED
  4171. static int
  4172. pthread_cond_timedwait(pthread_cond_t *cv,
  4173. pthread_mutex_t *mutex,
  4174. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4175. {
  4176. struct mg_workerTLS **ptls,
  4177. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4178. int ok;
  4179. int64_t nsnow, nswaitabs, nswaitrel;
  4180. DWORD mswaitrel;
  4181. EnterCriticalSection(&cv->threadIdSec);
  4182. /* Add this thread to cv's waiting list */
  4183. ptls = &cv->waiting_thread;
  4184. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4185. ;
  4186. tls->next_waiting_thread = NULL;
  4187. *ptls = tls;
  4188. LeaveCriticalSection(&cv->threadIdSec);
  4189. if (abstime) {
  4190. nsnow = mg_get_current_time_ns();
  4191. nswaitabs =
  4192. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4193. nswaitrel = nswaitabs - nsnow;
  4194. if (nswaitrel < 0) {
  4195. nswaitrel = 0;
  4196. }
  4197. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4198. } else {
  4199. mswaitrel = (DWORD)INFINITE;
  4200. }
  4201. pthread_mutex_unlock(mutex);
  4202. ok = (WAIT_OBJECT_0
  4203. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4204. if (!ok) {
  4205. ok = 1;
  4206. EnterCriticalSection(&cv->threadIdSec);
  4207. ptls = &cv->waiting_thread;
  4208. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4209. if (*ptls == tls) {
  4210. *ptls = tls->next_waiting_thread;
  4211. ok = 0;
  4212. break;
  4213. }
  4214. }
  4215. LeaveCriticalSection(&cv->threadIdSec);
  4216. if (ok) {
  4217. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4218. (DWORD)INFINITE);
  4219. }
  4220. }
  4221. /* This thread has been removed from cv's waiting list */
  4222. pthread_mutex_lock(mutex);
  4223. return ok ? 0 : -1;
  4224. }
  4225. FUNCTION_MAY_BE_UNUSED
  4226. static int
  4227. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4228. {
  4229. return pthread_cond_timedwait(cv, mutex, NULL);
  4230. }
  4231. FUNCTION_MAY_BE_UNUSED
  4232. static int
  4233. pthread_cond_signal(pthread_cond_t *cv)
  4234. {
  4235. HANDLE wkup = NULL;
  4236. BOOL ok = FALSE;
  4237. EnterCriticalSection(&cv->threadIdSec);
  4238. if (cv->waiting_thread) {
  4239. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4240. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4241. ok = SetEvent(wkup);
  4242. DEBUG_ASSERT(ok);
  4243. }
  4244. LeaveCriticalSection(&cv->threadIdSec);
  4245. return ok ? 0 : 1;
  4246. }
  4247. FUNCTION_MAY_BE_UNUSED
  4248. static int
  4249. pthread_cond_broadcast(pthread_cond_t *cv)
  4250. {
  4251. EnterCriticalSection(&cv->threadIdSec);
  4252. while (cv->waiting_thread) {
  4253. pthread_cond_signal(cv);
  4254. }
  4255. LeaveCriticalSection(&cv->threadIdSec);
  4256. return 0;
  4257. }
  4258. FUNCTION_MAY_BE_UNUSED
  4259. static int
  4260. pthread_cond_destroy(pthread_cond_t *cv)
  4261. {
  4262. EnterCriticalSection(&cv->threadIdSec);
  4263. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4264. LeaveCriticalSection(&cv->threadIdSec);
  4265. DeleteCriticalSection(&cv->threadIdSec);
  4266. return 0;
  4267. }
  4268. #if defined(ALTERNATIVE_QUEUE)
  4269. FUNCTION_MAY_BE_UNUSED
  4270. static void *
  4271. event_create(void)
  4272. {
  4273. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4274. }
  4275. FUNCTION_MAY_BE_UNUSED
  4276. static int
  4277. event_wait(void *eventhdl)
  4278. {
  4279. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4280. return (res == WAIT_OBJECT_0);
  4281. }
  4282. FUNCTION_MAY_BE_UNUSED
  4283. static int
  4284. event_signal(void *eventhdl)
  4285. {
  4286. return (int)SetEvent((HANDLE)eventhdl);
  4287. }
  4288. FUNCTION_MAY_BE_UNUSED
  4289. static void
  4290. event_destroy(void *eventhdl)
  4291. {
  4292. CloseHandle((HANDLE)eventhdl);
  4293. }
  4294. #endif
  4295. #if defined(GCC_DIAGNOSTIC)
  4296. /* Enable unused function warning again */
  4297. #pragma GCC diagnostic pop
  4298. #endif
  4299. /* For Windows, change all slashes to backslashes in path names. */
  4300. static void
  4301. change_slashes_to_backslashes(char *path)
  4302. {
  4303. int i;
  4304. for (i = 0; path[i] != '\0'; i++) {
  4305. if (path[i] == '/') {
  4306. path[i] = '\\';
  4307. }
  4308. /* remove double backslash (check i > 0 to preserve UNC paths,
  4309. * like \\server\file.txt) */
  4310. if ((path[i] == '\\') && (i > 0)) {
  4311. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4312. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4313. }
  4314. }
  4315. }
  4316. }
  4317. static int
  4318. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4319. {
  4320. int diff;
  4321. do {
  4322. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4323. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4324. s1++;
  4325. s2++;
  4326. } while ((diff == 0) && (s1[-1] != L'\0'));
  4327. return diff;
  4328. }
  4329. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4330. * wbuf and wbuf_len is a target buffer and its length. */
  4331. static void
  4332. path_to_unicode(const struct mg_connection *conn,
  4333. const char *path,
  4334. wchar_t *wbuf,
  4335. size_t wbuf_len)
  4336. {
  4337. char buf[PATH_MAX], buf2[PATH_MAX];
  4338. wchar_t wbuf2[W_PATH_MAX + 1];
  4339. DWORD long_len, err;
  4340. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4341. mg_strlcpy(buf, path, sizeof(buf));
  4342. change_slashes_to_backslashes(buf);
  4343. /* Convert to Unicode and back. If doubly-converted string does not
  4344. * match the original, something is fishy, reject. */
  4345. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4346. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4347. WideCharToMultiByte(
  4348. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4349. if (strcmp(buf, buf2) != 0) {
  4350. wbuf[0] = L'\0';
  4351. }
  4352. /* Windows file systems are not case sensitive, but you can still use
  4353. * uppercase and lowercase letters (on all modern file systems).
  4354. * The server can check if the URI uses the same upper/lowercase
  4355. * letters an the file system, effectively making Windows servers
  4356. * case sensitive (like Linux servers are). It is still not possible
  4357. * to use two files with the same name in different cases on Windows
  4358. * (like /a and /A) - this would be possible in Linux.
  4359. * As a default, Windows is not case sensitive, but the case sensitive
  4360. * file name check can be activated by an additional configuration. */
  4361. if (conn) {
  4362. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4363. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4364. "yes")) {
  4365. /* Use case sensitive compare function */
  4366. fcompare = wcscmp;
  4367. }
  4368. }
  4369. (void)conn; /* conn is currently unused */
  4370. #if !defined(_WIN32_WCE)
  4371. /* Only accept a full file path, not a Windows short (8.3) path. */
  4372. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4373. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4374. if (long_len == 0) {
  4375. err = GetLastError();
  4376. if (err == ERROR_FILE_NOT_FOUND) {
  4377. /* File does not exist. This is not always a problem here. */
  4378. return;
  4379. }
  4380. }
  4381. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4382. /* Short name is used. */
  4383. wbuf[0] = L'\0';
  4384. }
  4385. #else
  4386. (void)long_len;
  4387. (void)wbuf2;
  4388. (void)err;
  4389. if (strchr(path, '~')) {
  4390. wbuf[0] = L'\0';
  4391. }
  4392. #endif
  4393. }
  4394. static int
  4395. mg_stat(const struct mg_connection *conn,
  4396. const char *path,
  4397. struct mg_file_stat *filep)
  4398. {
  4399. wchar_t wbuf[W_PATH_MAX];
  4400. WIN32_FILE_ATTRIBUTE_DATA info;
  4401. time_t creation_time;
  4402. size_t len;
  4403. if (!filep) {
  4404. return 0;
  4405. }
  4406. memset(filep, 0, sizeof(*filep));
  4407. if (conn && is_file_in_memory(conn, path)) {
  4408. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4409. * memset */
  4410. /* Quick fix (for 1.9.x): */
  4411. /* mg_stat must fill all fields, also for files in memory */
  4412. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4413. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4414. filep->size = tmp_file.stat.size;
  4415. filep->location = 2;
  4416. /* TODO: for 1.10: restructure how files in memory are handled */
  4417. /* The "file in memory" feature is a candidate for deletion.
  4418. * Please join the discussion at
  4419. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4420. */
  4421. filep->last_modified = time(NULL); /* TODO */
  4422. /* last_modified = now ... assumes the file may change during
  4423. * runtime,
  4424. * so every mg_fopen call may return different data */
  4425. /* last_modified = conn->phys_ctx.start_time;
  4426. * May be used it the data does not change during runtime. This
  4427. * allows
  4428. * browser caching. Since we do not know, we have to assume the file
  4429. * in memory may change. */
  4430. return 1;
  4431. }
  4432. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4433. /* Windows happily opens files with some garbage at the end of file name.
  4434. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4435. * "a.cgi", despite one would expect an error back. */
  4436. len = strlen(path);
  4437. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4438. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4439. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4440. filep->last_modified =
  4441. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4442. info.ftLastWriteTime.dwHighDateTime);
  4443. /* On Windows, the file creation time can be higher than the
  4444. * modification time, e.g. when a file is copied.
  4445. * Since the Last-Modified timestamp is used for caching
  4446. * it should be based on the most recent timestamp. */
  4447. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4448. info.ftCreationTime.dwHighDateTime);
  4449. if (creation_time > filep->last_modified) {
  4450. filep->last_modified = creation_time;
  4451. }
  4452. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4453. return 1;
  4454. }
  4455. return 0;
  4456. }
  4457. static int
  4458. mg_remove(const struct mg_connection *conn, const char *path)
  4459. {
  4460. wchar_t wbuf[W_PATH_MAX];
  4461. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4462. return DeleteFileW(wbuf) ? 0 : -1;
  4463. }
  4464. static int
  4465. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4466. {
  4467. wchar_t wbuf[W_PATH_MAX];
  4468. (void)mode;
  4469. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4470. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4471. }
  4472. /* Create substitutes for POSIX functions in Win32. */
  4473. #if defined(GCC_DIAGNOSTIC)
  4474. /* Show no warning in case system functions are not used. */
  4475. #pragma GCC diagnostic push
  4476. #pragma GCC diagnostic ignored "-Wunused-function"
  4477. #endif
  4478. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4479. FUNCTION_MAY_BE_UNUSED
  4480. static DIR *
  4481. mg_opendir(const struct mg_connection *conn, const char *name)
  4482. {
  4483. DIR *dir = NULL;
  4484. wchar_t wpath[W_PATH_MAX];
  4485. DWORD attrs;
  4486. if (name == NULL) {
  4487. SetLastError(ERROR_BAD_ARGUMENTS);
  4488. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4489. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4490. } else {
  4491. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4492. attrs = GetFileAttributesW(wpath);
  4493. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4494. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4495. (void)wcscat(wpath, L"\\*");
  4496. dir->handle = FindFirstFileW(wpath, &dir->info);
  4497. dir->result.d_name[0] = '\0';
  4498. } else {
  4499. mg_free(dir);
  4500. dir = NULL;
  4501. }
  4502. }
  4503. return dir;
  4504. }
  4505. FUNCTION_MAY_BE_UNUSED
  4506. static int
  4507. mg_closedir(DIR *dir)
  4508. {
  4509. int result = 0;
  4510. if (dir != NULL) {
  4511. if (dir->handle != INVALID_HANDLE_VALUE)
  4512. result = FindClose(dir->handle) ? 0 : -1;
  4513. mg_free(dir);
  4514. } else {
  4515. result = -1;
  4516. SetLastError(ERROR_BAD_ARGUMENTS);
  4517. }
  4518. return result;
  4519. }
  4520. FUNCTION_MAY_BE_UNUSED
  4521. static struct dirent *
  4522. mg_readdir(DIR *dir)
  4523. {
  4524. struct dirent *result = 0;
  4525. if (dir) {
  4526. if (dir->handle != INVALID_HANDLE_VALUE) {
  4527. result = &dir->result;
  4528. (void)WideCharToMultiByte(CP_UTF8,
  4529. 0,
  4530. dir->info.cFileName,
  4531. -1,
  4532. result->d_name,
  4533. sizeof(result->d_name),
  4534. NULL,
  4535. NULL);
  4536. if (!FindNextFileW(dir->handle, &dir->info)) {
  4537. (void)FindClose(dir->handle);
  4538. dir->handle = INVALID_HANDLE_VALUE;
  4539. }
  4540. } else {
  4541. SetLastError(ERROR_FILE_NOT_FOUND);
  4542. }
  4543. } else {
  4544. SetLastError(ERROR_BAD_ARGUMENTS);
  4545. }
  4546. return result;
  4547. }
  4548. #if !defined(HAVE_POLL)
  4549. #undef POLLIN
  4550. #undef POLLPRI
  4551. #undef POLLOUT
  4552. #define POLLIN (1) /* Data ready - read will not block. */
  4553. #define POLLPRI (2) /* Priority data ready. */
  4554. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4555. FUNCTION_MAY_BE_UNUSED
  4556. static int
  4557. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4558. {
  4559. struct timeval tv;
  4560. fd_set rset;
  4561. fd_set wset;
  4562. unsigned int i;
  4563. int result;
  4564. SOCKET maxfd = 0;
  4565. memset(&tv, 0, sizeof(tv));
  4566. tv.tv_sec = milliseconds / 1000;
  4567. tv.tv_usec = (milliseconds % 1000) * 1000;
  4568. FD_ZERO(&rset);
  4569. FD_ZERO(&wset);
  4570. for (i = 0; i < n; i++) {
  4571. if (pfd[i].events & POLLIN) {
  4572. FD_SET(pfd[i].fd, &rset);
  4573. }
  4574. if (pfd[i].events & POLLOUT) {
  4575. FD_SET(pfd[i].fd, &wset);
  4576. }
  4577. pfd[i].revents = 0;
  4578. if (pfd[i].fd > maxfd) {
  4579. maxfd = pfd[i].fd;
  4580. }
  4581. }
  4582. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4583. for (i = 0; i < n; i++) {
  4584. if (FD_ISSET(pfd[i].fd, &rset)) {
  4585. pfd[i].revents |= POLLIN;
  4586. }
  4587. if (FD_ISSET(pfd[i].fd, &wset)) {
  4588. pfd[i].revents |= POLLOUT;
  4589. }
  4590. }
  4591. }
  4592. /* We should subtract the time used in select from remaining
  4593. * "milliseconds", in particular if called from mg_poll with a
  4594. * timeout quantum.
  4595. * Unfortunately, the remaining time is not stored in "tv" in all
  4596. * implementations, so the result in "tv" must be considered undefined.
  4597. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4598. return result;
  4599. }
  4600. #endif /* HAVE_POLL */
  4601. #if defined(GCC_DIAGNOSTIC)
  4602. /* Enable unused function warning again */
  4603. #pragma GCC diagnostic pop
  4604. #endif
  4605. static void
  4606. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4607. {
  4608. (void)conn; /* Unused. */
  4609. #if defined(_WIN32_WCE)
  4610. (void)sock;
  4611. #else
  4612. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4613. #endif
  4614. }
  4615. int
  4616. mg_start_thread(mg_thread_func_t f, void *p)
  4617. {
  4618. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4619. /* Compile-time option to control stack size, e.g.
  4620. * -DUSE_STACK_SIZE=16384
  4621. */
  4622. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4623. == ((uintptr_t)(-1L)))
  4624. ? -1
  4625. : 0);
  4626. #else
  4627. return (
  4628. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4629. ? -1
  4630. : 0);
  4631. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4632. }
  4633. /* Start a thread storing the thread context. */
  4634. static int
  4635. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4636. void *p,
  4637. pthread_t *threadidptr)
  4638. {
  4639. uintptr_t uip;
  4640. HANDLE threadhandle;
  4641. int result = -1;
  4642. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4643. threadhandle = (HANDLE)uip;
  4644. if ((uip != 0) && (threadidptr != NULL)) {
  4645. *threadidptr = threadhandle;
  4646. result = 0;
  4647. }
  4648. return result;
  4649. }
  4650. /* Wait for a thread to finish. */
  4651. static int
  4652. mg_join_thread(pthread_t threadid)
  4653. {
  4654. int result;
  4655. DWORD dwevent;
  4656. result = -1;
  4657. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4658. if (dwevent == WAIT_FAILED) {
  4659. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4660. } else {
  4661. if (dwevent == WAIT_OBJECT_0) {
  4662. CloseHandle(threadid);
  4663. result = 0;
  4664. }
  4665. }
  4666. return result;
  4667. }
  4668. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4669. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4670. /* Create substitutes for POSIX functions in Win32. */
  4671. #if defined(GCC_DIAGNOSTIC)
  4672. /* Show no warning in case system functions are not used. */
  4673. #pragma GCC diagnostic push
  4674. #pragma GCC diagnostic ignored "-Wunused-function"
  4675. #endif
  4676. FUNCTION_MAY_BE_UNUSED
  4677. static HANDLE
  4678. dlopen(const char *dll_name, int flags)
  4679. {
  4680. wchar_t wbuf[W_PATH_MAX];
  4681. (void)flags;
  4682. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4683. return LoadLibraryW(wbuf);
  4684. }
  4685. FUNCTION_MAY_BE_UNUSED
  4686. static int
  4687. dlclose(void *handle)
  4688. {
  4689. int result;
  4690. if (FreeLibrary((HMODULE)handle) != 0) {
  4691. result = 0;
  4692. } else {
  4693. result = -1;
  4694. }
  4695. return result;
  4696. }
  4697. #if defined(GCC_DIAGNOSTIC)
  4698. /* Enable unused function warning again */
  4699. #pragma GCC diagnostic pop
  4700. #endif
  4701. #endif
  4702. #if !defined(NO_CGI)
  4703. #define SIGKILL (0)
  4704. static int
  4705. kill(pid_t pid, int sig_num)
  4706. {
  4707. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4708. (void)CloseHandle((HANDLE)pid);
  4709. return 0;
  4710. }
  4711. #if !defined(WNOHANG)
  4712. #define WNOHANG (1)
  4713. #endif
  4714. static pid_t
  4715. waitpid(pid_t pid, int *status, int flags)
  4716. {
  4717. DWORD timeout = INFINITE;
  4718. DWORD waitres;
  4719. (void)status; /* Currently not used by any client here */
  4720. if ((flags | WNOHANG) == WNOHANG) {
  4721. timeout = 0;
  4722. }
  4723. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4724. if (waitres == WAIT_OBJECT_0) {
  4725. return pid;
  4726. }
  4727. if (waitres == WAIT_TIMEOUT) {
  4728. return 0;
  4729. }
  4730. return (pid_t)-1;
  4731. }
  4732. static void
  4733. trim_trailing_whitespaces(char *s)
  4734. {
  4735. char *e = s + strlen(s);
  4736. while ((e > s) && isspace((unsigned char)e[-1])) {
  4737. *(--e) = '\0';
  4738. }
  4739. }
  4740. static pid_t
  4741. spawn_process(struct mg_connection *conn,
  4742. const char *prog,
  4743. char *envblk,
  4744. char *envp[],
  4745. int fdin[2],
  4746. int fdout[2],
  4747. int fderr[2],
  4748. const char *dir)
  4749. {
  4750. HANDLE me;
  4751. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4752. cmdline[PATH_MAX], buf[PATH_MAX];
  4753. int truncated;
  4754. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4755. STARTUPINFOA si;
  4756. PROCESS_INFORMATION pi = {0};
  4757. (void)envp;
  4758. memset(&si, 0, sizeof(si));
  4759. si.cb = sizeof(si);
  4760. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4761. si.wShowWindow = SW_HIDE;
  4762. me = GetCurrentProcess();
  4763. DuplicateHandle(me,
  4764. (HANDLE)_get_osfhandle(fdin[0]),
  4765. me,
  4766. &si.hStdInput,
  4767. 0,
  4768. TRUE,
  4769. DUPLICATE_SAME_ACCESS);
  4770. DuplicateHandle(me,
  4771. (HANDLE)_get_osfhandle(fdout[1]),
  4772. me,
  4773. &si.hStdOutput,
  4774. 0,
  4775. TRUE,
  4776. DUPLICATE_SAME_ACCESS);
  4777. DuplicateHandle(me,
  4778. (HANDLE)_get_osfhandle(fderr[1]),
  4779. me,
  4780. &si.hStdError,
  4781. 0,
  4782. TRUE,
  4783. DUPLICATE_SAME_ACCESS);
  4784. /* Mark handles that should not be inherited. See
  4785. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4786. */
  4787. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4788. HANDLE_FLAG_INHERIT,
  4789. 0);
  4790. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4791. HANDLE_FLAG_INHERIT,
  4792. 0);
  4793. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4794. HANDLE_FLAG_INHERIT,
  4795. 0);
  4796. /* If CGI file is a script, try to read the interpreter line */
  4797. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4798. if (interp == NULL) {
  4799. buf[0] = buf[1] = '\0';
  4800. /* Read the first line of the script into the buffer */
  4801. mg_snprintf(
  4802. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4803. if (truncated) {
  4804. pi.hProcess = (pid_t)-1;
  4805. goto spawn_cleanup;
  4806. }
  4807. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4808. #if defined(MG_USE_OPEN_FILE)
  4809. p = (char *)file.access.membuf;
  4810. #else
  4811. p = (char *)NULL;
  4812. #endif
  4813. mg_fgets(buf, sizeof(buf), &file, &p);
  4814. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4815. buf[sizeof(buf) - 1] = '\0';
  4816. }
  4817. if ((buf[0] == '#') && (buf[1] == '!')) {
  4818. trim_trailing_whitespaces(buf + 2);
  4819. } else {
  4820. buf[2] = '\0';
  4821. }
  4822. interp = buf + 2;
  4823. }
  4824. if (interp[0] != '\0') {
  4825. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4826. interp = full_interp;
  4827. }
  4828. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4829. if (interp[0] != '\0') {
  4830. mg_snprintf(conn,
  4831. &truncated,
  4832. cmdline,
  4833. sizeof(cmdline),
  4834. "\"%s\" \"%s\\%s\"",
  4835. interp,
  4836. full_dir,
  4837. prog);
  4838. } else {
  4839. mg_snprintf(conn,
  4840. &truncated,
  4841. cmdline,
  4842. sizeof(cmdline),
  4843. "\"%s\\%s\"",
  4844. full_dir,
  4845. prog);
  4846. }
  4847. if (truncated) {
  4848. pi.hProcess = (pid_t)-1;
  4849. goto spawn_cleanup;
  4850. }
  4851. DEBUG_TRACE("Running [%s]", cmdline);
  4852. if (CreateProcessA(NULL,
  4853. cmdline,
  4854. NULL,
  4855. NULL,
  4856. TRUE,
  4857. CREATE_NEW_PROCESS_GROUP,
  4858. envblk,
  4859. NULL,
  4860. &si,
  4861. &pi)
  4862. == 0) {
  4863. mg_cry_internal(
  4864. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4865. pi.hProcess = (pid_t)-1;
  4866. /* goto spawn_cleanup; */
  4867. }
  4868. spawn_cleanup:
  4869. (void)CloseHandle(si.hStdOutput);
  4870. (void)CloseHandle(si.hStdError);
  4871. (void)CloseHandle(si.hStdInput);
  4872. if (pi.hThread != NULL) {
  4873. (void)CloseHandle(pi.hThread);
  4874. }
  4875. return (pid_t)pi.hProcess;
  4876. }
  4877. #endif /* !NO_CGI */
  4878. static int
  4879. set_blocking_mode(SOCKET sock)
  4880. {
  4881. unsigned long non_blocking = 0;
  4882. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4883. }
  4884. static int
  4885. set_non_blocking_mode(SOCKET sock)
  4886. {
  4887. unsigned long non_blocking = 1;
  4888. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4889. }
  4890. #else
  4891. static int
  4892. mg_stat(const struct mg_connection *conn,
  4893. const char *path,
  4894. struct mg_file_stat *filep)
  4895. {
  4896. struct stat st;
  4897. if (!filep) {
  4898. return 0;
  4899. }
  4900. memset(filep, 0, sizeof(*filep));
  4901. if (conn && is_file_in_memory(conn, path)) {
  4902. /* Quick fix (for 1.9.x): */
  4903. /* mg_stat must fill all fields, also for files in memory */
  4904. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4905. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4906. filep->size = tmp_file.stat.size;
  4907. filep->last_modified = time(NULL);
  4908. filep->location = 2;
  4909. /* TODO: remove legacy "files in memory" feature */
  4910. return 1;
  4911. }
  4912. if (0 == stat(path, &st)) {
  4913. filep->size = (uint64_t)(st.st_size);
  4914. filep->last_modified = st.st_mtime;
  4915. filep->is_directory = S_ISDIR(st.st_mode);
  4916. return 1;
  4917. }
  4918. return 0;
  4919. }
  4920. static void
  4921. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4922. {
  4923. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4924. if (conn) {
  4925. mg_cry_internal(conn,
  4926. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4927. __func__,
  4928. strerror(ERRNO));
  4929. }
  4930. }
  4931. }
  4932. int
  4933. mg_start_thread(mg_thread_func_t func, void *param)
  4934. {
  4935. pthread_t thread_id;
  4936. pthread_attr_t attr;
  4937. int result;
  4938. (void)pthread_attr_init(&attr);
  4939. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4940. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4941. /* Compile-time option to control stack size,
  4942. * e.g. -DUSE_STACK_SIZE=16384 */
  4943. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4944. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4945. result = pthread_create(&thread_id, &attr, func, param);
  4946. pthread_attr_destroy(&attr);
  4947. return result;
  4948. }
  4949. /* Start a thread storing the thread context. */
  4950. static int
  4951. mg_start_thread_with_id(mg_thread_func_t func,
  4952. void *param,
  4953. pthread_t *threadidptr)
  4954. {
  4955. pthread_t thread_id;
  4956. pthread_attr_t attr;
  4957. int result;
  4958. (void)pthread_attr_init(&attr);
  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. if ((result == 0) && (threadidptr != NULL)) {
  4967. *threadidptr = thread_id;
  4968. }
  4969. return result;
  4970. }
  4971. /* Wait for a thread to finish. */
  4972. static int
  4973. mg_join_thread(pthread_t threadid)
  4974. {
  4975. int result;
  4976. result = pthread_join(threadid, NULL);
  4977. return result;
  4978. }
  4979. #if !defined(NO_CGI)
  4980. static pid_t
  4981. spawn_process(struct mg_connection *conn,
  4982. const char *prog,
  4983. char *envblk,
  4984. char *envp[],
  4985. int fdin[2],
  4986. int fdout[2],
  4987. int fderr[2],
  4988. const char *dir)
  4989. {
  4990. pid_t pid;
  4991. const char *interp;
  4992. (void)envblk;
  4993. if (conn == NULL) {
  4994. return 0;
  4995. }
  4996. if ((pid = fork()) == -1) {
  4997. /* Parent */
  4998. mg_send_http_error(conn,
  4999. 500,
  5000. "Error: Creating CGI process\nfork(): %s",
  5001. strerror(ERRNO));
  5002. } else if (pid == 0) {
  5003. /* Child */
  5004. if (chdir(dir) != 0) {
  5005. mg_cry_internal(
  5006. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5007. } else if (dup2(fdin[0], 0) == -1) {
  5008. mg_cry_internal(conn,
  5009. "%s: dup2(%d, 0): %s",
  5010. __func__,
  5011. fdin[0],
  5012. strerror(ERRNO));
  5013. } else if (dup2(fdout[1], 1) == -1) {
  5014. mg_cry_internal(conn,
  5015. "%s: dup2(%d, 1): %s",
  5016. __func__,
  5017. fdout[1],
  5018. strerror(ERRNO));
  5019. } else if (dup2(fderr[1], 2) == -1) {
  5020. mg_cry_internal(conn,
  5021. "%s: dup2(%d, 2): %s",
  5022. __func__,
  5023. fderr[1],
  5024. strerror(ERRNO));
  5025. } else {
  5026. struct sigaction sa;
  5027. /* Keep stderr and stdout in two different pipes.
  5028. * Stdout will be sent back to the client,
  5029. * stderr should go into a server error log. */
  5030. (void)close(fdin[0]);
  5031. (void)close(fdout[1]);
  5032. (void)close(fderr[1]);
  5033. /* Close write end fdin and read end fdout and fderr */
  5034. (void)close(fdin[1]);
  5035. (void)close(fdout[0]);
  5036. (void)close(fderr[0]);
  5037. /* After exec, all signal handlers are restored to their default
  5038. * values, with one exception of SIGCHLD. According to
  5039. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5040. * will leave unchanged after exec if it was set to be ignored.
  5041. * Restore it to default action. */
  5042. memset(&sa, 0, sizeof(sa));
  5043. sa.sa_handler = SIG_DFL;
  5044. sigaction(SIGCHLD, &sa, NULL);
  5045. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5046. if (interp == NULL) {
  5047. (void)execle(prog, prog, NULL, envp);
  5048. mg_cry_internal(conn,
  5049. "%s: execle(%s): %s",
  5050. __func__,
  5051. prog,
  5052. strerror(ERRNO));
  5053. } else {
  5054. (void)execle(interp, interp, prog, NULL, envp);
  5055. mg_cry_internal(conn,
  5056. "%s: execle(%s %s): %s",
  5057. __func__,
  5058. interp,
  5059. prog,
  5060. strerror(ERRNO));
  5061. }
  5062. }
  5063. exit(EXIT_FAILURE);
  5064. }
  5065. return pid;
  5066. }
  5067. #endif /* !NO_CGI */
  5068. static int
  5069. set_non_blocking_mode(SOCKET sock)
  5070. {
  5071. int flags = fcntl(sock, F_GETFL, 0);
  5072. if (flags < 0) {
  5073. return -1;
  5074. }
  5075. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5076. return -1;
  5077. }
  5078. return 0;
  5079. }
  5080. static int
  5081. set_blocking_mode(SOCKET sock)
  5082. {
  5083. int flags = fcntl(sock, F_GETFL, 0);
  5084. if (flags < 0) {
  5085. return -1;
  5086. }
  5087. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5088. return -1;
  5089. }
  5090. return 0;
  5091. }
  5092. #endif /* _WIN32 / else */
  5093. /* End of initial operating system specific define block. */
  5094. /* Get a random number (independent of C rand function) */
  5095. static uint64_t
  5096. get_random(void)
  5097. {
  5098. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5099. static uint64_t lcg = 0; /* Linear congruential generator */
  5100. uint64_t now = mg_get_current_time_ns();
  5101. if (lfsr == 0) {
  5102. /* lfsr will be only 0 if has not been initialized,
  5103. * so this code is called only once. */
  5104. lfsr = mg_get_current_time_ns();
  5105. lcg = mg_get_current_time_ns();
  5106. } else {
  5107. /* Get the next step of both random number generators. */
  5108. lfsr = (lfsr >> 1)
  5109. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5110. << 63);
  5111. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5112. }
  5113. /* Combining two pseudo-random number generators and a high resolution
  5114. * part
  5115. * of the current server time will make it hard (impossible?) to guess
  5116. * the
  5117. * next number. */
  5118. return (lfsr ^ lcg ^ now);
  5119. }
  5120. static int
  5121. mg_poll(struct mg_pollfd *pfd,
  5122. unsigned int n,
  5123. int milliseconds,
  5124. volatile int *stop_server)
  5125. {
  5126. /* Call poll, but only for a maximum time of a few seconds.
  5127. * This will allow to stop the server after some seconds, instead
  5128. * of having to wait for a long socket timeout. */
  5129. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5130. do {
  5131. int result;
  5132. if (*stop_server) {
  5133. /* Shut down signal */
  5134. return -2;
  5135. }
  5136. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5137. ms_now = milliseconds;
  5138. }
  5139. result = poll(pfd, n, ms_now);
  5140. if (result != 0) {
  5141. /* Poll returned either success (1) or error (-1).
  5142. * Forward both to the caller. */
  5143. return result;
  5144. }
  5145. /* Poll returned timeout (0). */
  5146. if (milliseconds > 0) {
  5147. milliseconds -= ms_now;
  5148. }
  5149. } while (milliseconds != 0);
  5150. /* timeout: return 0 */
  5151. return 0;
  5152. }
  5153. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5154. * descriptor.
  5155. * Return value:
  5156. * >=0 .. number of bytes successfully written
  5157. * -1 .. timeout
  5158. * -2 .. error
  5159. */
  5160. static int
  5161. push_inner(struct mg_context *ctx,
  5162. FILE *fp,
  5163. SOCKET sock,
  5164. SSL *ssl,
  5165. const char *buf,
  5166. int len,
  5167. double timeout)
  5168. {
  5169. uint64_t start = 0, now = 0, timeout_ns = 0;
  5170. int n, err;
  5171. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5172. #if defined(_WIN32)
  5173. typedef int len_t;
  5174. #else
  5175. typedef size_t len_t;
  5176. #endif
  5177. if (timeout > 0) {
  5178. now = mg_get_current_time_ns();
  5179. start = now;
  5180. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5181. }
  5182. if (ctx == NULL) {
  5183. return -2;
  5184. }
  5185. #if defined(NO_SSL)
  5186. if (ssl) {
  5187. return -2;
  5188. }
  5189. #endif
  5190. /* Try to read until it succeeds, fails, times out, or the server
  5191. * shuts down. */
  5192. for (;;) {
  5193. #if !defined(NO_SSL)
  5194. if (ssl != NULL) {
  5195. n = SSL_write(ssl, buf, len);
  5196. if (n <= 0) {
  5197. err = SSL_get_error(ssl, n);
  5198. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5199. err = ERRNO;
  5200. } else if ((err == SSL_ERROR_WANT_READ)
  5201. || (err == SSL_ERROR_WANT_WRITE)) {
  5202. n = 0;
  5203. } else {
  5204. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5205. return -2;
  5206. }
  5207. } else {
  5208. err = 0;
  5209. }
  5210. } else
  5211. #endif
  5212. if (fp != NULL) {
  5213. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5214. if (ferror(fp)) {
  5215. n = -1;
  5216. err = ERRNO;
  5217. } else {
  5218. err = 0;
  5219. }
  5220. } else {
  5221. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5222. err = (n < 0) ? ERRNO : 0;
  5223. #if defined(_WIN32)
  5224. if (err == WSAEWOULDBLOCK) {
  5225. err = 0;
  5226. n = 0;
  5227. }
  5228. #else
  5229. if (err == EWOULDBLOCK) {
  5230. err = 0;
  5231. n = 0;
  5232. }
  5233. #endif
  5234. if (n < 0) {
  5235. /* shutdown of the socket at client side */
  5236. return -2;
  5237. }
  5238. }
  5239. if (ctx->stop_flag) {
  5240. return -2;
  5241. }
  5242. if ((n > 0) || ((n == 0) && (len == 0))) {
  5243. /* some data has been read, or no data was requested */
  5244. return n;
  5245. }
  5246. if (n < 0) {
  5247. /* socket error - check errno */
  5248. DEBUG_TRACE("send() failed, error %d", err);
  5249. /* TODO (mid): error handling depending on the error code.
  5250. * These codes are different between Windows and Linux.
  5251. * Currently there is no problem with failing send calls,
  5252. * if there is a reproducible situation, it should be
  5253. * investigated in detail.
  5254. */
  5255. return -2;
  5256. }
  5257. /* Only in case n=0 (timeout), repeat calling the write function */
  5258. /* If send failed, wait before retry */
  5259. if (fp != NULL) {
  5260. /* For files, just wait a fixed time.
  5261. * Maybe it helps, maybe not. */
  5262. mg_sleep(5);
  5263. } else {
  5264. /* For sockets, wait for the socket using poll */
  5265. struct mg_pollfd pfd[1];
  5266. int pollres;
  5267. pfd[0].fd = sock;
  5268. pfd[0].events = POLLOUT;
  5269. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5270. if (ctx->stop_flag) {
  5271. return -2;
  5272. }
  5273. if (pollres > 0) {
  5274. continue;
  5275. }
  5276. }
  5277. if (timeout > 0) {
  5278. now = mg_get_current_time_ns();
  5279. if ((now - start) > timeout_ns) {
  5280. /* Timeout */
  5281. break;
  5282. }
  5283. }
  5284. }
  5285. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5286. used */
  5287. return -1;
  5288. }
  5289. static int
  5290. push_all(struct mg_context *ctx,
  5291. FILE *fp,
  5292. SOCKET sock,
  5293. SSL *ssl,
  5294. const char *buf,
  5295. int len)
  5296. {
  5297. double timeout = -1.0;
  5298. int n, nwritten = 0;
  5299. if (ctx == NULL) {
  5300. return -1;
  5301. }
  5302. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5303. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5304. }
  5305. while ((len > 0) && (ctx->stop_flag == 0)) {
  5306. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5307. if (n < 0) {
  5308. if (nwritten == 0) {
  5309. nwritten = -1; /* Propagate the error */
  5310. }
  5311. break;
  5312. } else if (n == 0) {
  5313. break; /* No more data to write */
  5314. } else {
  5315. nwritten += n;
  5316. len -= n;
  5317. }
  5318. }
  5319. return nwritten;
  5320. }
  5321. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5322. * Return value:
  5323. * >=0 .. number of bytes successfully read
  5324. * -1 .. timeout
  5325. * -2 .. error
  5326. */
  5327. static int
  5328. pull_inner(FILE *fp,
  5329. struct mg_connection *conn,
  5330. char *buf,
  5331. int len,
  5332. double timeout)
  5333. {
  5334. int nread, err = 0;
  5335. #if defined(_WIN32)
  5336. typedef int len_t;
  5337. #else
  5338. typedef size_t len_t;
  5339. #endif
  5340. #if !defined(NO_SSL)
  5341. int ssl_pending;
  5342. #endif
  5343. /* We need an additional wait loop around this, because in some cases
  5344. * with TLSwe may get data from the socket but not from SSL_read.
  5345. * In this case we need to repeat at least once.
  5346. */
  5347. if (fp != NULL) {
  5348. #if !defined(_WIN32_WCE)
  5349. /* Use read() instead of fread(), because if we're reading from the
  5350. * CGI pipe, fread() may block until IO buffer is filled up. We
  5351. * cannot afford to block and must pass all read bytes immediately
  5352. * to the client. */
  5353. nread = (int)read(fileno(fp), buf, (size_t)len);
  5354. #else
  5355. /* WinCE does not support CGI pipes */
  5356. nread = (int)fread(buf, 1, (size_t)len, fp);
  5357. #endif
  5358. err = (nread < 0) ? ERRNO : 0;
  5359. if ((nread == 0) && (len > 0)) {
  5360. /* Should get data, but got EOL */
  5361. return -2;
  5362. }
  5363. #if !defined(NO_SSL)
  5364. } else if ((conn->ssl != NULL)
  5365. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5366. /* We already know there is no more data buffered in conn->buf
  5367. * but there is more available in the SSL layer. So don't poll
  5368. * conn->client.sock yet. */
  5369. if (ssl_pending > len) {
  5370. ssl_pending = len;
  5371. }
  5372. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5373. if (nread <= 0) {
  5374. err = SSL_get_error(conn->ssl, nread);
  5375. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5376. err = ERRNO;
  5377. } else if ((err == SSL_ERROR_WANT_READ)
  5378. || (err == SSL_ERROR_WANT_WRITE)) {
  5379. nread = 0;
  5380. } else {
  5381. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5382. return -1;
  5383. }
  5384. } else {
  5385. err = 0;
  5386. }
  5387. } else if (conn->ssl != NULL) {
  5388. struct mg_pollfd pfd[1];
  5389. int pollres;
  5390. pfd[0].fd = conn->client.sock;
  5391. pfd[0].events = POLLIN;
  5392. pollres = mg_poll(pfd,
  5393. 1,
  5394. (int)(timeout * 1000.0),
  5395. &(conn->phys_ctx->stop_flag));
  5396. if (conn->phys_ctx->stop_flag) {
  5397. return -2;
  5398. }
  5399. if (pollres > 0) {
  5400. nread = SSL_read(conn->ssl, buf, len);
  5401. if (nread <= 0) {
  5402. err = SSL_get_error(conn->ssl, nread);
  5403. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5404. err = ERRNO;
  5405. } else if ((err == SSL_ERROR_WANT_READ)
  5406. || (err == SSL_ERROR_WANT_WRITE)) {
  5407. nread = 0;
  5408. } else {
  5409. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5410. return -2;
  5411. }
  5412. } else {
  5413. err = 0;
  5414. }
  5415. } else if (pollres < 0) {
  5416. /* Error */
  5417. return -2;
  5418. } else {
  5419. /* pollres = 0 means timeout */
  5420. nread = 0;
  5421. }
  5422. #endif
  5423. } else {
  5424. struct mg_pollfd pfd[1];
  5425. int pollres;
  5426. pfd[0].fd = conn->client.sock;
  5427. pfd[0].events = POLLIN;
  5428. pollres = mg_poll(pfd,
  5429. 1,
  5430. (int)(timeout * 1000.0),
  5431. &(conn->phys_ctx->stop_flag));
  5432. if (conn->phys_ctx->stop_flag) {
  5433. return -2;
  5434. }
  5435. if (pollres > 0) {
  5436. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5437. err = (nread < 0) ? ERRNO : 0;
  5438. if (nread <= 0) {
  5439. /* shutdown of the socket at client side */
  5440. return -2;
  5441. }
  5442. } else if (pollres < 0) {
  5443. /* error callint poll */
  5444. return -2;
  5445. } else {
  5446. /* pollres = 0 means timeout */
  5447. nread = 0;
  5448. }
  5449. }
  5450. if (conn->phys_ctx->stop_flag) {
  5451. return -2;
  5452. }
  5453. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5454. /* some data has been read, or no data was requested */
  5455. return nread;
  5456. }
  5457. if (nread < 0) {
  5458. /* socket error - check errno */
  5459. #if defined(_WIN32)
  5460. if (err == WSAEWOULDBLOCK) {
  5461. /* TODO (low): check if this is still required */
  5462. /* standard case if called from close_socket_gracefully */
  5463. return -2;
  5464. } else if (err == WSAETIMEDOUT) {
  5465. /* TODO (low): check if this is still required */
  5466. /* timeout is handled by the while loop */
  5467. return 0;
  5468. } else if (err == WSAECONNABORTED) {
  5469. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5470. return -2;
  5471. } else {
  5472. DEBUG_TRACE("recv() failed, error %d", err);
  5473. return -2;
  5474. }
  5475. #else
  5476. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5477. * if the timeout is reached and if the socket was set to non-
  5478. * blocking in close_socket_gracefully, so we can not distinguish
  5479. * here. We have to wait for the timeout in both cases for now.
  5480. */
  5481. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5482. /* TODO (low): check if this is still required */
  5483. /* EAGAIN/EWOULDBLOCK:
  5484. * standard case if called from close_socket_gracefully
  5485. * => should return -1 */
  5486. /* or timeout occurred
  5487. * => the code must stay in the while loop */
  5488. /* EINTR can be generated on a socket with a timeout set even
  5489. * when SA_RESTART is effective for all relevant signals
  5490. * (see signal(7)).
  5491. * => stay in the while loop */
  5492. } else {
  5493. DEBUG_TRACE("recv() failed, error %d", err);
  5494. return -2;
  5495. }
  5496. #endif
  5497. }
  5498. /* Timeout occurred, but no data available. */
  5499. return -1;
  5500. }
  5501. static int
  5502. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5503. {
  5504. int n, nread = 0;
  5505. double timeout = -1.0;
  5506. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5507. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5508. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5509. }
  5510. if (timeout >= 0.0) {
  5511. start_time = mg_get_current_time_ns();
  5512. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5513. }
  5514. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5515. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5516. if (n == -2) {
  5517. if (nread == 0) {
  5518. nread = -1; /* Propagate the error */
  5519. }
  5520. break;
  5521. } else if (n == -1) {
  5522. /* timeout */
  5523. if (timeout >= 0.0) {
  5524. now = mg_get_current_time_ns();
  5525. if ((now - start_time) <= timeout_ns) {
  5526. continue;
  5527. }
  5528. }
  5529. break;
  5530. } else if (n == 0) {
  5531. break; /* No more data to read */
  5532. } else {
  5533. conn->consumed_content += n;
  5534. nread += n;
  5535. len -= n;
  5536. }
  5537. }
  5538. return nread;
  5539. }
  5540. static void
  5541. discard_unread_request_data(struct mg_connection *conn)
  5542. {
  5543. char buf[MG_BUF_LEN];
  5544. size_t to_read;
  5545. int nread;
  5546. if (conn == NULL) {
  5547. return;
  5548. }
  5549. to_read = sizeof(buf);
  5550. if (conn->is_chunked) {
  5551. /* Chunked encoding: 3=chunk read completely
  5552. * completely */
  5553. while (conn->is_chunked != 3) {
  5554. nread = mg_read(conn, buf, to_read);
  5555. if (nread <= 0) {
  5556. break;
  5557. }
  5558. }
  5559. } else {
  5560. /* Not chunked: content length is known */
  5561. while (conn->consumed_content < conn->content_len) {
  5562. if (to_read
  5563. > (size_t)(conn->content_len - conn->consumed_content)) {
  5564. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5565. }
  5566. nread = mg_read(conn, buf, to_read);
  5567. if (nread <= 0) {
  5568. break;
  5569. }
  5570. }
  5571. }
  5572. }
  5573. static int
  5574. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5575. {
  5576. int64_t n, buffered_len, nread;
  5577. int64_t len64 =
  5578. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5579. * int, we may not read more
  5580. * bytes */
  5581. const char *body;
  5582. if (conn == NULL) {
  5583. return 0;
  5584. }
  5585. /* If Content-Length is not set for a request with body data
  5586. * (e.g., a PUT or POST request), we do not know in advance
  5587. * how much data should be read. */
  5588. if (conn->consumed_content == 0) {
  5589. if (conn->is_chunked == 1) {
  5590. conn->content_len = len64;
  5591. conn->is_chunked = 2;
  5592. } else if (conn->content_len == -1) {
  5593. /* The body data is completed when the connection
  5594. * is closed. */
  5595. conn->content_len = INT64_MAX;
  5596. conn->must_close = 1;
  5597. }
  5598. }
  5599. nread = 0;
  5600. if (conn->consumed_content < conn->content_len) {
  5601. /* Adjust number of bytes to read. */
  5602. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5603. if (left_to_read < len64) {
  5604. /* Do not read more than the total content length of the
  5605. * request.
  5606. */
  5607. len64 = left_to_read;
  5608. }
  5609. /* Return buffered data */
  5610. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5611. - conn->consumed_content;
  5612. if (buffered_len > 0) {
  5613. if (len64 < buffered_len) {
  5614. buffered_len = len64;
  5615. }
  5616. body = conn->buf + conn->request_len + conn->consumed_content;
  5617. memcpy(buf, body, (size_t)buffered_len);
  5618. len64 -= buffered_len;
  5619. conn->consumed_content += buffered_len;
  5620. nread += buffered_len;
  5621. buf = (char *)buf + buffered_len;
  5622. }
  5623. /* We have returned all buffered data. Read new data from the remote
  5624. * socket.
  5625. */
  5626. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5627. nread += n;
  5628. } else {
  5629. nread = ((nread > 0) ? nread : n);
  5630. }
  5631. }
  5632. return (int)nread;
  5633. }
  5634. static char
  5635. mg_getc(struct mg_connection *conn)
  5636. {
  5637. char c;
  5638. if (conn == NULL) {
  5639. return 0;
  5640. }
  5641. if (mg_read_inner(conn, &c, 1) <= 0) {
  5642. return (char)0;
  5643. }
  5644. return c;
  5645. }
  5646. int
  5647. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5648. {
  5649. if (len > INT_MAX) {
  5650. len = INT_MAX;
  5651. }
  5652. if (conn == NULL) {
  5653. return 0;
  5654. }
  5655. if (conn->is_chunked) {
  5656. size_t all_read = 0;
  5657. while (len > 0) {
  5658. if (conn->is_chunked == 3) {
  5659. /* No more data left to read */
  5660. return 0;
  5661. }
  5662. if (conn->chunk_remainder) {
  5663. /* copy from the remainder of the last received chunk */
  5664. long read_ret;
  5665. size_t read_now =
  5666. ((conn->chunk_remainder > len) ? (len)
  5667. : (conn->chunk_remainder));
  5668. conn->content_len += (int)read_now;
  5669. read_ret =
  5670. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5671. if (read_ret < 1) {
  5672. /* read error */
  5673. return -1;
  5674. }
  5675. all_read += (size_t)read_ret;
  5676. conn->chunk_remainder -= (size_t)read_ret;
  5677. len -= (size_t)read_ret;
  5678. if (conn->chunk_remainder == 0) {
  5679. /* Add data bytes in the current chunk have been read,
  5680. * so we are expecting \r\n now. */
  5681. char x1, x2;
  5682. conn->content_len += 2;
  5683. x1 = mg_getc(conn);
  5684. x2 = mg_getc(conn);
  5685. if ((x1 != '\r') || (x2 != '\n')) {
  5686. /* Protocol violation */
  5687. return -1;
  5688. }
  5689. }
  5690. } else {
  5691. /* fetch a new chunk */
  5692. int i = 0;
  5693. char lenbuf[64];
  5694. char *end = 0;
  5695. unsigned long chunkSize = 0;
  5696. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5697. conn->content_len++;
  5698. lenbuf[i] = mg_getc(conn);
  5699. if ((i > 0) && (lenbuf[i] == '\r')
  5700. && (lenbuf[i - 1] != '\r')) {
  5701. continue;
  5702. }
  5703. if ((i > 1) && (lenbuf[i] == '\n')
  5704. && (lenbuf[i - 1] == '\r')) {
  5705. lenbuf[i + 1] = 0;
  5706. chunkSize = strtoul(lenbuf, &end, 16);
  5707. if (chunkSize == 0) {
  5708. /* regular end of content */
  5709. conn->is_chunked = 3;
  5710. }
  5711. break;
  5712. }
  5713. if (!isxdigit((unsigned char)lenbuf[i])) {
  5714. /* illegal character for chunk length */
  5715. return -1;
  5716. }
  5717. }
  5718. if ((end == NULL) || (*end != '\r')) {
  5719. /* chunksize not set correctly */
  5720. return -1;
  5721. }
  5722. if (chunkSize == 0) {
  5723. break;
  5724. }
  5725. conn->chunk_remainder = chunkSize;
  5726. }
  5727. }
  5728. return (int)all_read;
  5729. }
  5730. return mg_read_inner(conn, buf, len);
  5731. }
  5732. int
  5733. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5734. {
  5735. time_t now;
  5736. int n, total, allowed;
  5737. if (conn == NULL) {
  5738. return 0;
  5739. }
  5740. if (len > INT_MAX) {
  5741. return -1;
  5742. }
  5743. if (conn->throttle > 0) {
  5744. if ((now = time(NULL)) != conn->last_throttle_time) {
  5745. conn->last_throttle_time = now;
  5746. conn->last_throttle_bytes = 0;
  5747. }
  5748. allowed = conn->throttle - conn->last_throttle_bytes;
  5749. if (allowed > (int)len) {
  5750. allowed = (int)len;
  5751. }
  5752. if ((total = push_all(conn->phys_ctx,
  5753. NULL,
  5754. conn->client.sock,
  5755. conn->ssl,
  5756. (const char *)buf,
  5757. allowed))
  5758. == allowed) {
  5759. buf = (const char *)buf + total;
  5760. conn->last_throttle_bytes += total;
  5761. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5762. allowed = (conn->throttle > ((int)len - total))
  5763. ? (int)len - total
  5764. : conn->throttle;
  5765. if ((n = push_all(conn->phys_ctx,
  5766. NULL,
  5767. conn->client.sock,
  5768. conn->ssl,
  5769. (const char *)buf,
  5770. allowed))
  5771. != allowed) {
  5772. break;
  5773. }
  5774. sleep(1);
  5775. conn->last_throttle_bytes = allowed;
  5776. conn->last_throttle_time = time(NULL);
  5777. buf = (const char *)buf + n;
  5778. total += n;
  5779. }
  5780. }
  5781. } else {
  5782. total = push_all(conn->phys_ctx,
  5783. NULL,
  5784. conn->client.sock,
  5785. conn->ssl,
  5786. (const char *)buf,
  5787. (int)len);
  5788. }
  5789. if (total > 0) {
  5790. conn->num_bytes_sent += total;
  5791. }
  5792. return total;
  5793. }
  5794. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5795. int
  5796. mg_send_chunk(struct mg_connection *conn,
  5797. const char *chunk,
  5798. unsigned int chunk_len)
  5799. {
  5800. char lenbuf[16];
  5801. size_t lenbuf_len;
  5802. int ret;
  5803. int t;
  5804. /* First store the length information in a text buffer. */
  5805. sprintf(lenbuf, "%x\r\n", chunk_len);
  5806. lenbuf_len = strlen(lenbuf);
  5807. /* Then send length information, chunk and terminating \r\n. */
  5808. ret = mg_write(conn, lenbuf, lenbuf_len);
  5809. if (ret != (int)lenbuf_len) {
  5810. return -1;
  5811. }
  5812. t = ret;
  5813. ret = mg_write(conn, chunk, chunk_len);
  5814. if (ret != (int)chunk_len) {
  5815. return -1;
  5816. }
  5817. t += ret;
  5818. ret = mg_write(conn, "\r\n", 2);
  5819. if (ret != 2) {
  5820. return -1;
  5821. }
  5822. t += ret;
  5823. return t;
  5824. }
  5825. #if defined(GCC_DIAGNOSTIC)
  5826. /* This block forwards format strings to printf implementations,
  5827. * so we need to disable the format-nonliteral warning. */
  5828. #pragma GCC diagnostic push
  5829. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5830. #endif
  5831. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5832. static int
  5833. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5834. {
  5835. va_list ap_copy;
  5836. size_t size = MG_BUF_LEN / 4;
  5837. int len = -1;
  5838. *buf = NULL;
  5839. while (len < 0) {
  5840. if (*buf) {
  5841. mg_free(*buf);
  5842. }
  5843. size *= 4;
  5844. *buf = (char *)mg_malloc(size);
  5845. if (!*buf) {
  5846. break;
  5847. }
  5848. va_copy(ap_copy, ap);
  5849. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5850. va_end(ap_copy);
  5851. (*buf)[size - 1] = 0;
  5852. }
  5853. return len;
  5854. }
  5855. /* Print message to buffer. If buffer is large enough to hold the message,
  5856. * return buffer. If buffer is to small, allocate large enough buffer on
  5857. * heap,
  5858. * and return allocated buffer. */
  5859. static int
  5860. alloc_vprintf(char **out_buf,
  5861. char *prealloc_buf,
  5862. size_t prealloc_size,
  5863. const char *fmt,
  5864. va_list ap)
  5865. {
  5866. va_list ap_copy;
  5867. int len;
  5868. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5869. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5870. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5871. * Therefore, we make two passes: on first pass, get required message
  5872. * length.
  5873. * On second pass, actually print the message. */
  5874. va_copy(ap_copy, ap);
  5875. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5876. va_end(ap_copy);
  5877. if (len < 0) {
  5878. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5879. * Switch to alternative code path that uses incremental
  5880. * allocations.
  5881. */
  5882. va_copy(ap_copy, ap);
  5883. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5884. va_end(ap_copy);
  5885. } else if ((size_t)(len) >= prealloc_size) {
  5886. /* The pre-allocated buffer not large enough. */
  5887. /* Allocate a new buffer. */
  5888. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5889. if (!*out_buf) {
  5890. /* Allocation failed. Return -1 as "out of memory" error. */
  5891. return -1;
  5892. }
  5893. /* Buffer allocation successful. Store the string there. */
  5894. va_copy(ap_copy, ap);
  5895. IGNORE_UNUSED_RESULT(
  5896. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5897. va_end(ap_copy);
  5898. } else {
  5899. /* The pre-allocated buffer is large enough.
  5900. * Use it to store the string and return the address. */
  5901. va_copy(ap_copy, ap);
  5902. IGNORE_UNUSED_RESULT(
  5903. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5904. va_end(ap_copy);
  5905. *out_buf = prealloc_buf;
  5906. }
  5907. return len;
  5908. }
  5909. #if defined(GCC_DIAGNOSTIC)
  5910. /* Enable format-nonliteral warning again. */
  5911. #pragma GCC diagnostic pop
  5912. #endif
  5913. static int
  5914. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5915. {
  5916. char mem[MG_BUF_LEN];
  5917. char *buf = NULL;
  5918. int len;
  5919. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5920. len = mg_write(conn, buf, (size_t)len);
  5921. }
  5922. if ((buf != mem) && (buf != NULL)) {
  5923. mg_free(buf);
  5924. }
  5925. return len;
  5926. }
  5927. int
  5928. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5929. {
  5930. va_list ap;
  5931. int result;
  5932. va_start(ap, fmt);
  5933. result = mg_vprintf(conn, fmt, ap);
  5934. va_end(ap);
  5935. return result;
  5936. }
  5937. int
  5938. mg_url_decode(const char *src,
  5939. int src_len,
  5940. char *dst,
  5941. int dst_len,
  5942. int is_form_url_encoded)
  5943. {
  5944. int i, j, a, b;
  5945. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5946. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5947. if ((i < src_len - 2) && (src[i] == '%')
  5948. && isxdigit((unsigned char)src[i + 1])
  5949. && isxdigit((unsigned char)src[i + 2])) {
  5950. a = tolower((unsigned char)src[i + 1]);
  5951. b = tolower((unsigned char)src[i + 2]);
  5952. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5953. i += 2;
  5954. } else if (is_form_url_encoded && (src[i] == '+')) {
  5955. dst[j] = ' ';
  5956. } else {
  5957. dst[j] = src[i];
  5958. }
  5959. }
  5960. dst[j] = '\0'; /* Null-terminate the destination */
  5961. return (i >= src_len) ? j : -1;
  5962. }
  5963. int
  5964. mg_get_var(const char *data,
  5965. size_t data_len,
  5966. const char *name,
  5967. char *dst,
  5968. size_t dst_len)
  5969. {
  5970. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5971. }
  5972. int
  5973. mg_get_var2(const char *data,
  5974. size_t data_len,
  5975. const char *name,
  5976. char *dst,
  5977. size_t dst_len,
  5978. size_t occurrence)
  5979. {
  5980. const char *p, *e, *s;
  5981. size_t name_len;
  5982. int len;
  5983. if ((dst == NULL) || (dst_len == 0)) {
  5984. len = -2;
  5985. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5986. len = -1;
  5987. dst[0] = '\0';
  5988. } else {
  5989. name_len = strlen(name);
  5990. e = data + data_len;
  5991. len = -1;
  5992. dst[0] = '\0';
  5993. /* data is "var1=val1&var2=val2...". Find variable first */
  5994. for (p = data; p + name_len < e; p++) {
  5995. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5996. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5997. /* Point p to variable value */
  5998. p += name_len + 1;
  5999. /* Point s to the end of the value */
  6000. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6001. if (s == NULL) {
  6002. s = e;
  6003. }
  6004. DEBUG_ASSERT(s >= p);
  6005. if (s < p) {
  6006. return -3;
  6007. }
  6008. /* Decode variable into destination buffer */
  6009. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6010. /* Redirect error code from -1 to -2 (destination buffer too
  6011. * small). */
  6012. if (len == -1) {
  6013. len = -2;
  6014. }
  6015. break;
  6016. }
  6017. }
  6018. }
  6019. return len;
  6020. }
  6021. /* HCP24: some changes to compare hole var_name */
  6022. int
  6023. mg_get_cookie(const char *cookie_header,
  6024. const char *var_name,
  6025. char *dst,
  6026. size_t dst_size)
  6027. {
  6028. const char *s, *p, *end;
  6029. int name_len, len = -1;
  6030. if ((dst == NULL) || (dst_size == 0)) {
  6031. return -2;
  6032. }
  6033. dst[0] = '\0';
  6034. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6035. return -1;
  6036. }
  6037. name_len = (int)strlen(var_name);
  6038. end = s + strlen(s);
  6039. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6040. if (s[name_len] == '=') {
  6041. /* HCP24: now check is it a substring or a full cookie name */
  6042. if ((s == cookie_header) || (s[-1] == ' ')) {
  6043. s += name_len + 1;
  6044. if ((p = strchr(s, ' ')) == NULL) {
  6045. p = end;
  6046. }
  6047. if (p[-1] == ';') {
  6048. p--;
  6049. }
  6050. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6051. s++;
  6052. p--;
  6053. }
  6054. if ((size_t)(p - s) < dst_size) {
  6055. len = (int)(p - s);
  6056. mg_strlcpy(dst, s, (size_t)len + 1);
  6057. } else {
  6058. len = -3;
  6059. }
  6060. break;
  6061. }
  6062. }
  6063. }
  6064. return len;
  6065. }
  6066. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6067. static void
  6068. base64_encode(const unsigned char *src, int src_len, char *dst)
  6069. {
  6070. static const char *b64 =
  6071. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6072. int i, j, a, b, c;
  6073. for (i = j = 0; i < src_len; i += 3) {
  6074. a = src[i];
  6075. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6076. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6077. dst[j++] = b64[a >> 2];
  6078. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6079. if (i + 1 < src_len) {
  6080. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6081. }
  6082. if (i + 2 < src_len) {
  6083. dst[j++] = b64[c & 63];
  6084. }
  6085. }
  6086. while (j % 4 != 0) {
  6087. dst[j++] = '=';
  6088. }
  6089. dst[j++] = '\0';
  6090. }
  6091. #endif
  6092. #if defined(USE_LUA)
  6093. static unsigned char
  6094. b64reverse(char letter)
  6095. {
  6096. if ((letter >= 'A') && (letter <= 'Z')) {
  6097. return letter - 'A';
  6098. }
  6099. if ((letter >= 'a') && (letter <= 'z')) {
  6100. return letter - 'a' + 26;
  6101. }
  6102. if ((letter >= '0') && (letter <= '9')) {
  6103. return letter - '0' + 52;
  6104. }
  6105. if (letter == '+') {
  6106. return 62;
  6107. }
  6108. if (letter == '/') {
  6109. return 63;
  6110. }
  6111. if (letter == '=') {
  6112. return 255; /* normal end */
  6113. }
  6114. return 254; /* error */
  6115. }
  6116. static int
  6117. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6118. {
  6119. int i;
  6120. unsigned char a, b, c, d;
  6121. *dst_len = 0;
  6122. for (i = 0; i < src_len; i += 4) {
  6123. a = b64reverse(src[i]);
  6124. if (a >= 254) {
  6125. return i;
  6126. }
  6127. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6128. if (b >= 254) {
  6129. return i + 1;
  6130. }
  6131. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6132. if (c == 254) {
  6133. return i + 2;
  6134. }
  6135. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6136. if (d == 254) {
  6137. return i + 3;
  6138. }
  6139. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6140. if (c != 255) {
  6141. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6142. if (d != 255) {
  6143. dst[(*dst_len)++] = (c << 6) + d;
  6144. }
  6145. }
  6146. }
  6147. return -1;
  6148. }
  6149. #endif
  6150. static int
  6151. is_put_or_delete_method(const struct mg_connection *conn)
  6152. {
  6153. if (conn) {
  6154. const char *s = conn->request_info.request_method;
  6155. return (s != NULL)
  6156. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6157. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6158. }
  6159. return 0;
  6160. }
  6161. #if !defined(NO_FILES)
  6162. static int
  6163. extention_matches_script(
  6164. struct mg_connection *conn, /* in: request (must be valid) */
  6165. const char *filename /* in: filename (must be valid) */
  6166. )
  6167. {
  6168. #if !defined(NO_CGI)
  6169. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6170. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6171. filename)
  6172. > 0) {
  6173. return 1;
  6174. }
  6175. #endif
  6176. #if defined(USE_LUA)
  6177. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6178. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6179. filename)
  6180. > 0) {
  6181. return 1;
  6182. }
  6183. #endif
  6184. #if defined(USE_DUKTAPE)
  6185. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6186. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6187. filename)
  6188. > 0) {
  6189. return 1;
  6190. }
  6191. #endif
  6192. /* filename and conn could be unused, if all preocessor conditions
  6193. * are false (no script language supported). */
  6194. (void)filename;
  6195. (void)conn;
  6196. return 0;
  6197. }
  6198. /* For given directory path, substitute it to valid index file.
  6199. * Return 1 if index file has been found, 0 if not found.
  6200. * If the file is found, it's stats is returned in stp. */
  6201. static int
  6202. substitute_index_file(struct mg_connection *conn,
  6203. char *path,
  6204. size_t path_len,
  6205. struct mg_file_stat *filestat)
  6206. {
  6207. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6208. struct vec filename_vec;
  6209. size_t n = strlen(path);
  6210. int found = 0;
  6211. /* The 'path' given to us points to the directory. Remove all trailing
  6212. * directory separator characters from the end of the path, and
  6213. * then append single directory separator character. */
  6214. while ((n > 0) && (path[n - 1] == '/')) {
  6215. n--;
  6216. }
  6217. path[n] = '/';
  6218. /* Traverse index files list. For each entry, append it to the given
  6219. * path and see if the file exists. If it exists, break the loop */
  6220. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6221. /* Ignore too long entries that may overflow path buffer */
  6222. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6223. continue;
  6224. }
  6225. /* Prepare full path to the index file */
  6226. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6227. /* Does it exist? */
  6228. if (mg_stat(conn, path, filestat)) {
  6229. /* Yes it does, break the loop */
  6230. found = 1;
  6231. break;
  6232. }
  6233. }
  6234. /* If no index file exists, restore directory path */
  6235. if (!found) {
  6236. path[n] = '\0';
  6237. }
  6238. return found;
  6239. }
  6240. #endif
  6241. static void
  6242. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6243. char *filename, /* out: filename */
  6244. size_t filename_buf_len, /* in: size of filename buffer */
  6245. struct mg_file_stat *filestat, /* out: file status structure */
  6246. int *is_found, /* out: file found (directly) */
  6247. int *is_script_resource, /* out: handled by a script? */
  6248. int *is_websocket_request, /* out: websocket connetion? */
  6249. int *is_put_or_delete_request /* out: put/delete a file? */
  6250. )
  6251. {
  6252. char const *accept_encoding;
  6253. #if !defined(NO_FILES)
  6254. const char *uri = conn->request_info.local_uri;
  6255. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6256. const char *rewrite;
  6257. struct vec a, b;
  6258. ptrdiff_t match_len;
  6259. char gz_path[PATH_MAX];
  6260. int truncated;
  6261. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6262. char *tmp_str;
  6263. size_t tmp_str_len, sep_pos;
  6264. int allow_substitute_script_subresources;
  6265. #endif
  6266. #else
  6267. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6268. #endif
  6269. /* Step 1: Set all initially unknown outputs to zero */
  6270. memset(filestat, 0, sizeof(*filestat));
  6271. *filename = 0;
  6272. *is_found = 0;
  6273. *is_script_resource = 0;
  6274. /* Step 2: Check if the request attempts to modify the file system */
  6275. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6276. /* Step 3: Check if it is a websocket request, and modify the document
  6277. * root if required */
  6278. #if defined(USE_WEBSOCKET)
  6279. *is_websocket_request = is_websocket_protocol(conn);
  6280. #if !defined(NO_FILES)
  6281. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6282. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6283. }
  6284. #endif /* !NO_FILES */
  6285. #else /* USE_WEBSOCKET */
  6286. *is_websocket_request = 0;
  6287. #endif /* USE_WEBSOCKET */
  6288. /* Step 4: Check if gzip encoded response is allowed */
  6289. conn->accept_gzip = 0;
  6290. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6291. if (strstr(accept_encoding, "gzip") != NULL) {
  6292. conn->accept_gzip = 1;
  6293. }
  6294. }
  6295. #if !defined(NO_FILES)
  6296. /* Step 5: If there is no root directory, don't look for files. */
  6297. /* Note that root == NULL is a regular use case here. This occurs,
  6298. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6299. * config is not required. */
  6300. if (root == NULL) {
  6301. /* all file related outputs have already been set to 0, just return
  6302. */
  6303. return;
  6304. }
  6305. /* Step 6: Determine the local file path from the root path and the
  6306. * request uri. */
  6307. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6308. * part of the path one byte on the right. */
  6309. mg_snprintf(
  6310. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6311. if (truncated) {
  6312. goto interpret_cleanup;
  6313. }
  6314. /* Step 7: URI rewriting */
  6315. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6316. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6317. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6318. mg_snprintf(conn,
  6319. &truncated,
  6320. filename,
  6321. filename_buf_len - 1,
  6322. "%.*s%s",
  6323. (int)b.len,
  6324. b.ptr,
  6325. uri + match_len);
  6326. break;
  6327. }
  6328. }
  6329. if (truncated) {
  6330. goto interpret_cleanup;
  6331. }
  6332. /* Step 8: Check if the file exists at the server */
  6333. /* Local file path and name, corresponding to requested URI
  6334. * is now stored in "filename" variable. */
  6335. if (mg_stat(conn, filename, filestat)) {
  6336. int uri_len = (int)strlen(uri);
  6337. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6338. /* 8.1: File exists. */
  6339. *is_found = 1;
  6340. /* 8.2: Check if it is a script type. */
  6341. if (extention_matches_script(conn, filename)) {
  6342. /* The request addresses a CGI resource, Lua script or
  6343. * server-side javascript.
  6344. * The URI corresponds to the script itself (like
  6345. * /path/script.cgi), and there is no additional resource
  6346. * path (like /path/script.cgi/something).
  6347. * Requests that modify (replace or delete) a resource, like
  6348. * PUT and DELETE requests, should replace/delete the script
  6349. * file.
  6350. * Requests that read or write from/to a resource, like GET and
  6351. * POST requests, should call the script and return the
  6352. * generated response. */
  6353. *is_script_resource = (!*is_put_or_delete_request);
  6354. }
  6355. /* 8.3: If the request target is a directory, there could be
  6356. * a substitute file (index.html, index.cgi, ...). */
  6357. if (filestat->is_directory && is_uri_end_slash) {
  6358. /* Use a local copy here, since substitute_index_file will
  6359. * change the content of the file status */
  6360. struct mg_file_stat tmp_filestat;
  6361. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6362. if (substitute_index_file(
  6363. conn, filename, filename_buf_len, &tmp_filestat)) {
  6364. /* Substitute file found. Copy stat to the output, then
  6365. * check if the file is a script file */
  6366. *filestat = tmp_filestat;
  6367. if (extention_matches_script(conn, filename)) {
  6368. /* Substitute file is a script file */
  6369. *is_script_resource = 1;
  6370. } else {
  6371. /* Substitute file is a regular file */
  6372. *is_script_resource = 0;
  6373. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6374. }
  6375. }
  6376. /* If there is no substitute file, the server could return
  6377. * a directory listing in a later step */
  6378. }
  6379. return;
  6380. }
  6381. /* Step 9: Check for zipped files: */
  6382. /* If we can't find the actual file, look for the file
  6383. * with the same name but a .gz extension. If we find it,
  6384. * use that and set the gzipped flag in the file struct
  6385. * to indicate that the response need to have the content-
  6386. * encoding: gzip header.
  6387. * We can only do this if the browser declares support. */
  6388. if (conn->accept_gzip) {
  6389. mg_snprintf(
  6390. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6391. if (truncated) {
  6392. goto interpret_cleanup;
  6393. }
  6394. if (mg_stat(conn, gz_path, filestat)) {
  6395. if (filestat) {
  6396. filestat->is_gzipped = 1;
  6397. *is_found = 1;
  6398. }
  6399. /* Currently gz files can not be scripts. */
  6400. return;
  6401. }
  6402. }
  6403. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6404. /* Step 10: Script resources may handle sub-resources */
  6405. /* Support PATH_INFO for CGI scripts. */
  6406. tmp_str_len = strlen(filename);
  6407. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6408. if (!tmp_str) {
  6409. /* Out of memory */
  6410. goto interpret_cleanup;
  6411. }
  6412. memcpy(tmp_str, filename, tmp_str_len + 1);
  6413. /* Check config, if index scripts may have sub-resources */
  6414. allow_substitute_script_subresources =
  6415. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6416. "yes");
  6417. sep_pos = tmp_str_len;
  6418. while (sep_pos > 0) {
  6419. sep_pos--;
  6420. if (tmp_str[sep_pos] == '/') {
  6421. int is_script = 0, does_exist = 0;
  6422. tmp_str[sep_pos] = 0;
  6423. if (tmp_str[0]) {
  6424. is_script = extention_matches_script(conn, tmp_str);
  6425. does_exist = mg_stat(conn, tmp_str, filestat);
  6426. }
  6427. if (does_exist && is_script) {
  6428. filename[sep_pos] = 0;
  6429. memmove(filename + sep_pos + 2,
  6430. filename + sep_pos + 1,
  6431. strlen(filename + sep_pos + 1) + 1);
  6432. conn->path_info = filename + sep_pos + 1;
  6433. filename[sep_pos + 1] = '/';
  6434. *is_script_resource = 1;
  6435. *is_found = 1;
  6436. break;
  6437. }
  6438. if (allow_substitute_script_subresources) {
  6439. if (substitute_index_file(
  6440. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6441. /* some intermediate directory has an index file */
  6442. if (extention_matches_script(conn, tmp_str)) {
  6443. char *tmp_str2;
  6444. DEBUG_TRACE("Substitute script %s serving path %s",
  6445. tmp_str,
  6446. filename);
  6447. /* this index file is a script */
  6448. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6449. conn->phys_ctx);
  6450. mg_snprintf(conn,
  6451. &truncated,
  6452. filename,
  6453. filename_buf_len,
  6454. "%s//%s",
  6455. tmp_str,
  6456. tmp_str2);
  6457. mg_free(tmp_str2);
  6458. if (truncated) {
  6459. mg_free(tmp_str);
  6460. goto interpret_cleanup;
  6461. }
  6462. sep_pos = strlen(tmp_str);
  6463. filename[sep_pos] = 0;
  6464. conn->path_info = filename + sep_pos + 1;
  6465. *is_script_resource = 1;
  6466. *is_found = 1;
  6467. break;
  6468. } else {
  6469. DEBUG_TRACE("Substitute file %s serving path %s",
  6470. tmp_str,
  6471. filename);
  6472. /* non-script files will not have sub-resources */
  6473. filename[sep_pos] = 0;
  6474. conn->path_info = 0;
  6475. *is_script_resource = 0;
  6476. *is_found = 0;
  6477. break;
  6478. }
  6479. }
  6480. }
  6481. tmp_str[sep_pos] = '/';
  6482. }
  6483. }
  6484. mg_free(tmp_str);
  6485. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6486. #endif /* !defined(NO_FILES) */
  6487. return;
  6488. #if !defined(NO_FILES)
  6489. /* Reset all outputs */
  6490. interpret_cleanup:
  6491. memset(filestat, 0, sizeof(*filestat));
  6492. *filename = 0;
  6493. *is_found = 0;
  6494. *is_script_resource = 0;
  6495. *is_websocket_request = 0;
  6496. *is_put_or_delete_request = 0;
  6497. #endif /* !defined(NO_FILES) */
  6498. }
  6499. /* Check whether full request is buffered. Return:
  6500. * -1 if request or response is malformed
  6501. * 0 if request or response is not yet fully buffered
  6502. * >0 actual request length, including last \r\n\r\n */
  6503. static int
  6504. get_http_header_len(const char *buf, int buflen)
  6505. {
  6506. int i;
  6507. for (i = 0; i < buflen; i++) {
  6508. /* Do an unsigned comparison in some conditions below */
  6509. const unsigned char c = (unsigned char)buf[i];
  6510. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6511. && !isprint(c)) {
  6512. /* abort scan as soon as one malformed character is found */
  6513. return -1;
  6514. }
  6515. if (i < buflen - 1) {
  6516. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6517. /* Two newline, no carriage return - not standard compliant,
  6518. * but
  6519. * it
  6520. * should be accepted */
  6521. return i + 2;
  6522. }
  6523. }
  6524. if (i < buflen - 3) {
  6525. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6526. && (buf[i + 3] == '\n')) {
  6527. /* Two \r\n - standard compliant */
  6528. return i + 4;
  6529. }
  6530. }
  6531. }
  6532. return 0;
  6533. }
  6534. #if !defined(NO_CACHING)
  6535. /* Convert month to the month number. Return -1 on error, or month number */
  6536. static int
  6537. get_month_index(const char *s)
  6538. {
  6539. size_t i;
  6540. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6541. if (!strcmp(s, month_names[i])) {
  6542. return (int)i;
  6543. }
  6544. }
  6545. return -1;
  6546. }
  6547. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6548. static time_t
  6549. parse_date_string(const char *datetime)
  6550. {
  6551. char month_str[32] = {0};
  6552. int second, minute, hour, day, month, year;
  6553. time_t result = (time_t)0;
  6554. struct tm tm;
  6555. if ((sscanf(datetime,
  6556. "%d/%3s/%d %d:%d:%d",
  6557. &day,
  6558. month_str,
  6559. &year,
  6560. &hour,
  6561. &minute,
  6562. &second)
  6563. == 6)
  6564. || (sscanf(datetime,
  6565. "%d %3s %d %d:%d:%d",
  6566. &day,
  6567. month_str,
  6568. &year,
  6569. &hour,
  6570. &minute,
  6571. &second)
  6572. == 6)
  6573. || (sscanf(datetime,
  6574. "%*3s, %d %3s %d %d:%d:%d",
  6575. &day,
  6576. month_str,
  6577. &year,
  6578. &hour,
  6579. &minute,
  6580. &second)
  6581. == 6)
  6582. || (sscanf(datetime,
  6583. "%d-%3s-%d %d:%d:%d",
  6584. &day,
  6585. month_str,
  6586. &year,
  6587. &hour,
  6588. &minute,
  6589. &second)
  6590. == 6)) {
  6591. month = get_month_index(month_str);
  6592. if ((month >= 0) && (year >= 1970)) {
  6593. memset(&tm, 0, sizeof(tm));
  6594. tm.tm_year = year - 1900;
  6595. tm.tm_mon = month;
  6596. tm.tm_mday = day;
  6597. tm.tm_hour = hour;
  6598. tm.tm_min = minute;
  6599. tm.tm_sec = second;
  6600. result = timegm(&tm);
  6601. }
  6602. }
  6603. return result;
  6604. }
  6605. #endif /* !NO_CACHING */
  6606. /* Protect against directory disclosure attack by removing '..',
  6607. * excessive '/' and '\' characters */
  6608. static void
  6609. remove_double_dots_and_double_slashes(char *s)
  6610. {
  6611. char *p = s;
  6612. while ((s[0] == '.') && (s[1] == '.')) {
  6613. s++;
  6614. }
  6615. while (*s != '\0') {
  6616. *p++ = *s++;
  6617. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6618. /* Skip all following slashes, backslashes and double-dots */
  6619. while (s[0] != '\0') {
  6620. if ((s[0] == '/') || (s[0] == '\\')) {
  6621. s++;
  6622. } else if ((s[0] == '.') && (s[1] == '.')) {
  6623. s += 2;
  6624. } else {
  6625. break;
  6626. }
  6627. }
  6628. }
  6629. }
  6630. *p = '\0';
  6631. }
  6632. static const struct {
  6633. const char *extension;
  6634. size_t ext_len;
  6635. const char *mime_type;
  6636. } builtin_mime_types[] = {
  6637. /* IANA registered MIME types
  6638. * (http://www.iana.org/assignments/media-types)
  6639. * application types */
  6640. {".doc", 4, "application/msword"},
  6641. {".eps", 4, "application/postscript"},
  6642. {".exe", 4, "application/octet-stream"},
  6643. {".js", 3, "application/javascript"},
  6644. {".json", 5, "application/json"},
  6645. {".pdf", 4, "application/pdf"},
  6646. {".ps", 3, "application/postscript"},
  6647. {".rtf", 4, "application/rtf"},
  6648. {".xhtml", 6, "application/xhtml+xml"},
  6649. {".xsl", 4, "application/xml"},
  6650. {".xslt", 5, "application/xml"},
  6651. /* fonts */
  6652. {".ttf", 4, "application/font-sfnt"},
  6653. {".cff", 4, "application/font-sfnt"},
  6654. {".otf", 4, "application/font-sfnt"},
  6655. {".aat", 4, "application/font-sfnt"},
  6656. {".sil", 4, "application/font-sfnt"},
  6657. {".pfr", 4, "application/font-tdpfr"},
  6658. {".woff", 5, "application/font-woff"},
  6659. /* audio */
  6660. {".mp3", 4, "audio/mpeg"},
  6661. {".oga", 4, "audio/ogg"},
  6662. {".ogg", 4, "audio/ogg"},
  6663. /* image */
  6664. {".gif", 4, "image/gif"},
  6665. {".ief", 4, "image/ief"},
  6666. {".jpeg", 5, "image/jpeg"},
  6667. {".jpg", 4, "image/jpeg"},
  6668. {".jpm", 4, "image/jpm"},
  6669. {".jpx", 4, "image/jpx"},
  6670. {".png", 4, "image/png"},
  6671. {".svg", 4, "image/svg+xml"},
  6672. {".tif", 4, "image/tiff"},
  6673. {".tiff", 5, "image/tiff"},
  6674. /* model */
  6675. {".wrl", 4, "model/vrml"},
  6676. /* text */
  6677. {".css", 4, "text/css"},
  6678. {".csv", 4, "text/csv"},
  6679. {".htm", 4, "text/html"},
  6680. {".html", 5, "text/html"},
  6681. {".sgm", 4, "text/sgml"},
  6682. {".shtm", 5, "text/html"},
  6683. {".shtml", 6, "text/html"},
  6684. {".txt", 4, "text/plain"},
  6685. {".xml", 4, "text/xml"},
  6686. /* video */
  6687. {".mov", 4, "video/quicktime"},
  6688. {".mp4", 4, "video/mp4"},
  6689. {".mpeg", 5, "video/mpeg"},
  6690. {".mpg", 4, "video/mpeg"},
  6691. {".ogv", 4, "video/ogg"},
  6692. {".qt", 3, "video/quicktime"},
  6693. /* not registered types
  6694. * (http://reference.sitepoint.com/html/mime-types-full,
  6695. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6696. {".arj", 4, "application/x-arj-compressed"},
  6697. {".gz", 3, "application/x-gunzip"},
  6698. {".rar", 4, "application/x-arj-compressed"},
  6699. {".swf", 4, "application/x-shockwave-flash"},
  6700. {".tar", 4, "application/x-tar"},
  6701. {".tgz", 4, "application/x-tar-gz"},
  6702. {".torrent", 8, "application/x-bittorrent"},
  6703. {".ppt", 4, "application/x-mspowerpoint"},
  6704. {".xls", 4, "application/x-msexcel"},
  6705. {".zip", 4, "application/x-zip-compressed"},
  6706. {".aac",
  6707. 4,
  6708. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6709. {".aif", 4, "audio/x-aif"},
  6710. {".m3u", 4, "audio/x-mpegurl"},
  6711. {".mid", 4, "audio/x-midi"},
  6712. {".ra", 3, "audio/x-pn-realaudio"},
  6713. {".ram", 4, "audio/x-pn-realaudio"},
  6714. {".wav", 4, "audio/x-wav"},
  6715. {".bmp", 4, "image/bmp"},
  6716. {".ico", 4, "image/x-icon"},
  6717. {".pct", 4, "image/x-pct"},
  6718. {".pict", 5, "image/pict"},
  6719. {".rgb", 4, "image/x-rgb"},
  6720. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6721. {".asf", 4, "video/x-ms-asf"},
  6722. {".avi", 4, "video/x-msvideo"},
  6723. {".m4v", 4, "video/x-m4v"},
  6724. {NULL, 0, NULL}};
  6725. const char *
  6726. mg_get_builtin_mime_type(const char *path)
  6727. {
  6728. const char *ext;
  6729. size_t i, path_len;
  6730. path_len = strlen(path);
  6731. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6732. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6733. if ((path_len > builtin_mime_types[i].ext_len)
  6734. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6735. return builtin_mime_types[i].mime_type;
  6736. }
  6737. }
  6738. return "text/plain";
  6739. }
  6740. /* Look at the "path" extension and figure what mime type it has.
  6741. * Store mime type in the vector. */
  6742. static void
  6743. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6744. {
  6745. struct vec ext_vec, mime_vec;
  6746. const char *list, *ext;
  6747. size_t path_len;
  6748. path_len = strlen(path);
  6749. if ((conn == NULL) || (vec == NULL)) {
  6750. if (vec != NULL) {
  6751. memset(vec, '\0', sizeof(struct vec));
  6752. }
  6753. return;
  6754. }
  6755. /* Scan user-defined mime types first, in case user wants to
  6756. * override default mime types. */
  6757. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6758. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6759. /* ext now points to the path suffix */
  6760. ext = path + path_len - ext_vec.len;
  6761. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6762. *vec = mime_vec;
  6763. return;
  6764. }
  6765. }
  6766. vec->ptr = mg_get_builtin_mime_type(path);
  6767. vec->len = strlen(vec->ptr);
  6768. }
  6769. /* Stringify binary data. Output buffer must be twice as big as input,
  6770. * because each byte takes 2 bytes in string representation */
  6771. static void
  6772. bin2str(char *to, const unsigned char *p, size_t len)
  6773. {
  6774. static const char *hex = "0123456789abcdef";
  6775. for (; len--; p++) {
  6776. *to++ = hex[p[0] >> 4];
  6777. *to++ = hex[p[0] & 0x0f];
  6778. }
  6779. *to = '\0';
  6780. }
  6781. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6782. */
  6783. char *
  6784. mg_md5(char buf[33], ...)
  6785. {
  6786. md5_byte_t hash[16];
  6787. const char *p;
  6788. va_list ap;
  6789. md5_state_t ctx;
  6790. md5_init(&ctx);
  6791. va_start(ap, buf);
  6792. while ((p = va_arg(ap, const char *)) != NULL) {
  6793. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6794. }
  6795. va_end(ap);
  6796. md5_finish(&ctx, hash);
  6797. bin2str(buf, hash, sizeof(hash));
  6798. return buf;
  6799. }
  6800. /* Check the user's password, return 1 if OK */
  6801. static int
  6802. check_password(const char *method,
  6803. const char *ha1,
  6804. const char *uri,
  6805. const char *nonce,
  6806. const char *nc,
  6807. const char *cnonce,
  6808. const char *qop,
  6809. const char *response)
  6810. {
  6811. char ha2[32 + 1], expected_response[32 + 1];
  6812. /* Some of the parameters may be NULL */
  6813. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6814. || (qop == NULL) || (response == NULL)) {
  6815. return 0;
  6816. }
  6817. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6818. if (strlen(response) != 32) {
  6819. return 0;
  6820. }
  6821. mg_md5(ha2, method, ":", uri, NULL);
  6822. mg_md5(expected_response,
  6823. ha1,
  6824. ":",
  6825. nonce,
  6826. ":",
  6827. nc,
  6828. ":",
  6829. cnonce,
  6830. ":",
  6831. qop,
  6832. ":",
  6833. ha2,
  6834. NULL);
  6835. return mg_strcasecmp(response, expected_response) == 0;
  6836. }
  6837. /* Use the global passwords file, if specified by auth_gpass option,
  6838. * or search for .htpasswd in the requested directory. */
  6839. static void
  6840. open_auth_file(struct mg_connection *conn,
  6841. const char *path,
  6842. struct mg_file *filep)
  6843. {
  6844. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6845. char name[PATH_MAX];
  6846. const char *p, *e,
  6847. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6848. int truncated;
  6849. if (gpass != NULL) {
  6850. /* Use global passwords file */
  6851. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6852. #if defined(DEBUG)
  6853. /* Use mg_cry_internal here, since gpass has been configured. */
  6854. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6855. #endif
  6856. }
  6857. /* Important: using local struct mg_file to test path for
  6858. * is_directory flag. If filep is used, mg_stat() makes it
  6859. * appear as if auth file was opened.
  6860. * TODO(mid): Check if this is still required after rewriting
  6861. * mg_stat */
  6862. } else if (mg_stat(conn, path, &filep->stat)
  6863. && filep->stat.is_directory) {
  6864. mg_snprintf(conn,
  6865. &truncated,
  6866. name,
  6867. sizeof(name),
  6868. "%s/%s",
  6869. path,
  6870. PASSWORDS_FILE_NAME);
  6871. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6872. #if defined(DEBUG)
  6873. /* Don't use mg_cry_internal here, but only a trace, since this
  6874. * is
  6875. * a typical case. It will occur for every directory
  6876. * without a password file. */
  6877. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6878. #endif
  6879. }
  6880. } else {
  6881. /* Try to find .htpasswd in requested directory. */
  6882. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6883. if (e[0] == '/') {
  6884. break;
  6885. }
  6886. }
  6887. mg_snprintf(conn,
  6888. &truncated,
  6889. name,
  6890. sizeof(name),
  6891. "%.*s/%s",
  6892. (int)(e - p),
  6893. p,
  6894. PASSWORDS_FILE_NAME);
  6895. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6896. #if defined(DEBUG)
  6897. /* Don't use mg_cry_internal here, but only a trace, since this
  6898. * is
  6899. * a typical case. It will occur for every directory
  6900. * without a password file. */
  6901. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6902. #endif
  6903. }
  6904. }
  6905. }
  6906. }
  6907. /* Parsed Authorization header */
  6908. struct ah {
  6909. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6910. };
  6911. /* Return 1 on success. Always initializes the ah structure. */
  6912. static int
  6913. parse_auth_header(struct mg_connection *conn,
  6914. char *buf,
  6915. size_t buf_size,
  6916. struct ah *ah)
  6917. {
  6918. char *name, *value, *s;
  6919. const char *auth_header;
  6920. uint64_t nonce;
  6921. if (!ah || !conn) {
  6922. return 0;
  6923. }
  6924. (void)memset(ah, 0, sizeof(*ah));
  6925. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6926. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6927. return 0;
  6928. }
  6929. /* Make modifiable copy of the auth header */
  6930. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6931. s = buf;
  6932. /* Parse authorization header */
  6933. for (;;) {
  6934. /* Gobble initial spaces */
  6935. while (isspace((unsigned char)*s)) {
  6936. s++;
  6937. }
  6938. name = skip_quoted(&s, "=", " ", 0);
  6939. /* Value is either quote-delimited, or ends at first comma or space.
  6940. */
  6941. if (s[0] == '\"') {
  6942. s++;
  6943. value = skip_quoted(&s, "\"", " ", '\\');
  6944. if (s[0] == ',') {
  6945. s++;
  6946. }
  6947. } else {
  6948. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6949. * spaces */
  6950. }
  6951. if (*name == '\0') {
  6952. break;
  6953. }
  6954. if (!strcmp(name, "username")) {
  6955. ah->user = value;
  6956. } else if (!strcmp(name, "cnonce")) {
  6957. ah->cnonce = value;
  6958. } else if (!strcmp(name, "response")) {
  6959. ah->response = value;
  6960. } else if (!strcmp(name, "uri")) {
  6961. ah->uri = value;
  6962. } else if (!strcmp(name, "qop")) {
  6963. ah->qop = value;
  6964. } else if (!strcmp(name, "nc")) {
  6965. ah->nc = value;
  6966. } else if (!strcmp(name, "nonce")) {
  6967. ah->nonce = value;
  6968. }
  6969. }
  6970. #if !defined(NO_NONCE_CHECK)
  6971. /* Read the nonce from the response. */
  6972. if (ah->nonce == NULL) {
  6973. return 0;
  6974. }
  6975. s = NULL;
  6976. nonce = strtoull(ah->nonce, &s, 10);
  6977. if ((s == NULL) || (*s != 0)) {
  6978. return 0;
  6979. }
  6980. /* Convert the nonce from the client to a number. */
  6981. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6982. /* The converted number corresponds to the time the nounce has been
  6983. * created. This should not be earlier than the server start. */
  6984. /* Server side nonce check is valuable in all situations but one:
  6985. * if the server restarts frequently, but the client should not see
  6986. * that, so the server should accept nonces from previous starts. */
  6987. /* However, the reasonable default is to not accept a nonce from a
  6988. * previous start, so if anyone changed the access rights between
  6989. * two restarts, a new login is required. */
  6990. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6991. /* nonce is from a previous start of the server and no longer valid
  6992. * (replay attack?) */
  6993. return 0;
  6994. }
  6995. /* Check if the nonce is too high, so it has not (yet) been used by the
  6996. * server. */
  6997. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6998. + conn->dom_ctx->nonce_count)) {
  6999. return 0;
  7000. }
  7001. #else
  7002. (void)nonce;
  7003. #endif
  7004. /* CGI needs it as REMOTE_USER */
  7005. if (ah->user != NULL) {
  7006. conn->request_info.remote_user =
  7007. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7008. } else {
  7009. return 0;
  7010. }
  7011. return 1;
  7012. }
  7013. static const char *
  7014. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7015. {
  7016. #if defined(MG_USE_OPEN_FILE)
  7017. const char *eof;
  7018. size_t len;
  7019. const char *memend;
  7020. #else
  7021. (void)p; /* parameter is unused */
  7022. #endif
  7023. if (!filep) {
  7024. return NULL;
  7025. }
  7026. #if defined(MG_USE_OPEN_FILE)
  7027. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7028. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7029. /* Search for \n from p till the end of stream */
  7030. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7031. if (eof != NULL) {
  7032. eof += 1; /* Include \n */
  7033. } else {
  7034. eof = memend; /* Copy remaining data */
  7035. }
  7036. len =
  7037. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7038. memcpy(buf, *p, len);
  7039. buf[len] = '\0';
  7040. *p += len;
  7041. return len ? eof : NULL;
  7042. } else /* filep->access.fp block below */
  7043. #endif
  7044. if (filep->access.fp != NULL) {
  7045. return fgets(buf, (int)size, filep->access.fp);
  7046. } else {
  7047. return NULL;
  7048. }
  7049. }
  7050. /* Define the initial recursion depth for procesesing htpasswd files that
  7051. * include other htpasswd
  7052. * (or even the same) files. It is not difficult to provide a file or files
  7053. * s.t. they force civetweb
  7054. * to infinitely recurse and then crash.
  7055. */
  7056. #define INITIAL_DEPTH 9
  7057. #if INITIAL_DEPTH <= 0
  7058. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7059. #endif
  7060. struct read_auth_file_struct {
  7061. struct mg_connection *conn;
  7062. struct ah ah;
  7063. const char *domain;
  7064. char buf[256 + 256 + 40];
  7065. const char *f_user;
  7066. const char *f_domain;
  7067. const char *f_ha1;
  7068. };
  7069. static int
  7070. read_auth_file(struct mg_file *filep,
  7071. struct read_auth_file_struct *workdata,
  7072. int depth)
  7073. {
  7074. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7075. int is_authorized = 0;
  7076. struct mg_file fp;
  7077. size_t l;
  7078. if (!filep || !workdata || (0 == depth)) {
  7079. return 0;
  7080. }
  7081. /* Loop over passwords file */
  7082. #if defined(MG_USE_OPEN_FILE)
  7083. p = (char *)filep->access.membuf;
  7084. #endif
  7085. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7086. l = strlen(workdata->buf);
  7087. while (l > 0) {
  7088. if (isspace((unsigned char)workdata->buf[l - 1])
  7089. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7090. l--;
  7091. workdata->buf[l] = 0;
  7092. } else
  7093. break;
  7094. }
  7095. if (l < 1) {
  7096. continue;
  7097. }
  7098. workdata->f_user = workdata->buf;
  7099. if (workdata->f_user[0] == ':') {
  7100. /* user names may not contain a ':' and may not be empty,
  7101. * so lines starting with ':' may be used for a special purpose
  7102. */
  7103. if (workdata->f_user[1] == '#') {
  7104. /* :# is a comment */
  7105. continue;
  7106. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7107. if (mg_fopen(workdata->conn,
  7108. workdata->f_user + 9,
  7109. MG_FOPEN_MODE_READ,
  7110. &fp)) {
  7111. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7112. (void)mg_fclose(
  7113. &fp.access); /* ignore error on read only file */
  7114. /* No need to continue processing files once we have a
  7115. * match, since nothing will reset it back
  7116. * to 0.
  7117. */
  7118. if (is_authorized) {
  7119. return is_authorized;
  7120. }
  7121. } else {
  7122. mg_cry_internal(workdata->conn,
  7123. "%s: cannot open authorization file: %s",
  7124. __func__,
  7125. workdata->buf);
  7126. }
  7127. continue;
  7128. }
  7129. /* everything is invalid for the moment (might change in the
  7130. * future) */
  7131. mg_cry_internal(workdata->conn,
  7132. "%s: syntax error in authorization file: %s",
  7133. __func__,
  7134. workdata->buf);
  7135. continue;
  7136. }
  7137. workdata->f_domain = strchr(workdata->f_user, ':');
  7138. if (workdata->f_domain == NULL) {
  7139. mg_cry_internal(workdata->conn,
  7140. "%s: syntax error in authorization file: %s",
  7141. __func__,
  7142. workdata->buf);
  7143. continue;
  7144. }
  7145. *(char *)(workdata->f_domain) = 0;
  7146. (workdata->f_domain)++;
  7147. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7148. if (workdata->f_ha1 == NULL) {
  7149. mg_cry_internal(workdata->conn,
  7150. "%s: syntax error in authorization file: %s",
  7151. __func__,
  7152. workdata->buf);
  7153. continue;
  7154. }
  7155. *(char *)(workdata->f_ha1) = 0;
  7156. (workdata->f_ha1)++;
  7157. if (!strcmp(workdata->ah.user, workdata->f_user)
  7158. && !strcmp(workdata->domain, workdata->f_domain)) {
  7159. return check_password(workdata->conn->request_info.request_method,
  7160. workdata->f_ha1,
  7161. workdata->ah.uri,
  7162. workdata->ah.nonce,
  7163. workdata->ah.nc,
  7164. workdata->ah.cnonce,
  7165. workdata->ah.qop,
  7166. workdata->ah.response);
  7167. }
  7168. }
  7169. return is_authorized;
  7170. }
  7171. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7172. static int
  7173. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7174. {
  7175. struct read_auth_file_struct workdata;
  7176. char buf[MG_BUF_LEN];
  7177. if (!conn || !conn->dom_ctx) {
  7178. return 0;
  7179. }
  7180. memset(&workdata, 0, sizeof(workdata));
  7181. workdata.conn = conn;
  7182. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7183. return 0;
  7184. }
  7185. if (realm) {
  7186. workdata.domain = realm;
  7187. } else {
  7188. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7189. }
  7190. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7191. }
  7192. /* Public function to check http digest authentication header */
  7193. int
  7194. mg_check_digest_access_authentication(struct mg_connection *conn,
  7195. const char *realm,
  7196. const char *filename)
  7197. {
  7198. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7199. int auth;
  7200. if (!conn || !filename) {
  7201. return -1;
  7202. }
  7203. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7204. return -2;
  7205. }
  7206. auth = authorize(conn, &file, realm);
  7207. mg_fclose(&file.access);
  7208. return auth;
  7209. }
  7210. /* Return 1 if request is authorised, 0 otherwise. */
  7211. static int
  7212. check_authorization(struct mg_connection *conn, const char *path)
  7213. {
  7214. char fname[PATH_MAX];
  7215. struct vec uri_vec, filename_vec;
  7216. const char *list;
  7217. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7218. int authorized = 1, truncated;
  7219. if (!conn || !conn->dom_ctx) {
  7220. return 0;
  7221. }
  7222. list = conn->dom_ctx->config[PROTECT_URI];
  7223. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7224. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7225. mg_snprintf(conn,
  7226. &truncated,
  7227. fname,
  7228. sizeof(fname),
  7229. "%.*s",
  7230. (int)filename_vec.len,
  7231. filename_vec.ptr);
  7232. if (truncated
  7233. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7234. mg_cry_internal(conn,
  7235. "%s: cannot open %s: %s",
  7236. __func__,
  7237. fname,
  7238. strerror(errno));
  7239. }
  7240. break;
  7241. }
  7242. }
  7243. if (!is_file_opened(&file.access)) {
  7244. open_auth_file(conn, path, &file);
  7245. }
  7246. if (is_file_opened(&file.access)) {
  7247. authorized = authorize(conn, &file, NULL);
  7248. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7249. }
  7250. return authorized;
  7251. }
  7252. /* Internal function. Assumes conn is valid */
  7253. static void
  7254. send_authorization_request(struct mg_connection *conn, const char *realm)
  7255. {
  7256. char date[64];
  7257. time_t curtime = time(NULL);
  7258. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7259. if (!realm) {
  7260. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7261. }
  7262. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7263. nonce += conn->dom_ctx->nonce_count;
  7264. ++conn->dom_ctx->nonce_count;
  7265. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7266. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7267. conn->status_code = 401;
  7268. conn->must_close = 1;
  7269. gmt_time_string(date, sizeof(date), &curtime);
  7270. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7271. send_no_cache_header(conn);
  7272. send_additional_header(conn);
  7273. mg_printf(conn,
  7274. "Date: %s\r\n"
  7275. "Connection: %s\r\n"
  7276. "Content-Length: 0\r\n"
  7277. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7278. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7279. date,
  7280. suggest_connection_header(conn),
  7281. realm,
  7282. nonce);
  7283. }
  7284. /* Interface function. Parameters are provided by the user, so do
  7285. * at least some basic checks.
  7286. */
  7287. int
  7288. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7289. const char *realm)
  7290. {
  7291. if (conn && conn->dom_ctx) {
  7292. send_authorization_request(conn, realm);
  7293. return 0;
  7294. }
  7295. return -1;
  7296. }
  7297. #if !defined(NO_FILES)
  7298. static int
  7299. is_authorized_for_put(struct mg_connection *conn)
  7300. {
  7301. if (conn) {
  7302. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7303. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7304. int ret = 0;
  7305. if (passfile != NULL
  7306. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7307. ret = authorize(conn, &file, NULL);
  7308. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7309. }
  7310. return ret;
  7311. }
  7312. return 0;
  7313. }
  7314. #endif
  7315. int
  7316. mg_modify_passwords_file(const char *fname,
  7317. const char *domain,
  7318. const char *user,
  7319. const char *pass)
  7320. {
  7321. int found, i;
  7322. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7323. FILE *fp, *fp2;
  7324. found = 0;
  7325. fp = fp2 = NULL;
  7326. /* Regard empty password as no password - remove user record. */
  7327. if ((pass != NULL) && (pass[0] == '\0')) {
  7328. pass = NULL;
  7329. }
  7330. /* Other arguments must not be empty */
  7331. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7332. return 0;
  7333. }
  7334. /* Using the given file format, user name and domain must not contain
  7335. * ':'
  7336. */
  7337. if (strchr(user, ':') != NULL) {
  7338. return 0;
  7339. }
  7340. if (strchr(domain, ':') != NULL) {
  7341. return 0;
  7342. }
  7343. /* Do not allow control characters like newline in user name and domain.
  7344. * Do not allow excessively long names either. */
  7345. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7346. if (iscntrl((unsigned char)user[i])) {
  7347. return 0;
  7348. }
  7349. }
  7350. if (user[i]) {
  7351. return 0;
  7352. }
  7353. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7354. if (iscntrl((unsigned char)domain[i])) {
  7355. return 0;
  7356. }
  7357. }
  7358. if (domain[i]) {
  7359. return 0;
  7360. }
  7361. /* The maximum length of the path to the password file is limited */
  7362. if ((strlen(fname) + 4) >= PATH_MAX) {
  7363. return 0;
  7364. }
  7365. /* Create a temporary file name. Length has been checked before. */
  7366. strcpy(tmp, fname);
  7367. strcat(tmp, ".tmp");
  7368. /* Create the file if does not exist */
  7369. /* Use of fopen here is OK, since fname is only ASCII */
  7370. if ((fp = fopen(fname, "a+")) != NULL) {
  7371. (void)fclose(fp);
  7372. }
  7373. /* Open the given file and temporary file */
  7374. if ((fp = fopen(fname, "r")) == NULL) {
  7375. return 0;
  7376. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7377. fclose(fp);
  7378. return 0;
  7379. }
  7380. /* Copy the stuff to temporary file */
  7381. while (fgets(line, sizeof(line), fp) != NULL) {
  7382. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7383. continue;
  7384. }
  7385. u[255] = 0;
  7386. d[255] = 0;
  7387. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7388. found++;
  7389. if (pass != NULL) {
  7390. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7391. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7392. }
  7393. } else {
  7394. fprintf(fp2, "%s", line);
  7395. }
  7396. }
  7397. /* If new user, just add it */
  7398. if (!found && (pass != NULL)) {
  7399. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7400. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7401. }
  7402. /* Close files */
  7403. fclose(fp);
  7404. fclose(fp2);
  7405. /* Put the temp file in place of real file */
  7406. IGNORE_UNUSED_RESULT(remove(fname));
  7407. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7408. return 1;
  7409. }
  7410. static int
  7411. is_valid_port(unsigned long port)
  7412. {
  7413. return (port <= 0xffff);
  7414. }
  7415. static int
  7416. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7417. {
  7418. struct addrinfo hints, *res, *ressave;
  7419. int func_ret = 0;
  7420. int gai_ret;
  7421. memset(&hints, 0, sizeof(struct addrinfo));
  7422. hints.ai_family = af;
  7423. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7424. if (gai_ret != 0) {
  7425. /* gai_strerror could be used to convert gai_ret to a string */
  7426. /* POSIX return values: see
  7427. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7428. */
  7429. /* Windows return values: see
  7430. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7431. */
  7432. return 0;
  7433. }
  7434. ressave = res;
  7435. while (res) {
  7436. if (dstlen >= (size_t)res->ai_addrlen) {
  7437. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7438. func_ret = 1;
  7439. }
  7440. res = res->ai_next;
  7441. }
  7442. freeaddrinfo(ressave);
  7443. return func_ret;
  7444. }
  7445. static int
  7446. connect_socket(struct mg_context *ctx /* may be NULL */,
  7447. const char *host,
  7448. int port,
  7449. int use_ssl,
  7450. char *ebuf,
  7451. size_t ebuf_len,
  7452. SOCKET *sock /* output: socket, must not be NULL */,
  7453. union usa *sa /* output: socket address, must not be NULL */
  7454. )
  7455. {
  7456. int ip_ver = 0;
  7457. int conn_ret = -1;
  7458. int ret;
  7459. *sock = INVALID_SOCKET;
  7460. memset(sa, 0, sizeof(*sa));
  7461. if (ebuf_len > 0) {
  7462. *ebuf = 0;
  7463. }
  7464. if (host == NULL) {
  7465. mg_snprintf(NULL,
  7466. NULL, /* No truncation check for ebuf */
  7467. ebuf,
  7468. ebuf_len,
  7469. "%s",
  7470. "NULL host");
  7471. return 0;
  7472. }
  7473. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7474. mg_snprintf(NULL,
  7475. NULL, /* No truncation check for ebuf */
  7476. ebuf,
  7477. ebuf_len,
  7478. "%s",
  7479. "invalid port");
  7480. return 0;
  7481. }
  7482. #if !defined(NO_SSL)
  7483. #if !defined(NO_SSL_DL)
  7484. #if defined(OPENSSL_API_1_1)
  7485. if (use_ssl && (TLS_client_method == NULL)) {
  7486. mg_snprintf(NULL,
  7487. NULL, /* No truncation check for ebuf */
  7488. ebuf,
  7489. ebuf_len,
  7490. "%s",
  7491. "SSL is not initialized");
  7492. return 0;
  7493. }
  7494. #else
  7495. if (use_ssl && (SSLv23_client_method == NULL)) {
  7496. mg_snprintf(NULL,
  7497. NULL, /* No truncation check for ebuf */
  7498. ebuf,
  7499. ebuf_len,
  7500. "%s",
  7501. "SSL is not initialized");
  7502. return 0;
  7503. }
  7504. #endif /* OPENSSL_API_1_1 */
  7505. #else
  7506. (void)use_ssl;
  7507. #endif /* NO_SSL_DL */
  7508. #else
  7509. (void)use_ssl;
  7510. #endif /* !defined(NO_SSL) */
  7511. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7512. sa->sin.sin_family = AF_INET;
  7513. sa->sin.sin_port = htons((uint16_t)port);
  7514. ip_ver = 4;
  7515. #if defined(USE_IPV6)
  7516. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7517. sa->sin6.sin6_family = AF_INET6;
  7518. sa->sin6.sin6_port = htons((uint16_t)port);
  7519. ip_ver = 6;
  7520. } else if (host[0] == '[') {
  7521. /* While getaddrinfo on Windows will work with [::1],
  7522. * getaddrinfo on Linux only works with ::1 (without []). */
  7523. size_t l = strlen(host + 1);
  7524. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7525. if (h) {
  7526. h[l - 1] = 0;
  7527. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7528. sa->sin6.sin6_family = AF_INET6;
  7529. sa->sin6.sin6_port = htons((uint16_t)port);
  7530. ip_ver = 6;
  7531. }
  7532. mg_free(h);
  7533. }
  7534. #endif
  7535. }
  7536. if (ip_ver == 0) {
  7537. mg_snprintf(NULL,
  7538. NULL, /* No truncation check for ebuf */
  7539. ebuf,
  7540. ebuf_len,
  7541. "%s",
  7542. "host not found");
  7543. return 0;
  7544. }
  7545. if (ip_ver == 4) {
  7546. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7547. }
  7548. #if defined(USE_IPV6)
  7549. else if (ip_ver == 6) {
  7550. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7551. }
  7552. #endif
  7553. if (*sock == INVALID_SOCKET) {
  7554. mg_snprintf(NULL,
  7555. NULL, /* No truncation check for ebuf */
  7556. ebuf,
  7557. ebuf_len,
  7558. "socket(): %s",
  7559. strerror(ERRNO));
  7560. return 0;
  7561. }
  7562. if (0 != set_non_blocking_mode(*sock)) {
  7563. mg_snprintf(NULL,
  7564. NULL, /* No truncation check for ebuf */
  7565. ebuf,
  7566. ebuf_len,
  7567. "Cannot set socket to non-blocking: %s",
  7568. strerror(ERRNO));
  7569. closesocket(*sock);
  7570. *sock = INVALID_SOCKET;
  7571. return 0;
  7572. }
  7573. set_close_on_exec(*sock, fc(ctx));
  7574. if (ip_ver == 4) {
  7575. /* connected with IPv4 */
  7576. conn_ret = connect(*sock,
  7577. (struct sockaddr *)((void *)&sa->sin),
  7578. sizeof(sa->sin));
  7579. }
  7580. #if defined(USE_IPV6)
  7581. else if (ip_ver == 6) {
  7582. /* connected with IPv6 */
  7583. conn_ret = connect(*sock,
  7584. (struct sockaddr *)((void *)&sa->sin6),
  7585. sizeof(sa->sin6));
  7586. }
  7587. #endif
  7588. #if defined(_WIN32)
  7589. if (conn_ret != 0) {
  7590. DWORD err = WSAGetLastError(); /* could return WSAEWOULDBLOCK */
  7591. conn_ret = (int)err;
  7592. #if !defined(EINPROGRESS)
  7593. #define EINPROGRESS (WSAEWOULDBLOCK) /* Winsock equivalent */
  7594. #endif /* if !defined(EINPROGRESS) */
  7595. }
  7596. #endif
  7597. if ((conn_ret != 0) && (conn_ret != EINPROGRESS)) {
  7598. /* Data for getsockopt */
  7599. int sockerr = -1;
  7600. void *psockerr = &sockerr;
  7601. #if defined(_WIN32)
  7602. int len = (int)sizeof(sockerr);
  7603. #else
  7604. socklen_t len = (socklen_t)sizeof(sockerr);
  7605. #endif
  7606. /* Data for poll */
  7607. struct mg_pollfd pfd[1];
  7608. int pollres;
  7609. int ms_wait = 10000; /* 10 second timeout */
  7610. /* For a non-blocking socket, the connect sequence is:
  7611. * 1) call connect (will not block)
  7612. * 2) wait until the socket is ready for writing (select or poll)
  7613. * 3) check connection state with getsockopt
  7614. */
  7615. pfd[0].fd = *sock;
  7616. pfd[0].events = POLLOUT;
  7617. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  7618. if (pollres != 1) {
  7619. /* Not connected */
  7620. mg_snprintf(NULL,
  7621. NULL, /* No truncation check for ebuf */
  7622. ebuf,
  7623. ebuf_len,
  7624. "connect(%s:%d): timeout",
  7625. host,
  7626. port);
  7627. closesocket(*sock);
  7628. *sock = INVALID_SOCKET;
  7629. return 0;
  7630. }
  7631. #if defined(_WIN32)
  7632. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7633. #else
  7634. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7635. #endif
  7636. if ((ret != 0) || (sockerr != 0)) {
  7637. /* Not connected */
  7638. mg_snprintf(NULL,
  7639. NULL, /* No truncation check for ebuf */
  7640. ebuf,
  7641. ebuf_len,
  7642. "connect(%s:%d): error %s",
  7643. host,
  7644. port,
  7645. strerror(sockerr));
  7646. closesocket(*sock);
  7647. *sock = INVALID_SOCKET;
  7648. return 0;
  7649. }
  7650. }
  7651. return 1;
  7652. }
  7653. int
  7654. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7655. {
  7656. static const char *dont_escape = "._-$,;~()";
  7657. static const char *hex = "0123456789abcdef";
  7658. char *pos = dst;
  7659. const char *end = dst + dst_len - 1;
  7660. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7661. if (isalnum((unsigned char)*src)
  7662. || (strchr(dont_escape, *src) != NULL)) {
  7663. *pos = *src;
  7664. } else if (pos + 2 < end) {
  7665. pos[0] = '%';
  7666. pos[1] = hex[(unsigned char)*src >> 4];
  7667. pos[2] = hex[(unsigned char)*src & 0xf];
  7668. pos += 2;
  7669. } else {
  7670. break;
  7671. }
  7672. }
  7673. *pos = '\0';
  7674. return (*src == '\0') ? (int)(pos - dst) : -1;
  7675. }
  7676. /* Return 0 on success, non-zero if an error occurs. */
  7677. static int
  7678. print_dir_entry(struct de *de)
  7679. {
  7680. size_t namesize, escsize, i;
  7681. char *href, *esc, *p;
  7682. char size[64], mod[64];
  7683. #if defined(REENTRANT_TIME)
  7684. struct tm _tm;
  7685. struct tm *tm = &_tm;
  7686. #else
  7687. struct tm *tm;
  7688. #endif
  7689. /* Estimate worst case size for encoding and escaping */
  7690. namesize = strlen(de->file_name) + 1;
  7691. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7692. href = (char *)mg_malloc(namesize * 3 + escsize);
  7693. if (href == NULL) {
  7694. return -1;
  7695. }
  7696. mg_url_encode(de->file_name, href, namesize * 3);
  7697. esc = NULL;
  7698. if (escsize > 0) {
  7699. /* HTML escaping needed */
  7700. esc = href + namesize * 3;
  7701. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7702. mg_strlcpy(p, de->file_name + i, 2);
  7703. if (*p == '&') {
  7704. strcpy(p, "&amp;");
  7705. } else if (*p == '<') {
  7706. strcpy(p, "&lt;");
  7707. } else if (*p == '>') {
  7708. strcpy(p, "&gt;");
  7709. }
  7710. }
  7711. }
  7712. if (de->file.is_directory) {
  7713. mg_snprintf(de->conn,
  7714. NULL, /* Buffer is big enough */
  7715. size,
  7716. sizeof(size),
  7717. "%s",
  7718. "[DIRECTORY]");
  7719. } else {
  7720. /* We use (signed) cast below because MSVC 6 compiler cannot
  7721. * convert unsigned __int64 to double. Sigh. */
  7722. if (de->file.size < 1024) {
  7723. mg_snprintf(de->conn,
  7724. NULL, /* Buffer is big enough */
  7725. size,
  7726. sizeof(size),
  7727. "%d",
  7728. (int)de->file.size);
  7729. } else if (de->file.size < 0x100000) {
  7730. mg_snprintf(de->conn,
  7731. NULL, /* Buffer is big enough */
  7732. size,
  7733. sizeof(size),
  7734. "%.1fk",
  7735. (double)de->file.size / 1024.0);
  7736. } else if (de->file.size < 0x40000000) {
  7737. mg_snprintf(de->conn,
  7738. NULL, /* Buffer is big enough */
  7739. size,
  7740. sizeof(size),
  7741. "%.1fM",
  7742. (double)de->file.size / 1048576);
  7743. } else {
  7744. mg_snprintf(de->conn,
  7745. NULL, /* Buffer is big enough */
  7746. size,
  7747. sizeof(size),
  7748. "%.1fG",
  7749. (double)de->file.size / 1073741824);
  7750. }
  7751. }
  7752. /* Note: mg_snprintf will not cause a buffer overflow above.
  7753. * So, string truncation checks are not required here. */
  7754. #if defined(REENTRANT_TIME)
  7755. localtime_r(&de->file.last_modified, tm);
  7756. #else
  7757. tm = localtime(&de->file.last_modified);
  7758. #endif
  7759. if (tm != NULL) {
  7760. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7761. } else {
  7762. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7763. mod[sizeof(mod) - 1] = '\0';
  7764. }
  7765. mg_printf(de->conn,
  7766. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7767. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7768. href,
  7769. de->file.is_directory ? "/" : "",
  7770. esc ? esc : de->file_name,
  7771. de->file.is_directory ? "/" : "",
  7772. mod,
  7773. size);
  7774. mg_free(href);
  7775. return 0;
  7776. }
  7777. /* This function is called from send_directory() and used for
  7778. * sorting directory entries by size, or name, or modification time.
  7779. * On windows, __cdecl specification is needed in case if project is built
  7780. * with __stdcall convention. qsort always requires __cdels callback. */
  7781. static int WINCDECL
  7782. compare_dir_entries(const void *p1, const void *p2)
  7783. {
  7784. if (p1 && p2) {
  7785. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7786. const char *query_string = a->conn->request_info.query_string;
  7787. int cmp_result = 0;
  7788. if ((query_string == NULL) || (query_string[0] == '\0')) {
  7789. query_string = "n";
  7790. }
  7791. if (a->file.is_directory && !b->file.is_directory) {
  7792. return -1; /* Always put directories on top */
  7793. } else if (!a->file.is_directory && b->file.is_directory) {
  7794. return 1; /* Always put directories on top */
  7795. } else if (*query_string == 'n') {
  7796. cmp_result = strcmp(a->file_name, b->file_name);
  7797. } else if (*query_string == 's') {
  7798. cmp_result = (a->file.size == b->file.size)
  7799. ? 0
  7800. : ((a->file.size > b->file.size) ? 1 : -1);
  7801. } else if (*query_string == 'd') {
  7802. cmp_result =
  7803. (a->file.last_modified == b->file.last_modified)
  7804. ? 0
  7805. : ((a->file.last_modified > b->file.last_modified) ? 1
  7806. : -1);
  7807. }
  7808. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7809. }
  7810. return 0;
  7811. }
  7812. static int
  7813. must_hide_file(struct mg_connection *conn, const char *path)
  7814. {
  7815. if (conn && conn->dom_ctx) {
  7816. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7817. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7818. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7819. || ((pattern != NULL)
  7820. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7821. }
  7822. return 0;
  7823. }
  7824. static int
  7825. scan_directory(struct mg_connection *conn,
  7826. const char *dir,
  7827. void *data,
  7828. int (*cb)(struct de *, void *))
  7829. {
  7830. char path[PATH_MAX];
  7831. struct dirent *dp;
  7832. DIR *dirp;
  7833. struct de de;
  7834. int truncated;
  7835. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7836. return 0;
  7837. } else {
  7838. de.conn = conn;
  7839. while ((dp = mg_readdir(dirp)) != NULL) {
  7840. /* Do not show current dir and hidden files */
  7841. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7842. || must_hide_file(conn, dp->d_name)) {
  7843. continue;
  7844. }
  7845. mg_snprintf(
  7846. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7847. /* If we don't memset stat structure to zero, mtime will have
  7848. * garbage and strftime() will segfault later on in
  7849. * print_dir_entry(). memset is required only if mg_stat()
  7850. * fails. For more details, see
  7851. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7852. memset(&de.file, 0, sizeof(de.file));
  7853. if (truncated) {
  7854. /* If the path is not complete, skip processing. */
  7855. continue;
  7856. }
  7857. if (!mg_stat(conn, path, &de.file)) {
  7858. mg_cry_internal(conn,
  7859. "%s: mg_stat(%s) failed: %s",
  7860. __func__,
  7861. path,
  7862. strerror(ERRNO));
  7863. }
  7864. de.file_name = dp->d_name;
  7865. cb(&de, data);
  7866. }
  7867. (void)mg_closedir(dirp);
  7868. }
  7869. return 1;
  7870. }
  7871. #if !defined(NO_FILES)
  7872. static int
  7873. remove_directory(struct mg_connection *conn, const char *dir)
  7874. {
  7875. char path[PATH_MAX];
  7876. struct dirent *dp;
  7877. DIR *dirp;
  7878. struct de de;
  7879. int truncated;
  7880. int ok = 1;
  7881. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7882. return 0;
  7883. } else {
  7884. de.conn = conn;
  7885. while ((dp = mg_readdir(dirp)) != NULL) {
  7886. /* Do not show current dir (but show hidden files as they will
  7887. * also be removed) */
  7888. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7889. continue;
  7890. }
  7891. mg_snprintf(
  7892. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7893. /* If we don't memset stat structure to zero, mtime will have
  7894. * garbage and strftime() will segfault later on in
  7895. * print_dir_entry(). memset is required only if mg_stat()
  7896. * fails. For more details, see
  7897. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7898. memset(&de.file, 0, sizeof(de.file));
  7899. if (truncated) {
  7900. /* Do not delete anything shorter */
  7901. ok = 0;
  7902. continue;
  7903. }
  7904. if (!mg_stat(conn, path, &de.file)) {
  7905. mg_cry_internal(conn,
  7906. "%s: mg_stat(%s) failed: %s",
  7907. __func__,
  7908. path,
  7909. strerror(ERRNO));
  7910. ok = 0;
  7911. }
  7912. if (de.file.is_directory) {
  7913. if (remove_directory(conn, path) == 0) {
  7914. ok = 0;
  7915. }
  7916. } else {
  7917. /* This will fail file is the file is in memory */
  7918. if (mg_remove(conn, path) == 0) {
  7919. ok = 0;
  7920. }
  7921. }
  7922. }
  7923. (void)mg_closedir(dirp);
  7924. IGNORE_UNUSED_RESULT(rmdir(dir));
  7925. }
  7926. return ok;
  7927. }
  7928. #endif
  7929. struct dir_scan_data {
  7930. struct de *entries;
  7931. unsigned int num_entries;
  7932. unsigned int arr_size;
  7933. };
  7934. /* Behaves like realloc(), but frees original pointer on failure */
  7935. static void *
  7936. realloc2(void *ptr, size_t size)
  7937. {
  7938. void *new_ptr = mg_realloc(ptr, size);
  7939. if (new_ptr == NULL) {
  7940. mg_free(ptr);
  7941. }
  7942. return new_ptr;
  7943. }
  7944. static int
  7945. dir_scan_callback(struct de *de, void *data)
  7946. {
  7947. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7948. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7949. dsd->arr_size *= 2;
  7950. dsd->entries =
  7951. (struct de *)realloc2(dsd->entries,
  7952. dsd->arr_size * sizeof(dsd->entries[0]));
  7953. }
  7954. if (dsd->entries == NULL) {
  7955. /* TODO(lsm, low): propagate an error to the caller */
  7956. dsd->num_entries = 0;
  7957. } else {
  7958. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7959. dsd->entries[dsd->num_entries].file = de->file;
  7960. dsd->entries[dsd->num_entries].conn = de->conn;
  7961. dsd->num_entries++;
  7962. }
  7963. return 0;
  7964. }
  7965. static void
  7966. handle_directory_request(struct mg_connection *conn, const char *dir)
  7967. {
  7968. unsigned int i;
  7969. int sort_direction;
  7970. struct dir_scan_data data = {NULL, 0, 128};
  7971. char date[64], *esc, *p;
  7972. const char *title;
  7973. time_t curtime = time(NULL);
  7974. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7975. mg_send_http_error(conn,
  7976. 500,
  7977. "Error: Cannot open directory\nopendir(%s): %s",
  7978. dir,
  7979. strerror(ERRNO));
  7980. return;
  7981. }
  7982. gmt_time_string(date, sizeof(date), &curtime);
  7983. if (!conn) {
  7984. return;
  7985. }
  7986. esc = NULL;
  7987. title = conn->request_info.local_uri;
  7988. if (title[strcspn(title, "&<>")]) {
  7989. /* HTML escaping needed */
  7990. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  7991. if (esc) {
  7992. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  7993. mg_strlcpy(p, title + i, 2);
  7994. if (*p == '&') {
  7995. strcpy(p, "&amp;");
  7996. } else if (*p == '<') {
  7997. strcpy(p, "&lt;");
  7998. } else if (*p == '>') {
  7999. strcpy(p, "&gt;");
  8000. }
  8001. }
  8002. } else {
  8003. title = "";
  8004. }
  8005. }
  8006. sort_direction = ((conn->request_info.query_string != NULL)
  8007. && (conn->request_info.query_string[0] != '\0')
  8008. && (conn->request_info.query_string[1] == 'd'))
  8009. ? 'a'
  8010. : 'd';
  8011. conn->must_close = 1;
  8012. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8013. send_static_cache_header(conn);
  8014. send_additional_header(conn);
  8015. mg_printf(conn,
  8016. "Date: %s\r\n"
  8017. "Connection: close\r\n"
  8018. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8019. date);
  8020. mg_printf(conn,
  8021. "<html><head><title>Index of %s</title>"
  8022. "<style>th {text-align: left;}</style></head>"
  8023. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8024. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8025. "<th><a href=\"?d%c\">Modified</a></th>"
  8026. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8027. "<tr><td colspan=\"3\"><hr></td></tr>",
  8028. esc ? esc : title,
  8029. esc ? esc : title,
  8030. sort_direction,
  8031. sort_direction,
  8032. sort_direction);
  8033. mg_free(esc);
  8034. /* Print first entry - link to a parent directory */
  8035. mg_printf(conn,
  8036. "<tr><td><a href=\"%s\">%s</a></td>"
  8037. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8038. "..",
  8039. "Parent directory",
  8040. "-",
  8041. "-");
  8042. /* Sort and print directory entries */
  8043. if (data.entries != NULL) {
  8044. qsort(data.entries,
  8045. (size_t)data.num_entries,
  8046. sizeof(data.entries[0]),
  8047. compare_dir_entries);
  8048. for (i = 0; i < data.num_entries; i++) {
  8049. print_dir_entry(&data.entries[i]);
  8050. mg_free(data.entries[i].file_name);
  8051. }
  8052. mg_free(data.entries);
  8053. }
  8054. mg_printf(conn, "%s", "</table></pre></body></html>");
  8055. conn->status_code = 200;
  8056. }
  8057. /* Send len bytes from the opened file to the client. */
  8058. static void
  8059. send_file_data(struct mg_connection *conn,
  8060. struct mg_file *filep,
  8061. int64_t offset,
  8062. int64_t len)
  8063. {
  8064. char buf[MG_BUF_LEN];
  8065. int to_read, num_read, num_written;
  8066. int64_t size;
  8067. if (!filep || !conn) {
  8068. return;
  8069. }
  8070. /* Sanity check the offset */
  8071. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8072. : (int64_t)(filep->stat.size);
  8073. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8074. #if defined(MG_USE_OPEN_FILE)
  8075. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8076. /* file stored in memory */
  8077. if (len > size - offset) {
  8078. len = size - offset;
  8079. }
  8080. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8081. } else /* else block below */
  8082. #endif
  8083. if (len > 0 && filep->access.fp != NULL) {
  8084. /* file stored on disk */
  8085. #if defined(__linux__)
  8086. /* sendfile is only available for Linux */
  8087. if ((conn->ssl == 0) && (conn->throttle == 0)
  8088. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8089. "yes"))) {
  8090. off_t sf_offs = (off_t)offset;
  8091. ssize_t sf_sent;
  8092. int sf_file = fileno(filep->access.fp);
  8093. int loop_cnt = 0;
  8094. do {
  8095. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8096. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8097. size_t sf_tosend =
  8098. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8099. sf_sent =
  8100. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8101. if (sf_sent > 0) {
  8102. len -= sf_sent;
  8103. offset += sf_sent;
  8104. } else if (loop_cnt == 0) {
  8105. /* This file can not be sent using sendfile.
  8106. * This might be the case for pseudo-files in the
  8107. * /sys/ and /proc/ file system.
  8108. * Use the regular user mode copy code instead. */
  8109. break;
  8110. } else if (sf_sent == 0) {
  8111. /* No error, but 0 bytes sent. May be EOF? */
  8112. return;
  8113. }
  8114. loop_cnt++;
  8115. } while ((len > 0) && (sf_sent >= 0));
  8116. if (sf_sent > 0) {
  8117. return; /* OK */
  8118. }
  8119. /* sf_sent<0 means error, thus fall back to the classic way */
  8120. /* This is always the case, if sf_file is not a "normal" file,
  8121. * e.g., for sending data from the output of a CGI process. */
  8122. offset = (int64_t)sf_offs;
  8123. }
  8124. #endif
  8125. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8126. mg_cry_internal(conn,
  8127. "%s: fseeko() failed: %s",
  8128. __func__,
  8129. strerror(ERRNO));
  8130. mg_send_http_error(
  8131. conn,
  8132. 500,
  8133. "%s",
  8134. "Error: Unable to access file at requested position.");
  8135. } else {
  8136. while (len > 0) {
  8137. /* Calculate how much to read from the file in the buffer */
  8138. to_read = sizeof(buf);
  8139. if ((int64_t)to_read > len) {
  8140. to_read = (int)len;
  8141. }
  8142. /* Read from file, exit the loop on error */
  8143. if ((num_read =
  8144. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8145. <= 0) {
  8146. break;
  8147. }
  8148. /* Send read bytes to the client, exit the loop on error */
  8149. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8150. != num_read) {
  8151. break;
  8152. }
  8153. /* Both read and were successful, adjust counters */
  8154. len -= num_written;
  8155. }
  8156. }
  8157. }
  8158. }
  8159. static int
  8160. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8161. {
  8162. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8163. }
  8164. static void
  8165. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8166. {
  8167. if ((filestat != NULL) && (buf != NULL)) {
  8168. mg_snprintf(NULL,
  8169. NULL, /* All calls to construct_etag use 64 byte buffer */
  8170. buf,
  8171. buf_len,
  8172. "\"%lx.%" INT64_FMT "\"",
  8173. (unsigned long)filestat->last_modified,
  8174. filestat->size);
  8175. }
  8176. }
  8177. static void
  8178. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8179. {
  8180. if (filep != NULL && filep->fp != NULL) {
  8181. #if defined(_WIN32)
  8182. (void)conn; /* Unused. */
  8183. #else
  8184. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8185. mg_cry_internal(conn,
  8186. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8187. __func__,
  8188. strerror(ERRNO));
  8189. }
  8190. #endif
  8191. }
  8192. }
  8193. #if defined(USE_ZLIB)
  8194. #include "mod_zlib.inl"
  8195. #endif
  8196. static void
  8197. handle_static_file_request(struct mg_connection *conn,
  8198. const char *path,
  8199. struct mg_file *filep,
  8200. const char *mime_type,
  8201. const char *additional_headers)
  8202. {
  8203. char date[64], lm[64], etag[64];
  8204. char range[128]; /* large enough, so there will be no overflow */
  8205. const char *msg = "OK", *hdr;
  8206. time_t curtime = time(NULL);
  8207. int64_t cl, r1, r2;
  8208. struct vec mime_vec;
  8209. int n, truncated;
  8210. char gz_path[PATH_MAX];
  8211. const char *encoding = "";
  8212. const char *cors_orig_cfg;
  8213. const char *cors1, *cors2, *cors3;
  8214. int is_head_request;
  8215. #if defined(USE_ZLIB)
  8216. /* Compression is allowed, unless there is a reason not to use compression.
  8217. * If the file is already compressed, too small or a "range" request was
  8218. * made, on the fly compression is not possible. */
  8219. int allow_on_the_fly_compression = 1;
  8220. #endif
  8221. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8222. return;
  8223. }
  8224. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8225. if (mime_type == NULL) {
  8226. get_mime_type(conn, path, &mime_vec);
  8227. } else {
  8228. mime_vec.ptr = mime_type;
  8229. mime_vec.len = strlen(mime_type);
  8230. }
  8231. if (filep->stat.size > INT64_MAX) {
  8232. mg_send_http_error(conn,
  8233. 500,
  8234. "Error: File size is too large to send\n%" INT64_FMT,
  8235. filep->stat.size);
  8236. return;
  8237. }
  8238. cl = (int64_t)filep->stat.size;
  8239. conn->status_code = 200;
  8240. range[0] = '\0';
  8241. #if defined(USE_ZLIB)
  8242. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8243. * it's important to rewrite the filename after resolving
  8244. * the mime type from it, to preserve the actual file's type */
  8245. if (!conn->accept_gzip) {
  8246. allow_on_the_fly_compression = 0;
  8247. }
  8248. #endif
  8249. if (filep->stat.is_gzipped) {
  8250. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8251. if (truncated) {
  8252. mg_send_http_error(conn,
  8253. 500,
  8254. "Error: Path of zipped file too long (%s)",
  8255. path);
  8256. return;
  8257. }
  8258. path = gz_path;
  8259. encoding = "Content-Encoding: gzip\r\n";
  8260. #if defined(USE_ZLIB)
  8261. /* File is already compressed. No "on the fly" compression. */
  8262. allow_on_the_fly_compression = 0;
  8263. #endif
  8264. }
  8265. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8266. mg_send_http_error(conn,
  8267. 500,
  8268. "Error: Cannot open file\nfopen(%s): %s",
  8269. path,
  8270. strerror(ERRNO));
  8271. return;
  8272. }
  8273. fclose_on_exec(&filep->access, conn);
  8274. /* If "Range" request was made: parse header, send only selected part
  8275. * of the file. */
  8276. r1 = r2 = 0;
  8277. hdr = mg_get_header(conn, "Range");
  8278. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  8279. && (r1 >= 0) && (r2 >= 0)) {
  8280. /* actually, range requests don't play well with a pre-gzipped
  8281. * file (since the range is specified in the uncompressed space) */
  8282. if (filep->stat.is_gzipped) {
  8283. mg_send_http_error(
  8284. conn,
  8285. 416, /* 416 = Range Not Satisfiable */
  8286. "%s",
  8287. "Error: Range requests in gzipped files are not supported");
  8288. (void)mg_fclose(
  8289. &filep->access); /* ignore error on read only file */
  8290. return;
  8291. }
  8292. conn->status_code = 206;
  8293. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8294. mg_snprintf(conn,
  8295. NULL, /* range buffer is big enough */
  8296. range,
  8297. sizeof(range),
  8298. "Content-Range: bytes "
  8299. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8300. r1,
  8301. r1 + cl - 1,
  8302. filep->stat.size);
  8303. msg = "Partial Content";
  8304. #if defined(USE_ZLIB)
  8305. /* Do not compress ranges. */
  8306. allow_on_the_fly_compression = 0;
  8307. #endif
  8308. }
  8309. /* Do not compress small files. Small files do not benefit from file
  8310. * compression, but there is still some overhead. */
  8311. #if defined(USE_ZLIB)
  8312. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8313. /* File is below the size limit. */
  8314. allow_on_the_fly_compression = 0;
  8315. }
  8316. #endif
  8317. /* Standard CORS header */
  8318. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8319. hdr = mg_get_header(conn, "Origin");
  8320. if (cors_orig_cfg && *cors_orig_cfg && hdr) {
  8321. /* Cross-origin resource sharing (CORS), see
  8322. * http://www.html5rocks.com/en/tutorials/cors/,
  8323. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8324. * -
  8325. * preflight is not supported for files. */
  8326. cors1 = "Access-Control-Allow-Origin: ";
  8327. cors2 = cors_orig_cfg;
  8328. cors3 = "\r\n";
  8329. } else {
  8330. cors1 = cors2 = cors3 = "";
  8331. }
  8332. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8333. * according to
  8334. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8335. gmt_time_string(date, sizeof(date), &curtime);
  8336. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8337. construct_etag(etag, sizeof(etag), &filep->stat);
  8338. /* Send header */
  8339. (void)mg_printf(conn,
  8340. "HTTP/1.1 %d %s\r\n"
  8341. "%s%s%s" /* CORS */
  8342. "Date: %s\r\n"
  8343. "Last-Modified: %s\r\n"
  8344. "Etag: %s\r\n"
  8345. "Content-Type: %.*s\r\n"
  8346. "Connection: %s\r\n",
  8347. conn->status_code,
  8348. msg,
  8349. cors1,
  8350. cors2,
  8351. cors3,
  8352. date,
  8353. lm,
  8354. etag,
  8355. (int)mime_vec.len,
  8356. mime_vec.ptr,
  8357. suggest_connection_header(conn));
  8358. send_static_cache_header(conn);
  8359. send_additional_header(conn);
  8360. #if defined(USE_ZLIB)
  8361. /* On the fly compression allowed */
  8362. if (allow_on_the_fly_compression) {
  8363. /* For on the fly compression, we don't know the content size in
  8364. * advance, so we have to use chunked encoding */
  8365. (void)mg_printf(conn,
  8366. "Content-Encoding: gzip\r\n"
  8367. "Transfer-Encoding: chunked\r\n");
  8368. } else
  8369. #endif
  8370. {
  8371. /* Without on-the-fly compression, we know the content-length
  8372. * and we can use ranges (with on-the-fly compression we cannot).
  8373. * So we send these response headers only in this case. */
  8374. (void)mg_printf(conn,
  8375. "Content-Length: %" INT64_FMT "\r\n"
  8376. "Accept-Ranges: bytes\r\n"
  8377. "%s" /* range */
  8378. "%s" /* encoding */,
  8379. cl,
  8380. range,
  8381. encoding);
  8382. }
  8383. /* The previous code must not add any header starting with X- to make
  8384. * sure no one of the additional_headers is included twice */
  8385. if (additional_headers != NULL) {
  8386. (void)mg_printf(conn,
  8387. "%.*s\r\n\r\n",
  8388. (int)strlen(additional_headers),
  8389. additional_headers);
  8390. } else {
  8391. (void)mg_printf(conn, "\r\n");
  8392. }
  8393. if (!is_head_request) {
  8394. #if defined(USE_ZLIB)
  8395. if (allow_on_the_fly_compression) {
  8396. /* Compress and send */
  8397. send_compressed_data(conn, filep);
  8398. } else
  8399. #endif
  8400. {
  8401. /* Send file directly */
  8402. send_file_data(conn, filep, r1, cl);
  8403. }
  8404. }
  8405. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8406. }
  8407. int
  8408. mg_send_file_body(struct mg_connection *conn, const char *path)
  8409. {
  8410. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8411. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8412. return -1;
  8413. }
  8414. fclose_on_exec(&file.access, conn);
  8415. send_file_data(conn, &file, 0, INT64_MAX);
  8416. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8417. return 0; /* >= 0 for OK */
  8418. }
  8419. #if !defined(NO_CACHING)
  8420. /* Return True if we should reply 304 Not Modified. */
  8421. static int
  8422. is_not_modified(const struct mg_connection *conn,
  8423. const struct mg_file_stat *filestat)
  8424. {
  8425. char etag[64];
  8426. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8427. const char *inm = mg_get_header(conn, "If-None-Match");
  8428. construct_etag(etag, sizeof(etag), filestat);
  8429. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8430. || ((ims != NULL)
  8431. && (filestat->last_modified <= parse_date_string(ims)));
  8432. }
  8433. static void
  8434. handle_not_modified_static_file_request(struct mg_connection *conn,
  8435. struct mg_file *filep)
  8436. {
  8437. char date[64], lm[64], etag[64];
  8438. time_t curtime = time(NULL);
  8439. if ((conn == NULL) || (filep == NULL)) {
  8440. return;
  8441. }
  8442. conn->status_code = 304;
  8443. gmt_time_string(date, sizeof(date), &curtime);
  8444. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8445. construct_etag(etag, sizeof(etag), &filep->stat);
  8446. (void)mg_printf(conn,
  8447. "HTTP/1.1 %d %s\r\n"
  8448. "Date: %s\r\n",
  8449. conn->status_code,
  8450. mg_get_response_code_text(conn, conn->status_code),
  8451. date);
  8452. send_static_cache_header(conn);
  8453. send_additional_header(conn);
  8454. (void)mg_printf(conn,
  8455. "Last-Modified: %s\r\n"
  8456. "Etag: %s\r\n"
  8457. "Connection: %s\r\n"
  8458. "\r\n",
  8459. lm,
  8460. etag,
  8461. suggest_connection_header(conn));
  8462. }
  8463. #endif
  8464. void
  8465. mg_send_file(struct mg_connection *conn, const char *path)
  8466. {
  8467. mg_send_mime_file2(conn, path, NULL, NULL);
  8468. }
  8469. void
  8470. mg_send_mime_file(struct mg_connection *conn,
  8471. const char *path,
  8472. const char *mime_type)
  8473. {
  8474. mg_send_mime_file2(conn, path, mime_type, NULL);
  8475. }
  8476. void
  8477. mg_send_mime_file2(struct mg_connection *conn,
  8478. const char *path,
  8479. const char *mime_type,
  8480. const char *additional_headers)
  8481. {
  8482. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8483. if (!conn) {
  8484. /* No conn */
  8485. return;
  8486. }
  8487. if (mg_stat(conn, path, &file.stat)) {
  8488. #if !defined(NO_CACHING)
  8489. if (is_not_modified(conn, &file.stat)) {
  8490. /* Send 304 "Not Modified" - this must not send any body data */
  8491. handle_not_modified_static_file_request(conn, &file);
  8492. } else
  8493. #endif /* NO_CACHING */
  8494. if (file.stat.is_directory) {
  8495. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8496. "yes")) {
  8497. handle_directory_request(conn, path);
  8498. } else {
  8499. mg_send_http_error(conn,
  8500. 403,
  8501. "%s",
  8502. "Error: Directory listing denied");
  8503. }
  8504. } else {
  8505. handle_static_file_request(
  8506. conn, path, &file, mime_type, additional_headers);
  8507. }
  8508. } else {
  8509. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8510. }
  8511. }
  8512. /* For a given PUT path, create all intermediate subdirectories.
  8513. * Return 0 if the path itself is a directory.
  8514. * Return 1 if the path leads to a file.
  8515. * Return -1 for if the path is too long.
  8516. * Return -2 if path can not be created.
  8517. */
  8518. static int
  8519. put_dir(struct mg_connection *conn, const char *path)
  8520. {
  8521. char buf[PATH_MAX];
  8522. const char *s, *p;
  8523. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8524. size_t len;
  8525. int res = 1;
  8526. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8527. len = (size_t)(p - path);
  8528. if (len >= sizeof(buf)) {
  8529. /* path too long */
  8530. res = -1;
  8531. break;
  8532. }
  8533. memcpy(buf, path, len);
  8534. buf[len] = '\0';
  8535. /* Try to create intermediate directory */
  8536. DEBUG_TRACE("mkdir(%s)", buf);
  8537. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8538. /* path does not exixt and can not be created */
  8539. res = -2;
  8540. break;
  8541. }
  8542. /* Is path itself a directory? */
  8543. if (p[1] == '\0') {
  8544. res = 0;
  8545. }
  8546. }
  8547. return res;
  8548. }
  8549. static void
  8550. remove_bad_file(const struct mg_connection *conn, const char *path)
  8551. {
  8552. int r = mg_remove(conn, path);
  8553. if (r != 0) {
  8554. mg_cry_internal(conn,
  8555. "%s: Cannot remove invalid file %s",
  8556. __func__,
  8557. path);
  8558. }
  8559. }
  8560. long long
  8561. mg_store_body(struct mg_connection *conn, const char *path)
  8562. {
  8563. char buf[MG_BUF_LEN];
  8564. long long len = 0;
  8565. int ret, n;
  8566. struct mg_file fi;
  8567. if (conn->consumed_content != 0) {
  8568. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8569. return -11;
  8570. }
  8571. ret = put_dir(conn, path);
  8572. if (ret < 0) {
  8573. /* -1 for path too long,
  8574. * -2 for path can not be created. */
  8575. return ret;
  8576. }
  8577. if (ret != 1) {
  8578. /* Return 0 means, path itself is a directory. */
  8579. return 0;
  8580. }
  8581. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8582. return -12;
  8583. }
  8584. ret = mg_read(conn, buf, sizeof(buf));
  8585. while (ret > 0) {
  8586. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8587. if (n != ret) {
  8588. (void)mg_fclose(
  8589. &fi.access); /* File is bad and will be removed anyway. */
  8590. remove_bad_file(conn, path);
  8591. return -13;
  8592. }
  8593. len += ret;
  8594. ret = mg_read(conn, buf, sizeof(buf));
  8595. }
  8596. /* File is open for writing. If fclose fails, there was probably an
  8597. * error flushing the buffer to disk, so the file on disk might be
  8598. * broken. Delete it and return an error to the caller. */
  8599. if (mg_fclose(&fi.access) != 0) {
  8600. remove_bad_file(conn, path);
  8601. return -14;
  8602. }
  8603. return len;
  8604. }
  8605. /* Parse a buffer:
  8606. * Forward the string pointer till the end of a word, then
  8607. * terminate it and forward till the begin of the next word.
  8608. */
  8609. static int
  8610. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8611. {
  8612. /* Forward until a space is found - use isgraph here */
  8613. /* See http://www.cplusplus.com/reference/cctype/ */
  8614. while (isgraph((unsigned char)**ppw)) {
  8615. (*ppw)++;
  8616. }
  8617. /* Check end of word */
  8618. if (eol) {
  8619. /* must be a end of line */
  8620. if ((**ppw != '\r') && (**ppw != '\n')) {
  8621. return -1;
  8622. }
  8623. } else {
  8624. /* must be a end of a word, but not a line */
  8625. if (**ppw != ' ') {
  8626. return -1;
  8627. }
  8628. }
  8629. /* Terminate and forward to the next word */
  8630. do {
  8631. **ppw = 0;
  8632. (*ppw)++;
  8633. } while (isspace((unsigned char)**ppw));
  8634. /* Check after term */
  8635. if (!eol) {
  8636. /* if it's not the end of line, there must be a next word */
  8637. if (!isgraph((unsigned char)**ppw)) {
  8638. return -1;
  8639. }
  8640. }
  8641. /* ok */
  8642. return 1;
  8643. }
  8644. /* Parse HTTP headers from the given buffer, advance buf pointer
  8645. * to the point where parsing stopped.
  8646. * All parameters must be valid pointers (not NULL).
  8647. * Return <0 on error. */
  8648. static int
  8649. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8650. {
  8651. int i;
  8652. int num_headers = 0;
  8653. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8654. char *dp = *buf;
  8655. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8656. dp++;
  8657. }
  8658. if (dp == *buf) {
  8659. /* End of headers reached. */
  8660. break;
  8661. }
  8662. if (*dp != ':') {
  8663. /* This is not a valid field. */
  8664. return -1;
  8665. }
  8666. /* End of header key (*dp == ':') */
  8667. /* Truncate here and set the key name */
  8668. *dp = 0;
  8669. hdr[i].name = *buf;
  8670. do {
  8671. dp++;
  8672. } while (*dp == ' ');
  8673. /* The rest of the line is the value */
  8674. hdr[i].value = dp;
  8675. *buf = dp + strcspn(dp, "\r\n");
  8676. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8677. *buf = NULL;
  8678. }
  8679. num_headers = i + 1;
  8680. if (*buf) {
  8681. (*buf)[0] = 0;
  8682. (*buf)[1] = 0;
  8683. *buf += 2;
  8684. } else {
  8685. *buf = dp;
  8686. break;
  8687. }
  8688. if ((*buf)[0] == '\r') {
  8689. /* This is the end of the header */
  8690. break;
  8691. }
  8692. }
  8693. return num_headers;
  8694. }
  8695. struct mg_http_method_info {
  8696. const char *name;
  8697. int request_has_body;
  8698. int response_has_body;
  8699. int is_safe;
  8700. int is_idempotent;
  8701. int is_cacheable;
  8702. };
  8703. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8704. static struct mg_http_method_info http_methods[] = {
  8705. /* HTTP (RFC 2616) */
  8706. {"GET", 0, 1, 1, 1, 1},
  8707. {"POST", 1, 1, 0, 0, 0},
  8708. {"PUT", 1, 0, 0, 1, 0},
  8709. {"DELETE", 0, 0, 0, 1, 0},
  8710. {"HEAD", 0, 0, 1, 1, 1},
  8711. {"OPTIONS", 0, 0, 1, 1, 0},
  8712. {"CONNECT", 1, 1, 0, 0, 0},
  8713. /* TRACE method (RFC 2616) is not supported for security reasons */
  8714. /* PATCH method (RFC 5789) */
  8715. {"PATCH", 1, 0, 0, 0, 0},
  8716. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8717. /* WEBDAV (RFC 2518) */
  8718. {"PROPFIND", 0, 1, 1, 1, 0},
  8719. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8720. * Some PROPFIND results MAY be cached, with care,
  8721. * as there is no cache validation mechanism for
  8722. * most properties. This method is both safe and
  8723. * idempotent (see Section 9.1 of [RFC2616]). */
  8724. {"MKCOL", 0, 0, 0, 1, 0},
  8725. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8726. * When MKCOL is invoked without a request body,
  8727. * the newly created collection SHOULD have no
  8728. * members. A MKCOL request message may contain
  8729. * a message body. The precise behavior of a MKCOL
  8730. * request when the body is present is undefined,
  8731. * ... ==> We do not support MKCOL with body data.
  8732. * This method is idempotent, but not safe (see
  8733. * Section 9.1 of [RFC2616]). Responses to this
  8734. * method MUST NOT be cached. */
  8735. /* Unsupported WEBDAV Methods: */
  8736. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8737. /* + 11 methods from RFC 3253 */
  8738. /* ORDERPATCH (RFC 3648) */
  8739. /* ACL (RFC 3744) */
  8740. /* SEARCH (RFC 5323) */
  8741. /* + MicroSoft extensions
  8742. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8743. /* REPORT method (RFC 3253) */
  8744. {"REPORT", 1, 1, 1, 1, 1},
  8745. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8746. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8747. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8748. * to be useful for REST in case a "GET request with body" is
  8749. * required. */
  8750. {NULL, 0, 0, 0, 0, 0}
  8751. /* end of list */
  8752. };
  8753. static const struct mg_http_method_info *
  8754. get_http_method_info(const char *method)
  8755. {
  8756. /* Check if the method is known to the server. The list of all known
  8757. * HTTP methods can be found here at
  8758. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8759. */
  8760. const struct mg_http_method_info *m = http_methods;
  8761. while (m->name) {
  8762. if (!strcmp(m->name, method)) {
  8763. return m;
  8764. }
  8765. m++;
  8766. }
  8767. return NULL;
  8768. }
  8769. static int
  8770. is_valid_http_method(const char *method)
  8771. {
  8772. return (get_http_method_info(method) != NULL);
  8773. }
  8774. /* Parse HTTP request, fill in mg_request_info structure.
  8775. * This function modifies the buffer by NUL-terminating
  8776. * HTTP request components, header names and header values.
  8777. * Parameters:
  8778. * buf (in/out): pointer to the HTTP header to parse and split
  8779. * len (in): length of HTTP header buffer
  8780. * re (out): parsed header as mg_request_info
  8781. * buf and ri must be valid pointers (not NULL), len>0.
  8782. * Returns <0 on error. */
  8783. static int
  8784. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8785. {
  8786. int request_length;
  8787. int init_skip = 0;
  8788. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8789. * remote_port */
  8790. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8791. NULL;
  8792. ri->num_headers = 0;
  8793. /* RFC says that all initial whitespaces should be ingored */
  8794. /* This included all leading \r and \n (isspace) */
  8795. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8796. while ((len > 0) && isspace((unsigned char)*buf)) {
  8797. buf++;
  8798. len--;
  8799. init_skip++;
  8800. }
  8801. if (len == 0) {
  8802. /* Incomplete request */
  8803. return 0;
  8804. }
  8805. /* Control characters are not allowed, including zero */
  8806. if (iscntrl((unsigned char)*buf)) {
  8807. return -1;
  8808. }
  8809. /* Find end of HTTP header */
  8810. request_length = get_http_header_len(buf, len);
  8811. if (request_length <= 0) {
  8812. return request_length;
  8813. }
  8814. buf[request_length - 1] = '\0';
  8815. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8816. return -1;
  8817. }
  8818. /* The first word has to be the HTTP method */
  8819. ri->request_method = buf;
  8820. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8821. return -1;
  8822. }
  8823. /* Check for a valid http method */
  8824. if (!is_valid_http_method(ri->request_method)) {
  8825. return -1;
  8826. }
  8827. /* The second word is the URI */
  8828. ri->request_uri = buf;
  8829. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8830. return -1;
  8831. }
  8832. /* Next would be the HTTP version */
  8833. ri->http_version = buf;
  8834. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8835. return -1;
  8836. }
  8837. /* Check for a valid HTTP version key */
  8838. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8839. /* Invalid request */
  8840. return -1;
  8841. }
  8842. ri->http_version += 5;
  8843. /* Parse all HTTP headers */
  8844. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8845. if (ri->num_headers < 0) {
  8846. /* Error while parsing headers */
  8847. return -1;
  8848. }
  8849. return request_length + init_skip;
  8850. }
  8851. static int
  8852. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8853. {
  8854. int response_length;
  8855. int init_skip = 0;
  8856. char *tmp, *tmp2;
  8857. long l;
  8858. /* Initialize elements. */
  8859. ri->http_version = ri->status_text = NULL;
  8860. ri->num_headers = ri->status_code = 0;
  8861. /* RFC says that all initial whitespaces should be ingored */
  8862. /* This included all leading \r and \n (isspace) */
  8863. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8864. while ((len > 0) && isspace((unsigned char)*buf)) {
  8865. buf++;
  8866. len--;
  8867. init_skip++;
  8868. }
  8869. if (len == 0) {
  8870. /* Incomplete request */
  8871. return 0;
  8872. }
  8873. /* Control characters are not allowed, including zero */
  8874. if (iscntrl((unsigned char)*buf)) {
  8875. return -1;
  8876. }
  8877. /* Find end of HTTP header */
  8878. response_length = get_http_header_len(buf, len);
  8879. if (response_length <= 0) {
  8880. return response_length;
  8881. }
  8882. buf[response_length - 1] = '\0';
  8883. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8884. return -1;
  8885. }
  8886. /* The first word is the HTTP version */
  8887. /* Check for a valid HTTP version key */
  8888. if (strncmp(buf, "HTTP/", 5) != 0) {
  8889. /* Invalid request */
  8890. return -1;
  8891. }
  8892. buf += 5;
  8893. if (!isgraph((unsigned char)buf[0])) {
  8894. /* Invalid request */
  8895. return -1;
  8896. }
  8897. ri->http_version = buf;
  8898. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8899. return -1;
  8900. }
  8901. /* The second word is the status as a number */
  8902. tmp = buf;
  8903. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8904. return -1;
  8905. }
  8906. l = strtol(tmp, &tmp2, 10);
  8907. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8908. /* Everything else but a 3 digit code is invalid */
  8909. return -1;
  8910. }
  8911. ri->status_code = (int)l;
  8912. /* The rest of the line is the status text */
  8913. ri->status_text = buf;
  8914. /* Find end of status text */
  8915. /* isgraph or isspace = isprint */
  8916. while (isprint((unsigned char)*buf)) {
  8917. buf++;
  8918. }
  8919. if ((*buf != '\r') && (*buf != '\n')) {
  8920. return -1;
  8921. }
  8922. /* Terminate string and forward buf to next line */
  8923. do {
  8924. *buf = 0;
  8925. buf++;
  8926. } while (isspace((unsigned char)*buf));
  8927. /* Parse all HTTP headers */
  8928. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8929. if (ri->num_headers < 0) {
  8930. /* Error while parsing headers */
  8931. return -1;
  8932. }
  8933. return response_length + init_skip;
  8934. }
  8935. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8936. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8937. * buffer (which marks the end of HTTP request). Buffer buf may already
  8938. * have some data. The length of the data is stored in nread.
  8939. * Upon every read operation, increase nread by the number of bytes read. */
  8940. static int
  8941. read_message(FILE *fp,
  8942. struct mg_connection *conn,
  8943. char *buf,
  8944. int bufsiz,
  8945. int *nread)
  8946. {
  8947. int request_len, n = 0;
  8948. struct timespec last_action_time;
  8949. double request_timeout;
  8950. if (!conn) {
  8951. return 0;
  8952. }
  8953. memset(&last_action_time, 0, sizeof(last_action_time));
  8954. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8955. /* value of request_timeout is in seconds, config in milliseconds */
  8956. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8957. } else {
  8958. request_timeout = -1.0;
  8959. }
  8960. if (conn->handled_requests > 0) {
  8961. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8962. request_timeout =
  8963. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8964. }
  8965. }
  8966. request_len = get_http_header_len(buf, *nread);
  8967. /* first time reading from this connection */
  8968. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8969. while (request_len == 0) {
  8970. /* Full request not yet received */
  8971. if (conn->phys_ctx->stop_flag != 0) {
  8972. /* Server is to be stopped. */
  8973. return -1;
  8974. }
  8975. if (*nread >= bufsiz) {
  8976. /* Request too long */
  8977. return -2;
  8978. }
  8979. n = pull_inner(
  8980. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8981. if (n == -2) {
  8982. /* Receive error */
  8983. return -1;
  8984. }
  8985. if (n > 0) {
  8986. *nread += n;
  8987. request_len = get_http_header_len(buf, *nread);
  8988. } else {
  8989. request_len = 0;
  8990. }
  8991. if ((request_len == 0) && (request_timeout >= 0)) {
  8992. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8993. > request_timeout) {
  8994. /* Timeout */
  8995. return -1;
  8996. }
  8997. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8998. }
  8999. }
  9000. return request_len;
  9001. }
  9002. #if !defined(NO_CGI) || !defined(NO_FILES)
  9003. static int
  9004. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9005. {
  9006. const char *expect, *body;
  9007. char buf[MG_BUF_LEN];
  9008. int to_read, nread, success = 0;
  9009. int buffered_len;
  9010. double timeout = -1.0;
  9011. if (!conn) {
  9012. return 0;
  9013. }
  9014. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9015. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9016. }
  9017. expect = mg_get_header(conn, "Expect");
  9018. DEBUG_ASSERT(fp != NULL);
  9019. if (!fp) {
  9020. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9021. return 0;
  9022. }
  9023. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  9024. /* Content length is not specified by the client. */
  9025. mg_send_http_error(conn,
  9026. 411,
  9027. "%s",
  9028. "Error: Client did not specify content length");
  9029. } else if ((expect != NULL)
  9030. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9031. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9032. */
  9033. mg_send_http_error(conn,
  9034. 417,
  9035. "Error: Can not fulfill expectation %s",
  9036. expect);
  9037. } else {
  9038. if (expect != NULL) {
  9039. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9040. conn->status_code = 100;
  9041. } else {
  9042. conn->status_code = 200;
  9043. }
  9044. buffered_len = conn->data_len - conn->request_len;
  9045. DEBUG_ASSERT(buffered_len >= 0);
  9046. DEBUG_ASSERT(conn->consumed_content == 0);
  9047. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  9048. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9049. return 0;
  9050. }
  9051. if (buffered_len > 0) {
  9052. if ((int64_t)buffered_len > conn->content_len) {
  9053. buffered_len = (int)conn->content_len;
  9054. }
  9055. body = conn->buf + conn->request_len;
  9056. push_all(conn->phys_ctx, fp, sock, ssl, body, buffered_len);
  9057. conn->consumed_content += buffered_len;
  9058. }
  9059. nread = 0;
  9060. while (conn->consumed_content < conn->content_len) {
  9061. to_read = sizeof(buf);
  9062. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  9063. to_read = (int)(conn->content_len - conn->consumed_content);
  9064. }
  9065. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  9066. if (nread == -2) {
  9067. /* error */
  9068. break;
  9069. }
  9070. if (nread > 0) {
  9071. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  9072. != nread) {
  9073. break;
  9074. }
  9075. conn->consumed_content += nread;
  9076. }
  9077. }
  9078. if (conn->consumed_content == conn->content_len) {
  9079. success = (nread >= 0);
  9080. }
  9081. /* Each error code path in this function must send an error */
  9082. if (!success) {
  9083. /* NOTE: Maybe some data has already been sent. */
  9084. /* TODO (low): If some data has been sent, a correct error
  9085. * reply can no longer be sent, so just close the connection */
  9086. mg_send_http_error(conn, 500, "%s", "");
  9087. }
  9088. }
  9089. return success;
  9090. }
  9091. #endif
  9092. #if defined(USE_TIMERS)
  9093. #define TIMER_API static
  9094. #include "timer.inl"
  9095. #endif /* USE_TIMERS */
  9096. #if !defined(NO_CGI)
  9097. /* This structure helps to create an environment for the spawned CGI
  9098. * program.
  9099. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9100. * last element must be NULL.
  9101. * However, on Windows there is a requirement that all these
  9102. * VARIABLE=VALUE\0
  9103. * strings must reside in a contiguous buffer. The end of the buffer is
  9104. * marked by two '\0' characters.
  9105. * We satisfy both worlds: we create an envp array (which is vars), all
  9106. * entries are actually pointers inside buf. */
  9107. struct cgi_environment {
  9108. struct mg_connection *conn;
  9109. /* Data block */
  9110. char *buf; /* Environment buffer */
  9111. size_t buflen; /* Space available in buf */
  9112. size_t bufused; /* Space taken in buf */
  9113. /* Index block */
  9114. char **var; /* char **envp */
  9115. size_t varlen; /* Number of variables available in var */
  9116. size_t varused; /* Number of variables stored in var */
  9117. };
  9118. static void addenv(struct cgi_environment *env,
  9119. PRINTF_FORMAT_STRING(const char *fmt),
  9120. ...) PRINTF_ARGS(2, 3);
  9121. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9122. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9123. static void
  9124. addenv(struct cgi_environment *env, const char *fmt, ...)
  9125. {
  9126. size_t n, space;
  9127. int truncated = 0;
  9128. char *added;
  9129. va_list ap;
  9130. /* Calculate how much space is left in the buffer */
  9131. space = (env->buflen - env->bufused);
  9132. /* Calculate an estimate for the required space */
  9133. n = strlen(fmt) + 2 + 128;
  9134. do {
  9135. if (space <= n) {
  9136. /* Allocate new buffer */
  9137. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9138. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9139. if (!added) {
  9140. /* Out of memory */
  9141. mg_cry_internal(
  9142. env->conn,
  9143. "%s: Cannot allocate memory for CGI variable [%s]",
  9144. __func__,
  9145. fmt);
  9146. return;
  9147. }
  9148. env->buf = added;
  9149. env->buflen = n;
  9150. space = (env->buflen - env->bufused);
  9151. }
  9152. /* Make a pointer to the free space int the buffer */
  9153. added = env->buf + env->bufused;
  9154. /* Copy VARIABLE=VALUE\0 string into the free space */
  9155. va_start(ap, fmt);
  9156. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  9157. va_end(ap);
  9158. /* Do not add truncated strings to the environment */
  9159. if (truncated) {
  9160. /* Reallocate the buffer */
  9161. space = 0;
  9162. n = 1;
  9163. }
  9164. } while (truncated);
  9165. /* Calculate number of bytes added to the environment */
  9166. n = strlen(added) + 1;
  9167. env->bufused += n;
  9168. /* Now update the variable index */
  9169. space = (env->varlen - env->varused);
  9170. if (space < 2) {
  9171. mg_cry_internal(env->conn,
  9172. "%s: Cannot register CGI variable [%s]",
  9173. __func__,
  9174. fmt);
  9175. return;
  9176. }
  9177. /* Append a pointer to the added string into the envp array */
  9178. env->var[env->varused] = added;
  9179. env->varused++;
  9180. }
  9181. /* Return 0 on success, non-zero if an error occurs. */
  9182. static int
  9183. prepare_cgi_environment(struct mg_connection *conn,
  9184. const char *prog,
  9185. struct cgi_environment *env)
  9186. {
  9187. const char *s;
  9188. struct vec var_vec;
  9189. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9190. int i, truncated, uri_len;
  9191. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9192. return -1;
  9193. }
  9194. env->conn = conn;
  9195. env->buflen = CGI_ENVIRONMENT_SIZE;
  9196. env->bufused = 0;
  9197. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9198. if (env->buf == NULL) {
  9199. mg_cry_internal(conn,
  9200. "%s: Not enough memory for environmental buffer",
  9201. __func__);
  9202. return -1;
  9203. }
  9204. env->varlen = MAX_CGI_ENVIR_VARS;
  9205. env->varused = 0;
  9206. env->var =
  9207. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  9208. if (env->var == NULL) {
  9209. mg_cry_internal(conn,
  9210. "%s: Not enough memory for environmental variables",
  9211. __func__);
  9212. mg_free(env->buf);
  9213. return -1;
  9214. }
  9215. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9216. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9217. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9218. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9219. /* Prepare the environment block */
  9220. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9221. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9222. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9223. #if defined(USE_IPV6)
  9224. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9225. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9226. } else
  9227. #endif
  9228. {
  9229. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9230. }
  9231. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9232. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9233. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9234. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9235. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9236. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9237. /* SCRIPT_NAME */
  9238. uri_len = (int)strlen(conn->request_info.local_uri);
  9239. if (conn->path_info == NULL) {
  9240. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9241. /* URI: /path_to_script/script.cgi */
  9242. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9243. } else {
  9244. /* URI: /path_to_script/ ... using index.cgi */
  9245. const char *index_file = strrchr(prog, '/');
  9246. if (index_file) {
  9247. addenv(env,
  9248. "SCRIPT_NAME=%s%s",
  9249. conn->request_info.local_uri,
  9250. index_file + 1);
  9251. }
  9252. }
  9253. } else {
  9254. /* URI: /path_to_script/script.cgi/path_info */
  9255. addenv(env,
  9256. "SCRIPT_NAME=%.*s",
  9257. uri_len - (int)strlen(conn->path_info),
  9258. conn->request_info.local_uri);
  9259. }
  9260. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9261. if (conn->path_info == NULL) {
  9262. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9263. } else {
  9264. addenv(env,
  9265. "PATH_TRANSLATED=%s%s",
  9266. conn->dom_ctx->config[DOCUMENT_ROOT],
  9267. conn->path_info);
  9268. }
  9269. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9270. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9271. addenv(env, "CONTENT_TYPE=%s", s);
  9272. }
  9273. if (conn->request_info.query_string != NULL) {
  9274. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9275. }
  9276. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9277. addenv(env, "CONTENT_LENGTH=%s", s);
  9278. }
  9279. if ((s = getenv("PATH")) != NULL) {
  9280. addenv(env, "PATH=%s", s);
  9281. }
  9282. if (conn->path_info != NULL) {
  9283. addenv(env, "PATH_INFO=%s", conn->path_info);
  9284. }
  9285. if (conn->status_code > 0) {
  9286. /* CGI error handler should show the status code */
  9287. addenv(env, "STATUS=%d", conn->status_code);
  9288. }
  9289. #if defined(_WIN32)
  9290. if ((s = getenv("COMSPEC")) != NULL) {
  9291. addenv(env, "COMSPEC=%s", s);
  9292. }
  9293. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9294. addenv(env, "SYSTEMROOT=%s", s);
  9295. }
  9296. if ((s = getenv("SystemDrive")) != NULL) {
  9297. addenv(env, "SystemDrive=%s", s);
  9298. }
  9299. if ((s = getenv("ProgramFiles")) != NULL) {
  9300. addenv(env, "ProgramFiles=%s", s);
  9301. }
  9302. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9303. addenv(env, "ProgramFiles(x86)=%s", s);
  9304. }
  9305. #else
  9306. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9307. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9308. }
  9309. #endif /* _WIN32 */
  9310. if ((s = getenv("PERLLIB")) != NULL) {
  9311. addenv(env, "PERLLIB=%s", s);
  9312. }
  9313. if (conn->request_info.remote_user != NULL) {
  9314. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9315. addenv(env, "%s", "AUTH_TYPE=Digest");
  9316. }
  9317. /* Add all headers as HTTP_* variables */
  9318. for (i = 0; i < conn->request_info.num_headers; i++) {
  9319. (void)mg_snprintf(conn,
  9320. &truncated,
  9321. http_var_name,
  9322. sizeof(http_var_name),
  9323. "HTTP_%s",
  9324. conn->request_info.http_headers[i].name);
  9325. if (truncated) {
  9326. mg_cry_internal(conn,
  9327. "%s: HTTP header variable too long [%s]",
  9328. __func__,
  9329. conn->request_info.http_headers[i].name);
  9330. continue;
  9331. }
  9332. /* Convert variable name into uppercase, and change - to _ */
  9333. for (p = http_var_name; *p != '\0'; p++) {
  9334. if (*p == '-') {
  9335. *p = '_';
  9336. }
  9337. *p = (char)toupper((unsigned char)*p);
  9338. }
  9339. addenv(env,
  9340. "%s=%s",
  9341. http_var_name,
  9342. conn->request_info.http_headers[i].value);
  9343. }
  9344. /* Add user-specified variables */
  9345. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9346. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9347. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9348. }
  9349. env->var[env->varused] = NULL;
  9350. env->buf[env->bufused] = '\0';
  9351. return 0;
  9352. }
  9353. /* Data for CGI process control: PID and number of references */
  9354. struct process_control_data {
  9355. pid_t pid;
  9356. int references;
  9357. };
  9358. static int
  9359. abort_process(void *data)
  9360. {
  9361. /* Waitpid checks for child status and won't work for a pid that does not
  9362. * identify a child of the current process. Thus, if the pid is reused,
  9363. * we will not affect a different process. */
  9364. struct process_control_data *proc = (struct process_control_data *)data;
  9365. int status = 0;
  9366. int refs;
  9367. pid_t ret_pid;
  9368. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9369. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9370. /* Stop child process */
  9371. DEBUG_TRACE("CGI timer: Stop child process %p\n", proc->pid);
  9372. kill(proc->pid, SIGABRT);
  9373. /* Wait until process is terminated (don't leave zombies) */
  9374. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9375. ;
  9376. } else {
  9377. DEBUG_TRACE("CGI timer: Child process %p already stopped\n", proc->pid);
  9378. }
  9379. /* Dec reference counter */
  9380. refs = mg_atomic_dec(&proc->references);
  9381. if (refs == 0) {
  9382. /* no more references - free data */
  9383. mg_free(data);
  9384. }
  9385. return 0;
  9386. }
  9387. static void
  9388. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9389. {
  9390. char *buf;
  9391. size_t buflen;
  9392. int headers_len, data_len, i, truncated;
  9393. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9394. const char *status, *status_text, *connection_state;
  9395. char *pbuf, dir[PATH_MAX], *p;
  9396. struct mg_request_info ri;
  9397. struct cgi_environment blk;
  9398. FILE *in = NULL, *out = NULL, *err = NULL;
  9399. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9400. pid_t pid = (pid_t)-1;
  9401. struct process_control_data *proc = NULL;
  9402. #if defined(USE_TIMERS)
  9403. double cgi_timeout = -1.0;
  9404. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9405. /* Get timeout in seconds */
  9406. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9407. }
  9408. #endif
  9409. if (conn == NULL) {
  9410. return;
  9411. }
  9412. buf = NULL;
  9413. buflen = conn->phys_ctx->max_request_size;
  9414. i = prepare_cgi_environment(conn, prog, &blk);
  9415. if (i != 0) {
  9416. blk.buf = NULL;
  9417. blk.var = NULL;
  9418. goto done;
  9419. }
  9420. /* CGI must be executed in its own directory. 'dir' must point to the
  9421. * directory containing executable program, 'p' must point to the
  9422. * executable program name relative to 'dir'. */
  9423. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9424. if (truncated) {
  9425. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9426. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9427. goto done;
  9428. }
  9429. if ((p = strrchr(dir, '/')) != NULL) {
  9430. *p++ = '\0';
  9431. } else {
  9432. dir[0] = '.';
  9433. dir[1] = '\0';
  9434. p = (char *)prog;
  9435. }
  9436. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9437. status = strerror(ERRNO);
  9438. mg_cry_internal(
  9439. conn,
  9440. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9441. prog,
  9442. status);
  9443. mg_send_http_error(conn,
  9444. 500,
  9445. "Error: Cannot create CGI pipe: %s",
  9446. status);
  9447. goto done;
  9448. }
  9449. proc = (struct process_control_data *)
  9450. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9451. if (proc == NULL) {
  9452. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9453. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9454. goto done;
  9455. }
  9456. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9457. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9458. if (pid == (pid_t)-1) {
  9459. status = strerror(ERRNO);
  9460. mg_cry_internal(
  9461. conn,
  9462. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9463. prog,
  9464. status);
  9465. mg_send_http_error(conn,
  9466. 500,
  9467. "Error: Cannot spawn CGI process [%s]: %s",
  9468. prog,
  9469. status);
  9470. mg_free(proc);
  9471. proc = NULL;
  9472. goto done;
  9473. }
  9474. /* Store data in shared process_control_data */
  9475. proc->pid = pid;
  9476. proc->references = 1;
  9477. #if defined(USE_TIMERS)
  9478. if (cgi_timeout > 0.0) {
  9479. proc->references = 2;
  9480. // Start a timer for CGI
  9481. timer_add(conn->phys_ctx,
  9482. cgi_timeout /* in seconds */,
  9483. 0.0,
  9484. 1,
  9485. abort_process,
  9486. (void *)proc);
  9487. }
  9488. #endif
  9489. /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */
  9490. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  9491. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  9492. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  9493. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  9494. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  9495. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  9496. /* Parent closes only one side of the pipes.
  9497. * If we don't mark them as closed, close() attempt before
  9498. * return from this function throws an exception on Windows.
  9499. * Windows does not like when closed descriptor is closed again. */
  9500. (void)close(fdin[0]);
  9501. (void)close(fdout[1]);
  9502. (void)close(fderr[1]);
  9503. fdin[0] = fdout[1] = fderr[1] = -1;
  9504. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  9505. status = strerror(ERRNO);
  9506. mg_cry_internal(conn,
  9507. "Error: CGI program \"%s\": Can not open stdin: %s",
  9508. prog,
  9509. status);
  9510. mg_send_http_error(conn,
  9511. 500,
  9512. "Error: CGI can not open fdin\nfopen: %s",
  9513. status);
  9514. goto done;
  9515. }
  9516. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  9517. status = strerror(ERRNO);
  9518. mg_cry_internal(conn,
  9519. "Error: CGI program \"%s\": Can not open stdout: %s",
  9520. prog,
  9521. status);
  9522. mg_send_http_error(conn,
  9523. 500,
  9524. "Error: CGI can not open fdout\nfopen: %s",
  9525. status);
  9526. goto done;
  9527. }
  9528. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  9529. status = strerror(ERRNO);
  9530. mg_cry_internal(conn,
  9531. "Error: CGI program \"%s\": Can not open stderr: %s",
  9532. prog,
  9533. status);
  9534. mg_send_http_error(conn,
  9535. 500,
  9536. "Error: CGI can not open fderr\nfopen: %s",
  9537. status);
  9538. goto done;
  9539. }
  9540. setbuf(in, NULL);
  9541. setbuf(out, NULL);
  9542. setbuf(err, NULL);
  9543. fout.access.fp = out;
  9544. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  9545. DEBUG_TRACE("CGI: send body data (%lli)\n",
  9546. (signed long long)conn->request_info.content_length);
  9547. /* This is a POST/PUT request, or another request with body data. */
  9548. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9549. /* Error sending the body data */
  9550. mg_cry_internal(
  9551. conn,
  9552. "Error: CGI program \"%s\": Forward body data failed",
  9553. prog);
  9554. goto done;
  9555. }
  9556. }
  9557. /* Close so child gets an EOF. */
  9558. fclose(in);
  9559. in = NULL;
  9560. fdin[1] = -1;
  9561. /* Now read CGI reply into a buffer. We need to set correct
  9562. * status code, thus we need to see all HTTP headers first.
  9563. * Do not send anything back to client, until we buffer in all
  9564. * HTTP headers. */
  9565. data_len = 0;
  9566. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9567. if (buf == NULL) {
  9568. mg_send_http_error(conn,
  9569. 500,
  9570. "Error: Not enough memory for CGI buffer (%u bytes)",
  9571. (unsigned int)buflen);
  9572. mg_cry_internal(
  9573. conn,
  9574. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9575. "bytes)",
  9576. prog,
  9577. (unsigned int)buflen);
  9578. goto done;
  9579. }
  9580. DEBUG_TRACE("CGI: %s", "wait for response");
  9581. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9582. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9583. if (headers_len <= 0) {
  9584. /* Could not parse the CGI response. Check if some error message on
  9585. * stderr. */
  9586. i = pull_all(err, conn, buf, (int)buflen);
  9587. if (i > 0) {
  9588. /* CGI program explicitly sent an error */
  9589. /* Write the error message to the internal log */
  9590. mg_cry_internal(conn,
  9591. "Error: CGI program \"%s\" sent error "
  9592. "message: [%.*s]",
  9593. prog,
  9594. i,
  9595. buf);
  9596. /* Don't send the error message back to the client */
  9597. mg_send_http_error(conn,
  9598. 500,
  9599. "Error: CGI program \"%s\" failed.",
  9600. prog);
  9601. } else {
  9602. /* CGI program did not explicitly send an error, but a broken
  9603. * respon header */
  9604. mg_cry_internal(conn,
  9605. "Error: CGI program sent malformed or too big "
  9606. "(>%u bytes) HTTP headers: [%.*s]",
  9607. (unsigned)buflen,
  9608. data_len,
  9609. buf);
  9610. mg_send_http_error(conn,
  9611. 500,
  9612. "Error: CGI program sent malformed or too big "
  9613. "(>%u bytes) HTTP headers: [%.*s]",
  9614. (unsigned)buflen,
  9615. data_len,
  9616. buf);
  9617. }
  9618. /* in both cases, abort processing CGI */
  9619. goto done;
  9620. }
  9621. pbuf = buf;
  9622. buf[headers_len - 1] = '\0';
  9623. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9624. /* Make up and send the status line */
  9625. status_text = "OK";
  9626. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9627. != NULL) {
  9628. conn->status_code = atoi(status);
  9629. status_text = status;
  9630. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9631. status_text++;
  9632. }
  9633. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9634. != NULL) {
  9635. conn->status_code = 307;
  9636. } else {
  9637. conn->status_code = 200;
  9638. }
  9639. connection_state =
  9640. get_header(ri.http_headers, ri.num_headers, "Connection");
  9641. if (!header_has_option(connection_state, "keep-alive")) {
  9642. conn->must_close = 1;
  9643. }
  9644. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9645. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9646. /* Send headers */
  9647. for (i = 0; i < ri.num_headers; i++) {
  9648. mg_printf(conn,
  9649. "%s: %s\r\n",
  9650. ri.http_headers[i].name,
  9651. ri.http_headers[i].value);
  9652. }
  9653. mg_write(conn, "\r\n", 2);
  9654. /* Send chunk of data that may have been read after the headers */
  9655. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9656. /* Read the rest of CGI output and send to the client */
  9657. DEBUG_TRACE("CGI: %s", "forward all data");
  9658. send_file_data(conn, &fout, 0, INT64_MAX);
  9659. DEBUG_TRACE("CGI: %s", "all data sent");
  9660. done:
  9661. mg_free(blk.var);
  9662. mg_free(blk.buf);
  9663. if (pid != (pid_t)-1) {
  9664. abort_process((void *)proc);
  9665. }
  9666. if (fdin[0] != -1) {
  9667. close(fdin[0]);
  9668. }
  9669. if (fdout[1] != -1) {
  9670. close(fdout[1]);
  9671. }
  9672. if (in != NULL) {
  9673. fclose(in);
  9674. } else if (fdin[1] != -1) {
  9675. close(fdin[1]);
  9676. }
  9677. if (out != NULL) {
  9678. fclose(out);
  9679. } else if (fdout[0] != -1) {
  9680. close(fdout[0]);
  9681. }
  9682. if (err != NULL) {
  9683. fclose(err);
  9684. } else if (fderr[0] != -1) {
  9685. close(fderr[0]);
  9686. }
  9687. if (buf != NULL) {
  9688. mg_free(buf);
  9689. }
  9690. }
  9691. #endif /* !NO_CGI */
  9692. #if !defined(NO_FILES)
  9693. static void
  9694. mkcol(struct mg_connection *conn, const char *path)
  9695. {
  9696. int rc, body_len;
  9697. struct de de;
  9698. char date[64];
  9699. time_t curtime = time(NULL);
  9700. if (conn == NULL) {
  9701. return;
  9702. }
  9703. /* TODO (mid): Check the mg_send_http_error situations in this function
  9704. */
  9705. memset(&de.file, 0, sizeof(de.file));
  9706. if (!mg_stat(conn, path, &de.file)) {
  9707. mg_cry_internal(conn,
  9708. "%s: mg_stat(%s) failed: %s",
  9709. __func__,
  9710. path,
  9711. strerror(ERRNO));
  9712. }
  9713. if (de.file.last_modified) {
  9714. /* TODO (mid): This check does not seem to make any sense ! */
  9715. /* TODO (mid): Add a webdav unit test first, before changing
  9716. * anything here. */
  9717. mg_send_http_error(
  9718. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9719. return;
  9720. }
  9721. body_len = conn->data_len - conn->request_len;
  9722. if (body_len > 0) {
  9723. mg_send_http_error(
  9724. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9725. return;
  9726. }
  9727. rc = mg_mkdir(conn, path, 0755);
  9728. if (rc == 0) {
  9729. conn->status_code = 201;
  9730. gmt_time_string(date, sizeof(date), &curtime);
  9731. mg_printf(conn,
  9732. "HTTP/1.1 %d Created\r\n"
  9733. "Date: %s\r\n",
  9734. conn->status_code,
  9735. date);
  9736. send_static_cache_header(conn);
  9737. send_additional_header(conn);
  9738. mg_printf(conn,
  9739. "Content-Length: 0\r\n"
  9740. "Connection: %s\r\n\r\n",
  9741. suggest_connection_header(conn));
  9742. } else {
  9743. if (errno == EEXIST) {
  9744. mg_send_http_error(
  9745. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9746. } else if (errno == EACCES) {
  9747. mg_send_http_error(
  9748. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9749. } else if (errno == ENOENT) {
  9750. mg_send_http_error(
  9751. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9752. } else {
  9753. mg_send_http_error(
  9754. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9755. }
  9756. }
  9757. }
  9758. static void
  9759. put_file(struct mg_connection *conn, const char *path)
  9760. {
  9761. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9762. const char *range;
  9763. int64_t r1, r2;
  9764. int rc;
  9765. char date[64];
  9766. time_t curtime = time(NULL);
  9767. if (conn == NULL) {
  9768. return;
  9769. }
  9770. if (mg_stat(conn, path, &file.stat)) {
  9771. /* File already exists */
  9772. conn->status_code = 200;
  9773. if (file.stat.is_directory) {
  9774. /* This is an already existing directory,
  9775. * so there is nothing to do for the server. */
  9776. rc = 0;
  9777. } else {
  9778. /* File exists and is not a directory. */
  9779. /* Can it be replaced? */
  9780. #if defined(MG_USE_OPEN_FILE)
  9781. if (file.access.membuf != NULL) {
  9782. /* This is an "in-memory" file, that can not be replaced */
  9783. mg_send_http_error(conn,
  9784. 405,
  9785. "Error: Put not possible\nReplacing %s "
  9786. "is not supported",
  9787. path);
  9788. return;
  9789. }
  9790. #endif
  9791. /* Check if the server may write this file */
  9792. if (access(path, W_OK) == 0) {
  9793. /* Access granted */
  9794. conn->status_code = 200;
  9795. rc = 1;
  9796. } else {
  9797. mg_send_http_error(
  9798. conn,
  9799. 403,
  9800. "Error: Put not possible\nReplacing %s is not allowed",
  9801. path);
  9802. return;
  9803. }
  9804. }
  9805. } else {
  9806. /* File should be created */
  9807. conn->status_code = 201;
  9808. rc = put_dir(conn, path);
  9809. }
  9810. if (rc == 0) {
  9811. /* put_dir returns 0 if path is a directory */
  9812. gmt_time_string(date, sizeof(date), &curtime);
  9813. mg_printf(conn,
  9814. "HTTP/1.1 %d %s\r\n",
  9815. conn->status_code,
  9816. mg_get_response_code_text(NULL, conn->status_code));
  9817. send_no_cache_header(conn);
  9818. send_additional_header(conn);
  9819. mg_printf(conn,
  9820. "Date: %s\r\n"
  9821. "Content-Length: 0\r\n"
  9822. "Connection: %s\r\n\r\n",
  9823. date,
  9824. suggest_connection_header(conn));
  9825. /* Request to create a directory has been fulfilled successfully.
  9826. * No need to put a file. */
  9827. return;
  9828. }
  9829. if (rc == -1) {
  9830. /* put_dir returns -1 if the path is too long */
  9831. mg_send_http_error(conn,
  9832. 414,
  9833. "Error: Path too long\nput_dir(%s): %s",
  9834. path,
  9835. strerror(ERRNO));
  9836. return;
  9837. }
  9838. if (rc == -2) {
  9839. /* put_dir returns -2 if the directory can not be created */
  9840. mg_send_http_error(conn,
  9841. 500,
  9842. "Error: Can not create directory\nput_dir(%s): %s",
  9843. path,
  9844. strerror(ERRNO));
  9845. return;
  9846. }
  9847. /* A file should be created or overwritten. */
  9848. /* Currently CivetWeb does not nead read+write access. */
  9849. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9850. || file.access.fp == NULL) {
  9851. (void)mg_fclose(&file.access);
  9852. mg_send_http_error(conn,
  9853. 500,
  9854. "Error: Can not create file\nfopen(%s): %s",
  9855. path,
  9856. strerror(ERRNO));
  9857. return;
  9858. }
  9859. fclose_on_exec(&file.access, conn);
  9860. range = mg_get_header(conn, "Content-Range");
  9861. r1 = r2 = 0;
  9862. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9863. conn->status_code = 206; /* Partial content */
  9864. fseeko(file.access.fp, r1, SEEK_SET);
  9865. }
  9866. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9867. /* forward_body_data failed.
  9868. * The error code has already been sent to the client,
  9869. * and conn->status_code is already set. */
  9870. (void)mg_fclose(&file.access);
  9871. return;
  9872. }
  9873. if (mg_fclose(&file.access) != 0) {
  9874. /* fclose failed. This might have different reasons, but a likely
  9875. * one is "no space on disk", http 507. */
  9876. conn->status_code = 507;
  9877. }
  9878. gmt_time_string(date, sizeof(date), &curtime);
  9879. mg_printf(conn,
  9880. "HTTP/1.1 %d %s\r\n",
  9881. conn->status_code,
  9882. mg_get_response_code_text(NULL, conn->status_code));
  9883. send_no_cache_header(conn);
  9884. send_additional_header(conn);
  9885. mg_printf(conn,
  9886. "Date: %s\r\n"
  9887. "Content-Length: 0\r\n"
  9888. "Connection: %s\r\n\r\n",
  9889. date,
  9890. suggest_connection_header(conn));
  9891. }
  9892. static void
  9893. delete_file(struct mg_connection *conn, const char *path)
  9894. {
  9895. struct de de;
  9896. memset(&de.file, 0, sizeof(de.file));
  9897. if (!mg_stat(conn, path, &de.file)) {
  9898. /* mg_stat returns 0 if the file does not exist */
  9899. mg_send_http_error(conn,
  9900. 404,
  9901. "Error: Cannot delete file\nFile %s not found",
  9902. path);
  9903. return;
  9904. }
  9905. #if 0 /* Ignore if a file in memory is inside a folder */
  9906. if (de.access.membuf != NULL) {
  9907. /* the file is cached in memory */
  9908. mg_send_http_error(
  9909. conn,
  9910. 405,
  9911. "Error: Delete not possible\nDeleting %s is not supported",
  9912. path);
  9913. return;
  9914. }
  9915. #endif
  9916. if (de.file.is_directory) {
  9917. if (remove_directory(conn, path)) {
  9918. /* Delete is successful: Return 204 without content. */
  9919. mg_send_http_error(conn, 204, "%s", "");
  9920. } else {
  9921. /* Delete is not successful: Return 500 (Server error). */
  9922. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9923. }
  9924. return;
  9925. }
  9926. /* This is an existing file (not a directory).
  9927. * Check if write permission is granted. */
  9928. if (access(path, W_OK) != 0) {
  9929. /* File is read only */
  9930. mg_send_http_error(
  9931. conn,
  9932. 403,
  9933. "Error: Delete not possible\nDeleting %s is not allowed",
  9934. path);
  9935. return;
  9936. }
  9937. /* Try to delete it. */
  9938. if (mg_remove(conn, path) == 0) {
  9939. /* Delete was successful: Return 204 without content. */
  9940. mg_send_http_error(conn, 204, "%s", "");
  9941. } else {
  9942. /* Delete not successful (file locked). */
  9943. mg_send_http_error(conn,
  9944. 423,
  9945. "Error: Cannot delete file\nremove(%s): %s",
  9946. path,
  9947. strerror(ERRNO));
  9948. }
  9949. }
  9950. #endif /* !NO_FILES */
  9951. static void
  9952. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9953. static void
  9954. do_ssi_include(struct mg_connection *conn,
  9955. const char *ssi,
  9956. char *tag,
  9957. int include_level)
  9958. {
  9959. char file_name[MG_BUF_LEN], path[512], *p;
  9960. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9961. size_t len;
  9962. int truncated = 0;
  9963. if (conn == NULL) {
  9964. return;
  9965. }
  9966. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9967. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9968. * always < MG_BUF_LEN. */
  9969. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9970. /* File name is relative to the webserver root */
  9971. file_name[511] = 0;
  9972. (void)mg_snprintf(conn,
  9973. &truncated,
  9974. path,
  9975. sizeof(path),
  9976. "%s/%s",
  9977. conn->dom_ctx->config[DOCUMENT_ROOT],
  9978. file_name);
  9979. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9980. /* File name is relative to the webserver working directory
  9981. * or it is absolute system path */
  9982. file_name[511] = 0;
  9983. (void)
  9984. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9985. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9986. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9987. /* File name is relative to the currect document */
  9988. file_name[511] = 0;
  9989. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9990. if (!truncated) {
  9991. if ((p = strrchr(path, '/')) != NULL) {
  9992. p[1] = '\0';
  9993. }
  9994. len = strlen(path);
  9995. (void)mg_snprintf(conn,
  9996. &truncated,
  9997. path + len,
  9998. sizeof(path) - len,
  9999. "%s",
  10000. file_name);
  10001. }
  10002. } else {
  10003. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  10004. return;
  10005. }
  10006. if (truncated) {
  10007. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  10008. return;
  10009. }
  10010. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  10011. mg_cry_internal(conn,
  10012. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  10013. tag,
  10014. path,
  10015. strerror(ERRNO));
  10016. } else {
  10017. fclose_on_exec(&file.access, conn);
  10018. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10019. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10020. path)
  10021. > 0) {
  10022. send_ssi_file(conn, path, &file, include_level + 1);
  10023. } else {
  10024. send_file_data(conn, &file, 0, INT64_MAX);
  10025. }
  10026. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10027. }
  10028. }
  10029. #if !defined(NO_POPEN)
  10030. static void
  10031. do_ssi_exec(struct mg_connection *conn, char *tag)
  10032. {
  10033. char cmd[1024] = "";
  10034. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10035. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10036. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10037. } else {
  10038. cmd[1023] = 0;
  10039. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10040. mg_cry_internal(conn,
  10041. "Cannot SSI #exec: [%s]: %s",
  10042. cmd,
  10043. strerror(ERRNO));
  10044. } else {
  10045. send_file_data(conn, &file, 0, INT64_MAX);
  10046. pclose(file.access.fp);
  10047. }
  10048. }
  10049. }
  10050. #endif /* !NO_POPEN */
  10051. static int
  10052. mg_fgetc(struct mg_file *filep, int offset)
  10053. {
  10054. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10055. if (filep == NULL) {
  10056. return EOF;
  10057. }
  10058. #if defined(MG_USE_OPEN_FILE)
  10059. if ((filep->access.membuf != NULL) && (offset >= 0)
  10060. && (((unsigned int)(offset)) < filep->stat.size)) {
  10061. return ((const unsigned char *)filep->access.membuf)[offset];
  10062. } else /* else block below */
  10063. #endif
  10064. if (filep->access.fp != NULL) {
  10065. return fgetc(filep->access.fp);
  10066. } else {
  10067. return EOF;
  10068. }
  10069. }
  10070. static void
  10071. send_ssi_file(struct mg_connection *conn,
  10072. const char *path,
  10073. struct mg_file *filep,
  10074. int include_level)
  10075. {
  10076. char buf[MG_BUF_LEN];
  10077. int ch, offset, len, in_tag, in_ssi_tag;
  10078. if (include_level > 10) {
  10079. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10080. return;
  10081. }
  10082. in_tag = in_ssi_tag = len = offset = 0;
  10083. /* Read file, byte by byte, and look for SSI include tags */
  10084. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10085. if (in_tag) {
  10086. /* We are in a tag, either SSI tag or html tag */
  10087. if (ch == '>') {
  10088. /* Tag is closing */
  10089. buf[len++] = '>';
  10090. if (in_ssi_tag) {
  10091. /* Handle SSI tag */
  10092. buf[len] = 0;
  10093. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10094. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10095. #if !defined(NO_POPEN)
  10096. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10097. do_ssi_exec(conn, buf + 9);
  10098. #endif /* !NO_POPEN */
  10099. } else {
  10100. mg_cry_internal(conn,
  10101. "%s: unknown SSI "
  10102. "command: \"%s\"",
  10103. path,
  10104. buf);
  10105. }
  10106. len = 0;
  10107. in_ssi_tag = in_tag = 0;
  10108. } else {
  10109. /* Not an SSI tag */
  10110. /* Flush buffer */
  10111. (void)mg_write(conn, buf, (size_t)len);
  10112. len = 0;
  10113. in_tag = 0;
  10114. }
  10115. } else {
  10116. /* Tag is still open */
  10117. buf[len++] = (char)(ch & 0xff);
  10118. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10119. /* All SSI tags start with <!--# */
  10120. in_ssi_tag = 1;
  10121. }
  10122. if ((len + 2) > (int)sizeof(buf)) {
  10123. /* Tag to long for buffer */
  10124. mg_cry_internal(conn, "%s: tag is too large", path);
  10125. return;
  10126. }
  10127. }
  10128. } else {
  10129. /* We are not in a tag yet. */
  10130. if (ch == '<') {
  10131. /* Tag is opening */
  10132. in_tag = 1;
  10133. if (len > 0) {
  10134. /* Flush current buffer.
  10135. * Buffer is filled with "len" bytes. */
  10136. (void)mg_write(conn, buf, (size_t)len);
  10137. }
  10138. /* Store the < */
  10139. len = 1;
  10140. buf[0] = '<';
  10141. } else {
  10142. /* No Tag */
  10143. /* Add data to buffer */
  10144. buf[len++] = (char)(ch & 0xff);
  10145. /* Flush if buffer is full */
  10146. if (len == (int)sizeof(buf)) {
  10147. mg_write(conn, buf, (size_t)len);
  10148. len = 0;
  10149. }
  10150. }
  10151. }
  10152. }
  10153. /* Send the rest of buffered data */
  10154. if (len > 0) {
  10155. mg_write(conn, buf, (size_t)len);
  10156. }
  10157. }
  10158. static void
  10159. handle_ssi_file_request(struct mg_connection *conn,
  10160. const char *path,
  10161. struct mg_file *filep)
  10162. {
  10163. char date[64];
  10164. time_t curtime = time(NULL);
  10165. const char *cors_orig_cfg;
  10166. const char *cors1, *cors2, *cors3;
  10167. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10168. return;
  10169. }
  10170. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10171. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10172. /* Cross-origin resource sharing (CORS). */
  10173. cors1 = "Access-Control-Allow-Origin: ";
  10174. cors2 = cors_orig_cfg;
  10175. cors3 = "\r\n";
  10176. } else {
  10177. cors1 = cors2 = cors3 = "";
  10178. }
  10179. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10180. /* File exists (precondition for calling this function),
  10181. * but can not be opened by the server. */
  10182. mg_send_http_error(conn,
  10183. 500,
  10184. "Error: Cannot read file\nfopen(%s): %s",
  10185. path,
  10186. strerror(ERRNO));
  10187. } else {
  10188. conn->must_close = 1;
  10189. gmt_time_string(date, sizeof(date), &curtime);
  10190. fclose_on_exec(&filep->access, conn);
  10191. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10192. send_no_cache_header(conn);
  10193. send_additional_header(conn);
  10194. mg_printf(conn,
  10195. "%s%s%s"
  10196. "Date: %s\r\n"
  10197. "Content-Type: text/html\r\n"
  10198. "Connection: %s\r\n\r\n",
  10199. cors1,
  10200. cors2,
  10201. cors3,
  10202. date,
  10203. suggest_connection_header(conn));
  10204. send_ssi_file(conn, path, filep, 0);
  10205. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10206. }
  10207. }
  10208. #if !defined(NO_FILES)
  10209. static void
  10210. send_options(struct mg_connection *conn)
  10211. {
  10212. char date[64];
  10213. time_t curtime = time(NULL);
  10214. if (!conn) {
  10215. return;
  10216. }
  10217. conn->status_code = 200;
  10218. conn->must_close = 1;
  10219. gmt_time_string(date, sizeof(date), &curtime);
  10220. /* We do not set a "Cache-Control" header here, but leave the default.
  10221. * Since browsers do not send an OPTIONS request, we can not test the
  10222. * effect anyway. */
  10223. mg_printf(conn,
  10224. "HTTP/1.1 200 OK\r\n"
  10225. "Date: %s\r\n"
  10226. "Connection: %s\r\n"
  10227. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10228. "PROPFIND, MKCOL\r\n"
  10229. "DAV: 1\r\n",
  10230. date,
  10231. suggest_connection_header(conn));
  10232. send_additional_header(conn);
  10233. mg_printf(conn, "\r\n");
  10234. }
  10235. /* Writes PROPFIND properties for a collection element */
  10236. static int
  10237. print_props(struct mg_connection *conn,
  10238. const char *uri,
  10239. const char *name,
  10240. struct mg_file_stat *filep)
  10241. {
  10242. size_t href_size, i, j;
  10243. int len;
  10244. char *href, mtime[64];
  10245. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10246. return 0;
  10247. }
  10248. /* Estimate worst case size for encoding */
  10249. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10250. href = (char *)mg_malloc(href_size);
  10251. if (href == NULL) {
  10252. return 0;
  10253. }
  10254. len = mg_url_encode(uri, href, href_size);
  10255. if (len >= 0) {
  10256. /* Append an extra string */
  10257. mg_url_encode(name, href + len, href_size - (size_t)len);
  10258. }
  10259. /* Directory separator should be preserved. */
  10260. for (i = j = 0; href[i]; j++) {
  10261. if (!strncmp(href + i, "%2f", 3)) {
  10262. href[j] = '/';
  10263. i += 3;
  10264. } else {
  10265. href[j] = href[i++];
  10266. }
  10267. }
  10268. href[j] = '\0';
  10269. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10270. mg_printf(conn,
  10271. "<d:response>"
  10272. "<d:href>%s</d:href>"
  10273. "<d:propstat>"
  10274. "<d:prop>"
  10275. "<d:resourcetype>%s</d:resourcetype>"
  10276. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10277. "<d:getlastmodified>%s</d:getlastmodified>"
  10278. "</d:prop>"
  10279. "<d:status>HTTP/1.1 200 OK</d:status>"
  10280. "</d:propstat>"
  10281. "</d:response>\n",
  10282. href,
  10283. filep->is_directory ? "<d:collection/>" : "",
  10284. filep->size,
  10285. mtime);
  10286. mg_free(href);
  10287. return 1;
  10288. }
  10289. static int
  10290. print_dav_dir_entry(struct de *de, void *data)
  10291. {
  10292. struct mg_connection *conn = (struct mg_connection *)data;
  10293. if (!de || !conn || !print_props(conn, conn->request_info.local_uri,
  10294. de->file_name, &de->file)) {
  10295. return -1;
  10296. }
  10297. return 0;
  10298. }
  10299. static void
  10300. handle_propfind(struct mg_connection *conn,
  10301. const char *path,
  10302. struct mg_file_stat *filep)
  10303. {
  10304. const char *depth = mg_get_header(conn, "Depth");
  10305. char date[64];
  10306. time_t curtime = time(NULL);
  10307. gmt_time_string(date, sizeof(date), &curtime);
  10308. if (!conn || !path || !filep || !conn->dom_ctx) {
  10309. return;
  10310. }
  10311. conn->must_close = 1;
  10312. conn->status_code = 207;
  10313. mg_printf(conn,
  10314. "HTTP/1.1 207 Multi-Status\r\n"
  10315. "Date: %s\r\n",
  10316. date);
  10317. send_static_cache_header(conn);
  10318. send_additional_header(conn);
  10319. mg_printf(conn,
  10320. "Connection: %s\r\n"
  10321. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10322. suggest_connection_header(conn));
  10323. mg_printf(conn,
  10324. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10325. "<d:multistatus xmlns:d='DAV:'>\n");
  10326. /* Print properties for the requested resource itself */
  10327. print_props(conn, conn->request_info.local_uri, "", filep);
  10328. /* If it is a directory, print directory entries too if Depth is not 0
  10329. */
  10330. if (filep->is_directory
  10331. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10332. "yes")
  10333. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10334. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10335. }
  10336. mg_printf(conn, "%s\n", "</d:multistatus>");
  10337. }
  10338. #endif
  10339. void
  10340. mg_lock_connection(struct mg_connection *conn)
  10341. {
  10342. if (conn) {
  10343. (void)pthread_mutex_lock(&conn->mutex);
  10344. }
  10345. }
  10346. void
  10347. mg_unlock_connection(struct mg_connection *conn)
  10348. {
  10349. if (conn) {
  10350. (void)pthread_mutex_unlock(&conn->mutex);
  10351. }
  10352. }
  10353. void
  10354. mg_lock_context(struct mg_context *ctx)
  10355. {
  10356. if (ctx) {
  10357. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10358. }
  10359. }
  10360. void
  10361. mg_unlock_context(struct mg_context *ctx)
  10362. {
  10363. if (ctx) {
  10364. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10365. }
  10366. }
  10367. #if defined(USE_LUA)
  10368. #include "mod_lua.inl"
  10369. #endif /* USE_LUA */
  10370. #if defined(USE_DUKTAPE)
  10371. #include "mod_duktape.inl"
  10372. #endif /* USE_DUKTAPE */
  10373. #if defined(USE_WEBSOCKET)
  10374. #if !defined(NO_SSL_DL)
  10375. #define SHA_API static
  10376. #include "sha1.inl"
  10377. #endif
  10378. static int
  10379. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10380. {
  10381. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10382. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10383. SHA_CTX sha_ctx;
  10384. int truncated;
  10385. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10386. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10387. if (truncated) {
  10388. conn->must_close = 1;
  10389. return 0;
  10390. }
  10391. DEBUG_TRACE("%s", "Send websocket handshake");
  10392. SHA1_Init(&sha_ctx);
  10393. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10394. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10395. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10396. mg_printf(conn,
  10397. "HTTP/1.1 101 Switching Protocols\r\n"
  10398. "Upgrade: websocket\r\n"
  10399. "Connection: Upgrade\r\n"
  10400. "Sec-WebSocket-Accept: %s\r\n",
  10401. b64_sha);
  10402. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10403. mg_printf(conn,
  10404. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10405. conn->request_info.acceptedWebSocketSubprotocol);
  10406. } else {
  10407. mg_printf(conn, "%s", "\r\n");
  10408. }
  10409. return 1;
  10410. }
  10411. #if !defined(MG_MAX_UNANSWERED_PING)
  10412. /* Configuration of the maximum number of websocket PINGs that might
  10413. * stay unanswered before the connection is considered broken.
  10414. * Note: The name of this define may still change (until it is
  10415. * defined as a compile parameter in a documentation).
  10416. */
  10417. #define MG_MAX_UNANSWERED_PING (5)
  10418. #endif
  10419. static void
  10420. read_websocket(struct mg_connection *conn,
  10421. mg_websocket_data_handler ws_data_handler,
  10422. void *callback_data)
  10423. {
  10424. /* Pointer to the beginning of the portion of the incoming websocket
  10425. * message queue.
  10426. * The original websocket upgrade request is never removed, so the queue
  10427. * begins after it. */
  10428. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10429. int n, error, exit_by_callback;
  10430. int ret;
  10431. /* body_len is the length of the entire queue in bytes
  10432. * len is the length of the current message
  10433. * data_len is the length of the current message's data payload
  10434. * header_len is the length of the current message's header */
  10435. size_t i, len, mask_len = 0, header_len, body_len;
  10436. uint64_t data_len = 0;
  10437. /* "The masking key is a 32-bit value chosen at random by the client."
  10438. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10439. */
  10440. unsigned char mask[4];
  10441. /* data points to the place where the message is stored when passed to
  10442. * the websocket_data callback. This is either mem on the stack, or a
  10443. * dynamically allocated buffer if it is too large. */
  10444. unsigned char mem[4096];
  10445. unsigned char mop; /* mask flag and opcode */
  10446. /* Variables used for connection monitoring */
  10447. double timeout = -1.0;
  10448. int enable_ping_pong = 0;
  10449. int ping_count = 0;
  10450. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10451. enable_ping_pong =
  10452. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10453. "yes");
  10454. }
  10455. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10456. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10457. }
  10458. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10459. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10460. }
  10461. /* Enter data processing loop */
  10462. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10463. conn->request_info.remote_addr,
  10464. conn->request_info.remote_port);
  10465. conn->in_websocket_handling = 1;
  10466. mg_set_thread_name("wsock");
  10467. /* Loop continuously, reading messages from the socket, invoking the
  10468. * callback, and waiting repeatedly until an error occurs. */
  10469. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10470. header_len = 0;
  10471. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10472. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10473. len = buf[1] & 127;
  10474. mask_len = (buf[1] & 128) ? 4 : 0;
  10475. if ((len < 126) && (body_len >= mask_len)) {
  10476. /* inline 7-bit length field */
  10477. data_len = len;
  10478. header_len = 2 + mask_len;
  10479. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10480. /* 16-bit length field */
  10481. header_len = 4 + mask_len;
  10482. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10483. } else if (body_len >= (10 + mask_len)) {
  10484. /* 64-bit length field */
  10485. uint32_t l1, l2;
  10486. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10487. memcpy(&l2, &buf[6], 4);
  10488. header_len = 10 + mask_len;
  10489. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10490. if (data_len > (uint64_t)0x7FFF0000ul) {
  10491. /* no can do */
  10492. mg_cry_internal(
  10493. conn,
  10494. "%s",
  10495. "websocket out of memory; closing connection");
  10496. break;
  10497. }
  10498. }
  10499. }
  10500. if ((header_len > 0) && (body_len >= header_len)) {
  10501. /* Allocate space to hold websocket payload */
  10502. unsigned char *data = mem;
  10503. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10504. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10505. conn->phys_ctx);
  10506. if (data == NULL) {
  10507. /* Allocation failed, exit the loop and then close the
  10508. * connection */
  10509. mg_cry_internal(
  10510. conn,
  10511. "%s",
  10512. "websocket out of memory; closing connection");
  10513. break;
  10514. }
  10515. }
  10516. /* Copy the mask before we shift the queue and destroy it */
  10517. if (mask_len > 0) {
  10518. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10519. } else {
  10520. memset(mask, 0, sizeof(mask));
  10521. }
  10522. /* Read frame payload from the first message in the queue into
  10523. * data and advance the queue by moving the memory in place. */
  10524. DEBUG_ASSERT(body_len >= header_len);
  10525. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10526. mop = buf[0]; /* current mask and opcode */
  10527. /* Overflow case */
  10528. len = body_len - header_len;
  10529. memcpy(data, buf + header_len, len);
  10530. error = 0;
  10531. while ((uint64_t)len < data_len) {
  10532. n = pull_inner(NULL,
  10533. conn,
  10534. (char *)(data + len),
  10535. (int)(data_len - len),
  10536. timeout);
  10537. if (n <= -2) {
  10538. error = 1;
  10539. break;
  10540. } else if (n > 0) {
  10541. len += (size_t)n;
  10542. } else {
  10543. /* Timeout: should retry */
  10544. /* TODO: retry condition */
  10545. }
  10546. }
  10547. if (error) {
  10548. mg_cry_internal(
  10549. conn,
  10550. "%s",
  10551. "Websocket pull failed; closing connection");
  10552. if (data != mem) {
  10553. mg_free(data);
  10554. }
  10555. break;
  10556. }
  10557. conn->data_len = conn->request_len;
  10558. } else {
  10559. mop = buf[0]; /* current mask and opcode, overwritten by
  10560. * memmove() */
  10561. /* Length of the message being read at the front of the
  10562. * queue. Cast to 31 bit is OK, since we limited
  10563. * data_len before. */
  10564. len = (size_t)data_len + header_len;
  10565. /* Copy the data payload into the data pointer for the
  10566. * callback. Cast to 31 bit is OK, since we
  10567. * limited data_len */
  10568. memcpy(data, buf + header_len, (size_t)data_len);
  10569. /* Move the queue forward len bytes */
  10570. memmove(buf, buf + len, body_len - len);
  10571. /* Mark the queue as advanced */
  10572. conn->data_len -= (int)len;
  10573. }
  10574. /* Apply mask if necessary */
  10575. if (mask_len > 0) {
  10576. for (i = 0; i < (size_t)data_len; i++) {
  10577. data[i] ^= mask[i & 3];
  10578. }
  10579. }
  10580. exit_by_callback = 0;
  10581. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10582. /* filter PONG messages */
  10583. DEBUG_TRACE("PONG from %s:%u",
  10584. conn->request_info.remote_addr,
  10585. conn->request_info.remote_port);
  10586. /* No unanwered PINGs left */
  10587. ping_count = 0;
  10588. } else if (enable_ping_pong
  10589. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10590. /* reply PING messages */
  10591. DEBUG_TRACE("Reply PING from %s:%u",
  10592. conn->request_info.remote_addr,
  10593. conn->request_info.remote_port);
  10594. ret = mg_websocket_write(conn,
  10595. MG_WEBSOCKET_OPCODE_PONG,
  10596. (char *)data,
  10597. (size_t)data_len);
  10598. if (ret <= 0) {
  10599. /* Error: send failed */
  10600. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10601. break;
  10602. }
  10603. } else {
  10604. /* Exit the loop if callback signals to exit (server side),
  10605. * or "connection close" opcode received (client side). */
  10606. if ((ws_data_handler != NULL)
  10607. && !ws_data_handler(conn,
  10608. mop,
  10609. (char *)data,
  10610. (size_t)data_len,
  10611. callback_data)) {
  10612. exit_by_callback = 1;
  10613. }
  10614. }
  10615. /* It a buffer has been allocated, free it again */
  10616. if (data != mem) {
  10617. mg_free(data);
  10618. }
  10619. if (exit_by_callback) {
  10620. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10621. conn->request_info.remote_addr,
  10622. conn->request_info.remote_port);
  10623. break;
  10624. }
  10625. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10626. /* Opcode == 8, connection close */
  10627. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10628. conn->request_info.remote_addr,
  10629. conn->request_info.remote_port);
  10630. break;
  10631. }
  10632. /* Not breaking the loop, process next websocket frame. */
  10633. } else {
  10634. /* Read from the socket into the next available location in the
  10635. * message queue. */
  10636. n = pull_inner(NULL,
  10637. conn,
  10638. conn->buf + conn->data_len,
  10639. conn->buf_size - conn->data_len,
  10640. timeout);
  10641. if (n <= -2) {
  10642. /* Error, no bytes read */
  10643. DEBUG_TRACE("PULL from %s:%u failed",
  10644. conn->request_info.remote_addr,
  10645. conn->request_info.remote_port);
  10646. break;
  10647. }
  10648. if (n > 0) {
  10649. conn->data_len += n;
  10650. /* Reset open PING count */
  10651. ping_count = 0;
  10652. } else {
  10653. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10654. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10655. /* Stop sending PING */
  10656. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10657. "- closing connection",
  10658. ping_count,
  10659. conn->request_info.remote_addr,
  10660. conn->request_info.remote_port);
  10661. break;
  10662. }
  10663. if (enable_ping_pong) {
  10664. /* Send Websocket PING message */
  10665. DEBUG_TRACE("PING to %s:%u",
  10666. conn->request_info.remote_addr,
  10667. conn->request_info.remote_port);
  10668. ret = mg_websocket_write(conn,
  10669. MG_WEBSOCKET_OPCODE_PING,
  10670. NULL,
  10671. 0);
  10672. if (ret <= 0) {
  10673. /* Error: send failed */
  10674. DEBUG_TRACE("Send PING failed (%i)", ret);
  10675. break;
  10676. }
  10677. ping_count++;
  10678. }
  10679. }
  10680. /* Timeout: should retry */
  10681. /* TODO: get timeout def */
  10682. }
  10683. }
  10684. }
  10685. /* Leave data processing loop */
  10686. mg_set_thread_name("worker");
  10687. conn->in_websocket_handling = 0;
  10688. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10689. conn->request_info.remote_addr,
  10690. conn->request_info.remote_port);
  10691. }
  10692. static int
  10693. mg_websocket_write_exec(struct mg_connection *conn,
  10694. int opcode,
  10695. const char *data,
  10696. size_t dataLen,
  10697. uint32_t masking_key)
  10698. {
  10699. unsigned char header[14];
  10700. size_t headerLen;
  10701. int retval;
  10702. #if defined(GCC_DIAGNOSTIC)
  10703. /* Disable spurious conversion warning for GCC */
  10704. #pragma GCC diagnostic push
  10705. #pragma GCC diagnostic ignored "-Wconversion"
  10706. #endif
  10707. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10708. #if defined(GCC_DIAGNOSTIC)
  10709. #pragma GCC diagnostic pop
  10710. #endif
  10711. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10712. if (dataLen < 126) {
  10713. /* inline 7-bit length field */
  10714. header[1] = (unsigned char)dataLen;
  10715. headerLen = 2;
  10716. } else if (dataLen <= 0xFFFF) {
  10717. /* 16-bit length field */
  10718. uint16_t len = htons((uint16_t)dataLen);
  10719. header[1] = 126;
  10720. memcpy(header + 2, &len, 2);
  10721. headerLen = 4;
  10722. } else {
  10723. /* 64-bit length field */
  10724. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10725. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10726. header[1] = 127;
  10727. memcpy(header + 2, &len1, 4);
  10728. memcpy(header + 6, &len2, 4);
  10729. headerLen = 10;
  10730. }
  10731. if (masking_key) {
  10732. /* add mask */
  10733. header[1] |= 0x80;
  10734. memcpy(header + headerLen, &masking_key, 4);
  10735. headerLen += 4;
  10736. }
  10737. /* Note that POSIX/Winsock's send() is threadsafe
  10738. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10739. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10740. * push(), although that is only a problem if the packet is large or
  10741. * outgoing buffer is full). */
  10742. /* TODO: Check if this lock should be moved to user land.
  10743. * Currently the server sets this lock for websockets, but
  10744. * not for any other connection. It must be set for every
  10745. * conn read/written by more than one thread, no matter if
  10746. * it is a websocket or regular connection. */
  10747. (void)mg_lock_connection(conn);
  10748. retval = mg_write(conn, header, headerLen);
  10749. if (retval != (int)headerLen) {
  10750. /* Did not send complete header */
  10751. retval = -1;
  10752. } else {
  10753. if (dataLen > 0) {
  10754. retval = mg_write(conn, data, dataLen);
  10755. }
  10756. /* if dataLen == 0, the header length (2) is returned */
  10757. }
  10758. /* TODO: Remove this unlock as well, when lock is removed. */
  10759. mg_unlock_connection(conn);
  10760. return retval;
  10761. }
  10762. int
  10763. mg_websocket_write(struct mg_connection *conn,
  10764. int opcode,
  10765. const char *data,
  10766. size_t dataLen)
  10767. {
  10768. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10769. }
  10770. static void
  10771. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10772. {
  10773. size_t i = 0;
  10774. i = 0;
  10775. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10776. /* Convert in 32 bit words, if data is 4 byte aligned */
  10777. while (i < (in_len - 3)) {
  10778. *(uint32_t *)(void *)(out + i) =
  10779. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10780. i += 4;
  10781. }
  10782. }
  10783. if (i != in_len) {
  10784. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10785. while (i < in_len) {
  10786. *(uint8_t *)(void *)(out + i) =
  10787. *(uint8_t *)(void *)(in + i)
  10788. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10789. i++;
  10790. }
  10791. }
  10792. }
  10793. int
  10794. mg_websocket_client_write(struct mg_connection *conn,
  10795. int opcode,
  10796. const char *data,
  10797. size_t dataLen)
  10798. {
  10799. int retval = -1;
  10800. char *masked_data =
  10801. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10802. uint32_t masking_key = 0;
  10803. if (masked_data == NULL) {
  10804. /* Return -1 in an error case */
  10805. mg_cry_internal(conn,
  10806. "%s",
  10807. "Cannot allocate buffer for masked websocket response: "
  10808. "Out of memory");
  10809. return -1;
  10810. }
  10811. do {
  10812. /* Get a masking key - but not 0 */
  10813. masking_key = (uint32_t)get_random();
  10814. } while (masking_key == 0);
  10815. mask_data(data, dataLen, masking_key, masked_data);
  10816. retval = mg_websocket_write_exec(
  10817. conn, opcode, masked_data, dataLen, masking_key);
  10818. mg_free(masked_data);
  10819. return retval;
  10820. }
  10821. static void
  10822. handle_websocket_request(struct mg_connection *conn,
  10823. const char *path,
  10824. int is_callback_resource,
  10825. struct mg_websocket_subprotocols *subprotocols,
  10826. mg_websocket_connect_handler ws_connect_handler,
  10827. mg_websocket_ready_handler ws_ready_handler,
  10828. mg_websocket_data_handler ws_data_handler,
  10829. mg_websocket_close_handler ws_close_handler,
  10830. void *cbData)
  10831. {
  10832. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10833. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10834. ptrdiff_t lua_websock = 0;
  10835. #if !defined(USE_LUA)
  10836. (void)path;
  10837. #endif
  10838. /* Step 1: Check websocket protocol version. */
  10839. /* Step 1.1: Check Sec-WebSocket-Key. */
  10840. if (!websock_key) {
  10841. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10842. * requires a Sec-WebSocket-Key header.
  10843. */
  10844. /* It could be the hixie draft version
  10845. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10846. */
  10847. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10848. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10849. char key3[8];
  10850. if ((key1 != NULL) && (key2 != NULL)) {
  10851. /* This version uses 8 byte body data in a GET request */
  10852. conn->content_len = 8;
  10853. if (8 == mg_read(conn, key3, 8)) {
  10854. /* This is the hixie version */
  10855. mg_send_http_error(conn,
  10856. 426,
  10857. "%s",
  10858. "Protocol upgrade to RFC 6455 required");
  10859. return;
  10860. }
  10861. }
  10862. /* This is an unknown version */
  10863. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10864. return;
  10865. }
  10866. /* Step 1.2: Check websocket protocol version. */
  10867. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10868. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10869. /* Reject wrong versions */
  10870. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10871. return;
  10872. }
  10873. /* Step 1.3: Could check for "Host", but we do not really nead this
  10874. * value for anything, so just ignore it. */
  10875. /* Step 2: If a callback is responsible, call it. */
  10876. if (is_callback_resource) {
  10877. /* Step 2.1 check and select subprotocol */
  10878. const char *protocols[64]; // max 64 headers
  10879. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10880. "Sec-WebSocket-Protocol",
  10881. protocols,
  10882. 64);
  10883. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10884. int cnt = 0;
  10885. int idx;
  10886. unsigned long len;
  10887. const char *sep, *curSubProtocol,
  10888. *acceptedWebSocketSubprotocol = NULL;
  10889. /* look for matching subprotocol */
  10890. do {
  10891. const char *protocol = protocols[cnt];
  10892. do {
  10893. sep = strchr(protocol, ',');
  10894. curSubProtocol = protocol;
  10895. len = sep ? (unsigned long)(sep - protocol)
  10896. : (unsigned long)strlen(protocol);
  10897. while (sep && isspace((unsigned char)*++sep))
  10898. ; // ignore leading whitespaces
  10899. protocol = sep;
  10900. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10901. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10902. && (strncmp(curSubProtocol,
  10903. subprotocols->subprotocols[idx],
  10904. len)
  10905. == 0)) {
  10906. acceptedWebSocketSubprotocol =
  10907. subprotocols->subprotocols[idx];
  10908. break;
  10909. }
  10910. }
  10911. } while (sep && !acceptedWebSocketSubprotocol);
  10912. } while (++cnt < nbSubprotocolHeader
  10913. && !acceptedWebSocketSubprotocol);
  10914. conn->request_info.acceptedWebSocketSubprotocol =
  10915. acceptedWebSocketSubprotocol;
  10916. } else if (nbSubprotocolHeader > 0) {
  10917. /* keep legacy behavior */
  10918. const char *protocol = protocols[0];
  10919. /* The protocol is a comma separated list of names. */
  10920. /* The server must only return one value from this list. */
  10921. /* First check if it is a list or just a single value. */
  10922. const char *sep = strrchr(protocol, ',');
  10923. if (sep == NULL) {
  10924. /* Just a single protocol -> accept it. */
  10925. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10926. } else {
  10927. /* Multiple protocols -> accept the last one. */
  10928. /* This is just a quick fix if the client offers multiple
  10929. * protocols. The handler should have a list of accepted
  10930. * protocols on his own
  10931. * and use it to select one protocol among those the client
  10932. * has
  10933. * offered.
  10934. */
  10935. while (isspace((unsigned char)*++sep)) {
  10936. ; /* ignore leading whitespaces */
  10937. }
  10938. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10939. }
  10940. }
  10941. if ((ws_connect_handler != NULL)
  10942. && (ws_connect_handler(conn, cbData) != 0)) {
  10943. /* C callback has returned non-zero, do not proceed with
  10944. * handshake.
  10945. */
  10946. /* Note that C callbacks are no longer called when Lua is
  10947. * responsible, so C can no longer filter callbacks for Lua. */
  10948. return;
  10949. }
  10950. }
  10951. #if defined(USE_LUA)
  10952. /* Step 3: No callback. Check if Lua is responsible. */
  10953. else {
  10954. /* Step 3.1: Check if Lua is responsible. */
  10955. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10956. lua_websock = match_prefix(
  10957. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10958. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10959. path);
  10960. }
  10961. if (lua_websock) {
  10962. /* Step 3.2: Lua is responsible: call it. */
  10963. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10964. if (!conn->lua_websocket_state) {
  10965. /* Lua rejected the new client */
  10966. return;
  10967. }
  10968. }
  10969. }
  10970. #endif
  10971. /* Step 4: Check if there is a responsible websocket handler. */
  10972. if (!is_callback_resource && !lua_websock) {
  10973. /* There is no callback, and Lua is not responsible either. */
  10974. /* Reply with a 404 Not Found. We are still at a standard
  10975. * HTTP request here, before the websocket handshake, so
  10976. * we can still send standard HTTP error replies. */
  10977. mg_send_http_error(conn, 404, "%s", "Not found");
  10978. return;
  10979. }
  10980. /* Step 5: The websocket connection has been accepted */
  10981. if (!send_websocket_handshake(conn, websock_key)) {
  10982. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10983. return;
  10984. }
  10985. /* Step 6: Call the ready handler */
  10986. if (is_callback_resource) {
  10987. if (ws_ready_handler != NULL) {
  10988. ws_ready_handler(conn, cbData);
  10989. }
  10990. #if defined(USE_LUA)
  10991. } else if (lua_websock) {
  10992. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10993. /* the ready handler returned false */
  10994. return;
  10995. }
  10996. #endif
  10997. }
  10998. /* Step 7: Enter the read loop */
  10999. if (is_callback_resource) {
  11000. read_websocket(conn, ws_data_handler, cbData);
  11001. #if defined(USE_LUA)
  11002. } else if (lua_websock) {
  11003. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  11004. #endif
  11005. }
  11006. /* Step 8: Call the close handler */
  11007. if (ws_close_handler) {
  11008. ws_close_handler(conn, cbData);
  11009. }
  11010. }
  11011. static int
  11012. is_websocket_protocol(const struct mg_connection *conn)
  11013. {
  11014. const char *upgrade, *connection;
  11015. /* A websocket protocoll has the following HTTP headers:
  11016. *
  11017. * Connection: Upgrade
  11018. * Upgrade: Websocket
  11019. */
  11020. upgrade = mg_get_header(conn, "Upgrade");
  11021. if (upgrade == NULL) {
  11022. return 0; /* fail early, don't waste time checking other header
  11023. * fields
  11024. */
  11025. }
  11026. if (!mg_strcasestr(upgrade, "websocket")) {
  11027. return 0;
  11028. }
  11029. connection = mg_get_header(conn, "Connection");
  11030. if (connection == NULL) {
  11031. return 0;
  11032. }
  11033. if (!mg_strcasestr(connection, "upgrade")) {
  11034. return 0;
  11035. }
  11036. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11037. * "Sec-WebSocket-Version" are also required.
  11038. * Don't check them here, since even an unsupported websocket protocol
  11039. * request still IS a websocket request (in contrast to a standard HTTP
  11040. * request). It will fail later in handle_websocket_request.
  11041. */
  11042. return 1;
  11043. }
  11044. #endif /* !USE_WEBSOCKET */
  11045. static int
  11046. isbyte(int n)
  11047. {
  11048. return (n >= 0) && (n <= 255);
  11049. }
  11050. static int
  11051. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11052. {
  11053. int n, a, b, c, d, slash = 32, len = 0;
  11054. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11055. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11056. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11057. && (slash < 33)) {
  11058. len = n;
  11059. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11060. | (uint32_t)d;
  11061. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11062. }
  11063. return len;
  11064. }
  11065. static int
  11066. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11067. {
  11068. int throttle = 0;
  11069. struct vec vec, val;
  11070. uint32_t net, mask;
  11071. char mult;
  11072. double v;
  11073. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11074. mult = ',';
  11075. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11076. || (v < 0)
  11077. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11078. && (mult != ','))) {
  11079. continue;
  11080. }
  11081. v *= (lowercase(&mult) == 'k')
  11082. ? 1024
  11083. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11084. if (vec.len == 1 && vec.ptr[0] == '*') {
  11085. throttle = (int)v;
  11086. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11087. if ((remote_ip & mask) == net) {
  11088. throttle = (int)v;
  11089. }
  11090. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11091. throttle = (int)v;
  11092. }
  11093. }
  11094. return throttle;
  11095. }
  11096. static uint32_t
  11097. get_remote_ip(const struct mg_connection *conn)
  11098. {
  11099. if (!conn) {
  11100. return 0;
  11101. }
  11102. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11103. }
  11104. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11105. #include "handle_form.inl"
  11106. #if defined(MG_LEGACY_INTERFACE)
  11107. /* Implement the deprecated mg_upload function by calling the new
  11108. * mg_handle_form_request function. While mg_upload could only handle
  11109. * HTML forms sent as POST request in multipart/form-data format
  11110. * containing only file input elements, mg_handle_form_request can
  11111. * handle all form input elements and all standard request methods. */
  11112. struct mg_upload_user_data {
  11113. struct mg_connection *conn;
  11114. const char *destination_dir;
  11115. int num_uploaded_files;
  11116. };
  11117. /* Helper function for deprecated mg_upload. */
  11118. static int
  11119. mg_upload_field_found(const char *key,
  11120. const char *filename,
  11121. char *path,
  11122. size_t pathlen,
  11123. void *user_data)
  11124. {
  11125. int truncated = 0;
  11126. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11127. (void)key;
  11128. if (!filename) {
  11129. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11130. return FORM_FIELD_STORAGE_ABORT;
  11131. }
  11132. mg_snprintf(fud->conn,
  11133. &truncated,
  11134. path,
  11135. pathlen - 1,
  11136. "%s/%s",
  11137. fud->destination_dir,
  11138. filename);
  11139. if (truncated) {
  11140. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11141. return FORM_FIELD_STORAGE_ABORT;
  11142. }
  11143. return FORM_FIELD_STORAGE_STORE;
  11144. }
  11145. /* Helper function for deprecated mg_upload. */
  11146. static int
  11147. mg_upload_field_get(const char *key,
  11148. const char *value,
  11149. size_t value_size,
  11150. void *user_data)
  11151. {
  11152. /* Function should never be called */
  11153. (void)key;
  11154. (void)value;
  11155. (void)value_size;
  11156. (void)user_data;
  11157. return 0;
  11158. }
  11159. /* Helper function for deprecated mg_upload. */
  11160. static int
  11161. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11162. {
  11163. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11164. (void)file_size;
  11165. fud->num_uploaded_files++;
  11166. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11167. return 0;
  11168. }
  11169. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11170. int
  11171. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11172. {
  11173. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11174. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11175. mg_upload_field_get,
  11176. mg_upload_field_stored,
  11177. 0};
  11178. int ret;
  11179. fdh.user_data = (void *)&fud;
  11180. ret = mg_handle_form_request(conn, &fdh);
  11181. if (ret < 0) {
  11182. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11183. }
  11184. return fud.num_uploaded_files;
  11185. }
  11186. #endif
  11187. static int
  11188. get_first_ssl_listener_index(const struct mg_context *ctx)
  11189. {
  11190. unsigned int i;
  11191. int idx = -1;
  11192. if (ctx) {
  11193. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11194. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11195. }
  11196. }
  11197. return idx;
  11198. }
  11199. /* Return host (without port) */
  11200. /* Use mg_free to free the result */
  11201. static const char *
  11202. alloc_get_host(struct mg_connection *conn)
  11203. {
  11204. char buf[1025];
  11205. size_t buflen = sizeof(buf);
  11206. const char *host_header = get_header(conn->request_info.http_headers,
  11207. conn->request_info.num_headers,
  11208. "Host");
  11209. char *host;
  11210. if (host_header != NULL) {
  11211. char *pos;
  11212. /* Create a local copy of the "Host" header, since it might be
  11213. * modified here. */
  11214. mg_strlcpy(buf, host_header, buflen);
  11215. buf[buflen - 1] = '\0';
  11216. host = buf;
  11217. while (isspace((unsigned char)*host)) {
  11218. host++;
  11219. }
  11220. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11221. * is found. */
  11222. if (*host == '[') {
  11223. pos = strchr(host, ']');
  11224. if (!pos) {
  11225. /* Malformed hostname starts with '[', but no ']' found */
  11226. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11227. return NULL;
  11228. }
  11229. /* terminate after ']' */
  11230. pos[1] = 0;
  11231. } else {
  11232. /* Otherwise, a ':' separates hostname and port number */
  11233. pos = strchr(host, ':');
  11234. if (pos != NULL) {
  11235. *pos = '\0';
  11236. }
  11237. }
  11238. if (conn->ssl) {
  11239. /* This is a HTTPS connection, maybe we have a hostname
  11240. * from SNI (set in ssl_servername_callback). */
  11241. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11242. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11243. /* We are not using the default domain */
  11244. if (mg_strcasecmp(host, sslhost)) {
  11245. /* Mismatch between SNI domain and HTTP domain */
  11246. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11247. sslhost,
  11248. host);
  11249. return NULL;
  11250. }
  11251. }
  11252. DEBUG_TRACE("HTTPS Host: %s", host);
  11253. } else {
  11254. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11255. while (dom) {
  11256. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11257. /* Found matching domain */
  11258. DEBUG_TRACE("HTTP domain %s found",
  11259. dom->config[AUTHENTICATION_DOMAIN]);
  11260. /* TODO: Check if this is a HTTP or HTTPS domain */
  11261. conn->dom_ctx = dom;
  11262. break;
  11263. }
  11264. dom = dom->next;
  11265. }
  11266. DEBUG_TRACE("HTTP Host: %s", host);
  11267. }
  11268. } else {
  11269. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11270. host = buf;
  11271. DEBUG_TRACE("IP: %s", host);
  11272. }
  11273. return mg_strdup_ctx(host, conn->phys_ctx);
  11274. }
  11275. static void
  11276. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11277. {
  11278. char target_url[MG_BUF_LEN];
  11279. int truncated = 0;
  11280. conn->must_close = 1;
  11281. /* Send host, port, uri and (if it exists) ?query_string */
  11282. if (conn->host) {
  11283. /* Use "308 Permanent Redirect" */
  11284. int redirect_code = 308;
  11285. /* Create target URL */
  11286. mg_snprintf(
  11287. conn,
  11288. &truncated,
  11289. target_url,
  11290. sizeof(target_url),
  11291. "https://%s:%d%s%s%s",
  11292. conn->host,
  11293. #if defined(USE_IPV6)
  11294. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11295. == AF_INET6)
  11296. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11297. .lsa.sin6.sin6_port)
  11298. :
  11299. #endif
  11300. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11301. .lsa.sin.sin_port),
  11302. conn->request_info.local_uri,
  11303. (conn->request_info.query_string == NULL) ? "" : "?",
  11304. (conn->request_info.query_string == NULL)
  11305. ? ""
  11306. : conn->request_info.query_string);
  11307. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11308. * is used as buffer size) */
  11309. if (truncated) {
  11310. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11311. return;
  11312. }
  11313. /* Use redirect helper function */
  11314. mg_send_http_redirect(conn, target_url, redirect_code);
  11315. }
  11316. }
  11317. static void
  11318. handler_info_acquire(struct mg_handler_info *handler_info)
  11319. {
  11320. pthread_mutex_lock(&handler_info->refcount_mutex);
  11321. handler_info->refcount++;
  11322. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11323. }
  11324. static void
  11325. handler_info_release(struct mg_handler_info *handler_info)
  11326. {
  11327. pthread_mutex_lock(&handler_info->refcount_mutex);
  11328. handler_info->refcount--;
  11329. pthread_cond_signal(&handler_info->refcount_cond);
  11330. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11331. }
  11332. static void
  11333. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11334. {
  11335. pthread_mutex_lock(&handler_info->refcount_mutex);
  11336. while (handler_info->refcount) {
  11337. pthread_cond_wait(&handler_info->refcount_cond,
  11338. &handler_info->refcount_mutex);
  11339. }
  11340. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11341. }
  11342. static void
  11343. mg_set_handler_type(struct mg_context *phys_ctx,
  11344. struct mg_domain_context *dom_ctx,
  11345. const char *uri,
  11346. int handler_type,
  11347. int is_delete_request,
  11348. mg_request_handler handler,
  11349. struct mg_websocket_subprotocols *subprotocols,
  11350. mg_websocket_connect_handler connect_handler,
  11351. mg_websocket_ready_handler ready_handler,
  11352. mg_websocket_data_handler data_handler,
  11353. mg_websocket_close_handler close_handler,
  11354. mg_authorization_handler auth_handler,
  11355. void *cbdata)
  11356. {
  11357. struct mg_handler_info *tmp_rh, **lastref;
  11358. size_t urilen = strlen(uri);
  11359. if (handler_type == WEBSOCKET_HANDLER) {
  11360. DEBUG_ASSERT(handler == NULL);
  11361. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11362. || ready_handler != NULL || data_handler != NULL
  11363. || close_handler != NULL);
  11364. DEBUG_ASSERT(auth_handler == NULL);
  11365. if (handler != NULL) {
  11366. return;
  11367. }
  11368. if (!is_delete_request && (connect_handler == NULL)
  11369. && (ready_handler == NULL) && (data_handler == NULL)
  11370. && (close_handler == NULL)) {
  11371. return;
  11372. }
  11373. if (auth_handler != NULL) {
  11374. return;
  11375. }
  11376. } else if (handler_type == REQUEST_HANDLER) {
  11377. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11378. && data_handler == NULL && close_handler == NULL);
  11379. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11380. DEBUG_ASSERT(auth_handler == NULL);
  11381. if ((connect_handler != NULL) || (ready_handler != NULL)
  11382. || (data_handler != NULL) || (close_handler != NULL)) {
  11383. return;
  11384. }
  11385. if (!is_delete_request && (handler == NULL)) {
  11386. return;
  11387. }
  11388. if (auth_handler != NULL) {
  11389. return;
  11390. }
  11391. } else { /* AUTH_HANDLER */
  11392. DEBUG_ASSERT(handler == NULL);
  11393. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11394. && data_handler == NULL && close_handler == NULL);
  11395. DEBUG_ASSERT(auth_handler != NULL);
  11396. if (handler != NULL) {
  11397. return;
  11398. }
  11399. if ((connect_handler != NULL) || (ready_handler != NULL)
  11400. || (data_handler != NULL) || (close_handler != NULL)) {
  11401. return;
  11402. }
  11403. if (!is_delete_request && (auth_handler == NULL)) {
  11404. return;
  11405. }
  11406. }
  11407. if (!phys_ctx || !dom_ctx) {
  11408. return;
  11409. }
  11410. mg_lock_context(phys_ctx);
  11411. /* first try to find an existing handler */
  11412. lastref = &(dom_ctx->handlers);
  11413. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11414. if (tmp_rh->handler_type == handler_type) {
  11415. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11416. if (!is_delete_request) {
  11417. /* update existing handler */
  11418. if (handler_type == REQUEST_HANDLER) {
  11419. /* Wait for end of use before updating */
  11420. handler_info_wait_unused(tmp_rh);
  11421. /* Ok, the handler is no more use -> Update it */
  11422. tmp_rh->handler = handler;
  11423. } else if (handler_type == WEBSOCKET_HANDLER) {
  11424. tmp_rh->subprotocols = subprotocols;
  11425. tmp_rh->connect_handler = connect_handler;
  11426. tmp_rh->ready_handler = ready_handler;
  11427. tmp_rh->data_handler = data_handler;
  11428. tmp_rh->close_handler = close_handler;
  11429. } else { /* AUTH_HANDLER */
  11430. tmp_rh->auth_handler = auth_handler;
  11431. }
  11432. tmp_rh->cbdata = cbdata;
  11433. } else {
  11434. /* remove existing handler */
  11435. if (handler_type == REQUEST_HANDLER) {
  11436. /* Wait for end of use before removing */
  11437. handler_info_wait_unused(tmp_rh);
  11438. /* Ok, the handler is no more used -> Destroy resources
  11439. */
  11440. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11441. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11442. }
  11443. *lastref = tmp_rh->next;
  11444. mg_free(tmp_rh->uri);
  11445. mg_free(tmp_rh);
  11446. }
  11447. mg_unlock_context(phys_ctx);
  11448. return;
  11449. }
  11450. }
  11451. lastref = &(tmp_rh->next);
  11452. }
  11453. if (is_delete_request) {
  11454. /* no handler to set, this was a remove request to a non-existing
  11455. * handler */
  11456. mg_unlock_context(phys_ctx);
  11457. return;
  11458. }
  11459. tmp_rh =
  11460. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11461. 1,
  11462. phys_ctx);
  11463. if (tmp_rh == NULL) {
  11464. mg_unlock_context(phys_ctx);
  11465. mg_cry_internal(fc(phys_ctx),
  11466. "%s",
  11467. "Cannot create new request handler struct, OOM");
  11468. return;
  11469. }
  11470. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11471. if (!tmp_rh->uri) {
  11472. mg_unlock_context(phys_ctx);
  11473. mg_free(tmp_rh);
  11474. mg_cry_internal(fc(phys_ctx),
  11475. "%s",
  11476. "Cannot create new request handler struct, OOM");
  11477. return;
  11478. }
  11479. tmp_rh->uri_len = urilen;
  11480. if (handler_type == REQUEST_HANDLER) {
  11481. /* Init refcount mutex and condition */
  11482. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11483. mg_unlock_context(phys_ctx);
  11484. mg_free(tmp_rh);
  11485. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");
  11486. return;
  11487. }
  11488. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11489. mg_unlock_context(phys_ctx);
  11490. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11491. mg_free(tmp_rh);
  11492. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");
  11493. return;
  11494. }
  11495. tmp_rh->refcount = 0;
  11496. tmp_rh->handler = handler;
  11497. } else if (handler_type == WEBSOCKET_HANDLER) {
  11498. tmp_rh->subprotocols = subprotocols;
  11499. tmp_rh->connect_handler = connect_handler;
  11500. tmp_rh->ready_handler = ready_handler;
  11501. tmp_rh->data_handler = data_handler;
  11502. tmp_rh->close_handler = close_handler;
  11503. } else { /* AUTH_HANDLER */
  11504. tmp_rh->auth_handler = auth_handler;
  11505. }
  11506. tmp_rh->cbdata = cbdata;
  11507. tmp_rh->handler_type = handler_type;
  11508. tmp_rh->next = NULL;
  11509. *lastref = tmp_rh;
  11510. mg_unlock_context(phys_ctx);
  11511. }
  11512. void
  11513. mg_set_request_handler(struct mg_context *ctx,
  11514. const char *uri,
  11515. mg_request_handler handler,
  11516. void *cbdata)
  11517. {
  11518. mg_set_handler_type(ctx,
  11519. &(ctx->dd),
  11520. uri,
  11521. REQUEST_HANDLER,
  11522. handler == NULL,
  11523. handler,
  11524. NULL,
  11525. NULL,
  11526. NULL,
  11527. NULL,
  11528. NULL,
  11529. NULL,
  11530. cbdata);
  11531. }
  11532. void
  11533. mg_set_websocket_handler(struct mg_context *ctx,
  11534. const char *uri,
  11535. mg_websocket_connect_handler connect_handler,
  11536. mg_websocket_ready_handler ready_handler,
  11537. mg_websocket_data_handler data_handler,
  11538. mg_websocket_close_handler close_handler,
  11539. void *cbdata)
  11540. {
  11541. mg_set_websocket_handler_with_subprotocols(ctx,
  11542. uri,
  11543. NULL,
  11544. connect_handler,
  11545. ready_handler,
  11546. data_handler,
  11547. close_handler,
  11548. cbdata);
  11549. }
  11550. void
  11551. mg_set_websocket_handler_with_subprotocols(
  11552. struct mg_context *ctx,
  11553. const char *uri,
  11554. struct mg_websocket_subprotocols *subprotocols,
  11555. mg_websocket_connect_handler connect_handler,
  11556. mg_websocket_ready_handler ready_handler,
  11557. mg_websocket_data_handler data_handler,
  11558. mg_websocket_close_handler close_handler,
  11559. void *cbdata)
  11560. {
  11561. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11562. && (data_handler == NULL)
  11563. && (close_handler == NULL);
  11564. mg_set_handler_type(ctx,
  11565. &(ctx->dd),
  11566. uri,
  11567. WEBSOCKET_HANDLER,
  11568. is_delete_request,
  11569. NULL,
  11570. subprotocols,
  11571. connect_handler,
  11572. ready_handler,
  11573. data_handler,
  11574. close_handler,
  11575. NULL,
  11576. cbdata);
  11577. }
  11578. void
  11579. mg_set_auth_handler(struct mg_context *ctx,
  11580. const char *uri,
  11581. mg_authorization_handler handler,
  11582. void *cbdata)
  11583. {
  11584. mg_set_handler_type(ctx,
  11585. &(ctx->dd),
  11586. uri,
  11587. AUTH_HANDLER,
  11588. handler == NULL,
  11589. NULL,
  11590. NULL,
  11591. NULL,
  11592. NULL,
  11593. NULL,
  11594. NULL,
  11595. handler,
  11596. cbdata);
  11597. }
  11598. static int
  11599. get_request_handler(struct mg_connection *conn,
  11600. int handler_type,
  11601. mg_request_handler *handler,
  11602. struct mg_websocket_subprotocols **subprotocols,
  11603. mg_websocket_connect_handler *connect_handler,
  11604. mg_websocket_ready_handler *ready_handler,
  11605. mg_websocket_data_handler *data_handler,
  11606. mg_websocket_close_handler *close_handler,
  11607. mg_authorization_handler *auth_handler,
  11608. void **cbdata,
  11609. struct mg_handler_info **handler_info)
  11610. {
  11611. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11612. if (request_info) {
  11613. const char *uri = request_info->local_uri;
  11614. size_t urilen = strlen(uri);
  11615. struct mg_handler_info *tmp_rh;
  11616. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11617. return 0;
  11618. }
  11619. mg_lock_context(conn->phys_ctx);
  11620. /* first try for an exact match */
  11621. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11622. tmp_rh = tmp_rh->next) {
  11623. if (tmp_rh->handler_type == handler_type) {
  11624. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11625. if (handler_type == WEBSOCKET_HANDLER) {
  11626. *subprotocols = tmp_rh->subprotocols;
  11627. *connect_handler = tmp_rh->connect_handler;
  11628. *ready_handler = tmp_rh->ready_handler;
  11629. *data_handler = tmp_rh->data_handler;
  11630. *close_handler = tmp_rh->close_handler;
  11631. } else if (handler_type == REQUEST_HANDLER) {
  11632. *handler = tmp_rh->handler;
  11633. /* Acquire handler and give it back */
  11634. handler_info_acquire(tmp_rh);
  11635. *handler_info = tmp_rh;
  11636. } else { /* AUTH_HANDLER */
  11637. *auth_handler = tmp_rh->auth_handler;
  11638. }
  11639. *cbdata = tmp_rh->cbdata;
  11640. mg_unlock_context(conn->phys_ctx);
  11641. return 1;
  11642. }
  11643. }
  11644. }
  11645. /* next try for a partial match, we will accept uri/something */
  11646. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11647. tmp_rh = tmp_rh->next) {
  11648. if (tmp_rh->handler_type == handler_type) {
  11649. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11650. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11651. if (handler_type == WEBSOCKET_HANDLER) {
  11652. *subprotocols = tmp_rh->subprotocols;
  11653. *connect_handler = tmp_rh->connect_handler;
  11654. *ready_handler = tmp_rh->ready_handler;
  11655. *data_handler = tmp_rh->data_handler;
  11656. *close_handler = tmp_rh->close_handler;
  11657. } else if (handler_type == REQUEST_HANDLER) {
  11658. *handler = tmp_rh->handler;
  11659. /* Acquire handler and give it back */
  11660. handler_info_acquire(tmp_rh);
  11661. *handler_info = tmp_rh;
  11662. } else { /* AUTH_HANDLER */
  11663. *auth_handler = tmp_rh->auth_handler;
  11664. }
  11665. *cbdata = tmp_rh->cbdata;
  11666. mg_unlock_context(conn->phys_ctx);
  11667. return 1;
  11668. }
  11669. }
  11670. }
  11671. /* finally try for pattern match */
  11672. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11673. tmp_rh = tmp_rh->next) {
  11674. if (tmp_rh->handler_type == handler_type) {
  11675. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11676. if (handler_type == WEBSOCKET_HANDLER) {
  11677. *subprotocols = tmp_rh->subprotocols;
  11678. *connect_handler = tmp_rh->connect_handler;
  11679. *ready_handler = tmp_rh->ready_handler;
  11680. *data_handler = tmp_rh->data_handler;
  11681. *close_handler = tmp_rh->close_handler;
  11682. } else if (handler_type == REQUEST_HANDLER) {
  11683. *handler = tmp_rh->handler;
  11684. /* Acquire handler and give it back */
  11685. handler_info_acquire(tmp_rh);
  11686. *handler_info = tmp_rh;
  11687. } else { /* AUTH_HANDLER */
  11688. *auth_handler = tmp_rh->auth_handler;
  11689. }
  11690. *cbdata = tmp_rh->cbdata;
  11691. mg_unlock_context(conn->phys_ctx);
  11692. return 1;
  11693. }
  11694. }
  11695. }
  11696. mg_unlock_context(conn->phys_ctx);
  11697. }
  11698. return 0; /* none found */
  11699. }
  11700. /* Check if the script file is in a path, allowed for script files.
  11701. * This can be used if uploading files is possible not only for the server
  11702. * admin, and the upload mechanism does not check the file extension.
  11703. */
  11704. static int
  11705. is_in_script_path(const struct mg_connection *conn, const char *path)
  11706. {
  11707. /* TODO (Feature): Add config value for allowed script path.
  11708. * Default: All allowed. */
  11709. (void)conn;
  11710. (void)path;
  11711. return 1;
  11712. }
  11713. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11714. static int
  11715. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11716. void *cbdata)
  11717. {
  11718. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11719. if (pcallbacks->websocket_connect) {
  11720. return pcallbacks->websocket_connect(conn);
  11721. }
  11722. /* No handler set - assume "OK" */
  11723. return 0;
  11724. }
  11725. static void
  11726. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11727. {
  11728. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11729. if (pcallbacks->websocket_ready) {
  11730. pcallbacks->websocket_ready(conn);
  11731. }
  11732. }
  11733. static int
  11734. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11735. int bits,
  11736. char *data,
  11737. size_t len,
  11738. void *cbdata)
  11739. {
  11740. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11741. if (pcallbacks->websocket_data) {
  11742. return pcallbacks->websocket_data(conn, bits, data, len);
  11743. }
  11744. /* No handler set - assume "OK" */
  11745. return 1;
  11746. }
  11747. #endif
  11748. /* This is the heart of the Civetweb's logic.
  11749. * This function is called when the request is read, parsed and validated,
  11750. * and Civetweb must decide what action to take: serve a file, or
  11751. * a directory, or call embedded function, etcetera. */
  11752. static void
  11753. handle_request(struct mg_connection *conn)
  11754. {
  11755. struct mg_request_info *ri = &conn->request_info;
  11756. char path[PATH_MAX];
  11757. int uri_len, ssl_index;
  11758. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11759. is_put_or_delete_request = 0, is_callback_resource = 0;
  11760. int i;
  11761. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11762. mg_request_handler callback_handler = NULL;
  11763. struct mg_handler_info *handler_info = NULL;
  11764. struct mg_websocket_subprotocols *subprotocols;
  11765. mg_websocket_connect_handler ws_connect_handler = NULL;
  11766. mg_websocket_ready_handler ws_ready_handler = NULL;
  11767. mg_websocket_data_handler ws_data_handler = NULL;
  11768. mg_websocket_close_handler ws_close_handler = NULL;
  11769. void *callback_data = NULL;
  11770. mg_authorization_handler auth_handler = NULL;
  11771. void *auth_callback_data = NULL;
  11772. int handler_type;
  11773. time_t curtime = time(NULL);
  11774. char date[64];
  11775. path[0] = 0;
  11776. /* 1. get the request url */
  11777. /* 1.1. split into url and query string */
  11778. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11779. != NULL) {
  11780. *((char *)conn->request_info.query_string++) = '\0';
  11781. }
  11782. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11783. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11784. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11785. if (ssl_index >= 0) {
  11786. redirect_to_https_port(conn, ssl_index);
  11787. } else {
  11788. /* A http to https forward port has been specified,
  11789. * but no https port to forward to. */
  11790. mg_send_http_error(conn,
  11791. 503,
  11792. "%s",
  11793. "Error: SSL forward not configured properly");
  11794. mg_cry_internal(conn,
  11795. "%s",
  11796. "Can not redirect to SSL, no SSL port available");
  11797. }
  11798. return;
  11799. }
  11800. uri_len = (int)strlen(ri->local_uri);
  11801. /* 1.3. decode url (if config says so) */
  11802. if (should_decode_url(conn)) {
  11803. mg_url_decode(
  11804. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11805. }
  11806. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11807. * not possible */
  11808. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11809. /* step 1. completed, the url is known now */
  11810. uri_len = (int)strlen(ri->local_uri);
  11811. DEBUG_TRACE("URL: %s", ri->local_uri);
  11812. /* 2. if this ip has limited speed, set it for this connection */
  11813. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11814. get_remote_ip(conn),
  11815. ri->local_uri);
  11816. /* 3. call a "handle everything" callback, if registered */
  11817. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11818. /* Note that since V1.7 the "begin_request" function is called
  11819. * before an authorization check. If an authorization check is
  11820. * required, use a request_handler instead. */
  11821. i = conn->phys_ctx->callbacks.begin_request(conn);
  11822. if (i > 0) {
  11823. /* callback already processed the request. Store the
  11824. return value as a status code for the access log. */
  11825. conn->status_code = i;
  11826. discard_unread_request_data(conn);
  11827. return;
  11828. } else if (i == 0) {
  11829. /* civetweb should process the request */
  11830. } else {
  11831. /* unspecified - may change with the next version */
  11832. return;
  11833. }
  11834. }
  11835. /* request not yet handled by a handler or redirect, so the request
  11836. * is processed here */
  11837. /* 4. Check for CORS preflight requests and handle them (if configured).
  11838. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11839. */
  11840. if (!strcmp(ri->request_method, "OPTIONS")) {
  11841. /* Send a response to CORS preflights only if
  11842. * access_control_allow_methods is not NULL and not an empty string.
  11843. * In this case, scripts can still handle CORS. */
  11844. const char *cors_meth_cfg =
  11845. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11846. const char *cors_orig_cfg =
  11847. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11848. const char *cors_origin =
  11849. get_header(ri->http_headers, ri->num_headers, "Origin");
  11850. const char *cors_acrm = get_header(ri->http_headers,
  11851. ri->num_headers,
  11852. "Access-Control-Request-Method");
  11853. /* Todo: check if cors_origin is in cors_orig_cfg.
  11854. * Or, let the client check this. */
  11855. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11856. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11857. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11858. /* This is a valid CORS preflight, and the server is configured
  11859. * to
  11860. * handle it automatically. */
  11861. const char *cors_acrh =
  11862. get_header(ri->http_headers,
  11863. ri->num_headers,
  11864. "Access-Control-Request-Headers");
  11865. gmt_time_string(date, sizeof(date), &curtime);
  11866. mg_printf(conn,
  11867. "HTTP/1.1 200 OK\r\n"
  11868. "Date: %s\r\n"
  11869. "Access-Control-Allow-Origin: %s\r\n"
  11870. "Access-Control-Allow-Methods: %s\r\n"
  11871. "Content-Length: 0\r\n"
  11872. "Connection: %s\r\n",
  11873. date,
  11874. cors_orig_cfg,
  11875. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11876. suggest_connection_header(conn));
  11877. if (cors_acrh != NULL) {
  11878. /* CORS request is asking for additional headers */
  11879. const char *cors_hdr_cfg =
  11880. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11881. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11882. /* Allow only if access_control_allow_headers is
  11883. * not NULL and not an empty string. If this
  11884. * configuration is set to *, allow everything.
  11885. * Otherwise this configuration must be a list
  11886. * of allowed HTTP header names. */
  11887. mg_printf(conn,
  11888. "Access-Control-Allow-Headers: %s\r\n",
  11889. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11890. : cors_hdr_cfg));
  11891. }
  11892. }
  11893. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11894. mg_printf(conn, "\r\n");
  11895. return;
  11896. }
  11897. }
  11898. /* 5. interpret the url to find out how the request must be handled
  11899. */
  11900. /* 5.1. first test, if the request targets the regular http(s)://
  11901. * protocol namespace or the websocket ws(s):// protocol namespace.
  11902. */
  11903. is_websocket_request = is_websocket_protocol(conn);
  11904. #if defined(USE_WEBSOCKET)
  11905. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11906. #else
  11907. handler_type = REQUEST_HANDLER;
  11908. #endif /* defined(USE_WEBSOCKET) */
  11909. /* 5.2. check if the request will be handled by a callback */
  11910. if (get_request_handler(conn,
  11911. handler_type,
  11912. &callback_handler,
  11913. &subprotocols,
  11914. &ws_connect_handler,
  11915. &ws_ready_handler,
  11916. &ws_data_handler,
  11917. &ws_close_handler,
  11918. NULL,
  11919. &callback_data,
  11920. &handler_info)) {
  11921. /* 5.2.1. A callback will handle this request. All requests
  11922. * handled
  11923. * by a callback have to be considered as requests to a script
  11924. * resource. */
  11925. is_callback_resource = 1;
  11926. is_script_resource = 1;
  11927. is_put_or_delete_request = is_put_or_delete_method(conn);
  11928. } else {
  11929. no_callback_resource:
  11930. /* 5.2.2. No callback is responsible for this request. The URI
  11931. * addresses a file based resource (static content or Lua/cgi
  11932. * scripts in the file system). */
  11933. is_callback_resource = 0;
  11934. interpret_uri(conn,
  11935. path,
  11936. sizeof(path),
  11937. &file.stat,
  11938. &is_found,
  11939. &is_script_resource,
  11940. &is_websocket_request,
  11941. &is_put_or_delete_request);
  11942. }
  11943. /* 6. authorization check */
  11944. /* 6.1. a custom authorization handler is installed */
  11945. if (get_request_handler(conn,
  11946. AUTH_HANDLER,
  11947. NULL,
  11948. NULL,
  11949. NULL,
  11950. NULL,
  11951. NULL,
  11952. NULL,
  11953. &auth_handler,
  11954. &auth_callback_data,
  11955. NULL)) {
  11956. if (!auth_handler(conn, auth_callback_data)) {
  11957. return;
  11958. }
  11959. } else if (is_put_or_delete_request && !is_script_resource
  11960. && !is_callback_resource) {
  11961. /* 6.2. this request is a PUT/DELETE to a real file */
  11962. /* 6.2.1. thus, the server must have real files */
  11963. #if defined(NO_FILES)
  11964. if (1) {
  11965. #else
  11966. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11967. #endif
  11968. /* This server does not have any real files, thus the
  11969. * PUT/DELETE methods are not valid. */
  11970. mg_send_http_error(conn,
  11971. 405,
  11972. "%s method not allowed",
  11973. conn->request_info.request_method);
  11974. return;
  11975. }
  11976. #if !defined(NO_FILES)
  11977. /* 6.2.2. Check if put authorization for static files is
  11978. * available.
  11979. */
  11980. if (!is_authorized_for_put(conn)) {
  11981. send_authorization_request(conn, NULL);
  11982. return;
  11983. }
  11984. #endif
  11985. } else {
  11986. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11987. * or it is a PUT or DELETE request to a resource that does not
  11988. * correspond to a file. Check authorization. */
  11989. if (!check_authorization(conn, path)) {
  11990. send_authorization_request(conn, NULL);
  11991. return;
  11992. }
  11993. }
  11994. /* request is authorized or does not need authorization */
  11995. /* 7. check if there are request handlers for this uri */
  11996. if (is_callback_resource) {
  11997. if (!is_websocket_request) {
  11998. i = callback_handler(conn, callback_data);
  11999. /* Callback handler will not be used anymore. Release it */
  12000. handler_info_release(handler_info);
  12001. if (i > 0) {
  12002. /* Do nothing, callback has served the request. Store
  12003. * then return value as status code for the log and discard
  12004. * all data from the client not used by the callback. */
  12005. conn->status_code = i;
  12006. discard_unread_request_data(conn);
  12007. } else {
  12008. /* The handler did NOT handle the request. */
  12009. /* Some proper reactions would be:
  12010. * a) close the connections without sending anything
  12011. * b) send a 404 not found
  12012. * c) try if there is a file matching the URI
  12013. * It would be possible to do a, b or c in the callback
  12014. * implementation, and return 1 - we cannot do anything
  12015. * here, that is not possible in the callback.
  12016. *
  12017. * TODO: What would be the best reaction here?
  12018. * (Note: The reaction may change, if there is a better
  12019. *idea.)
  12020. */
  12021. /* For the moment, use option c: We look for a proper file,
  12022. * but since a file request is not always a script resource,
  12023. * the authorization check might be different. */
  12024. interpret_uri(conn,
  12025. path,
  12026. sizeof(path),
  12027. &file.stat,
  12028. &is_found,
  12029. &is_script_resource,
  12030. &is_websocket_request,
  12031. &is_put_or_delete_request);
  12032. callback_handler = NULL;
  12033. /* Here we are at a dead end:
  12034. * According to URI matching, a callback should be
  12035. * responsible for handling the request,
  12036. * we called it, but the callback declared itself
  12037. * not responsible.
  12038. * We use a goto here, to get out of this dead end,
  12039. * and continue with the default handling.
  12040. * A goto here is simpler and better to understand
  12041. * than some curious loop. */
  12042. goto no_callback_resource;
  12043. }
  12044. } else {
  12045. #if defined(USE_WEBSOCKET)
  12046. handle_websocket_request(conn,
  12047. path,
  12048. is_callback_resource,
  12049. subprotocols,
  12050. ws_connect_handler,
  12051. ws_ready_handler,
  12052. ws_data_handler,
  12053. ws_close_handler,
  12054. callback_data);
  12055. #endif
  12056. }
  12057. return;
  12058. }
  12059. /* 8. handle websocket requests */
  12060. #if defined(USE_WEBSOCKET)
  12061. if (is_websocket_request) {
  12062. if (is_script_resource) {
  12063. if (is_in_script_path(conn, path)) {
  12064. /* Websocket Lua script */
  12065. handle_websocket_request(conn,
  12066. path,
  12067. 0 /* Lua Script */,
  12068. NULL,
  12069. NULL,
  12070. NULL,
  12071. NULL,
  12072. NULL,
  12073. conn->phys_ctx->user_data);
  12074. } else {
  12075. /* Script was in an illegal path */
  12076. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12077. }
  12078. } else {
  12079. #if defined(MG_LEGACY_INTERFACE)
  12080. handle_websocket_request(
  12081. conn,
  12082. path,
  12083. !is_script_resource /* could be deprecated global callback */,
  12084. NULL,
  12085. deprecated_websocket_connect_wrapper,
  12086. deprecated_websocket_ready_wrapper,
  12087. deprecated_websocket_data_wrapper,
  12088. NULL,
  12089. conn->phys_ctx->user_data);
  12090. #else
  12091. mg_send_http_error(conn, 404, "%s", "Not found");
  12092. #endif
  12093. }
  12094. return;
  12095. } else
  12096. #endif
  12097. #if defined(NO_FILES)
  12098. /* 9a. In case the server uses only callbacks, this uri is
  12099. * unknown.
  12100. * Then, all request handling ends here. */
  12101. mg_send_http_error(conn, 404, "%s", "Not Found");
  12102. #else
  12103. /* 9b. This request is either for a static file or resource handled
  12104. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12105. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12106. mg_send_http_error(conn, 404, "%s", "Not Found");
  12107. return;
  12108. }
  12109. /* 10. Request is handled by a script */
  12110. if (is_script_resource) {
  12111. handle_file_based_request(conn, path, &file);
  12112. return;
  12113. }
  12114. /* 11. Handle put/delete/mkcol requests */
  12115. if (is_put_or_delete_request) {
  12116. /* 11.1. PUT method */
  12117. if (!strcmp(ri->request_method, "PUT")) {
  12118. put_file(conn, path);
  12119. return;
  12120. }
  12121. /* 11.2. DELETE method */
  12122. if (!strcmp(ri->request_method, "DELETE")) {
  12123. delete_file(conn, path);
  12124. return;
  12125. }
  12126. /* 11.3. MKCOL method */
  12127. if (!strcmp(ri->request_method, "MKCOL")) {
  12128. mkcol(conn, path);
  12129. return;
  12130. }
  12131. /* 11.4. PATCH method
  12132. * This method is not supported for static resources,
  12133. * only for scripts (Lua, CGI) and callbacks. */
  12134. mg_send_http_error(conn,
  12135. 405,
  12136. "%s method not allowed",
  12137. conn->request_info.request_method);
  12138. return;
  12139. }
  12140. /* 11. File does not exist, or it was configured that it should be
  12141. * hidden */
  12142. if (!is_found || (must_hide_file(conn, path))) {
  12143. mg_send_http_error(conn, 404, "%s", "Not found");
  12144. return;
  12145. }
  12146. /* 12. Directory uris should end with a slash */
  12147. if (file.stat.is_directory && (uri_len > 0)
  12148. && (ri->local_uri[uri_len - 1] != '/')) {
  12149. gmt_time_string(date, sizeof(date), &curtime);
  12150. mg_printf(conn,
  12151. "HTTP/1.1 301 Moved Permanently\r\n"
  12152. "Location: %s/\r\n"
  12153. "Date: %s\r\n"
  12154. /* "Cache-Control: private\r\n" (= default) */
  12155. "Content-Length: 0\r\n"
  12156. "Connection: %s\r\n",
  12157. ri->request_uri,
  12158. date,
  12159. suggest_connection_header(conn));
  12160. send_additional_header(conn);
  12161. mg_printf(conn, "\r\n");
  12162. return;
  12163. }
  12164. /* 13. Handle other methods than GET/HEAD */
  12165. /* 13.1. Handle PROPFIND */
  12166. if (!strcmp(ri->request_method, "PROPFIND")) {
  12167. handle_propfind(conn, path, &file.stat);
  12168. return;
  12169. }
  12170. /* 13.2. Handle OPTIONS for files */
  12171. if (!strcmp(ri->request_method, "OPTIONS")) {
  12172. /* This standard handler is only used for real files.
  12173. * Scripts should support the OPTIONS method themselves, to allow a
  12174. * maximum flexibility.
  12175. * Lua and CGI scripts may fully support CORS this way (including
  12176. * preflights). */
  12177. send_options(conn);
  12178. return;
  12179. }
  12180. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12181. if ((0 != strcmp(ri->request_method, "GET"))
  12182. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12183. mg_send_http_error(conn,
  12184. 405,
  12185. "%s method not allowed",
  12186. conn->request_info.request_method);
  12187. return;
  12188. }
  12189. /* 14. directories */
  12190. if (file.stat.is_directory) {
  12191. /* Substitute files have already been handled above. */
  12192. /* Here we can either generate and send a directory listing,
  12193. * or send an "access denied" error. */
  12194. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12195. "yes")) {
  12196. handle_directory_request(conn, path);
  12197. } else {
  12198. mg_send_http_error(conn,
  12199. 403,
  12200. "%s",
  12201. "Error: Directory listing denied");
  12202. }
  12203. return;
  12204. }
  12205. /* 15. read a normal file with GET or HEAD */
  12206. handle_file_based_request(conn, path, &file);
  12207. #endif /* !defined(NO_FILES) */
  12208. }
  12209. static void
  12210. handle_file_based_request(struct mg_connection *conn,
  12211. const char *path,
  12212. struct mg_file *file)
  12213. {
  12214. if (!conn || !conn->dom_ctx) {
  12215. return;
  12216. }
  12217. if (0) {
  12218. #if defined(USE_LUA)
  12219. } else if (match_prefix(
  12220. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12221. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12222. path)
  12223. > 0) {
  12224. if (is_in_script_path(conn, path)) {
  12225. /* Lua server page: an SSI like page containing mostly plain
  12226. * html
  12227. * code
  12228. * plus some tags with server generated contents. */
  12229. handle_lsp_request(conn, path, file, NULL);
  12230. } else {
  12231. /* Script was in an illegal path */
  12232. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12233. }
  12234. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12235. strlen(
  12236. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12237. path)
  12238. > 0) {
  12239. if (is_in_script_path(conn, path)) {
  12240. /* Lua in-server module script: a CGI like script used to
  12241. * generate
  12242. * the
  12243. * entire reply. */
  12244. mg_exec_lua_script(conn, path, NULL);
  12245. } else {
  12246. /* Script was in an illegal path */
  12247. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12248. }
  12249. #endif
  12250. #if defined(USE_DUKTAPE)
  12251. } else if (match_prefix(
  12252. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12253. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12254. path)
  12255. > 0) {
  12256. if (is_in_script_path(conn, path)) {
  12257. /* Call duktape to generate the page */
  12258. mg_exec_duktape_script(conn, path);
  12259. } else {
  12260. /* Script was in an illegal path */
  12261. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12262. }
  12263. #endif
  12264. #if !defined(NO_CGI)
  12265. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12266. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12267. path)
  12268. > 0) {
  12269. if (is_in_script_path(conn, path)) {
  12270. /* CGI scripts may support all HTTP methods */
  12271. handle_cgi_request(conn, path);
  12272. } else {
  12273. /* Script was in an illegal path */
  12274. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12275. }
  12276. #endif /* !NO_CGI */
  12277. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12278. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12279. path)
  12280. > 0) {
  12281. if (is_in_script_path(conn, path)) {
  12282. handle_ssi_file_request(conn, path, file);
  12283. } else {
  12284. /* Script was in an illegal path */
  12285. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12286. }
  12287. #if !defined(NO_CACHING)
  12288. } else if ((!conn->in_error_handler)
  12289. && is_not_modified(conn, &file->stat)) {
  12290. /* Send 304 "Not Modified" - this must not send any body data */
  12291. handle_not_modified_static_file_request(conn, file);
  12292. #endif /* !NO_CACHING */
  12293. } else {
  12294. handle_static_file_request(conn, path, file, NULL, NULL);
  12295. }
  12296. }
  12297. static void
  12298. close_all_listening_sockets(struct mg_context *ctx)
  12299. {
  12300. unsigned int i;
  12301. if (!ctx) {
  12302. return;
  12303. }
  12304. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12305. closesocket(ctx->listening_sockets[i].sock);
  12306. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12307. }
  12308. mg_free(ctx->listening_sockets);
  12309. ctx->listening_sockets = NULL;
  12310. mg_free(ctx->listening_socket_fds);
  12311. ctx->listening_socket_fds = NULL;
  12312. }
  12313. /* Valid listening port specification is: [ip_address:]port[s]
  12314. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12315. * Examples for IPv6: [::]:80, [::1]:80,
  12316. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12317. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12318. * In order to bind to both, IPv4 and IPv6, you can either add
  12319. * both ports using 8080,[::]:8080, or the short form +8080.
  12320. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12321. * one only accepting IPv4 the other only IPv6. +8080 creates
  12322. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12323. * environment, they might work differently, or might not work
  12324. * at all - it must be tested what options work best in the
  12325. * relevant network environment.
  12326. */
  12327. static int
  12328. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12329. {
  12330. unsigned int a, b, c, d, port;
  12331. int ch, len;
  12332. const char *cb;
  12333. #if defined(USE_IPV6)
  12334. char buf[100] = {0};
  12335. #endif
  12336. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12337. * Also, all-zeroes in the socket address means binding to all addresses
  12338. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12339. memset(so, 0, sizeof(*so));
  12340. so->lsa.sin.sin_family = AF_INET;
  12341. *ip_version = 0;
  12342. /* Initialize port and len as invalid. */
  12343. port = 0;
  12344. len = 0;
  12345. /* Test for different ways to format this string */
  12346. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12347. == 5) {
  12348. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12349. so->lsa.sin.sin_addr.s_addr =
  12350. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12351. so->lsa.sin.sin_port = htons((uint16_t)port);
  12352. *ip_version = 4;
  12353. #if defined(USE_IPV6)
  12354. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12355. && mg_inet_pton(
  12356. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12357. /* IPv6 address, examples: see above */
  12358. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12359. */
  12360. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12361. *ip_version = 6;
  12362. #endif
  12363. } else if ((vec->ptr[0] == '+')
  12364. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12365. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12366. /* Add 1 to len for the + character we skipped before */
  12367. len++;
  12368. #if defined(USE_IPV6)
  12369. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12370. so->lsa.sin6.sin6_family = AF_INET6;
  12371. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12372. *ip_version = 4 + 6;
  12373. #else
  12374. /* Bind to IPv4 only, since IPv6 is not built in. */
  12375. so->lsa.sin.sin_port = htons((uint16_t)port);
  12376. *ip_version = 4;
  12377. #endif
  12378. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  12379. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12380. so->lsa.sin.sin_port = htons((uint16_t)port);
  12381. *ip_version = 4;
  12382. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12383. /* String could be a hostname. This check algotithm
  12384. * will only work for RFC 952 compliant hostnames,
  12385. * starting with a letter, containing only letters,
  12386. * digits and hyphen ('-'). Newer specs may allow
  12387. * more, but this is not guaranteed here, since it
  12388. * may interfere with rules for port option lists. */
  12389. /* According to RFC 1035, hostnames are restricted to 255 characters
  12390. * in total (63 between two dots). */
  12391. char hostname[256];
  12392. size_t hostnlen = (size_t)(cb - vec->ptr);
  12393. if (hostnlen >= sizeof(hostname)) {
  12394. /* This would be invalid in any case */
  12395. *ip_version = 0;
  12396. return 0;
  12397. }
  12398. memcpy(hostname, vec->ptr, hostnlen);
  12399. hostname[hostnlen] = 0;
  12400. if (mg_inet_pton(
  12401. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12402. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12403. *ip_version = 4;
  12404. so->lsa.sin.sin_family = AF_INET;
  12405. so->lsa.sin.sin_port = htons((uint16_t)port);
  12406. len += (int)(hostnlen + 1);
  12407. } else {
  12408. port = 0;
  12409. len = 0;
  12410. }
  12411. #if defined(USE_IPV6)
  12412. } else if (mg_inet_pton(AF_INET6,
  12413. vec->ptr,
  12414. &so->lsa.sin6,
  12415. sizeof(so->lsa.sin6))) {
  12416. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12417. *ip_version = 6;
  12418. so->lsa.sin6.sin6_family = AF_INET6;
  12419. so->lsa.sin.sin_port = htons((uint16_t)port);
  12420. len += (int)(hostnlen + 1);
  12421. } else {
  12422. port = 0;
  12423. len = 0;
  12424. }
  12425. #endif
  12426. }
  12427. } else {
  12428. /* Parsing failure. */
  12429. }
  12430. /* sscanf and the option splitting code ensure the following condition
  12431. */
  12432. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12433. *ip_version = 0;
  12434. return 0;
  12435. }
  12436. ch = vec->ptr[len]; /* Next character after the port number */
  12437. so->is_ssl = (ch == 's');
  12438. so->ssl_redir = (ch == 'r');
  12439. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12440. if (is_valid_port(port)
  12441. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12442. return 1;
  12443. }
  12444. /* Reset ip_version to 0 if there is an error */
  12445. *ip_version = 0;
  12446. return 0;
  12447. }
  12448. /* Is there any SSL port in use? */
  12449. static int
  12450. is_ssl_port_used(const char *ports)
  12451. {
  12452. if (ports) {
  12453. /* There are several different allowed syntax variants:
  12454. * - "80" for a single port using every network interface
  12455. * - "localhost:80" for a single port using only localhost
  12456. * - "80,localhost:8080" for two ports, one bound to localhost
  12457. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12458. * to IPv4 localhost, one to IPv6 localhost
  12459. * - "+80" use port 80 for IPv4 and IPv6
  12460. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12461. * for both: IPv4 and IPv4
  12462. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12463. * additionally port 8080 bound to localhost connections
  12464. *
  12465. * If we just look for 's' anywhere in the string, "localhost:80"
  12466. * will be detected as SSL (false positive).
  12467. * Looking for 's' after a digit may cause false positives in
  12468. * "my24service:8080".
  12469. * Looking from 's' backward if there are only ':' and numbers
  12470. * before will not work for "24service:8080" (non SSL, port 8080)
  12471. * or "24s" (SSL, port 24).
  12472. *
  12473. * Remark: Initially hostnames were not allowed to start with a
  12474. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12475. * Section 2.1).
  12476. *
  12477. * To get this correct, the entire string must be parsed as a whole,
  12478. * reading it as a list element for element and parsing with an
  12479. * algorithm equivalent to parse_port_string.
  12480. *
  12481. * In fact, we use local interface names here, not arbitrary hostnames,
  12482. * so in most cases the only name will be "localhost".
  12483. *
  12484. * So, for now, we use this simple algorithm, that may still return
  12485. * a false positive in bizarre cases.
  12486. */
  12487. int i;
  12488. int portslen = (int)strlen(ports);
  12489. char prevIsNumber = 0;
  12490. for (i = 0; i < portslen; i++) {
  12491. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12492. return 1;
  12493. }
  12494. if (ports[i] >= '0' && ports[i] <= '9') {
  12495. prevIsNumber = 1;
  12496. } else {
  12497. prevIsNumber = 0;
  12498. }
  12499. }
  12500. }
  12501. return 0;
  12502. }
  12503. static int
  12504. set_ports_option(struct mg_context *phys_ctx)
  12505. {
  12506. const char *list;
  12507. int on = 1;
  12508. #if defined(USE_IPV6)
  12509. int off = 0;
  12510. #endif
  12511. struct vec vec;
  12512. struct socket so, *ptr;
  12513. struct mg_pollfd *pfd;
  12514. union usa usa;
  12515. socklen_t len;
  12516. int ip_version;
  12517. int portsTotal = 0;
  12518. int portsOk = 0;
  12519. if (!phys_ctx) {
  12520. return 0;
  12521. }
  12522. memset(&so, 0, sizeof(so));
  12523. memset(&usa, 0, sizeof(usa));
  12524. len = sizeof(usa);
  12525. list = phys_ctx->dd.config[LISTENING_PORTS];
  12526. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12527. portsTotal++;
  12528. if (!parse_port_string(&vec, &so, &ip_version)) {
  12529. mg_cry_internal(
  12530. fc(phys_ctx),
  12531. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12532. (int)vec.len,
  12533. vec.ptr,
  12534. portsTotal,
  12535. "[IP_ADDRESS:]PORT[s|r]");
  12536. continue;
  12537. }
  12538. #if !defined(NO_SSL)
  12539. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12540. mg_cry_internal(fc(phys_ctx),
  12541. "Cannot add SSL socket (entry %i)",
  12542. portsTotal);
  12543. continue;
  12544. }
  12545. #endif
  12546. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12547. == INVALID_SOCKET) {
  12548. mg_cry_internal(fc(phys_ctx),
  12549. "cannot create socket (entry %i)",
  12550. portsTotal);
  12551. continue;
  12552. }
  12553. #if defined(_WIN32)
  12554. /* Windows SO_REUSEADDR lets many procs binds to a
  12555. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12556. * if someone already has the socket -- DTL */
  12557. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12558. * Windows might need a few seconds before
  12559. * the same port can be used again in the
  12560. * same process, so a short Sleep may be
  12561. * required between mg_stop and mg_start.
  12562. */
  12563. if (setsockopt(so.sock,
  12564. SOL_SOCKET,
  12565. SO_EXCLUSIVEADDRUSE,
  12566. (SOCK_OPT_TYPE)&on,
  12567. sizeof(on))
  12568. != 0) {
  12569. /* Set reuse option, but don't abort on errors. */
  12570. mg_cry_internal(
  12571. fc(phys_ctx),
  12572. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12573. portsTotal);
  12574. }
  12575. #else
  12576. if (setsockopt(so.sock,
  12577. SOL_SOCKET,
  12578. SO_REUSEADDR,
  12579. (SOCK_OPT_TYPE)&on,
  12580. sizeof(on))
  12581. != 0) {
  12582. /* Set reuse option, but don't abort on errors. */
  12583. mg_cry_internal(fc(phys_ctx),
  12584. "cannot set socket option SO_REUSEADDR (entry %i)",
  12585. portsTotal);
  12586. }
  12587. #endif
  12588. if (ip_version > 4) {
  12589. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12590. #if defined(USE_IPV6)
  12591. if (ip_version > 6) {
  12592. if (so.lsa.sa.sa_family == AF_INET6
  12593. && setsockopt(so.sock,
  12594. IPPROTO_IPV6,
  12595. IPV6_V6ONLY,
  12596. (void *)&off,
  12597. sizeof(off))
  12598. != 0) {
  12599. /* Set IPv6 only option, but don't abort on errors. */
  12600. mg_cry_internal(
  12601. fc(phys_ctx),
  12602. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12603. portsTotal);
  12604. }
  12605. } else {
  12606. if (so.lsa.sa.sa_family == AF_INET6
  12607. && setsockopt(so.sock,
  12608. IPPROTO_IPV6,
  12609. IPV6_V6ONLY,
  12610. (void *)&on,
  12611. sizeof(on))
  12612. != 0) {
  12613. /* Set IPv6 only option, but don't abort on errors. */
  12614. mg_cry_internal(
  12615. fc(phys_ctx),
  12616. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12617. portsTotal);
  12618. }
  12619. }
  12620. #else
  12621. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  12622. closesocket(so.sock);
  12623. so.sock = INVALID_SOCKET;
  12624. continue;
  12625. #endif
  12626. }
  12627. if (so.lsa.sa.sa_family == AF_INET) {
  12628. len = sizeof(so.lsa.sin);
  12629. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12630. mg_cry_internal(fc(phys_ctx),
  12631. "cannot bind to %.*s: %d (%s)",
  12632. (int)vec.len,
  12633. vec.ptr,
  12634. (int)ERRNO,
  12635. strerror(errno));
  12636. closesocket(so.sock);
  12637. so.sock = INVALID_SOCKET;
  12638. continue;
  12639. }
  12640. }
  12641. #if defined(USE_IPV6)
  12642. else if (so.lsa.sa.sa_family == AF_INET6) {
  12643. len = sizeof(so.lsa.sin6);
  12644. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12645. mg_cry_internal(fc(phys_ctx),
  12646. "cannot bind to IPv6 %.*s: %d (%s)",
  12647. (int)vec.len,
  12648. vec.ptr,
  12649. (int)ERRNO,
  12650. strerror(errno));
  12651. closesocket(so.sock);
  12652. so.sock = INVALID_SOCKET;
  12653. continue;
  12654. }
  12655. }
  12656. #endif
  12657. else {
  12658. mg_cry_internal(
  12659. fc(phys_ctx),
  12660. "cannot bind: address family not supported (entry %i)",
  12661. portsTotal);
  12662. closesocket(so.sock);
  12663. so.sock = INVALID_SOCKET;
  12664. continue;
  12665. }
  12666. if (listen(so.sock, SOMAXCONN) != 0) {
  12667. mg_cry_internal(fc(phys_ctx),
  12668. "cannot listen to %.*s: %d (%s)",
  12669. (int)vec.len,
  12670. vec.ptr,
  12671. (int)ERRNO,
  12672. strerror(errno));
  12673. closesocket(so.sock);
  12674. so.sock = INVALID_SOCKET;
  12675. continue;
  12676. }
  12677. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12678. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12679. int err = (int)ERRNO;
  12680. mg_cry_internal(fc(phys_ctx),
  12681. "call to getsockname failed %.*s: %d (%s)",
  12682. (int)vec.len,
  12683. vec.ptr,
  12684. err,
  12685. strerror(errno));
  12686. closesocket(so.sock);
  12687. so.sock = INVALID_SOCKET;
  12688. continue;
  12689. }
  12690. /* Update lsa port in case of random free ports */
  12691. #if defined(USE_IPV6)
  12692. if (so.lsa.sa.sa_family == AF_INET6) {
  12693. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12694. } else
  12695. #endif
  12696. {
  12697. so.lsa.sin.sin_port = usa.sin.sin_port;
  12698. }
  12699. if ((ptr = (struct socket *)
  12700. mg_realloc_ctx(phys_ctx->listening_sockets,
  12701. (phys_ctx->num_listening_sockets + 1)
  12702. * sizeof(phys_ctx->listening_sockets[0]),
  12703. phys_ctx))
  12704. == NULL) {
  12705. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12706. closesocket(so.sock);
  12707. so.sock = INVALID_SOCKET;
  12708. continue;
  12709. }
  12710. if ((pfd = (struct mg_pollfd *)
  12711. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12712. (phys_ctx->num_listening_sockets + 1)
  12713. * sizeof(phys_ctx->listening_socket_fds[0]),
  12714. phys_ctx))
  12715. == NULL) {
  12716. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12717. closesocket(so.sock);
  12718. so.sock = INVALID_SOCKET;
  12719. mg_free(ptr);
  12720. continue;
  12721. }
  12722. set_close_on_exec(so.sock, fc(phys_ctx));
  12723. phys_ctx->listening_sockets = ptr;
  12724. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12725. phys_ctx->listening_socket_fds = pfd;
  12726. phys_ctx->num_listening_sockets++;
  12727. portsOk++;
  12728. }
  12729. if (portsOk != portsTotal) {
  12730. close_all_listening_sockets(phys_ctx);
  12731. portsOk = 0;
  12732. }
  12733. return portsOk;
  12734. }
  12735. static const char *
  12736. header_val(const struct mg_connection *conn, const char *header)
  12737. {
  12738. const char *header_value;
  12739. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12740. return "-";
  12741. } else {
  12742. return header_value;
  12743. }
  12744. }
  12745. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12746. static void log_access(const struct mg_connection *conn);
  12747. #include "external_log_access.inl"
  12748. #else
  12749. static void
  12750. log_access(const struct mg_connection *conn)
  12751. {
  12752. const struct mg_request_info *ri;
  12753. struct mg_file fi;
  12754. char date[64], src_addr[IP_ADDR_STR_LEN];
  12755. struct tm *tm;
  12756. const char *referer;
  12757. const char *user_agent;
  12758. char buf[4096];
  12759. if (!conn || !conn->dom_ctx) {
  12760. return;
  12761. }
  12762. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12763. if (mg_fopen(conn,
  12764. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12765. MG_FOPEN_MODE_APPEND,
  12766. &fi)
  12767. == 0) {
  12768. fi.access.fp = NULL;
  12769. }
  12770. } else {
  12771. fi.access.fp = NULL;
  12772. }
  12773. /* Log is written to a file and/or a callback. If both are not set,
  12774. * executing the rest of the function is pointless. */
  12775. if ((fi.access.fp == NULL)
  12776. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12777. return;
  12778. }
  12779. tm = localtime(&conn->conn_birth_time);
  12780. if (tm != NULL) {
  12781. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12782. } else {
  12783. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12784. date[sizeof(date) - 1] = '\0';
  12785. }
  12786. ri = &conn->request_info;
  12787. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12788. referer = header_val(conn, "Referer");
  12789. user_agent = header_val(conn, "User-Agent");
  12790. mg_snprintf(conn,
  12791. NULL, /* Ignore truncation in access log */
  12792. buf,
  12793. sizeof(buf),
  12794. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12795. src_addr,
  12796. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12797. date,
  12798. ri->request_method ? ri->request_method : "-",
  12799. ri->request_uri ? ri->request_uri : "-",
  12800. ri->query_string ? "?" : "",
  12801. ri->query_string ? ri->query_string : "",
  12802. ri->http_version,
  12803. conn->status_code,
  12804. conn->num_bytes_sent,
  12805. referer,
  12806. user_agent);
  12807. if (conn->phys_ctx->callbacks.log_access) {
  12808. conn->phys_ctx->callbacks.log_access(conn, buf);
  12809. }
  12810. if (fi.access.fp) {
  12811. int ok = 1;
  12812. flockfile(fi.access.fp);
  12813. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12814. ok = 0;
  12815. }
  12816. if (fflush(fi.access.fp) != 0) {
  12817. ok = 0;
  12818. }
  12819. funlockfile(fi.access.fp);
  12820. if (mg_fclose(&fi.access) != 0) {
  12821. ok = 0;
  12822. }
  12823. if (!ok) {
  12824. mg_cry_internal(conn,
  12825. "Error writing log file %s",
  12826. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12827. }
  12828. }
  12829. }
  12830. #endif /* Externally provided function */
  12831. /* Verify given socket address against the ACL.
  12832. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12833. */
  12834. static int
  12835. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12836. {
  12837. int allowed, flag;
  12838. uint32_t net, mask;
  12839. struct vec vec;
  12840. if (phys_ctx) {
  12841. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12842. /* If any ACL is set, deny by default */
  12843. allowed = (list == NULL) ? '+' : '-';
  12844. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12845. flag = vec.ptr[0];
  12846. if ((flag != '+' && flag != '-')
  12847. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12848. mg_cry_internal(fc(phys_ctx),
  12849. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12850. __func__);
  12851. return -1;
  12852. }
  12853. if (net == (remote_ip & mask)) {
  12854. allowed = flag;
  12855. }
  12856. }
  12857. return allowed == '+';
  12858. }
  12859. return -1;
  12860. }
  12861. #if !defined(_WIN32)
  12862. static int
  12863. set_uid_option(struct mg_context *phys_ctx)
  12864. {
  12865. int success = 0;
  12866. if (phys_ctx) {
  12867. /* We are currently running as curr_uid. */
  12868. const uid_t curr_uid = getuid();
  12869. /* If set, we want to run as run_as_user. */
  12870. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12871. const struct passwd *to_pw = NULL;
  12872. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12873. /* run_as_user does not exist on the system. We can't proceed
  12874. * further. */
  12875. mg_cry_internal(fc(phys_ctx),
  12876. "%s: unknown user [%s]",
  12877. __func__,
  12878. run_as_user);
  12879. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12880. /* There was either no request to change user, or we're already
  12881. * running as run_as_user. Nothing else to do.
  12882. */
  12883. success = 1;
  12884. } else {
  12885. /* Valid change request. */
  12886. if (setgid(to_pw->pw_gid) == -1) {
  12887. mg_cry_internal(fc(phys_ctx),
  12888. "%s: setgid(%s): %s",
  12889. __func__,
  12890. run_as_user,
  12891. strerror(errno));
  12892. } else if (setgroups(0, NULL) == -1) {
  12893. mg_cry_internal(fc(phys_ctx),
  12894. "%s: setgroups(): %s",
  12895. __func__,
  12896. strerror(errno));
  12897. } else if (setuid(to_pw->pw_uid) == -1) {
  12898. mg_cry_internal(fc(phys_ctx),
  12899. "%s: setuid(%s): %s",
  12900. __func__,
  12901. run_as_user,
  12902. strerror(errno));
  12903. } else {
  12904. success = 1;
  12905. }
  12906. }
  12907. }
  12908. return success;
  12909. }
  12910. #endif /* !_WIN32 */
  12911. static void
  12912. tls_dtor(void *key)
  12913. {
  12914. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12915. /* key == pthread_getspecific(sTlsKey); */
  12916. if (tls) {
  12917. if (tls->is_master == 2) {
  12918. tls->is_master = -3; /* Mark memory as dead */
  12919. mg_free(tls);
  12920. }
  12921. }
  12922. pthread_setspecific(sTlsKey, NULL);
  12923. }
  12924. #if !defined(NO_SSL)
  12925. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12926. struct mg_domain_context *dom_ctx,
  12927. const char *pem,
  12928. const char *chain);
  12929. static const char *ssl_error(void);
  12930. static int
  12931. refresh_trust(struct mg_connection *conn)
  12932. {
  12933. static int reload_lock = 0;
  12934. static long int data_check = 0;
  12935. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12936. struct stat cert_buf;
  12937. long int t;
  12938. const char *pem;
  12939. const char *chain;
  12940. int should_verify_peer;
  12941. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12942. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12943. * refresh_trust still can not work. */
  12944. return 0;
  12945. }
  12946. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12947. if (chain == NULL) {
  12948. /* pem is not NULL here */
  12949. chain = pem;
  12950. }
  12951. if (*chain == 0) {
  12952. chain = NULL;
  12953. }
  12954. t = data_check;
  12955. if (stat(pem, &cert_buf) != -1) {
  12956. t = (long int)cert_buf.st_mtime;
  12957. }
  12958. if (data_check != t) {
  12959. data_check = t;
  12960. should_verify_peer = 0;
  12961. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12962. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12963. == 0) {
  12964. should_verify_peer = 1;
  12965. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12966. "optional")
  12967. == 0) {
  12968. should_verify_peer = 1;
  12969. }
  12970. }
  12971. if (should_verify_peer) {
  12972. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12973. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12974. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12975. ca_file,
  12976. ca_path)
  12977. != 1) {
  12978. mg_cry_internal(
  12979. fc(conn->phys_ctx),
  12980. "SSL_CTX_load_verify_locations error: %s "
  12981. "ssl_verify_peer requires setting "
  12982. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12983. "present in "
  12984. "the .conf file?",
  12985. ssl_error());
  12986. return 0;
  12987. }
  12988. }
  12989. if (1 == mg_atomic_inc(p_reload_lock)) {
  12990. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12991. == 0) {
  12992. return 0;
  12993. }
  12994. *p_reload_lock = 0;
  12995. }
  12996. }
  12997. /* lock while cert is reloading */
  12998. while (*p_reload_lock) {
  12999. sleep(1);
  13000. }
  13001. return 1;
  13002. }
  13003. #if defined(OPENSSL_API_1_1)
  13004. #else
  13005. static pthread_mutex_t *ssl_mutexes;
  13006. #endif /* OPENSSL_API_1_1 */
  13007. static int
  13008. sslize(struct mg_connection *conn,
  13009. SSL_CTX *s,
  13010. int (*func)(SSL *),
  13011. volatile int *stop_server,
  13012. const struct mg_client_options *client_options)
  13013. {
  13014. int ret, err;
  13015. int short_trust;
  13016. unsigned timeout = 1024;
  13017. unsigned i;
  13018. if (!conn) {
  13019. return 0;
  13020. }
  13021. short_trust =
  13022. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13023. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13024. if (short_trust) {
  13025. int trust_ret = refresh_trust(conn);
  13026. if (!trust_ret) {
  13027. return trust_ret;
  13028. }
  13029. }
  13030. conn->ssl = SSL_new(s);
  13031. if (conn->ssl == NULL) {
  13032. return 0;
  13033. }
  13034. SSL_set_app_data(conn->ssl, (char *)conn);
  13035. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13036. if (ret != 1) {
  13037. err = SSL_get_error(conn->ssl, ret);
  13038. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13039. SSL_free(conn->ssl);
  13040. conn->ssl = NULL;
  13041. OPENSSL_REMOVE_THREAD_STATE();
  13042. return 0;
  13043. }
  13044. if (client_options) {
  13045. if (client_options->host_name) {
  13046. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13047. }
  13048. }
  13049. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13050. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13051. /* NOTE: The loop below acts as a back-off, so we can end
  13052. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13053. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13054. }
  13055. /* SSL functions may fail and require to be called again:
  13056. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13057. * Here "func" could be SSL_connect or SSL_accept. */
  13058. for (i = 0; i <= timeout; i += 50) {
  13059. ret = func(conn->ssl);
  13060. if (ret != 1) {
  13061. err = SSL_get_error(conn->ssl, ret);
  13062. if ((err == SSL_ERROR_WANT_CONNECT)
  13063. || (err == SSL_ERROR_WANT_ACCEPT)
  13064. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13065. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13066. if (*stop_server) {
  13067. /* Don't wait if the server is going to be stopped. */
  13068. break;
  13069. }
  13070. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13071. /* Simply retry the function call. */
  13072. mg_sleep(50);
  13073. } else {
  13074. /* Need to retry the function call "later".
  13075. * See https://linux.die.net/man/3/ssl_get_error
  13076. * This is typical for non-blocking sockets. */
  13077. struct mg_pollfd pfd;
  13078. pfd.fd = conn->client.sock;
  13079. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13080. || (err == SSL_ERROR_WANT_WRITE)) ? POLLOUT
  13081. : POLLIN;
  13082. mg_poll(&pfd, 1, 50, stop_server);
  13083. }
  13084. } else if (err == SSL_ERROR_SYSCALL) {
  13085. /* This is an IO error. Look at errno. */
  13086. err = errno;
  13087. mg_cry_internal(conn, "SSL syscall error %i", err);
  13088. break;
  13089. } else {
  13090. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13091. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13092. break;
  13093. }
  13094. } else {
  13095. /* success */
  13096. break;
  13097. }
  13098. }
  13099. if (ret != 1) {
  13100. SSL_free(conn->ssl);
  13101. conn->ssl = NULL;
  13102. OPENSSL_REMOVE_THREAD_STATE();
  13103. return 0;
  13104. }
  13105. return 1;
  13106. }
  13107. /* Return OpenSSL error message (from CRYPTO lib) */
  13108. static const char *
  13109. ssl_error(void)
  13110. {
  13111. unsigned long err;
  13112. err = ERR_get_error();
  13113. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13114. }
  13115. static int
  13116. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13117. {
  13118. int i;
  13119. const char hexdigit[] = "0123456789abcdef";
  13120. if ((memlen <= 0) || (buflen <= 0)) {
  13121. return 0;
  13122. }
  13123. if (buflen < (3 * memlen)) {
  13124. return 0;
  13125. }
  13126. for (i = 0; i < memlen; i++) {
  13127. if (i > 0) {
  13128. buf[3 * i - 1] = ' ';
  13129. }
  13130. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13131. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13132. }
  13133. buf[3 * memlen - 1] = 0;
  13134. return 1;
  13135. }
  13136. static void
  13137. ssl_get_client_cert_info(struct mg_connection *conn)
  13138. {
  13139. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13140. if (cert) {
  13141. char str_subject[1024];
  13142. char str_issuer[1024];
  13143. char str_finger[1024];
  13144. unsigned char buf[256];
  13145. char *str_serial = NULL;
  13146. unsigned int ulen;
  13147. int ilen;
  13148. unsigned char *tmp_buf;
  13149. unsigned char *tmp_p;
  13150. /* Handle to algorithm used for fingerprint */
  13151. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13152. /* Get Subject and issuer */
  13153. X509_NAME *subj = X509_get_subject_name(cert);
  13154. X509_NAME *iss = X509_get_issuer_name(cert);
  13155. /* Get serial number */
  13156. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13157. /* Translate serial number to a hex string */
  13158. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13159. str_serial = BN_bn2hex(serial_bn);
  13160. BN_free(serial_bn);
  13161. /* Translate subject and issuer to a string */
  13162. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13163. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13164. /* Calculate SHA1 fingerprint and store as a hex string */
  13165. ulen = 0;
  13166. /* ASN1_digest is deprecated. Do the calculation manually,
  13167. * using EVP_Digest. */
  13168. ilen = i2d_X509(cert, NULL);
  13169. tmp_buf = (ilen > 0)
  13170. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13171. conn->phys_ctx)
  13172. : NULL;
  13173. if (tmp_buf) {
  13174. tmp_p = tmp_buf;
  13175. (void)i2d_X509(cert, &tmp_p);
  13176. if (!EVP_Digest(
  13177. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13178. ulen = 0;
  13179. }
  13180. mg_free(tmp_buf);
  13181. }
  13182. if (!hexdump2string(
  13183. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13184. *str_finger = 0;
  13185. }
  13186. conn->request_info.client_cert = (struct mg_client_cert *)
  13187. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13188. if (conn->request_info.client_cert) {
  13189. conn->request_info.client_cert->peer_cert = (void *)cert;
  13190. conn->request_info.client_cert->subject =
  13191. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13192. conn->request_info.client_cert->issuer =
  13193. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13194. conn->request_info.client_cert->serial =
  13195. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13196. conn->request_info.client_cert->finger =
  13197. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13198. } else {
  13199. mg_cry_internal(conn,
  13200. "%s",
  13201. "Out of memory: Cannot allocate memory for client "
  13202. "certificate");
  13203. }
  13204. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13205. * see https://linux.die.net/man/3/bn_bn2hex */
  13206. OPENSSL_free(str_serial);
  13207. }
  13208. }
  13209. #if defined(OPENSSL_API_1_1)
  13210. #else
  13211. static void
  13212. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13213. {
  13214. (void)line;
  13215. (void)file;
  13216. if (mode & 1) {
  13217. /* 1 is CRYPTO_LOCK */
  13218. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13219. } else {
  13220. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13221. }
  13222. }
  13223. #endif /* OPENSSL_API_1_1 */
  13224. #if !defined(NO_SSL_DL)
  13225. static void *
  13226. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13227. {
  13228. union {
  13229. void *p;
  13230. void (*fp)(void);
  13231. } u;
  13232. void *dll_handle;
  13233. struct ssl_func *fp;
  13234. int ok;
  13235. int truncated = 0;
  13236. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13237. mg_snprintf(NULL,
  13238. NULL, /* No truncation check for ebuf */
  13239. ebuf,
  13240. ebuf_len,
  13241. "%s: cannot load %s",
  13242. __func__,
  13243. dll_name);
  13244. return NULL;
  13245. }
  13246. ok = 1;
  13247. for (fp = sw; fp->name != NULL; fp++) {
  13248. #if defined(_WIN32)
  13249. /* GetProcAddress() returns pointer to function */
  13250. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13251. #else
  13252. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13253. * pointers to function pointers. We need to use a union to make a
  13254. * cast. */
  13255. u.p = dlsym(dll_handle, fp->name);
  13256. #endif /* _WIN32 */
  13257. if (u.fp == NULL) {
  13258. if (ok) {
  13259. mg_snprintf(NULL,
  13260. &truncated,
  13261. ebuf,
  13262. ebuf_len,
  13263. "%s: %s: cannot find %s",
  13264. __func__,
  13265. dll_name,
  13266. fp->name);
  13267. ok = 0;
  13268. } else {
  13269. size_t cur_len = strlen(ebuf);
  13270. if (!truncated) {
  13271. mg_snprintf(NULL,
  13272. &truncated,
  13273. ebuf + cur_len,
  13274. ebuf_len - cur_len - 3,
  13275. ", %s",
  13276. fp->name);
  13277. if (truncated) {
  13278. /* If truncated, add "..." */
  13279. strcat(ebuf, "...");
  13280. }
  13281. }
  13282. }
  13283. /* Debug:
  13284. * printf("Missing function: %s\n", fp->name); */
  13285. } else {
  13286. fp->ptr = u.fp;
  13287. }
  13288. }
  13289. if (!ok) {
  13290. (void)dlclose(dll_handle);
  13291. return NULL;
  13292. }
  13293. return dll_handle;
  13294. }
  13295. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13296. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13297. #endif /* NO_SSL_DL */
  13298. #if defined(SSL_ALREADY_INITIALIZED)
  13299. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13300. #else
  13301. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13302. #endif
  13303. static int
  13304. initialize_ssl(char *ebuf, size_t ebuf_len)
  13305. {
  13306. #if defined(OPENSSL_API_1_1)
  13307. if (ebuf_len > 0) {
  13308. ebuf[0] = 0;
  13309. }
  13310. #if !defined(NO_SSL_DL)
  13311. if (!cryptolib_dll_handle) {
  13312. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13313. if (!cryptolib_dll_handle) {
  13314. mg_snprintf(NULL,
  13315. NULL, /* No truncation check for ebuf */
  13316. ebuf,
  13317. ebuf_len,
  13318. "%s: error loading library %s",
  13319. __func__,
  13320. CRYPTO_LIB);
  13321. DEBUG_TRACE("%s", ebuf);
  13322. return 0;
  13323. }
  13324. }
  13325. #endif /* NO_SSL_DL */
  13326. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13327. return 1;
  13328. }
  13329. #else /* not OPENSSL_API_1_1 */
  13330. int i, num_locks;
  13331. size_t size;
  13332. if (ebuf_len > 0) {
  13333. ebuf[0] = 0;
  13334. }
  13335. #if !defined(NO_SSL_DL)
  13336. if (!cryptolib_dll_handle) {
  13337. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13338. if (!cryptolib_dll_handle) {
  13339. mg_snprintf(NULL,
  13340. NULL, /* No truncation check for ebuf */
  13341. ebuf,
  13342. ebuf_len,
  13343. "%s: error loading library %s",
  13344. __func__,
  13345. CRYPTO_LIB);
  13346. DEBUG_TRACE("%s", ebuf);
  13347. return 0;
  13348. }
  13349. }
  13350. #endif /* NO_SSL_DL */
  13351. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13352. return 1;
  13353. }
  13354. /* Initialize locking callbacks, needed for thread safety.
  13355. * http://www.openssl.org/support/faq.html#PROG1
  13356. */
  13357. num_locks = CRYPTO_num_locks();
  13358. if (num_locks < 0) {
  13359. num_locks = 0;
  13360. }
  13361. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13362. /* allocate mutex array, if required */
  13363. if (num_locks == 0) {
  13364. /* No mutex array required */
  13365. ssl_mutexes = NULL;
  13366. } else {
  13367. /* Mutex array required - allocate it */
  13368. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13369. /* Check OOM */
  13370. if (ssl_mutexes == NULL) {
  13371. mg_snprintf(NULL,
  13372. NULL, /* No truncation check for ebuf */
  13373. ebuf,
  13374. ebuf_len,
  13375. "%s: cannot allocate mutexes: %s",
  13376. __func__,
  13377. ssl_error());
  13378. DEBUG_TRACE("%s", ebuf);
  13379. return 0;
  13380. }
  13381. /* initialize mutex array */
  13382. for (i = 0; i < num_locks; i++) {
  13383. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13384. mg_snprintf(NULL,
  13385. NULL, /* No truncation check for ebuf */
  13386. ebuf,
  13387. ebuf_len,
  13388. "%s: error initializing mutex %i of %i",
  13389. __func__,
  13390. i,
  13391. num_locks);
  13392. DEBUG_TRACE("%s", ebuf);
  13393. mg_free(ssl_mutexes);
  13394. return 0;
  13395. }
  13396. }
  13397. }
  13398. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13399. CRYPTO_set_id_callback(&mg_current_thread_id);
  13400. #endif /* OPENSSL_API_1_1 */
  13401. #if !defined(NO_SSL_DL)
  13402. if (!ssllib_dll_handle) {
  13403. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13404. if (!ssllib_dll_handle) {
  13405. #if !defined(OPENSSL_API_1_1)
  13406. mg_free(ssl_mutexes);
  13407. #endif
  13408. DEBUG_TRACE("%s", ebuf);
  13409. return 0;
  13410. }
  13411. }
  13412. #endif /* NO_SSL_DL */
  13413. #if defined(OPENSSL_API_1_1)
  13414. /* Initialize SSL library */
  13415. OPENSSL_init_ssl(0, NULL);
  13416. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13417. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13418. NULL);
  13419. #else
  13420. /* Initialize SSL library */
  13421. SSL_library_init();
  13422. SSL_load_error_strings();
  13423. #endif
  13424. return 1;
  13425. }
  13426. static int
  13427. ssl_use_pem_file(struct mg_context *phys_ctx,
  13428. struct mg_domain_context *dom_ctx,
  13429. const char *pem,
  13430. const char *chain)
  13431. {
  13432. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13433. mg_cry_internal(fc(phys_ctx),
  13434. "%s: cannot open certificate file %s: %s",
  13435. __func__,
  13436. pem,
  13437. ssl_error());
  13438. return 0;
  13439. }
  13440. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13441. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13442. mg_cry_internal(fc(phys_ctx),
  13443. "%s: cannot open private key file %s: %s",
  13444. __func__,
  13445. pem,
  13446. ssl_error());
  13447. return 0;
  13448. }
  13449. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13450. mg_cry_internal(fc(phys_ctx),
  13451. "%s: certificate and private key do not match: %s",
  13452. __func__,
  13453. pem);
  13454. return 0;
  13455. }
  13456. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13457. * chain files that contain private keys and certificates in
  13458. * SSL_CTX_use_certificate_chain_file.
  13459. * The CivetWeb-Server used pem-Files that contained both information.
  13460. * In order to make wolfSSL work, it is split in two files.
  13461. * One file that contains key and certificate used by the server and
  13462. * an optional chain file for the ssl stack.
  13463. */
  13464. if (chain) {
  13465. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13466. mg_cry_internal(fc(phys_ctx),
  13467. "%s: cannot use certificate chain file %s: %s",
  13468. __func__,
  13469. pem,
  13470. ssl_error());
  13471. return 0;
  13472. }
  13473. }
  13474. return 1;
  13475. }
  13476. #if defined(OPENSSL_API_1_1)
  13477. static unsigned long
  13478. ssl_get_protocol(int version_id)
  13479. {
  13480. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13481. if (version_id > 0)
  13482. ret |= SSL_OP_NO_SSLv2;
  13483. if (version_id > 1)
  13484. ret |= SSL_OP_NO_SSLv3;
  13485. if (version_id > 2)
  13486. ret |= SSL_OP_NO_TLSv1;
  13487. if (version_id > 3)
  13488. ret |= SSL_OP_NO_TLSv1_1;
  13489. return ret;
  13490. }
  13491. #else
  13492. static long
  13493. ssl_get_protocol(int version_id)
  13494. {
  13495. long ret = (long)SSL_OP_ALL;
  13496. if (version_id > 0)
  13497. ret |= SSL_OP_NO_SSLv2;
  13498. if (version_id > 1)
  13499. ret |= SSL_OP_NO_SSLv3;
  13500. if (version_id > 2)
  13501. ret |= SSL_OP_NO_TLSv1;
  13502. if (version_id > 3)
  13503. ret |= SSL_OP_NO_TLSv1_1;
  13504. return ret;
  13505. }
  13506. #endif /* OPENSSL_API_1_1 */
  13507. /* SSL callback documentation:
  13508. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13509. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13510. * https://linux.die.net/man/3/ssl_set_info_callback */
  13511. /* Note: There is no "const" for the first argument in the documentation
  13512. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13513. * / OpenSSL compatibility layers have it. Having a different definition will
  13514. * cause a warning in C and an error in C++. Use "const SSL *", while
  13515. * automatical conversion from "SSL *" works for all compilers, but not other
  13516. * way around */
  13517. static void
  13518. ssl_info_callback(const SSL *ssl, int what, int ret)
  13519. {
  13520. (void)ret;
  13521. if (what & SSL_CB_HANDSHAKE_START) {
  13522. SSL_get_app_data(ssl);
  13523. }
  13524. if (what & SSL_CB_HANDSHAKE_DONE) {
  13525. /* TODO: check for openSSL 1.1 */
  13526. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13527. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13528. }
  13529. }
  13530. static int
  13531. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13532. {
  13533. struct mg_context *ctx = (struct mg_context *)arg;
  13534. struct mg_domain_context *dom =
  13535. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13536. #if defined(GCC_DIAGNOSTIC)
  13537. #pragma GCC diagnostic push
  13538. #pragma GCC diagnostic ignored "-Wcast-align"
  13539. #endif /* defined(GCC_DIAGNOSTIC) */
  13540. /* We used an aligned pointer in SSL_set_app_data */
  13541. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13542. #if defined(GCC_DIAGNOSTIC)
  13543. #pragma GCC diagnostic pop
  13544. #endif /* defined(GCC_DIAGNOSTIC) */
  13545. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13546. (void)ad;
  13547. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13548. DEBUG_TRACE("%s", "internal error - assertion failed");
  13549. return SSL_TLSEXT_ERR_NOACK;
  13550. }
  13551. /* Old clients (Win XP) will not support SNI. Then, there
  13552. * is no server name available in the request - we can
  13553. * only work with the default certificate.
  13554. * Multiple HTTPS hosts on one IP+port are only possible
  13555. * with a certificate containing all alternative names.
  13556. */
  13557. if ((servername == NULL) || (*servername == 0)) {
  13558. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13559. conn->dom_ctx = &(ctx->dd);
  13560. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13561. return SSL_TLSEXT_ERR_NOACK;
  13562. }
  13563. DEBUG_TRACE("TLS connection to host %s", servername);
  13564. while (dom) {
  13565. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13566. /* Found matching domain */
  13567. DEBUG_TRACE("TLS domain %s found",
  13568. dom->config[AUTHENTICATION_DOMAIN]);
  13569. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13570. conn->dom_ctx = dom;
  13571. return SSL_TLSEXT_ERR_OK;
  13572. }
  13573. dom = dom->next;
  13574. }
  13575. /* Default domain */
  13576. DEBUG_TRACE("TLS default domain %s used",
  13577. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13578. conn->dom_ctx = &(ctx->dd);
  13579. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13580. return SSL_TLSEXT_ERR_OK;
  13581. }
  13582. /* Setup SSL CTX as required by CivetWeb */
  13583. static int
  13584. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13585. struct mg_domain_context *dom_ctx,
  13586. const char *pem,
  13587. const char *chain)
  13588. {
  13589. int callback_ret;
  13590. int should_verify_peer;
  13591. int peer_certificate_optional;
  13592. const char *ca_path;
  13593. const char *ca_file;
  13594. int use_default_verify_paths;
  13595. int verify_depth;
  13596. struct timespec now_mt;
  13597. md5_byte_t ssl_context_id[16];
  13598. md5_state_t md5state;
  13599. int protocol_ver;
  13600. #if defined(OPENSSL_API_1_1)
  13601. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13602. mg_cry_internal(fc(phys_ctx),
  13603. "SSL_CTX_new (server) error: %s",
  13604. ssl_error());
  13605. return 0;
  13606. }
  13607. #else
  13608. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13609. mg_cry_internal(fc(phys_ctx),
  13610. "SSL_CTX_new (server) error: %s",
  13611. ssl_error());
  13612. return 0;
  13613. }
  13614. #endif /* OPENSSL_API_1_1 */
  13615. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13616. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13617. | SSL_OP_NO_TLSv1_1);
  13618. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13619. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13620. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13621. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13622. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13623. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13624. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13625. #if !defined(NO_SSL_DL)
  13626. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13627. #endif /* NO_SSL_DL */
  13628. /* In SSL documentation examples callback defined without const specifier
  13629. * 'void (*)(SSL *, int, int)' See:
  13630. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13631. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13632. * But in the source code const SSL is used:
  13633. * 'void (*)(const SSL *, int, int)' See:
  13634. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13635. * Problem about wrong documentation described, but not resolved:
  13636. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13637. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13638. * But when compiled with modern C++ compiler, correct const should be
  13639. * provided
  13640. */
  13641. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13642. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13643. ssl_servername_callback);
  13644. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13645. /* If a callback has been specified, call it. */
  13646. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13647. ? 0
  13648. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13649. phys_ctx->user_data));
  13650. /* If callback returns 0, civetweb sets up the SSL certificate.
  13651. * If it returns 1, civetweb assumes the calback already did this.
  13652. * If it returns -1, initializing ssl fails. */
  13653. if (callback_ret < 0) {
  13654. mg_cry_internal(fc(phys_ctx),
  13655. "SSL callback returned error: %i",
  13656. callback_ret);
  13657. return 0;
  13658. }
  13659. if (callback_ret > 0) {
  13660. /* Callback did everything. */
  13661. return 1;
  13662. }
  13663. /* Use some combination of start time, domain and port as a SSL
  13664. * context ID. This should be unique on the current machine. */
  13665. md5_init(&md5state);
  13666. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13667. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13668. md5_append(&md5state,
  13669. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13670. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13671. md5_append(&md5state,
  13672. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13673. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13674. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13675. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13676. md5_finish(&md5state, ssl_context_id);
  13677. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13678. (unsigned char *)ssl_context_id,
  13679. sizeof(ssl_context_id));
  13680. if (pem != NULL) {
  13681. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13682. return 0;
  13683. }
  13684. }
  13685. /* Should we support client certificates? */
  13686. /* Default is "no". */
  13687. should_verify_peer = 0;
  13688. peer_certificate_optional = 0;
  13689. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13690. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13691. /* Yes, they are mandatory */
  13692. should_verify_peer = 1;
  13693. peer_certificate_optional = 0;
  13694. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13695. "optional")
  13696. == 0) {
  13697. /* Yes, they are optional */
  13698. should_verify_peer = 1;
  13699. peer_certificate_optional = 1;
  13700. }
  13701. }
  13702. use_default_verify_paths =
  13703. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13704. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13705. == 0);
  13706. if (should_verify_peer) {
  13707. ca_path = dom_ctx->config[SSL_CA_PATH];
  13708. ca_file = dom_ctx->config[SSL_CA_FILE];
  13709. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13710. != 1) {
  13711. mg_cry_internal(fc(phys_ctx),
  13712. "SSL_CTX_load_verify_locations error: %s "
  13713. "ssl_verify_peer requires setting "
  13714. "either ssl_ca_path or ssl_ca_file. "
  13715. "Is any of them present in the "
  13716. ".conf file?",
  13717. ssl_error());
  13718. return 0;
  13719. }
  13720. if (peer_certificate_optional) {
  13721. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13722. } else {
  13723. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13724. SSL_VERIFY_PEER
  13725. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13726. NULL);
  13727. }
  13728. if (use_default_verify_paths
  13729. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13730. mg_cry_internal(fc(phys_ctx),
  13731. "SSL_CTX_set_default_verify_paths error: %s",
  13732. ssl_error());
  13733. return 0;
  13734. }
  13735. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13736. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13737. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13738. }
  13739. }
  13740. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13741. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13742. dom_ctx->config[SSL_CIPHER_LIST])
  13743. != 1) {
  13744. mg_cry_internal(fc(phys_ctx),
  13745. "SSL_CTX_set_cipher_list error: %s",
  13746. ssl_error());
  13747. }
  13748. }
  13749. return 1;
  13750. }
  13751. /* Check if SSL is required.
  13752. * If so, dynamically load SSL library
  13753. * and set up ctx->ssl_ctx pointer. */
  13754. static int
  13755. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13756. {
  13757. void *ssl_ctx = 0;
  13758. int callback_ret;
  13759. const char *pem;
  13760. const char *chain;
  13761. char ebuf[128];
  13762. if (!phys_ctx) {
  13763. return 0;
  13764. }
  13765. if (!dom_ctx) {
  13766. dom_ctx = &(phys_ctx->dd);
  13767. }
  13768. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13769. /* No SSL port is set. No need to setup SSL. */
  13770. return 1;
  13771. }
  13772. /* Check for external SSL_CTX */
  13773. callback_ret =
  13774. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13775. ? 0
  13776. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13777. phys_ctx->user_data));
  13778. if (callback_ret < 0) {
  13779. mg_cry_internal(fc(phys_ctx),
  13780. "external_ssl_ctx callback returned error: %i",
  13781. callback_ret);
  13782. return 0;
  13783. } else if (callback_ret > 0) {
  13784. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13785. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13786. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13787. return 0;
  13788. }
  13789. return 1;
  13790. }
  13791. /* else: external_ssl_ctx does not exist or returns 0,
  13792. * CivetWeb should continue initializing SSL */
  13793. /* If PEM file is not specified and the init_ssl callback
  13794. * is not specified, setup will fail. */
  13795. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13796. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13797. /* No certificate and no callback:
  13798. * Essential data to set up TLS is missing.
  13799. */
  13800. mg_cry_internal(fc(phys_ctx),
  13801. "Initializing SSL failed: -%s is not set",
  13802. config_options[SSL_CERTIFICATE].name);
  13803. return 0;
  13804. }
  13805. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13806. if (chain == NULL) {
  13807. chain = pem;
  13808. }
  13809. if ((chain != NULL) && (*chain == 0)) {
  13810. chain = NULL;
  13811. }
  13812. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13813. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13814. return 0;
  13815. }
  13816. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13817. }
  13818. static void
  13819. uninitialize_ssl(void)
  13820. {
  13821. #if defined(OPENSSL_API_1_1)
  13822. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13823. /* Shutdown according to
  13824. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13825. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13826. */
  13827. CONF_modules_unload(1);
  13828. #else
  13829. int i;
  13830. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13831. /* Shutdown according to
  13832. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13833. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13834. */
  13835. CRYPTO_set_locking_callback(NULL);
  13836. CRYPTO_set_id_callback(NULL);
  13837. ENGINE_cleanup();
  13838. CONF_modules_unload(1);
  13839. ERR_free_strings();
  13840. EVP_cleanup();
  13841. CRYPTO_cleanup_all_ex_data();
  13842. OPENSSL_REMOVE_THREAD_STATE();
  13843. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13844. pthread_mutex_destroy(&ssl_mutexes[i]);
  13845. }
  13846. mg_free(ssl_mutexes);
  13847. ssl_mutexes = NULL;
  13848. #endif /* OPENSSL_API_1_1 */
  13849. }
  13850. }
  13851. #endif /* !NO_SSL */
  13852. static int
  13853. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13854. {
  13855. if (phys_ctx) {
  13856. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13857. const char *path;
  13858. if (!dom_ctx) {
  13859. dom_ctx = &(phys_ctx->dd);
  13860. }
  13861. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13862. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  13863. mg_cry_internal(fc(phys_ctx),
  13864. "Cannot open %s: %s",
  13865. path,
  13866. strerror(ERRNO));
  13867. return 0;
  13868. }
  13869. return 1;
  13870. }
  13871. return 0;
  13872. }
  13873. static int
  13874. set_acl_option(struct mg_context *phys_ctx)
  13875. {
  13876. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13877. }
  13878. static void
  13879. reset_per_request_attributes(struct mg_connection *conn)
  13880. {
  13881. if (!conn) {
  13882. return;
  13883. }
  13884. conn->connection_type =
  13885. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13886. conn->num_bytes_sent = conn->consumed_content = 0;
  13887. conn->path_info = NULL;
  13888. conn->status_code = -1;
  13889. conn->content_len = -1;
  13890. conn->is_chunked = 0;
  13891. conn->must_close = 0;
  13892. conn->request_len = 0;
  13893. conn->throttle = 0;
  13894. conn->chunk_remainder = 0;
  13895. conn->accept_gzip = 0;
  13896. conn->response_info.content_length = conn->request_info.content_length = -1;
  13897. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13898. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13899. conn->response_info.status_text = NULL;
  13900. conn->response_info.status_code = 0;
  13901. conn->request_info.remote_user = NULL;
  13902. conn->request_info.request_method = NULL;
  13903. conn->request_info.request_uri = NULL;
  13904. conn->request_info.local_uri = NULL;
  13905. #if defined(MG_LEGACY_INTERFACE)
  13906. /* Legacy before split into local_uri and request_uri */
  13907. conn->request_info.uri = NULL;
  13908. #endif
  13909. }
  13910. #if 0
  13911. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13912. * Leave this function here (commented out) for reference until
  13913. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13914. * no longer required.
  13915. */
  13916. static int
  13917. set_sock_timeout(SOCKET sock, int milliseconds)
  13918. {
  13919. int r0 = 0, r1, r2;
  13920. #if defined(_WIN32)
  13921. /* Windows specific */
  13922. DWORD tv = (DWORD)milliseconds;
  13923. #else
  13924. /* Linux, ... (not Windows) */
  13925. struct timeval tv;
  13926. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13927. * max. time waiting for the acknowledged of TCP data before the connection
  13928. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13929. * If this option is not set, the default timeout of 20-30 minutes is used.
  13930. */
  13931. /* #define TCP_USER_TIMEOUT (18) */
  13932. #if defined(TCP_USER_TIMEOUT)
  13933. unsigned int uto = (unsigned int)milliseconds;
  13934. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13935. #endif
  13936. memset(&tv, 0, sizeof(tv));
  13937. tv.tv_sec = milliseconds / 1000;
  13938. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13939. #endif /* _WIN32 */
  13940. r1 = setsockopt(
  13941. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13942. r2 = setsockopt(
  13943. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13944. return r0 || r1 || r2;
  13945. }
  13946. #endif
  13947. static int
  13948. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13949. {
  13950. if (setsockopt(sock,
  13951. IPPROTO_TCP,
  13952. TCP_NODELAY,
  13953. (SOCK_OPT_TYPE)&nodelay_on,
  13954. sizeof(nodelay_on))
  13955. != 0) {
  13956. /* Error */
  13957. return 1;
  13958. }
  13959. /* OK */
  13960. return 0;
  13961. }
  13962. static void
  13963. close_socket_gracefully(struct mg_connection *conn)
  13964. {
  13965. #if defined(_WIN32)
  13966. char buf[MG_BUF_LEN];
  13967. int n;
  13968. #endif
  13969. struct linger linger;
  13970. int error_code = 0;
  13971. int linger_timeout = -2;
  13972. socklen_t opt_len = sizeof(error_code);
  13973. if (!conn) {
  13974. return;
  13975. }
  13976. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13977. * "Note that enabling a nonzero timeout on a nonblocking socket
  13978. * is not recommended.", so set it to blocking now */
  13979. set_blocking_mode(conn->client.sock);
  13980. /* Send FIN to the client */
  13981. shutdown(conn->client.sock, SHUTDOWN_WR);
  13982. #if defined(_WIN32)
  13983. /* Read and discard pending incoming data. If we do not do that and
  13984. * close
  13985. * the socket, the data in the send buffer may be discarded. This
  13986. * behaviour is seen on Windows, when client keeps sending data
  13987. * when server decides to close the connection; then when client
  13988. * does recv() it gets no data back. */
  13989. do {
  13990. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13991. } while (n > 0);
  13992. #endif
  13993. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13994. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13995. }
  13996. /* Set linger option according to configuration */
  13997. if (linger_timeout >= 0) {
  13998. /* Set linger option to avoid socket hanging out after close. This
  13999. * prevent ephemeral port exhaust problem under high QPS. */
  14000. linger.l_onoff = 1;
  14001. #if defined(_MSC_VER)
  14002. #pragma warning(push)
  14003. #pragma warning(disable : 4244)
  14004. #endif
  14005. #if defined(GCC_DIAGNOSTIC)
  14006. #pragma GCC diagnostic push
  14007. #pragma GCC diagnostic ignored "-Wconversion"
  14008. #endif
  14009. /* Data type of linger structure elements may differ,
  14010. * so we don't know what cast we need here.
  14011. * Disable type conversion warnings. */
  14012. linger.l_linger = (linger_timeout + 999) / 1000;
  14013. #if defined(GCC_DIAGNOSTIC)
  14014. #pragma GCC diagnostic pop
  14015. #endif
  14016. #if defined(_MSC_VER)
  14017. #pragma warning(pop)
  14018. #endif
  14019. } else {
  14020. linger.l_onoff = 0;
  14021. linger.l_linger = 0;
  14022. }
  14023. if (linger_timeout < -1) {
  14024. /* Default: don't configure any linger */
  14025. } else if (getsockopt(conn->client.sock,
  14026. SOL_SOCKET,
  14027. SO_ERROR,
  14028. #if defined(_WIN32) /* WinSock uses different data type here */
  14029. (char *)&error_code,
  14030. #else
  14031. &error_code,
  14032. #endif
  14033. &opt_len)
  14034. != 0) {
  14035. /* Cannot determine if socket is already closed. This should
  14036. * not occur and never did in a test. Log an error message
  14037. * and continue. */
  14038. mg_cry_internal(conn,
  14039. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14040. __func__,
  14041. strerror(ERRNO));
  14042. } else if (error_code == ECONNRESET) {
  14043. /* Socket already closed by client/peer, close socket without linger
  14044. */
  14045. } else {
  14046. /* Set linger timeout */
  14047. if (setsockopt(conn->client.sock,
  14048. SOL_SOCKET,
  14049. SO_LINGER,
  14050. (char *)&linger,
  14051. sizeof(linger))
  14052. != 0) {
  14053. mg_cry_internal(
  14054. conn,
  14055. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14056. __func__,
  14057. linger.l_onoff,
  14058. linger.l_linger,
  14059. strerror(ERRNO));
  14060. }
  14061. }
  14062. /* Now we know that our FIN is ACK-ed, safe to close */
  14063. closesocket(conn->client.sock);
  14064. conn->client.sock = INVALID_SOCKET;
  14065. }
  14066. static void
  14067. close_connection(struct mg_connection *conn)
  14068. {
  14069. #if defined(USE_SERVER_STATS)
  14070. conn->conn_state = 6; /* to close */
  14071. #endif
  14072. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14073. if (conn->lua_websocket_state) {
  14074. lua_websocket_close(conn, conn->lua_websocket_state);
  14075. conn->lua_websocket_state = NULL;
  14076. }
  14077. #endif
  14078. mg_lock_connection(conn);
  14079. /* Set close flag, so keep-alive loops will stop */
  14080. conn->must_close = 1;
  14081. /* call the connection_close callback if assigned */
  14082. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14083. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14084. conn->phys_ctx->callbacks.connection_close(conn);
  14085. }
  14086. }
  14087. /* Reset user data, after close callback is called.
  14088. * Do not reuse it. If the user needs a destructor,
  14089. * it must be done in the connection_close callback. */
  14090. mg_set_user_connection_data(conn, NULL);
  14091. #if defined(USE_SERVER_STATS)
  14092. conn->conn_state = 7; /* closing */
  14093. #endif
  14094. #if !defined(NO_SSL)
  14095. if (conn->ssl != NULL) {
  14096. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14097. */
  14098. SSL_shutdown(conn->ssl);
  14099. SSL_free(conn->ssl);
  14100. OPENSSL_REMOVE_THREAD_STATE();
  14101. conn->ssl = NULL;
  14102. }
  14103. #endif
  14104. if (conn->client.sock != INVALID_SOCKET) {
  14105. close_socket_gracefully(conn);
  14106. conn->client.sock = INVALID_SOCKET;
  14107. }
  14108. if (conn->host) {
  14109. mg_free((void *)conn->host);
  14110. conn->host = NULL;
  14111. }
  14112. mg_unlock_connection(conn);
  14113. #if defined(USE_SERVER_STATS)
  14114. conn->conn_state = 8; /* closed */
  14115. #endif
  14116. }
  14117. void
  14118. mg_close_connection(struct mg_connection *conn)
  14119. {
  14120. #if defined(USE_WEBSOCKET)
  14121. struct mg_context *client_ctx = NULL;
  14122. #endif /* defined(USE_WEBSOCKET) */
  14123. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14124. return;
  14125. }
  14126. #if defined(USE_WEBSOCKET)
  14127. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14128. if (conn->in_websocket_handling) {
  14129. /* Set close flag, so the server thread can exit. */
  14130. conn->must_close = 1;
  14131. return;
  14132. }
  14133. }
  14134. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14135. unsigned int i;
  14136. /* ws/wss client */
  14137. client_ctx = conn->phys_ctx;
  14138. /* client context: loops must end */
  14139. client_ctx->stop_flag = 1;
  14140. conn->must_close = 1;
  14141. /* We need to get the client thread out of the select/recv call
  14142. * here. */
  14143. /* Since we use a sleep quantum of some seconds to check for recv
  14144. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14145. /* join worker thread */
  14146. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  14147. if (client_ctx->worker_threadids[i] != 0) {
  14148. mg_join_thread(client_ctx->worker_threadids[i]);
  14149. }
  14150. }
  14151. }
  14152. #endif /* defined(USE_WEBSOCKET) */
  14153. close_connection(conn);
  14154. #if !defined(NO_SSL)
  14155. if (conn->client_ssl_ctx != NULL) {
  14156. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  14157. }
  14158. #endif
  14159. #if defined(USE_WEBSOCKET)
  14160. if (client_ctx != NULL) {
  14161. /* free context */
  14162. mg_free(client_ctx->worker_threadids);
  14163. mg_free(client_ctx);
  14164. (void)pthread_mutex_destroy(&conn->mutex);
  14165. mg_free(conn);
  14166. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14167. mg_free(conn);
  14168. }
  14169. #else
  14170. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14171. mg_free(conn);
  14172. }
  14173. #endif /* defined(USE_WEBSOCKET) */
  14174. }
  14175. /* Only for memory statistics */
  14176. static struct mg_context common_client_context;
  14177. static struct mg_connection *
  14178. mg_connect_client_impl(const struct mg_client_options *client_options,
  14179. int use_ssl,
  14180. char *ebuf,
  14181. size_t ebuf_len)
  14182. {
  14183. struct mg_connection *conn = NULL;
  14184. SOCKET sock;
  14185. union usa sa;
  14186. struct sockaddr *psa;
  14187. socklen_t len;
  14188. unsigned max_req_size =
  14189. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14190. /* Size of structures, aligned to 8 bytes */
  14191. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14192. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14193. conn = (struct mg_connection *)mg_calloc_ctx(
  14194. 1, conn_size + ctx_size + max_req_size, &common_client_context);
  14195. if (conn == NULL) {
  14196. mg_snprintf(NULL,
  14197. NULL, /* No truncation check for ebuf */
  14198. ebuf,
  14199. ebuf_len,
  14200. "calloc(): %s",
  14201. strerror(ERRNO));
  14202. return NULL;
  14203. }
  14204. #if defined(GCC_DIAGNOSTIC)
  14205. #pragma GCC diagnostic push
  14206. #pragma GCC diagnostic ignored "-Wcast-align"
  14207. #endif /* defined(GCC_DIAGNOSTIC) */
  14208. /* conn_size is aligned to 8 bytes */
  14209. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14210. #if defined(GCC_DIAGNOSTIC)
  14211. #pragma GCC diagnostic pop
  14212. #endif /* defined(GCC_DIAGNOSTIC) */
  14213. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14214. conn->buf_size = (int)max_req_size;
  14215. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14216. conn->dom_ctx = &(conn->phys_ctx->dd);
  14217. if (!connect_socket(&common_client_context,
  14218. client_options->host,
  14219. client_options->port,
  14220. use_ssl,
  14221. ebuf,
  14222. ebuf_len,
  14223. &sock,
  14224. &sa)) {
  14225. /* ebuf is set by connect_socket,
  14226. * free all memory and return NULL; */
  14227. mg_free(conn);
  14228. return NULL;
  14229. }
  14230. #if !defined(NO_SSL)
  14231. #if defined(OPENSSL_API_1_1)
  14232. if (use_ssl
  14233. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  14234. mg_snprintf(NULL,
  14235. NULL, /* No truncation check for ebuf */
  14236. ebuf,
  14237. ebuf_len,
  14238. "SSL_CTX_new error");
  14239. closesocket(sock);
  14240. mg_free(conn);
  14241. return NULL;
  14242. }
  14243. #else
  14244. if (use_ssl
  14245. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14246. == NULL) {
  14247. mg_snprintf(NULL,
  14248. NULL, /* No truncation check for ebuf */
  14249. ebuf,
  14250. ebuf_len,
  14251. "SSL_CTX_new error");
  14252. closesocket(sock);
  14253. mg_free(conn);
  14254. return NULL;
  14255. }
  14256. #endif /* OPENSSL_API_1_1 */
  14257. #endif /* NO_SSL */
  14258. #if defined(USE_IPV6)
  14259. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14260. : sizeof(conn->client.rsa.sin6);
  14261. psa = (sa.sa.sa_family == AF_INET)
  14262. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14263. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14264. #else
  14265. len = sizeof(conn->client.rsa.sin);
  14266. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14267. #endif
  14268. conn->client.sock = sock;
  14269. conn->client.lsa = sa;
  14270. if (getsockname(sock, psa, &len) != 0) {
  14271. mg_cry_internal(conn,
  14272. "%s: getsockname() failed: %s",
  14273. __func__,
  14274. strerror(ERRNO));
  14275. }
  14276. conn->client.is_ssl = use_ssl ? 1 : 0;
  14277. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14278. mg_snprintf(NULL,
  14279. NULL, /* No truncation check for ebuf */
  14280. ebuf,
  14281. ebuf_len,
  14282. "Can not create mutex");
  14283. #if !defined(NO_SSL)
  14284. SSL_CTX_free(conn->client_ssl_ctx);
  14285. #endif
  14286. closesocket(sock);
  14287. mg_free(conn);
  14288. return NULL;
  14289. }
  14290. #if !defined(NO_SSL)
  14291. if (use_ssl) {
  14292. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  14293. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14294. * SSL_CTX_set_verify call is needed to switch off server
  14295. * certificate checking, which is off by default in OpenSSL and
  14296. * on in yaSSL. */
  14297. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  14298. * SSL_VERIFY_PEER, verify_ssl_server); */
  14299. if (client_options->client_cert) {
  14300. if (!ssl_use_pem_file(&common_client_context,
  14301. &(common_client_context.dd),
  14302. client_options->client_cert,
  14303. NULL)) {
  14304. mg_snprintf(NULL,
  14305. NULL, /* No truncation check for ebuf */
  14306. ebuf,
  14307. ebuf_len,
  14308. "Can not use SSL client certificate");
  14309. SSL_CTX_free(conn->client_ssl_ctx);
  14310. closesocket(sock);
  14311. mg_free(conn);
  14312. return NULL;
  14313. }
  14314. }
  14315. if (client_options->server_cert) {
  14316. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  14317. client_options->server_cert,
  14318. NULL);
  14319. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  14320. } else {
  14321. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  14322. }
  14323. if (!sslize(conn,
  14324. conn->client_ssl_ctx,
  14325. SSL_connect,
  14326. &(conn->phys_ctx->stop_flag),
  14327. client_options)) {
  14328. mg_snprintf(NULL,
  14329. NULL, /* No truncation check for ebuf */
  14330. ebuf,
  14331. ebuf_len,
  14332. "SSL connection error");
  14333. SSL_CTX_free(conn->client_ssl_ctx);
  14334. closesocket(sock);
  14335. mg_free(conn);
  14336. return NULL;
  14337. }
  14338. }
  14339. #endif
  14340. if (0 != set_non_blocking_mode(sock)) {
  14341. mg_cry_internal(conn,
  14342. "Cannot set non-blocking mode for client %s:%i",
  14343. client_options->host,
  14344. client_options->port);
  14345. }
  14346. return conn;
  14347. }
  14348. CIVETWEB_API struct mg_connection *
  14349. mg_connect_client_secure(const struct mg_client_options *client_options,
  14350. char *error_buffer,
  14351. size_t error_buffer_size)
  14352. {
  14353. return mg_connect_client_impl(client_options,
  14354. 1,
  14355. error_buffer,
  14356. error_buffer_size);
  14357. }
  14358. struct mg_connection *
  14359. mg_connect_client(const char *host,
  14360. int port,
  14361. int use_ssl,
  14362. char *error_buffer,
  14363. size_t error_buffer_size)
  14364. {
  14365. struct mg_client_options opts;
  14366. memset(&opts, 0, sizeof(opts));
  14367. opts.host = host;
  14368. opts.port = port;
  14369. return mg_connect_client_impl(&opts,
  14370. use_ssl,
  14371. error_buffer,
  14372. error_buffer_size);
  14373. }
  14374. static const struct {
  14375. const char *proto;
  14376. size_t proto_len;
  14377. unsigned default_port;
  14378. } abs_uri_protocols[] = {{"http://", 7, 80},
  14379. {"https://", 8, 443},
  14380. {"ws://", 5, 80},
  14381. {"wss://", 6, 443},
  14382. {NULL, 0, 0}};
  14383. /* Check if the uri is valid.
  14384. * return 0 for invalid uri,
  14385. * return 1 for *,
  14386. * return 2 for relative uri,
  14387. * return 3 for absolute uri without port,
  14388. * return 4 for absolute uri with port */
  14389. static int
  14390. get_uri_type(const char *uri)
  14391. {
  14392. int i;
  14393. const char *hostend, *portbegin;
  14394. char *portend;
  14395. unsigned long port;
  14396. /* According to the HTTP standard
  14397. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14398. * URI can be an asterisk (*) or should start with slash (relative uri),
  14399. * or it should start with the protocol (absolute uri). */
  14400. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14401. /* asterisk */
  14402. return 1;
  14403. }
  14404. /* Valid URIs according to RFC 3986
  14405. * (https://www.ietf.org/rfc/rfc3986.txt)
  14406. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14407. * and unreserved characters A-Z a-z 0-9 and -._~
  14408. * and % encoded symbols.
  14409. */
  14410. for (i = 0; uri[i] != 0; i++) {
  14411. if (uri[i] < 33) {
  14412. /* control characters and spaces are invalid */
  14413. return 0;
  14414. }
  14415. if (uri[i] > 126) {
  14416. /* non-ascii characters must be % encoded */
  14417. return 0;
  14418. } else {
  14419. switch (uri[i]) {
  14420. case '"': /* 34 */
  14421. case '<': /* 60 */
  14422. case '>': /* 62 */
  14423. case '\\': /* 92 */
  14424. case '^': /* 94 */
  14425. case '`': /* 96 */
  14426. case '{': /* 123 */
  14427. case '|': /* 124 */
  14428. case '}': /* 125 */
  14429. return 0;
  14430. default:
  14431. /* character is ok */
  14432. break;
  14433. }
  14434. }
  14435. }
  14436. /* A relative uri starts with a / character */
  14437. if (uri[0] == '/') {
  14438. /* relative uri */
  14439. return 2;
  14440. }
  14441. /* It could be an absolute uri: */
  14442. /* This function only checks if the uri is valid, not if it is
  14443. * addressing the current server. So civetweb can also be used
  14444. * as a proxy server. */
  14445. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14446. if (mg_strncasecmp(uri,
  14447. abs_uri_protocols[i].proto,
  14448. abs_uri_protocols[i].proto_len)
  14449. == 0) {
  14450. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14451. if (!hostend) {
  14452. return 0;
  14453. }
  14454. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14455. if (!portbegin) {
  14456. return 3;
  14457. }
  14458. port = strtoul(portbegin + 1, &portend, 10);
  14459. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14460. return 0;
  14461. }
  14462. return 4;
  14463. }
  14464. }
  14465. return 0;
  14466. }
  14467. /* Return NULL or the relative uri at the current server */
  14468. static const char *
  14469. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14470. {
  14471. const char *server_domain;
  14472. size_t server_domain_len;
  14473. size_t request_domain_len = 0;
  14474. unsigned long port = 0;
  14475. int i, auth_domain_check_enabled;
  14476. const char *hostbegin = NULL;
  14477. const char *hostend = NULL;
  14478. const char *portbegin;
  14479. char *portend;
  14480. auth_domain_check_enabled =
  14481. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14482. /* DNS is case insensitive, so use case insensitive string compare here
  14483. */
  14484. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14485. if (mg_strncasecmp(uri,
  14486. abs_uri_protocols[i].proto,
  14487. abs_uri_protocols[i].proto_len)
  14488. == 0) {
  14489. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14490. hostend = strchr(hostbegin, '/');
  14491. if (!hostend) {
  14492. return 0;
  14493. }
  14494. portbegin = strchr(hostbegin, ':');
  14495. if ((!portbegin) || (portbegin > hostend)) {
  14496. port = abs_uri_protocols[i].default_port;
  14497. request_domain_len = (size_t)(hostend - hostbegin);
  14498. } else {
  14499. port = strtoul(portbegin + 1, &portend, 10);
  14500. if ((portend != hostend) || (port <= 0)
  14501. || !is_valid_port(port)) {
  14502. return 0;
  14503. }
  14504. request_domain_len = (size_t)(portbegin - hostbegin);
  14505. }
  14506. /* protocol found, port set */
  14507. break;
  14508. }
  14509. }
  14510. if (!port) {
  14511. /* port remains 0 if the protocol is not found */
  14512. return 0;
  14513. }
  14514. /* Check if the request is directed to a different server. */
  14515. /* First check if the port is the same (IPv4 and IPv6). */
  14516. #if defined(USE_IPV6)
  14517. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14518. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14519. /* Request is directed to a different port */
  14520. return 0;
  14521. }
  14522. } else
  14523. #endif
  14524. {
  14525. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14526. /* Request is directed to a different port */
  14527. return 0;
  14528. }
  14529. }
  14530. /* Finally check if the server corresponds to the authentication
  14531. * domain of the server (the server domain).
  14532. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14533. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14534. * but do not allow substrings (like
  14535. * http://notmydomain.com/path/file.ext
  14536. * or http://mydomain.com.fake/path/file.ext).
  14537. */
  14538. if (auth_domain_check_enabled) {
  14539. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14540. server_domain_len = strlen(server_domain);
  14541. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14542. return 0;
  14543. }
  14544. if ((request_domain_len == server_domain_len)
  14545. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14546. /* Request is directed to this server - full name match. */
  14547. } else {
  14548. if (request_domain_len < (server_domain_len + 2)) {
  14549. /* Request is directed to another server: The server name
  14550. * is longer than the request name.
  14551. * Drop this case here to avoid overflows in the
  14552. * following checks. */
  14553. return 0;
  14554. }
  14555. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14556. /* Request is directed to another server: It could be a
  14557. * substring
  14558. * like notmyserver.com */
  14559. return 0;
  14560. }
  14561. if (0
  14562. != memcmp(server_domain,
  14563. hostbegin + request_domain_len - server_domain_len,
  14564. server_domain_len)) {
  14565. /* Request is directed to another server:
  14566. * The server name is different. */
  14567. return 0;
  14568. }
  14569. }
  14570. }
  14571. return hostend;
  14572. }
  14573. static int
  14574. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14575. {
  14576. if (ebuf_len > 0) {
  14577. ebuf[0] = '\0';
  14578. }
  14579. *err = 0;
  14580. reset_per_request_attributes(conn);
  14581. if (!conn) {
  14582. mg_snprintf(conn,
  14583. NULL, /* No truncation check for ebuf */
  14584. ebuf,
  14585. ebuf_len,
  14586. "%s",
  14587. "Internal error");
  14588. *err = 500;
  14589. return 0;
  14590. }
  14591. /* Set the time the request was received. This value should be used for
  14592. * timeouts. */
  14593. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14594. conn->request_len =
  14595. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14596. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14597. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14598. mg_snprintf(conn,
  14599. NULL, /* No truncation check for ebuf */
  14600. ebuf,
  14601. ebuf_len,
  14602. "%s",
  14603. "Invalid message size");
  14604. *err = 500;
  14605. return 0;
  14606. }
  14607. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14608. mg_snprintf(conn,
  14609. NULL, /* No truncation check for ebuf */
  14610. ebuf,
  14611. ebuf_len,
  14612. "%s",
  14613. "Message too large");
  14614. *err = 413;
  14615. return 0;
  14616. }
  14617. if (conn->request_len <= 0) {
  14618. if (conn->data_len > 0) {
  14619. mg_snprintf(conn,
  14620. NULL, /* No truncation check for ebuf */
  14621. ebuf,
  14622. ebuf_len,
  14623. "%s",
  14624. "Malformed message");
  14625. *err = 400;
  14626. } else {
  14627. /* Server did not recv anything -> just close the connection */
  14628. conn->must_close = 1;
  14629. mg_snprintf(conn,
  14630. NULL, /* No truncation check for ebuf */
  14631. ebuf,
  14632. ebuf_len,
  14633. "%s",
  14634. "No data received");
  14635. *err = 0;
  14636. }
  14637. return 0;
  14638. }
  14639. return 1;
  14640. }
  14641. static int
  14642. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14643. {
  14644. const char *cl;
  14645. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14646. return 0;
  14647. }
  14648. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14649. <= 0) {
  14650. mg_snprintf(conn,
  14651. NULL, /* No truncation check for ebuf */
  14652. ebuf,
  14653. ebuf_len,
  14654. "%s",
  14655. "Bad request");
  14656. *err = 400;
  14657. return 0;
  14658. }
  14659. /* Message is a valid request */
  14660. /* Is there a "host" ? */
  14661. if (conn->host != NULL) {
  14662. mg_free((void *)conn->host);
  14663. }
  14664. conn->host = alloc_get_host(conn);
  14665. if (!conn->host) {
  14666. mg_snprintf(conn,
  14667. NULL, /* No truncation check for ebuf */
  14668. ebuf,
  14669. ebuf_len,
  14670. "%s",
  14671. "Bad request: Host mismatch");
  14672. *err = 400;
  14673. return 0;
  14674. }
  14675. /* Do we know the content length? */
  14676. if ((cl = get_header(conn->request_info.http_headers,
  14677. conn->request_info.num_headers,
  14678. "Content-Length"))
  14679. != NULL) {
  14680. /* Request/response has content length set */
  14681. char *endptr = NULL;
  14682. conn->content_len = strtoll(cl, &endptr, 10);
  14683. if (endptr == cl) {
  14684. mg_snprintf(conn,
  14685. NULL, /* No truncation check for ebuf */
  14686. ebuf,
  14687. ebuf_len,
  14688. "%s",
  14689. "Bad request");
  14690. *err = 411;
  14691. return 0;
  14692. }
  14693. /* Publish the content length back to the request info. */
  14694. conn->request_info.content_length = conn->content_len;
  14695. } else if ((cl = get_header(conn->request_info.http_headers,
  14696. conn->request_info.num_headers,
  14697. "Transfer-Encoding"))
  14698. != NULL
  14699. && !mg_strcasecmp(cl, "chunked")) {
  14700. conn->is_chunked = 1;
  14701. conn->content_len = -1; /* unknown content length */
  14702. } else {
  14703. const struct mg_http_method_info *meth =
  14704. get_http_method_info(conn->request_info.request_method);
  14705. if (!meth) {
  14706. /* No valid HTTP method */
  14707. mg_snprintf(conn,
  14708. NULL, /* No truncation check for ebuf */
  14709. ebuf,
  14710. ebuf_len,
  14711. "%s",
  14712. "Bad request");
  14713. *err = 411;
  14714. return 0;
  14715. }
  14716. if (meth->request_has_body) {
  14717. /* POST or PUT request without content length set */
  14718. conn->content_len = -1; /* unknown content length */
  14719. } else {
  14720. /* Other request */
  14721. conn->content_len = 0; /* No content */
  14722. }
  14723. }
  14724. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14725. return 1;
  14726. }
  14727. /* conn is assumed to be valid in this internal function */
  14728. static int
  14729. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14730. {
  14731. const char *cl;
  14732. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14733. return 0;
  14734. }
  14735. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14736. <= 0) {
  14737. mg_snprintf(conn,
  14738. NULL, /* No truncation check for ebuf */
  14739. ebuf,
  14740. ebuf_len,
  14741. "%s",
  14742. "Bad response");
  14743. *err = 400;
  14744. return 0;
  14745. }
  14746. /* Message is a valid response */
  14747. /* Do we know the content length? */
  14748. if ((cl = get_header(conn->response_info.http_headers,
  14749. conn->response_info.num_headers,
  14750. "Content-Length"))
  14751. != NULL) {
  14752. /* Request/response has content length set */
  14753. char *endptr = NULL;
  14754. conn->content_len = strtoll(cl, &endptr, 10);
  14755. if (endptr == cl) {
  14756. mg_snprintf(conn,
  14757. NULL, /* No truncation check for ebuf */
  14758. ebuf,
  14759. ebuf_len,
  14760. "%s",
  14761. "Bad request");
  14762. *err = 411;
  14763. return 0;
  14764. }
  14765. /* Publish the content length back to the response info. */
  14766. conn->response_info.content_length = conn->content_len;
  14767. /* TODO: check if it is still used in response_info */
  14768. conn->request_info.content_length = conn->content_len;
  14769. } else if ((cl = get_header(conn->response_info.http_headers,
  14770. conn->response_info.num_headers,
  14771. "Transfer-Encoding"))
  14772. != NULL
  14773. && !mg_strcasecmp(cl, "chunked")) {
  14774. conn->is_chunked = 1;
  14775. conn->content_len = -1; /* unknown content length */
  14776. } else {
  14777. conn->content_len = -1; /* unknown content length */
  14778. }
  14779. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14780. return 1;
  14781. }
  14782. int
  14783. mg_get_response(struct mg_connection *conn,
  14784. char *ebuf,
  14785. size_t ebuf_len,
  14786. int timeout)
  14787. {
  14788. int err, ret;
  14789. char txt[32]; /* will not overflow */
  14790. char *save_timeout;
  14791. char *new_timeout;
  14792. if (ebuf_len > 0) {
  14793. ebuf[0] = '\0';
  14794. }
  14795. if (!conn) {
  14796. mg_snprintf(conn,
  14797. NULL, /* No truncation check for ebuf */
  14798. ebuf,
  14799. ebuf_len,
  14800. "%s",
  14801. "Parameter error");
  14802. return -1;
  14803. }
  14804. /* Reset the previous responses */
  14805. conn->data_len = 0;
  14806. /* Implementation of API function for HTTP clients */
  14807. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14808. if (timeout >= 0) {
  14809. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14810. new_timeout = txt;
  14811. /* Not required for non-blocking sockets.
  14812. set_sock_timeout(conn->client.sock, timeout);
  14813. */
  14814. } else {
  14815. new_timeout = NULL;
  14816. }
  14817. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14818. ret = get_response(conn, ebuf, ebuf_len, &err);
  14819. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14820. #if defined(MG_LEGACY_INTERFACE)
  14821. /* TODO: 1) uri is deprecated;
  14822. * 2) here, ri.uri is the http response code */
  14823. conn->request_info.uri = conn->request_info.request_uri;
  14824. #endif
  14825. conn->request_info.local_uri = conn->request_info.request_uri;
  14826. /* TODO (mid): Define proper return values - maybe return length?
  14827. * For the first test use <0 for error and >0 for OK */
  14828. return (ret == 0) ? -1 : +1;
  14829. }
  14830. struct mg_connection *
  14831. mg_download(const char *host,
  14832. int port,
  14833. int use_ssl,
  14834. char *ebuf,
  14835. size_t ebuf_len,
  14836. const char *fmt,
  14837. ...)
  14838. {
  14839. struct mg_connection *conn;
  14840. va_list ap;
  14841. int i;
  14842. int reqerr;
  14843. if (ebuf_len > 0) {
  14844. ebuf[0] = '\0';
  14845. }
  14846. va_start(ap, fmt);
  14847. /* open a connection */
  14848. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14849. if (conn != NULL) {
  14850. i = mg_vprintf(conn, fmt, ap);
  14851. if (i <= 0) {
  14852. mg_snprintf(conn,
  14853. NULL, /* No truncation check for ebuf */
  14854. ebuf,
  14855. ebuf_len,
  14856. "%s",
  14857. "Error sending request");
  14858. } else {
  14859. /* make sure the buffer is clear */
  14860. conn->data_len = 0;
  14861. get_response(conn, ebuf, ebuf_len, &reqerr);
  14862. #if defined(MG_LEGACY_INTERFACE)
  14863. /* TODO: 1) uri is deprecated;
  14864. * 2) here, ri.uri is the http response code */
  14865. conn->request_info.uri = conn->request_info.request_uri;
  14866. #endif
  14867. conn->request_info.local_uri = conn->request_info.request_uri;
  14868. }
  14869. }
  14870. /* if an error occurred, close the connection */
  14871. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14872. mg_close_connection(conn);
  14873. conn = NULL;
  14874. }
  14875. va_end(ap);
  14876. return conn;
  14877. }
  14878. struct websocket_client_thread_data {
  14879. struct mg_connection *conn;
  14880. mg_websocket_data_handler data_handler;
  14881. mg_websocket_close_handler close_handler;
  14882. void *callback_data;
  14883. };
  14884. #if defined(USE_WEBSOCKET)
  14885. #if defined(_WIN32)
  14886. static unsigned __stdcall websocket_client_thread(void *data)
  14887. #else
  14888. static void *
  14889. websocket_client_thread(void *data)
  14890. #endif
  14891. {
  14892. struct websocket_client_thread_data *cdata =
  14893. (struct websocket_client_thread_data *)data;
  14894. #if !defined(_WIN32)
  14895. struct sigaction sa;
  14896. /* Ignore SIGPIPE */
  14897. memset(&sa, 0, sizeof(sa));
  14898. sa.sa_handler = SIG_IGN;
  14899. sigaction(SIGPIPE, &sa, NULL);
  14900. #endif
  14901. mg_set_thread_name("ws-clnt");
  14902. if (cdata->conn->phys_ctx) {
  14903. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14904. /* 3 indicates a websocket client thread */
  14905. /* TODO: check if conn->phys_ctx can be set */
  14906. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  14907. 3);
  14908. }
  14909. }
  14910. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14911. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14912. if (cdata->close_handler != NULL) {
  14913. cdata->close_handler(cdata->conn, cdata->callback_data);
  14914. }
  14915. /* The websocket_client context has only this thread. If it runs out,
  14916. set the stop_flag to 2 (= "stopped"). */
  14917. cdata->conn->phys_ctx->stop_flag = 2;
  14918. mg_free((void *)cdata);
  14919. #if defined(_WIN32)
  14920. return 0;
  14921. #else
  14922. return NULL;
  14923. #endif
  14924. }
  14925. #endif
  14926. struct mg_connection *
  14927. mg_connect_websocket_client(const char *host,
  14928. int port,
  14929. int use_ssl,
  14930. char *error_buffer,
  14931. size_t error_buffer_size,
  14932. const char *path,
  14933. const char *origin,
  14934. mg_websocket_data_handler data_func,
  14935. mg_websocket_close_handler close_func,
  14936. void *user_data)
  14937. {
  14938. struct mg_connection *conn = NULL;
  14939. #if defined(USE_WEBSOCKET)
  14940. struct mg_context *newctx = NULL;
  14941. struct websocket_client_thread_data *thread_data;
  14942. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14943. static const char *handshake_req;
  14944. if (origin != NULL) {
  14945. handshake_req = "GET %s HTTP/1.1\r\n"
  14946. "Host: %s\r\n"
  14947. "Upgrade: websocket\r\n"
  14948. "Connection: Upgrade\r\n"
  14949. "Sec-WebSocket-Key: %s\r\n"
  14950. "Sec-WebSocket-Version: 13\r\n"
  14951. "Origin: %s\r\n"
  14952. "\r\n";
  14953. } else {
  14954. handshake_req = "GET %s HTTP/1.1\r\n"
  14955. "Host: %s\r\n"
  14956. "Upgrade: websocket\r\n"
  14957. "Connection: Upgrade\r\n"
  14958. "Sec-WebSocket-Key: %s\r\n"
  14959. "Sec-WebSocket-Version: 13\r\n"
  14960. "\r\n";
  14961. }
  14962. #if defined(__clang__)
  14963. #pragma clang diagnostic push
  14964. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  14965. #endif
  14966. /* Establish the client connection and request upgrade */
  14967. conn = mg_download(host,
  14968. port,
  14969. use_ssl,
  14970. error_buffer,
  14971. error_buffer_size,
  14972. handshake_req,
  14973. path,
  14974. host,
  14975. magic,
  14976. origin);
  14977. #if defined(__clang__)
  14978. #pragma clang diagnostic pop
  14979. #endif
  14980. /* Connection object will be null if something goes wrong */
  14981. if (conn == NULL) {
  14982. if (!*error_buffer) {
  14983. /* There should be already an error message */
  14984. mg_snprintf(conn,
  14985. NULL, /* No truncation check for ebuf */
  14986. error_buffer,
  14987. error_buffer_size,
  14988. "Unexpected error");
  14989. }
  14990. return NULL;
  14991. }
  14992. if (conn->response_info.status_code != 101) {
  14993. /* We sent an "upgrade" request. For a correct websocket
  14994. * protocol handshake, we expect a "101 Continue" response.
  14995. * Otherwise it is a protocol violation. Maybe the HTTP
  14996. * Server does not know websockets. */
  14997. if (!*error_buffer) {
  14998. /* set an error, if not yet set */
  14999. mg_snprintf(conn,
  15000. NULL, /* No truncation check for ebuf */
  15001. error_buffer,
  15002. error_buffer_size,
  15003. "Unexpected server reply");
  15004. }
  15005. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  15006. mg_free(conn);
  15007. return NULL;
  15008. }
  15009. /* For client connections, mg_context is fake. Since we need to set a
  15010. * callback function, we need to create a copy and modify it. */
  15011. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  15012. if (!newctx) {
  15013. DEBUG_TRACE("%s\r\n", "Out of memory");
  15014. mg_free(conn);
  15015. return NULL;
  15016. }
  15017. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  15018. newctx->user_data = user_data;
  15019. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  15020. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  15021. newctx->worker_threadids =
  15022. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  15023. sizeof(pthread_t),
  15024. newctx);
  15025. conn->phys_ctx = newctx;
  15026. conn->dom_ctx = &(newctx->dd);
  15027. thread_data = (struct websocket_client_thread_data *)
  15028. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  15029. if (!thread_data) {
  15030. DEBUG_TRACE("%s\r\n", "Out of memory");
  15031. mg_free(newctx);
  15032. mg_free(conn);
  15033. return NULL;
  15034. }
  15035. thread_data->conn = conn;
  15036. thread_data->data_handler = data_func;
  15037. thread_data->close_handler = close_func;
  15038. thread_data->callback_data = user_data;
  15039. /* Start a thread to read the websocket client connection
  15040. * This thread will automatically stop when mg_disconnect is
  15041. * called on the client connection */
  15042. if (mg_start_thread_with_id(websocket_client_thread,
  15043. (void *)thread_data,
  15044. newctx->worker_threadids)
  15045. != 0) {
  15046. mg_free((void *)thread_data);
  15047. mg_free((void *)newctx->worker_threadids);
  15048. mg_free((void *)newctx);
  15049. mg_free((void *)conn);
  15050. conn = NULL;
  15051. DEBUG_TRACE("%s",
  15052. "Websocket client connect thread could not be started\r\n");
  15053. }
  15054. #else
  15055. /* Appease "unused parameter" warnings */
  15056. (void)host;
  15057. (void)port;
  15058. (void)use_ssl;
  15059. (void)error_buffer;
  15060. (void)error_buffer_size;
  15061. (void)path;
  15062. (void)origin;
  15063. (void)user_data;
  15064. (void)data_func;
  15065. (void)close_func;
  15066. #endif
  15067. return conn;
  15068. }
  15069. /* Prepare connection data structure */
  15070. static void
  15071. init_connection(struct mg_connection *conn)
  15072. {
  15073. /* Is keep alive allowed by the server */
  15074. int keep_alive_enabled =
  15075. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15076. if (!keep_alive_enabled) {
  15077. conn->must_close = 1;
  15078. }
  15079. /* Important: on new connection, reset the receiving buffer. Credit
  15080. * goes to crule42. */
  15081. conn->data_len = 0;
  15082. conn->handled_requests = 0;
  15083. mg_set_user_connection_data(conn, NULL);
  15084. #if defined(USE_SERVER_STATS)
  15085. conn->conn_state = 2; /* init */
  15086. #endif
  15087. /* call the init_connection callback if assigned */
  15088. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15089. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15090. void *conn_data = NULL;
  15091. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15092. mg_set_user_connection_data(conn, conn_data);
  15093. }
  15094. }
  15095. }
  15096. /* Process a connection - may handle multiple requests
  15097. * using the same connection.
  15098. * Must be called with a valid connection (conn and
  15099. * conn->phys_ctx must be valid).
  15100. */
  15101. static void
  15102. process_new_connection(struct mg_connection *conn)
  15103. {
  15104. struct mg_request_info *ri = &conn->request_info;
  15105. int keep_alive, discard_len;
  15106. char ebuf[100];
  15107. const char *hostend;
  15108. int reqerr, uri_type;
  15109. #if defined(USE_SERVER_STATS)
  15110. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15111. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15112. if (mcon > (conn->phys_ctx->max_connections)) {
  15113. /* could use atomic compare exchange, but this
  15114. * seems overkill for statistics data */
  15115. conn->phys_ctx->max_connections = mcon;
  15116. }
  15117. #endif
  15118. init_connection(conn);
  15119. DEBUG_TRACE("Start processing connection from %s",
  15120. conn->request_info.remote_addr);
  15121. /* Loop over multiple requests sent using the same connection
  15122. * (while "keep alive"). */
  15123. do {
  15124. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15125. conn->handled_requests + 1);
  15126. #if defined(USE_SERVER_STATS)
  15127. conn->conn_state = 3; /* ready */
  15128. #endif
  15129. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15130. /* The request sent by the client could not be understood by
  15131. * the server, or it was incomplete or a timeout. Send an
  15132. * error message and close the connection. */
  15133. if (reqerr > 0) {
  15134. DEBUG_ASSERT(ebuf[0] != '\0');
  15135. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15136. }
  15137. } else if (strcmp(ri->http_version, "1.0")
  15138. && strcmp(ri->http_version, "1.1")) {
  15139. mg_snprintf(conn,
  15140. NULL, /* No truncation check for ebuf */
  15141. ebuf,
  15142. sizeof(ebuf),
  15143. "Bad HTTP version: [%s]",
  15144. ri->http_version);
  15145. mg_send_http_error(conn, 505, "%s", ebuf);
  15146. }
  15147. if (ebuf[0] == '\0') {
  15148. uri_type = get_uri_type(conn->request_info.request_uri);
  15149. switch (uri_type) {
  15150. case 1:
  15151. /* Asterisk */
  15152. conn->request_info.local_uri = NULL;
  15153. break;
  15154. case 2:
  15155. /* relative uri */
  15156. conn->request_info.local_uri = conn->request_info.request_uri;
  15157. break;
  15158. case 3:
  15159. case 4:
  15160. /* absolute uri (with/without port) */
  15161. hostend = get_rel_url_at_current_server(
  15162. conn->request_info.request_uri, conn);
  15163. if (hostend) {
  15164. conn->request_info.local_uri = hostend;
  15165. } else {
  15166. conn->request_info.local_uri = NULL;
  15167. }
  15168. break;
  15169. default:
  15170. mg_snprintf(conn,
  15171. NULL, /* No truncation check for ebuf */
  15172. ebuf,
  15173. sizeof(ebuf),
  15174. "Invalid URI");
  15175. mg_send_http_error(conn, 400, "%s", ebuf);
  15176. conn->request_info.local_uri = NULL;
  15177. break;
  15178. }
  15179. #if defined(MG_LEGACY_INTERFACE)
  15180. /* Legacy before split into local_uri and request_uri */
  15181. conn->request_info.uri = conn->request_info.local_uri;
  15182. #endif
  15183. }
  15184. DEBUG_TRACE("http: %s, error: %s",
  15185. (ri->http_version ? ri->http_version : "none"),
  15186. (ebuf[0] ? ebuf : "none"));
  15187. if (ebuf[0] == '\0') {
  15188. if (conn->request_info.local_uri) {
  15189. /* handle request to local server */
  15190. #if defined(USE_SERVER_STATS)
  15191. conn->conn_state = 4; /* processing */
  15192. #endif
  15193. handle_request(conn);
  15194. #if defined(USE_SERVER_STATS)
  15195. conn->conn_state = 5; /* processed */
  15196. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15197. conn->consumed_content);
  15198. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15199. conn->num_bytes_sent);
  15200. #endif
  15201. DEBUG_TRACE("%s", "handle_request done");
  15202. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15203. conn->phys_ctx->callbacks.end_request(conn,
  15204. conn->status_code);
  15205. DEBUG_TRACE("%s", "end_request callback done");
  15206. }
  15207. log_access(conn);
  15208. } else {
  15209. /* TODO: handle non-local request (PROXY) */
  15210. conn->must_close = 1;
  15211. }
  15212. } else {
  15213. conn->must_close = 1;
  15214. }
  15215. if (ri->remote_user != NULL) {
  15216. mg_free((void *)ri->remote_user);
  15217. /* Important! When having connections with and without auth
  15218. * would cause double free and then crash */
  15219. ri->remote_user = NULL;
  15220. }
  15221. /* NOTE(lsm): order is important here. should_keep_alive() call
  15222. * is using parsed request, which will be invalid after
  15223. * memmove's below.
  15224. * Therefore, memorize should_keep_alive() result now for later
  15225. * use in loop exit condition. */
  15226. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15227. && (conn->content_len >= 0);
  15228. /* Discard all buffered data for this request */
  15229. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  15230. && ((conn->request_len + conn->content_len)
  15231. < (int64_t)conn->data_len))
  15232. ? (int)(conn->request_len + conn->content_len)
  15233. : conn->data_len;
  15234. DEBUG_ASSERT(discard_len >= 0);
  15235. if (discard_len < 0) {
  15236. DEBUG_TRACE("internal error: discard_len = %li",
  15237. (long int)discard_len);
  15238. break;
  15239. }
  15240. conn->data_len -= discard_len;
  15241. if (conn->data_len > 0) {
  15242. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  15243. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  15244. }
  15245. DEBUG_ASSERT(conn->data_len >= 0);
  15246. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15247. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15248. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15249. (long int)conn->data_len,
  15250. (long int)conn->buf_size);
  15251. break;
  15252. }
  15253. conn->handled_requests++;
  15254. } while (keep_alive);
  15255. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15256. conn->request_info.remote_addr,
  15257. difftime(time(NULL), conn->conn_birth_time));
  15258. close_connection(conn);
  15259. #if defined(USE_SERVER_STATS)
  15260. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15261. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15262. #endif
  15263. }
  15264. #if defined(ALTERNATIVE_QUEUE)
  15265. static void
  15266. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15267. {
  15268. unsigned int i;
  15269. while (!ctx->stop_flag) {
  15270. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15271. /* find a free worker slot and signal it */
  15272. if (ctx->client_socks[i].in_use == 2) {
  15273. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15274. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15275. ctx->client_socks[i] = *sp;
  15276. ctx->client_socks[i].in_use = 1;
  15277. /* socket has been moved to the consumer */
  15278. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15279. (void)event_signal(ctx->client_wait_events[i]);
  15280. return;
  15281. }
  15282. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15283. }
  15284. }
  15285. /* queue is full */
  15286. mg_sleep(1);
  15287. }
  15288. /* must consume */
  15289. set_blocking_mode(sp->sock);
  15290. closesocket(sp->sock);
  15291. }
  15292. static int
  15293. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15294. {
  15295. DEBUG_TRACE("%s", "going idle");
  15296. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15297. ctx->client_socks[thread_index].in_use = 2;
  15298. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15299. event_wait(ctx->client_wait_events[thread_index]);
  15300. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15301. *sp = ctx->client_socks[thread_index];
  15302. if (ctx->stop_flag) {
  15303. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15304. if (sp->in_use == 1) {
  15305. /* must consume */
  15306. set_blocking_mode(sp->sock);
  15307. closesocket(sp->sock);
  15308. }
  15309. return 0;
  15310. }
  15311. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15312. if (sp->in_use == 1) {
  15313. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15314. return 1;
  15315. }
  15316. /* must not reach here */
  15317. DEBUG_ASSERT(0);
  15318. return 0;
  15319. }
  15320. #else /* ALTERNATIVE_QUEUE */
  15321. /* Worker threads take accepted socket from the queue */
  15322. static int
  15323. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15324. {
  15325. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15326. (void)thread_index;
  15327. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15328. DEBUG_TRACE("%s", "going idle");
  15329. /* If the queue is empty, wait. We're idle at this point. */
  15330. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15331. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15332. }
  15333. /* If we're stopping, sq_head may be equal to sq_tail. */
  15334. if (ctx->sq_head > ctx->sq_tail) {
  15335. /* Copy socket from the queue and increment tail */
  15336. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15337. ctx->sq_tail++;
  15338. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15339. /* Wrap pointers if needed */
  15340. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15341. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15342. ctx->sq_head -= QUEUE_SIZE(ctx);
  15343. }
  15344. }
  15345. (void)pthread_cond_signal(&ctx->sq_empty);
  15346. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15347. return !ctx->stop_flag;
  15348. #undef QUEUE_SIZE
  15349. }
  15350. /* Master thread adds accepted socket to a queue */
  15351. static void
  15352. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15353. {
  15354. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15355. if (!ctx) {
  15356. return;
  15357. }
  15358. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15359. /* If the queue is full, wait */
  15360. while ((ctx->stop_flag == 0)
  15361. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15362. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15363. }
  15364. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15365. /* Copy socket to the queue and increment head */
  15366. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15367. ctx->sq_head++;
  15368. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15369. }
  15370. (void)pthread_cond_signal(&ctx->sq_full);
  15371. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15372. #undef QUEUE_SIZE
  15373. }
  15374. #endif /* ALTERNATIVE_QUEUE */
  15375. static void
  15376. worker_thread_run(struct mg_connection *conn)
  15377. {
  15378. struct mg_context *ctx = conn->phys_ctx;
  15379. int thread_index;
  15380. struct mg_workerTLS tls;
  15381. #if defined(MG_LEGACY_INTERFACE)
  15382. uint32_t addr;
  15383. #endif
  15384. mg_set_thread_name("worker");
  15385. tls.is_master = 0;
  15386. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15387. #if defined(_WIN32)
  15388. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15389. #endif
  15390. /* Initialize thread local storage before calling any callback */
  15391. pthread_setspecific(sTlsKey, &tls);
  15392. if (ctx->callbacks.init_thread) {
  15393. /* call init_thread for a worker thread (type 1) */
  15394. ctx->callbacks.init_thread(ctx, 1);
  15395. }
  15396. /* Connection structure has been pre-allocated */
  15397. thread_index = (int)(conn - ctx->worker_connections);
  15398. if ((thread_index < 0)
  15399. || ((unsigned)thread_index
  15400. >= (unsigned)ctx->cfg_worker_threads)) {
  15401. mg_cry_internal(fc(ctx),
  15402. "Internal error: Invalid worker index %i",
  15403. thread_index);
  15404. return;
  15405. }
  15406. /* Request buffers are not pre-allocated. They are private to the
  15407. * request and do not contain any state information that might be
  15408. * of interest to anyone observing a server status. */
  15409. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15410. if (conn->buf == NULL) {
  15411. mg_cry_internal(fc(ctx),
  15412. "Out of memory: Cannot allocate buffer for worker %i",
  15413. thread_index);
  15414. return;
  15415. }
  15416. conn->buf_size = (int)ctx->max_request_size;
  15417. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15418. conn->host = NULL; /* until we have more information. */
  15419. conn->request_info.user_data = ctx->user_data;
  15420. /* Allocate a mutex for this connection to allow communication both
  15421. * within the request handler and from elsewhere in the application
  15422. */
  15423. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15424. mg_free(conn->buf);
  15425. mg_cry_internal(fc(ctx), "%s", "Cannot create mutex");
  15426. return;
  15427. }
  15428. #if defined(USE_SERVER_STATS)
  15429. conn->conn_state = 1; /* not consumed */
  15430. #endif
  15431. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15432. * signal sq_empty condvar to wake up the master waiting in
  15433. * produce_socket() */
  15434. while (consume_socket(ctx, &conn->client, thread_index)) {
  15435. conn->conn_birth_time = time(NULL);
  15436. /* Fill in IP, port info early so even if SSL setup below fails,
  15437. * error handler would have the corresponding info.
  15438. * Thanks to Johannes Winkelmann for the patch.
  15439. */
  15440. #if defined(USE_IPV6)
  15441. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15442. conn->request_info.remote_port =
  15443. ntohs(conn->client.rsa.sin6.sin6_port);
  15444. } else
  15445. #endif
  15446. {
  15447. conn->request_info.remote_port =
  15448. ntohs(conn->client.rsa.sin.sin_port);
  15449. }
  15450. sockaddr_to_string(conn->request_info.remote_addr,
  15451. sizeof(conn->request_info.remote_addr),
  15452. &conn->client.rsa);
  15453. DEBUG_TRACE("Start processing connection from %s",
  15454. conn->request_info.remote_addr);
  15455. conn->request_info.is_ssl = conn->client.is_ssl;
  15456. if (conn->client.is_ssl) {
  15457. #if !defined(NO_SSL)
  15458. /* HTTPS connection */
  15459. if (sslize(conn,
  15460. conn->dom_ctx->ssl_ctx,
  15461. SSL_accept,
  15462. &(conn->phys_ctx->stop_flag),
  15463. NULL)) {
  15464. /* conn->dom_ctx is set in get_request */
  15465. /* Get SSL client certificate information (if set) */
  15466. ssl_get_client_cert_info(conn);
  15467. /* process HTTPS connection */
  15468. process_new_connection(conn);
  15469. /* Free client certificate info */
  15470. if (conn->request_info.client_cert) {
  15471. mg_free((void *)(conn->request_info.client_cert->subject));
  15472. mg_free((void *)(conn->request_info.client_cert->issuer));
  15473. mg_free((void *)(conn->request_info.client_cert->serial));
  15474. mg_free((void *)(conn->request_info.client_cert->finger));
  15475. /* Free certificate memory */
  15476. X509_free(
  15477. (X509 *)conn->request_info.client_cert->peer_cert);
  15478. conn->request_info.client_cert->peer_cert = 0;
  15479. conn->request_info.client_cert->subject = 0;
  15480. conn->request_info.client_cert->issuer = 0;
  15481. conn->request_info.client_cert->serial = 0;
  15482. conn->request_info.client_cert->finger = 0;
  15483. mg_free(conn->request_info.client_cert);
  15484. conn->request_info.client_cert = 0;
  15485. }
  15486. } else {
  15487. /* make sure the connection is cleaned up on SSL failure */
  15488. close_connection(conn);
  15489. }
  15490. #endif
  15491. } else {
  15492. /* process HTTP connection */
  15493. process_new_connection(conn);
  15494. }
  15495. DEBUG_TRACE("%s", "Connection closed");
  15496. }
  15497. pthread_setspecific(sTlsKey, NULL);
  15498. #if defined(_WIN32)
  15499. CloseHandle(tls.pthread_cond_helper_mutex);
  15500. #endif
  15501. pthread_mutex_destroy(&conn->mutex);
  15502. /* Free the request buffer. */
  15503. conn->buf_size = 0;
  15504. mg_free(conn->buf);
  15505. conn->buf = NULL;
  15506. #if defined(USE_SERVER_STATS)
  15507. conn->conn_state = 9; /* done */
  15508. #endif
  15509. DEBUG_TRACE("%s", "exiting");
  15510. }
  15511. /* Threads have different return types on Windows and Unix. */
  15512. #if defined(_WIN32)
  15513. static unsigned __stdcall worker_thread(void *thread_func_param)
  15514. {
  15515. worker_thread_run((struct mg_connection *)thread_func_param);
  15516. return 0;
  15517. }
  15518. #else
  15519. static void *
  15520. worker_thread(void *thread_func_param)
  15521. {
  15522. struct sigaction sa;
  15523. /* Ignore SIGPIPE */
  15524. memset(&sa, 0, sizeof(sa));
  15525. sa.sa_handler = SIG_IGN;
  15526. sigaction(SIGPIPE, &sa, NULL);
  15527. worker_thread_run((struct mg_connection *)thread_func_param);
  15528. return NULL;
  15529. }
  15530. #endif /* _WIN32 */
  15531. /* This is an internal function, thus all arguments are expected to be
  15532. * valid - a NULL check is not required. */
  15533. static void
  15534. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15535. {
  15536. struct socket so;
  15537. char src_addr[IP_ADDR_STR_LEN];
  15538. socklen_t len = sizeof(so.rsa);
  15539. int on = 1;
  15540. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15541. == INVALID_SOCKET) {
  15542. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15543. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15544. mg_cry_internal(fc(ctx),
  15545. "%s: %s is not allowed to connect",
  15546. __func__,
  15547. src_addr);
  15548. closesocket(so.sock);
  15549. } else {
  15550. /* Put so socket structure into the queue */
  15551. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15552. set_close_on_exec(so.sock, fc(ctx));
  15553. so.is_ssl = listener->is_ssl;
  15554. so.ssl_redir = listener->ssl_redir;
  15555. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15556. mg_cry_internal(fc(ctx),
  15557. "%s: getsockname() failed: %s",
  15558. __func__,
  15559. strerror(ERRNO));
  15560. }
  15561. /* Set TCP keep-alive. This is needed because if HTTP-level
  15562. * keep-alive
  15563. * is enabled, and client resets the connection, server won't get
  15564. * TCP FIN or RST and will keep the connection open forever. With
  15565. * TCP keep-alive, next keep-alive handshake will figure out that
  15566. * the client is down and will close the server end.
  15567. * Thanks to Igor Klopov who suggested the patch. */
  15568. if (setsockopt(so.sock,
  15569. SOL_SOCKET,
  15570. SO_KEEPALIVE,
  15571. (SOCK_OPT_TYPE)&on,
  15572. sizeof(on))
  15573. != 0) {
  15574. mg_cry_internal(
  15575. fc(ctx),
  15576. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15577. __func__,
  15578. strerror(ERRNO));
  15579. }
  15580. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15581. * to effectively fill up the underlying IP packet payload and
  15582. * reduce the overhead of sending lots of small buffers. However
  15583. * this hurts the server's throughput (ie. operations per second)
  15584. * when HTTP 1.1 persistent connections are used and the responses
  15585. * are relatively small (eg. less than 1400 bytes).
  15586. */
  15587. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15588. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15589. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15590. mg_cry_internal(
  15591. fc(ctx),
  15592. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15593. __func__,
  15594. strerror(ERRNO));
  15595. }
  15596. }
  15597. /* We are using non-blocking sockets. Thus, the
  15598. * set_sock_timeout(so.sock, timeout);
  15599. * call is no longer required. */
  15600. /* The "non blocking" property should already be
  15601. * inherited from the parent socket. Set it for
  15602. * non-compliant socket implementations. */
  15603. set_non_blocking_mode(so.sock);
  15604. so.in_use = 0;
  15605. produce_socket(ctx, &so);
  15606. }
  15607. }
  15608. static void
  15609. master_thread_run(struct mg_context *ctx)
  15610. {
  15611. struct mg_workerTLS tls;
  15612. struct mg_pollfd *pfd;
  15613. unsigned int i;
  15614. unsigned int workerthreadcount;
  15615. if (!ctx) {
  15616. return;
  15617. }
  15618. mg_set_thread_name("master");
  15619. /* Increase priority of the master thread */
  15620. #if defined(_WIN32)
  15621. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15622. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15623. int min_prio = sched_get_priority_min(SCHED_RR);
  15624. int max_prio = sched_get_priority_max(SCHED_RR);
  15625. if ((min_prio >= 0) && (max_prio >= 0)
  15626. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15627. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15628. struct sched_param sched_param = {0};
  15629. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15630. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15631. }
  15632. #endif
  15633. /* Initialize thread local storage */
  15634. #if defined(_WIN32)
  15635. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15636. #endif
  15637. tls.is_master = 1;
  15638. pthread_setspecific(sTlsKey, &tls);
  15639. if (ctx->callbacks.init_thread) {
  15640. /* Callback for the master thread (type 0) */
  15641. ctx->callbacks.init_thread(ctx, 0);
  15642. }
  15643. /* Server starts *now* */
  15644. ctx->start_time = time(NULL);
  15645. /* Start the server */
  15646. pfd = ctx->listening_socket_fds;
  15647. while (ctx->stop_flag == 0) {
  15648. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15649. pfd[i].fd = ctx->listening_sockets[i].sock;
  15650. pfd[i].events = POLLIN;
  15651. }
  15652. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15653. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15654. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15655. * successful poll, and POLLIN is defined as
  15656. * (POLLRDNORM | POLLRDBAND)
  15657. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15658. * pfd[i].revents == POLLIN. */
  15659. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15660. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15661. }
  15662. }
  15663. }
  15664. }
  15665. /* Here stop_flag is 1 - Initiate shutdown. */
  15666. DEBUG_TRACE("%s", "stopping workers");
  15667. /* Stop signal received: somebody called mg_stop. Quit. */
  15668. close_all_listening_sockets(ctx);
  15669. /* Wakeup workers that are waiting for connections to handle. */
  15670. #if defined(ALTERNATIVE_QUEUE)
  15671. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15672. event_signal(ctx->client_wait_events[i]);
  15673. }
  15674. #else
  15675. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15676. pthread_cond_broadcast(&ctx->sq_full);
  15677. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15678. #endif
  15679. /* Join all worker threads to avoid leaking threads. */
  15680. workerthreadcount = ctx->cfg_worker_threads;
  15681. for (i = 0; i < workerthreadcount; i++) {
  15682. if (ctx->worker_threadids[i] != 0) {
  15683. mg_join_thread(ctx->worker_threadids[i]);
  15684. }
  15685. }
  15686. #if defined(USE_LUA)
  15687. /* Free Lua state of lua background task */
  15688. if (ctx->lua_background_state) {
  15689. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15690. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15691. if (lua_istable(lstate, -1)) {
  15692. reg_boolean(lstate, "shutdown", 1);
  15693. lua_pop(lstate, 1);
  15694. mg_sleep(2);
  15695. }
  15696. lua_close(lstate);
  15697. ctx->lua_background_state = 0;
  15698. }
  15699. #endif
  15700. DEBUG_TRACE("%s", "exiting");
  15701. #if defined(_WIN32)
  15702. CloseHandle(tls.pthread_cond_helper_mutex);
  15703. #endif
  15704. pthread_setspecific(sTlsKey, NULL);
  15705. /* Signal mg_stop() that we're done.
  15706. * WARNING: This must be the very last thing this
  15707. * thread does, as ctx becomes invalid after this line. */
  15708. ctx->stop_flag = 2;
  15709. }
  15710. /* Threads have different return types on Windows and Unix. */
  15711. #if defined(_WIN32)
  15712. static unsigned __stdcall master_thread(void *thread_func_param)
  15713. {
  15714. master_thread_run((struct mg_context *)thread_func_param);
  15715. return 0;
  15716. }
  15717. #else
  15718. static void *
  15719. master_thread(void *thread_func_param)
  15720. {
  15721. struct sigaction sa;
  15722. /* Ignore SIGPIPE */
  15723. memset(&sa, 0, sizeof(sa));
  15724. sa.sa_handler = SIG_IGN;
  15725. sigaction(SIGPIPE, &sa, NULL);
  15726. master_thread_run((struct mg_context *)thread_func_param);
  15727. return NULL;
  15728. }
  15729. #endif /* _WIN32 */
  15730. static void
  15731. free_context(struct mg_context *ctx)
  15732. {
  15733. int i;
  15734. struct mg_handler_info *tmp_rh;
  15735. if (ctx == NULL) {
  15736. return;
  15737. }
  15738. if (ctx->callbacks.exit_context) {
  15739. ctx->callbacks.exit_context(ctx);
  15740. }
  15741. /* All threads exited, no sync is needed. Destroy thread mutex and
  15742. * condvars
  15743. */
  15744. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15745. #if defined(ALTERNATIVE_QUEUE)
  15746. mg_free(ctx->client_socks);
  15747. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15748. event_destroy(ctx->client_wait_events[i]);
  15749. }
  15750. mg_free(ctx->client_wait_events);
  15751. #else
  15752. (void)pthread_cond_destroy(&ctx->sq_empty);
  15753. (void)pthread_cond_destroy(&ctx->sq_full);
  15754. #endif
  15755. /* Destroy other context global data structures mutex */
  15756. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15757. #if defined(USE_TIMERS)
  15758. timers_exit(ctx);
  15759. #endif
  15760. /* Deallocate config parameters */
  15761. for (i = 0; i < NUM_OPTIONS; i++) {
  15762. if (ctx->dd.config[i] != NULL) {
  15763. #if defined(_MSC_VER)
  15764. #pragma warning(suppress : 6001)
  15765. #endif
  15766. mg_free(ctx->dd.config[i]);
  15767. }
  15768. }
  15769. /* Deallocate request handlers */
  15770. while (ctx->dd.handlers) {
  15771. tmp_rh = ctx->dd.handlers;
  15772. ctx->dd.handlers = tmp_rh->next;
  15773. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15774. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15775. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15776. }
  15777. mg_free(tmp_rh->uri);
  15778. mg_free(tmp_rh);
  15779. }
  15780. #if !defined(NO_SSL)
  15781. /* Deallocate SSL context */
  15782. if (ctx->dd.ssl_ctx != NULL) {
  15783. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15784. int callback_ret =
  15785. (ctx->callbacks.external_ssl_ctx == NULL)
  15786. ? 0
  15787. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15788. if (callback_ret == 0) {
  15789. SSL_CTX_free(ctx->dd.ssl_ctx);
  15790. }
  15791. /* else: ignore error and ommit SSL_CTX_free in case
  15792. * callback_ret is 1 */
  15793. }
  15794. #endif /* !NO_SSL */
  15795. /* Deallocate worker thread ID array */
  15796. if (ctx->worker_threadids != NULL) {
  15797. mg_free(ctx->worker_threadids);
  15798. }
  15799. /* Deallocate worker thread ID array */
  15800. if (ctx->worker_connections != NULL) {
  15801. mg_free(ctx->worker_connections);
  15802. }
  15803. /* deallocate system name string */
  15804. mg_free(ctx->systemName);
  15805. /* Deallocate context itself */
  15806. mg_free(ctx);
  15807. }
  15808. void
  15809. mg_stop(struct mg_context *ctx)
  15810. {
  15811. pthread_t mt;
  15812. if (!ctx) {
  15813. return;
  15814. }
  15815. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15816. * two threads is not allowed. */
  15817. mt = ctx->masterthreadid;
  15818. if (mt == 0) {
  15819. return;
  15820. }
  15821. ctx->masterthreadid = 0;
  15822. /* Set stop flag, so all threads know they have to exit. */
  15823. ctx->stop_flag = 1;
  15824. /* Wait until everything has stopped. */
  15825. while (ctx->stop_flag != 2) {
  15826. (void)mg_sleep(10);
  15827. }
  15828. mg_join_thread(mt);
  15829. free_context(ctx);
  15830. #if defined(_WIN32)
  15831. (void)WSACleanup();
  15832. #endif /* _WIN32 */
  15833. }
  15834. static void
  15835. get_system_name(char **sysName)
  15836. {
  15837. #if defined(_WIN32)
  15838. #if !defined(__SYMBIAN32__)
  15839. #if defined(_WIN32_WCE)
  15840. *sysName = mg_strdup("WinCE");
  15841. #else
  15842. char name[128];
  15843. DWORD dwVersion = 0;
  15844. DWORD dwMajorVersion = 0;
  15845. DWORD dwMinorVersion = 0;
  15846. DWORD dwBuild = 0;
  15847. BOOL wowRet, isWoW = FALSE;
  15848. #if defined(_MSC_VER)
  15849. #pragma warning(push)
  15850. /* GetVersion was declared deprecated */
  15851. #pragma warning(disable : 4996)
  15852. #endif
  15853. dwVersion = GetVersion();
  15854. #if defined(_MSC_VER)
  15855. #pragma warning(pop)
  15856. #endif
  15857. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15858. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15859. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15860. (void)dwBuild;
  15861. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15862. sprintf(name,
  15863. "Windows %u.%u%s",
  15864. (unsigned)dwMajorVersion,
  15865. (unsigned)dwMinorVersion,
  15866. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15867. *sysName = mg_strdup(name);
  15868. #endif
  15869. #else
  15870. *sysName = mg_strdup("Symbian");
  15871. #endif
  15872. #else
  15873. struct utsname name;
  15874. memset(&name, 0, sizeof(name));
  15875. uname(&name);
  15876. *sysName = mg_strdup(name.sysname);
  15877. #endif
  15878. }
  15879. struct mg_context *
  15880. mg_start(const struct mg_callbacks *callbacks,
  15881. void *user_data,
  15882. const char **options)
  15883. {
  15884. struct mg_context *ctx;
  15885. const char *name, *value, *default_value;
  15886. int idx, ok, workerthreadcount;
  15887. unsigned int i;
  15888. int itmp;
  15889. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15890. struct mg_workerTLS tls;
  15891. #if defined(_WIN32)
  15892. WSADATA data;
  15893. WSAStartup(MAKEWORD(2, 2), &data);
  15894. #endif /* _WIN32 */
  15895. /* Allocate context and initialize reasonable general case defaults. */
  15896. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15897. return NULL;
  15898. }
  15899. /* Random number generator will initialize at the first call */
  15900. ctx->dd.auth_nonce_mask =
  15901. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15902. if (mg_init_library_called == 0) {
  15903. /* Legacy INIT, if mg_start is called without mg_init_library.
  15904. * Note: This may cause a memory leak */
  15905. const char *ports_option =
  15906. config_options[LISTENING_PORTS].default_value;
  15907. if (options) {
  15908. const char **run_options = options;
  15909. const char *optname = config_options[LISTENING_PORTS].name;
  15910. /* Try to find the "listening_ports" option */
  15911. while (*run_options) {
  15912. if (!strcmp(*run_options, optname)) {
  15913. ports_option = run_options[1];
  15914. }
  15915. run_options += 2;
  15916. }
  15917. }
  15918. if (is_ssl_port_used(ports_option)) {
  15919. /* Initialize with SSL support */
  15920. mg_init_library(MG_FEATURES_TLS);
  15921. } else {
  15922. /* Initialize without SSL support */
  15923. mg_init_library(MG_FEATURES_DEFAULT);
  15924. }
  15925. }
  15926. tls.is_master = -1;
  15927. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15928. #if defined(_WIN32)
  15929. tls.pthread_cond_helper_mutex = NULL;
  15930. #endif
  15931. pthread_setspecific(sTlsKey, &tls);
  15932. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  15933. #if !defined(ALTERNATIVE_QUEUE)
  15934. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  15935. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  15936. #endif
  15937. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  15938. if (!ok) {
  15939. /* Fatal error - abort start. However, this situation should never
  15940. * occur in practice. */
  15941. mg_cry_internal(fc(ctx),
  15942. "%s",
  15943. "Cannot initialize thread synchronization objects");
  15944. mg_free(ctx);
  15945. pthread_setspecific(sTlsKey, NULL);
  15946. return NULL;
  15947. }
  15948. if (callbacks) {
  15949. ctx->callbacks = *callbacks;
  15950. exit_callback = callbacks->exit_context;
  15951. ctx->callbacks.exit_context = 0;
  15952. }
  15953. ctx->user_data = user_data;
  15954. ctx->dd.handlers = NULL;
  15955. ctx->dd.next = NULL;
  15956. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15957. ctx->dd.shared_lua_websockets = NULL;
  15958. #endif
  15959. /* Store options */
  15960. while (options && (name = *options++) != NULL) {
  15961. if ((idx = get_option_index(name)) == -1) {
  15962. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15963. free_context(ctx);
  15964. pthread_setspecific(sTlsKey, NULL);
  15965. return NULL;
  15966. } else if ((value = *options++) == NULL) {
  15967. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15968. free_context(ctx);
  15969. pthread_setspecific(sTlsKey, NULL);
  15970. return NULL;
  15971. }
  15972. if (ctx->dd.config[idx] != NULL) {
  15973. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15974. mg_free(ctx->dd.config[idx]);
  15975. }
  15976. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15977. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15978. }
  15979. /* Set default value if needed */
  15980. for (i = 0; config_options[i].name != NULL; i++) {
  15981. default_value = config_options[i].default_value;
  15982. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15983. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15984. }
  15985. }
  15986. /* Request size option */
  15987. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15988. if (itmp < 1024) {
  15989. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  15990. free_context(ctx);
  15991. pthread_setspecific(sTlsKey, NULL);
  15992. return NULL;
  15993. }
  15994. ctx->max_request_size = (unsigned)itmp;
  15995. /* Worker thread count option */
  15996. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15997. if (workerthreadcount > MAX_WORKER_THREADS) {
  15998. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  15999. free_context(ctx);
  16000. pthread_setspecific(sTlsKey, NULL);
  16001. return NULL;
  16002. }
  16003. if (workerthreadcount <= 0) {
  16004. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  16005. free_context(ctx);
  16006. pthread_setspecific(sTlsKey, NULL);
  16007. return NULL;
  16008. }
  16009. /* Document root */
  16010. #if defined(NO_FILES)
  16011. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16012. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  16013. free_context(ctx);
  16014. pthread_setspecific(sTlsKey, NULL);
  16015. return NULL;
  16016. }
  16017. #endif
  16018. get_system_name(&ctx->systemName);
  16019. #if defined(USE_LUA)
  16020. /* If a Lua background script has been configured, start it. */
  16021. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16022. char ebuf[256];
  16023. struct vec opt_vec;
  16024. struct vec eq_vec;
  16025. const char *sparams;
  16026. lua_State *state = mg_prepare_lua_context_script(
  16027. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16028. if (!state) {
  16029. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  16030. free_context(ctx);
  16031. pthread_setspecific(sTlsKey, NULL);
  16032. return NULL;
  16033. }
  16034. ctx->lua_background_state = (void *)state;
  16035. lua_newtable(state);
  16036. reg_boolean(state, "shutdown", 0);
  16037. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16038. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16039. reg_llstring(
  16040. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16041. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16042. break;
  16043. }
  16044. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16045. } else {
  16046. ctx->lua_background_state = 0;
  16047. }
  16048. #endif
  16049. /* NOTE(lsm): order is important here. SSL certificates must
  16050. * be initialized before listening ports. UID must be set last. */
  16051. if (!set_gpass_option(ctx, NULL) ||
  16052. #if !defined(NO_SSL)
  16053. !init_ssl_ctx(ctx, NULL) ||
  16054. #endif
  16055. !set_ports_option(ctx) ||
  16056. #if !defined(_WIN32)
  16057. !set_uid_option(ctx) ||
  16058. #endif
  16059. !set_acl_option(ctx)) {
  16060. free_context(ctx);
  16061. pthread_setspecific(sTlsKey, NULL);
  16062. return NULL;
  16063. }
  16064. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16065. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16066. sizeof(pthread_t),
  16067. ctx);
  16068. if (ctx->worker_threadids == NULL) {
  16069. mg_cry_internal(fc(ctx),
  16070. "%s",
  16071. "Not enough memory for worker thread ID array");
  16072. free_context(ctx);
  16073. pthread_setspecific(sTlsKey, NULL);
  16074. return NULL;
  16075. }
  16076. ctx->worker_connections =
  16077. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16078. sizeof(struct mg_connection),
  16079. ctx);
  16080. if (ctx->worker_connections == NULL) {
  16081. mg_cry_internal(fc(ctx),
  16082. "%s",
  16083. "Not enough memory for worker thread connection array");
  16084. free_context(ctx);
  16085. pthread_setspecific(sTlsKey, NULL);
  16086. return NULL;
  16087. }
  16088. #if defined(ALTERNATIVE_QUEUE)
  16089. ctx->client_wait_events =
  16090. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  16091. ctx->cfg_worker_threads,
  16092. ctx);
  16093. if (ctx->client_wait_events == NULL) {
  16094. mg_cry_internal(fc(ctx),
  16095. "%s",
  16096. "Not enough memory for worker event array");
  16097. mg_free(ctx->worker_threadids);
  16098. free_context(ctx);
  16099. pthread_setspecific(sTlsKey, NULL);
  16100. return NULL;
  16101. }
  16102. ctx->client_socks =
  16103. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  16104. ctx->cfg_worker_threads,
  16105. ctx);
  16106. if (ctx->client_socks == NULL) {
  16107. mg_cry_internal(fc(ctx),
  16108. "%s",
  16109. "Not enough memory for worker socket array");
  16110. mg_free(ctx->client_wait_events);
  16111. mg_free(ctx->worker_threadids);
  16112. free_context(ctx);
  16113. pthread_setspecific(sTlsKey, NULL);
  16114. return NULL;
  16115. }
  16116. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16117. ctx->client_wait_events[i] = event_create();
  16118. if (ctx->client_wait_events[i] == 0) {
  16119. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  16120. while (i > 0) {
  16121. i--;
  16122. event_destroy(ctx->client_wait_events[i]);
  16123. }
  16124. mg_free(ctx->client_socks);
  16125. mg_free(ctx->client_wait_events);
  16126. mg_free(ctx->worker_threadids);
  16127. free_context(ctx);
  16128. pthread_setspecific(sTlsKey, NULL);
  16129. return NULL;
  16130. }
  16131. }
  16132. #endif
  16133. #if defined(USE_TIMERS)
  16134. if (timers_init(ctx) != 0) {
  16135. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  16136. free_context(ctx);
  16137. pthread_setspecific(sTlsKey, NULL);
  16138. return NULL;
  16139. }
  16140. #endif
  16141. /* Context has been created - init user libraries */
  16142. if (ctx->callbacks.init_context) {
  16143. ctx->callbacks.init_context(ctx);
  16144. }
  16145. ctx->callbacks.exit_context = exit_callback;
  16146. ctx->context_type = CONTEXT_SERVER; /* server context */
  16147. /* Start master (listening) thread */
  16148. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16149. /* Start worker threads */
  16150. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16151. /* worker_thread sets up the other fields */
  16152. ctx->worker_connections[i].phys_ctx = ctx;
  16153. if (mg_start_thread_with_id(worker_thread,
  16154. &ctx->worker_connections[i],
  16155. &ctx->worker_threadids[i]) != 0) {
  16156. /* thread was not created */
  16157. if (i > 0) {
  16158. mg_cry_internal(fc(ctx),
  16159. "Cannot start worker thread %i: error %ld",
  16160. i + 1,
  16161. (long)ERRNO);
  16162. } else {
  16163. mg_cry_internal(fc(ctx),
  16164. "Cannot create threads: error %ld",
  16165. (long)ERRNO);
  16166. free_context(ctx);
  16167. pthread_setspecific(sTlsKey, NULL);
  16168. return NULL;
  16169. }
  16170. break;
  16171. }
  16172. }
  16173. pthread_setspecific(sTlsKey, NULL);
  16174. return ctx;
  16175. }
  16176. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16177. /* Add an additional domain to an already running web server. */
  16178. int
  16179. mg_start_domain(struct mg_context *ctx, const char **options)
  16180. {
  16181. const char *name;
  16182. const char *value;
  16183. const char *default_value;
  16184. struct mg_domain_context *new_dom;
  16185. struct mg_domain_context *dom;
  16186. int idx, i;
  16187. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  16188. return -1;
  16189. }
  16190. new_dom = (struct mg_domain_context *)
  16191. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16192. if (!new_dom) {
  16193. /* Out of memory */
  16194. return -6;
  16195. }
  16196. /* Store options - TODO: unite duplicate code */
  16197. while (options && (name = *options++) != NULL) {
  16198. if ((idx = get_option_index(name)) == -1) {
  16199. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  16200. mg_free(new_dom);
  16201. return -2;
  16202. } else if ((value = *options++) == NULL) {
  16203. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  16204. mg_free(new_dom);
  16205. return -2;
  16206. }
  16207. if (new_dom->config[idx] != NULL) {
  16208. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  16209. mg_free(new_dom->config[idx]);
  16210. }
  16211. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16212. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16213. }
  16214. /* Authentication domain is mandatory */
  16215. /* TODO: Maybe use a new option hostname? */
  16216. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16217. mg_cry_internal(fc(ctx), "%s", "authentication domain required");
  16218. mg_free(new_dom);
  16219. return -4;
  16220. }
  16221. /* Set default value if needed. Take the config value from
  16222. * ctx as a default value. */
  16223. for (i = 0; config_options[i].name != NULL; i++) {
  16224. default_value = ctx->dd.config[i];
  16225. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16226. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16227. }
  16228. }
  16229. new_dom->handlers = NULL;
  16230. new_dom->next = NULL;
  16231. new_dom->nonce_count = 0;
  16232. new_dom->auth_nonce_mask =
  16233. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16234. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16235. new_dom->shared_lua_websockets = NULL;
  16236. #endif
  16237. if (!init_ssl_ctx(ctx, new_dom)) {
  16238. /* Init SSL failed */
  16239. mg_free(new_dom);
  16240. return -3;
  16241. }
  16242. /* Add element to linked list. */
  16243. mg_lock_context(ctx);
  16244. idx = 0;
  16245. dom = &(ctx->dd);
  16246. for (;;) {
  16247. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16248. dom->config[AUTHENTICATION_DOMAIN])) {
  16249. /* Domain collision */
  16250. mg_cry_internal(fc(ctx),
  16251. "domain %s already in use",
  16252. new_dom->config[AUTHENTICATION_DOMAIN]);
  16253. mg_free(new_dom);
  16254. return -5;
  16255. }
  16256. /* Count number of domains */
  16257. idx++;
  16258. if (dom->next == NULL) {
  16259. dom->next = new_dom;
  16260. break;
  16261. }
  16262. dom = dom->next;
  16263. }
  16264. mg_unlock_context(ctx);
  16265. /* Return domain number */
  16266. return idx;
  16267. }
  16268. #endif
  16269. /* Feature check API function */
  16270. unsigned
  16271. mg_check_feature(unsigned feature)
  16272. {
  16273. static const unsigned feature_set = 0
  16274. /* Set bits for available features according to API documentation.
  16275. * This bit mask is created at compile time, according to the active
  16276. * preprocessor defines. It is a single const value at runtime. */
  16277. #if !defined(NO_FILES)
  16278. | MG_FEATURES_FILES
  16279. #endif
  16280. #if !defined(NO_SSL)
  16281. | MG_FEATURES_SSL
  16282. #endif
  16283. #if !defined(NO_CGI)
  16284. | MG_FEATURES_CGI
  16285. #endif
  16286. #if defined(USE_IPV6)
  16287. | MG_FEATURES_IPV6
  16288. #endif
  16289. #if defined(USE_WEBSOCKET)
  16290. | MG_FEATURES_WEBSOCKET
  16291. #endif
  16292. #if defined(USE_LUA)
  16293. | MG_FEATURES_LUA
  16294. #endif
  16295. #if defined(USE_DUKTAPE)
  16296. | MG_FEATURES_SSJS
  16297. #endif
  16298. #if !defined(NO_CACHING)
  16299. | MG_FEATURES_CACHE
  16300. #endif
  16301. #if defined(USE_SERVER_STATS)
  16302. | MG_FEATURES_STATS
  16303. #endif
  16304. #if defined(USE_ZLIB)
  16305. | MG_FEATURES_COMPRESSION
  16306. #endif
  16307. /* Set some extra bits not defined in the API documentation.
  16308. * These bits may change without further notice. */
  16309. #if defined(MG_LEGACY_INTERFACE)
  16310. | 0x00008000u
  16311. #endif
  16312. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16313. | 0x00004000u
  16314. #endif
  16315. #if defined(MEMORY_DEBUGGING)
  16316. | 0x00001000u
  16317. #endif
  16318. #if defined(USE_TIMERS)
  16319. | 0x00020000u
  16320. #endif
  16321. #if !defined(NO_NONCE_CHECK)
  16322. | 0x00040000u
  16323. #endif
  16324. #if !defined(NO_POPEN)
  16325. | 0x00080000u
  16326. #endif
  16327. ;
  16328. return (feature & feature_set);
  16329. }
  16330. /* strcat with additional NULL check to avoid clang scan-build warning. */
  16331. #define strcat0(a, b) \
  16332. { \
  16333. if ((a != NULL) && (b != NULL)) { \
  16334. strcat(a, b); \
  16335. } \
  16336. }
  16337. /* Get system information. It can be printed or stored by the caller.
  16338. * Return the size of available information. */
  16339. static int
  16340. mg_get_system_info_impl(char *buffer, int buflen)
  16341. {
  16342. char block[256];
  16343. int system_info_length = 0;
  16344. #if defined(_WIN32)
  16345. const char *eol = "\r\n";
  16346. #else
  16347. const char *eol = "\n";
  16348. #endif
  16349. const char *eoobj = "}";
  16350. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16351. if ((buffer == NULL) || (buflen < 1)) {
  16352. buflen = 0;
  16353. } else {
  16354. *buffer = 0;
  16355. }
  16356. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16357. system_info_length += (int)strlen(block);
  16358. if (system_info_length < buflen) {
  16359. strcat0(buffer, block);
  16360. }
  16361. /* Server version */
  16362. {
  16363. const char *version = mg_version();
  16364. mg_snprintf(NULL,
  16365. NULL,
  16366. block,
  16367. sizeof(block),
  16368. "\"version\" : \"%s\",%s",
  16369. version,
  16370. eol);
  16371. system_info_length += (int)strlen(block);
  16372. if (system_info_length < buflen) {
  16373. strcat0(buffer, block);
  16374. }
  16375. }
  16376. /* System info */
  16377. {
  16378. #if defined(_WIN32)
  16379. DWORD dwVersion = 0;
  16380. DWORD dwMajorVersion = 0;
  16381. DWORD dwMinorVersion = 0;
  16382. SYSTEM_INFO si;
  16383. GetSystemInfo(&si);
  16384. #if defined(_MSC_VER)
  16385. #pragma warning(push)
  16386. /* GetVersion was declared deprecated */
  16387. #pragma warning(disable : 4996)
  16388. #endif
  16389. dwVersion = GetVersion();
  16390. #if defined(_MSC_VER)
  16391. #pragma warning(pop)
  16392. #endif
  16393. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16394. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16395. mg_snprintf(NULL,
  16396. NULL,
  16397. block,
  16398. sizeof(block),
  16399. "\"os\" : \"Windows %u.%u\",%s",
  16400. (unsigned)dwMajorVersion,
  16401. (unsigned)dwMinorVersion,
  16402. eol);
  16403. system_info_length += (int)strlen(block);
  16404. if (system_info_length < buflen) {
  16405. strcat0(buffer, block);
  16406. }
  16407. mg_snprintf(NULL,
  16408. NULL,
  16409. block,
  16410. sizeof(block),
  16411. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  16412. (unsigned)si.wProcessorArchitecture,
  16413. (unsigned)si.dwNumberOfProcessors,
  16414. (unsigned)si.dwActiveProcessorMask,
  16415. eol);
  16416. system_info_length += (int)strlen(block);
  16417. if (system_info_length < buflen) {
  16418. strcat0(buffer, block);
  16419. }
  16420. #else
  16421. struct utsname name;
  16422. memset(&name, 0, sizeof(name));
  16423. uname(&name);
  16424. mg_snprintf(NULL,
  16425. NULL,
  16426. block,
  16427. sizeof(block),
  16428. "\"os\" : \"%s %s (%s) - %s\",%s",
  16429. name.sysname,
  16430. name.version,
  16431. name.release,
  16432. name.machine,
  16433. eol);
  16434. system_info_length += (int)strlen(block);
  16435. if (system_info_length < buflen) {
  16436. strcat0(buffer, block);
  16437. }
  16438. #endif
  16439. }
  16440. /* Features */
  16441. {
  16442. mg_snprintf(NULL,
  16443. NULL,
  16444. block,
  16445. sizeof(block),
  16446. "\"features\" : %lu,%s"
  16447. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  16448. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16449. eol,
  16450. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16451. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16452. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16453. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16454. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16455. : "",
  16456. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16457. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16458. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16459. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  16460. eol);
  16461. system_info_length += (int)strlen(block);
  16462. if (system_info_length < buflen) {
  16463. strcat0(buffer, block);
  16464. }
  16465. #if defined(USE_LUA)
  16466. mg_snprintf(NULL,
  16467. NULL,
  16468. block,
  16469. sizeof(block),
  16470. "\"lua_version\" : \"%u (%s)\",%s",
  16471. (unsigned)LUA_VERSION_NUM,
  16472. LUA_RELEASE,
  16473. eol);
  16474. system_info_length += (int)strlen(block);
  16475. if (system_info_length < buflen) {
  16476. strcat0(buffer, block);
  16477. }
  16478. #endif
  16479. #if defined(USE_DUKTAPE)
  16480. mg_snprintf(NULL,
  16481. NULL,
  16482. block,
  16483. sizeof(block),
  16484. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  16485. (unsigned)DUK_VERSION / 10000,
  16486. ((unsigned)DUK_VERSION / 100) % 100,
  16487. (unsigned)DUK_VERSION % 100,
  16488. eol);
  16489. system_info_length += (int)strlen(block);
  16490. if (system_info_length < buflen) {
  16491. strcat0(buffer, block);
  16492. }
  16493. #endif
  16494. }
  16495. /* Build date */
  16496. {
  16497. #if defined(GCC_DIAGNOSTIC)
  16498. #if GCC_VERSION >= 40900
  16499. #pragma GCC diagnostic push
  16500. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  16501. #pragma GCC diagnostic ignored "-Wdate-time"
  16502. #endif
  16503. #endif
  16504. mg_snprintf(NULL,
  16505. NULL,
  16506. block,
  16507. sizeof(block),
  16508. "\"build\" : \"%s\",%s",
  16509. __DATE__,
  16510. eol);
  16511. #if defined(GCC_DIAGNOSTIC)
  16512. #if GCC_VERSION >= 40900
  16513. #pragma GCC diagnostic pop
  16514. #endif
  16515. #endif
  16516. system_info_length += (int)strlen(block);
  16517. if (system_info_length < buflen) {
  16518. strcat0(buffer, block);
  16519. }
  16520. }
  16521. /* Compiler information */
  16522. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16523. {
  16524. #if defined(_MSC_VER)
  16525. mg_snprintf(NULL,
  16526. NULL,
  16527. block,
  16528. sizeof(block),
  16529. "\"compiler\" : \"MSC: %u (%u)\",%s",
  16530. (unsigned)_MSC_VER,
  16531. (unsigned)_MSC_FULL_VER,
  16532. eol);
  16533. system_info_length += (int)strlen(block);
  16534. if (system_info_length < buflen) {
  16535. strcat0(buffer, block);
  16536. }
  16537. #elif defined(__MINGW64__)
  16538. mg_snprintf(NULL,
  16539. NULL,
  16540. block,
  16541. sizeof(block),
  16542. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  16543. (unsigned)__MINGW64_VERSION_MAJOR,
  16544. (unsigned)__MINGW64_VERSION_MINOR,
  16545. eol);
  16546. system_info_length += (int)strlen(block);
  16547. if (system_info_length < buflen) {
  16548. strcat0(buffer, block);
  16549. }
  16550. mg_snprintf(NULL,
  16551. NULL,
  16552. block,
  16553. sizeof(block),
  16554. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16555. (unsigned)__MINGW32_MAJOR_VERSION,
  16556. (unsigned)__MINGW32_MINOR_VERSION,
  16557. eol);
  16558. system_info_length += (int)strlen(block);
  16559. if (system_info_length < buflen) {
  16560. strcat0(buffer, block);
  16561. }
  16562. #elif defined(__MINGW32__)
  16563. mg_snprintf(NULL,
  16564. NULL,
  16565. block,
  16566. sizeof(block),
  16567. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16568. (unsigned)__MINGW32_MAJOR_VERSION,
  16569. (unsigned)__MINGW32_MINOR_VERSION,
  16570. eol);
  16571. system_info_length += (int)strlen(block);
  16572. if (system_info_length < buflen) {
  16573. strcat0(buffer, block);
  16574. }
  16575. #elif defined(__clang__)
  16576. mg_snprintf(NULL,
  16577. NULL,
  16578. block,
  16579. sizeof(block),
  16580. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  16581. __clang_major__,
  16582. __clang_minor__,
  16583. __clang_patchlevel__,
  16584. __clang_version__,
  16585. eol);
  16586. system_info_length += (int)strlen(block);
  16587. if (system_info_length < buflen) {
  16588. strcat0(buffer, block);
  16589. }
  16590. #elif defined(__GNUC__)
  16591. mg_snprintf(NULL,
  16592. NULL,
  16593. block,
  16594. sizeof(block),
  16595. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  16596. (unsigned)__GNUC__,
  16597. (unsigned)__GNUC_MINOR__,
  16598. (unsigned)__GNUC_PATCHLEVEL__,
  16599. eol);
  16600. system_info_length += (int)strlen(block);
  16601. if (system_info_length < buflen) {
  16602. strcat0(buffer, block);
  16603. }
  16604. #elif defined(__INTEL_COMPILER)
  16605. mg_snprintf(NULL,
  16606. NULL,
  16607. block,
  16608. sizeof(block),
  16609. "\"compiler\" : \"Intel C/C++: %u\",%s",
  16610. (unsigned)__INTEL_COMPILER,
  16611. eol);
  16612. system_info_length += (int)strlen(block);
  16613. if (system_info_length < buflen) {
  16614. strcat0(buffer, block);
  16615. }
  16616. #elif defined(__BORLANDC__)
  16617. mg_snprintf(NULL,
  16618. NULL,
  16619. block,
  16620. sizeof(block),
  16621. "\"compiler\" : \"Borland C: 0x%x\",%s",
  16622. (unsigned)__BORLANDC__,
  16623. eol);
  16624. system_info_length += (int)strlen(block);
  16625. if (system_info_length < buflen) {
  16626. strcat0(buffer, block);
  16627. }
  16628. #elif defined(__SUNPRO_C)
  16629. mg_snprintf(NULL,
  16630. NULL,
  16631. block,
  16632. sizeof(block),
  16633. "\"compiler\" : \"Solaris: 0x%x\",%s",
  16634. (unsigned)__SUNPRO_C,
  16635. eol);
  16636. system_info_length += (int)strlen(block);
  16637. if (system_info_length < buflen) {
  16638. strcat0(buffer, block);
  16639. }
  16640. #else
  16641. mg_snprintf(NULL,
  16642. NULL,
  16643. block,
  16644. sizeof(block),
  16645. "\"compiler\" : \"other\",%s",
  16646. eol);
  16647. system_info_length += (int)strlen(block);
  16648. if (system_info_length < buflen) {
  16649. strcat0(buffer, block);
  16650. }
  16651. #endif
  16652. }
  16653. /* Determine 32/64 bit data mode.
  16654. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16655. {
  16656. mg_snprintf(NULL,
  16657. NULL,
  16658. block,
  16659. sizeof(block),
  16660. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16661. "char:%u/%u, "
  16662. "ptr:%u, size:%u, time:%u\"%s",
  16663. (unsigned)sizeof(short),
  16664. (unsigned)sizeof(int),
  16665. (unsigned)sizeof(long),
  16666. (unsigned)sizeof(long long),
  16667. (unsigned)sizeof(float),
  16668. (unsigned)sizeof(double),
  16669. (unsigned)sizeof(long double),
  16670. (unsigned)sizeof(char),
  16671. (unsigned)sizeof(wchar_t),
  16672. (unsigned)sizeof(void *),
  16673. (unsigned)sizeof(size_t),
  16674. (unsigned)sizeof(time_t),
  16675. eol);
  16676. system_info_length += (int)strlen(block);
  16677. if (system_info_length < buflen) {
  16678. strcat0(buffer, block);
  16679. }
  16680. }
  16681. /* Terminate string */
  16682. if ((buflen > 0) && buffer && buffer[0]) {
  16683. if (system_info_length < buflen) {
  16684. strcat0(buffer, eoobj);
  16685. strcat0(buffer, eol);
  16686. }
  16687. }
  16688. system_info_length += reserved_len;
  16689. return system_info_length;
  16690. }
  16691. #if defined(USE_SERVER_STATS)
  16692. /* Get context information. It can be printed or stored by the caller.
  16693. * Return the size of available information. */
  16694. static int
  16695. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  16696. {
  16697. char block[256];
  16698. int context_info_length = 0;
  16699. #if defined(_WIN32)
  16700. const char *eol = "\r\n";
  16701. #else
  16702. const char *eol = "\n";
  16703. #endif
  16704. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16705. const char *eoobj = "}";
  16706. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16707. if ((buffer == NULL) || (buflen < 1)) {
  16708. buflen = 0;
  16709. } else {
  16710. *buffer = 0;
  16711. }
  16712. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16713. context_info_length += (int)strlen(block);
  16714. if (context_info_length < buflen) {
  16715. strcat0(buffer, block);
  16716. }
  16717. if (ms) { /* <-- should be always true */
  16718. /* Memory information */
  16719. mg_snprintf(NULL,
  16720. NULL,
  16721. block,
  16722. sizeof(block),
  16723. "\"memory\" : {%s"
  16724. "\"blocks\" : %i,%s"
  16725. "\"used\" : %" INT64_FMT ",%s"
  16726. "\"maxUsed\" : %" INT64_FMT "%s"
  16727. "}%s%s",
  16728. eol,
  16729. ms->blockCount,
  16730. eol,
  16731. ms->totalMemUsed,
  16732. eol,
  16733. ms->maxMemUsed,
  16734. eol,
  16735. (ctx ? "," : ""),
  16736. eol);
  16737. context_info_length += (int)strlen(block);
  16738. if (context_info_length + reserved_len < buflen) {
  16739. strcat0(buffer, block);
  16740. }
  16741. }
  16742. if (ctx) {
  16743. /* Declare all variables at begin of the block, to comply
  16744. * with old C standards. */
  16745. char start_time_str[64] = {0};
  16746. char now_str[64] = {0};
  16747. time_t start_time = ctx->start_time;
  16748. time_t now = time(NULL);
  16749. /* Connections information */
  16750. mg_snprintf(NULL,
  16751. NULL,
  16752. block,
  16753. sizeof(block),
  16754. "\"connections\" : {%s"
  16755. "\"active\" : %i,%s"
  16756. "\"maxActive\" : %i,%s"
  16757. "\"total\" : %" INT64_FMT "%s"
  16758. "},%s",
  16759. eol,
  16760. ctx->active_connections,
  16761. eol,
  16762. ctx->max_connections,
  16763. eol,
  16764. ctx->total_connections,
  16765. eol,
  16766. eol);
  16767. context_info_length += (int)strlen(block);
  16768. if (context_info_length + reserved_len < buflen) {
  16769. strcat0(buffer, block);
  16770. }
  16771. /* Requests information */
  16772. mg_snprintf(NULL,
  16773. NULL,
  16774. block,
  16775. sizeof(block),
  16776. "\"requests\" : {%s"
  16777. "\"total\" : %" INT64_FMT "%s"
  16778. "},%s",
  16779. eol,
  16780. ctx->total_requests,
  16781. eol,
  16782. eol);
  16783. context_info_length += (int)strlen(block);
  16784. if (context_info_length + reserved_len < buflen) {
  16785. strcat0(buffer, block);
  16786. }
  16787. /* Data information */
  16788. mg_snprintf(NULL,
  16789. NULL,
  16790. block,
  16791. sizeof(block),
  16792. "\"data\" : {%s"
  16793. "\"read\" : %" INT64_FMT "%s,"
  16794. "\"written\" : %" INT64_FMT "%s"
  16795. "},%s",
  16796. eol,
  16797. ctx->total_data_read,
  16798. eol,
  16799. ctx->total_data_written,
  16800. eol,
  16801. eol);
  16802. context_info_length += (int)strlen(block);
  16803. if (context_info_length + reserved_len < buflen) {
  16804. strcat0(buffer, block);
  16805. }
  16806. /* Execution time information */
  16807. gmt_time_string(start_time_str,
  16808. sizeof(start_time_str) - 1,
  16809. &start_time);
  16810. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16811. mg_snprintf(NULL,
  16812. NULL,
  16813. block,
  16814. sizeof(block),
  16815. "\"time\" : {%s"
  16816. "\"uptime\" : %.0f,%s"
  16817. "\"start\" : \"%s\",%s"
  16818. "\"now\" : \"%s\"%s"
  16819. "}%s",
  16820. eol,
  16821. difftime(now, start_time),
  16822. eol,
  16823. start_time_str,
  16824. eol,
  16825. now_str,
  16826. eol,
  16827. eol);
  16828. context_info_length += (int)strlen(block);
  16829. if (context_info_length + reserved_len < buflen) {
  16830. strcat0(buffer, block);
  16831. }
  16832. }
  16833. /* Terminate string */
  16834. if ((buflen > 0) && buffer && buffer[0]) {
  16835. if (context_info_length < buflen) {
  16836. strcat0(buffer, eoobj);
  16837. strcat0(buffer, eol);
  16838. }
  16839. }
  16840. context_info_length += reserved_len;
  16841. return context_info_length;
  16842. }
  16843. #endif
  16844. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16845. /* Get connection information. It can be printed or stored by the caller.
  16846. * Return the size of available information. */
  16847. static int
  16848. mg_get_connection_info_impl(const struct mg_context *ctx,
  16849. int idx,
  16850. char *buffer,
  16851. int buflen)
  16852. {
  16853. const struct mg_connection *conn;
  16854. const struct mg_request_info *ri;
  16855. char block[256];
  16856. int connection_info_length = 0;
  16857. int state = 0;
  16858. const char *state_str = "unknown";
  16859. #if defined(_WIN32)
  16860. const char *eol = "\r\n";
  16861. #else
  16862. const char *eol = "\n";
  16863. #endif
  16864. const char *eoobj = "}";
  16865. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16866. if ((buffer == NULL) || (buflen < 1)) {
  16867. buflen = 0;
  16868. } else {
  16869. *buffer = 0;
  16870. }
  16871. if ((ctx == NULL) || (idx < 0)) {
  16872. /* Parameter error */
  16873. return 0;
  16874. }
  16875. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16876. /* Out of range */
  16877. return 0;
  16878. }
  16879. /* Take connection [idx]. This connection is not locked in
  16880. * any way, so some other thread might use it. */
  16881. conn = (ctx->worker_connections) + idx;
  16882. /* Initialize output string */
  16883. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16884. connection_info_length += (int)strlen(block);
  16885. if (connection_info_length < buflen) {
  16886. strcat0(buffer, block);
  16887. }
  16888. /* Init variables */
  16889. ri = &(conn->request_info);
  16890. #if defined(USE_SERVER_STATS)
  16891. state = conn->conn_state;
  16892. /* State as string */
  16893. switch (state) {
  16894. case 0:
  16895. state_str = "undefined";
  16896. break;
  16897. case 1:
  16898. state_str = "not used";
  16899. break;
  16900. case 2:
  16901. state_str = "init";
  16902. break;
  16903. case 3:
  16904. state_str = "ready";
  16905. break;
  16906. case 4:
  16907. state_str = "processing";
  16908. break;
  16909. case 5:
  16910. state_str = "processed";
  16911. break;
  16912. case 6:
  16913. state_str = "to close";
  16914. break;
  16915. case 7:
  16916. state_str = "closing";
  16917. break;
  16918. case 8:
  16919. state_str = "closed";
  16920. break;
  16921. case 9:
  16922. state_str = "done";
  16923. break;
  16924. }
  16925. #endif
  16926. /* Connection info */
  16927. if ((state >= 3) && (state < 9)) {
  16928. mg_snprintf(NULL,
  16929. NULL,
  16930. block,
  16931. sizeof(block),
  16932. "\"connection\" : {%s"
  16933. "\"remote\" : {%s"
  16934. "\"protocol\" : \"%s\",%s"
  16935. "\"addr\" : \"%s\",%s"
  16936. "\"port\" : %u%s"
  16937. "},%s"
  16938. "\"handled_requests\" : %u%s"
  16939. "},%s",
  16940. eol,
  16941. eol,
  16942. get_proto_name(conn),
  16943. eol,
  16944. ri->remote_addr,
  16945. eol,
  16946. ri->remote_port,
  16947. eol,
  16948. eol,
  16949. conn->handled_requests,
  16950. eol,
  16951. eol);
  16952. connection_info_length += (int)strlen(block);
  16953. if (connection_info_length + reserved_len < buflen) {
  16954. strcat0(buffer, block);
  16955. }
  16956. }
  16957. /* Request info */
  16958. if ((state >= 4) && (state < 6)) {
  16959. mg_snprintf(NULL,
  16960. NULL,
  16961. block,
  16962. sizeof(block),
  16963. "\"request_info\" : {%s"
  16964. "\"method\" : \"%s\",%s"
  16965. "\"uri\" : \"%s\",%s"
  16966. "\"query\" : %s%s%s%s"
  16967. "},%s",
  16968. eol,
  16969. ri->request_method,
  16970. eol,
  16971. ri->request_uri,
  16972. eol,
  16973. ri->query_string ? "\"" : "",
  16974. ri->query_string ? ri->query_string : "null",
  16975. ri->query_string ? "\"" : "",
  16976. eol,
  16977. eol);
  16978. connection_info_length += (int)strlen(block);
  16979. if (connection_info_length + reserved_len < buflen) {
  16980. strcat0(buffer, block);
  16981. }
  16982. }
  16983. /* Execution time information */
  16984. if ((state >= 2) && (state < 9)) {
  16985. char start_time_str[64] = {0};
  16986. char now_str[64] = {0};
  16987. time_t start_time = conn->conn_birth_time;
  16988. time_t now = time(NULL);
  16989. gmt_time_string(start_time_str,
  16990. sizeof(start_time_str) - 1,
  16991. &start_time);
  16992. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16993. mg_snprintf(NULL,
  16994. NULL,
  16995. block,
  16996. sizeof(block),
  16997. "\"time\" : {%s"
  16998. "\"uptime\" : %.0f,%s"
  16999. "\"start\" : \"%s\",%s"
  17000. "\"now\" : \"%s\"%s"
  17001. "},%s",
  17002. eol,
  17003. difftime(now, start_time),
  17004. eol,
  17005. start_time_str,
  17006. eol,
  17007. now_str,
  17008. eol,
  17009. eol);
  17010. connection_info_length += (int)strlen(block);
  17011. if (connection_info_length + reserved_len < buflen) {
  17012. strcat0(buffer, block);
  17013. }
  17014. }
  17015. /* Remote user name */
  17016. if ((ri->remote_user) && (state < 9)) {
  17017. mg_snprintf(NULL,
  17018. NULL,
  17019. block,
  17020. sizeof(block),
  17021. "\"user\" : {%s"
  17022. "\"name\" : \"%s\",%s"
  17023. "},%s",
  17024. eol,
  17025. ri->remote_user,
  17026. eol,
  17027. eol);
  17028. connection_info_length += (int)strlen(block);
  17029. if (connection_info_length + reserved_len < buflen) {
  17030. strcat0(buffer, block);
  17031. }
  17032. }
  17033. /* Data block */
  17034. if (state >= 3) {
  17035. mg_snprintf(NULL,
  17036. NULL,
  17037. block,
  17038. sizeof(block),
  17039. "\"data\" : {%s"
  17040. "\"read\" : %" INT64_FMT ",%s"
  17041. "\"written\" : %" INT64_FMT "%s"
  17042. "},%s",
  17043. eol,
  17044. conn->consumed_content,
  17045. eol,
  17046. conn->num_bytes_sent,
  17047. eol,
  17048. eol);
  17049. connection_info_length += (int)strlen(block);
  17050. if (connection_info_length + reserved_len < buflen) {
  17051. strcat0(buffer, block);
  17052. }
  17053. }
  17054. /* State */
  17055. mg_snprintf(NULL,
  17056. NULL,
  17057. block,
  17058. sizeof(block),
  17059. "\"state\" : \"%s\"%s",
  17060. state_str,
  17061. eol);
  17062. connection_info_length += (int)strlen(block);
  17063. if (connection_info_length + reserved_len < buflen) {
  17064. strcat0(buffer, block);
  17065. }
  17066. /* Terminate string */
  17067. if ((buflen > 0) && buffer && buffer[0]) {
  17068. if (connection_info_length < buflen) {
  17069. strcat0(buffer, eoobj);
  17070. strcat0(buffer, eol);
  17071. }
  17072. }
  17073. connection_info_length += reserved_len;
  17074. return connection_info_length;
  17075. }
  17076. #endif
  17077. /* Get system information. It can be printed or stored by the caller.
  17078. * Return the size of available information. */
  17079. int
  17080. mg_get_system_info(char *buffer, int buflen)
  17081. {
  17082. if ((buffer == NULL) || (buflen < 1)) {
  17083. return mg_get_system_info_impl(NULL, 0);
  17084. } else {
  17085. /* Reset buffer, so we can always use strcat. */
  17086. buffer[0] = 0;
  17087. return mg_get_system_info_impl(buffer, buflen);
  17088. }
  17089. }
  17090. /* Get context information. It can be printed or stored by the caller.
  17091. * Return the size of available information. */
  17092. int
  17093. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  17094. {
  17095. #if defined(USE_SERVER_STATS)
  17096. if ((buffer == NULL) || (buflen < 1)) {
  17097. return mg_get_context_info_impl(ctx, NULL, 0);
  17098. } else {
  17099. /* Reset buffer, so we can always use strcat. */
  17100. buffer[0] = 0;
  17101. return mg_get_context_info_impl(ctx, buffer, buflen);
  17102. }
  17103. #else
  17104. (void)ctx;
  17105. if ((buffer != NULL) && (buflen > 0)) {
  17106. buffer[0] = 0;
  17107. }
  17108. return 0;
  17109. #endif
  17110. }
  17111. #if defined(MG_EXPERIMENTAL_INTERFACES)
  17112. int
  17113. mg_get_connection_info(const struct mg_context *ctx,
  17114. int idx,
  17115. char *buffer,
  17116. int buflen)
  17117. {
  17118. if ((buffer == NULL) || (buflen < 1)) {
  17119. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  17120. } else {
  17121. /* Reset buffer, so we can always use strcat. */
  17122. buffer[0] = 0;
  17123. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  17124. }
  17125. }
  17126. #endif
  17127. /* Initialize this library. This function does not need to be thread safe.
  17128. */
  17129. unsigned
  17130. mg_init_library(unsigned features)
  17131. {
  17132. #if !defined(NO_SSL)
  17133. char ebuf[128];
  17134. #endif
  17135. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17136. unsigned features_inited = features_to_init;
  17137. if (mg_init_library_called <= 0) {
  17138. /* Not initialized yet */
  17139. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17140. return 0;
  17141. }
  17142. }
  17143. mg_global_lock();
  17144. if (mg_init_library_called <= 0) {
  17145. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17146. /* Fatal error - abort start. However, this situation should
  17147. * never occur in practice. */
  17148. mg_global_unlock();
  17149. return 0;
  17150. }
  17151. #if defined(_WIN32)
  17152. InitializeCriticalSection(&global_log_file_lock);
  17153. #endif
  17154. #if !defined(_WIN32)
  17155. pthread_mutexattr_init(&pthread_mutex_attr);
  17156. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17157. #endif
  17158. #if defined(USE_LUA)
  17159. lua_init_optional_libraries();
  17160. #endif
  17161. }
  17162. mg_global_unlock();
  17163. #if !defined(NO_SSL)
  17164. if (features_to_init & MG_FEATURES_SSL) {
  17165. if (!mg_ssl_initialized) {
  17166. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17167. mg_ssl_initialized = 1;
  17168. } else {
  17169. (void)ebuf;
  17170. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17171. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17172. }
  17173. } else {
  17174. /* ssl already initialized */
  17175. }
  17176. }
  17177. #endif
  17178. /* Start WinSock for Windows */
  17179. mg_global_lock();
  17180. if (mg_init_library_called <= 0) {
  17181. #if defined(_WIN32)
  17182. WSADATA data;
  17183. WSAStartup(MAKEWORD(2, 2), &data);
  17184. #endif /* _WIN32 */
  17185. mg_init_library_called = 1;
  17186. } else {
  17187. mg_init_library_called++;
  17188. }
  17189. mg_global_unlock();
  17190. return features_inited;
  17191. }
  17192. /* Un-initialize this library. */
  17193. unsigned
  17194. mg_exit_library(void)
  17195. {
  17196. if (mg_init_library_called <= 0) {
  17197. return 0;
  17198. }
  17199. mg_global_lock();
  17200. mg_init_library_called--;
  17201. if (mg_init_library_called == 0) {
  17202. #if defined(_WIN32)
  17203. (void)WSACleanup();
  17204. #endif /* _WIN32 */
  17205. #if !defined(NO_SSL)
  17206. if (mg_ssl_initialized) {
  17207. uninitialize_ssl();
  17208. mg_ssl_initialized = 0;
  17209. }
  17210. #endif
  17211. #if defined(_WIN32)
  17212. (void)DeleteCriticalSection(&global_log_file_lock);
  17213. #endif /* _WIN32 */
  17214. #if !defined(_WIN32)
  17215. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17216. #endif
  17217. (void)pthread_key_delete(sTlsKey);
  17218. #if defined(USE_LUA)
  17219. lua_exit_optional_libraries();
  17220. #endif
  17221. mg_global_unlock();
  17222. (void)pthread_mutex_destroy(&global_lock_mutex);
  17223. return 1;
  17224. }
  17225. mg_global_unlock();
  17226. return 1;
  17227. }
  17228. /* End of civetweb.c */