civetweb.c 527 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756
  1. /* Copyright (c) 2013-2018 the Civetweb developers
  2. * Copyright (c) 2004-2013 Sergey Lyubka
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. #if defined(__GNUC__) || defined(__MINGW32__)
  23. #define GCC_VERSION \
  24. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  25. #if GCC_VERSION >= 40500
  26. /* gcc diagnostic pragmas available */
  27. #define GCC_DIAGNOSTIC
  28. #endif
  29. #endif
  30. #if defined(GCC_DIAGNOSTIC)
  31. /* Disable unused macros warnings - not all defines are required
  32. * for all systems and all compilers. */
  33. #pragma GCC diagnostic ignored "-Wunused-macros"
  34. /* A padding warning is just plain useless */
  35. #pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  38. /* We must set some flags for the headers we include. These flags
  39. * are reserved ids according to C99, so we need to disable a
  40. * warning for that. */
  41. #pragma GCC diagnostic push
  42. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  43. #endif
  44. #if defined(_WIN32)
  45. #if !defined(_CRT_SECURE_NO_WARNINGS)
  46. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  47. #endif
  48. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  49. #define _WIN32_WINNT 0x0501
  50. #endif
  51. #else
  52. #if !defined(_GNU_SOURCE)
  53. #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */
  54. #endif
  55. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  56. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  57. #endif
  58. #if defined(__LSB_VERSION__)
  59. #define NEED_TIMEGM
  60. #define NO_THREAD_NAME
  61. #endif
  62. #if !defined(_LARGEFILE_SOURCE)
  63. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  64. #endif
  65. #if !defined(_FILE_OFFSET_BITS)
  66. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  67. #endif
  68. #if !defined(__STDC_FORMAT_MACROS)
  69. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  70. #endif
  71. #if !defined(__STDC_LIMIT_MACROS)
  72. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  73. #endif
  74. #if !defined(_DARWIN_UNLIMITED_SELECT)
  75. #define _DARWIN_UNLIMITED_SELECT
  76. #endif
  77. #if defined(__sun)
  78. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  79. #define __inline inline /* not recognized on older compiler versions */
  80. #endif
  81. #endif
  82. #if defined(__clang__)
  83. /* Enable reserved-id-macro warning again. */
  84. #pragma GCC diagnostic pop
  85. #endif
  86. #if defined(USE_LUA)
  87. #define USE_TIMERS
  88. #endif
  89. #if defined(_MSC_VER)
  90. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  91. #pragma warning(disable : 4306)
  92. /* conditional expression is constant: introduced by FD_SET(..) */
  93. #pragma warning(disable : 4127)
  94. /* non-constant aggregate initializer: issued due to missing C99 support */
  95. #pragma warning(disable : 4204)
  96. /* padding added after data member */
  97. #pragma warning(disable : 4820)
  98. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  99. #pragma warning(disable : 4668)
  100. /* no function prototype given: converting '()' to '(void)' */
  101. #pragma warning(disable : 4255)
  102. /* function has been selected for automatic inline expansion */
  103. #pragma warning(disable : 4711)
  104. #endif
  105. /* This code uses static_assert to check some conditions.
  106. * Unfortunately some compilers still do not support it, so we have a
  107. * replacement function here. */
  108. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  109. #define mg_static_assert _Static_assert
  110. #elif defined(__cplusplus) && __cplusplus >= 201103L
  111. #define mg_static_assert static_assert
  112. #else
  113. char static_assert_replacement[1];
  114. #define mg_static_assert(cond, txt) \
  115. extern char static_assert_replacement[(cond) ? 1 : -1]
  116. #endif
  117. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  118. "int data type size check");
  119. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  120. "pointer data type size check");
  121. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  122. /* Alternative queue is well tested and should be the new default */
  123. #if defined(NO_ALTERNATIVE_QUEUE)
  124. #if defined(ALTERNATIVE_QUEUE)
  125. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  126. #endif
  127. #else
  128. #define ALTERNATIVE_QUEUE
  129. #endif
  130. #if defined(NO_FILESYSTEMS) && !defined(NO_FILES)
  131. #error "Inconsistent build flags, NO_FILESYSTEMS requires NO_FILES"
  132. #endif
  133. /* DTL -- including winsock2.h works better if lean and mean */
  134. #if !defined(WIN32_LEAN_AND_MEAN)
  135. #define WIN32_LEAN_AND_MEAN
  136. #endif
  137. #if defined(__SYMBIAN32__)
  138. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  139. * Symbian is no longer maintained since 2014-01-01.
  140. * Recent versions of CivetWeb are no longer tested for Symbian.
  141. * It makes no sense, to support an abandoned operating system.
  142. */
  143. #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian."
  144. #define NO_SSL /* SSL is not supported */
  145. #define NO_CGI /* CGI is not supported */
  146. #define PATH_MAX FILENAME_MAX
  147. #endif /* __SYMBIAN32__ */
  148. #if !defined(CIVETWEB_HEADER_INCLUDED)
  149. /* Include the header file here, so the CivetWeb interface is defined for the
  150. * entire implementation, including the following forward definitions. */
  151. #include "civetweb.h"
  152. #endif
  153. #if !defined(DEBUG_TRACE)
  154. #if defined(DEBUG)
  155. static void DEBUG_TRACE_FUNC(const char *func,
  156. unsigned line,
  157. PRINTF_FORMAT_STRING(const char *fmt),
  158. ...) PRINTF_ARGS(3, 4);
  159. #define DEBUG_TRACE(fmt, ...) \
  160. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  161. #define NEED_DEBUG_TRACE_FUNC
  162. #else
  163. #define DEBUG_TRACE(fmt, ...) \
  164. do { \
  165. } while (0)
  166. #endif /* DEBUG */
  167. #endif /* DEBUG_TRACE */
  168. #if !defined(DEBUG_ASSERT)
  169. #if defined(DEBUG)
  170. #define DEBUG_ASSERT(cond) \
  171. do { \
  172. if (!(cond)) { \
  173. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  174. exit(2); /* Exit with error */ \
  175. } \
  176. } while (0)
  177. #else
  178. #define DEBUG_ASSERT(cond)
  179. #endif /* DEBUG */
  180. #endif
  181. #if defined(__GNUC__) && defined(GCC_INSTRUMENTATION)
  182. void __cyg_profile_func_enter(void *this_fn, void *call_site)
  183. __attribute__((no_instrument_function));
  184. void __cyg_profile_func_exit(void *this_fn, void *call_site)
  185. __attribute__((no_instrument_function));
  186. void
  187. __cyg_profile_func_enter(void *this_fn, void *call_site)
  188. {
  189. if ((void *)this_fn != (void *)printf) {
  190. printf("E %p %p\n", this_fn, call_site);
  191. }
  192. }
  193. void
  194. __cyg_profile_func_exit(void *this_fn, void *call_site)
  195. {
  196. if ((void *)this_fn != (void *)printf) {
  197. printf("X %p %p\n", this_fn, call_site);
  198. }
  199. }
  200. #endif
  201. #if !defined(IGNORE_UNUSED_RESULT)
  202. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  203. #endif
  204. #if defined(__GNUC__) || defined(__MINGW32__)
  205. /* GCC unused function attribute seems fundamentally broken.
  206. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  207. * OR UNUSED" for individual functions failed.
  208. * Either the compiler creates an "unused-function" warning if a
  209. * function is not marked with __attribute__((unused)).
  210. * On the other hand, if the function is marked with this attribute,
  211. * but is used, the compiler raises a completely idiotic
  212. * "used-but-marked-unused" warning - and
  213. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  214. * raises error: unknown option after "#pragma GCC diagnostic".
  215. * Disable this warning completely, until the GCC guys sober up
  216. * again.
  217. */
  218. #pragma GCC diagnostic ignored "-Wunused-function"
  219. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  220. #else
  221. #define FUNCTION_MAY_BE_UNUSED
  222. #endif
  223. /* Some ANSI #includes are not available on Windows CE */
  224. #if !defined(_WIN32_WCE)
  225. #include <errno.h>
  226. #include <fcntl.h>
  227. #include <signal.h>
  228. #include <sys/stat.h>
  229. #include <sys/types.h>
  230. #endif /* !_WIN32_WCE */
  231. #if defined(__clang__)
  232. /* When using -Weverything, clang does not accept it's own headers
  233. * in a release build configuration. Disable what is too much in
  234. * -Weverything. */
  235. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  236. #endif
  237. #if defined(__GNUC__) || defined(__MINGW32__)
  238. /* Who on earth came to the conclusion, using __DATE__ should rise
  239. * an "expansion of date or time macro is not reproducible"
  240. * warning. That's exactly what was intended by using this macro.
  241. * Just disable this nonsense warning. */
  242. /* And disabling them does not work either:
  243. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  244. * #pragma clang diagnostic ignored "-Wdate-time"
  245. * So we just have to disable ALL warnings for some lines
  246. * of code.
  247. * This seems to be a known GCC bug, not resolved since 2012:
  248. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  249. */
  250. #endif
  251. #if defined(__MACH__) /* Apple OSX section */
  252. #if defined(__clang__)
  253. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  254. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  255. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  256. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  257. #endif
  258. #endif
  259. #define CLOCK_MONOTONIC (1)
  260. #define CLOCK_REALTIME (2)
  261. #include <mach/clock.h>
  262. #include <mach/mach.h>
  263. #include <mach/mach_time.h>
  264. #include <sys/errno.h>
  265. #include <sys/time.h>
  266. /* clock_gettime is not implemented on OSX prior to 10.12 */
  267. static int
  268. _civet_clock_gettime(int clk_id, struct timespec *t)
  269. {
  270. memset(t, 0, sizeof(*t));
  271. if (clk_id == CLOCK_REALTIME) {
  272. struct timeval now;
  273. int rv = gettimeofday(&now, NULL);
  274. if (rv) {
  275. return rv;
  276. }
  277. t->tv_sec = now.tv_sec;
  278. t->tv_nsec = now.tv_usec * 1000;
  279. return 0;
  280. } else if (clk_id == CLOCK_MONOTONIC) {
  281. static uint64_t clock_start_time = 0;
  282. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  283. uint64_t now = mach_absolute_time();
  284. if (clock_start_time == 0) {
  285. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  286. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  287. /* appease "unused variable" warning for release builds */
  288. (void)mach_status;
  289. clock_start_time = now;
  290. }
  291. now = (uint64_t)((double)(now - clock_start_time)
  292. * (double)timebase_ifo.numer
  293. / (double)timebase_ifo.denom);
  294. t->tv_sec = now / 1000000000;
  295. t->tv_nsec = now % 1000000000;
  296. return 0;
  297. }
  298. return -1; /* EINVAL - Clock ID is unknown */
  299. }
  300. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  301. #if defined(__CLOCK_AVAILABILITY)
  302. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  303. * declared but it may be NULL at runtime. So we need to check before using
  304. * it. */
  305. static int
  306. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  307. {
  308. if (clock_gettime) {
  309. return clock_gettime(clk_id, t);
  310. }
  311. return _civet_clock_gettime(clk_id, t);
  312. }
  313. #define clock_gettime _civet_safe_clock_gettime
  314. #else
  315. #define clock_gettime _civet_clock_gettime
  316. #endif
  317. #endif
  318. #include <ctype.h>
  319. #include <limits.h>
  320. #include <stdarg.h>
  321. #include <stddef.h>
  322. #include <stdint.h>
  323. #include <stdio.h>
  324. #include <stdlib.h>
  325. #include <string.h>
  326. #include <time.h>
  327. /********************************************************************/
  328. /* CivetWeb configuration defines */
  329. /********************************************************************/
  330. /* Maximum number of threads that can be configured.
  331. * The number of threads actually created depends on the "num_threads"
  332. * configuration parameter, but this is the upper limit. */
  333. #if !defined(MAX_WORKER_THREADS)
  334. #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */
  335. #endif
  336. /* Timeout interval for select/poll calls.
  337. * The timeouts depend on "*_timeout_ms" configuration values, but long
  338. * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM.
  339. * This reduces the time required to stop the server. */
  340. #if !defined(SOCKET_TIMEOUT_QUANTUM)
  341. #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */
  342. #endif
  343. /* Do not try to compress files smaller than this limit. */
  344. #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT)
  345. #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */
  346. #endif
  347. #if !defined(PASSWORDS_FILE_NAME)
  348. #define PASSWORDS_FILE_NAME ".htpasswd"
  349. #endif
  350. /* Initial buffer size for all CGI environment variables. In case there is
  351. * not enough space, another block is allocated. */
  352. #if !defined(CGI_ENVIRONMENT_SIZE)
  353. #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */
  354. #endif
  355. /* Maximum number of environment variables. */
  356. #if !defined(MAX_CGI_ENVIR_VARS)
  357. #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */
  358. #endif
  359. /* General purpose buffer size. */
  360. #if !defined(MG_BUF_LEN) /* in bytes */
  361. #define MG_BUF_LEN (1024 * 8)
  362. #endif
  363. /* Size of the accepted socket queue (in case the old queue implementation
  364. * is used). */
  365. #if !defined(MGSQLEN)
  366. #define MGSQLEN (20) /* count */
  367. #endif
  368. /********************************************************************/
  369. /* Helper makros */
  370. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  371. /* Standard defines */
  372. #if !defined(INT64_MAX)
  373. #define INT64_MAX (9223372036854775807)
  374. #endif
  375. #define SHUTDOWN_RD (0)
  376. #define SHUTDOWN_WR (1)
  377. #define SHUTDOWN_BOTH (2)
  378. mg_static_assert(MAX_WORKER_THREADS >= 1,
  379. "worker threads must be a positive number");
  380. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  381. "size_t data type size check");
  382. #if defined(_WIN32) /* WINDOWS include block */
  383. #include <windows.h>
  384. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  385. #include <ws2tcpip.h>
  386. typedef const char *SOCK_OPT_TYPE;
  387. #if !defined(PATH_MAX)
  388. #define W_PATH_MAX (MAX_PATH)
  389. /* at most three UTF-8 chars per wchar_t */
  390. #define PATH_MAX (W_PATH_MAX * 3)
  391. #else
  392. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  393. #endif
  394. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  395. #if !defined(_IN_PORT_T)
  396. #if !defined(in_port_t)
  397. #define in_port_t u_short
  398. #endif
  399. #endif
  400. #if !defined(_WIN32_WCE)
  401. #include <direct.h>
  402. #include <io.h>
  403. #include <process.h>
  404. #else /* _WIN32_WCE */
  405. #define NO_CGI /* WinCE has no pipes */
  406. #define NO_POPEN /* WinCE has no popen */
  407. typedef long off_t;
  408. #define errno ((int)(GetLastError()))
  409. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  410. #endif /* _WIN32_WCE */
  411. #define MAKEUQUAD(lo, hi) \
  412. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  413. #define RATE_DIFF (10000000) /* 100 nsecs */
  414. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  415. #define SYS2UNIX_TIME(lo, hi) \
  416. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  417. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  418. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  419. * Also use _strtoui64 on modern M$ compilers */
  420. #if defined(_MSC_VER)
  421. #if (_MSC_VER < 1300)
  422. #define STRX(x) #x
  423. #define STR(x) STRX(x)
  424. #define __func__ __FILE__ ":" STR(__LINE__)
  425. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  426. #define strtoll(x, y, z) (_atoi64(x))
  427. #else
  428. #define __func__ __FUNCTION__
  429. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  430. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  431. #endif
  432. #endif /* _MSC_VER */
  433. #define ERRNO ((int)(GetLastError()))
  434. #define NO_SOCKLEN_T
  435. #if defined(_WIN64) || defined(__MINGW64__)
  436. #if !defined(SSL_LIB)
  437. #define SSL_LIB "ssleay64.dll"
  438. #endif
  439. #if !defined(CRYPTO_LIB)
  440. #define CRYPTO_LIB "libeay64.dll"
  441. #endif
  442. #else
  443. #if !defined(SSL_LIB)
  444. #define SSL_LIB "ssleay32.dll"
  445. #endif
  446. #if !defined(CRYPTO_LIB)
  447. #define CRYPTO_LIB "libeay32.dll"
  448. #endif
  449. #endif
  450. #define O_NONBLOCK (0)
  451. #if !defined(W_OK)
  452. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  453. #endif
  454. #define _POSIX_
  455. #define INT64_FMT "I64d"
  456. #define UINT64_FMT "I64u"
  457. #define WINCDECL __cdecl
  458. #define vsnprintf_impl _vsnprintf
  459. #define access _access
  460. #define mg_sleep(x) (Sleep(x))
  461. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  462. #if !defined(popen)
  463. #define popen(x, y) (_popen(x, y))
  464. #endif
  465. #if !defined(pclose)
  466. #define pclose(x) (_pclose(x))
  467. #endif
  468. #define close(x) (_close(x))
  469. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  470. #define RTLD_LAZY (0)
  471. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  472. #define fdopen(x, y) (_fdopen((x), (y)))
  473. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  474. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  475. #define flockfile(x) ((void)pthread_mutex_lock(&global_log_file_lock))
  476. #define funlockfile(x) ((void)pthread_mutex_unlock(&global_log_file_lock))
  477. #define sleep(x) (Sleep((x)*1000))
  478. #define rmdir(x) (_rmdir(x))
  479. #if defined(_WIN64) || !defined(__MINGW32__)
  480. /* Only MinGW 32 bit is missing this function */
  481. #define timegm(x) (_mkgmtime(x))
  482. #else
  483. time_t timegm(struct tm *tm);
  484. #define NEED_TIMEGM
  485. #endif
  486. #if !defined(fileno)
  487. #define fileno(x) (_fileno(x))
  488. #endif /* !fileno MINGW #defines fileno */
  489. typedef struct {
  490. CRITICAL_SECTION sec; /* Immovable */
  491. } pthread_mutex_t;
  492. typedef DWORD pthread_key_t;
  493. typedef HANDLE pthread_t;
  494. typedef struct {
  495. pthread_mutex_t threadIdSec;
  496. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  497. } pthread_cond_t;
  498. #if !defined(__clockid_t_defined)
  499. typedef DWORD clockid_t;
  500. #endif
  501. #if !defined(CLOCK_MONOTONIC)
  502. #define CLOCK_MONOTONIC (1)
  503. #endif
  504. #if !defined(CLOCK_REALTIME)
  505. #define CLOCK_REALTIME (2)
  506. #endif
  507. #if !defined(CLOCK_THREAD)
  508. #define CLOCK_THREAD (3)
  509. #endif
  510. #if !defined(CLOCK_PROCESS)
  511. #define CLOCK_PROCESS (4)
  512. #endif
  513. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  514. #define _TIMESPEC_DEFINED
  515. #endif
  516. #if !defined(_TIMESPEC_DEFINED)
  517. struct timespec {
  518. time_t tv_sec; /* seconds */
  519. long tv_nsec; /* nanoseconds */
  520. };
  521. #endif
  522. #if !defined(WIN_PTHREADS_TIME_H)
  523. #define MUST_IMPLEMENT_CLOCK_GETTIME
  524. #endif
  525. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  526. #define clock_gettime mg_clock_gettime
  527. static int
  528. clock_gettime(clockid_t clk_id, struct timespec *tp)
  529. {
  530. FILETIME ft;
  531. ULARGE_INTEGER li, li2;
  532. BOOL ok = FALSE;
  533. double d;
  534. static double perfcnt_per_sec = 0.0;
  535. static BOOL initialized = FALSE;
  536. if (!initialized) {
  537. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  538. perfcnt_per_sec = 1.0 / li.QuadPart;
  539. initialized = TRUE;
  540. }
  541. if (tp) {
  542. memset(tp, 0, sizeof(*tp));
  543. if (clk_id == CLOCK_REALTIME) {
  544. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  545. GetSystemTimeAsFileTime(&ft);
  546. li.LowPart = ft.dwLowDateTime;
  547. li.HighPart = ft.dwHighDateTime;
  548. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  549. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  550. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  551. ok = TRUE;
  552. /* END: CLOCK_REALTIME */
  553. } else if (clk_id == CLOCK_MONOTONIC) {
  554. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  555. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  556. d = li.QuadPart * perfcnt_per_sec;
  557. tp->tv_sec = (time_t)d;
  558. d -= (double)tp->tv_sec;
  559. tp->tv_nsec = (long)(d * 1.0E9);
  560. ok = TRUE;
  561. /* END: CLOCK_MONOTONIC */
  562. } else if (clk_id == CLOCK_THREAD) {
  563. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  564. FILETIME t_create, t_exit, t_kernel, t_user;
  565. if (GetThreadTimes(GetCurrentThread(),
  566. &t_create,
  567. &t_exit,
  568. &t_kernel,
  569. &t_user)) {
  570. li.LowPart = t_user.dwLowDateTime;
  571. li.HighPart = t_user.dwHighDateTime;
  572. li2.LowPart = t_kernel.dwLowDateTime;
  573. li2.HighPart = t_kernel.dwHighDateTime;
  574. li.QuadPart += li2.QuadPart;
  575. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  576. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  577. ok = TRUE;
  578. }
  579. /* END: CLOCK_THREAD */
  580. } else if (clk_id == CLOCK_PROCESS) {
  581. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  582. FILETIME t_create, t_exit, t_kernel, t_user;
  583. if (GetProcessTimes(GetCurrentProcess(),
  584. &t_create,
  585. &t_exit,
  586. &t_kernel,
  587. &t_user)) {
  588. li.LowPart = t_user.dwLowDateTime;
  589. li.HighPart = t_user.dwHighDateTime;
  590. li2.LowPart = t_kernel.dwLowDateTime;
  591. li2.HighPart = t_kernel.dwHighDateTime;
  592. li.QuadPart += li2.QuadPart;
  593. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  594. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  595. ok = TRUE;
  596. }
  597. /* END: CLOCK_PROCESS */
  598. } else {
  599. /* BEGIN: unknown clock */
  600. /* ok = FALSE; already set by init */
  601. /* END: unknown clock */
  602. }
  603. }
  604. return ok ? 0 : -1;
  605. }
  606. #endif
  607. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  608. static int pthread_mutex_lock(pthread_mutex_t *);
  609. static int pthread_mutex_unlock(pthread_mutex_t *);
  610. static void path_to_unicode(const struct mg_connection *conn,
  611. const char *path,
  612. wchar_t *wbuf,
  613. size_t wbuf_len);
  614. /* All file operations need to be rewritten to solve #246. */
  615. struct mg_file;
  616. static const char *
  617. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  618. /* POSIX dirent interface */
  619. struct dirent {
  620. char d_name[PATH_MAX];
  621. };
  622. typedef struct DIR {
  623. HANDLE handle;
  624. WIN32_FIND_DATAW info;
  625. struct dirent result;
  626. } DIR;
  627. #if defined(HAVE_POLL)
  628. #define mg_pollfd pollfd
  629. #else
  630. struct mg_pollfd {
  631. SOCKET fd;
  632. short events;
  633. short revents;
  634. };
  635. #endif
  636. /* Mark required libraries */
  637. #if defined(_MSC_VER)
  638. #pragma comment(lib, "Ws2_32.lib")
  639. #endif
  640. #else /* defined(_WIN32) - WINDOWS vs UNIX include block */
  641. #include <arpa/inet.h>
  642. #include <inttypes.h>
  643. #include <netdb.h>
  644. #include <netinet/in.h>
  645. #include <netinet/tcp.h>
  646. #include <stdint.h>
  647. #include <sys/poll.h>
  648. #include <sys/socket.h>
  649. #include <sys/time.h>
  650. #include <sys/utsname.h>
  651. #include <sys/wait.h>
  652. typedef const void *SOCK_OPT_TYPE;
  653. #if defined(ANDROID)
  654. typedef unsigned short int in_port_t;
  655. #endif
  656. #include <dirent.h>
  657. #include <grp.h>
  658. #include <pwd.h>
  659. #include <unistd.h>
  660. #define vsnprintf_impl vsnprintf
  661. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  662. #include <dlfcn.h>
  663. #endif
  664. #include <pthread.h>
  665. #if defined(__MACH__)
  666. #define SSL_LIB "libssl.dylib"
  667. #define CRYPTO_LIB "libcrypto.dylib"
  668. #else
  669. #if !defined(SSL_LIB)
  670. #define SSL_LIB "libssl.so"
  671. #endif
  672. #if !defined(CRYPTO_LIB)
  673. #define CRYPTO_LIB "libcrypto.so"
  674. #endif
  675. #endif
  676. #if !defined(O_BINARY)
  677. #define O_BINARY (0)
  678. #endif /* O_BINARY */
  679. #define closesocket(a) (close(a))
  680. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  681. #define mg_remove(conn, x) (remove(x))
  682. #define mg_sleep(x) (usleep((x)*1000))
  683. #define mg_opendir(conn, x) (opendir(x))
  684. #define mg_closedir(x) (closedir(x))
  685. #define mg_readdir(x) (readdir(x))
  686. #define ERRNO (errno)
  687. #define INVALID_SOCKET (-1)
  688. #define INT64_FMT PRId64
  689. #define UINT64_FMT PRIu64
  690. typedef int SOCKET;
  691. #define WINCDECL
  692. #if defined(__hpux)
  693. /* HPUX 11 does not have monotonic, fall back to realtime */
  694. #if !defined(CLOCK_MONOTONIC)
  695. #define CLOCK_MONOTONIC CLOCK_REALTIME
  696. #endif
  697. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  698. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  699. * the prototypes use int* rather than socklen_t* which matches the
  700. * actual library expectation. When called with the wrong size arg
  701. * accept() returns a zero client inet addr and check_acl() always
  702. * fails. Since socklen_t is widely used below, just force replace
  703. * their typedef with int. - DTL
  704. */
  705. #define socklen_t int
  706. #endif /* hpux */
  707. #define mg_pollfd pollfd
  708. #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */
  709. /* Maximum queue length for pending connections. This value is passed as
  710. * parameter to the "listen" socket call. */
  711. #if !defined(SOMAXCONN)
  712. /* This symbol may be defined in winsock2.h so this must after that include */
  713. #define SOMAXCONN (100) /* in pending connections (count) */
  714. #endif
  715. /* In case our C library is missing "timegm", provide an implementation */
  716. #if defined(NEED_TIMEGM)
  717. static inline int
  718. is_leap(int y)
  719. {
  720. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  721. }
  722. static inline int
  723. count_leap(int y)
  724. {
  725. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  726. }
  727. time_t
  728. timegm(struct tm *tm)
  729. {
  730. static const unsigned short ydays[] = {
  731. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  732. int year = tm->tm_year + 1900;
  733. int mon = tm->tm_mon;
  734. int mday = tm->tm_mday - 1;
  735. int hour = tm->tm_hour;
  736. int min = tm->tm_min;
  737. int sec = tm->tm_sec;
  738. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  739. || (mday >= ydays[mon + 1] - ydays[mon]
  740. + (mon == 1 && is_leap(year) ? 1 : 0))
  741. || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60)
  742. return -1;
  743. time_t res = year - 1970;
  744. res *= 365;
  745. res += mday;
  746. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  747. res += count_leap(year);
  748. res *= 24;
  749. res += hour;
  750. res *= 60;
  751. res += min;
  752. res *= 60;
  753. res += sec;
  754. return res;
  755. }
  756. #endif /* NEED_TIMEGM */
  757. /* va_copy should always be a macro, C99 and C++11 - DTL */
  758. #if !defined(va_copy)
  759. #define va_copy(x, y) ((x) = (y))
  760. #endif
  761. #if defined(_WIN32)
  762. /* Create substitutes for POSIX functions in Win32. */
  763. #if defined(GCC_DIAGNOSTIC)
  764. /* Show no warning in case system functions are not used. */
  765. #pragma GCC diagnostic push
  766. #pragma GCC diagnostic ignored "-Wunused-function"
  767. #endif
  768. static pthread_mutex_t global_log_file_lock;
  769. FUNCTION_MAY_BE_UNUSED
  770. static DWORD
  771. pthread_self(void)
  772. {
  773. return GetCurrentThreadId();
  774. }
  775. FUNCTION_MAY_BE_UNUSED
  776. static int
  777. pthread_key_create(
  778. pthread_key_t *key,
  779. void (*_ignored)(void *) /* destructor not supported for Windows */
  780. )
  781. {
  782. (void)_ignored;
  783. if ((key != 0)) {
  784. *key = TlsAlloc();
  785. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  786. }
  787. return -2;
  788. }
  789. FUNCTION_MAY_BE_UNUSED
  790. static int
  791. pthread_key_delete(pthread_key_t key)
  792. {
  793. return TlsFree(key) ? 0 : 1;
  794. }
  795. FUNCTION_MAY_BE_UNUSED
  796. static int
  797. pthread_setspecific(pthread_key_t key, void *value)
  798. {
  799. return TlsSetValue(key, value) ? 0 : 1;
  800. }
  801. FUNCTION_MAY_BE_UNUSED
  802. static void *
  803. pthread_getspecific(pthread_key_t key)
  804. {
  805. return TlsGetValue(key);
  806. }
  807. #if defined(GCC_DIAGNOSTIC)
  808. /* Enable unused function warning again */
  809. #pragma GCC diagnostic pop
  810. #endif
  811. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  812. #else
  813. static pthread_mutexattr_t pthread_mutex_attr;
  814. #endif /* _WIN32 */
  815. #if defined(_WIN32_WCE)
  816. /* Create substitutes for POSIX functions in Win32. */
  817. #if defined(GCC_DIAGNOSTIC)
  818. /* Show no warning in case system functions are not used. */
  819. #pragma GCC diagnostic push
  820. #pragma GCC diagnostic ignored "-Wunused-function"
  821. #endif
  822. FUNCTION_MAY_BE_UNUSED
  823. static time_t
  824. time(time_t *ptime)
  825. {
  826. time_t t;
  827. SYSTEMTIME st;
  828. FILETIME ft;
  829. GetSystemTime(&st);
  830. SystemTimeToFileTime(&st, &ft);
  831. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  832. if (ptime != NULL) {
  833. *ptime = t;
  834. }
  835. return t;
  836. }
  837. FUNCTION_MAY_BE_UNUSED
  838. static struct tm *
  839. localtime_s(const time_t *ptime, struct tm *ptm)
  840. {
  841. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  842. FILETIME ft, lft;
  843. SYSTEMTIME st;
  844. TIME_ZONE_INFORMATION tzinfo;
  845. if (ptm == NULL) {
  846. return NULL;
  847. }
  848. *(int64_t *)&ft = t;
  849. FileTimeToLocalFileTime(&ft, &lft);
  850. FileTimeToSystemTime(&lft, &st);
  851. ptm->tm_year = st.wYear - 1900;
  852. ptm->tm_mon = st.wMonth - 1;
  853. ptm->tm_wday = st.wDayOfWeek;
  854. ptm->tm_mday = st.wDay;
  855. ptm->tm_hour = st.wHour;
  856. ptm->tm_min = st.wMinute;
  857. ptm->tm_sec = st.wSecond;
  858. ptm->tm_yday = 0; /* hope nobody uses this */
  859. ptm->tm_isdst =
  860. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  861. return ptm;
  862. }
  863. FUNCTION_MAY_BE_UNUSED
  864. static struct tm *
  865. gmtime_s(const time_t *ptime, struct tm *ptm)
  866. {
  867. /* FIXME(lsm): fix this. */
  868. return localtime_s(ptime, ptm);
  869. }
  870. static int mg_atomic_inc(volatile int *addr);
  871. static struct tm tm_array[MAX_WORKER_THREADS];
  872. static int tm_index = 0;
  873. FUNCTION_MAY_BE_UNUSED
  874. static struct tm *
  875. localtime(const time_t *ptime)
  876. {
  877. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  878. return localtime_s(ptime, tm_array + i);
  879. }
  880. FUNCTION_MAY_BE_UNUSED
  881. static struct tm *
  882. gmtime(const time_t *ptime)
  883. {
  884. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  885. return gmtime_s(ptime, tm_array + i);
  886. }
  887. FUNCTION_MAY_BE_UNUSED
  888. static size_t
  889. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  890. {
  891. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  892. * for WinCE"); */
  893. return 0;
  894. }
  895. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  896. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  897. #define remove(f) mg_remove(NULL, f)
  898. FUNCTION_MAY_BE_UNUSED
  899. static int
  900. rename(const char *a, const char *b)
  901. {
  902. wchar_t wa[W_PATH_MAX];
  903. wchar_t wb[W_PATH_MAX];
  904. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  905. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  906. return MoveFileW(wa, wb) ? 0 : -1;
  907. }
  908. struct stat {
  909. int64_t st_size;
  910. time_t st_mtime;
  911. };
  912. FUNCTION_MAY_BE_UNUSED
  913. static int
  914. stat(const char *name, struct stat *st)
  915. {
  916. wchar_t wbuf[W_PATH_MAX];
  917. WIN32_FILE_ATTRIBUTE_DATA attr;
  918. time_t creation_time, write_time;
  919. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  920. memset(&attr, 0, sizeof(attr));
  921. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  922. st->st_size =
  923. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  924. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  925. attr.ftLastWriteTime.dwHighDateTime);
  926. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  927. attr.ftCreationTime.dwHighDateTime);
  928. if (creation_time > write_time) {
  929. st->st_mtime = creation_time;
  930. } else {
  931. st->st_mtime = write_time;
  932. }
  933. return 0;
  934. }
  935. #define access(x, a) 1 /* not required anyway */
  936. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  937. /* Values from errno.h in Windows SDK (Visual Studio). */
  938. #define EEXIST 17
  939. #define EACCES 13
  940. #define ENOENT 2
  941. #if defined(GCC_DIAGNOSTIC)
  942. /* Enable unused function warning again */
  943. #pragma GCC diagnostic pop
  944. #endif
  945. #endif /* defined(_WIN32_WCE) */
  946. #if defined(GCC_DIAGNOSTIC)
  947. /* Show no warning in case system functions are not used. */
  948. #pragma GCC diagnostic push
  949. #pragma GCC diagnostic ignored "-Wunused-function"
  950. #endif /* defined(GCC_DIAGNOSTIC) */
  951. #if defined(__clang__)
  952. /* Show no warning in case system functions are not used. */
  953. #pragma clang diagnostic push
  954. #pragma clang diagnostic ignored "-Wunused-function"
  955. #endif
  956. static pthread_mutex_t global_lock_mutex;
  957. FUNCTION_MAY_BE_UNUSED
  958. static void
  959. mg_global_lock(void)
  960. {
  961. (void)pthread_mutex_lock(&global_lock_mutex);
  962. }
  963. FUNCTION_MAY_BE_UNUSED
  964. static void
  965. mg_global_unlock(void)
  966. {
  967. (void)pthread_mutex_unlock(&global_lock_mutex);
  968. }
  969. FUNCTION_MAY_BE_UNUSED
  970. static int
  971. mg_atomic_inc(volatile int *addr)
  972. {
  973. int ret;
  974. #if defined(_WIN32) && !defined(NO_ATOMICS)
  975. /* Depending on the SDK, this function uses either
  976. * (volatile unsigned int *) or (volatile LONG *),
  977. * so whatever you use, the other SDK is likely to raise a warning. */
  978. ret = InterlockedIncrement((volatile long *)addr);
  979. #elif defined(__GNUC__) \
  980. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  981. && !defined(NO_ATOMICS)
  982. ret = __sync_add_and_fetch(addr, 1);
  983. #else
  984. mg_global_lock();
  985. ret = (++(*addr));
  986. mg_global_unlock();
  987. #endif
  988. return ret;
  989. }
  990. FUNCTION_MAY_BE_UNUSED
  991. static int
  992. mg_atomic_dec(volatile int *addr)
  993. {
  994. int ret;
  995. #if defined(_WIN32) && !defined(NO_ATOMICS)
  996. /* Depending on the SDK, this function uses either
  997. * (volatile unsigned int *) or (volatile LONG *),
  998. * so whatever you use, the other SDK is likely to raise a warning. */
  999. ret = InterlockedDecrement((volatile long *)addr);
  1000. #elif defined(__GNUC__) \
  1001. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1002. && !defined(NO_ATOMICS)
  1003. ret = __sync_sub_and_fetch(addr, 1);
  1004. #else
  1005. mg_global_lock();
  1006. ret = (--(*addr));
  1007. mg_global_unlock();
  1008. #endif
  1009. return ret;
  1010. }
  1011. #if defined(USE_SERVER_STATS)
  1012. static int64_t
  1013. mg_atomic_add(volatile int64_t *addr, int64_t value)
  1014. {
  1015. int64_t ret;
  1016. #if defined(_WIN64) && !defined(NO_ATOMICS)
  1017. ret = InterlockedAdd64(addr, value);
  1018. #elif defined(__GNUC__) \
  1019. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  1020. && !defined(NO_ATOMICS)
  1021. ret = __sync_add_and_fetch(addr, value);
  1022. #else
  1023. mg_global_lock();
  1024. *addr += value;
  1025. ret = (*addr);
  1026. mg_global_unlock();
  1027. #endif
  1028. return ret;
  1029. }
  1030. #endif
  1031. #if defined(GCC_DIAGNOSTIC)
  1032. /* Show no warning in case system functions are not used. */
  1033. #pragma GCC diagnostic pop
  1034. #endif /* defined(GCC_DIAGNOSTIC) */
  1035. #if defined(__clang__)
  1036. /* Show no warning in case system functions are not used. */
  1037. #pragma clang diagnostic pop
  1038. #endif
  1039. #if defined(USE_SERVER_STATS)
  1040. struct mg_memory_stat {
  1041. volatile int64_t totalMemUsed;
  1042. volatile int64_t maxMemUsed;
  1043. volatile int blockCount;
  1044. };
  1045. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  1046. static void *
  1047. mg_malloc_ex(size_t size,
  1048. struct mg_context *ctx,
  1049. const char *file,
  1050. unsigned line)
  1051. {
  1052. void *data = malloc(size + 2 * sizeof(uintptr_t));
  1053. void *memory = 0;
  1054. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  1055. #if defined(MEMORY_DEBUGGING)
  1056. char mallocStr[256];
  1057. #else
  1058. (void)file;
  1059. (void)line;
  1060. #endif
  1061. if (data) {
  1062. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1063. if (mmem > mstat->maxMemUsed) {
  1064. /* could use atomic compare exchange, but this
  1065. * seems overkill for statistics data */
  1066. mstat->maxMemUsed = mmem;
  1067. }
  1068. mg_atomic_inc(&mstat->blockCount);
  1069. ((uintptr_t *)data)[0] = size;
  1070. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1071. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1072. }
  1073. #if defined(MEMORY_DEBUGGING)
  1074. sprintf(mallocStr,
  1075. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1076. memory,
  1077. (unsigned long)size,
  1078. (unsigned long)mstat->totalMemUsed,
  1079. (unsigned long)mstat->blockCount,
  1080. file,
  1081. line);
  1082. #if defined(_WIN32)
  1083. OutputDebugStringA(mallocStr);
  1084. #else
  1085. DEBUG_TRACE("%s", mallocStr);
  1086. #endif
  1087. #endif
  1088. return memory;
  1089. }
  1090. static void *
  1091. mg_calloc_ex(size_t count,
  1092. size_t size,
  1093. struct mg_context *ctx,
  1094. const char *file,
  1095. unsigned line)
  1096. {
  1097. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1098. if (data) {
  1099. memset(data, 0, size * count);
  1100. }
  1101. return data;
  1102. }
  1103. static void
  1104. mg_free_ex(void *memory, const char *file, unsigned line)
  1105. {
  1106. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1107. #if defined(MEMORY_DEBUGGING)
  1108. char mallocStr[256];
  1109. #else
  1110. (void)file;
  1111. (void)line;
  1112. #endif
  1113. if (memory) {
  1114. uintptr_t size = ((uintptr_t *)data)[0];
  1115. struct mg_memory_stat *mstat =
  1116. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1117. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1118. mg_atomic_dec(&mstat->blockCount);
  1119. #if defined(MEMORY_DEBUGGING)
  1120. sprintf(mallocStr,
  1121. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1122. memory,
  1123. (unsigned long)size,
  1124. (unsigned long)mstat->totalMemUsed,
  1125. (unsigned long)mstat->blockCount,
  1126. file,
  1127. line);
  1128. #if defined(_WIN32)
  1129. OutputDebugStringA(mallocStr);
  1130. #else
  1131. DEBUG_TRACE("%s", mallocStr);
  1132. #endif
  1133. #endif
  1134. free(data);
  1135. }
  1136. }
  1137. static void *
  1138. mg_realloc_ex(void *memory,
  1139. size_t newsize,
  1140. struct mg_context *ctx,
  1141. const char *file,
  1142. unsigned line)
  1143. {
  1144. void *data;
  1145. void *_realloc;
  1146. uintptr_t oldsize;
  1147. #if defined(MEMORY_DEBUGGING)
  1148. char mallocStr[256];
  1149. #else
  1150. (void)file;
  1151. (void)line;
  1152. #endif
  1153. if (newsize) {
  1154. if (memory) {
  1155. /* Reallocate existing block */
  1156. struct mg_memory_stat *mstat;
  1157. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1158. oldsize = ((uintptr_t *)data)[0];
  1159. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1160. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1161. if (_realloc) {
  1162. data = _realloc;
  1163. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1164. #if defined(MEMORY_DEBUGGING)
  1165. sprintf(mallocStr,
  1166. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1167. memory,
  1168. (unsigned long)oldsize,
  1169. (unsigned long)mstat->totalMemUsed,
  1170. (unsigned long)mstat->blockCount,
  1171. file,
  1172. line);
  1173. #if defined(_WIN32)
  1174. OutputDebugStringA(mallocStr);
  1175. #else
  1176. DEBUG_TRACE("%s", mallocStr);
  1177. #endif
  1178. #endif
  1179. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1180. #if defined(MEMORY_DEBUGGING)
  1181. sprintf(mallocStr,
  1182. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1183. memory,
  1184. (unsigned long)newsize,
  1185. (unsigned long)mstat->totalMemUsed,
  1186. (unsigned long)mstat->blockCount,
  1187. file,
  1188. line);
  1189. #if defined(_WIN32)
  1190. OutputDebugStringA(mallocStr);
  1191. #else
  1192. DEBUG_TRACE("%s", mallocStr);
  1193. #endif
  1194. #endif
  1195. *(uintptr_t *)data = newsize;
  1196. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1197. } else {
  1198. #if defined(MEMORY_DEBUGGING)
  1199. #if defined(_WIN32)
  1200. OutputDebugStringA("MEM: realloc failed\n");
  1201. #else
  1202. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1203. #endif
  1204. #endif
  1205. return _realloc;
  1206. }
  1207. } else {
  1208. /* Allocate new block */
  1209. data = mg_malloc_ex(newsize, ctx, file, line);
  1210. }
  1211. } else {
  1212. /* Free existing block */
  1213. data = 0;
  1214. mg_free_ex(memory, file, line);
  1215. }
  1216. return data;
  1217. }
  1218. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1219. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1220. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1221. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1222. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1223. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1224. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1225. #else /* USE_SERVER_STATS */
  1226. static __inline void *
  1227. mg_malloc(size_t a)
  1228. {
  1229. return malloc(a);
  1230. }
  1231. static __inline void *
  1232. mg_calloc(size_t a, size_t b)
  1233. {
  1234. return calloc(a, b);
  1235. }
  1236. static __inline void *
  1237. mg_realloc(void *a, size_t b)
  1238. {
  1239. return realloc(a, b);
  1240. }
  1241. static __inline void
  1242. mg_free(void *a)
  1243. {
  1244. free(a);
  1245. }
  1246. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1247. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1248. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1249. #define mg_free_ctx(a, c) mg_free(a)
  1250. #endif /* USE_SERVER_STATS */
  1251. static void mg_vsnprintf(const struct mg_connection *conn,
  1252. int *truncated,
  1253. char *buf,
  1254. size_t buflen,
  1255. const char *fmt,
  1256. va_list ap);
  1257. static void mg_snprintf(const struct mg_connection *conn,
  1258. int *truncated,
  1259. char *buf,
  1260. size_t buflen,
  1261. PRINTF_FORMAT_STRING(const char *fmt),
  1262. ...) PRINTF_ARGS(5, 6);
  1263. /* This following lines are just meant as a reminder to use the mg-functions
  1264. * for memory management */
  1265. #if defined(malloc)
  1266. #undef malloc
  1267. #endif
  1268. #if defined(calloc)
  1269. #undef calloc
  1270. #endif
  1271. #if defined(realloc)
  1272. #undef realloc
  1273. #endif
  1274. #if defined(free)
  1275. #undef free
  1276. #endif
  1277. #if defined(snprintf)
  1278. #undef snprintf
  1279. #endif
  1280. #if defined(vsnprintf)
  1281. #undef vsnprintf
  1282. #endif
  1283. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1284. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1285. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1286. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1287. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1288. #if defined(_WIN32)
  1289. /* vsnprintf must not be used in any system,
  1290. * but this define only works well for Windows. */
  1291. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1292. #endif
  1293. /* mg_init_library counter */
  1294. static int mg_init_library_called = 0;
  1295. #if !defined(NO_SSL)
  1296. static int mg_ssl_initialized = 0;
  1297. #endif
  1298. static pthread_key_t sTlsKey; /* Thread local storage index */
  1299. static int thread_idx_max = 0;
  1300. #if defined(MG_LEGACY_INTERFACE)
  1301. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1302. #endif
  1303. struct mg_workerTLS {
  1304. int is_master;
  1305. unsigned long thread_idx;
  1306. void *user_ptr;
  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 (0x80000BFFul)
  1493. #define SSL_OP_NO_SSLv2 (0x01000000ul)
  1494. #define SSL_OP_NO_SSLv3 (0x02000000ul)
  1495. #define SSL_OP_NO_TLSv1 (0x04000000ul)
  1496. #define SSL_OP_NO_TLSv1_2 (0x08000000ul)
  1497. #define SSL_OP_NO_TLSv1_1 (0x10000000ul)
  1498. #define SSL_OP_NO_TLSv1_3 (0x20000000ul)
  1499. #define SSL_OP_SINGLE_DH_USE (0x00100000ul)
  1500. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000ul)
  1501. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000ul)
  1502. #define SSL_OP_NO_COMPRESSION (0x00020000ul)
  1503. #define SSL_OP_NO_RENEGOTIATION (0x40000000ul)
  1504. #define SSL_CB_HANDSHAKE_START (0x10)
  1505. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1506. #define SSL_ERROR_NONE (0)
  1507. #define SSL_ERROR_SSL (1)
  1508. #define SSL_ERROR_WANT_READ (2)
  1509. #define SSL_ERROR_WANT_WRITE (3)
  1510. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1511. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1512. #define SSL_ERROR_ZERO_RETURN (6)
  1513. #define SSL_ERROR_WANT_CONNECT (7)
  1514. #define SSL_ERROR_WANT_ACCEPT (8)
  1515. #define TLSEXT_TYPE_server_name (0)
  1516. #define TLSEXT_NAMETYPE_host_name (0)
  1517. #define SSL_TLSEXT_ERR_OK (0)
  1518. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1519. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1520. #define SSL_TLSEXT_ERR_NOACK (3)
  1521. struct ssl_func {
  1522. const char *name; /* SSL function name */
  1523. void (*ptr)(void); /* Function pointer */
  1524. };
  1525. #if defined(OPENSSL_API_1_1)
  1526. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1527. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1528. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1529. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1530. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1531. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1532. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1533. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1534. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1535. #define TLS_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1536. #define OPENSSL_init_ssl \
  1537. (*(int (*)(uint64_t opts, \
  1538. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10] \
  1539. .ptr)
  1540. #define SSL_CTX_use_PrivateKey_file \
  1541. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1542. #define SSL_CTX_use_certificate_file \
  1543. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1544. #define SSL_CTX_set_default_passwd_cb \
  1545. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1546. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1547. #define SSL_CTX_use_certificate_chain_file \
  1548. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1549. #define TLS_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[16].ptr)
  1550. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1551. #define SSL_CTX_set_verify \
  1552. (*(void (*)(SSL_CTX *, \
  1553. int, \
  1554. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18] \
  1555. .ptr)
  1556. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1557. #define SSL_CTX_load_verify_locations \
  1558. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1559. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1560. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1561. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[23].ptr)
  1562. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1563. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[25].ptr)
  1564. #define SSL_CIPHER_get_name \
  1565. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1566. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1567. #define SSL_CTX_set_session_id_context \
  1568. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1569. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1570. #define SSL_CTX_set_cipher_list \
  1571. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1572. #define SSL_CTX_set_options \
  1573. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1574. #define SSL_CTX_set_info_callback \
  1575. (*(void (*)(SSL_CTX * ctx, void (*callback)(const SSL *, int, int))) \
  1576. ssl_sw[32] \
  1577. .ptr)
  1578. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1579. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1580. #define SSL_CTX_callback_ctrl \
  1581. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1582. #define SSL_get_servername \
  1583. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1584. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1585. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1586. #define SSL_CTX_clear_options(ctx, op) \
  1587. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1588. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1589. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1590. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1591. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1592. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1593. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1594. SSL_CTX_callback_ctrl(ctx, \
  1595. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1596. (void (*)(void))cb)
  1597. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1598. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1599. #define SSL_set_tlsext_host_name(ctx, arg) \
  1600. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1601. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1602. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1603. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1604. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1605. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1606. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1607. #define CONF_modules_unload (*(void (*)(int))crypto_sw[2].ptr)
  1608. #define X509_free (*(void (*)(X509 *))crypto_sw[3].ptr)
  1609. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[4].ptr)
  1610. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[5].ptr)
  1611. #define X509_NAME_oneline \
  1612. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[6].ptr)
  1613. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[7].ptr)
  1614. #define EVP_get_digestbyname \
  1615. (*(const EVP_MD *(*)(const char *))crypto_sw[8].ptr)
  1616. #define EVP_Digest \
  1617. (*(int (*)( \
  1618. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1619. crypto_sw[9] \
  1620. .ptr)
  1621. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[10].ptr)
  1622. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[11].ptr)
  1623. #define ASN1_INTEGER_to_BN \
  1624. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[12].ptr)
  1625. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[13].ptr)
  1626. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[14].ptr)
  1627. #define ERR_clear_error (*(void (*)(void))crypto_sw[15].ptr)
  1628. #define OPENSSL_free(a) CRYPTO_free(a)
  1629. #define OPENSSL_REMOVE_THREAD_STATE()
  1630. /* init_ssl_ctx() function updates this array.
  1631. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1632. * of respective functions. The macros above (like SSL_connect()) are really
  1633. * just calling these functions indirectly via the pointer. */
  1634. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1635. {"SSL_accept", NULL},
  1636. {"SSL_connect", NULL},
  1637. {"SSL_read", NULL},
  1638. {"SSL_write", NULL},
  1639. {"SSL_get_error", NULL},
  1640. {"SSL_set_fd", NULL},
  1641. {"SSL_new", NULL},
  1642. {"SSL_CTX_new", NULL},
  1643. {"TLS_server_method", NULL},
  1644. {"OPENSSL_init_ssl", NULL},
  1645. {"SSL_CTX_use_PrivateKey_file", NULL},
  1646. {"SSL_CTX_use_certificate_file", NULL},
  1647. {"SSL_CTX_set_default_passwd_cb", NULL},
  1648. {"SSL_CTX_free", NULL},
  1649. {"SSL_CTX_use_certificate_chain_file", NULL},
  1650. {"TLS_client_method", NULL},
  1651. {"SSL_pending", NULL},
  1652. {"SSL_CTX_set_verify", NULL},
  1653. {"SSL_shutdown", NULL},
  1654. {"SSL_CTX_load_verify_locations", NULL},
  1655. {"SSL_CTX_set_default_verify_paths", NULL},
  1656. {"SSL_CTX_set_verify_depth", NULL},
  1657. {"SSL_get_peer_certificate", NULL},
  1658. {"SSL_get_version", NULL},
  1659. {"SSL_get_current_cipher", NULL},
  1660. {"SSL_CIPHER_get_name", NULL},
  1661. {"SSL_CTX_check_private_key", NULL},
  1662. {"SSL_CTX_set_session_id_context", NULL},
  1663. {"SSL_CTX_ctrl", NULL},
  1664. {"SSL_CTX_set_cipher_list", NULL},
  1665. {"SSL_CTX_set_options", NULL},
  1666. {"SSL_CTX_set_info_callback", NULL},
  1667. {"SSL_get_ex_data", NULL},
  1668. {"SSL_set_ex_data", NULL},
  1669. {"SSL_CTX_callback_ctrl", NULL},
  1670. {"SSL_get_servername", NULL},
  1671. {"SSL_set_SSL_CTX", NULL},
  1672. {"SSL_ctrl", NULL},
  1673. {NULL, NULL}};
  1674. /* Similar array as ssl_sw. These functions could be located in different
  1675. * lib. */
  1676. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1677. {"ERR_error_string", NULL},
  1678. {"CONF_modules_unload", NULL},
  1679. {"X509_free", NULL},
  1680. {"X509_get_subject_name", NULL},
  1681. {"X509_get_issuer_name", NULL},
  1682. {"X509_NAME_oneline", NULL},
  1683. {"X509_get_serialNumber", NULL},
  1684. {"EVP_get_digestbyname", NULL},
  1685. {"EVP_Digest", NULL},
  1686. {"i2d_X509", NULL},
  1687. {"BN_bn2hex", NULL},
  1688. {"ASN1_INTEGER_to_BN", NULL},
  1689. {"BN_free", NULL},
  1690. {"CRYPTO_free", NULL},
  1691. {"ERR_clear_error", NULL},
  1692. {NULL, NULL}};
  1693. #else
  1694. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1695. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1696. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1697. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1698. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1699. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1700. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1701. #define SSL_new (*(SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  1702. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  1703. #define SSLv23_server_method (*(SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  1704. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1705. #define SSL_CTX_use_PrivateKey_file \
  1706. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1707. #define SSL_CTX_use_certificate_file \
  1708. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1709. #define SSL_CTX_set_default_passwd_cb \
  1710. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1711. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1712. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1713. #define SSL_CTX_use_certificate_chain_file \
  1714. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1715. #define SSLv23_client_method (*(SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  1716. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1717. #define SSL_CTX_set_verify \
  1718. (*(void (*)(SSL_CTX *, \
  1719. int, \
  1720. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19] \
  1721. .ptr)
  1722. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1723. #define SSL_CTX_load_verify_locations \
  1724. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1725. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1726. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1727. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *)) ssl_sw[24].ptr)
  1728. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1729. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *)) ssl_sw[26].ptr)
  1730. #define SSL_CIPHER_get_name \
  1731. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1732. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1733. #define SSL_CTX_set_session_id_context \
  1734. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1735. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1736. #define SSL_CTX_set_cipher_list \
  1737. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1738. #define SSL_CTX_set_info_callback \
  1739. (*(void (*)(SSL_CTX *, void (*callback)(const SSL *, int, int)))ssl_sw[32] \
  1740. .ptr)
  1741. #define SSL_get_ex_data (*(char *(*)(const SSL *, int))ssl_sw[33].ptr)
  1742. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1743. #define SSL_CTX_callback_ctrl \
  1744. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1745. #define SSL_get_servername \
  1746. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1747. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *)) ssl_sw[37].ptr)
  1748. #define SSL_ctrl (*(long (*)(SSL *, int, long, void *))ssl_sw[38].ptr)
  1749. #define SSL_CTX_set_options(ctx, op) \
  1750. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1751. #define SSL_CTX_clear_options(ctx, op) \
  1752. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1753. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1754. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1755. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1756. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1757. #define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
  1758. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1759. SSL_CTX_callback_ctrl(ctx, \
  1760. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1761. (void (*)(void))cb)
  1762. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1763. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1764. #define SSL_set_tlsext_host_name(ctx, arg) \
  1765. SSL_ctrl(ctx, SSL_CTRL_SET_TLSEXT_HOSTNAME, 0, (void *)arg)
  1766. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1767. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1768. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1769. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1770. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1771. #define CRYPTO_set_locking_callback \
  1772. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1773. #define CRYPTO_set_id_callback \
  1774. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1775. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1776. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1777. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1778. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1779. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1780. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1781. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1782. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1783. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1784. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *)) crypto_sw[12].ptr)
  1785. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *)) crypto_sw[13].ptr)
  1786. #define X509_NAME_oneline \
  1787. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1788. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *)) crypto_sw[15].ptr)
  1789. #define i2c_ASN1_INTEGER \
  1790. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1791. #define EVP_get_digestbyname \
  1792. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1793. #define EVP_Digest \
  1794. (*(int (*)( \
  1795. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1796. crypto_sw[18] \
  1797. .ptr)
  1798. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1799. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1800. #define ASN1_INTEGER_to_BN \
  1801. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn)) crypto_sw[21].ptr)
  1802. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1803. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1804. #define ERR_clear_error (*(void (*)(void))crypto_sw[24].ptr)
  1805. #define OPENSSL_free(a) CRYPTO_free(a)
  1806. /* use here ERR_remove_state,
  1807. * while on some platforms function is not included into library due to
  1808. * deprication */
  1809. #define OPENSSL_REMOVE_THREAD_STATE() ERR_remove_state(0)
  1810. /* init_ssl_ctx() function updates this array.
  1811. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1812. * of respective functions. The macros above (like SSL_connect()) are really
  1813. * just calling these functions indirectly via the pointer. */
  1814. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1815. {"SSL_accept", NULL},
  1816. {"SSL_connect", NULL},
  1817. {"SSL_read", NULL},
  1818. {"SSL_write", NULL},
  1819. {"SSL_get_error", NULL},
  1820. {"SSL_set_fd", NULL},
  1821. {"SSL_new", NULL},
  1822. {"SSL_CTX_new", NULL},
  1823. {"SSLv23_server_method", NULL},
  1824. {"SSL_library_init", NULL},
  1825. {"SSL_CTX_use_PrivateKey_file", NULL},
  1826. {"SSL_CTX_use_certificate_file", NULL},
  1827. {"SSL_CTX_set_default_passwd_cb", NULL},
  1828. {"SSL_CTX_free", NULL},
  1829. {"SSL_load_error_strings", NULL},
  1830. {"SSL_CTX_use_certificate_chain_file", NULL},
  1831. {"SSLv23_client_method", NULL},
  1832. {"SSL_pending", NULL},
  1833. {"SSL_CTX_set_verify", NULL},
  1834. {"SSL_shutdown", NULL},
  1835. {"SSL_CTX_load_verify_locations", NULL},
  1836. {"SSL_CTX_set_default_verify_paths", NULL},
  1837. {"SSL_CTX_set_verify_depth", NULL},
  1838. {"SSL_get_peer_certificate", NULL},
  1839. {"SSL_get_version", NULL},
  1840. {"SSL_get_current_cipher", NULL},
  1841. {"SSL_CIPHER_get_name", NULL},
  1842. {"SSL_CTX_check_private_key", NULL},
  1843. {"SSL_CTX_set_session_id_context", NULL},
  1844. {"SSL_CTX_ctrl", NULL},
  1845. {"SSL_CTX_set_cipher_list", NULL},
  1846. {"SSL_CTX_set_info_callback", NULL},
  1847. {"SSL_get_ex_data", NULL},
  1848. {"SSL_set_ex_data", NULL},
  1849. {"SSL_CTX_callback_ctrl", NULL},
  1850. {"SSL_get_servername", NULL},
  1851. {"SSL_set_SSL_CTX", NULL},
  1852. {"SSL_ctrl", NULL},
  1853. {NULL, NULL}};
  1854. /* Similar array as ssl_sw. These functions could be located in different
  1855. * lib. */
  1856. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1857. {"CRYPTO_set_locking_callback", NULL},
  1858. {"CRYPTO_set_id_callback", NULL},
  1859. {"ERR_get_error", NULL},
  1860. {"ERR_error_string", NULL},
  1861. {"ERR_remove_state", NULL},
  1862. {"ERR_free_strings", NULL},
  1863. {"ENGINE_cleanup", NULL},
  1864. {"CONF_modules_unload", NULL},
  1865. {"CRYPTO_cleanup_all_ex_data", NULL},
  1866. {"EVP_cleanup", NULL},
  1867. {"X509_free", NULL},
  1868. {"X509_get_subject_name", NULL},
  1869. {"X509_get_issuer_name", NULL},
  1870. {"X509_NAME_oneline", NULL},
  1871. {"X509_get_serialNumber", NULL},
  1872. {"i2c_ASN1_INTEGER", NULL},
  1873. {"EVP_get_digestbyname", NULL},
  1874. {"EVP_Digest", NULL},
  1875. {"i2d_X509", NULL},
  1876. {"BN_bn2hex", NULL},
  1877. {"ASN1_INTEGER_to_BN", NULL},
  1878. {"BN_free", NULL},
  1879. {"CRYPTO_free", NULL},
  1880. {"ERR_clear_error", NULL},
  1881. {NULL, NULL}};
  1882. #endif /* OPENSSL_API_1_1 */
  1883. #endif /* NO_SSL_DL */
  1884. #endif /* NO_SSL */
  1885. #if !defined(NO_CACHING)
  1886. static const char month_names[][4] = {"Jan",
  1887. "Feb",
  1888. "Mar",
  1889. "Apr",
  1890. "May",
  1891. "Jun",
  1892. "Jul",
  1893. "Aug",
  1894. "Sep",
  1895. "Oct",
  1896. "Nov",
  1897. "Dec"};
  1898. #endif /* !NO_CACHING */
  1899. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1900. * the
  1901. * union u. */
  1902. union usa {
  1903. struct sockaddr sa;
  1904. struct sockaddr_in sin;
  1905. #if defined(USE_IPV6)
  1906. struct sockaddr_in6 sin6;
  1907. #endif
  1908. };
  1909. /* Describes a string (chunk of memory). */
  1910. struct vec {
  1911. const char *ptr;
  1912. size_t len;
  1913. };
  1914. struct mg_file_stat {
  1915. /* File properties filled by mg_stat: */
  1916. uint64_t size;
  1917. time_t last_modified;
  1918. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1919. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1920. * case we need a "Content-Eencoding: gzip" header */
  1921. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1922. };
  1923. struct mg_file_in_memory {
  1924. char *p;
  1925. uint32_t pos;
  1926. char mode;
  1927. };
  1928. struct mg_file_access {
  1929. /* File properties filled by mg_fopen: */
  1930. FILE *fp;
  1931. #if defined(MG_USE_OPEN_FILE)
  1932. /* TODO (low): Remove obsolete "file in memory" implementation.
  1933. * In an "early 2017" discussion at Google groups
  1934. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1935. * we decided to get rid of this feature (after some fade-out
  1936. * phase). */
  1937. const char *membuf;
  1938. #endif
  1939. };
  1940. struct mg_file {
  1941. struct mg_file_stat stat;
  1942. struct mg_file_access access;
  1943. };
  1944. #if defined(MG_USE_OPEN_FILE)
  1945. #define STRUCT_FILE_INITIALIZER \
  1946. { \
  1947. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1948. { \
  1949. (FILE *)NULL, (const char *)NULL \
  1950. } \
  1951. }
  1952. #else
  1953. #define STRUCT_FILE_INITIALIZER \
  1954. { \
  1955. {(uint64_t)0, (time_t)0, 0, 0, 0}, \
  1956. { \
  1957. (FILE *)NULL \
  1958. } \
  1959. }
  1960. #endif
  1961. /* Describes listening socket, or socket which was accept()-ed by the master
  1962. * thread and queued for future handling by the worker thread. */
  1963. struct socket {
  1964. SOCKET sock; /* Listening socket */
  1965. union usa lsa; /* Local socket address */
  1966. union usa rsa; /* Remote socket address */
  1967. unsigned char is_ssl; /* Is port SSL-ed */
  1968. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1969. * port */
  1970. unsigned char in_use; /* 0: invalid, 1: valid, 2: free */
  1971. };
  1972. /* Enum const for all options must be in sync with
  1973. * static struct mg_option config_options[]
  1974. * This is tested in the unit test (test/private.c)
  1975. * "Private Config Options"
  1976. */
  1977. enum {
  1978. /* Once for each server */
  1979. LISTENING_PORTS,
  1980. NUM_THREADS,
  1981. RUN_AS_USER,
  1982. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1983. * socket option typedef TCP_NODELAY. */
  1984. MAX_REQUEST_SIZE,
  1985. LINGER_TIMEOUT,
  1986. #if defined(__linux__)
  1987. ALLOW_SENDFILE_CALL,
  1988. #endif
  1989. #if defined(_WIN32)
  1990. CASE_SENSITIVE_FILES,
  1991. #endif
  1992. THROTTLE,
  1993. ACCESS_LOG_FILE,
  1994. ERROR_LOG_FILE,
  1995. ENABLE_KEEP_ALIVE,
  1996. REQUEST_TIMEOUT,
  1997. KEEP_ALIVE_TIMEOUT,
  1998. #if defined(USE_WEBSOCKET)
  1999. WEBSOCKET_TIMEOUT,
  2000. ENABLE_WEBSOCKET_PING_PONG,
  2001. #endif
  2002. DECODE_URL,
  2003. #if defined(USE_LUA)
  2004. LUA_BACKGROUND_SCRIPT,
  2005. LUA_BACKGROUND_SCRIPT_PARAMS,
  2006. #endif
  2007. #if defined(USE_TIMERS)
  2008. CGI_TIMEOUT,
  2009. #endif
  2010. /* Once for each domain */
  2011. DOCUMENT_ROOT,
  2012. CGI_EXTENSIONS,
  2013. CGI_ENVIRONMENT,
  2014. PUT_DELETE_PASSWORDS_FILE,
  2015. CGI_INTERPRETER,
  2016. PROTECT_URI,
  2017. AUTHENTICATION_DOMAIN,
  2018. ENABLE_AUTH_DOMAIN_CHECK,
  2019. SSI_EXTENSIONS,
  2020. ENABLE_DIRECTORY_LISTING,
  2021. GLOBAL_PASSWORDS_FILE,
  2022. INDEX_FILES,
  2023. ACCESS_CONTROL_LIST,
  2024. EXTRA_MIME_TYPES,
  2025. SSL_CERTIFICATE,
  2026. SSL_CERTIFICATE_CHAIN,
  2027. URL_REWRITE_PATTERN,
  2028. HIDE_FILES,
  2029. SSL_DO_VERIFY_PEER,
  2030. SSL_CA_PATH,
  2031. SSL_CA_FILE,
  2032. SSL_VERIFY_DEPTH,
  2033. SSL_DEFAULT_VERIFY_PATHS,
  2034. SSL_CIPHER_LIST,
  2035. SSL_PROTOCOL_VERSION,
  2036. SSL_SHORT_TRUST,
  2037. #if defined(USE_LUA)
  2038. LUA_PRELOAD_FILE,
  2039. LUA_SCRIPT_EXTENSIONS,
  2040. LUA_SERVER_PAGE_EXTENSIONS,
  2041. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2042. LUA_DEBUG_PARAMS,
  2043. #endif
  2044. #endif
  2045. #if defined(USE_DUKTAPE)
  2046. DUKTAPE_SCRIPT_EXTENSIONS,
  2047. #endif
  2048. #if defined(USE_WEBSOCKET)
  2049. WEBSOCKET_ROOT,
  2050. #endif
  2051. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2052. LUA_WEBSOCKET_EXTENSIONS,
  2053. #endif
  2054. ACCESS_CONTROL_ALLOW_ORIGIN,
  2055. ACCESS_CONTROL_ALLOW_METHODS,
  2056. ACCESS_CONTROL_ALLOW_HEADERS,
  2057. ERROR_PAGES,
  2058. #if !defined(NO_CACHING)
  2059. STATIC_FILE_MAX_AGE,
  2060. #endif
  2061. #if !defined(NO_SSL)
  2062. STRICT_HTTPS_MAX_AGE,
  2063. #endif
  2064. ADDITIONAL_HEADER,
  2065. ALLOW_INDEX_SCRIPT_SUB_RES,
  2066. #if defined(DAEMONIZE)
  2067. ENABLE_DAEMONIZE,
  2068. #endif
  2069. NUM_OPTIONS
  2070. };
  2071. /* Config option name, config types, default value.
  2072. * Must be in the same order as the enum const above.
  2073. */
  2074. static const struct mg_option config_options[] = {
  2075. /* Once for each server */
  2076. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  2077. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  2078. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  2079. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  2080. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  2081. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2082. #if defined(__linux__)
  2083. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2084. #endif
  2085. #if defined(_WIN32)
  2086. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2087. #endif
  2088. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2089. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2090. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2091. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2092. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2093. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2094. #if defined(USE_WEBSOCKET)
  2095. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2096. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2097. #endif
  2098. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2099. #if defined(USE_LUA)
  2100. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2101. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2102. #endif
  2103. #if defined(USE_TIMERS)
  2104. {"cgi_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2105. #endif
  2106. /* Once for each domain */
  2107. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2108. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2109. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2110. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2111. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2112. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2113. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2114. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2115. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2116. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2117. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2118. {"index_files",
  2119. MG_CONFIG_TYPE_STRING_LIST,
  2120. #if defined(USE_LUA)
  2121. "index.xhtml,index.html,index.htm,"
  2122. "index.lp,index.lsp,index.lua,index.cgi,"
  2123. "index.shtml,index.php"},
  2124. #else
  2125. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2126. #endif
  2127. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2128. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2129. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2130. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2131. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2132. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2133. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2134. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2135. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2136. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2137. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2138. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2139. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2140. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2141. #if defined(USE_LUA)
  2142. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2143. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2144. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2145. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2146. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2147. #endif
  2148. #endif
  2149. #if defined(USE_DUKTAPE)
  2150. /* The support for duktape is still in alpha version state.
  2151. * The name of this config option might change. */
  2152. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2153. #endif
  2154. #if defined(USE_WEBSOCKET)
  2155. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2156. #endif
  2157. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2158. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2159. #endif
  2160. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2161. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2162. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2163. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2164. #if !defined(NO_CACHING)
  2165. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2166. #endif
  2167. #if !defined(NO_SSL)
  2168. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2169. #endif
  2170. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2171. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2172. #if defined(DAEMONIZE)
  2173. {"daemonize", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2174. #endif
  2175. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2176. /* Check if the config_options and the corresponding enum have compatible
  2177. * sizes. */
  2178. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2179. == (NUM_OPTIONS + 1),
  2180. "config_options and enum not sync");
  2181. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2182. struct mg_handler_info {
  2183. /* Name/Pattern of the URI. */
  2184. char *uri;
  2185. size_t uri_len;
  2186. /* handler type */
  2187. int handler_type;
  2188. /* Handler for http/https or authorization requests. */
  2189. mg_request_handler handler;
  2190. unsigned int refcount;
  2191. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2192. pthread_cond_t
  2193. refcount_cond; /* Signaled when handler refcount is decremented */
  2194. /* Handler for ws/wss (websocket) requests. */
  2195. mg_websocket_connect_handler connect_handler;
  2196. mg_websocket_ready_handler ready_handler;
  2197. mg_websocket_data_handler data_handler;
  2198. mg_websocket_close_handler close_handler;
  2199. /* accepted subprotocols for ws/wss requests. */
  2200. struct mg_websocket_subprotocols *subprotocols;
  2201. /* Handler for authorization requests */
  2202. mg_authorization_handler auth_handler;
  2203. /* User supplied argument for the handler function. */
  2204. void *cbdata;
  2205. /* next handler in a linked list */
  2206. struct mg_handler_info *next;
  2207. };
  2208. enum {
  2209. CONTEXT_INVALID,
  2210. CONTEXT_SERVER,
  2211. CONTEXT_HTTP_CLIENT,
  2212. CONTEXT_WS_CLIENT
  2213. };
  2214. struct mg_domain_context {
  2215. SSL_CTX *ssl_ctx; /* SSL context */
  2216. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2217. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2218. /* Server nonce */
  2219. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2220. unsigned long nonce_count; /* Used nonces, used for authentication */
  2221. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2222. /* linked list of shared lua websockets */
  2223. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2224. #endif
  2225. /* Linked list of domains */
  2226. struct mg_domain_context *next;
  2227. };
  2228. struct mg_context {
  2229. /* Part 1 - Physical context:
  2230. * This holds threads, ports, timeouts, ...
  2231. * set for the entire server, independent from the
  2232. * addressed hostname.
  2233. */
  2234. /* Connection related */
  2235. int context_type; /* See CONTEXT_* above */
  2236. struct socket *listening_sockets;
  2237. struct mg_pollfd *listening_socket_fds;
  2238. unsigned int num_listening_sockets;
  2239. struct mg_connection *worker_connections; /* The connection struct, pre-
  2240. * allocated for each worker */
  2241. #if defined(USE_SERVER_STATS)
  2242. int active_connections;
  2243. int max_connections;
  2244. int64_t total_connections;
  2245. int64_t total_requests;
  2246. int64_t total_data_read;
  2247. int64_t total_data_written;
  2248. #endif
  2249. /* Thread related */
  2250. volatile int stop_flag; /* Should we stop event loop */
  2251. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2252. pthread_t masterthreadid; /* The master thread ID */
  2253. unsigned int
  2254. cfg_worker_threads; /* The number of configured worker threads. */
  2255. pthread_t *worker_threadids; /* The worker thread IDs */
  2256. /* Connection to thread dispatching */
  2257. #if defined(ALTERNATIVE_QUEUE)
  2258. struct socket *client_socks;
  2259. void **client_wait_events;
  2260. #else
  2261. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2262. volatile int sq_head; /* Head of the socket queue */
  2263. volatile int sq_tail; /* Tail of the socket queue */
  2264. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2265. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2266. #endif
  2267. /* Memory related */
  2268. unsigned int max_request_size; /* The max request size */
  2269. #if defined(USE_SERVER_STATS)
  2270. struct mg_memory_stat ctx_memory;
  2271. #endif
  2272. /* Operating system related */
  2273. char *systemName; /* What operating system is running */
  2274. time_t start_time; /* Server start time, used for authentication
  2275. * and for diagnstics. */
  2276. #if defined(USE_TIMERS)
  2277. struct ttimers *timers;
  2278. #endif
  2279. /* Lua specific: Background operations and shared websockets */
  2280. #if defined(USE_LUA)
  2281. void *lua_background_state;
  2282. #endif
  2283. /* Server nonce */
  2284. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2285. /* Server callbacks */
  2286. struct mg_callbacks callbacks; /* User-defined callback function */
  2287. void *user_data; /* User-defined data */
  2288. /* Part 2 - Logical domain:
  2289. * This holds hostname, TLS certificate, document root, ...
  2290. * set for a domain hosted at the server.
  2291. * There may be multiple domains hosted at one physical server.
  2292. * The default domain "dd" is the first element of a list of
  2293. * domains.
  2294. */
  2295. struct mg_domain_context dd; /* default domain */
  2296. };
  2297. #if defined(USE_SERVER_STATS)
  2298. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2299. static struct mg_memory_stat *
  2300. get_memory_stat(struct mg_context *ctx)
  2301. {
  2302. if (ctx) {
  2303. return &(ctx->ctx_memory);
  2304. }
  2305. return &mg_common_memory;
  2306. }
  2307. #endif
  2308. enum {
  2309. CONNECTION_TYPE_INVALID,
  2310. CONNECTION_TYPE_REQUEST,
  2311. CONNECTION_TYPE_RESPONSE
  2312. };
  2313. struct mg_connection {
  2314. int connection_type; /* see CONNECTION_TYPE_* above */
  2315. struct mg_request_info request_info;
  2316. struct mg_response_info response_info;
  2317. struct mg_context *phys_ctx;
  2318. struct mg_domain_context *dom_ctx;
  2319. #if defined(USE_SERVER_STATS)
  2320. int conn_state; /* 0 = undef, numerical value may change in different
  2321. * versions. For the current definition, see
  2322. * mg_get_connection_info_impl */
  2323. #endif
  2324. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2325. SSL *ssl; /* SSL descriptor */
  2326. struct socket client; /* Connected client */
  2327. time_t conn_birth_time; /* Time (wall clock) when connection was
  2328. * established */
  2329. struct timespec req_time; /* Time (since system start) when the request
  2330. * was received */
  2331. int64_t num_bytes_sent; /* Total bytes sent to client */
  2332. int64_t content_len; /* How many bytes of content can be read
  2333. * !is_chunked: Content-Length header value
  2334. * or -1 (until connection closed,
  2335. * not allowed for a request)
  2336. * is_chunked: >= 0, appended gradually
  2337. */
  2338. int64_t consumed_content; /* How many bytes of content have been read */
  2339. int is_chunked; /* Transfer-Encoding is chunked:
  2340. * 0 = not chunked,
  2341. * 1 = chunked, not yet, or some data read,
  2342. * 2 = chunked, has error,
  2343. * 3 = chunked, all data read except trailer,
  2344. * 4 = chunked, all data read
  2345. */
  2346. char *buf; /* Buffer for received data */
  2347. char *path_info; /* PATH_INFO part of the URL */
  2348. int must_close; /* 1 if connection must be closed */
  2349. int accept_gzip; /* 1 if gzip encoding is accepted */
  2350. int in_error_handler; /* 1 if in handler for user defined error
  2351. * pages */
  2352. #if defined(USE_WEBSOCKET)
  2353. int in_websocket_handling; /* 1 if in read_websocket */
  2354. #endif
  2355. int handled_requests; /* Number of requests handled by this connection
  2356. */
  2357. int buf_size; /* Buffer size */
  2358. int request_len; /* Size of the request + headers in a buffer */
  2359. int data_len; /* Total size of data in a buffer */
  2360. int status_code; /* HTTP reply status code, e.g. 200 */
  2361. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2362. * throttle */
  2363. time_t last_throttle_time; /* Last time throttled data was sent */
  2364. int last_throttle_bytes; /* Bytes sent this second */
  2365. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2366. * atomic transmissions for websockets */
  2367. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2368. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2369. #endif
  2370. void *tls_user_ptr; /* User defined pointer in thread local storage,
  2371. * for quick access */
  2372. };
  2373. /* Directory entry */
  2374. struct de {
  2375. struct mg_connection *conn;
  2376. char *file_name;
  2377. struct mg_file_stat file;
  2378. };
  2379. #if defined(USE_WEBSOCKET)
  2380. static int is_websocket_protocol(const struct mg_connection *conn);
  2381. #else
  2382. #define is_websocket_protocol(conn) (0)
  2383. #endif
  2384. #define mg_cry_internal(conn, fmt, ...) \
  2385. mg_cry_internal_wrap(conn, NULL, __func__, __LINE__, fmt, __VA_ARGS__)
  2386. #define mg_cry_ctx_internal(ctx, fmt, ...) \
  2387. mg_cry_internal_wrap(NULL, ctx, __func__, __LINE__, fmt, __VA_ARGS__)
  2388. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2389. struct mg_context *ctx,
  2390. const char *func,
  2391. unsigned line,
  2392. const char *fmt,
  2393. ...) PRINTF_ARGS(5, 6);
  2394. #if !defined(NO_THREAD_NAME)
  2395. #if defined(_WIN32) && defined(_MSC_VER)
  2396. /* Set the thread name for debugging purposes in Visual Studio
  2397. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2398. */
  2399. #pragma pack(push, 8)
  2400. typedef struct tagTHREADNAME_INFO {
  2401. DWORD dwType; /* Must be 0x1000. */
  2402. LPCSTR szName; /* Pointer to name (in user addr space). */
  2403. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2404. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2405. } THREADNAME_INFO;
  2406. #pragma pack(pop)
  2407. #elif defined(__linux__)
  2408. #include <sys/prctl.h>
  2409. #include <sys/sendfile.h>
  2410. #if defined(ALTERNATIVE_QUEUE)
  2411. #include <sys/eventfd.h>
  2412. #endif /* ALTERNATIVE_QUEUE */
  2413. #if defined(ALTERNATIVE_QUEUE)
  2414. static void *
  2415. event_create(void)
  2416. {
  2417. int evhdl = eventfd(0, EFD_CLOEXEC);
  2418. int *ret;
  2419. if (evhdl == -1) {
  2420. /* Linux uses -1 on error, Windows NULL. */
  2421. /* However, Linux does not return 0 on success either. */
  2422. return 0;
  2423. }
  2424. ret = (int *)mg_malloc(sizeof(int));
  2425. if (ret) {
  2426. *ret = evhdl;
  2427. } else {
  2428. (void)close(evhdl);
  2429. }
  2430. return (void *)ret;
  2431. }
  2432. static int
  2433. event_wait(void *eventhdl)
  2434. {
  2435. uint64_t u;
  2436. int evhdl, s;
  2437. if (!eventhdl) {
  2438. /* error */
  2439. return 0;
  2440. }
  2441. evhdl = *(int *)eventhdl;
  2442. s = (int)read(evhdl, &u, sizeof(u));
  2443. if (s != sizeof(u)) {
  2444. /* error */
  2445. return 0;
  2446. }
  2447. (void)u; /* the value is not required */
  2448. return 1;
  2449. }
  2450. static int
  2451. event_signal(void *eventhdl)
  2452. {
  2453. uint64_t u = 1;
  2454. int evhdl, s;
  2455. if (!eventhdl) {
  2456. /* error */
  2457. return 0;
  2458. }
  2459. evhdl = *(int *)eventhdl;
  2460. s = (int)write(evhdl, &u, sizeof(u));
  2461. if (s != sizeof(u)) {
  2462. /* error */
  2463. return 0;
  2464. }
  2465. return 1;
  2466. }
  2467. static void
  2468. event_destroy(void *eventhdl)
  2469. {
  2470. int evhdl;
  2471. if (!eventhdl) {
  2472. /* error */
  2473. return;
  2474. }
  2475. evhdl = *(int *)eventhdl;
  2476. close(evhdl);
  2477. mg_free(eventhdl);
  2478. }
  2479. #endif
  2480. #endif
  2481. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2482. struct posix_event {
  2483. pthread_mutex_t mutex;
  2484. pthread_cond_t cond;
  2485. int signaled;
  2486. };
  2487. static void *
  2488. event_create(void)
  2489. {
  2490. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2491. if (ret == 0) {
  2492. /* out of memory */
  2493. return 0;
  2494. }
  2495. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2496. /* pthread mutex not available */
  2497. mg_free(ret);
  2498. return 0;
  2499. }
  2500. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2501. /* pthread cond not available */
  2502. pthread_mutex_destroy(&(ret->mutex));
  2503. mg_free(ret);
  2504. return 0;
  2505. }
  2506. ret->signaled = 0;
  2507. return (void *)ret;
  2508. }
  2509. static int
  2510. event_wait(void *eventhdl)
  2511. {
  2512. struct posix_event *ev = (struct posix_event *)eventhdl;
  2513. pthread_mutex_lock(&(ev->mutex));
  2514. while (!ev->signaled) {
  2515. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2516. }
  2517. ev->signaled = 0;
  2518. pthread_mutex_unlock(&(ev->mutex));
  2519. return 1;
  2520. }
  2521. static int
  2522. event_signal(void *eventhdl)
  2523. {
  2524. struct posix_event *ev = (struct posix_event *)eventhdl;
  2525. pthread_mutex_lock(&(ev->mutex));
  2526. pthread_cond_signal(&(ev->cond));
  2527. ev->signaled = 1;
  2528. pthread_mutex_unlock(&(ev->mutex));
  2529. return 1;
  2530. }
  2531. static void
  2532. event_destroy(void *eventhdl)
  2533. {
  2534. struct posix_event *ev = (struct posix_event *)eventhdl;
  2535. pthread_cond_destroy(&(ev->cond));
  2536. pthread_mutex_destroy(&(ev->mutex));
  2537. mg_free(ev);
  2538. }
  2539. #endif
  2540. static void
  2541. mg_set_thread_name(const char *name)
  2542. {
  2543. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2544. mg_snprintf(
  2545. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2546. #if defined(_WIN32)
  2547. #if defined(_MSC_VER)
  2548. /* Windows and Visual Studio Compiler */
  2549. __try {
  2550. THREADNAME_INFO info;
  2551. info.dwType = 0x1000;
  2552. info.szName = threadName;
  2553. info.dwThreadID = ~0U;
  2554. info.dwFlags = 0;
  2555. RaiseException(0x406D1388,
  2556. 0,
  2557. sizeof(info) / sizeof(ULONG_PTR),
  2558. (ULONG_PTR *)&info);
  2559. } __except (EXCEPTION_EXECUTE_HANDLER) {
  2560. }
  2561. #elif defined(__MINGW32__)
  2562. /* No option known to set thread name for MinGW */
  2563. #endif
  2564. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \
  2565. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2566. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2567. #if defined(__MACH__)
  2568. /* OS X only current thread name can be changed */
  2569. (void)pthread_setname_np(threadName);
  2570. #else
  2571. (void)pthread_setname_np(pthread_self(), threadName);
  2572. #endif
  2573. #elif defined(__linux__)
  2574. /* on linux we can use the old prctl function */
  2575. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2576. #endif
  2577. }
  2578. #else /* !defined(NO_THREAD_NAME) */
  2579. void
  2580. mg_set_thread_name(const char *threadName)
  2581. {
  2582. }
  2583. #endif
  2584. #if defined(MG_LEGACY_INTERFACE)
  2585. const char **
  2586. mg_get_valid_option_names(void)
  2587. {
  2588. /* This function is deprecated. Use mg_get_valid_options instead. */
  2589. static const char
  2590. *data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2591. int i;
  2592. for (i = 0; config_options[i].name != NULL; i++) {
  2593. data[i * 2] = config_options[i].name;
  2594. data[i * 2 + 1] = config_options[i].default_value;
  2595. }
  2596. return data;
  2597. }
  2598. #endif
  2599. const struct mg_option *
  2600. mg_get_valid_options(void)
  2601. {
  2602. return config_options;
  2603. }
  2604. /* Do not open file (used in is_file_in_memory) */
  2605. #define MG_FOPEN_MODE_NONE (0)
  2606. /* Open file for read only access */
  2607. #define MG_FOPEN_MODE_READ (1)
  2608. /* Open file for writing, create and overwrite */
  2609. #define MG_FOPEN_MODE_WRITE (2)
  2610. /* Open file for writing, create and append */
  2611. #define MG_FOPEN_MODE_APPEND (4)
  2612. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2613. * output filep and return 1, otherwise return 0 and don't modify anything.
  2614. */
  2615. static int
  2616. open_file_in_memory(const struct mg_connection *conn,
  2617. const char *path,
  2618. struct mg_file *filep,
  2619. int mode)
  2620. {
  2621. #if defined(MG_USE_OPEN_FILE)
  2622. size_t size = 0;
  2623. const char *buf = NULL;
  2624. if (!conn) {
  2625. return 0;
  2626. }
  2627. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2628. return 0;
  2629. }
  2630. if (conn->phys_ctx->callbacks.open_file) {
  2631. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2632. if (buf != NULL) {
  2633. if (filep == NULL) {
  2634. /* This is a file in memory, but we cannot store the
  2635. * properties
  2636. * now.
  2637. * Called from "is_file_in_memory" function. */
  2638. return 1;
  2639. }
  2640. /* NOTE: override filep->size only on success. Otherwise, it
  2641. * might
  2642. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2643. filep->access.membuf = buf;
  2644. filep->access.fp = NULL;
  2645. /* Size was set by the callback */
  2646. filep->stat.size = size;
  2647. /* Assume the data may change during runtime by setting
  2648. * last_modified = now */
  2649. filep->stat.last_modified = time(NULL);
  2650. filep->stat.is_directory = 0;
  2651. filep->stat.is_gzipped = 0;
  2652. }
  2653. }
  2654. return (buf != NULL);
  2655. #else
  2656. (void)conn;
  2657. (void)path;
  2658. (void)filep;
  2659. (void)mode;
  2660. return 0;
  2661. #endif
  2662. }
  2663. static int
  2664. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2665. {
  2666. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2667. }
  2668. static int
  2669. is_file_opened(const struct mg_file_access *fileacc)
  2670. {
  2671. if (!fileacc) {
  2672. return 0;
  2673. }
  2674. #if defined(MG_USE_OPEN_FILE)
  2675. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2676. #else
  2677. return (fileacc->fp != NULL);
  2678. #endif
  2679. }
  2680. #if !defined(NO_FILESYSTEMS)
  2681. static int mg_stat(const struct mg_connection *conn,
  2682. const char *path,
  2683. struct mg_file_stat *filep);
  2684. /* mg_fopen will open a file either in memory or on the disk.
  2685. * The input parameter path is a string in UTF-8 encoding.
  2686. * The input parameter mode is MG_FOPEN_MODE_*
  2687. * On success, either fp or membuf will be set in the output
  2688. * struct file. All status members will also be set.
  2689. * The function returns 1 on success, 0 on error. */
  2690. static int
  2691. mg_fopen(const struct mg_connection *conn,
  2692. const char *path,
  2693. int mode,
  2694. struct mg_file *filep)
  2695. {
  2696. int found;
  2697. if (!filep) {
  2698. return 0;
  2699. }
  2700. filep->access.fp = NULL;
  2701. #if defined(MG_USE_OPEN_FILE)
  2702. filep->access.membuf = NULL;
  2703. #endif
  2704. if (!is_file_in_memory(conn, path)) {
  2705. /* filep is initialized in mg_stat: all fields with memset to,
  2706. * some fields like size and modification date with values */
  2707. found = mg_stat(conn, path, &(filep->stat));
  2708. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2709. /* file does not exist and will not be created */
  2710. return 0;
  2711. }
  2712. #if defined(_WIN32)
  2713. {
  2714. wchar_t wbuf[W_PATH_MAX];
  2715. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2716. switch (mode) {
  2717. case MG_FOPEN_MODE_READ:
  2718. filep->access.fp = _wfopen(wbuf, L"rb");
  2719. break;
  2720. case MG_FOPEN_MODE_WRITE:
  2721. filep->access.fp = _wfopen(wbuf, L"wb");
  2722. break;
  2723. case MG_FOPEN_MODE_APPEND:
  2724. filep->access.fp = _wfopen(wbuf, L"ab");
  2725. break;
  2726. }
  2727. }
  2728. #else
  2729. /* Linux et al already use unicode. No need to convert. */
  2730. switch (mode) {
  2731. case MG_FOPEN_MODE_READ:
  2732. filep->access.fp = fopen(path, "r");
  2733. break;
  2734. case MG_FOPEN_MODE_WRITE:
  2735. filep->access.fp = fopen(path, "w");
  2736. break;
  2737. case MG_FOPEN_MODE_APPEND:
  2738. filep->access.fp = fopen(path, "a");
  2739. break;
  2740. }
  2741. #endif
  2742. if (!found) {
  2743. /* File did not exist before fopen was called.
  2744. * Maybe it has been created now. Get stat info
  2745. * like creation time now. */
  2746. found = mg_stat(conn, path, &(filep->stat));
  2747. (void)found;
  2748. }
  2749. /* file is on disk */
  2750. return (filep->access.fp != NULL);
  2751. } else {
  2752. #if defined(MG_USE_OPEN_FILE)
  2753. /* is_file_in_memory returned true */
  2754. if (open_file_in_memory(conn, path, filep, mode)) {
  2755. /* file is in memory */
  2756. return (filep->access.membuf != NULL);
  2757. }
  2758. #endif
  2759. }
  2760. /* Open failed */
  2761. return 0;
  2762. }
  2763. /* return 0 on success, just like fclose */
  2764. static int
  2765. mg_fclose(struct mg_file_access *fileacc)
  2766. {
  2767. int ret = -1;
  2768. if (fileacc != NULL) {
  2769. if (fileacc->fp != NULL) {
  2770. ret = fclose(fileacc->fp);
  2771. #if defined(MG_USE_OPEN_FILE)
  2772. } else if (fileacc->membuf != NULL) {
  2773. ret = 0;
  2774. #endif
  2775. }
  2776. /* reset all members of fileacc */
  2777. memset(fileacc, 0, sizeof(*fileacc));
  2778. }
  2779. return ret;
  2780. }
  2781. #endif /* NO_FILESYSTEMS */
  2782. static void
  2783. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2784. {
  2785. for (; *src != '\0' && n > 1; n--) {
  2786. *dst++ = *src++;
  2787. }
  2788. *dst = '\0';
  2789. }
  2790. static int
  2791. lowercase(const char *s)
  2792. {
  2793. return tolower((unsigned char)*s);
  2794. }
  2795. int
  2796. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2797. {
  2798. int diff = 0;
  2799. if (len > 0) {
  2800. do {
  2801. diff = lowercase(s1++) - lowercase(s2++);
  2802. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2803. }
  2804. return diff;
  2805. }
  2806. int
  2807. mg_strcasecmp(const char *s1, const char *s2)
  2808. {
  2809. int diff;
  2810. do {
  2811. diff = lowercase(s1++) - lowercase(s2++);
  2812. } while (diff == 0 && s1[-1] != '\0');
  2813. return diff;
  2814. }
  2815. static char *
  2816. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2817. {
  2818. char *p;
  2819. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2820. * defined */
  2821. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2822. mg_strlcpy(p, ptr, len + 1);
  2823. }
  2824. return p;
  2825. }
  2826. static char *
  2827. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2828. {
  2829. return mg_strndup_ctx(str, strlen(str), ctx);
  2830. }
  2831. static char *
  2832. mg_strdup(const char *str)
  2833. {
  2834. return mg_strndup_ctx(str, strlen(str), NULL);
  2835. }
  2836. static const char *
  2837. mg_strcasestr(const char *big_str, const char *small_str)
  2838. {
  2839. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2840. if (big_len >= small_len) {
  2841. for (i = 0; i <= (big_len - small_len); i++) {
  2842. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2843. return big_str + i;
  2844. }
  2845. }
  2846. }
  2847. return NULL;
  2848. }
  2849. /* Return null terminated string of given maximum length.
  2850. * Report errors if length is exceeded. */
  2851. static void
  2852. mg_vsnprintf(const struct mg_connection *conn,
  2853. int *truncated,
  2854. char *buf,
  2855. size_t buflen,
  2856. const char *fmt,
  2857. va_list ap)
  2858. {
  2859. int n, ok;
  2860. if (buflen == 0) {
  2861. if (truncated) {
  2862. *truncated = 1;
  2863. }
  2864. return;
  2865. }
  2866. #if defined(__clang__)
  2867. #pragma clang diagnostic push
  2868. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2869. /* Using fmt as a non-literal is intended here, since it is mostly called
  2870. * indirectly by mg_snprintf */
  2871. #endif
  2872. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2873. ok = (n >= 0) && ((size_t)n < buflen);
  2874. #if defined(__clang__)
  2875. #pragma clang diagnostic pop
  2876. #endif
  2877. if (ok) {
  2878. if (truncated) {
  2879. *truncated = 0;
  2880. }
  2881. } else {
  2882. if (truncated) {
  2883. *truncated = 1;
  2884. }
  2885. mg_cry_internal(conn,
  2886. "truncating vsnprintf buffer: [%.*s]",
  2887. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2888. buf);
  2889. n = (int)buflen - 1;
  2890. }
  2891. buf[n] = '\0';
  2892. }
  2893. static void
  2894. mg_snprintf(const struct mg_connection *conn,
  2895. int *truncated,
  2896. char *buf,
  2897. size_t buflen,
  2898. const char *fmt,
  2899. ...)
  2900. {
  2901. va_list ap;
  2902. va_start(ap, fmt);
  2903. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2904. va_end(ap);
  2905. }
  2906. static int
  2907. get_option_index(const char *name)
  2908. {
  2909. int i;
  2910. for (i = 0; config_options[i].name != NULL; i++) {
  2911. if (strcmp(config_options[i].name, name) == 0) {
  2912. return i;
  2913. }
  2914. }
  2915. return -1;
  2916. }
  2917. const char *
  2918. mg_get_option(const struct mg_context *ctx, const char *name)
  2919. {
  2920. int i;
  2921. if ((i = get_option_index(name)) == -1) {
  2922. return NULL;
  2923. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2924. return "";
  2925. } else {
  2926. return ctx->dd.config[i];
  2927. }
  2928. }
  2929. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2930. struct mg_context *
  2931. mg_get_context(const struct mg_connection *conn)
  2932. {
  2933. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2934. }
  2935. void *
  2936. mg_get_user_data(const struct mg_context *ctx)
  2937. {
  2938. return (ctx == NULL) ? NULL : ctx->user_data;
  2939. }
  2940. void *
  2941. mg_get_thread_pointer(const struct mg_connection *conn)
  2942. {
  2943. /* both methods should return the same pointer */
  2944. if (conn) {
  2945. /* quick access, in case conn is known */
  2946. return conn->tls_user_ptr;
  2947. } else {
  2948. /* otherwise get pointer from thread local storage (TLS) */
  2949. struct mg_workerTLS *tls =
  2950. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  2951. return tls->user_ptr;
  2952. }
  2953. }
  2954. void
  2955. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2956. {
  2957. if (conn != NULL) {
  2958. conn->request_info.conn_data = data;
  2959. }
  2960. }
  2961. void *
  2962. mg_get_user_connection_data(const struct mg_connection *conn)
  2963. {
  2964. if (conn != NULL) {
  2965. return conn->request_info.conn_data;
  2966. }
  2967. return NULL;
  2968. }
  2969. #if defined(MG_LEGACY_INTERFACE)
  2970. /* Deprecated: Use mg_get_server_ports instead. */
  2971. size_t
  2972. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2973. {
  2974. size_t i;
  2975. if (!ctx) {
  2976. return 0;
  2977. }
  2978. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2979. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2980. ports[i] =
  2981. #if defined(USE_IPV6)
  2982. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2983. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2984. :
  2985. #endif
  2986. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2987. }
  2988. return i;
  2989. }
  2990. #endif
  2991. int
  2992. mg_get_server_ports(const struct mg_context *ctx,
  2993. int size,
  2994. struct mg_server_port *ports)
  2995. {
  2996. int i, cnt = 0;
  2997. if (size <= 0) {
  2998. return -1;
  2999. }
  3000. memset(ports, 0, sizeof(*ports) * (size_t)size);
  3001. if (!ctx) {
  3002. return -1;
  3003. }
  3004. if (!ctx->listening_sockets) {
  3005. return -1;
  3006. }
  3007. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  3008. ports[cnt].port =
  3009. #if defined(USE_IPV6)
  3010. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  3011. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  3012. :
  3013. #endif
  3014. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  3015. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  3016. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  3017. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  3018. /* IPv4 */
  3019. ports[cnt].protocol = 1;
  3020. cnt++;
  3021. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  3022. /* IPv6 */
  3023. ports[cnt].protocol = 3;
  3024. cnt++;
  3025. }
  3026. }
  3027. return cnt;
  3028. }
  3029. static void
  3030. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  3031. {
  3032. buf[0] = '\0';
  3033. if (!usa) {
  3034. return;
  3035. }
  3036. if (usa->sa.sa_family == AF_INET) {
  3037. getnameinfo(&usa->sa,
  3038. sizeof(usa->sin),
  3039. buf,
  3040. (unsigned)len,
  3041. NULL,
  3042. 0,
  3043. NI_NUMERICHOST);
  3044. }
  3045. #if defined(USE_IPV6)
  3046. else if (usa->sa.sa_family == AF_INET6) {
  3047. getnameinfo(&usa->sa,
  3048. sizeof(usa->sin6),
  3049. buf,
  3050. (unsigned)len,
  3051. NULL,
  3052. 0,
  3053. NI_NUMERICHOST);
  3054. }
  3055. #endif
  3056. }
  3057. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  3058. * included in all responses other than 100, 101, 5xx. */
  3059. static void
  3060. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  3061. {
  3062. #if !defined(REENTRANT_TIME)
  3063. struct tm *tm;
  3064. tm = ((t != NULL) ? gmtime(t) : NULL);
  3065. if (tm != NULL) {
  3066. #else
  3067. struct tm _tm;
  3068. struct tm *tm = &_tm;
  3069. if (t != NULL) {
  3070. gmtime_r(t, tm);
  3071. #endif
  3072. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  3073. } else {
  3074. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  3075. buf[buf_len - 1] = '\0';
  3076. }
  3077. }
  3078. /* difftime for struct timespec. Return value is in seconds. */
  3079. static double
  3080. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  3081. {
  3082. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  3083. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  3084. }
  3085. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  3086. static void mg_cry_internal_impl(const struct mg_connection *conn,
  3087. const char *func,
  3088. unsigned line,
  3089. const char *fmt,
  3090. va_list ap);
  3091. #include "external_mg_cry_internal_impl.inl"
  3092. #elif !defined(NO_FILESYSTEMS)
  3093. /* Print error message to the opened error log stream. */
  3094. static void
  3095. mg_cry_internal_impl(const struct mg_connection *conn,
  3096. const char *func,
  3097. unsigned line,
  3098. const char *fmt,
  3099. va_list ap)
  3100. {
  3101. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  3102. struct mg_file fi;
  3103. time_t timestamp;
  3104. /* Unused, in the RELEASE build */
  3105. (void)func;
  3106. (void)line;
  3107. #if defined(GCC_DIAGNOSTIC)
  3108. #pragma GCC diagnostic push
  3109. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  3110. #endif
  3111. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  3112. #if defined(GCC_DIAGNOSTIC)
  3113. #pragma GCC diagnostic pop
  3114. #endif
  3115. buf[sizeof(buf) - 1] = 0;
  3116. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  3117. if (!conn) {
  3118. puts(buf);
  3119. return;
  3120. }
  3121. /* Do not lock when getting the callback value, here and below.
  3122. * I suppose this is fine, since function cannot disappear in the
  3123. * same way string option can. */
  3124. if ((conn->phys_ctx->callbacks.log_message == NULL)
  3125. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3126. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3127. if (mg_fopen(conn,
  3128. conn->dom_ctx->config[ERROR_LOG_FILE],
  3129. MG_FOPEN_MODE_APPEND,
  3130. &fi)
  3131. == 0) {
  3132. fi.access.fp = NULL;
  3133. }
  3134. } else {
  3135. fi.access.fp = NULL;
  3136. }
  3137. if (fi.access.fp != NULL) {
  3138. flockfile(fi.access.fp);
  3139. timestamp = time(NULL);
  3140. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3141. fprintf(fi.access.fp,
  3142. "[%010lu] [error] [client %s] ",
  3143. (unsigned long)timestamp,
  3144. src_addr);
  3145. if (conn->request_info.request_method != NULL) {
  3146. fprintf(fi.access.fp,
  3147. "%s %s: ",
  3148. conn->request_info.request_method,
  3149. conn->request_info.request_uri
  3150. ? conn->request_info.request_uri
  3151. : "");
  3152. }
  3153. fprintf(fi.access.fp, "%s", buf);
  3154. fputc('\n', fi.access.fp);
  3155. fflush(fi.access.fp);
  3156. funlockfile(fi.access.fp);
  3157. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3158. * mg_cry here anyway ;-) */
  3159. }
  3160. }
  3161. }
  3162. #else
  3163. #error Must either enable filesystems or provide a custom mg_cry_internal_impl implementation
  3164. #endif /* Externally provided function */
  3165. /* Construct fake connection structure. Used for logging, if connection
  3166. * is not applicable at the moment of logging. */
  3167. static struct mg_connection *
  3168. fake_connection(struct mg_connection *fc, struct mg_context *ctx)
  3169. {
  3170. static const struct mg_connection conn_zero = {0};
  3171. *fc = conn_zero;
  3172. fc->phys_ctx = ctx;
  3173. fc->dom_ctx = &(ctx->dd);
  3174. return fc;
  3175. }
  3176. static void
  3177. mg_cry_internal_wrap(const struct mg_connection *conn,
  3178. struct mg_context *ctx,
  3179. const char *func,
  3180. unsigned line,
  3181. const char *fmt,
  3182. ...)
  3183. {
  3184. va_list ap;
  3185. va_start(ap, fmt);
  3186. if (!conn && ctx) {
  3187. struct mg_connection fc;
  3188. mg_cry_internal_impl(fake_connection(&fc, ctx), func, line, fmt, ap);
  3189. } else {
  3190. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3191. }
  3192. va_end(ap);
  3193. }
  3194. void
  3195. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3196. {
  3197. va_list ap;
  3198. va_start(ap, fmt);
  3199. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3200. va_end(ap);
  3201. }
  3202. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3203. const char *
  3204. mg_version(void)
  3205. {
  3206. return CIVETWEB_VERSION;
  3207. }
  3208. const struct mg_request_info *
  3209. mg_get_request_info(const struct mg_connection *conn)
  3210. {
  3211. if (!conn) {
  3212. return NULL;
  3213. }
  3214. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3215. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3216. char txt[16];
  3217. struct mg_workerTLS *tls =
  3218. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3219. sprintf(txt, "%03i", conn->response_info.status_code);
  3220. if (strlen(txt) == 3) {
  3221. memcpy(tls->txtbuf, txt, 4);
  3222. } else {
  3223. strcpy(tls->txtbuf, "ERR");
  3224. }
  3225. ((struct mg_connection *)conn)->request_info.local_uri =
  3226. ((struct mg_connection *)conn)->request_info.request_uri =
  3227. tls->txtbuf; /* use thread safe buffer */
  3228. ((struct mg_connection *)conn)->request_info.num_headers =
  3229. conn->response_info.num_headers;
  3230. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3231. conn->response_info.http_headers,
  3232. sizeof(conn->response_info.http_headers));
  3233. } else
  3234. #endif
  3235. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3236. return NULL;
  3237. }
  3238. return &conn->request_info;
  3239. }
  3240. const struct mg_response_info *
  3241. mg_get_response_info(const struct mg_connection *conn)
  3242. {
  3243. if (!conn) {
  3244. return NULL;
  3245. }
  3246. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3247. return NULL;
  3248. }
  3249. return &conn->response_info;
  3250. }
  3251. static const char *
  3252. get_proto_name(const struct mg_connection *conn)
  3253. {
  3254. #if defined(__clang__)
  3255. #pragma clang diagnostic push
  3256. #pragma clang diagnostic ignored "-Wunreachable-code"
  3257. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3258. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3259. * unreachable, but splitting into four different #ifdef clauses here is more
  3260. * complicated.
  3261. */
  3262. #endif
  3263. const struct mg_request_info *ri = &conn->request_info;
  3264. const char *proto =
  3265. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3266. : (ri->is_ssl ? "https" : "http"));
  3267. return proto;
  3268. #if defined(__clang__)
  3269. #pragma clang diagnostic pop
  3270. #endif
  3271. }
  3272. int
  3273. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3274. {
  3275. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3276. return -1;
  3277. } else {
  3278. int truncated = 0;
  3279. const struct mg_request_info *ri = &conn->request_info;
  3280. const char *proto = get_proto_name(conn);
  3281. if (ri->local_uri == NULL) {
  3282. return -1;
  3283. }
  3284. if ((ri->request_uri != NULL)
  3285. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3286. /* The request uri is different from the local uri.
  3287. * This is usually if an absolute URI, including server
  3288. * name has been provided. */
  3289. mg_snprintf(conn,
  3290. &truncated,
  3291. buf,
  3292. buflen,
  3293. "%s://%s",
  3294. proto,
  3295. ri->request_uri);
  3296. if (truncated) {
  3297. return -1;
  3298. }
  3299. return 0;
  3300. } else {
  3301. /* The common case is a relative URI, so we have to
  3302. * construct an absolute URI from server name and port */
  3303. #if defined(USE_IPV6)
  3304. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3305. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3306. : htons(conn->client.lsa.sin.sin_port);
  3307. #else
  3308. int port = htons(conn->client.lsa.sin.sin_port);
  3309. #endif
  3310. int def_port = ri->is_ssl ? 443 : 80;
  3311. int auth_domain_check_enabled =
  3312. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3313. && (!mg_strcasecmp(
  3314. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"));
  3315. const char *server_domain =
  3316. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3317. char portstr[16];
  3318. char server_ip[48];
  3319. if (port != def_port) {
  3320. sprintf(portstr, ":%u", (unsigned)port);
  3321. } else {
  3322. portstr[0] = 0;
  3323. }
  3324. if (!auth_domain_check_enabled || !server_domain) {
  3325. sockaddr_to_string(server_ip,
  3326. sizeof(server_ip),
  3327. &conn->client.lsa);
  3328. server_domain = server_ip;
  3329. }
  3330. mg_snprintf(conn,
  3331. &truncated,
  3332. buf,
  3333. buflen,
  3334. "%s://%s%s%s",
  3335. proto,
  3336. server_domain,
  3337. portstr,
  3338. ri->local_uri);
  3339. if (truncated) {
  3340. return -1;
  3341. }
  3342. return 0;
  3343. }
  3344. }
  3345. }
  3346. /* Skip the characters until one of the delimiters characters found.
  3347. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3348. * Advance pointer to buffer to the next word. Return found 0-terminated
  3349. * word.
  3350. * Delimiters can be quoted with quotechar. */
  3351. static char *
  3352. skip_quoted(char **buf,
  3353. const char *delimiters,
  3354. const char *whitespace,
  3355. char quotechar)
  3356. {
  3357. char *p, *begin_word, *end_word, *end_whitespace;
  3358. begin_word = *buf;
  3359. end_word = begin_word + strcspn(begin_word, delimiters);
  3360. /* Check for quotechar */
  3361. if (end_word > begin_word) {
  3362. p = end_word - 1;
  3363. while (*p == quotechar) {
  3364. /* While the delimiter is quoted, look for the next delimiter.
  3365. */
  3366. /* This happens, e.g., in calls from parse_auth_header,
  3367. * if the user name contains a " character. */
  3368. /* If there is anything beyond end_word, copy it. */
  3369. if (*end_word != '\0') {
  3370. size_t end_off = strcspn(end_word + 1, delimiters);
  3371. memmove(p, end_word, end_off + 1);
  3372. p += end_off; /* p must correspond to end_word - 1 */
  3373. end_word += end_off + 1;
  3374. } else {
  3375. *p = '\0';
  3376. break;
  3377. }
  3378. }
  3379. for (p++; p < end_word; p++) {
  3380. *p = '\0';
  3381. }
  3382. }
  3383. if (*end_word == '\0') {
  3384. *buf = end_word;
  3385. } else {
  3386. #if defined(GCC_DIAGNOSTIC)
  3387. /* Disable spurious conversion warning for GCC */
  3388. #pragma GCC diagnostic push
  3389. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3390. #endif /* defined(GCC_DIAGNOSTIC) */
  3391. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3392. #if defined(GCC_DIAGNOSTIC)
  3393. #pragma GCC diagnostic pop
  3394. #endif /* defined(GCC_DIAGNOSTIC) */
  3395. for (p = end_word; p < end_whitespace; p++) {
  3396. *p = '\0';
  3397. }
  3398. *buf = end_whitespace;
  3399. }
  3400. return begin_word;
  3401. }
  3402. /* Return HTTP header value, or NULL if not found. */
  3403. static const char *
  3404. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3405. {
  3406. int i;
  3407. for (i = 0; i < num_hdr; i++) {
  3408. if (!mg_strcasecmp(name, hdr[i].name)) {
  3409. return hdr[i].value;
  3410. }
  3411. }
  3412. return NULL;
  3413. }
  3414. #if defined(USE_WEBSOCKET)
  3415. /* Retrieve requested HTTP header multiple values, and return the number of
  3416. * found occurrences */
  3417. static int
  3418. get_req_headers(const struct mg_request_info *ri,
  3419. const char *name,
  3420. const char **output,
  3421. int output_max_size)
  3422. {
  3423. int i;
  3424. int cnt = 0;
  3425. if (ri) {
  3426. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3427. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3428. output[cnt++] = ri->http_headers[i].value;
  3429. }
  3430. }
  3431. }
  3432. return cnt;
  3433. }
  3434. #endif
  3435. const char *
  3436. mg_get_header(const struct mg_connection *conn, const char *name)
  3437. {
  3438. if (!conn) {
  3439. return NULL;
  3440. }
  3441. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3442. return get_header(conn->request_info.http_headers,
  3443. conn->request_info.num_headers,
  3444. name);
  3445. }
  3446. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3447. return get_header(conn->response_info.http_headers,
  3448. conn->response_info.num_headers,
  3449. name);
  3450. }
  3451. return NULL;
  3452. }
  3453. static const char *
  3454. get_http_version(const struct mg_connection *conn)
  3455. {
  3456. if (!conn) {
  3457. return NULL;
  3458. }
  3459. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3460. return conn->request_info.http_version;
  3461. }
  3462. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3463. return conn->response_info.http_version;
  3464. }
  3465. return NULL;
  3466. }
  3467. /* A helper function for traversing a comma separated list of values.
  3468. * It returns a list pointer shifted to the next value, or NULL if the end
  3469. * of the list found.
  3470. * Value is stored in val vector. If value has form "x=y", then eq_val
  3471. * vector is initialized to point to the "y" part, and val vector length
  3472. * is adjusted to point only to "x". */
  3473. static const char *
  3474. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3475. {
  3476. int end;
  3477. reparse:
  3478. if (val == NULL || list == NULL || *list == '\0') {
  3479. /* End of the list */
  3480. return NULL;
  3481. }
  3482. /* Skip over leading LWS */
  3483. while (*list == ' ' || *list == '\t')
  3484. list++;
  3485. val->ptr = list;
  3486. if ((list = strchr(val->ptr, ',')) != NULL) {
  3487. /* Comma found. Store length and shift the list ptr */
  3488. val->len = ((size_t)(list - val->ptr));
  3489. list++;
  3490. } else {
  3491. /* This value is the last one */
  3492. list = val->ptr + strlen(val->ptr);
  3493. val->len = ((size_t)(list - val->ptr));
  3494. }
  3495. /* Adjust length for trailing LWS */
  3496. end = (int)val->len - 1;
  3497. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3498. end--;
  3499. val->len = (size_t)(end) + (size_t)(1);
  3500. if (val->len == 0) {
  3501. /* Ignore any empty entries. */
  3502. goto reparse;
  3503. }
  3504. if (eq_val != NULL) {
  3505. /* Value has form "x=y", adjust pointers and lengths
  3506. * so that val points to "x", and eq_val points to "y". */
  3507. eq_val->len = 0;
  3508. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3509. if (eq_val->ptr != NULL) {
  3510. eq_val->ptr++; /* Skip over '=' character */
  3511. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3512. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3513. }
  3514. }
  3515. return list;
  3516. }
  3517. /* A helper function for checking if a comma separated list of values
  3518. * contains
  3519. * the given option (case insensitvely).
  3520. * 'header' can be NULL, in which case false is returned. */
  3521. static int
  3522. header_has_option(const char *header, const char *option)
  3523. {
  3524. struct vec opt_vec;
  3525. struct vec eq_vec;
  3526. DEBUG_ASSERT(option != NULL);
  3527. DEBUG_ASSERT(option[0] != '\0');
  3528. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3529. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3530. return 1;
  3531. }
  3532. return 0;
  3533. }
  3534. /* Perform case-insensitive match of string against pattern */
  3535. static ptrdiff_t
  3536. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3537. {
  3538. const char *or_str;
  3539. ptrdiff_t i, j, len, res;
  3540. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3541. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3542. return (res > 0) ? res
  3543. : match_prefix(or_str + 1,
  3544. (size_t)((pattern + pattern_len)
  3545. - (or_str + 1)),
  3546. str);
  3547. }
  3548. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3549. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3550. continue;
  3551. } else if (pattern[i] == '$') {
  3552. return (str[j] == '\0') ? j : -1;
  3553. } else if (pattern[i] == '*') {
  3554. i++;
  3555. if (pattern[i] == '*') {
  3556. i++;
  3557. len = strlen(str + j);
  3558. } else {
  3559. len = strcspn(str + j, "/");
  3560. }
  3561. if (i == (ptrdiff_t)pattern_len) {
  3562. return j + len;
  3563. }
  3564. do {
  3565. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3566. } while (res == -1 && len-- > 0);
  3567. return (res == -1) ? -1 : j + res + len;
  3568. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3569. return -1;
  3570. }
  3571. }
  3572. return (ptrdiff_t)j;
  3573. }
  3574. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3575. * This function must tolerate situations when connection info is not
  3576. * set up, for example if request parsing failed. */
  3577. static int
  3578. should_keep_alive(const struct mg_connection *conn)
  3579. {
  3580. const char *http_version;
  3581. const char *header;
  3582. /* First satisfy needs of the server */
  3583. if ((conn == NULL) || conn->must_close) {
  3584. /* Close, if civetweb framework needs to close */
  3585. return 0;
  3586. }
  3587. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3588. /* Close, if keep alive is not enabled */
  3589. return 0;
  3590. }
  3591. /* Check explicit wish of the client */
  3592. header = mg_get_header(conn, "Connection");
  3593. if (header) {
  3594. /* If there is a connection header from the client, obey */
  3595. if (header_has_option(header, "keep-alive")) {
  3596. return 1;
  3597. }
  3598. return 0;
  3599. }
  3600. /* Use default of the standard */
  3601. http_version = get_http_version(conn);
  3602. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3603. /* HTTP 1.1 default is keep alive */
  3604. return 1;
  3605. }
  3606. /* HTTP 1.0 (and earlier) default is to close the connection */
  3607. return 0;
  3608. }
  3609. static int
  3610. should_decode_url(const struct mg_connection *conn)
  3611. {
  3612. if (!conn || !conn->dom_ctx) {
  3613. return 0;
  3614. }
  3615. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3616. }
  3617. static const char *
  3618. suggest_connection_header(const struct mg_connection *conn)
  3619. {
  3620. return should_keep_alive(conn) ? "keep-alive" : "close";
  3621. }
  3622. static int
  3623. send_no_cache_header(struct mg_connection *conn)
  3624. {
  3625. /* Send all current and obsolete cache opt-out directives. */
  3626. return mg_printf(conn,
  3627. "Cache-Control: no-cache, no-store, "
  3628. "must-revalidate, private, max-age=0\r\n"
  3629. "Pragma: no-cache\r\n"
  3630. "Expires: 0\r\n");
  3631. }
  3632. static int
  3633. send_static_cache_header(struct mg_connection *conn)
  3634. {
  3635. #if !defined(NO_CACHING)
  3636. /* Read the server config to check how long a file may be cached.
  3637. * The configuration is in seconds. */
  3638. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3639. if (max_age <= 0) {
  3640. /* 0 means "do not cache". All values <0 are reserved
  3641. * and may be used differently in the future. */
  3642. /* If a file should not be cached, do not only send
  3643. * max-age=0, but also pragmas and Expires headers. */
  3644. return send_no_cache_header(conn);
  3645. }
  3646. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3647. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3648. /* See also https://www.mnot.net/cache_docs/ */
  3649. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3650. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3651. * leap
  3652. * year to 31622400 seconds. For the moment, we just send whatever has
  3653. * been configured, still the behavior for >1 year should be considered
  3654. * as undefined. */
  3655. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3656. #else /* NO_CACHING */
  3657. return send_no_cache_header(conn);
  3658. #endif /* !NO_CACHING */
  3659. }
  3660. static int
  3661. send_additional_header(struct mg_connection *conn)
  3662. {
  3663. int i = 0;
  3664. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3665. #if !defined(NO_SSL)
  3666. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3667. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3668. if (max_age >= 0) {
  3669. i += mg_printf(conn,
  3670. "Strict-Transport-Security: max-age=%u\r\n",
  3671. (unsigned)max_age);
  3672. }
  3673. }
  3674. #endif
  3675. if (header && header[0]) {
  3676. i += mg_printf(conn, "%s\r\n", header);
  3677. }
  3678. return i;
  3679. }
  3680. #if !defined(NO_FILESYSTEMS)
  3681. static void handle_file_based_request(struct mg_connection *conn,
  3682. const char *path,
  3683. struct mg_file *filep);
  3684. #endif /* NO_FILESYSTEMS */
  3685. const char *
  3686. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3687. {
  3688. /* See IANA HTTP status code assignment:
  3689. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3690. */
  3691. switch (response_code) {
  3692. /* RFC2616 Section 10.1 - Informational 1xx */
  3693. case 100:
  3694. return "Continue"; /* RFC2616 Section 10.1.1 */
  3695. case 101:
  3696. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3697. case 102:
  3698. return "Processing"; /* RFC2518 Section 10.1 */
  3699. /* RFC2616 Section 10.2 - Successful 2xx */
  3700. case 200:
  3701. return "OK"; /* RFC2616 Section 10.2.1 */
  3702. case 201:
  3703. return "Created"; /* RFC2616 Section 10.2.2 */
  3704. case 202:
  3705. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3706. case 203:
  3707. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3708. case 204:
  3709. return "No Content"; /* RFC2616 Section 10.2.5 */
  3710. case 205:
  3711. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3712. case 206:
  3713. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3714. case 207:
  3715. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3716. */
  3717. case 208:
  3718. return "Already Reported"; /* RFC5842 Section 7.1 */
  3719. case 226:
  3720. return "IM used"; /* RFC3229 Section 10.4.1 */
  3721. /* RFC2616 Section 10.3 - Redirection 3xx */
  3722. case 300:
  3723. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3724. case 301:
  3725. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3726. case 302:
  3727. return "Found"; /* RFC2616 Section 10.3.3 */
  3728. case 303:
  3729. return "See Other"; /* RFC2616 Section 10.3.4 */
  3730. case 304:
  3731. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3732. case 305:
  3733. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3734. case 307:
  3735. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3736. case 308:
  3737. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3738. /* RFC2616 Section 10.4 - Client Error 4xx */
  3739. case 400:
  3740. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3741. case 401:
  3742. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3743. case 402:
  3744. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3745. case 403:
  3746. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3747. case 404:
  3748. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3749. case 405:
  3750. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3751. case 406:
  3752. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3753. case 407:
  3754. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3755. case 408:
  3756. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3757. case 409:
  3758. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3759. case 410:
  3760. return "Gone"; /* RFC2616 Section 10.4.11 */
  3761. case 411:
  3762. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3763. case 412:
  3764. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3765. case 413:
  3766. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3767. case 414:
  3768. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3769. case 415:
  3770. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3771. case 416:
  3772. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3773. */
  3774. case 417:
  3775. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3776. case 421:
  3777. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3778. case 422:
  3779. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3780. * Section 11.2 */
  3781. case 423:
  3782. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3783. case 424:
  3784. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3785. * Section 11.4 */
  3786. case 426:
  3787. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3788. case 428:
  3789. return "Precondition Required"; /* RFC 6585, Section 3 */
  3790. case 429:
  3791. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3792. case 431:
  3793. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3794. case 451:
  3795. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3796. * Section 3 */
  3797. /* RFC2616 Section 10.5 - Server Error 5xx */
  3798. case 500:
  3799. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3800. case 501:
  3801. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3802. case 502:
  3803. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3804. case 503:
  3805. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3806. case 504:
  3807. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3808. case 505:
  3809. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3810. case 506:
  3811. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3812. case 507:
  3813. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3814. * Section 11.5 */
  3815. case 508:
  3816. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3817. case 510:
  3818. return "Not Extended"; /* RFC 2774, Section 7 */
  3819. case 511:
  3820. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3821. /* Other status codes, not shown in the IANA HTTP status code
  3822. * assignment.
  3823. * E.g., "de facto" standards due to common use, ... */
  3824. case 418:
  3825. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3826. case 419:
  3827. return "Authentication Timeout"; /* common use */
  3828. case 420:
  3829. return "Enhance Your Calm"; /* common use */
  3830. case 440:
  3831. return "Login Timeout"; /* common use */
  3832. case 509:
  3833. return "Bandwidth Limit Exceeded"; /* common use */
  3834. default:
  3835. /* This error code is unknown. This should not happen. */
  3836. if (conn) {
  3837. mg_cry_internal(conn,
  3838. "Unknown HTTP response code: %u",
  3839. response_code);
  3840. }
  3841. /* Return at least a category according to RFC 2616 Section 10. */
  3842. if (response_code >= 100 && response_code < 200) {
  3843. /* Unknown informational status code */
  3844. return "Information";
  3845. }
  3846. if (response_code >= 200 && response_code < 300) {
  3847. /* Unknown success code */
  3848. return "Success";
  3849. }
  3850. if (response_code >= 300 && response_code < 400) {
  3851. /* Unknown redirection code */
  3852. return "Redirection";
  3853. }
  3854. if (response_code >= 400 && response_code < 500) {
  3855. /* Unknown request error code */
  3856. return "Client Error";
  3857. }
  3858. if (response_code >= 500 && response_code < 600) {
  3859. /* Unknown server error code */
  3860. return "Server Error";
  3861. }
  3862. /* Response code not even within reasonable range */
  3863. return "";
  3864. }
  3865. }
  3866. static int
  3867. mg_send_http_error_impl(struct mg_connection *conn,
  3868. int status,
  3869. const char *fmt,
  3870. va_list args)
  3871. {
  3872. char errmsg_buf[MG_BUF_LEN];
  3873. va_list ap;
  3874. int has_body;
  3875. char date[64];
  3876. time_t curtime = time(NULL);
  3877. #if !defined(NO_FILESYSTEMS)
  3878. char path_buf[PATH_MAX];
  3879. int len, i, page_handler_found, scope, truncated;
  3880. const char *error_handler = NULL;
  3881. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3882. const char *error_page_file_ext, *tstr;
  3883. #endif /* NO_FILESYSTEMS */
  3884. int handled_by_callback = 0;
  3885. const char *status_text = mg_get_response_code_text(conn, status);
  3886. if ((conn == NULL) || (fmt == NULL)) {
  3887. return -2;
  3888. }
  3889. /* Set status (for log) */
  3890. conn->status_code = status;
  3891. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3892. has_body = ((status > 199) && (status != 204) && (status != 304));
  3893. /* Prepare message in buf, if required */
  3894. if (has_body
  3895. || (!conn->in_error_handler
  3896. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3897. /* Store error message in errmsg_buf */
  3898. va_copy(ap, args);
  3899. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3900. va_end(ap);
  3901. /* In a debug build, print all html errors */
  3902. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3903. }
  3904. /* If there is a http_error callback, call it.
  3905. * But don't do it recursively, if callback calls mg_send_http_error again.
  3906. */
  3907. if (!conn->in_error_handler
  3908. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3909. /* Mark in_error_handler to avoid recursion and call user callback. */
  3910. conn->in_error_handler = 1;
  3911. handled_by_callback =
  3912. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3913. == 0);
  3914. conn->in_error_handler = 0;
  3915. }
  3916. if (!handled_by_callback) {
  3917. /* Check for recursion */
  3918. if (conn->in_error_handler) {
  3919. DEBUG_TRACE(
  3920. "Recursion when handling error %u - fall back to default",
  3921. status);
  3922. #if !defined(NO_FILESYSTEMS)
  3923. } else {
  3924. /* Send user defined error pages, if defined */
  3925. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3926. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3927. page_handler_found = 0;
  3928. if (error_handler != NULL) {
  3929. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3930. switch (scope) {
  3931. case 1: /* Handler for specific error, e.g. 404 error */
  3932. mg_snprintf(conn,
  3933. &truncated,
  3934. path_buf,
  3935. sizeof(path_buf) - 32,
  3936. "%serror%03u.",
  3937. error_handler,
  3938. status);
  3939. break;
  3940. case 2: /* Handler for error group, e.g., 5xx error
  3941. * handler
  3942. * for all server errors (500-599) */
  3943. mg_snprintf(conn,
  3944. &truncated,
  3945. path_buf,
  3946. sizeof(path_buf) - 32,
  3947. "%serror%01uxx.",
  3948. error_handler,
  3949. status / 100);
  3950. break;
  3951. default: /* Handler for all errors */
  3952. mg_snprintf(conn,
  3953. &truncated,
  3954. path_buf,
  3955. sizeof(path_buf) - 32,
  3956. "%serror.",
  3957. error_handler);
  3958. break;
  3959. }
  3960. /* String truncation in buf may only occur if
  3961. * error_handler is too long. This string is
  3962. * from the config, not from a client. */
  3963. (void)truncated;
  3964. len = (int)strlen(path_buf);
  3965. tstr = strchr(error_page_file_ext, '.');
  3966. while (tstr) {
  3967. for (i = 1;
  3968. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3969. i++) {
  3970. /* buffer overrun is not possible here, since
  3971. * (i < 32) && (len < sizeof(path_buf) - 32)
  3972. * ==> (i + len) < sizeof(path_buf) */
  3973. path_buf[len + i - 1] = tstr[i];
  3974. }
  3975. /* buffer overrun is not possible here, since
  3976. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3977. * ==> (i + len) <= sizeof(path_buf) */
  3978. path_buf[len + i - 1] = 0;
  3979. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3980. DEBUG_TRACE("Check error page %s - found",
  3981. path_buf);
  3982. page_handler_found = 1;
  3983. break;
  3984. }
  3985. DEBUG_TRACE("Check error page %s - not found",
  3986. path_buf);
  3987. tstr = strchr(tstr + i, '.');
  3988. }
  3989. }
  3990. }
  3991. if (page_handler_found) {
  3992. conn->in_error_handler = 1;
  3993. handle_file_based_request(conn, path_buf, &error_page_file);
  3994. conn->in_error_handler = 0;
  3995. return 0;
  3996. }
  3997. #endif /* NO_FILESYSTEMS */
  3998. }
  3999. /* No custom error page. Send default error page. */
  4000. gmt_time_string(date, sizeof(date), &curtime);
  4001. conn->must_close = 1;
  4002. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  4003. send_no_cache_header(conn);
  4004. send_additional_header(conn);
  4005. if (has_body) {
  4006. mg_printf(conn,
  4007. "%s",
  4008. "Content-Type: text/plain; charset=utf-8\r\n");
  4009. }
  4010. mg_printf(conn,
  4011. "Date: %s\r\n"
  4012. "Connection: close\r\n\r\n",
  4013. date);
  4014. /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */
  4015. if (has_body) {
  4016. /* For other errors, send a generic error message. */
  4017. mg_printf(conn, "Error %d: %s\n", status, status_text);
  4018. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  4019. } else {
  4020. /* No body allowed. Close the connection. */
  4021. DEBUG_TRACE("Error %i", status);
  4022. }
  4023. }
  4024. return 0;
  4025. }
  4026. int
  4027. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  4028. {
  4029. va_list ap;
  4030. int ret;
  4031. va_start(ap, fmt);
  4032. ret = mg_send_http_error_impl(conn, status, fmt, ap);
  4033. va_end(ap);
  4034. return ret;
  4035. }
  4036. int
  4037. mg_send_http_ok(struct mg_connection *conn,
  4038. const char *mime_type,
  4039. long long content_length)
  4040. {
  4041. char date[64];
  4042. time_t curtime = time(NULL);
  4043. if ((mime_type == NULL) || (*mime_type == 0)) {
  4044. /* Parameter error */
  4045. return -2;
  4046. }
  4047. gmt_time_string(date, sizeof(date), &curtime);
  4048. mg_printf(conn,
  4049. "HTTP/1.1 200 OK\r\n"
  4050. "Content-Type: %s\r\n"
  4051. "Date: %s\r\n"
  4052. "Connection: %s\r\n",
  4053. mime_type,
  4054. date,
  4055. suggest_connection_header(conn));
  4056. send_no_cache_header(conn);
  4057. send_additional_header(conn);
  4058. if (content_length < 0) {
  4059. mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n");
  4060. } else {
  4061. mg_printf(conn,
  4062. "Content-Length: %" UINT64_FMT "\r\n\r\n",
  4063. (uint64_t)content_length);
  4064. }
  4065. return 0;
  4066. }
  4067. int
  4068. mg_send_http_redirect(struct mg_connection *conn,
  4069. const char *target_url,
  4070. int redirect_code)
  4071. {
  4072. /* Send a 30x redirect response.
  4073. *
  4074. * Redirect types (status codes):
  4075. *
  4076. * Status | Perm/Temp | Method | Version
  4077. * 301 | permanent | POST->GET undefined | HTTP/1.0
  4078. * 302 | temporary | POST->GET undefined | HTTP/1.0
  4079. * 303 | temporary | always use GET | HTTP/1.1
  4080. * 307 | temporary | always keep method | HTTP/1.1
  4081. * 308 | permanent | always keep method | HTTP/1.1
  4082. */
  4083. const char *redirect_text;
  4084. int ret;
  4085. size_t content_len = 0;
  4086. char reply[MG_BUF_LEN];
  4087. /* In case redirect_code=0, use 307. */
  4088. if (redirect_code == 0) {
  4089. redirect_code = 307;
  4090. }
  4091. /* In case redirect_code is none of the above, return error. */
  4092. if ((redirect_code != 301) && (redirect_code != 302)
  4093. && (redirect_code != 303) && (redirect_code != 307)
  4094. && (redirect_code != 308)) {
  4095. /* Parameter error */
  4096. return -2;
  4097. }
  4098. /* Get proper text for response code */
  4099. redirect_text = mg_get_response_code_text(conn, redirect_code);
  4100. /* If target_url is not defined, redirect to "/". */
  4101. if ((target_url == NULL) || (*target_url == 0)) {
  4102. target_url = "/";
  4103. }
  4104. #if defined(MG_SEND_REDIRECT_BODY)
  4105. /* TODO: condition name? */
  4106. /* Prepare a response body with a hyperlink.
  4107. *
  4108. * According to RFC2616 (and RFC1945 before):
  4109. * Unless the request method was HEAD, the entity of the
  4110. * response SHOULD contain a short hypertext note with a hyperlink to
  4111. * the new URI(s).
  4112. *
  4113. * However, this response body is not useful in M2M communication.
  4114. * Probably the original reason in the RFC was, clients not supporting
  4115. * a 30x HTTP redirect could still show the HTML page and let the user
  4116. * press the link. Since current browsers support 30x HTTP, the additional
  4117. * HTML body does not seem to make sense anymore.
  4118. *
  4119. * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"),
  4120. * but it only notes:
  4121. * The server's response payload usually contains a short
  4122. * hypertext note with a hyperlink to the new URI(s).
  4123. *
  4124. * Deactivated by default. If you need the 30x body, set the define.
  4125. */
  4126. mg_snprintf(
  4127. conn,
  4128. NULL /* ignore truncation */,
  4129. reply,
  4130. sizeof(reply),
  4131. "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>",
  4132. redirect_text,
  4133. target_url,
  4134. target_url);
  4135. content_len = strlen(reply);
  4136. #else
  4137. reply[0] = 0;
  4138. #endif
  4139. /* Do not send any additional header. For all other options,
  4140. * including caching, there are suitable defaults. */
  4141. ret = mg_printf(conn,
  4142. "HTTP/1.1 %i %s\r\n"
  4143. "Location: %s\r\n"
  4144. "Content-Length: %u\r\n"
  4145. "Connection: %s\r\n\r\n",
  4146. redirect_code,
  4147. redirect_text,
  4148. target_url,
  4149. (unsigned int)content_len,
  4150. suggest_connection_header(conn));
  4151. /* Send response body */
  4152. if (ret > 0) {
  4153. /* ... unless it is a HEAD request */
  4154. if (0 != strcmp(conn->request_info.request_method, "HEAD")) {
  4155. ret = mg_write(conn, reply, content_len);
  4156. }
  4157. }
  4158. return (ret > 0) ? ret : -1;
  4159. }
  4160. #if defined(_WIN32)
  4161. /* Create substitutes for POSIX functions in Win32. */
  4162. #if defined(GCC_DIAGNOSTIC)
  4163. /* Show no warning in case system functions are not used. */
  4164. #pragma GCC diagnostic push
  4165. #pragma GCC diagnostic ignored "-Wunused-function"
  4166. #endif
  4167. static int
  4168. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  4169. {
  4170. (void)unused;
  4171. /* Always initialize as PTHREAD_MUTEX_RECURSIVE */
  4172. InitializeCriticalSection(&mutex->sec);
  4173. return 0;
  4174. }
  4175. static int
  4176. pthread_mutex_destroy(pthread_mutex_t *mutex)
  4177. {
  4178. DeleteCriticalSection(&mutex->sec);
  4179. return 0;
  4180. }
  4181. static int
  4182. pthread_mutex_lock(pthread_mutex_t *mutex)
  4183. {
  4184. EnterCriticalSection(&mutex->sec);
  4185. return 0;
  4186. }
  4187. static int
  4188. pthread_mutex_unlock(pthread_mutex_t *mutex)
  4189. {
  4190. LeaveCriticalSection(&mutex->sec);
  4191. return 0;
  4192. }
  4193. FUNCTION_MAY_BE_UNUSED
  4194. static int
  4195. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  4196. {
  4197. (void)unused;
  4198. (void)pthread_mutex_init(&cv->threadIdSec, &pthread_mutex_attr);
  4199. cv->waiting_thread = NULL;
  4200. return 0;
  4201. }
  4202. FUNCTION_MAY_BE_UNUSED
  4203. static int
  4204. pthread_cond_timedwait(pthread_cond_t *cv,
  4205. pthread_mutex_t *mutex,
  4206. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  4207. {
  4208. struct mg_workerTLS **ptls,
  4209. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  4210. int ok;
  4211. int64_t nsnow, nswaitabs, nswaitrel;
  4212. DWORD mswaitrel;
  4213. pthread_mutex_lock(&cv->threadIdSec);
  4214. /* Add this thread to cv's waiting list */
  4215. ptls = &cv->waiting_thread;
  4216. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  4217. ;
  4218. tls->next_waiting_thread = NULL;
  4219. *ptls = tls;
  4220. pthread_mutex_unlock(&cv->threadIdSec);
  4221. if (abstime) {
  4222. nsnow = mg_get_current_time_ns();
  4223. nswaitabs =
  4224. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  4225. nswaitrel = nswaitabs - nsnow;
  4226. if (nswaitrel < 0) {
  4227. nswaitrel = 0;
  4228. }
  4229. mswaitrel = (DWORD)(nswaitrel / 1000000);
  4230. } else {
  4231. mswaitrel = (DWORD)INFINITE;
  4232. }
  4233. pthread_mutex_unlock(mutex);
  4234. ok = (WAIT_OBJECT_0
  4235. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  4236. if (!ok) {
  4237. ok = 1;
  4238. pthread_mutex_lock(&cv->threadIdSec);
  4239. ptls = &cv->waiting_thread;
  4240. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  4241. if (*ptls == tls) {
  4242. *ptls = tls->next_waiting_thread;
  4243. ok = 0;
  4244. break;
  4245. }
  4246. }
  4247. pthread_mutex_unlock(&cv->threadIdSec);
  4248. if (ok) {
  4249. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  4250. (DWORD)INFINITE);
  4251. }
  4252. }
  4253. /* This thread has been removed from cv's waiting list */
  4254. pthread_mutex_lock(mutex);
  4255. return ok ? 0 : -1;
  4256. }
  4257. FUNCTION_MAY_BE_UNUSED
  4258. static int
  4259. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4260. {
  4261. return pthread_cond_timedwait(cv, mutex, NULL);
  4262. }
  4263. FUNCTION_MAY_BE_UNUSED
  4264. static int
  4265. pthread_cond_signal(pthread_cond_t *cv)
  4266. {
  4267. HANDLE wkup = NULL;
  4268. BOOL ok = FALSE;
  4269. pthread_mutex_lock(&cv->threadIdSec);
  4270. if (cv->waiting_thread) {
  4271. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4272. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4273. ok = SetEvent(wkup);
  4274. DEBUG_ASSERT(ok);
  4275. }
  4276. pthread_mutex_unlock(&cv->threadIdSec);
  4277. return ok ? 0 : 1;
  4278. }
  4279. FUNCTION_MAY_BE_UNUSED
  4280. static int
  4281. pthread_cond_broadcast(pthread_cond_t *cv)
  4282. {
  4283. pthread_mutex_lock(&cv->threadIdSec);
  4284. while (cv->waiting_thread) {
  4285. pthread_cond_signal(cv);
  4286. }
  4287. pthread_mutex_unlock(&cv->threadIdSec);
  4288. return 0;
  4289. }
  4290. FUNCTION_MAY_BE_UNUSED
  4291. static int
  4292. pthread_cond_destroy(pthread_cond_t *cv)
  4293. {
  4294. pthread_mutex_lock(&cv->threadIdSec);
  4295. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4296. pthread_mutex_unlock(&cv->threadIdSec);
  4297. pthread_mutex_destroy(&cv->threadIdSec);
  4298. return 0;
  4299. }
  4300. #if defined(ALTERNATIVE_QUEUE)
  4301. FUNCTION_MAY_BE_UNUSED
  4302. static void *
  4303. event_create(void)
  4304. {
  4305. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4306. }
  4307. FUNCTION_MAY_BE_UNUSED
  4308. static int
  4309. event_wait(void *eventhdl)
  4310. {
  4311. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4312. return (res == WAIT_OBJECT_0);
  4313. }
  4314. FUNCTION_MAY_BE_UNUSED
  4315. static int
  4316. event_signal(void *eventhdl)
  4317. {
  4318. return (int)SetEvent((HANDLE)eventhdl);
  4319. }
  4320. FUNCTION_MAY_BE_UNUSED
  4321. static void
  4322. event_destroy(void *eventhdl)
  4323. {
  4324. CloseHandle((HANDLE)eventhdl);
  4325. }
  4326. #endif
  4327. #if defined(GCC_DIAGNOSTIC)
  4328. /* Enable unused function warning again */
  4329. #pragma GCC diagnostic pop
  4330. #endif
  4331. /* For Windows, change all slashes to backslashes in path names. */
  4332. static void
  4333. change_slashes_to_backslashes(char *path)
  4334. {
  4335. int i;
  4336. for (i = 0; path[i] != '\0'; i++) {
  4337. if (path[i] == '/') {
  4338. path[i] = '\\';
  4339. }
  4340. /* remove double backslash (check i > 0 to preserve UNC paths,
  4341. * like \\server\file.txt) */
  4342. if ((path[i] == '\\') && (i > 0)) {
  4343. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4344. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4345. }
  4346. }
  4347. }
  4348. }
  4349. static int
  4350. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4351. {
  4352. int diff;
  4353. do {
  4354. diff = ((*s1 >= L'A') && (*s1 <= L'Z') ? (*s1 - L'A' + L'a') : *s1)
  4355. - ((*s2 >= L'A') && (*s2 <= L'Z') ? (*s2 - L'A' + L'a') : *s2);
  4356. s1++;
  4357. s2++;
  4358. } while ((diff == 0) && (s1[-1] != L'\0'));
  4359. return diff;
  4360. }
  4361. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4362. * wbuf and wbuf_len is a target buffer and its length. */
  4363. static void
  4364. path_to_unicode(const struct mg_connection *conn,
  4365. const char *path,
  4366. wchar_t *wbuf,
  4367. size_t wbuf_len)
  4368. {
  4369. char buf[PATH_MAX], buf2[PATH_MAX];
  4370. wchar_t wbuf2[W_PATH_MAX + 1];
  4371. DWORD long_len, err;
  4372. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4373. mg_strlcpy(buf, path, sizeof(buf));
  4374. change_slashes_to_backslashes(buf);
  4375. /* Convert to Unicode and back. If doubly-converted string does not
  4376. * match the original, something is fishy, reject. */
  4377. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4378. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4379. WideCharToMultiByte(
  4380. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4381. if (strcmp(buf, buf2) != 0) {
  4382. wbuf[0] = L'\0';
  4383. }
  4384. /* Windows file systems are not case sensitive, but you can still use
  4385. * uppercase and lowercase letters (on all modern file systems).
  4386. * The server can check if the URI uses the same upper/lowercase
  4387. * letters an the file system, effectively making Windows servers
  4388. * case sensitive (like Linux servers are). It is still not possible
  4389. * to use two files with the same name in different cases on Windows
  4390. * (like /a and /A) - this would be possible in Linux.
  4391. * As a default, Windows is not case sensitive, but the case sensitive
  4392. * file name check can be activated by an additional configuration. */
  4393. if (conn) {
  4394. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4395. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4396. "yes")) {
  4397. /* Use case sensitive compare function */
  4398. fcompare = wcscmp;
  4399. }
  4400. }
  4401. (void)conn; /* conn is currently unused */
  4402. #if !defined(_WIN32_WCE)
  4403. /* Only accept a full file path, not a Windows short (8.3) path. */
  4404. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4405. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4406. if (long_len == 0) {
  4407. err = GetLastError();
  4408. if (err == ERROR_FILE_NOT_FOUND) {
  4409. /* File does not exist. This is not always a problem here. */
  4410. return;
  4411. }
  4412. }
  4413. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4414. /* Short name is used. */
  4415. wbuf[0] = L'\0';
  4416. }
  4417. #else
  4418. (void)long_len;
  4419. (void)wbuf2;
  4420. (void)err;
  4421. if (strchr(path, '~')) {
  4422. wbuf[0] = L'\0';
  4423. }
  4424. #endif
  4425. }
  4426. #if !defined(NO_FILESYSTEMS)
  4427. static int
  4428. mg_stat(const struct mg_connection *conn,
  4429. const char *path,
  4430. struct mg_file_stat *filep)
  4431. {
  4432. wchar_t wbuf[W_PATH_MAX];
  4433. WIN32_FILE_ATTRIBUTE_DATA info;
  4434. time_t creation_time;
  4435. size_t len;
  4436. if (!filep) {
  4437. return 0;
  4438. }
  4439. memset(filep, 0, sizeof(*filep));
  4440. if (conn && is_file_in_memory(conn, path)) {
  4441. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4442. * memset */
  4443. /* Quick fix (for 1.9.x): */
  4444. /* mg_stat must fill all fields, also for files in memory */
  4445. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4446. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4447. filep->size = tmp_file.stat.size;
  4448. filep->location = 2;
  4449. /* TODO: for 1.10: restructure how files in memory are handled */
  4450. /* The "file in memory" feature is a candidate for deletion.
  4451. * Please join the discussion at
  4452. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4453. */
  4454. filep->last_modified = time(NULL); /* TODO */
  4455. /* last_modified = now ... assumes the file may change during
  4456. * runtime,
  4457. * so every mg_fopen call may return different data */
  4458. /* last_modified = conn->phys_ctx.start_time;
  4459. * May be used it the data does not change during runtime. This
  4460. * allows
  4461. * browser caching. Since we do not know, we have to assume the file
  4462. * in memory may change. */
  4463. return 1;
  4464. }
  4465. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4466. /* Windows happily opens files with some garbage at the end of file name.
  4467. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4468. * "a.cgi", despite one would expect an error back. */
  4469. len = strlen(path);
  4470. if ((len > 0) && (path[len - 1] != ' ') && (path[len - 1] != '.')
  4471. && (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0)) {
  4472. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4473. filep->last_modified =
  4474. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4475. info.ftLastWriteTime.dwHighDateTime);
  4476. /* On Windows, the file creation time can be higher than the
  4477. * modification time, e.g. when a file is copied.
  4478. * Since the Last-Modified timestamp is used for caching
  4479. * it should be based on the most recent timestamp. */
  4480. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4481. info.ftCreationTime.dwHighDateTime);
  4482. if (creation_time > filep->last_modified) {
  4483. filep->last_modified = creation_time;
  4484. }
  4485. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4486. return 1;
  4487. }
  4488. return 0;
  4489. }
  4490. #endif
  4491. static int
  4492. mg_remove(const struct mg_connection *conn, const char *path)
  4493. {
  4494. wchar_t wbuf[W_PATH_MAX];
  4495. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4496. return DeleteFileW(wbuf) ? 0 : -1;
  4497. }
  4498. static int
  4499. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4500. {
  4501. wchar_t wbuf[W_PATH_MAX];
  4502. (void)mode;
  4503. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4504. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4505. }
  4506. /* Create substitutes for POSIX functions in Win32. */
  4507. #if defined(GCC_DIAGNOSTIC)
  4508. /* Show no warning in case system functions are not used. */
  4509. #pragma GCC diagnostic push
  4510. #pragma GCC diagnostic ignored "-Wunused-function"
  4511. #endif
  4512. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4513. FUNCTION_MAY_BE_UNUSED
  4514. static DIR *
  4515. mg_opendir(const struct mg_connection *conn, const char *name)
  4516. {
  4517. DIR *dir = NULL;
  4518. wchar_t wpath[W_PATH_MAX];
  4519. DWORD attrs;
  4520. if (name == NULL) {
  4521. SetLastError(ERROR_BAD_ARGUMENTS);
  4522. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4523. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4524. } else {
  4525. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4526. attrs = GetFileAttributesW(wpath);
  4527. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4528. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4529. (void)wcscat(wpath, L"\\*");
  4530. dir->handle = FindFirstFileW(wpath, &dir->info);
  4531. dir->result.d_name[0] = '\0';
  4532. } else {
  4533. mg_free(dir);
  4534. dir = NULL;
  4535. }
  4536. }
  4537. return dir;
  4538. }
  4539. FUNCTION_MAY_BE_UNUSED
  4540. static int
  4541. mg_closedir(DIR *dir)
  4542. {
  4543. int result = 0;
  4544. if (dir != NULL) {
  4545. if (dir->handle != INVALID_HANDLE_VALUE)
  4546. result = FindClose(dir->handle) ? 0 : -1;
  4547. mg_free(dir);
  4548. } else {
  4549. result = -1;
  4550. SetLastError(ERROR_BAD_ARGUMENTS);
  4551. }
  4552. return result;
  4553. }
  4554. FUNCTION_MAY_BE_UNUSED
  4555. static struct dirent *
  4556. mg_readdir(DIR *dir)
  4557. {
  4558. struct dirent *result = 0;
  4559. if (dir) {
  4560. if (dir->handle != INVALID_HANDLE_VALUE) {
  4561. result = &dir->result;
  4562. (void)WideCharToMultiByte(CP_UTF8,
  4563. 0,
  4564. dir->info.cFileName,
  4565. -1,
  4566. result->d_name,
  4567. sizeof(result->d_name),
  4568. NULL,
  4569. NULL);
  4570. if (!FindNextFileW(dir->handle, &dir->info)) {
  4571. (void)FindClose(dir->handle);
  4572. dir->handle = INVALID_HANDLE_VALUE;
  4573. }
  4574. } else {
  4575. SetLastError(ERROR_FILE_NOT_FOUND);
  4576. }
  4577. } else {
  4578. SetLastError(ERROR_BAD_ARGUMENTS);
  4579. }
  4580. return result;
  4581. }
  4582. #if !defined(HAVE_POLL)
  4583. #undef POLLIN
  4584. #undef POLLPRI
  4585. #undef POLLOUT
  4586. #define POLLIN (1) /* Data ready - read will not block. */
  4587. #define POLLPRI (2) /* Priority data ready. */
  4588. #define POLLOUT (4) /* Send queue not full - write will not block. */
  4589. FUNCTION_MAY_BE_UNUSED
  4590. static int
  4591. poll(struct mg_pollfd *pfd, unsigned int n, int milliseconds)
  4592. {
  4593. struct timeval tv;
  4594. fd_set rset;
  4595. fd_set wset;
  4596. unsigned int i;
  4597. int result;
  4598. SOCKET maxfd = 0;
  4599. memset(&tv, 0, sizeof(tv));
  4600. tv.tv_sec = milliseconds / 1000;
  4601. tv.tv_usec = (milliseconds % 1000) * 1000;
  4602. FD_ZERO(&rset);
  4603. FD_ZERO(&wset);
  4604. for (i = 0; i < n; i++) {
  4605. if (pfd[i].events & POLLIN) {
  4606. FD_SET(pfd[i].fd, &rset);
  4607. }
  4608. if (pfd[i].events & POLLOUT) {
  4609. FD_SET(pfd[i].fd, &wset);
  4610. }
  4611. pfd[i].revents = 0;
  4612. if (pfd[i].fd > maxfd) {
  4613. maxfd = pfd[i].fd;
  4614. }
  4615. }
  4616. if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) {
  4617. for (i = 0; i < n; i++) {
  4618. if (FD_ISSET(pfd[i].fd, &rset)) {
  4619. pfd[i].revents |= POLLIN;
  4620. }
  4621. if (FD_ISSET(pfd[i].fd, &wset)) {
  4622. pfd[i].revents |= POLLOUT;
  4623. }
  4624. }
  4625. }
  4626. /* We should subtract the time used in select from remaining
  4627. * "milliseconds", in particular if called from mg_poll with a
  4628. * timeout quantum.
  4629. * Unfortunately, the remaining time is not stored in "tv" in all
  4630. * implementations, so the result in "tv" must be considered undefined.
  4631. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4632. return result;
  4633. }
  4634. #endif /* HAVE_POLL */
  4635. #if defined(GCC_DIAGNOSTIC)
  4636. /* Enable unused function warning again */
  4637. #pragma GCC diagnostic pop
  4638. #endif
  4639. static void
  4640. set_close_on_exec(SOCKET sock,
  4641. const struct mg_connection *conn /* may be null */,
  4642. struct mg_context *ctx /* may be null */)
  4643. {
  4644. (void)conn; /* Unused. */
  4645. (void)ctx;
  4646. #if defined(_WIN32_WCE)
  4647. (void)sock;
  4648. #else
  4649. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4650. #endif
  4651. }
  4652. int
  4653. mg_start_thread(mg_thread_func_t f, void *p)
  4654. {
  4655. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4656. /* Compile-time option to control stack size, e.g.
  4657. * -DUSE_STACK_SIZE=16384
  4658. */
  4659. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4660. == ((uintptr_t)(-1L)))
  4661. ? -1
  4662. : 0);
  4663. #else
  4664. return (
  4665. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4666. ? -1
  4667. : 0);
  4668. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4669. }
  4670. /* Start a thread storing the thread context. */
  4671. static int
  4672. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4673. void *p,
  4674. pthread_t *threadidptr)
  4675. {
  4676. uintptr_t uip;
  4677. HANDLE threadhandle;
  4678. int result = -1;
  4679. uip = _beginthreadex(NULL, 0, f, p, 0, NULL);
  4680. threadhandle = (HANDLE)uip;
  4681. if ((uip != 0) && (threadidptr != NULL)) {
  4682. *threadidptr = threadhandle;
  4683. result = 0;
  4684. }
  4685. return result;
  4686. }
  4687. /* Wait for a thread to finish. */
  4688. static int
  4689. mg_join_thread(pthread_t threadid)
  4690. {
  4691. int result;
  4692. DWORD dwevent;
  4693. result = -1;
  4694. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4695. if (dwevent == WAIT_FAILED) {
  4696. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4697. } else {
  4698. if (dwevent == WAIT_OBJECT_0) {
  4699. CloseHandle(threadid);
  4700. result = 0;
  4701. }
  4702. }
  4703. return result;
  4704. }
  4705. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4706. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4707. /* Create substitutes for POSIX functions in Win32. */
  4708. #if defined(GCC_DIAGNOSTIC)
  4709. /* Show no warning in case system functions are not used. */
  4710. #pragma GCC diagnostic push
  4711. #pragma GCC diagnostic ignored "-Wunused-function"
  4712. #endif
  4713. FUNCTION_MAY_BE_UNUSED
  4714. static HANDLE
  4715. dlopen(const char *dll_name, int flags)
  4716. {
  4717. wchar_t wbuf[W_PATH_MAX];
  4718. (void)flags;
  4719. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4720. return LoadLibraryW(wbuf);
  4721. }
  4722. FUNCTION_MAY_BE_UNUSED
  4723. static int
  4724. dlclose(void *handle)
  4725. {
  4726. int result;
  4727. if (FreeLibrary((HMODULE)handle) != 0) {
  4728. result = 0;
  4729. } else {
  4730. result = -1;
  4731. }
  4732. return result;
  4733. }
  4734. #if defined(GCC_DIAGNOSTIC)
  4735. /* Enable unused function warning again */
  4736. #pragma GCC diagnostic pop
  4737. #endif
  4738. #endif
  4739. #if !defined(NO_CGI)
  4740. #define SIGKILL (0)
  4741. static int
  4742. kill(pid_t pid, int sig_num)
  4743. {
  4744. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4745. (void)CloseHandle((HANDLE)pid);
  4746. return 0;
  4747. }
  4748. #if !defined(WNOHANG)
  4749. #define WNOHANG (1)
  4750. #endif
  4751. static pid_t
  4752. waitpid(pid_t pid, int *status, int flags)
  4753. {
  4754. DWORD timeout = INFINITE;
  4755. DWORD waitres;
  4756. (void)status; /* Currently not used by any client here */
  4757. if ((flags | WNOHANG) == WNOHANG) {
  4758. timeout = 0;
  4759. }
  4760. waitres = WaitForSingleObject((HANDLE)pid, timeout);
  4761. if (waitres == WAIT_OBJECT_0) {
  4762. return pid;
  4763. }
  4764. if (waitres == WAIT_TIMEOUT) {
  4765. return 0;
  4766. }
  4767. return (pid_t)-1;
  4768. }
  4769. static void
  4770. trim_trailing_whitespaces(char *s)
  4771. {
  4772. char *e = s + strlen(s);
  4773. while ((e > s) && isspace((unsigned char)e[-1])) {
  4774. *(--e) = '\0';
  4775. }
  4776. }
  4777. static pid_t
  4778. spawn_process(struct mg_connection *conn,
  4779. const char *prog,
  4780. char *envblk,
  4781. char *envp[],
  4782. int fdin[2],
  4783. int fdout[2],
  4784. int fderr[2],
  4785. const char *dir)
  4786. {
  4787. HANDLE me;
  4788. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4789. cmdline[PATH_MAX], buf[PATH_MAX];
  4790. int truncated;
  4791. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4792. STARTUPINFOA si;
  4793. PROCESS_INFORMATION pi = {0};
  4794. (void)envp;
  4795. memset(&si, 0, sizeof(si));
  4796. si.cb = sizeof(si);
  4797. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4798. si.wShowWindow = SW_HIDE;
  4799. me = GetCurrentProcess();
  4800. DuplicateHandle(me,
  4801. (HANDLE)_get_osfhandle(fdin[0]),
  4802. me,
  4803. &si.hStdInput,
  4804. 0,
  4805. TRUE,
  4806. DUPLICATE_SAME_ACCESS);
  4807. DuplicateHandle(me,
  4808. (HANDLE)_get_osfhandle(fdout[1]),
  4809. me,
  4810. &si.hStdOutput,
  4811. 0,
  4812. TRUE,
  4813. DUPLICATE_SAME_ACCESS);
  4814. DuplicateHandle(me,
  4815. (HANDLE)_get_osfhandle(fderr[1]),
  4816. me,
  4817. &si.hStdError,
  4818. 0,
  4819. TRUE,
  4820. DUPLICATE_SAME_ACCESS);
  4821. /* Mark handles that should not be inherited. See
  4822. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4823. */
  4824. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4825. HANDLE_FLAG_INHERIT,
  4826. 0);
  4827. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4828. HANDLE_FLAG_INHERIT,
  4829. 0);
  4830. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4831. HANDLE_FLAG_INHERIT,
  4832. 0);
  4833. /* If CGI file is a script, try to read the interpreter line */
  4834. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4835. if (interp == NULL) {
  4836. buf[0] = buf[1] = '\0';
  4837. /* Read the first line of the script into the buffer */
  4838. mg_snprintf(
  4839. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4840. if (truncated) {
  4841. pi.hProcess = (pid_t)-1;
  4842. goto spawn_cleanup;
  4843. }
  4844. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4845. #if defined(MG_USE_OPEN_FILE)
  4846. p = (char *)file.access.membuf;
  4847. #else
  4848. p = (char *)NULL;
  4849. #endif
  4850. mg_fgets(buf, sizeof(buf), &file, &p);
  4851. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4852. buf[sizeof(buf) - 1] = '\0';
  4853. }
  4854. if ((buf[0] == '#') && (buf[1] == '!')) {
  4855. trim_trailing_whitespaces(buf + 2);
  4856. } else {
  4857. buf[2] = '\0';
  4858. }
  4859. interp = buf + 2;
  4860. }
  4861. if (interp[0] != '\0') {
  4862. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4863. interp = full_interp;
  4864. }
  4865. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4866. if (interp[0] != '\0') {
  4867. mg_snprintf(conn,
  4868. &truncated,
  4869. cmdline,
  4870. sizeof(cmdline),
  4871. "\"%s\" \"%s\\%s\"",
  4872. interp,
  4873. full_dir,
  4874. prog);
  4875. } else {
  4876. mg_snprintf(conn,
  4877. &truncated,
  4878. cmdline,
  4879. sizeof(cmdline),
  4880. "\"%s\\%s\"",
  4881. full_dir,
  4882. prog);
  4883. }
  4884. if (truncated) {
  4885. pi.hProcess = (pid_t)-1;
  4886. goto spawn_cleanup;
  4887. }
  4888. DEBUG_TRACE("Running [%s]", cmdline);
  4889. if (CreateProcessA(NULL,
  4890. cmdline,
  4891. NULL,
  4892. NULL,
  4893. TRUE,
  4894. CREATE_NEW_PROCESS_GROUP,
  4895. envblk,
  4896. NULL,
  4897. &si,
  4898. &pi)
  4899. == 0) {
  4900. mg_cry_internal(
  4901. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4902. pi.hProcess = (pid_t)-1;
  4903. /* goto spawn_cleanup; */
  4904. }
  4905. spawn_cleanup:
  4906. (void)CloseHandle(si.hStdOutput);
  4907. (void)CloseHandle(si.hStdError);
  4908. (void)CloseHandle(si.hStdInput);
  4909. if (pi.hThread != NULL) {
  4910. (void)CloseHandle(pi.hThread);
  4911. }
  4912. return (pid_t)pi.hProcess;
  4913. }
  4914. #endif /* !NO_CGI */
  4915. static int
  4916. set_blocking_mode(SOCKET sock)
  4917. {
  4918. unsigned long non_blocking = 0;
  4919. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4920. }
  4921. static int
  4922. set_non_blocking_mode(SOCKET sock)
  4923. {
  4924. unsigned long non_blocking = 1;
  4925. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4926. }
  4927. #else
  4928. #if !defined(NO_FILESYSTEMS)
  4929. static int
  4930. mg_stat(const struct mg_connection *conn,
  4931. const char *path,
  4932. struct mg_file_stat *filep)
  4933. {
  4934. struct stat st;
  4935. if (!filep) {
  4936. return 0;
  4937. }
  4938. memset(filep, 0, sizeof(*filep));
  4939. if (conn && is_file_in_memory(conn, path)) {
  4940. /* Quick fix (for 1.9.x): */
  4941. /* mg_stat must fill all fields, also for files in memory */
  4942. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4943. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4944. filep->size = tmp_file.stat.size;
  4945. filep->last_modified = time(NULL);
  4946. filep->location = 2;
  4947. /* TODO: remove legacy "files in memory" feature */
  4948. return 1;
  4949. }
  4950. if (0 == stat(path, &st)) {
  4951. filep->size = (uint64_t)(st.st_size);
  4952. filep->last_modified = st.st_mtime;
  4953. filep->is_directory = S_ISDIR(st.st_mode);
  4954. return 1;
  4955. }
  4956. return 0;
  4957. }
  4958. #endif /* NO_FILESYSTEMS */
  4959. static void
  4960. set_close_on_exec(int fd,
  4961. const struct mg_connection *conn /* may be null */,
  4962. struct mg_context *ctx /* may be null */)
  4963. {
  4964. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4965. if (conn || ctx) {
  4966. struct mg_connection fc;
  4967. mg_cry_internal((conn ? conn : fake_connection(&fc, ctx)),
  4968. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4969. __func__,
  4970. strerror(ERRNO));
  4971. }
  4972. }
  4973. }
  4974. int
  4975. mg_start_thread(mg_thread_func_t func, void *param)
  4976. {
  4977. pthread_t thread_id;
  4978. pthread_attr_t attr;
  4979. int result;
  4980. (void)pthread_attr_init(&attr);
  4981. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4982. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4983. /* Compile-time option to control stack size,
  4984. * e.g. -DUSE_STACK_SIZE=16384 */
  4985. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4986. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4987. result = pthread_create(&thread_id, &attr, func, param);
  4988. pthread_attr_destroy(&attr);
  4989. return result;
  4990. }
  4991. /* Start a thread storing the thread context. */
  4992. static int
  4993. mg_start_thread_with_id(mg_thread_func_t func,
  4994. void *param,
  4995. pthread_t *threadidptr)
  4996. {
  4997. pthread_t thread_id;
  4998. pthread_attr_t attr;
  4999. int result;
  5000. (void)pthread_attr_init(&attr);
  5001. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  5002. /* Compile-time option to control stack size,
  5003. * e.g. -DUSE_STACK_SIZE=16384 */
  5004. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  5005. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  5006. result = pthread_create(&thread_id, &attr, func, param);
  5007. pthread_attr_destroy(&attr);
  5008. if ((result == 0) && (threadidptr != NULL)) {
  5009. *threadidptr = thread_id;
  5010. }
  5011. return result;
  5012. }
  5013. /* Wait for a thread to finish. */
  5014. static int
  5015. mg_join_thread(pthread_t threadid)
  5016. {
  5017. int result;
  5018. result = pthread_join(threadid, NULL);
  5019. return result;
  5020. }
  5021. #if !defined(NO_CGI)
  5022. static pid_t
  5023. spawn_process(struct mg_connection *conn,
  5024. const char *prog,
  5025. char *envblk,
  5026. char *envp[],
  5027. int fdin[2],
  5028. int fdout[2],
  5029. int fderr[2],
  5030. const char *dir)
  5031. {
  5032. pid_t pid;
  5033. const char *interp;
  5034. (void)envblk;
  5035. if ((pid = fork()) == -1) {
  5036. /* Parent */
  5037. mg_cry_internal(conn, "%s: fork(): %s", __func__, strerror(ERRNO));
  5038. } else if (pid != 0) {
  5039. /* Make sure children close parent-side descriptors.
  5040. * The caller will close the child-side immediately. */
  5041. set_close_on_exec(fdin[1], conn, NULL); /* stdin write */
  5042. set_close_on_exec(fdout[0], conn, NULL); /* stdout read */
  5043. set_close_on_exec(fderr[0], conn, NULL); /* stderr read */
  5044. } else {
  5045. /* Child */
  5046. if (chdir(dir) != 0) {
  5047. mg_cry_internal(
  5048. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  5049. } else if (dup2(fdin[0], 0) == -1) {
  5050. mg_cry_internal(conn,
  5051. "%s: dup2(%d, 0): %s",
  5052. __func__,
  5053. fdin[0],
  5054. strerror(ERRNO));
  5055. } else if (dup2(fdout[1], 1) == -1) {
  5056. mg_cry_internal(conn,
  5057. "%s: dup2(%d, 1): %s",
  5058. __func__,
  5059. fdout[1],
  5060. strerror(ERRNO));
  5061. } else if (dup2(fderr[1], 2) == -1) {
  5062. mg_cry_internal(conn,
  5063. "%s: dup2(%d, 2): %s",
  5064. __func__,
  5065. fderr[1],
  5066. strerror(ERRNO));
  5067. } else {
  5068. struct sigaction sa;
  5069. /* Keep stderr and stdout in two different pipes.
  5070. * Stdout will be sent back to the client,
  5071. * stderr should go into a server error log. */
  5072. (void)close(fdin[0]);
  5073. (void)close(fdout[1]);
  5074. (void)close(fderr[1]);
  5075. /* Close write end fdin and read end fdout and fderr */
  5076. (void)close(fdin[1]);
  5077. (void)close(fdout[0]);
  5078. (void)close(fderr[0]);
  5079. /* After exec, all signal handlers are restored to their default
  5080. * values, with one exception of SIGCHLD. According to
  5081. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  5082. * will leave unchanged after exec if it was set to be ignored.
  5083. * Restore it to default action. */
  5084. memset(&sa, 0, sizeof(sa));
  5085. sa.sa_handler = SIG_DFL;
  5086. sigaction(SIGCHLD, &sa, NULL);
  5087. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  5088. if (interp == NULL) {
  5089. (void)execle(prog, prog, NULL, envp);
  5090. mg_cry_internal(conn,
  5091. "%s: execle(%s): %s",
  5092. __func__,
  5093. prog,
  5094. strerror(ERRNO));
  5095. } else {
  5096. (void)execle(interp, interp, prog, NULL, envp);
  5097. mg_cry_internal(conn,
  5098. "%s: execle(%s %s): %s",
  5099. __func__,
  5100. interp,
  5101. prog,
  5102. strerror(ERRNO));
  5103. }
  5104. }
  5105. exit(EXIT_FAILURE);
  5106. }
  5107. return pid;
  5108. }
  5109. #endif /* !NO_CGI */
  5110. static int
  5111. set_non_blocking_mode(SOCKET sock)
  5112. {
  5113. int flags = fcntl(sock, F_GETFL, 0);
  5114. if (flags < 0) {
  5115. return -1;
  5116. }
  5117. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  5118. return -1;
  5119. }
  5120. return 0;
  5121. }
  5122. static int
  5123. set_blocking_mode(SOCKET sock)
  5124. {
  5125. int flags = fcntl(sock, F_GETFL, 0);
  5126. if (flags < 0) {
  5127. return -1;
  5128. }
  5129. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  5130. return -1;
  5131. }
  5132. return 0;
  5133. }
  5134. #endif /* _WIN32 / else */
  5135. /* End of initial operating system specific define block. */
  5136. /* Get a random number (independent of C rand function) */
  5137. static uint64_t
  5138. get_random(void)
  5139. {
  5140. static uint64_t lfsr = 0; /* Linear feedback shift register */
  5141. static uint64_t lcg = 0; /* Linear congruential generator */
  5142. uint64_t now = mg_get_current_time_ns();
  5143. if (lfsr == 0) {
  5144. /* lfsr will be only 0 if has not been initialized,
  5145. * so this code is called only once. */
  5146. lfsr = mg_get_current_time_ns();
  5147. lcg = mg_get_current_time_ns();
  5148. } else {
  5149. /* Get the next step of both random number generators. */
  5150. lfsr = (lfsr >> 1)
  5151. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  5152. << 63);
  5153. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  5154. }
  5155. /* Combining two pseudo-random number generators and a high resolution
  5156. * part
  5157. * of the current server time will make it hard (impossible?) to guess
  5158. * the
  5159. * next number. */
  5160. return (lfsr ^ lcg ^ now);
  5161. }
  5162. static int
  5163. mg_poll(struct mg_pollfd *pfd,
  5164. unsigned int n,
  5165. int milliseconds,
  5166. volatile int *stop_server)
  5167. {
  5168. /* Call poll, but only for a maximum time of a few seconds.
  5169. * This will allow to stop the server after some seconds, instead
  5170. * of having to wait for a long socket timeout. */
  5171. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5172. do {
  5173. int result;
  5174. if (*stop_server) {
  5175. /* Shut down signal */
  5176. return -2;
  5177. }
  5178. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  5179. ms_now = milliseconds;
  5180. }
  5181. result = poll(pfd, n, ms_now);
  5182. if (result != 0) {
  5183. /* Poll returned either success (1) or error (-1).
  5184. * Forward both to the caller. */
  5185. return result;
  5186. }
  5187. /* Poll returned timeout (0). */
  5188. if (milliseconds > 0) {
  5189. milliseconds -= ms_now;
  5190. }
  5191. } while (milliseconds != 0);
  5192. /* timeout: return 0 */
  5193. return 0;
  5194. }
  5195. /* Write data to the IO channel - opened file descriptor, socket or SSL
  5196. * descriptor.
  5197. * Return value:
  5198. * >=0 .. number of bytes successfully written
  5199. * -1 .. timeout
  5200. * -2 .. error
  5201. */
  5202. static int
  5203. push_inner(struct mg_context *ctx,
  5204. FILE *fp,
  5205. SOCKET sock,
  5206. SSL *ssl,
  5207. const char *buf,
  5208. int len,
  5209. double timeout)
  5210. {
  5211. uint64_t start = 0, now = 0, timeout_ns = 0;
  5212. int n, err;
  5213. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  5214. #if defined(_WIN32)
  5215. typedef int len_t;
  5216. #else
  5217. typedef size_t len_t;
  5218. #endif
  5219. if (timeout > 0) {
  5220. now = mg_get_current_time_ns();
  5221. start = now;
  5222. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5223. }
  5224. if (ctx == NULL) {
  5225. return -2;
  5226. }
  5227. #if defined(NO_SSL)
  5228. if (ssl) {
  5229. return -2;
  5230. }
  5231. #endif
  5232. /* Try to read until it succeeds, fails, times out, or the server
  5233. * shuts down. */
  5234. for (;;) {
  5235. #if !defined(NO_SSL)
  5236. if (ssl != NULL) {
  5237. n = SSL_write(ssl, buf, len);
  5238. if (n <= 0) {
  5239. err = SSL_get_error(ssl, n);
  5240. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  5241. err = ERRNO;
  5242. } else if ((err == SSL_ERROR_WANT_READ)
  5243. || (err == SSL_ERROR_WANT_WRITE)) {
  5244. n = 0;
  5245. } else {
  5246. DEBUG_TRACE("SSL_write() failed, error %d", err);
  5247. return -2;
  5248. }
  5249. } else {
  5250. err = 0;
  5251. }
  5252. } else
  5253. #endif
  5254. if (fp != NULL) {
  5255. n = (int)fwrite(buf, 1, (size_t)len, fp);
  5256. if (ferror(fp)) {
  5257. n = -1;
  5258. err = ERRNO;
  5259. } else {
  5260. err = 0;
  5261. }
  5262. } else {
  5263. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  5264. err = (n < 0) ? ERRNO : 0;
  5265. #if defined(_WIN32)
  5266. if (err == WSAEWOULDBLOCK) {
  5267. err = 0;
  5268. n = 0;
  5269. }
  5270. #else
  5271. if (err == EWOULDBLOCK) {
  5272. err = 0;
  5273. n = 0;
  5274. }
  5275. #endif
  5276. if (n < 0) {
  5277. /* shutdown of the socket at client side */
  5278. return -2;
  5279. }
  5280. }
  5281. if (ctx->stop_flag) {
  5282. return -2;
  5283. }
  5284. if ((n > 0) || ((n == 0) && (len == 0))) {
  5285. /* some data has been read, or no data was requested */
  5286. return n;
  5287. }
  5288. if (n < 0) {
  5289. /* socket error - check errno */
  5290. DEBUG_TRACE("send() failed, error %d", err);
  5291. /* TODO (mid): error handling depending on the error code.
  5292. * These codes are different between Windows and Linux.
  5293. * Currently there is no problem with failing send calls,
  5294. * if there is a reproducible situation, it should be
  5295. * investigated in detail.
  5296. */
  5297. return -2;
  5298. }
  5299. /* Only in case n=0 (timeout), repeat calling the write function */
  5300. /* If send failed, wait before retry */
  5301. if (fp != NULL) {
  5302. /* For files, just wait a fixed time.
  5303. * Maybe it helps, maybe not. */
  5304. mg_sleep(5);
  5305. } else {
  5306. /* For sockets, wait for the socket using poll */
  5307. struct mg_pollfd pfd[1];
  5308. int pollres;
  5309. pfd[0].fd = sock;
  5310. pfd[0].events = POLLOUT;
  5311. pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag));
  5312. if (ctx->stop_flag) {
  5313. return -2;
  5314. }
  5315. if (pollres > 0) {
  5316. continue;
  5317. }
  5318. }
  5319. if (timeout > 0) {
  5320. now = mg_get_current_time_ns();
  5321. if ((now - start) > timeout_ns) {
  5322. /* Timeout */
  5323. break;
  5324. }
  5325. }
  5326. }
  5327. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5328. used */
  5329. return -1;
  5330. }
  5331. static int
  5332. push_all(struct mg_context *ctx,
  5333. FILE *fp,
  5334. SOCKET sock,
  5335. SSL *ssl,
  5336. const char *buf,
  5337. int len)
  5338. {
  5339. double timeout = -1.0;
  5340. int n, nwritten = 0;
  5341. if (ctx == NULL) {
  5342. return -1;
  5343. }
  5344. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5345. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5346. }
  5347. while ((len > 0) && (ctx->stop_flag == 0)) {
  5348. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, len, timeout);
  5349. if (n < 0) {
  5350. if (nwritten == 0) {
  5351. nwritten = -1; /* Propagate the error */
  5352. }
  5353. break;
  5354. } else if (n == 0) {
  5355. break; /* No more data to write */
  5356. } else {
  5357. nwritten += n;
  5358. len -= n;
  5359. }
  5360. }
  5361. return nwritten;
  5362. }
  5363. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5364. * Return value:
  5365. * >=0 .. number of bytes successfully read
  5366. * -1 .. timeout
  5367. * -2 .. error
  5368. */
  5369. static int
  5370. pull_inner(FILE *fp,
  5371. struct mg_connection *conn,
  5372. char *buf,
  5373. int len,
  5374. double timeout)
  5375. {
  5376. int nread, err = 0;
  5377. #if defined(_WIN32)
  5378. typedef int len_t;
  5379. #else
  5380. typedef size_t len_t;
  5381. #endif
  5382. #if !defined(NO_SSL)
  5383. int ssl_pending;
  5384. #endif
  5385. /* We need an additional wait loop around this, because in some cases
  5386. * with TLSwe may get data from the socket but not from SSL_read.
  5387. * In this case we need to repeat at least once.
  5388. */
  5389. if (fp != NULL) {
  5390. #if !defined(_WIN32_WCE)
  5391. /* Use read() instead of fread(), because if we're reading from the
  5392. * CGI pipe, fread() may block until IO buffer is filled up. We
  5393. * cannot afford to block and must pass all read bytes immediately
  5394. * to the client. */
  5395. nread = (int)read(fileno(fp), buf, (size_t)len);
  5396. #else
  5397. /* WinCE does not support CGI pipes */
  5398. nread = (int)fread(buf, 1, (size_t)len, fp);
  5399. #endif
  5400. err = (nread < 0) ? ERRNO : 0;
  5401. if ((nread == 0) && (len > 0)) {
  5402. /* Should get data, but got EOL */
  5403. return -2;
  5404. }
  5405. #if !defined(NO_SSL)
  5406. } else if ((conn->ssl != NULL)
  5407. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5408. /* We already know there is no more data buffered in conn->buf
  5409. * but there is more available in the SSL layer. So don't poll
  5410. * conn->client.sock yet. */
  5411. if (ssl_pending > len) {
  5412. ssl_pending = len;
  5413. }
  5414. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5415. if (nread <= 0) {
  5416. err = SSL_get_error(conn->ssl, nread);
  5417. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5418. err = ERRNO;
  5419. } else if ((err == SSL_ERROR_WANT_READ)
  5420. || (err == SSL_ERROR_WANT_WRITE)) {
  5421. nread = 0;
  5422. } else {
  5423. /* All errors should return -2 */
  5424. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5425. return -2;
  5426. }
  5427. ERR_clear_error();
  5428. } else {
  5429. err = 0;
  5430. }
  5431. } else if (conn->ssl != NULL) {
  5432. struct mg_pollfd pfd[1];
  5433. int pollres;
  5434. pfd[0].fd = conn->client.sock;
  5435. pfd[0].events = POLLIN;
  5436. pollres = mg_poll(pfd,
  5437. 1,
  5438. (int)(timeout * 1000.0),
  5439. &(conn->phys_ctx->stop_flag));
  5440. if (conn->phys_ctx->stop_flag) {
  5441. return -2;
  5442. }
  5443. if (pollres > 0) {
  5444. nread = SSL_read(conn->ssl, buf, len);
  5445. if (nread <= 0) {
  5446. err = SSL_get_error(conn->ssl, nread);
  5447. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5448. err = ERRNO;
  5449. } else if ((err == SSL_ERROR_WANT_READ)
  5450. || (err == SSL_ERROR_WANT_WRITE)) {
  5451. nread = 0;
  5452. } else {
  5453. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5454. return -2;
  5455. }
  5456. } else {
  5457. err = 0;
  5458. }
  5459. ERR_clear_error();
  5460. } else if (pollres < 0) {
  5461. /* Error */
  5462. return -2;
  5463. } else {
  5464. /* pollres = 0 means timeout */
  5465. nread = 0;
  5466. }
  5467. #endif
  5468. } else {
  5469. struct mg_pollfd pfd[1];
  5470. int pollres;
  5471. pfd[0].fd = conn->client.sock;
  5472. pfd[0].events = POLLIN;
  5473. pollres = mg_poll(pfd,
  5474. 1,
  5475. (int)(timeout * 1000.0),
  5476. &(conn->phys_ctx->stop_flag));
  5477. if (conn->phys_ctx->stop_flag) {
  5478. return -2;
  5479. }
  5480. if (pollres > 0) {
  5481. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5482. err = (nread < 0) ? ERRNO : 0;
  5483. if (nread <= 0) {
  5484. /* shutdown of the socket at client side */
  5485. return -2;
  5486. }
  5487. } else if (pollres < 0) {
  5488. /* error callint poll */
  5489. return -2;
  5490. } else {
  5491. /* pollres = 0 means timeout */
  5492. nread = 0;
  5493. }
  5494. }
  5495. if (conn->phys_ctx->stop_flag) {
  5496. return -2;
  5497. }
  5498. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5499. /* some data has been read, or no data was requested */
  5500. return nread;
  5501. }
  5502. if (nread < 0) {
  5503. /* socket error - check errno */
  5504. #if defined(_WIN32)
  5505. if (err == WSAEWOULDBLOCK) {
  5506. /* TODO (low): check if this is still required */
  5507. /* standard case if called from close_socket_gracefully */
  5508. return -2;
  5509. } else if (err == WSAETIMEDOUT) {
  5510. /* TODO (low): check if this is still required */
  5511. /* timeout is handled by the while loop */
  5512. return 0;
  5513. } else if (err == WSAECONNABORTED) {
  5514. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5515. return -2;
  5516. } else {
  5517. DEBUG_TRACE("recv() failed, error %d", err);
  5518. return -2;
  5519. }
  5520. #else
  5521. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5522. * if the timeout is reached and if the socket was set to non-
  5523. * blocking in close_socket_gracefully, so we can not distinguish
  5524. * here. We have to wait for the timeout in both cases for now.
  5525. */
  5526. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5527. /* TODO (low): check if this is still required */
  5528. /* EAGAIN/EWOULDBLOCK:
  5529. * standard case if called from close_socket_gracefully
  5530. * => should return -1 */
  5531. /* or timeout occurred
  5532. * => the code must stay in the while loop */
  5533. /* EINTR can be generated on a socket with a timeout set even
  5534. * when SA_RESTART is effective for all relevant signals
  5535. * (see signal(7)).
  5536. * => stay in the while loop */
  5537. } else {
  5538. DEBUG_TRACE("recv() failed, error %d", err);
  5539. return -2;
  5540. }
  5541. #endif
  5542. }
  5543. /* Timeout occurred, but no data available. */
  5544. return -1;
  5545. }
  5546. static int
  5547. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5548. {
  5549. int n, nread = 0;
  5550. double timeout = -1.0;
  5551. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5552. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5553. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5554. }
  5555. if (timeout >= 0.0) {
  5556. start_time = mg_get_current_time_ns();
  5557. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5558. }
  5559. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5560. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5561. if (n == -2) {
  5562. if (nread == 0) {
  5563. nread = -1; /* Propagate the error */
  5564. }
  5565. break;
  5566. } else if (n == -1) {
  5567. /* timeout */
  5568. if (timeout >= 0.0) {
  5569. now = mg_get_current_time_ns();
  5570. if ((now - start_time) <= timeout_ns) {
  5571. continue;
  5572. }
  5573. }
  5574. break;
  5575. } else if (n == 0) {
  5576. break; /* No more data to read */
  5577. } else {
  5578. nread += n;
  5579. len -= n;
  5580. }
  5581. }
  5582. return nread;
  5583. }
  5584. static void
  5585. discard_unread_request_data(struct mg_connection *conn)
  5586. {
  5587. char buf[MG_BUF_LEN];
  5588. while (mg_read(conn, buf, sizeof(buf)) > 0)
  5589. ;
  5590. }
  5591. static int
  5592. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5593. {
  5594. int64_t content_len, n, buffered_len, nread;
  5595. int64_t len64 =
  5596. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5597. * int, we may not read more
  5598. * bytes */
  5599. const char *body;
  5600. if (conn == NULL) {
  5601. return 0;
  5602. }
  5603. /* If Content-Length is not set for a response with body data,
  5604. * we do not know in advance how much data should be read. */
  5605. content_len = conn->content_len;
  5606. if (content_len < 0) {
  5607. /* The body data is completed when the connection is closed. */
  5608. content_len = INT64_MAX;
  5609. }
  5610. nread = 0;
  5611. if (conn->consumed_content < content_len) {
  5612. /* Adjust number of bytes to read. */
  5613. int64_t left_to_read = content_len - conn->consumed_content;
  5614. if (left_to_read < len64) {
  5615. /* Do not read more than the total content length of the
  5616. * request.
  5617. */
  5618. len64 = left_to_read;
  5619. }
  5620. /* Return buffered data */
  5621. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5622. - conn->consumed_content;
  5623. if (buffered_len > 0) {
  5624. if (len64 < buffered_len) {
  5625. buffered_len = len64;
  5626. }
  5627. body = conn->buf + conn->request_len + conn->consumed_content;
  5628. memcpy(buf, body, (size_t)buffered_len);
  5629. len64 -= buffered_len;
  5630. conn->consumed_content += buffered_len;
  5631. nread += buffered_len;
  5632. buf = (char *)buf + buffered_len;
  5633. }
  5634. /* We have returned all buffered data. Read new data from the remote
  5635. * socket.
  5636. */
  5637. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5638. conn->consumed_content += n;
  5639. nread += n;
  5640. } else {
  5641. nread = ((nread > 0) ? nread : n);
  5642. }
  5643. }
  5644. return (int)nread;
  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->is_chunked != 1) {
  5663. /* Has error */
  5664. return -1;
  5665. }
  5666. if (conn->consumed_content != conn->content_len) {
  5667. /* copy from the current chunk */
  5668. int read_ret = mg_read_inner(conn, (char *)buf + all_read, len);
  5669. if (read_ret < 1) {
  5670. /* read error */
  5671. conn->is_chunked = 2;
  5672. return -1;
  5673. }
  5674. all_read += (size_t)read_ret;
  5675. len -= (size_t)read_ret;
  5676. if (conn->consumed_content == conn->content_len) {
  5677. /* Add data bytes in the current chunk have been read,
  5678. * so we are expecting \r\n now. */
  5679. char x[2];
  5680. conn->content_len += 2;
  5681. if ((mg_read_inner(conn, x, 2) != 2) || (x[0] != '\r')
  5682. || (x[1] != '\n')) {
  5683. /* Protocol violation */
  5684. conn->is_chunked = 2;
  5685. return -1;
  5686. }
  5687. }
  5688. } else {
  5689. /* fetch a new chunk */
  5690. size_t i;
  5691. char lenbuf[64];
  5692. char *end = NULL;
  5693. unsigned long chunkSize = 0;
  5694. for (i = 0; i < (sizeof(lenbuf) - 1); i++) {
  5695. conn->content_len++;
  5696. if (mg_read_inner(conn, lenbuf + i, 1) != 1) {
  5697. lenbuf[i] = 0;
  5698. }
  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. conn->is_chunked = 2;
  5716. return -1;
  5717. }
  5718. }
  5719. if ((end == NULL) || (*end != '\r')) {
  5720. /* chunksize not set correctly */
  5721. conn->is_chunked = 2;
  5722. return -1;
  5723. }
  5724. if (chunkSize == 0) {
  5725. /* try discarding trailer for keep-alive */
  5726. conn->content_len += 2;
  5727. if ((mg_read_inner(conn, lenbuf, 2) == 2)
  5728. && (lenbuf[0] == '\r') && (lenbuf[1] == '\n')) {
  5729. conn->is_chunked = 4;
  5730. }
  5731. break;
  5732. }
  5733. /* append a new chunk */
  5734. conn->content_len += chunkSize;
  5735. }
  5736. }
  5737. return (int)all_read;
  5738. }
  5739. return mg_read_inner(conn, buf, len);
  5740. }
  5741. int
  5742. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5743. {
  5744. time_t now;
  5745. int n, total, allowed;
  5746. if (conn == NULL) {
  5747. return 0;
  5748. }
  5749. if (len > INT_MAX) {
  5750. return -1;
  5751. }
  5752. if (conn->throttle > 0) {
  5753. if ((now = time(NULL)) != conn->last_throttle_time) {
  5754. conn->last_throttle_time = now;
  5755. conn->last_throttle_bytes = 0;
  5756. }
  5757. allowed = conn->throttle - conn->last_throttle_bytes;
  5758. if (allowed > (int)len) {
  5759. allowed = (int)len;
  5760. }
  5761. if ((total = push_all(conn->phys_ctx,
  5762. NULL,
  5763. conn->client.sock,
  5764. conn->ssl,
  5765. (const char *)buf,
  5766. allowed))
  5767. == allowed) {
  5768. buf = (const char *)buf + total;
  5769. conn->last_throttle_bytes += total;
  5770. while ((total < (int)len) && (conn->phys_ctx->stop_flag == 0)) {
  5771. allowed = (conn->throttle > ((int)len - total))
  5772. ? (int)len - total
  5773. : conn->throttle;
  5774. if ((n = push_all(conn->phys_ctx,
  5775. NULL,
  5776. conn->client.sock,
  5777. conn->ssl,
  5778. (const char *)buf,
  5779. allowed))
  5780. != allowed) {
  5781. break;
  5782. }
  5783. sleep(1);
  5784. conn->last_throttle_bytes = allowed;
  5785. conn->last_throttle_time = time(NULL);
  5786. buf = (const char *)buf + n;
  5787. total += n;
  5788. }
  5789. }
  5790. } else {
  5791. total = push_all(conn->phys_ctx,
  5792. NULL,
  5793. conn->client.sock,
  5794. conn->ssl,
  5795. (const char *)buf,
  5796. (int)len);
  5797. }
  5798. if (total > 0) {
  5799. conn->num_bytes_sent += total;
  5800. }
  5801. return total;
  5802. }
  5803. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5804. int
  5805. mg_send_chunk(struct mg_connection *conn,
  5806. const char *chunk,
  5807. unsigned int chunk_len)
  5808. {
  5809. char lenbuf[16];
  5810. size_t lenbuf_len;
  5811. int ret;
  5812. int t;
  5813. /* First store the length information in a text buffer. */
  5814. sprintf(lenbuf, "%x\r\n", chunk_len);
  5815. lenbuf_len = strlen(lenbuf);
  5816. /* Then send length information, chunk and terminating \r\n. */
  5817. ret = mg_write(conn, lenbuf, lenbuf_len);
  5818. if (ret != (int)lenbuf_len) {
  5819. return -1;
  5820. }
  5821. t = ret;
  5822. ret = mg_write(conn, chunk, chunk_len);
  5823. if (ret != (int)chunk_len) {
  5824. return -1;
  5825. }
  5826. t += ret;
  5827. ret = mg_write(conn, "\r\n", 2);
  5828. if (ret != 2) {
  5829. return -1;
  5830. }
  5831. t += ret;
  5832. return t;
  5833. }
  5834. #if defined(GCC_DIAGNOSTIC)
  5835. /* This block forwards format strings to printf implementations,
  5836. * so we need to disable the format-nonliteral warning. */
  5837. #pragma GCC diagnostic push
  5838. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5839. #endif
  5840. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5841. static int
  5842. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5843. {
  5844. va_list ap_copy;
  5845. size_t size = MG_BUF_LEN / 4;
  5846. int len = -1;
  5847. *buf = NULL;
  5848. while (len < 0) {
  5849. if (*buf) {
  5850. mg_free(*buf);
  5851. }
  5852. size *= 4;
  5853. *buf = (char *)mg_malloc(size);
  5854. if (!*buf) {
  5855. break;
  5856. }
  5857. va_copy(ap_copy, ap);
  5858. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5859. va_end(ap_copy);
  5860. (*buf)[size - 1] = 0;
  5861. }
  5862. return len;
  5863. }
  5864. /* Print message to buffer. If buffer is large enough to hold the message,
  5865. * return buffer. If buffer is to small, allocate large enough buffer on
  5866. * heap,
  5867. * and return allocated buffer. */
  5868. static int
  5869. alloc_vprintf(char **out_buf,
  5870. char *prealloc_buf,
  5871. size_t prealloc_size,
  5872. const char *fmt,
  5873. va_list ap)
  5874. {
  5875. va_list ap_copy;
  5876. int len;
  5877. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5878. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5879. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5880. * Therefore, we make two passes: on first pass, get required message
  5881. * length.
  5882. * On second pass, actually print the message. */
  5883. va_copy(ap_copy, ap);
  5884. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5885. va_end(ap_copy);
  5886. if (len < 0) {
  5887. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5888. * Switch to alternative code path that uses incremental
  5889. * allocations.
  5890. */
  5891. va_copy(ap_copy, ap);
  5892. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5893. va_end(ap_copy);
  5894. } else if ((size_t)(len) >= prealloc_size) {
  5895. /* The pre-allocated buffer not large enough. */
  5896. /* Allocate a new buffer. */
  5897. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5898. if (!*out_buf) {
  5899. /* Allocation failed. Return -1 as "out of memory" error. */
  5900. return -1;
  5901. }
  5902. /* Buffer allocation successful. Store the string there. */
  5903. va_copy(ap_copy, ap);
  5904. IGNORE_UNUSED_RESULT(
  5905. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5906. va_end(ap_copy);
  5907. } else {
  5908. /* The pre-allocated buffer is large enough.
  5909. * Use it to store the string and return the address. */
  5910. va_copy(ap_copy, ap);
  5911. IGNORE_UNUSED_RESULT(
  5912. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5913. va_end(ap_copy);
  5914. *out_buf = prealloc_buf;
  5915. }
  5916. return len;
  5917. }
  5918. #if defined(GCC_DIAGNOSTIC)
  5919. /* Enable format-nonliteral warning again. */
  5920. #pragma GCC diagnostic pop
  5921. #endif
  5922. static int
  5923. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5924. {
  5925. char mem[MG_BUF_LEN];
  5926. char *buf = NULL;
  5927. int len;
  5928. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5929. len = mg_write(conn, buf, (size_t)len);
  5930. }
  5931. if (buf != mem) {
  5932. mg_free(buf);
  5933. }
  5934. return len;
  5935. }
  5936. int
  5937. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5938. {
  5939. va_list ap;
  5940. int result;
  5941. va_start(ap, fmt);
  5942. result = mg_vprintf(conn, fmt, ap);
  5943. va_end(ap);
  5944. return result;
  5945. }
  5946. int
  5947. mg_url_decode(const char *src,
  5948. int src_len,
  5949. char *dst,
  5950. int dst_len,
  5951. int is_form_url_encoded)
  5952. {
  5953. int i, j, a, b;
  5954. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5955. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5956. if ((i < src_len - 2) && (src[i] == '%')
  5957. && isxdigit((unsigned char)src[i + 1])
  5958. && isxdigit((unsigned char)src[i + 2])) {
  5959. a = tolower((unsigned char)src[i + 1]);
  5960. b = tolower((unsigned char)src[i + 2]);
  5961. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5962. i += 2;
  5963. } else if (is_form_url_encoded && (src[i] == '+')) {
  5964. dst[j] = ' ';
  5965. } else {
  5966. dst[j] = src[i];
  5967. }
  5968. }
  5969. dst[j] = '\0'; /* Null-terminate the destination */
  5970. return (i >= src_len) ? j : -1;
  5971. }
  5972. int
  5973. mg_get_var(const char *data,
  5974. size_t data_len,
  5975. const char *name,
  5976. char *dst,
  5977. size_t dst_len)
  5978. {
  5979. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5980. }
  5981. int
  5982. mg_get_var2(const char *data,
  5983. size_t data_len,
  5984. const char *name,
  5985. char *dst,
  5986. size_t dst_len,
  5987. size_t occurrence)
  5988. {
  5989. const char *p, *e, *s;
  5990. size_t name_len;
  5991. int len;
  5992. if ((dst == NULL) || (dst_len == 0)) {
  5993. len = -2;
  5994. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5995. len = -1;
  5996. dst[0] = '\0';
  5997. } else {
  5998. name_len = strlen(name);
  5999. e = data + data_len;
  6000. len = -1;
  6001. dst[0] = '\0';
  6002. /* data is "var1=val1&var2=val2...". Find variable first */
  6003. for (p = data; p + name_len < e; p++) {
  6004. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  6005. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  6006. /* Point p to variable value */
  6007. p += name_len + 1;
  6008. /* Point s to the end of the value */
  6009. s = (const char *)memchr(p, '&', (size_t)(e - p));
  6010. if (s == NULL) {
  6011. s = e;
  6012. }
  6013. DEBUG_ASSERT(s >= p);
  6014. if (s < p) {
  6015. return -3;
  6016. }
  6017. /* Decode variable into destination buffer */
  6018. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  6019. /* Redirect error code from -1 to -2 (destination buffer too
  6020. * small). */
  6021. if (len == -1) {
  6022. len = -2;
  6023. }
  6024. break;
  6025. }
  6026. }
  6027. }
  6028. return len;
  6029. }
  6030. /* HCP24: some changes to compare hole var_name */
  6031. int
  6032. mg_get_cookie(const char *cookie_header,
  6033. const char *var_name,
  6034. char *dst,
  6035. size_t dst_size)
  6036. {
  6037. const char *s, *p, *end;
  6038. int name_len, len = -1;
  6039. if ((dst == NULL) || (dst_size == 0)) {
  6040. return -2;
  6041. }
  6042. dst[0] = '\0';
  6043. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  6044. return -1;
  6045. }
  6046. name_len = (int)strlen(var_name);
  6047. end = s + strlen(s);
  6048. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  6049. if (s[name_len] == '=') {
  6050. /* HCP24: now check is it a substring or a full cookie name */
  6051. if ((s == cookie_header) || (s[-1] == ' ')) {
  6052. s += name_len + 1;
  6053. if ((p = strchr(s, ' ')) == NULL) {
  6054. p = end;
  6055. }
  6056. if (p[-1] == ';') {
  6057. p--;
  6058. }
  6059. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  6060. s++;
  6061. p--;
  6062. }
  6063. if ((size_t)(p - s) < dst_size) {
  6064. len = (int)(p - s);
  6065. mg_strlcpy(dst, s, (size_t)len + 1);
  6066. } else {
  6067. len = -3;
  6068. }
  6069. break;
  6070. }
  6071. }
  6072. }
  6073. return len;
  6074. }
  6075. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  6076. static void
  6077. base64_encode(const unsigned char *src, int src_len, char *dst)
  6078. {
  6079. static const char *b64 =
  6080. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  6081. int i, j, a, b, c;
  6082. for (i = j = 0; i < src_len; i += 3) {
  6083. a = src[i];
  6084. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  6085. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  6086. dst[j++] = b64[a >> 2];
  6087. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  6088. if (i + 1 < src_len) {
  6089. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  6090. }
  6091. if (i + 2 < src_len) {
  6092. dst[j++] = b64[c & 63];
  6093. }
  6094. }
  6095. while (j % 4 != 0) {
  6096. dst[j++] = '=';
  6097. }
  6098. dst[j++] = '\0';
  6099. }
  6100. #endif
  6101. #if defined(USE_LUA)
  6102. static unsigned char
  6103. b64reverse(char letter)
  6104. {
  6105. if ((letter >= 'A') && (letter <= 'Z')) {
  6106. return letter - 'A';
  6107. }
  6108. if ((letter >= 'a') && (letter <= 'z')) {
  6109. return letter - 'a' + 26;
  6110. }
  6111. if ((letter >= '0') && (letter <= '9')) {
  6112. return letter - '0' + 52;
  6113. }
  6114. if (letter == '+') {
  6115. return 62;
  6116. }
  6117. if (letter == '/') {
  6118. return 63;
  6119. }
  6120. if (letter == '=') {
  6121. return 255; /* normal end */
  6122. }
  6123. return 254; /* error */
  6124. }
  6125. static int
  6126. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  6127. {
  6128. int i;
  6129. unsigned char a, b, c, d;
  6130. *dst_len = 0;
  6131. for (i = 0; i < src_len; i += 4) {
  6132. a = b64reverse(src[i]);
  6133. if (a >= 254) {
  6134. return i;
  6135. }
  6136. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  6137. if (b >= 254) {
  6138. return i + 1;
  6139. }
  6140. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  6141. if (c == 254) {
  6142. return i + 2;
  6143. }
  6144. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  6145. if (d == 254) {
  6146. return i + 3;
  6147. }
  6148. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  6149. if (c != 255) {
  6150. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  6151. if (d != 255) {
  6152. dst[(*dst_len)++] = (c << 6) + d;
  6153. }
  6154. }
  6155. }
  6156. return -1;
  6157. }
  6158. #endif
  6159. static int
  6160. is_put_or_delete_method(const struct mg_connection *conn)
  6161. {
  6162. if (conn) {
  6163. const char *s = conn->request_info.request_method;
  6164. return (s != NULL)
  6165. && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  6166. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  6167. }
  6168. return 0;
  6169. }
  6170. #if !defined(NO_FILES)
  6171. static int
  6172. extention_matches_script(
  6173. struct mg_connection *conn, /* in: request (must be valid) */
  6174. const char *filename /* in: filename (must be valid) */
  6175. )
  6176. {
  6177. #if !defined(NO_CGI)
  6178. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  6179. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  6180. filename)
  6181. > 0) {
  6182. return 1;
  6183. }
  6184. #endif
  6185. #if defined(USE_LUA)
  6186. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  6187. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  6188. filename)
  6189. > 0) {
  6190. return 1;
  6191. }
  6192. #endif
  6193. #if defined(USE_DUKTAPE)
  6194. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  6195. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  6196. filename)
  6197. > 0) {
  6198. return 1;
  6199. }
  6200. #endif
  6201. /* filename and conn could be unused, if all preocessor conditions
  6202. * are false (no script language supported). */
  6203. (void)filename;
  6204. (void)conn;
  6205. return 0;
  6206. }
  6207. /* For given directory path, substitute it to valid index file.
  6208. * Return 1 if index file has been found, 0 if not found.
  6209. * If the file is found, it's stats is returned in stp. */
  6210. static int
  6211. substitute_index_file(struct mg_connection *conn,
  6212. char *path,
  6213. size_t path_len,
  6214. struct mg_file_stat *filestat)
  6215. {
  6216. const char *list = conn->dom_ctx->config[INDEX_FILES];
  6217. struct vec filename_vec;
  6218. size_t n = strlen(path);
  6219. int found = 0;
  6220. /* The 'path' given to us points to the directory. Remove all trailing
  6221. * directory separator characters from the end of the path, and
  6222. * then append single directory separator character. */
  6223. while ((n > 0) && (path[n - 1] == '/')) {
  6224. n--;
  6225. }
  6226. path[n] = '/';
  6227. /* Traverse index files list. For each entry, append it to the given
  6228. * path and see if the file exists. If it exists, break the loop */
  6229. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  6230. /* Ignore too long entries that may overflow path buffer */
  6231. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  6232. continue;
  6233. }
  6234. /* Prepare full path to the index file */
  6235. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  6236. /* Does it exist? */
  6237. if (mg_stat(conn, path, filestat)) {
  6238. /* Yes it does, break the loop */
  6239. found = 1;
  6240. break;
  6241. }
  6242. }
  6243. /* If no index file exists, restore directory path */
  6244. if (!found) {
  6245. path[n] = '\0';
  6246. }
  6247. return found;
  6248. }
  6249. #endif
  6250. static void
  6251. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  6252. char *filename, /* out: filename */
  6253. size_t filename_buf_len, /* in: size of filename buffer */
  6254. struct mg_file_stat *filestat, /* out: file status structure */
  6255. int *is_found, /* out: file found (directly) */
  6256. int *is_script_resource, /* out: handled by a script? */
  6257. int *is_websocket_request, /* out: websocket connetion? */
  6258. int *is_put_or_delete_request /* out: put/delete a file? */
  6259. )
  6260. {
  6261. char const *accept_encoding;
  6262. #if !defined(NO_FILES)
  6263. const char *uri = conn->request_info.local_uri;
  6264. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6265. const char *rewrite;
  6266. struct vec a, b;
  6267. ptrdiff_t match_len;
  6268. char gz_path[PATH_MAX];
  6269. int truncated;
  6270. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6271. char *tmp_str;
  6272. size_t tmp_str_len, sep_pos;
  6273. int allow_substitute_script_subresources;
  6274. #endif
  6275. #else
  6276. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6277. #endif
  6278. /* Step 1: Set all initially unknown outputs to zero */
  6279. memset(filestat, 0, sizeof(*filestat));
  6280. *filename = 0;
  6281. *is_found = 0;
  6282. *is_script_resource = 0;
  6283. /* Step 2: Check if the request attempts to modify the file system */
  6284. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6285. /* Step 3: Check if it is a websocket request, and modify the document
  6286. * root if required */
  6287. #if defined(USE_WEBSOCKET)
  6288. *is_websocket_request = is_websocket_protocol(conn);
  6289. #if !defined(NO_FILES)
  6290. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6291. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6292. }
  6293. #endif /* !NO_FILES */
  6294. #else /* USE_WEBSOCKET */
  6295. *is_websocket_request = 0;
  6296. #endif /* USE_WEBSOCKET */
  6297. /* Step 4: Check if gzip encoded response is allowed */
  6298. conn->accept_gzip = 0;
  6299. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6300. if (strstr(accept_encoding, "gzip") != NULL) {
  6301. conn->accept_gzip = 1;
  6302. }
  6303. }
  6304. #if !defined(NO_FILES)
  6305. /* Step 5: If there is no root directory, don't look for files. */
  6306. /* Note that root == NULL is a regular use case here. This occurs,
  6307. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6308. * config is not required. */
  6309. if (root == NULL) {
  6310. /* all file related outputs have already been set to 0, just return
  6311. */
  6312. return;
  6313. }
  6314. /* Step 6: Determine the local file path from the root path and the
  6315. * request uri. */
  6316. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6317. * part of the path one byte on the right. */
  6318. mg_snprintf(
  6319. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6320. if (truncated) {
  6321. goto interpret_cleanup;
  6322. }
  6323. /* Step 7: URI rewriting */
  6324. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6325. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6326. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6327. mg_snprintf(conn,
  6328. &truncated,
  6329. filename,
  6330. filename_buf_len - 1,
  6331. "%.*s%s",
  6332. (int)b.len,
  6333. b.ptr,
  6334. uri + match_len);
  6335. break;
  6336. }
  6337. }
  6338. if (truncated) {
  6339. goto interpret_cleanup;
  6340. }
  6341. /* Step 8: Check if the file exists at the server */
  6342. /* Local file path and name, corresponding to requested URI
  6343. * is now stored in "filename" variable. */
  6344. if (mg_stat(conn, filename, filestat)) {
  6345. int uri_len = (int)strlen(uri);
  6346. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6347. /* 8.1: File exists. */
  6348. *is_found = 1;
  6349. /* 8.2: Check if it is a script type. */
  6350. if (extention_matches_script(conn, filename)) {
  6351. /* The request addresses a CGI resource, Lua script or
  6352. * server-side javascript.
  6353. * The URI corresponds to the script itself (like
  6354. * /path/script.cgi), and there is no additional resource
  6355. * path (like /path/script.cgi/something).
  6356. * Requests that modify (replace or delete) a resource, like
  6357. * PUT and DELETE requests, should replace/delete the script
  6358. * file.
  6359. * Requests that read or write from/to a resource, like GET and
  6360. * POST requests, should call the script and return the
  6361. * generated response. */
  6362. *is_script_resource = (!*is_put_or_delete_request);
  6363. }
  6364. /* 8.3: If the request target is a directory, there could be
  6365. * a substitute file (index.html, index.cgi, ...). */
  6366. if (filestat->is_directory && is_uri_end_slash) {
  6367. /* Use a local copy here, since substitute_index_file will
  6368. * change the content of the file status */
  6369. struct mg_file_stat tmp_filestat;
  6370. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6371. if (substitute_index_file(
  6372. conn, filename, filename_buf_len, &tmp_filestat)) {
  6373. /* Substitute file found. Copy stat to the output, then
  6374. * check if the file is a script file */
  6375. *filestat = tmp_filestat;
  6376. if (extention_matches_script(conn, filename)) {
  6377. /* Substitute file is a script file */
  6378. *is_script_resource = 1;
  6379. } else {
  6380. /* Substitute file is a regular file */
  6381. *is_script_resource = 0;
  6382. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6383. }
  6384. }
  6385. /* If there is no substitute file, the server could return
  6386. * a directory listing in a later step */
  6387. }
  6388. return;
  6389. }
  6390. /* Step 9: Check for zipped files: */
  6391. /* If we can't find the actual file, look for the file
  6392. * with the same name but a .gz extension. If we find it,
  6393. * use that and set the gzipped flag in the file struct
  6394. * to indicate that the response need to have the content-
  6395. * encoding: gzip header.
  6396. * We can only do this if the browser declares support. */
  6397. if (conn->accept_gzip) {
  6398. mg_snprintf(
  6399. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6400. if (truncated) {
  6401. goto interpret_cleanup;
  6402. }
  6403. if (mg_stat(conn, gz_path, filestat)) {
  6404. if (filestat) {
  6405. filestat->is_gzipped = 1;
  6406. *is_found = 1;
  6407. }
  6408. /* Currently gz files can not be scripts. */
  6409. return;
  6410. }
  6411. }
  6412. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6413. /* Step 10: Script resources may handle sub-resources */
  6414. /* Support PATH_INFO for CGI scripts. */
  6415. tmp_str_len = strlen(filename);
  6416. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6417. if (!tmp_str) {
  6418. /* Out of memory */
  6419. goto interpret_cleanup;
  6420. }
  6421. memcpy(tmp_str, filename, tmp_str_len + 1);
  6422. /* Check config, if index scripts may have sub-resources */
  6423. allow_substitute_script_subresources =
  6424. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6425. "yes");
  6426. sep_pos = tmp_str_len;
  6427. while (sep_pos > 0) {
  6428. sep_pos--;
  6429. if (tmp_str[sep_pos] == '/') {
  6430. int is_script = 0, does_exist = 0;
  6431. tmp_str[sep_pos] = 0;
  6432. if (tmp_str[0]) {
  6433. is_script = extention_matches_script(conn, tmp_str);
  6434. does_exist = mg_stat(conn, tmp_str, filestat);
  6435. }
  6436. if (does_exist && is_script) {
  6437. filename[sep_pos] = 0;
  6438. memmove(filename + sep_pos + 2,
  6439. filename + sep_pos + 1,
  6440. strlen(filename + sep_pos + 1) + 1);
  6441. conn->path_info = filename + sep_pos + 1;
  6442. filename[sep_pos + 1] = '/';
  6443. *is_script_resource = 1;
  6444. *is_found = 1;
  6445. break;
  6446. }
  6447. if (allow_substitute_script_subresources) {
  6448. if (substitute_index_file(
  6449. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6450. /* some intermediate directory has an index file */
  6451. if (extention_matches_script(conn, tmp_str)) {
  6452. char *tmp_str2;
  6453. DEBUG_TRACE("Substitute script %s serving path %s",
  6454. tmp_str,
  6455. filename);
  6456. /* this index file is a script */
  6457. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6458. conn->phys_ctx);
  6459. mg_snprintf(conn,
  6460. &truncated,
  6461. filename,
  6462. filename_buf_len,
  6463. "%s//%s",
  6464. tmp_str,
  6465. tmp_str2);
  6466. mg_free(tmp_str2);
  6467. if (truncated) {
  6468. mg_free(tmp_str);
  6469. goto interpret_cleanup;
  6470. }
  6471. sep_pos = strlen(tmp_str);
  6472. filename[sep_pos] = 0;
  6473. conn->path_info = filename + sep_pos + 1;
  6474. *is_script_resource = 1;
  6475. *is_found = 1;
  6476. break;
  6477. } else {
  6478. DEBUG_TRACE("Substitute file %s serving path %s",
  6479. tmp_str,
  6480. filename);
  6481. /* non-script files will not have sub-resources */
  6482. filename[sep_pos] = 0;
  6483. conn->path_info = 0;
  6484. *is_script_resource = 0;
  6485. *is_found = 0;
  6486. break;
  6487. }
  6488. }
  6489. }
  6490. tmp_str[sep_pos] = '/';
  6491. }
  6492. }
  6493. mg_free(tmp_str);
  6494. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6495. #endif /* !defined(NO_FILES) */
  6496. return;
  6497. #if !defined(NO_FILES)
  6498. /* Reset all outputs */
  6499. interpret_cleanup:
  6500. memset(filestat, 0, sizeof(*filestat));
  6501. *filename = 0;
  6502. *is_found = 0;
  6503. *is_script_resource = 0;
  6504. *is_websocket_request = 0;
  6505. *is_put_or_delete_request = 0;
  6506. #endif /* !defined(NO_FILES) */
  6507. }
  6508. /* Check whether full request is buffered. Return:
  6509. * -1 if request or response is malformed
  6510. * 0 if request or response is not yet fully buffered
  6511. * >0 actual request length, including last \r\n\r\n */
  6512. static int
  6513. get_http_header_len(const char *buf, int buflen)
  6514. {
  6515. int i;
  6516. for (i = 0; i < buflen; i++) {
  6517. /* Do an unsigned comparison in some conditions below */
  6518. const unsigned char c = (unsigned char)buf[i];
  6519. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6520. && !isprint(c)) {
  6521. /* abort scan as soon as one malformed character is found */
  6522. return -1;
  6523. }
  6524. if (i < buflen - 1) {
  6525. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6526. /* Two newline, no carriage return - not standard compliant,
  6527. * but
  6528. * it
  6529. * should be accepted */
  6530. return i + 2;
  6531. }
  6532. }
  6533. if (i < buflen - 3) {
  6534. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6535. && (buf[i + 3] == '\n')) {
  6536. /* Two \r\n - standard compliant */
  6537. return i + 4;
  6538. }
  6539. }
  6540. }
  6541. return 0;
  6542. }
  6543. #if !defined(NO_CACHING)
  6544. /* Convert month to the month number. Return -1 on error, or month number */
  6545. static int
  6546. get_month_index(const char *s)
  6547. {
  6548. size_t i;
  6549. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6550. if (!strcmp(s, month_names[i])) {
  6551. return (int)i;
  6552. }
  6553. }
  6554. return -1;
  6555. }
  6556. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6557. static time_t
  6558. parse_date_string(const char *datetime)
  6559. {
  6560. char month_str[32] = {0};
  6561. int second, minute, hour, day, month, year;
  6562. time_t result = (time_t)0;
  6563. struct tm tm;
  6564. if ((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. "%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. "%*3s, %d %3s %d %d:%d:%d",
  6584. &day,
  6585. month_str,
  6586. &year,
  6587. &hour,
  6588. &minute,
  6589. &second)
  6590. == 6)
  6591. || (sscanf(datetime,
  6592. "%d-%3s-%d %d:%d:%d",
  6593. &day,
  6594. month_str,
  6595. &year,
  6596. &hour,
  6597. &minute,
  6598. &second)
  6599. == 6)) {
  6600. month = get_month_index(month_str);
  6601. if ((month >= 0) && (year >= 1970)) {
  6602. memset(&tm, 0, sizeof(tm));
  6603. tm.tm_year = year - 1900;
  6604. tm.tm_mon = month;
  6605. tm.tm_mday = day;
  6606. tm.tm_hour = hour;
  6607. tm.tm_min = minute;
  6608. tm.tm_sec = second;
  6609. result = timegm(&tm);
  6610. }
  6611. }
  6612. return result;
  6613. }
  6614. #endif /* !NO_CACHING */
  6615. /* Protect against directory disclosure attack by removing '..',
  6616. * excessive '/' and '\' characters */
  6617. static void
  6618. remove_double_dots_and_double_slashes(char *s)
  6619. {
  6620. char *p = s;
  6621. while ((s[0] == '.') && (s[1] == '.')) {
  6622. s++;
  6623. }
  6624. while (*s != '\0') {
  6625. *p++ = *s++;
  6626. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6627. /* Skip all following slashes, backslashes and double-dots */
  6628. while (s[0] != '\0') {
  6629. if ((s[0] == '/') || (s[0] == '\\')) {
  6630. s++;
  6631. } else if ((s[0] == '.') && (s[1] == '.')) {
  6632. s += 2;
  6633. } else {
  6634. break;
  6635. }
  6636. }
  6637. }
  6638. }
  6639. *p = '\0';
  6640. }
  6641. static const struct {
  6642. const char *extension;
  6643. size_t ext_len;
  6644. const char *mime_type;
  6645. } builtin_mime_types[] = {
  6646. /* IANA registered MIME types
  6647. * (http://www.iana.org/assignments/media-types)
  6648. * application types */
  6649. {".doc", 4, "application/msword"},
  6650. {".eps", 4, "application/postscript"},
  6651. {".exe", 4, "application/octet-stream"},
  6652. {".js", 3, "application/javascript"},
  6653. {".json", 5, "application/json"},
  6654. {".pdf", 4, "application/pdf"},
  6655. {".ps", 3, "application/postscript"},
  6656. {".rtf", 4, "application/rtf"},
  6657. {".xhtml", 6, "application/xhtml+xml"},
  6658. {".xsl", 4, "application/xml"},
  6659. {".xslt", 5, "application/xml"},
  6660. /* fonts */
  6661. {".ttf", 4, "application/font-sfnt"},
  6662. {".cff", 4, "application/font-sfnt"},
  6663. {".otf", 4, "application/font-sfnt"},
  6664. {".aat", 4, "application/font-sfnt"},
  6665. {".sil", 4, "application/font-sfnt"},
  6666. {".pfr", 4, "application/font-tdpfr"},
  6667. {".woff", 5, "application/font-woff"},
  6668. /* audio */
  6669. {".mp3", 4, "audio/mpeg"},
  6670. {".oga", 4, "audio/ogg"},
  6671. {".ogg", 4, "audio/ogg"},
  6672. /* image */
  6673. {".gif", 4, "image/gif"},
  6674. {".ief", 4, "image/ief"},
  6675. {".jpeg", 5, "image/jpeg"},
  6676. {".jpg", 4, "image/jpeg"},
  6677. {".jpm", 4, "image/jpm"},
  6678. {".jpx", 4, "image/jpx"},
  6679. {".png", 4, "image/png"},
  6680. {".svg", 4, "image/svg+xml"},
  6681. {".tif", 4, "image/tiff"},
  6682. {".tiff", 5, "image/tiff"},
  6683. /* model */
  6684. {".wrl", 4, "model/vrml"},
  6685. /* text */
  6686. {".css", 4, "text/css"},
  6687. {".csv", 4, "text/csv"},
  6688. {".htm", 4, "text/html"},
  6689. {".html", 5, "text/html"},
  6690. {".sgm", 4, "text/sgml"},
  6691. {".shtm", 5, "text/html"},
  6692. {".shtml", 6, "text/html"},
  6693. {".txt", 4, "text/plain"},
  6694. {".xml", 4, "text/xml"},
  6695. /* video */
  6696. {".mov", 4, "video/quicktime"},
  6697. {".mp4", 4, "video/mp4"},
  6698. {".mpeg", 5, "video/mpeg"},
  6699. {".mpg", 4, "video/mpeg"},
  6700. {".ogv", 4, "video/ogg"},
  6701. {".qt", 3, "video/quicktime"},
  6702. /* not registered types
  6703. * (http://reference.sitepoint.com/html/mime-types-full,
  6704. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6705. {".arj", 4, "application/x-arj-compressed"},
  6706. {".gz", 3, "application/x-gunzip"},
  6707. {".rar", 4, "application/x-arj-compressed"},
  6708. {".swf", 4, "application/x-shockwave-flash"},
  6709. {".tar", 4, "application/x-tar"},
  6710. {".tgz", 4, "application/x-tar-gz"},
  6711. {".torrent", 8, "application/x-bittorrent"},
  6712. {".ppt", 4, "application/x-mspowerpoint"},
  6713. {".xls", 4, "application/x-msexcel"},
  6714. {".zip", 4, "application/x-zip-compressed"},
  6715. {".aac",
  6716. 4,
  6717. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6718. {".aif", 4, "audio/x-aif"},
  6719. {".m3u", 4, "audio/x-mpegurl"},
  6720. {".mid", 4, "audio/x-midi"},
  6721. {".ra", 3, "audio/x-pn-realaudio"},
  6722. {".ram", 4, "audio/x-pn-realaudio"},
  6723. {".wav", 4, "audio/x-wav"},
  6724. {".bmp", 4, "image/bmp"},
  6725. {".ico", 4, "image/x-icon"},
  6726. {".pct", 4, "image/x-pct"},
  6727. {".pict", 5, "image/pict"},
  6728. {".rgb", 4, "image/x-rgb"},
  6729. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6730. {".asf", 4, "video/x-ms-asf"},
  6731. {".avi", 4, "video/x-msvideo"},
  6732. {".m4v", 4, "video/x-m4v"},
  6733. {NULL, 0, NULL}};
  6734. const char *
  6735. mg_get_builtin_mime_type(const char *path)
  6736. {
  6737. const char *ext;
  6738. size_t i, path_len;
  6739. path_len = strlen(path);
  6740. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6741. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6742. if ((path_len > builtin_mime_types[i].ext_len)
  6743. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6744. return builtin_mime_types[i].mime_type;
  6745. }
  6746. }
  6747. return "text/plain";
  6748. }
  6749. /* Look at the "path" extension and figure what mime type it has.
  6750. * Store mime type in the vector. */
  6751. static void
  6752. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6753. {
  6754. struct vec ext_vec, mime_vec;
  6755. const char *list, *ext;
  6756. size_t path_len;
  6757. path_len = strlen(path);
  6758. if ((conn == NULL) || (vec == NULL)) {
  6759. if (vec != NULL) {
  6760. memset(vec, '\0', sizeof(struct vec));
  6761. }
  6762. return;
  6763. }
  6764. /* Scan user-defined mime types first, in case user wants to
  6765. * override default mime types. */
  6766. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6767. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6768. /* ext now points to the path suffix */
  6769. ext = path + path_len - ext_vec.len;
  6770. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6771. *vec = mime_vec;
  6772. return;
  6773. }
  6774. }
  6775. vec->ptr = mg_get_builtin_mime_type(path);
  6776. vec->len = strlen(vec->ptr);
  6777. }
  6778. /* Stringify binary data. Output buffer must be twice as big as input,
  6779. * because each byte takes 2 bytes in string representation */
  6780. static void
  6781. bin2str(char *to, const unsigned char *p, size_t len)
  6782. {
  6783. static const char *hex = "0123456789abcdef";
  6784. for (; len--; p++) {
  6785. *to++ = hex[p[0] >> 4];
  6786. *to++ = hex[p[0] & 0x0f];
  6787. }
  6788. *to = '\0';
  6789. }
  6790. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6791. */
  6792. char *
  6793. mg_md5(char buf[33], ...)
  6794. {
  6795. md5_byte_t hash[16];
  6796. const char *p;
  6797. va_list ap;
  6798. md5_state_t ctx;
  6799. md5_init(&ctx);
  6800. va_start(ap, buf);
  6801. while ((p = va_arg(ap, const char *)) != NULL) {
  6802. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6803. }
  6804. va_end(ap);
  6805. md5_finish(&ctx, hash);
  6806. bin2str(buf, hash, sizeof(hash));
  6807. return buf;
  6808. }
  6809. /* Check the user's password, return 1 if OK */
  6810. static int
  6811. check_password(const char *method,
  6812. const char *ha1,
  6813. const char *uri,
  6814. const char *nonce,
  6815. const char *nc,
  6816. const char *cnonce,
  6817. const char *qop,
  6818. const char *response)
  6819. {
  6820. char ha2[32 + 1], expected_response[32 + 1];
  6821. /* Some of the parameters may be NULL */
  6822. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6823. || (qop == NULL) || (response == NULL)) {
  6824. return 0;
  6825. }
  6826. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6827. if (strlen(response) != 32) {
  6828. return 0;
  6829. }
  6830. mg_md5(ha2, method, ":", uri, NULL);
  6831. mg_md5(expected_response,
  6832. ha1,
  6833. ":",
  6834. nonce,
  6835. ":",
  6836. nc,
  6837. ":",
  6838. cnonce,
  6839. ":",
  6840. qop,
  6841. ":",
  6842. ha2,
  6843. NULL);
  6844. return mg_strcasecmp(response, expected_response) == 0;
  6845. }
  6846. #if !defined(NO_FILESYSTEMS)
  6847. /* Use the global passwords file, if specified by auth_gpass option,
  6848. * or search for .htpasswd in the requested directory. */
  6849. static void
  6850. open_auth_file(struct mg_connection *conn,
  6851. const char *path,
  6852. struct mg_file *filep)
  6853. {
  6854. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6855. char name[PATH_MAX];
  6856. const char *p, *e,
  6857. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6858. int truncated;
  6859. if (gpass != NULL) {
  6860. /* Use global passwords file */
  6861. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6862. #if defined(DEBUG)
  6863. /* Use mg_cry_internal here, since gpass has been configured. */
  6864. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6865. #endif
  6866. }
  6867. /* Important: using local struct mg_file to test path for
  6868. * is_directory flag. If filep is used, mg_stat() makes it
  6869. * appear as if auth file was opened.
  6870. * TODO(mid): Check if this is still required after rewriting
  6871. * mg_stat */
  6872. } else if (mg_stat(conn, path, &filep->stat)
  6873. && filep->stat.is_directory) {
  6874. mg_snprintf(conn,
  6875. &truncated,
  6876. name,
  6877. sizeof(name),
  6878. "%s/%s",
  6879. path,
  6880. PASSWORDS_FILE_NAME);
  6881. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6882. #if defined(DEBUG)
  6883. /* Don't use mg_cry_internal here, but only a trace, since this
  6884. * is
  6885. * a typical case. It will occur for every directory
  6886. * without a password file. */
  6887. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6888. #endif
  6889. }
  6890. } else {
  6891. /* Try to find .htpasswd in requested directory. */
  6892. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6893. if (e[0] == '/') {
  6894. break;
  6895. }
  6896. }
  6897. mg_snprintf(conn,
  6898. &truncated,
  6899. name,
  6900. sizeof(name),
  6901. "%.*s/%s",
  6902. (int)(e - p),
  6903. p,
  6904. PASSWORDS_FILE_NAME);
  6905. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6906. #if defined(DEBUG)
  6907. /* Don't use mg_cry_internal here, but only a trace, since this
  6908. * is
  6909. * a typical case. It will occur for every directory
  6910. * without a password file. */
  6911. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6912. #endif
  6913. }
  6914. }
  6915. }
  6916. }
  6917. #endif /* NO_FILESYSTEMS */
  6918. /* Parsed Authorization header */
  6919. struct ah {
  6920. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6921. };
  6922. /* Return 1 on success. Always initializes the ah structure. */
  6923. static int
  6924. parse_auth_header(struct mg_connection *conn,
  6925. char *buf,
  6926. size_t buf_size,
  6927. struct ah *ah)
  6928. {
  6929. char *name, *value, *s;
  6930. const char *auth_header;
  6931. uint64_t nonce;
  6932. if (!ah || !conn) {
  6933. return 0;
  6934. }
  6935. (void)memset(ah, 0, sizeof(*ah));
  6936. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6937. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6938. return 0;
  6939. }
  6940. /* Make modifiable copy of the auth header */
  6941. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6942. s = buf;
  6943. /* Parse authorization header */
  6944. for (;;) {
  6945. /* Gobble initial spaces */
  6946. while (isspace((unsigned char)*s)) {
  6947. s++;
  6948. }
  6949. name = skip_quoted(&s, "=", " ", 0);
  6950. /* Value is either quote-delimited, or ends at first comma or space.
  6951. */
  6952. if (s[0] == '\"') {
  6953. s++;
  6954. value = skip_quoted(&s, "\"", " ", '\\');
  6955. if (s[0] == ',') {
  6956. s++;
  6957. }
  6958. } else {
  6959. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6960. * spaces */
  6961. }
  6962. if (*name == '\0') {
  6963. break;
  6964. }
  6965. if (!strcmp(name, "username")) {
  6966. ah->user = value;
  6967. } else if (!strcmp(name, "cnonce")) {
  6968. ah->cnonce = value;
  6969. } else if (!strcmp(name, "response")) {
  6970. ah->response = value;
  6971. } else if (!strcmp(name, "uri")) {
  6972. ah->uri = value;
  6973. } else if (!strcmp(name, "qop")) {
  6974. ah->qop = value;
  6975. } else if (!strcmp(name, "nc")) {
  6976. ah->nc = value;
  6977. } else if (!strcmp(name, "nonce")) {
  6978. ah->nonce = value;
  6979. }
  6980. }
  6981. #if !defined(NO_NONCE_CHECK)
  6982. /* Read the nonce from the response. */
  6983. if (ah->nonce == NULL) {
  6984. return 0;
  6985. }
  6986. s = NULL;
  6987. nonce = strtoull(ah->nonce, &s, 10);
  6988. if ((s == NULL) || (*s != 0)) {
  6989. return 0;
  6990. }
  6991. /* Convert the nonce from the client to a number. */
  6992. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6993. /* The converted number corresponds to the time the nounce has been
  6994. * created. This should not be earlier than the server start. */
  6995. /* Server side nonce check is valuable in all situations but one:
  6996. * if the server restarts frequently, but the client should not see
  6997. * that, so the server should accept nonces from previous starts. */
  6998. /* However, the reasonable default is to not accept a nonce from a
  6999. * previous start, so if anyone changed the access rights between
  7000. * two restarts, a new login is required. */
  7001. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  7002. /* nonce is from a previous start of the server and no longer valid
  7003. * (replay attack?) */
  7004. return 0;
  7005. }
  7006. /* Check if the nonce is too high, so it has not (yet) been used by the
  7007. * server. */
  7008. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  7009. + conn->dom_ctx->nonce_count)) {
  7010. return 0;
  7011. }
  7012. #else
  7013. (void)nonce;
  7014. #endif
  7015. /* CGI needs it as REMOTE_USER */
  7016. if (ah->user != NULL) {
  7017. conn->request_info.remote_user =
  7018. mg_strdup_ctx(ah->user, conn->phys_ctx);
  7019. } else {
  7020. return 0;
  7021. }
  7022. return 1;
  7023. }
  7024. static const char *
  7025. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  7026. {
  7027. #if defined(MG_USE_OPEN_FILE)
  7028. const char *eof;
  7029. size_t len;
  7030. const char *memend;
  7031. #else
  7032. (void)p; /* parameter is unused */
  7033. #endif
  7034. if (!filep) {
  7035. return NULL;
  7036. }
  7037. #if defined(MG_USE_OPEN_FILE)
  7038. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  7039. memend = (const char *)&filep->access.membuf[filep->stat.size];
  7040. /* Search for \n from p till the end of stream */
  7041. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  7042. if (eof != NULL) {
  7043. eof += 1; /* Include \n */
  7044. } else {
  7045. eof = memend; /* Copy remaining data */
  7046. }
  7047. len =
  7048. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  7049. memcpy(buf, *p, len);
  7050. buf[len] = '\0';
  7051. *p += len;
  7052. return len ? eof : NULL;
  7053. } else /* filep->access.fp block below */
  7054. #endif
  7055. if (filep->access.fp != NULL) {
  7056. return fgets(buf, (int)size, filep->access.fp);
  7057. } else {
  7058. return NULL;
  7059. }
  7060. }
  7061. /* Define the initial recursion depth for procesesing htpasswd files that
  7062. * include other htpasswd
  7063. * (or even the same) files. It is not difficult to provide a file or files
  7064. * s.t. they force civetweb
  7065. * to infinitely recurse and then crash.
  7066. */
  7067. #define INITIAL_DEPTH 9
  7068. #if INITIAL_DEPTH <= 0
  7069. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  7070. #endif
  7071. #if !defined(NO_FILESYSTEMS)
  7072. struct read_auth_file_struct {
  7073. struct mg_connection *conn;
  7074. struct ah ah;
  7075. const char *domain;
  7076. char buf[256 + 256 + 40];
  7077. const char *f_user;
  7078. const char *f_domain;
  7079. const char *f_ha1;
  7080. };
  7081. static int
  7082. read_auth_file(struct mg_file *filep,
  7083. struct read_auth_file_struct *workdata,
  7084. int depth)
  7085. {
  7086. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  7087. int is_authorized = 0;
  7088. struct mg_file fp;
  7089. size_t l;
  7090. if (!filep || !workdata || (0 == depth)) {
  7091. return 0;
  7092. }
  7093. /* Loop over passwords file */
  7094. #if defined(MG_USE_OPEN_FILE)
  7095. p = (char *)filep->access.membuf;
  7096. #endif
  7097. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  7098. l = strlen(workdata->buf);
  7099. while (l > 0) {
  7100. if (isspace((unsigned char)workdata->buf[l - 1])
  7101. || iscntrl((unsigned char)workdata->buf[l - 1])) {
  7102. l--;
  7103. workdata->buf[l] = 0;
  7104. } else
  7105. break;
  7106. }
  7107. if (l < 1) {
  7108. continue;
  7109. }
  7110. workdata->f_user = workdata->buf;
  7111. if (workdata->f_user[0] == ':') {
  7112. /* user names may not contain a ':' and may not be empty,
  7113. * so lines starting with ':' may be used for a special purpose
  7114. */
  7115. if (workdata->f_user[1] == '#') {
  7116. /* :# is a comment */
  7117. continue;
  7118. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  7119. if (mg_fopen(workdata->conn,
  7120. workdata->f_user + 9,
  7121. MG_FOPEN_MODE_READ,
  7122. &fp)) {
  7123. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  7124. (void)mg_fclose(
  7125. &fp.access); /* ignore error on read only file */
  7126. /* No need to continue processing files once we have a
  7127. * match, since nothing will reset it back
  7128. * to 0.
  7129. */
  7130. if (is_authorized) {
  7131. return is_authorized;
  7132. }
  7133. } else {
  7134. mg_cry_internal(workdata->conn,
  7135. "%s: cannot open authorization file: %s",
  7136. __func__,
  7137. workdata->buf);
  7138. }
  7139. continue;
  7140. }
  7141. /* everything is invalid for the moment (might change in the
  7142. * future) */
  7143. mg_cry_internal(workdata->conn,
  7144. "%s: syntax error in authorization file: %s",
  7145. __func__,
  7146. workdata->buf);
  7147. continue;
  7148. }
  7149. workdata->f_domain = strchr(workdata->f_user, ':');
  7150. if (workdata->f_domain == NULL) {
  7151. mg_cry_internal(workdata->conn,
  7152. "%s: syntax error in authorization file: %s",
  7153. __func__,
  7154. workdata->buf);
  7155. continue;
  7156. }
  7157. *(char *)(workdata->f_domain) = 0;
  7158. (workdata->f_domain)++;
  7159. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  7160. if (workdata->f_ha1 == NULL) {
  7161. mg_cry_internal(workdata->conn,
  7162. "%s: syntax error in authorization file: %s",
  7163. __func__,
  7164. workdata->buf);
  7165. continue;
  7166. }
  7167. *(char *)(workdata->f_ha1) = 0;
  7168. (workdata->f_ha1)++;
  7169. if (!strcmp(workdata->ah.user, workdata->f_user)
  7170. && !strcmp(workdata->domain, workdata->f_domain)) {
  7171. return check_password(workdata->conn->request_info.request_method,
  7172. workdata->f_ha1,
  7173. workdata->ah.uri,
  7174. workdata->ah.nonce,
  7175. workdata->ah.nc,
  7176. workdata->ah.cnonce,
  7177. workdata->ah.qop,
  7178. workdata->ah.response);
  7179. }
  7180. }
  7181. return is_authorized;
  7182. }
  7183. /* Authorize against the opened passwords file. Return 1 if authorized. */
  7184. static int
  7185. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  7186. {
  7187. struct read_auth_file_struct workdata;
  7188. char buf[MG_BUF_LEN];
  7189. if (!conn || !conn->dom_ctx) {
  7190. return 0;
  7191. }
  7192. memset(&workdata, 0, sizeof(workdata));
  7193. workdata.conn = conn;
  7194. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  7195. return 0;
  7196. }
  7197. if (realm) {
  7198. workdata.domain = realm;
  7199. } else {
  7200. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7201. }
  7202. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  7203. }
  7204. /* Public function to check http digest authentication header */
  7205. int
  7206. mg_check_digest_access_authentication(struct mg_connection *conn,
  7207. const char *realm,
  7208. const char *filename)
  7209. {
  7210. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7211. int auth;
  7212. if (!conn || !filename) {
  7213. return -1;
  7214. }
  7215. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  7216. return -2;
  7217. }
  7218. auth = authorize(conn, &file, realm);
  7219. mg_fclose(&file.access);
  7220. return auth;
  7221. }
  7222. #endif /* NO_FILESYSTEMS */
  7223. /* Return 1 if request is authorised, 0 otherwise. */
  7224. static int
  7225. check_authorization(struct mg_connection *conn, const char *path)
  7226. {
  7227. #if !defined(NO_FILESYSTEMS)
  7228. char fname[PATH_MAX];
  7229. struct vec uri_vec, filename_vec;
  7230. const char *list;
  7231. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7232. int authorized = 1, truncated;
  7233. if (!conn || !conn->dom_ctx) {
  7234. return 0;
  7235. }
  7236. list = conn->dom_ctx->config[PROTECT_URI];
  7237. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  7238. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  7239. mg_snprintf(conn,
  7240. &truncated,
  7241. fname,
  7242. sizeof(fname),
  7243. "%.*s",
  7244. (int)filename_vec.len,
  7245. filename_vec.ptr);
  7246. if (truncated
  7247. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  7248. mg_cry_internal(conn,
  7249. "%s: cannot open %s: %s",
  7250. __func__,
  7251. fname,
  7252. strerror(errno));
  7253. }
  7254. break;
  7255. }
  7256. }
  7257. if (!is_file_opened(&file.access)) {
  7258. open_auth_file(conn, path, &file);
  7259. }
  7260. if (is_file_opened(&file.access)) {
  7261. authorized = authorize(conn, &file, NULL);
  7262. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7263. }
  7264. return authorized;
  7265. #else
  7266. (void)conn;
  7267. (void)path;
  7268. return 1;
  7269. #endif /* NO_FILESYSTEMS */
  7270. }
  7271. /* Internal function. Assumes conn is valid */
  7272. static void
  7273. send_authorization_request(struct mg_connection *conn, const char *realm)
  7274. {
  7275. char date[64];
  7276. time_t curtime = time(NULL);
  7277. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7278. if (!realm) {
  7279. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7280. }
  7281. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7282. nonce += conn->dom_ctx->nonce_count;
  7283. ++conn->dom_ctx->nonce_count;
  7284. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7285. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7286. conn->status_code = 401;
  7287. conn->must_close = 1;
  7288. gmt_time_string(date, sizeof(date), &curtime);
  7289. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7290. send_no_cache_header(conn);
  7291. send_additional_header(conn);
  7292. mg_printf(conn,
  7293. "Date: %s\r\n"
  7294. "Connection: %s\r\n"
  7295. "Content-Length: 0\r\n"
  7296. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7297. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7298. date,
  7299. suggest_connection_header(conn),
  7300. realm,
  7301. nonce);
  7302. }
  7303. /* Interface function. Parameters are provided by the user, so do
  7304. * at least some basic checks.
  7305. */
  7306. int
  7307. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7308. const char *realm)
  7309. {
  7310. if (conn && conn->dom_ctx) {
  7311. send_authorization_request(conn, realm);
  7312. return 0;
  7313. }
  7314. return -1;
  7315. }
  7316. #if !defined(NO_FILES)
  7317. static int
  7318. is_authorized_for_put(struct mg_connection *conn)
  7319. {
  7320. if (conn) {
  7321. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7322. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7323. int ret = 0;
  7324. if (passfile != NULL
  7325. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7326. ret = authorize(conn, &file, NULL);
  7327. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7328. }
  7329. return ret;
  7330. }
  7331. return 0;
  7332. }
  7333. #endif
  7334. int
  7335. mg_modify_passwords_file(const char *fname,
  7336. const char *domain,
  7337. const char *user,
  7338. const char *pass)
  7339. {
  7340. int found, i;
  7341. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7342. FILE *fp, *fp2;
  7343. found = 0;
  7344. fp = fp2 = NULL;
  7345. /* Regard empty password as no password - remove user record. */
  7346. if ((pass != NULL) && (pass[0] == '\0')) {
  7347. pass = NULL;
  7348. }
  7349. /* Other arguments must not be empty */
  7350. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7351. return 0;
  7352. }
  7353. /* Using the given file format, user name and domain must not contain
  7354. * ':'
  7355. */
  7356. if (strchr(user, ':') != NULL) {
  7357. return 0;
  7358. }
  7359. if (strchr(domain, ':') != NULL) {
  7360. return 0;
  7361. }
  7362. /* Do not allow control characters like newline in user name and domain.
  7363. * Do not allow excessively long names either. */
  7364. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7365. if (iscntrl((unsigned char)user[i])) {
  7366. return 0;
  7367. }
  7368. }
  7369. if (user[i]) {
  7370. return 0;
  7371. }
  7372. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7373. if (iscntrl((unsigned char)domain[i])) {
  7374. return 0;
  7375. }
  7376. }
  7377. if (domain[i]) {
  7378. return 0;
  7379. }
  7380. /* The maximum length of the path to the password file is limited */
  7381. if ((strlen(fname) + 4) >= PATH_MAX) {
  7382. return 0;
  7383. }
  7384. /* Create a temporary file name. Length has been checked before. */
  7385. strcpy(tmp, fname);
  7386. strcat(tmp, ".tmp");
  7387. /* Create the file if does not exist */
  7388. /* Use of fopen here is OK, since fname is only ASCII */
  7389. if ((fp = fopen(fname, "a+")) != NULL) {
  7390. (void)fclose(fp);
  7391. }
  7392. /* Open the given file and temporary file */
  7393. if ((fp = fopen(fname, "r")) == NULL) {
  7394. return 0;
  7395. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7396. fclose(fp);
  7397. return 0;
  7398. }
  7399. /* Copy the stuff to temporary file */
  7400. while (fgets(line, sizeof(line), fp) != NULL) {
  7401. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7402. continue;
  7403. }
  7404. u[255] = 0;
  7405. d[255] = 0;
  7406. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7407. found++;
  7408. if (pass != NULL) {
  7409. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7410. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7411. }
  7412. } else {
  7413. fprintf(fp2, "%s", line);
  7414. }
  7415. }
  7416. /* If new user, just add it */
  7417. if (!found && (pass != NULL)) {
  7418. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7419. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7420. }
  7421. /* Close files */
  7422. fclose(fp);
  7423. fclose(fp2);
  7424. /* Put the temp file in place of real file */
  7425. IGNORE_UNUSED_RESULT(remove(fname));
  7426. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7427. return 1;
  7428. }
  7429. static int
  7430. is_valid_port(unsigned long port)
  7431. {
  7432. return (port <= 0xffff);
  7433. }
  7434. static int
  7435. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7436. {
  7437. struct addrinfo hints, *res, *ressave;
  7438. int func_ret = 0;
  7439. int gai_ret;
  7440. memset(&hints, 0, sizeof(struct addrinfo));
  7441. hints.ai_family = af;
  7442. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7443. if (gai_ret != 0) {
  7444. /* gai_strerror could be used to convert gai_ret to a string */
  7445. /* POSIX return values: see
  7446. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7447. */
  7448. /* Windows return values: see
  7449. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7450. */
  7451. return 0;
  7452. }
  7453. ressave = res;
  7454. while (res) {
  7455. if (dstlen >= (size_t)res->ai_addrlen) {
  7456. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7457. func_ret = 1;
  7458. }
  7459. res = res->ai_next;
  7460. }
  7461. freeaddrinfo(ressave);
  7462. return func_ret;
  7463. }
  7464. static int
  7465. connect_socket(struct mg_context *ctx /* may be NULL */,
  7466. const char *host,
  7467. int port,
  7468. int use_ssl,
  7469. char *ebuf,
  7470. size_t ebuf_len,
  7471. SOCKET *sock /* output: socket, must not be NULL */,
  7472. union usa *sa /* output: socket address, must not be NULL */
  7473. )
  7474. {
  7475. int ip_ver = 0;
  7476. int conn_ret = -1;
  7477. int sockerr = 0;
  7478. *sock = INVALID_SOCKET;
  7479. memset(sa, 0, sizeof(*sa));
  7480. if (ebuf_len > 0) {
  7481. *ebuf = 0;
  7482. }
  7483. if (host == NULL) {
  7484. mg_snprintf(NULL,
  7485. NULL, /* No truncation check for ebuf */
  7486. ebuf,
  7487. ebuf_len,
  7488. "%s",
  7489. "NULL host");
  7490. return 0;
  7491. }
  7492. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7493. mg_snprintf(NULL,
  7494. NULL, /* No truncation check for ebuf */
  7495. ebuf,
  7496. ebuf_len,
  7497. "%s",
  7498. "invalid port");
  7499. return 0;
  7500. }
  7501. #if !defined(NO_SSL)
  7502. #if !defined(NO_SSL_DL)
  7503. #if defined(OPENSSL_API_1_1)
  7504. if (use_ssl && (TLS_client_method == NULL)) {
  7505. mg_snprintf(NULL,
  7506. NULL, /* No truncation check for ebuf */
  7507. ebuf,
  7508. ebuf_len,
  7509. "%s",
  7510. "SSL is not initialized");
  7511. return 0;
  7512. }
  7513. #else
  7514. if (use_ssl && (SSLv23_client_method == NULL)) {
  7515. mg_snprintf(NULL,
  7516. NULL, /* No truncation check for ebuf */
  7517. ebuf,
  7518. ebuf_len,
  7519. "%s",
  7520. "SSL is not initialized");
  7521. return 0;
  7522. }
  7523. #endif /* OPENSSL_API_1_1 */
  7524. #else
  7525. (void)use_ssl;
  7526. #endif /* NO_SSL_DL */
  7527. #else
  7528. (void)use_ssl;
  7529. #endif /* !defined(NO_SSL) */
  7530. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7531. sa->sin.sin_family = AF_INET;
  7532. sa->sin.sin_port = htons((uint16_t)port);
  7533. ip_ver = 4;
  7534. #if defined(USE_IPV6)
  7535. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7536. sa->sin6.sin6_family = AF_INET6;
  7537. sa->sin6.sin6_port = htons((uint16_t)port);
  7538. ip_ver = 6;
  7539. } else if (host[0] == '[') {
  7540. /* While getaddrinfo on Windows will work with [::1],
  7541. * getaddrinfo on Linux only works with ::1 (without []). */
  7542. size_t l = strlen(host + 1);
  7543. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7544. if (h) {
  7545. h[l - 1] = 0;
  7546. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7547. sa->sin6.sin6_family = AF_INET6;
  7548. sa->sin6.sin6_port = htons((uint16_t)port);
  7549. ip_ver = 6;
  7550. }
  7551. mg_free(h);
  7552. }
  7553. #endif
  7554. }
  7555. if (ip_ver == 0) {
  7556. mg_snprintf(NULL,
  7557. NULL, /* No truncation check for ebuf */
  7558. ebuf,
  7559. ebuf_len,
  7560. "%s",
  7561. "host not found");
  7562. return 0;
  7563. }
  7564. if (ip_ver == 4) {
  7565. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7566. }
  7567. #if defined(USE_IPV6)
  7568. else if (ip_ver == 6) {
  7569. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7570. }
  7571. #endif
  7572. if (*sock == INVALID_SOCKET) {
  7573. mg_snprintf(NULL,
  7574. NULL, /* No truncation check for ebuf */
  7575. ebuf,
  7576. ebuf_len,
  7577. "socket(): %s",
  7578. strerror(ERRNO));
  7579. return 0;
  7580. }
  7581. if (0 != set_non_blocking_mode(*sock)) {
  7582. mg_snprintf(NULL,
  7583. NULL, /* No truncation check for ebuf */
  7584. ebuf,
  7585. ebuf_len,
  7586. "Cannot set socket to non-blocking: %s",
  7587. strerror(ERRNO));
  7588. closesocket(*sock);
  7589. *sock = INVALID_SOCKET;
  7590. return 0;
  7591. }
  7592. set_close_on_exec(*sock, NULL, ctx);
  7593. if (ip_ver == 4) {
  7594. /* connected with IPv4 */
  7595. conn_ret = connect(*sock,
  7596. (struct sockaddr *)((void *)&sa->sin),
  7597. sizeof(sa->sin));
  7598. }
  7599. #if defined(USE_IPV6)
  7600. else if (ip_ver == 6) {
  7601. /* connected with IPv6 */
  7602. conn_ret = connect(*sock,
  7603. (struct sockaddr *)((void *)&sa->sin6),
  7604. sizeof(sa->sin6));
  7605. }
  7606. #endif
  7607. if (conn_ret != 0) {
  7608. sockerr = ERRNO;
  7609. }
  7610. #if defined(_WIN32)
  7611. if ((conn_ret != 0) && (sockerr == WSAEWOULDBLOCK)) {
  7612. #else
  7613. if ((conn_ret != 0) && (sockerr == EINPROGRESS)) {
  7614. #endif
  7615. /* Data for getsockopt */
  7616. void *psockerr = &sockerr;
  7617. int ret;
  7618. #if defined(_WIN32)
  7619. int len = (int)sizeof(sockerr);
  7620. #else
  7621. socklen_t len = (socklen_t)sizeof(sockerr);
  7622. #endif
  7623. /* Data for poll */
  7624. struct mg_pollfd pfd[1];
  7625. int pollres;
  7626. int ms_wait = 10000; /* 10 second timeout */
  7627. int nonstop = 0;
  7628. /* For a non-blocking socket, the connect sequence is:
  7629. * 1) call connect (will not block)
  7630. * 2) wait until the socket is ready for writing (select or poll)
  7631. * 3) check connection state with getsockopt
  7632. */
  7633. pfd[0].fd = *sock;
  7634. pfd[0].events = POLLOUT;
  7635. pollres = mg_poll(pfd, 1, ms_wait, ctx ? &(ctx->stop_flag) : &nonstop);
  7636. if (pollres != 1) {
  7637. /* Not connected */
  7638. mg_snprintf(NULL,
  7639. NULL, /* No truncation check for ebuf */
  7640. ebuf,
  7641. ebuf_len,
  7642. "connect(%s:%d): timeout",
  7643. host,
  7644. port);
  7645. closesocket(*sock);
  7646. *sock = INVALID_SOCKET;
  7647. return 0;
  7648. }
  7649. #if defined(_WIN32)
  7650. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7651. #else
  7652. ret = getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7653. #endif
  7654. if ((ret == 0) && (sockerr == 0)) {
  7655. conn_ret = 0;
  7656. }
  7657. }
  7658. if (conn_ret != 0) {
  7659. /* Not connected */
  7660. mg_snprintf(NULL,
  7661. NULL, /* No truncation check for ebuf */
  7662. ebuf,
  7663. ebuf_len,
  7664. "connect(%s:%d): error %s",
  7665. host,
  7666. port,
  7667. strerror(sockerr));
  7668. closesocket(*sock);
  7669. *sock = INVALID_SOCKET;
  7670. return 0;
  7671. }
  7672. return 1;
  7673. }
  7674. int
  7675. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7676. {
  7677. static const char *dont_escape = "._-$,;~()";
  7678. static const char *hex = "0123456789abcdef";
  7679. char *pos = dst;
  7680. const char *end = dst + dst_len - 1;
  7681. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7682. if (isalnum((unsigned char)*src)
  7683. || (strchr(dont_escape, *src) != NULL)) {
  7684. *pos = *src;
  7685. } else if (pos + 2 < end) {
  7686. pos[0] = '%';
  7687. pos[1] = hex[(unsigned char)*src >> 4];
  7688. pos[2] = hex[(unsigned char)*src & 0xf];
  7689. pos += 2;
  7690. } else {
  7691. break;
  7692. }
  7693. }
  7694. *pos = '\0';
  7695. return (*src == '\0') ? (int)(pos - dst) : -1;
  7696. }
  7697. /* Return 0 on success, non-zero if an error occurs. */
  7698. static int
  7699. print_dir_entry(struct de *de)
  7700. {
  7701. size_t namesize, escsize, i;
  7702. char *href, *esc, *p;
  7703. char size[64], mod[64];
  7704. #if defined(REENTRANT_TIME)
  7705. struct tm _tm;
  7706. struct tm *tm = &_tm;
  7707. #else
  7708. struct tm *tm;
  7709. #endif
  7710. /* Estimate worst case size for encoding and escaping */
  7711. namesize = strlen(de->file_name) + 1;
  7712. escsize = de->file_name[strcspn(de->file_name, "&<>")] ? namesize * 5 : 0;
  7713. href = (char *)mg_malloc(namesize * 3 + escsize);
  7714. if (href == NULL) {
  7715. return -1;
  7716. }
  7717. mg_url_encode(de->file_name, href, namesize * 3);
  7718. esc = NULL;
  7719. if (escsize > 0) {
  7720. /* HTML escaping needed */
  7721. esc = href + namesize * 3;
  7722. for (i = 0, p = esc; de->file_name[i]; i++, p += strlen(p)) {
  7723. mg_strlcpy(p, de->file_name + i, 2);
  7724. if (*p == '&') {
  7725. strcpy(p, "&amp;");
  7726. } else if (*p == '<') {
  7727. strcpy(p, "&lt;");
  7728. } else if (*p == '>') {
  7729. strcpy(p, "&gt;");
  7730. }
  7731. }
  7732. }
  7733. if (de->file.is_directory) {
  7734. mg_snprintf(de->conn,
  7735. NULL, /* Buffer is big enough */
  7736. size,
  7737. sizeof(size),
  7738. "%s",
  7739. "[DIRECTORY]");
  7740. } else {
  7741. /* We use (signed) cast below because MSVC 6 compiler cannot
  7742. * convert unsigned __int64 to double. Sigh. */
  7743. if (de->file.size < 1024) {
  7744. mg_snprintf(de->conn,
  7745. NULL, /* Buffer is big enough */
  7746. size,
  7747. sizeof(size),
  7748. "%d",
  7749. (int)de->file.size);
  7750. } else if (de->file.size < 0x100000) {
  7751. mg_snprintf(de->conn,
  7752. NULL, /* Buffer is big enough */
  7753. size,
  7754. sizeof(size),
  7755. "%.1fk",
  7756. (double)de->file.size / 1024.0);
  7757. } else if (de->file.size < 0x40000000) {
  7758. mg_snprintf(de->conn,
  7759. NULL, /* Buffer is big enough */
  7760. size,
  7761. sizeof(size),
  7762. "%.1fM",
  7763. (double)de->file.size / 1048576);
  7764. } else {
  7765. mg_snprintf(de->conn,
  7766. NULL, /* Buffer is big enough */
  7767. size,
  7768. sizeof(size),
  7769. "%.1fG",
  7770. (double)de->file.size / 1073741824);
  7771. }
  7772. }
  7773. /* Note: mg_snprintf will not cause a buffer overflow above.
  7774. * So, string truncation checks are not required here. */
  7775. #if defined(REENTRANT_TIME)
  7776. localtime_r(&de->file.last_modified, tm);
  7777. #else
  7778. tm = localtime(&de->file.last_modified);
  7779. #endif
  7780. if (tm != NULL) {
  7781. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7782. } else {
  7783. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7784. mod[sizeof(mod) - 1] = '\0';
  7785. }
  7786. mg_printf(de->conn,
  7787. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  7788. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7789. href,
  7790. de->file.is_directory ? "/" : "",
  7791. esc ? esc : de->file_name,
  7792. de->file.is_directory ? "/" : "",
  7793. mod,
  7794. size);
  7795. mg_free(href);
  7796. return 0;
  7797. }
  7798. /* This function is called from send_directory() and used for
  7799. * sorting directory entries by size, or name, or modification time.
  7800. * On windows, __cdecl specification is needed in case if project is built
  7801. * with __stdcall convention. qsort always requires __cdels callback. */
  7802. static int WINCDECL
  7803. compare_dir_entries(const void *p1, const void *p2)
  7804. {
  7805. if (p1 && p2) {
  7806. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7807. const char *query_string = a->conn->request_info.query_string;
  7808. int cmp_result = 0;
  7809. if ((query_string == NULL) || (query_string[0] == '\0')) {
  7810. query_string = "n";
  7811. }
  7812. if (a->file.is_directory && !b->file.is_directory) {
  7813. return -1; /* Always put directories on top */
  7814. } else if (!a->file.is_directory && b->file.is_directory) {
  7815. return 1; /* Always put directories on top */
  7816. } else if (*query_string == 'n') {
  7817. cmp_result = strcmp(a->file_name, b->file_name);
  7818. } else if (*query_string == 's') {
  7819. cmp_result = (a->file.size == b->file.size)
  7820. ? 0
  7821. : ((a->file.size > b->file.size) ? 1 : -1);
  7822. } else if (*query_string == 'd') {
  7823. cmp_result =
  7824. (a->file.last_modified == b->file.last_modified)
  7825. ? 0
  7826. : ((a->file.last_modified > b->file.last_modified) ? 1
  7827. : -1);
  7828. }
  7829. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7830. }
  7831. return 0;
  7832. }
  7833. static int
  7834. must_hide_file(struct mg_connection *conn, const char *path)
  7835. {
  7836. if (conn && conn->dom_ctx) {
  7837. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7838. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7839. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7840. || ((pattern != NULL)
  7841. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7842. }
  7843. return 0;
  7844. }
  7845. #if !defined(NO_FILESYSTEMS)
  7846. static int
  7847. scan_directory(struct mg_connection *conn,
  7848. const char *dir,
  7849. void *data,
  7850. int (*cb)(struct de *, void *))
  7851. {
  7852. char path[PATH_MAX];
  7853. struct dirent *dp;
  7854. DIR *dirp;
  7855. struct de de;
  7856. int truncated;
  7857. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7858. return 0;
  7859. } else {
  7860. de.conn = conn;
  7861. while ((dp = mg_readdir(dirp)) != NULL) {
  7862. /* Do not show current dir and hidden files */
  7863. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7864. || must_hide_file(conn, dp->d_name)) {
  7865. continue;
  7866. }
  7867. mg_snprintf(
  7868. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7869. /* If we don't memset stat structure to zero, mtime will have
  7870. * garbage and strftime() will segfault later on in
  7871. * print_dir_entry(). memset is required only if mg_stat()
  7872. * fails. For more details, see
  7873. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7874. memset(&de.file, 0, sizeof(de.file));
  7875. if (truncated) {
  7876. /* If the path is not complete, skip processing. */
  7877. continue;
  7878. }
  7879. if (!mg_stat(conn, path, &de.file)) {
  7880. mg_cry_internal(conn,
  7881. "%s: mg_stat(%s) failed: %s",
  7882. __func__,
  7883. path,
  7884. strerror(ERRNO));
  7885. }
  7886. de.file_name = dp->d_name;
  7887. cb(&de, data);
  7888. }
  7889. (void)mg_closedir(dirp);
  7890. }
  7891. return 1;
  7892. }
  7893. #endif /* NO_FILESYSTEMS */
  7894. #if !defined(NO_FILES)
  7895. static int
  7896. remove_directory(struct mg_connection *conn, const char *dir)
  7897. {
  7898. char path[PATH_MAX];
  7899. struct dirent *dp;
  7900. DIR *dirp;
  7901. struct de de;
  7902. int truncated;
  7903. int ok = 1;
  7904. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7905. return 0;
  7906. } else {
  7907. de.conn = conn;
  7908. while ((dp = mg_readdir(dirp)) != NULL) {
  7909. /* Do not show current dir (but show hidden files as they will
  7910. * also be removed) */
  7911. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7912. continue;
  7913. }
  7914. mg_snprintf(
  7915. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7916. /* If we don't memset stat structure to zero, mtime will have
  7917. * garbage and strftime() will segfault later on in
  7918. * print_dir_entry(). memset is required only if mg_stat()
  7919. * fails. For more details, see
  7920. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7921. memset(&de.file, 0, sizeof(de.file));
  7922. if (truncated) {
  7923. /* Do not delete anything shorter */
  7924. ok = 0;
  7925. continue;
  7926. }
  7927. if (!mg_stat(conn, path, &de.file)) {
  7928. mg_cry_internal(conn,
  7929. "%s: mg_stat(%s) failed: %s",
  7930. __func__,
  7931. path,
  7932. strerror(ERRNO));
  7933. ok = 0;
  7934. }
  7935. if (de.file.is_directory) {
  7936. if (remove_directory(conn, path) == 0) {
  7937. ok = 0;
  7938. }
  7939. } else {
  7940. /* This will fail file is the file is in memory */
  7941. if (mg_remove(conn, path) == 0) {
  7942. ok = 0;
  7943. }
  7944. }
  7945. }
  7946. (void)mg_closedir(dirp);
  7947. IGNORE_UNUSED_RESULT(rmdir(dir));
  7948. }
  7949. return ok;
  7950. }
  7951. #endif
  7952. struct dir_scan_data {
  7953. struct de *entries;
  7954. unsigned int num_entries;
  7955. unsigned int arr_size;
  7956. };
  7957. /* Behaves like realloc(), but frees original pointer on failure */
  7958. static void *
  7959. realloc2(void *ptr, size_t size)
  7960. {
  7961. void *new_ptr = mg_realloc(ptr, size);
  7962. if (new_ptr == NULL) {
  7963. mg_free(ptr);
  7964. }
  7965. return new_ptr;
  7966. }
  7967. #if !defined(NO_FILESYSTEMS)
  7968. static int
  7969. dir_scan_callback(struct de *de, void *data)
  7970. {
  7971. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7972. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7973. dsd->arr_size *= 2;
  7974. dsd->entries =
  7975. (struct de *)realloc2(dsd->entries,
  7976. dsd->arr_size * sizeof(dsd->entries[0]));
  7977. }
  7978. if (dsd->entries == NULL) {
  7979. /* TODO(lsm, low): propagate an error to the caller */
  7980. dsd->num_entries = 0;
  7981. } else {
  7982. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7983. dsd->entries[dsd->num_entries].file = de->file;
  7984. dsd->entries[dsd->num_entries].conn = de->conn;
  7985. dsd->num_entries++;
  7986. }
  7987. return 0;
  7988. }
  7989. static void
  7990. handle_directory_request(struct mg_connection *conn, const char *dir)
  7991. {
  7992. unsigned int i;
  7993. int sort_direction;
  7994. struct dir_scan_data data = {NULL, 0, 128};
  7995. char date[64], *esc, *p;
  7996. const char *title;
  7997. time_t curtime = time(NULL);
  7998. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7999. mg_send_http_error(conn,
  8000. 500,
  8001. "Error: Cannot open directory\nopendir(%s): %s",
  8002. dir,
  8003. strerror(ERRNO));
  8004. return;
  8005. }
  8006. gmt_time_string(date, sizeof(date), &curtime);
  8007. if (!conn) {
  8008. return;
  8009. }
  8010. esc = NULL;
  8011. title = conn->request_info.local_uri;
  8012. if (title[strcspn(title, "&<>")]) {
  8013. /* HTML escaping needed */
  8014. esc = (char *)mg_malloc(strlen(title) * 5 + 1);
  8015. if (esc) {
  8016. for (i = 0, p = esc; title[i]; i++, p += strlen(p)) {
  8017. mg_strlcpy(p, title + i, 2);
  8018. if (*p == '&') {
  8019. strcpy(p, "&amp;");
  8020. } else if (*p == '<') {
  8021. strcpy(p, "&lt;");
  8022. } else if (*p == '>') {
  8023. strcpy(p, "&gt;");
  8024. }
  8025. }
  8026. } else {
  8027. title = "";
  8028. }
  8029. }
  8030. sort_direction = ((conn->request_info.query_string != NULL)
  8031. && (conn->request_info.query_string[0] != '\0')
  8032. && (conn->request_info.query_string[1] == 'd'))
  8033. ? 'a'
  8034. : 'd';
  8035. conn->must_close = 1;
  8036. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  8037. send_static_cache_header(conn);
  8038. send_additional_header(conn);
  8039. mg_printf(conn,
  8040. "Date: %s\r\n"
  8041. "Connection: close\r\n"
  8042. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  8043. date);
  8044. mg_printf(conn,
  8045. "<html><head><title>Index of %s</title>"
  8046. "<style>th {text-align: left;}</style></head>"
  8047. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  8048. "<tr><th><a href=\"?n%c\">Name</a></th>"
  8049. "<th><a href=\"?d%c\">Modified</a></th>"
  8050. "<th><a href=\"?s%c\">Size</a></th></tr>"
  8051. "<tr><td colspan=\"3\"><hr></td></tr>",
  8052. esc ? esc : title,
  8053. esc ? esc : title,
  8054. sort_direction,
  8055. sort_direction,
  8056. sort_direction);
  8057. mg_free(esc);
  8058. /* Print first entry - link to a parent directory */
  8059. mg_printf(conn,
  8060. "<tr><td><a href=\"%s\">%s</a></td>"
  8061. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  8062. "..",
  8063. "Parent directory",
  8064. "-",
  8065. "-");
  8066. /* Sort and print directory entries */
  8067. if (data.entries != NULL) {
  8068. qsort(data.entries,
  8069. (size_t)data.num_entries,
  8070. sizeof(data.entries[0]),
  8071. compare_dir_entries);
  8072. for (i = 0; i < data.num_entries; i++) {
  8073. print_dir_entry(&data.entries[i]);
  8074. mg_free(data.entries[i].file_name);
  8075. }
  8076. mg_free(data.entries);
  8077. }
  8078. mg_printf(conn, "%s", "</table></pre></body></html>");
  8079. conn->status_code = 200;
  8080. }
  8081. #endif /* NO_FILESYSTEMS */
  8082. /* Send len bytes from the opened file to the client. */
  8083. static void
  8084. send_file_data(struct mg_connection *conn,
  8085. struct mg_file *filep,
  8086. int64_t offset,
  8087. int64_t len)
  8088. {
  8089. char buf[MG_BUF_LEN];
  8090. int to_read, num_read, num_written;
  8091. int64_t size;
  8092. if (!filep || !conn) {
  8093. return;
  8094. }
  8095. /* Sanity check the offset */
  8096. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  8097. : (int64_t)(filep->stat.size);
  8098. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  8099. #if defined(MG_USE_OPEN_FILE)
  8100. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  8101. /* file stored in memory */
  8102. if (len > size - offset) {
  8103. len = size - offset;
  8104. }
  8105. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  8106. } else /* else block below */
  8107. #endif
  8108. if (len > 0 && filep->access.fp != NULL) {
  8109. /* file stored on disk */
  8110. #if defined(__linux__)
  8111. /* sendfile is only available for Linux */
  8112. if ((conn->ssl == 0) && (conn->throttle == 0)
  8113. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  8114. "yes"))) {
  8115. off_t sf_offs = (off_t)offset;
  8116. ssize_t sf_sent;
  8117. int sf_file = fileno(filep->access.fp);
  8118. int loop_cnt = 0;
  8119. do {
  8120. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  8121. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  8122. size_t sf_tosend =
  8123. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  8124. sf_sent =
  8125. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  8126. if (sf_sent > 0) {
  8127. len -= sf_sent;
  8128. offset += sf_sent;
  8129. } else if (loop_cnt == 0) {
  8130. /* This file can not be sent using sendfile.
  8131. * This might be the case for pseudo-files in the
  8132. * /sys/ and /proc/ file system.
  8133. * Use the regular user mode copy code instead. */
  8134. break;
  8135. } else if (sf_sent == 0) {
  8136. /* No error, but 0 bytes sent. May be EOF? */
  8137. return;
  8138. }
  8139. loop_cnt++;
  8140. } while ((len > 0) && (sf_sent >= 0));
  8141. if (sf_sent > 0) {
  8142. return; /* OK */
  8143. }
  8144. /* sf_sent<0 means error, thus fall back to the classic way */
  8145. /* This is always the case, if sf_file is not a "normal" file,
  8146. * e.g., for sending data from the output of a CGI process. */
  8147. offset = (int64_t)sf_offs;
  8148. }
  8149. #endif
  8150. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  8151. mg_cry_internal(conn,
  8152. "%s: fseeko() failed: %s",
  8153. __func__,
  8154. strerror(ERRNO));
  8155. mg_send_http_error(
  8156. conn,
  8157. 500,
  8158. "%s",
  8159. "Error: Unable to access file at requested position.");
  8160. } else {
  8161. while (len > 0) {
  8162. /* Calculate how much to read from the file in the buffer */
  8163. to_read = sizeof(buf);
  8164. if ((int64_t)to_read > len) {
  8165. to_read = (int)len;
  8166. }
  8167. /* Read from file, exit the loop on error */
  8168. if ((num_read =
  8169. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  8170. <= 0) {
  8171. break;
  8172. }
  8173. /* Send read bytes to the client, exit the loop on error */
  8174. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  8175. != num_read) {
  8176. break;
  8177. }
  8178. /* Both read and were successful, adjust counters */
  8179. len -= num_written;
  8180. }
  8181. }
  8182. }
  8183. }
  8184. static int
  8185. parse_range_header(const char *header, int64_t *a, int64_t *b)
  8186. {
  8187. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  8188. }
  8189. static void
  8190. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  8191. {
  8192. if ((filestat != NULL) && (buf != NULL)) {
  8193. mg_snprintf(NULL,
  8194. NULL, /* All calls to construct_etag use 64 byte buffer */
  8195. buf,
  8196. buf_len,
  8197. "\"%lx.%" INT64_FMT "\"",
  8198. (unsigned long)filestat->last_modified,
  8199. filestat->size);
  8200. }
  8201. }
  8202. static void
  8203. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  8204. {
  8205. if (filep != NULL && filep->fp != NULL) {
  8206. #if defined(_WIN32)
  8207. (void)conn; /* Unused. */
  8208. #else
  8209. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  8210. mg_cry_internal(conn,
  8211. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  8212. __func__,
  8213. strerror(ERRNO));
  8214. }
  8215. #endif
  8216. }
  8217. }
  8218. #if defined(USE_ZLIB)
  8219. #include "mod_zlib.inl"
  8220. #endif
  8221. #if !defined(NO_FILESYSTEMS)
  8222. static void
  8223. handle_static_file_request(struct mg_connection *conn,
  8224. const char *path,
  8225. struct mg_file *filep,
  8226. const char *mime_type,
  8227. const char *additional_headers)
  8228. {
  8229. char date[64], lm[64], etag[64];
  8230. char range[128]; /* large enough, so there will be no overflow */
  8231. const char *msg = "OK";
  8232. const char *range_hdr;
  8233. time_t curtime = time(NULL);
  8234. int64_t cl, r1, r2;
  8235. struct vec mime_vec;
  8236. int n, truncated;
  8237. char gz_path[PATH_MAX];
  8238. const char *encoding = "";
  8239. const char *origin_hdr;
  8240. const char *cors_orig_cfg;
  8241. const char *cors1, *cors2, *cors3;
  8242. int is_head_request;
  8243. #if defined(USE_ZLIB)
  8244. /* Compression is allowed, unless there is a reason not to use compression.
  8245. * If the file is already compressed, too small or a "range" request was
  8246. * made, on the fly compression is not possible. */
  8247. int allow_on_the_fly_compression = 1;
  8248. #endif
  8249. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  8250. return;
  8251. }
  8252. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  8253. if (mime_type == NULL) {
  8254. get_mime_type(conn, path, &mime_vec);
  8255. } else {
  8256. mime_vec.ptr = mime_type;
  8257. mime_vec.len = strlen(mime_type);
  8258. }
  8259. if (filep->stat.size > INT64_MAX) {
  8260. mg_send_http_error(conn,
  8261. 500,
  8262. "Error: File size is too large to send\n%" INT64_FMT,
  8263. filep->stat.size);
  8264. return;
  8265. }
  8266. cl = (int64_t)filep->stat.size;
  8267. conn->status_code = 200;
  8268. range[0] = '\0';
  8269. #if defined(USE_ZLIB)
  8270. /* if this file is in fact a pre-gzipped file, rewrite its filename
  8271. * it's important to rewrite the filename after resolving
  8272. * the mime type from it, to preserve the actual file's type */
  8273. if (!conn->accept_gzip) {
  8274. allow_on_the_fly_compression = 0;
  8275. }
  8276. #endif
  8277. /* Check if there is a range header */
  8278. range_hdr = mg_get_header(conn, "Range");
  8279. /* For gzipped files, add *.gz */
  8280. if (filep->stat.is_gzipped) {
  8281. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8282. if (truncated) {
  8283. mg_send_http_error(conn,
  8284. 500,
  8285. "Error: Path of zipped file too long (%s)",
  8286. path);
  8287. return;
  8288. }
  8289. path = gz_path;
  8290. encoding = "Content-Encoding: gzip\r\n";
  8291. #if defined(USE_ZLIB)
  8292. /* File is already compressed. No "on the fly" compression. */
  8293. allow_on_the_fly_compression = 0;
  8294. #endif
  8295. } else if ((conn->accept_gzip) && (range_hdr == NULL)
  8296. && (filep->stat.size >= MG_FILE_COMPRESSION_SIZE_LIMIT)) {
  8297. struct mg_file_stat file_stat;
  8298. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  8299. if (!truncated && mg_stat(conn, gz_path, &file_stat)
  8300. && !file_stat.is_directory) {
  8301. file_stat.is_gzipped = 1;
  8302. filep->stat = file_stat;
  8303. cl = (int64_t)filep->stat.size;
  8304. path = gz_path;
  8305. encoding = "Content-Encoding: gzip\r\n";
  8306. #if defined(USE_ZLIB)
  8307. /* File is already compressed. No "on the fly" compression. */
  8308. allow_on_the_fly_compression = 0;
  8309. #endif
  8310. }
  8311. }
  8312. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  8313. mg_send_http_error(conn,
  8314. 500,
  8315. "Error: Cannot open file\nfopen(%s): %s",
  8316. path,
  8317. strerror(ERRNO));
  8318. return;
  8319. }
  8320. fclose_on_exec(&filep->access, conn);
  8321. /* If "Range" request was made: parse header, send only selected part
  8322. * of the file. */
  8323. r1 = r2 = 0;
  8324. if ((range_hdr != NULL)
  8325. && ((n = parse_range_header(range_hdr, &r1, &r2)) > 0) && (r1 >= 0)
  8326. && (r2 >= 0)) {
  8327. /* actually, range requests don't play well with a pre-gzipped
  8328. * file (since the range is specified in the uncompressed space) */
  8329. if (filep->stat.is_gzipped) {
  8330. mg_send_http_error(
  8331. conn,
  8332. 416, /* 416 = Range Not Satisfiable */
  8333. "%s",
  8334. "Error: Range requests in gzipped files are not supported");
  8335. (void)mg_fclose(
  8336. &filep->access); /* ignore error on read only file */
  8337. return;
  8338. }
  8339. conn->status_code = 206;
  8340. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  8341. mg_snprintf(conn,
  8342. NULL, /* range buffer is big enough */
  8343. range,
  8344. sizeof(range),
  8345. "Content-Range: bytes "
  8346. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  8347. r1,
  8348. r1 + cl - 1,
  8349. filep->stat.size);
  8350. msg = "Partial Content";
  8351. #if defined(USE_ZLIB)
  8352. /* Do not compress ranges. */
  8353. allow_on_the_fly_compression = 0;
  8354. #endif
  8355. }
  8356. /* Do not compress small files. Small files do not benefit from file
  8357. * compression, but there is still some overhead. */
  8358. #if defined(USE_ZLIB)
  8359. if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) {
  8360. /* File is below the size limit. */
  8361. allow_on_the_fly_compression = 0;
  8362. }
  8363. #endif
  8364. /* Standard CORS header */
  8365. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8366. origin_hdr = mg_get_header(conn, "Origin");
  8367. if (cors_orig_cfg && *cors_orig_cfg && origin_hdr) {
  8368. /* Cross-origin resource sharing (CORS), see
  8369. * http://www.html5rocks.com/en/tutorials/cors/,
  8370. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8371. * -
  8372. * preflight is not supported for files. */
  8373. cors1 = "Access-Control-Allow-Origin: ";
  8374. cors2 = cors_orig_cfg;
  8375. cors3 = "\r\n";
  8376. } else {
  8377. cors1 = cors2 = cors3 = "";
  8378. }
  8379. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8380. * according to
  8381. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8382. gmt_time_string(date, sizeof(date), &curtime);
  8383. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8384. construct_etag(etag, sizeof(etag), &filep->stat);
  8385. /* Send header */
  8386. (void)mg_printf(conn,
  8387. "HTTP/1.1 %d %s\r\n"
  8388. "%s%s%s" /* CORS */
  8389. "Date: %s\r\n"
  8390. "Last-Modified: %s\r\n"
  8391. "Etag: %s\r\n"
  8392. "Content-Type: %.*s\r\n"
  8393. "Connection: %s\r\n",
  8394. conn->status_code,
  8395. msg,
  8396. cors1,
  8397. cors2,
  8398. cors3,
  8399. date,
  8400. lm,
  8401. etag,
  8402. (int)mime_vec.len,
  8403. mime_vec.ptr,
  8404. suggest_connection_header(conn));
  8405. send_static_cache_header(conn);
  8406. send_additional_header(conn);
  8407. #if defined(USE_ZLIB)
  8408. /* On the fly compression allowed */
  8409. if (allow_on_the_fly_compression) {
  8410. /* For on the fly compression, we don't know the content size in
  8411. * advance, so we have to use chunked encoding */
  8412. (void)mg_printf(conn,
  8413. "Content-Encoding: gzip\r\n"
  8414. "Transfer-Encoding: chunked\r\n");
  8415. } else
  8416. #endif
  8417. {
  8418. /* Without on-the-fly compression, we know the content-length
  8419. * and we can use ranges (with on-the-fly compression we cannot).
  8420. * So we send these response headers only in this case. */
  8421. (void)mg_printf(conn,
  8422. "Content-Length: %" INT64_FMT "\r\n"
  8423. "Accept-Ranges: bytes\r\n"
  8424. "%s" /* range */
  8425. "%s" /* encoding */,
  8426. cl,
  8427. range,
  8428. encoding);
  8429. }
  8430. /* The previous code must not add any header starting with X- to make
  8431. * sure no one of the additional_headers is included twice */
  8432. if (additional_headers != NULL) {
  8433. (void)mg_printf(conn,
  8434. "%.*s\r\n\r\n",
  8435. (int)strlen(additional_headers),
  8436. additional_headers);
  8437. } else {
  8438. (void)mg_printf(conn, "\r\n");
  8439. }
  8440. if (!is_head_request) {
  8441. #if defined(USE_ZLIB)
  8442. if (allow_on_the_fly_compression) {
  8443. /* Compress and send */
  8444. send_compressed_data(conn, filep);
  8445. } else
  8446. #endif
  8447. {
  8448. /* Send file directly */
  8449. send_file_data(conn, filep, r1, cl);
  8450. }
  8451. }
  8452. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8453. }
  8454. int
  8455. mg_send_file_body(struct mg_connection *conn, const char *path)
  8456. {
  8457. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8458. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  8459. return -1;
  8460. }
  8461. fclose_on_exec(&file.access, conn);
  8462. send_file_data(conn, &file, 0, INT64_MAX);
  8463. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  8464. return 0; /* >= 0 for OK */
  8465. }
  8466. #endif /* NO_FILESYSTEMS */
  8467. #if !defined(NO_CACHING)
  8468. /* Return True if we should reply 304 Not Modified. */
  8469. static int
  8470. is_not_modified(const struct mg_connection *conn,
  8471. const struct mg_file_stat *filestat)
  8472. {
  8473. char etag[64];
  8474. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8475. const char *inm = mg_get_header(conn, "If-None-Match");
  8476. construct_etag(etag, sizeof(etag), filestat);
  8477. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8478. || ((ims != NULL)
  8479. && (filestat->last_modified <= parse_date_string(ims)));
  8480. }
  8481. static void
  8482. handle_not_modified_static_file_request(struct mg_connection *conn,
  8483. struct mg_file *filep)
  8484. {
  8485. char date[64], lm[64], etag[64];
  8486. time_t curtime = time(NULL);
  8487. if ((conn == NULL) || (filep == NULL)) {
  8488. return;
  8489. }
  8490. conn->status_code = 304;
  8491. gmt_time_string(date, sizeof(date), &curtime);
  8492. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8493. construct_etag(etag, sizeof(etag), &filep->stat);
  8494. (void)mg_printf(conn,
  8495. "HTTP/1.1 %d %s\r\n"
  8496. "Date: %s\r\n",
  8497. conn->status_code,
  8498. mg_get_response_code_text(conn, conn->status_code),
  8499. date);
  8500. send_static_cache_header(conn);
  8501. send_additional_header(conn);
  8502. (void)mg_printf(conn,
  8503. "Last-Modified: %s\r\n"
  8504. "Etag: %s\r\n"
  8505. "Connection: %s\r\n"
  8506. "\r\n",
  8507. lm,
  8508. etag,
  8509. suggest_connection_header(conn));
  8510. }
  8511. #endif
  8512. #if !defined(NO_FILESYSTEMS)
  8513. void
  8514. mg_send_file(struct mg_connection *conn, const char *path)
  8515. {
  8516. mg_send_mime_file2(conn, path, NULL, NULL);
  8517. }
  8518. void
  8519. mg_send_mime_file(struct mg_connection *conn,
  8520. const char *path,
  8521. const char *mime_type)
  8522. {
  8523. mg_send_mime_file2(conn, path, mime_type, NULL);
  8524. }
  8525. void
  8526. mg_send_mime_file2(struct mg_connection *conn,
  8527. const char *path,
  8528. const char *mime_type,
  8529. const char *additional_headers)
  8530. {
  8531. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8532. if (!conn) {
  8533. /* No conn */
  8534. return;
  8535. }
  8536. if (mg_stat(conn, path, &file.stat)) {
  8537. #if !defined(NO_CACHING)
  8538. if (is_not_modified(conn, &file.stat)) {
  8539. /* Send 304 "Not Modified" - this must not send any body data */
  8540. handle_not_modified_static_file_request(conn, &file);
  8541. } else
  8542. #endif /* NO_CACHING */
  8543. if (file.stat.is_directory) {
  8544. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8545. "yes")) {
  8546. handle_directory_request(conn, path);
  8547. } else {
  8548. mg_send_http_error(conn,
  8549. 403,
  8550. "%s",
  8551. "Error: Directory listing denied");
  8552. }
  8553. } else {
  8554. handle_static_file_request(
  8555. conn, path, &file, mime_type, additional_headers);
  8556. }
  8557. } else {
  8558. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8559. }
  8560. }
  8561. /* For a given PUT path, create all intermediate subdirectories.
  8562. * Return 0 if the path itself is a directory.
  8563. * Return 1 if the path leads to a file.
  8564. * Return -1 for if the path is too long.
  8565. * Return -2 if path can not be created.
  8566. */
  8567. static int
  8568. put_dir(struct mg_connection *conn, const char *path)
  8569. {
  8570. char buf[PATH_MAX];
  8571. const char *s, *p;
  8572. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8573. size_t len;
  8574. int res = 1;
  8575. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8576. len = (size_t)(p - path);
  8577. if (len >= sizeof(buf)) {
  8578. /* path too long */
  8579. res = -1;
  8580. break;
  8581. }
  8582. memcpy(buf, path, len);
  8583. buf[len] = '\0';
  8584. /* Try to create intermediate directory */
  8585. DEBUG_TRACE("mkdir(%s)", buf);
  8586. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8587. /* path does not exixt and can not be created */
  8588. res = -2;
  8589. break;
  8590. }
  8591. /* Is path itself a directory? */
  8592. if (p[1] == '\0') {
  8593. res = 0;
  8594. }
  8595. }
  8596. return res;
  8597. }
  8598. static void
  8599. remove_bad_file(const struct mg_connection *conn, const char *path)
  8600. {
  8601. int r = mg_remove(conn, path);
  8602. if (r != 0) {
  8603. mg_cry_internal(conn,
  8604. "%s: Cannot remove invalid file %s",
  8605. __func__,
  8606. path);
  8607. }
  8608. }
  8609. long long
  8610. mg_store_body(struct mg_connection *conn, const char *path)
  8611. {
  8612. char buf[MG_BUF_LEN];
  8613. long long len = 0;
  8614. int ret, n;
  8615. struct mg_file fi;
  8616. if (conn->consumed_content != 0) {
  8617. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8618. return -11;
  8619. }
  8620. ret = put_dir(conn, path);
  8621. if (ret < 0) {
  8622. /* -1 for path too long,
  8623. * -2 for path can not be created. */
  8624. return ret;
  8625. }
  8626. if (ret != 1) {
  8627. /* Return 0 means, path itself is a directory. */
  8628. return 0;
  8629. }
  8630. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8631. return -12;
  8632. }
  8633. ret = mg_read(conn, buf, sizeof(buf));
  8634. while (ret > 0) {
  8635. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8636. if (n != ret) {
  8637. (void)mg_fclose(
  8638. &fi.access); /* File is bad and will be removed anyway. */
  8639. remove_bad_file(conn, path);
  8640. return -13;
  8641. }
  8642. len += ret;
  8643. ret = mg_read(conn, buf, sizeof(buf));
  8644. }
  8645. /* File is open for writing. If fclose fails, there was probably an
  8646. * error flushing the buffer to disk, so the file on disk might be
  8647. * broken. Delete it and return an error to the caller. */
  8648. if (mg_fclose(&fi.access) != 0) {
  8649. remove_bad_file(conn, path);
  8650. return -14;
  8651. }
  8652. return len;
  8653. }
  8654. #endif /* NO_FILESYSTEMS */
  8655. /* Parse a buffer:
  8656. * Forward the string pointer till the end of a word, then
  8657. * terminate it and forward till the begin of the next word.
  8658. */
  8659. static int
  8660. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8661. {
  8662. /* Forward until a space is found - use isgraph here */
  8663. /* See http://www.cplusplus.com/reference/cctype/ */
  8664. while (isgraph((unsigned char)**ppw)) {
  8665. (*ppw)++;
  8666. }
  8667. /* Check end of word */
  8668. if (eol) {
  8669. /* must be a end of line */
  8670. if ((**ppw != '\r') && (**ppw != '\n')) {
  8671. return -1;
  8672. }
  8673. } else {
  8674. /* must be a end of a word, but not a line */
  8675. if (**ppw != ' ') {
  8676. return -1;
  8677. }
  8678. }
  8679. /* Terminate and forward to the next word */
  8680. do {
  8681. **ppw = 0;
  8682. (*ppw)++;
  8683. } while (isspace((unsigned char)**ppw));
  8684. /* Check after term */
  8685. if (!eol) {
  8686. /* if it's not the end of line, there must be a next word */
  8687. if (!isgraph((unsigned char)**ppw)) {
  8688. return -1;
  8689. }
  8690. }
  8691. /* ok */
  8692. return 1;
  8693. }
  8694. /* Parse HTTP headers from the given buffer, advance buf pointer
  8695. * to the point where parsing stopped.
  8696. * All parameters must be valid pointers (not NULL).
  8697. * Return <0 on error. */
  8698. static int
  8699. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8700. {
  8701. int i;
  8702. int num_headers = 0;
  8703. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8704. char *dp = *buf;
  8705. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8706. dp++;
  8707. }
  8708. if (dp == *buf) {
  8709. /* End of headers reached. */
  8710. break;
  8711. }
  8712. if (*dp != ':') {
  8713. /* This is not a valid field. */
  8714. return -1;
  8715. }
  8716. /* End of header key (*dp == ':') */
  8717. /* Truncate here and set the key name */
  8718. *dp = 0;
  8719. hdr[i].name = *buf;
  8720. do {
  8721. dp++;
  8722. } while (*dp == ' ');
  8723. /* The rest of the line is the value */
  8724. hdr[i].value = dp;
  8725. *buf = dp + strcspn(dp, "\r\n");
  8726. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8727. *buf = NULL;
  8728. }
  8729. num_headers = i + 1;
  8730. if (*buf) {
  8731. (*buf)[0] = 0;
  8732. (*buf)[1] = 0;
  8733. *buf += 2;
  8734. } else {
  8735. *buf = dp;
  8736. break;
  8737. }
  8738. if ((*buf)[0] == '\r') {
  8739. /* This is the end of the header */
  8740. break;
  8741. }
  8742. }
  8743. return num_headers;
  8744. }
  8745. struct mg_http_method_info {
  8746. const char *name;
  8747. int request_has_body;
  8748. int response_has_body;
  8749. int is_safe;
  8750. int is_idempotent;
  8751. int is_cacheable;
  8752. };
  8753. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8754. static struct mg_http_method_info http_methods[] = {
  8755. /* HTTP (RFC 2616) */
  8756. {"GET", 0, 1, 1, 1, 1},
  8757. {"POST", 1, 1, 0, 0, 0},
  8758. {"PUT", 1, 0, 0, 1, 0},
  8759. {"DELETE", 0, 0, 0, 1, 0},
  8760. {"HEAD", 0, 0, 1, 1, 1},
  8761. {"OPTIONS", 0, 0, 1, 1, 0},
  8762. {"CONNECT", 1, 1, 0, 0, 0},
  8763. /* TRACE method (RFC 2616) is not supported for security reasons */
  8764. /* PATCH method (RFC 5789) */
  8765. {"PATCH", 1, 0, 0, 0, 0},
  8766. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8767. /* WEBDAV (RFC 2518) */
  8768. {"PROPFIND", 0, 1, 1, 1, 0},
  8769. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8770. * Some PROPFIND results MAY be cached, with care,
  8771. * as there is no cache validation mechanism for
  8772. * most properties. This method is both safe and
  8773. * idempotent (see Section 9.1 of [RFC2616]). */
  8774. {"MKCOL", 0, 0, 0, 1, 0},
  8775. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8776. * When MKCOL is invoked without a request body,
  8777. * the newly created collection SHOULD have no
  8778. * members. A MKCOL request message may contain
  8779. * a message body. The precise behavior of a MKCOL
  8780. * request when the body is present is undefined,
  8781. * ... ==> We do not support MKCOL with body data.
  8782. * This method is idempotent, but not safe (see
  8783. * Section 9.1 of [RFC2616]). Responses to this
  8784. * method MUST NOT be cached. */
  8785. /* Unsupported WEBDAV Methods: */
  8786. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8787. /* + 11 methods from RFC 3253 */
  8788. /* ORDERPATCH (RFC 3648) */
  8789. /* ACL (RFC 3744) */
  8790. /* SEARCH (RFC 5323) */
  8791. /* + MicroSoft extensions
  8792. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8793. /* REPORT method (RFC 3253) */
  8794. {"REPORT", 1, 1, 1, 1, 1},
  8795. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8796. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8797. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8798. * to be useful for REST in case a "GET request with body" is
  8799. * required. */
  8800. {NULL, 0, 0, 0, 0, 0}
  8801. /* end of list */
  8802. };
  8803. static const struct mg_http_method_info *
  8804. get_http_method_info(const char *method)
  8805. {
  8806. /* Check if the method is known to the server. The list of all known
  8807. * HTTP methods can be found here at
  8808. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8809. */
  8810. const struct mg_http_method_info *m = http_methods;
  8811. while (m->name) {
  8812. if (!strcmp(m->name, method)) {
  8813. return m;
  8814. }
  8815. m++;
  8816. }
  8817. return NULL;
  8818. }
  8819. static int
  8820. is_valid_http_method(const char *method)
  8821. {
  8822. return (get_http_method_info(method) != NULL);
  8823. }
  8824. /* Parse HTTP request, fill in mg_request_info structure.
  8825. * This function modifies the buffer by NUL-terminating
  8826. * HTTP request components, header names and header values.
  8827. * Parameters:
  8828. * buf (in/out): pointer to the HTTP header to parse and split
  8829. * len (in): length of HTTP header buffer
  8830. * re (out): parsed header as mg_request_info
  8831. * buf and ri must be valid pointers (not NULL), len>0.
  8832. * Returns <0 on error. */
  8833. static int
  8834. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8835. {
  8836. int request_length;
  8837. int init_skip = 0;
  8838. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8839. * remote_port */
  8840. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8841. NULL;
  8842. ri->num_headers = 0;
  8843. /* RFC says that all initial whitespaces should be ingored */
  8844. /* This included all leading \r and \n (isspace) */
  8845. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8846. while ((len > 0) && isspace((unsigned char)*buf)) {
  8847. buf++;
  8848. len--;
  8849. init_skip++;
  8850. }
  8851. if (len == 0) {
  8852. /* Incomplete request */
  8853. return 0;
  8854. }
  8855. /* Control characters are not allowed, including zero */
  8856. if (iscntrl((unsigned char)*buf)) {
  8857. return -1;
  8858. }
  8859. /* Find end of HTTP header */
  8860. request_length = get_http_header_len(buf, len);
  8861. if (request_length <= 0) {
  8862. return request_length;
  8863. }
  8864. buf[request_length - 1] = '\0';
  8865. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8866. return -1;
  8867. }
  8868. /* The first word has to be the HTTP method */
  8869. ri->request_method = buf;
  8870. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8871. return -1;
  8872. }
  8873. /* Check for a valid http method */
  8874. if (!is_valid_http_method(ri->request_method)) {
  8875. return -1;
  8876. }
  8877. /* The second word is the URI */
  8878. ri->request_uri = buf;
  8879. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8880. return -1;
  8881. }
  8882. /* Next would be the HTTP version */
  8883. ri->http_version = buf;
  8884. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8885. return -1;
  8886. }
  8887. /* Check for a valid HTTP version key */
  8888. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8889. /* Invalid request */
  8890. return -1;
  8891. }
  8892. ri->http_version += 5;
  8893. /* Parse all HTTP headers */
  8894. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8895. if (ri->num_headers < 0) {
  8896. /* Error while parsing headers */
  8897. return -1;
  8898. }
  8899. return request_length + init_skip;
  8900. }
  8901. static int
  8902. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8903. {
  8904. int response_length;
  8905. int init_skip = 0;
  8906. char *tmp, *tmp2;
  8907. long l;
  8908. /* Initialize elements. */
  8909. ri->http_version = ri->status_text = NULL;
  8910. ri->num_headers = ri->status_code = 0;
  8911. /* RFC says that all initial whitespaces should be ingored */
  8912. /* This included all leading \r and \n (isspace) */
  8913. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8914. while ((len > 0) && isspace((unsigned char)*buf)) {
  8915. buf++;
  8916. len--;
  8917. init_skip++;
  8918. }
  8919. if (len == 0) {
  8920. /* Incomplete request */
  8921. return 0;
  8922. }
  8923. /* Control characters are not allowed, including zero */
  8924. if (iscntrl((unsigned char)*buf)) {
  8925. return -1;
  8926. }
  8927. /* Find end of HTTP header */
  8928. response_length = get_http_header_len(buf, len);
  8929. if (response_length <= 0) {
  8930. return response_length;
  8931. }
  8932. buf[response_length - 1] = '\0';
  8933. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8934. return -1;
  8935. }
  8936. /* The first word is the HTTP version */
  8937. /* Check for a valid HTTP version key */
  8938. if (strncmp(buf, "HTTP/", 5) != 0) {
  8939. /* Invalid request */
  8940. return -1;
  8941. }
  8942. buf += 5;
  8943. if (!isgraph((unsigned char)buf[0])) {
  8944. /* Invalid request */
  8945. return -1;
  8946. }
  8947. ri->http_version = buf;
  8948. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8949. return -1;
  8950. }
  8951. /* The second word is the status as a number */
  8952. tmp = buf;
  8953. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8954. return -1;
  8955. }
  8956. l = strtol(tmp, &tmp2, 10);
  8957. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8958. /* Everything else but a 3 digit code is invalid */
  8959. return -1;
  8960. }
  8961. ri->status_code = (int)l;
  8962. /* The rest of the line is the status text */
  8963. ri->status_text = buf;
  8964. /* Find end of status text */
  8965. /* isgraph or isspace = isprint */
  8966. while (isprint((unsigned char)*buf)) {
  8967. buf++;
  8968. }
  8969. if ((*buf != '\r') && (*buf != '\n')) {
  8970. return -1;
  8971. }
  8972. /* Terminate string and forward buf to next line */
  8973. do {
  8974. *buf = 0;
  8975. buf++;
  8976. } while (isspace((unsigned char)*buf));
  8977. /* Parse all HTTP headers */
  8978. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8979. if (ri->num_headers < 0) {
  8980. /* Error while parsing headers */
  8981. return -1;
  8982. }
  8983. return response_length + init_skip;
  8984. }
  8985. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8986. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8987. * buffer (which marks the end of HTTP request). Buffer buf may already
  8988. * have some data. The length of the data is stored in nread.
  8989. * Upon every read operation, increase nread by the number of bytes read. */
  8990. static int
  8991. read_message(FILE *fp,
  8992. struct mg_connection *conn,
  8993. char *buf,
  8994. int bufsiz,
  8995. int *nread)
  8996. {
  8997. int request_len, n = 0;
  8998. struct timespec last_action_time;
  8999. double request_timeout;
  9000. if (!conn) {
  9001. return 0;
  9002. }
  9003. memset(&last_action_time, 0, sizeof(last_action_time));
  9004. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  9005. /* value of request_timeout is in seconds, config in milliseconds */
  9006. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9007. } else {
  9008. request_timeout = -1.0;
  9009. }
  9010. if (conn->handled_requests > 0) {
  9011. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  9012. request_timeout =
  9013. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  9014. }
  9015. }
  9016. request_len = get_http_header_len(buf, *nread);
  9017. while (request_len == 0) {
  9018. /* Full request not yet received */
  9019. if (conn->phys_ctx->stop_flag != 0) {
  9020. /* Server is to be stopped. */
  9021. return -1;
  9022. }
  9023. if (*nread >= bufsiz) {
  9024. /* Request too long */
  9025. return -2;
  9026. }
  9027. n = pull_inner(
  9028. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  9029. if (n == -2) {
  9030. /* Receive error */
  9031. return -1;
  9032. }
  9033. /* update clock after every read request */
  9034. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  9035. if (n > 0) {
  9036. *nread += n;
  9037. request_len = get_http_header_len(buf, *nread);
  9038. } else {
  9039. request_len = 0;
  9040. }
  9041. if ((request_len == 0) && (request_timeout >= 0)) {
  9042. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  9043. > request_timeout) {
  9044. /* Timeout */
  9045. return -1;
  9046. }
  9047. }
  9048. }
  9049. return request_len;
  9050. }
  9051. #if !defined(NO_CGI) || !defined(NO_FILES)
  9052. static int
  9053. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  9054. {
  9055. const char *expect;
  9056. char buf[MG_BUF_LEN];
  9057. int success = 0;
  9058. if (!conn) {
  9059. return 0;
  9060. }
  9061. expect = mg_get_header(conn, "Expect");
  9062. DEBUG_ASSERT(fp != NULL);
  9063. if (!fp) {
  9064. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  9065. return 0;
  9066. }
  9067. if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) {
  9068. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  9069. */
  9070. mg_send_http_error(conn,
  9071. 417,
  9072. "Error: Can not fulfill expectation");
  9073. } else {
  9074. if (expect != NULL) {
  9075. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  9076. conn->status_code = 100;
  9077. } else {
  9078. conn->status_code = 200;
  9079. }
  9080. DEBUG_ASSERT(conn->consumed_content == 0);
  9081. if (conn->consumed_content != 0) {
  9082. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  9083. return 0;
  9084. }
  9085. for (;;) {
  9086. int nread = mg_read(conn, buf, sizeof(buf));
  9087. if (nread <= 0) {
  9088. success = (nread == 0);
  9089. break;
  9090. }
  9091. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) {
  9092. break;
  9093. }
  9094. }
  9095. /* Each error code path in this function must send an error */
  9096. if (!success) {
  9097. /* NOTE: Maybe some data has already been sent. */
  9098. /* TODO (low): If some data has been sent, a correct error
  9099. * reply can no longer be sent, so just close the connection */
  9100. mg_send_http_error(conn, 500, "%s", "");
  9101. }
  9102. }
  9103. return success;
  9104. }
  9105. #endif
  9106. #if defined(USE_TIMERS)
  9107. #define TIMER_API static
  9108. #include "timer.inl"
  9109. #endif /* USE_TIMERS */
  9110. #if !defined(NO_CGI)
  9111. /* This structure helps to create an environment for the spawned CGI
  9112. * program.
  9113. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  9114. * last element must be NULL.
  9115. * However, on Windows there is a requirement that all these
  9116. * VARIABLE=VALUE\0
  9117. * strings must reside in a contiguous buffer. The end of the buffer is
  9118. * marked by two '\0' characters.
  9119. * We satisfy both worlds: we create an envp array (which is vars), all
  9120. * entries are actually pointers inside buf. */
  9121. struct cgi_environment {
  9122. struct mg_connection *conn;
  9123. /* Data block */
  9124. char *buf; /* Environment buffer */
  9125. size_t buflen; /* Space available in buf */
  9126. size_t bufused; /* Space taken in buf */
  9127. /* Index block */
  9128. char **var; /* char **envp */
  9129. size_t varlen; /* Number of variables available in var */
  9130. size_t varused; /* Number of variables stored in var */
  9131. };
  9132. static void addenv(struct cgi_environment *env,
  9133. PRINTF_FORMAT_STRING(const char *fmt),
  9134. ...) PRINTF_ARGS(2, 3);
  9135. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  9136. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  9137. static void
  9138. addenv(struct cgi_environment *env, const char *fmt, ...)
  9139. {
  9140. size_t i, n, space;
  9141. int truncated = 0;
  9142. char *added;
  9143. va_list ap;
  9144. if ((env->varlen - env->varused) < 2) {
  9145. mg_cry_internal(env->conn,
  9146. "%s: Cannot register CGI variable [%s]",
  9147. __func__,
  9148. fmt);
  9149. return;
  9150. }
  9151. /* Calculate how much space is left in the buffer */
  9152. space = (env->buflen - env->bufused);
  9153. do {
  9154. /* Space for "\0\0" is always needed. */
  9155. if (space <= 2) {
  9156. /* Allocate new buffer */
  9157. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  9158. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  9159. if (!added) {
  9160. /* Out of memory */
  9161. mg_cry_internal(
  9162. env->conn,
  9163. "%s: Cannot allocate memory for CGI variable [%s]",
  9164. __func__,
  9165. fmt);
  9166. return;
  9167. }
  9168. /* Retarget pointers */
  9169. env->buf = added;
  9170. env->buflen = n;
  9171. for (i = 0, n = 0; i < env->varused; i++) {
  9172. env->var[i] = added + n;
  9173. n += strlen(added + n) + 1;
  9174. }
  9175. space = (env->buflen - env->bufused);
  9176. }
  9177. /* Make a pointer to the free space int the buffer */
  9178. added = env->buf + env->bufused;
  9179. /* Copy VARIABLE=VALUE\0 string into the free space */
  9180. va_start(ap, fmt);
  9181. mg_vsnprintf(env->conn, &truncated, added, space - 1, fmt, ap);
  9182. va_end(ap);
  9183. /* Do not add truncated strings to the environment */
  9184. if (truncated) {
  9185. /* Reallocate the buffer */
  9186. space = 0;
  9187. }
  9188. } while (truncated);
  9189. /* Calculate number of bytes added to the environment */
  9190. n = strlen(added) + 1;
  9191. env->bufused += n;
  9192. /* Append a pointer to the added string into the envp array */
  9193. env->var[env->varused] = added;
  9194. env->varused++;
  9195. }
  9196. /* Return 0 on success, non-zero if an error occurs. */
  9197. static int
  9198. prepare_cgi_environment(struct mg_connection *conn,
  9199. const char *prog,
  9200. struct cgi_environment *env)
  9201. {
  9202. const char *s;
  9203. struct vec var_vec;
  9204. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  9205. int i, truncated, uri_len;
  9206. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  9207. return -1;
  9208. }
  9209. env->conn = conn;
  9210. env->buflen = CGI_ENVIRONMENT_SIZE;
  9211. env->bufused = 0;
  9212. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  9213. if (env->buf == NULL) {
  9214. mg_cry_internal(conn,
  9215. "%s: Not enough memory for environmental buffer",
  9216. __func__);
  9217. return -1;
  9218. }
  9219. env->varlen = MAX_CGI_ENVIR_VARS;
  9220. env->varused = 0;
  9221. env->var =
  9222. (char **)mg_malloc_ctx(env->varlen * sizeof(char *), conn->phys_ctx);
  9223. if (env->var == NULL) {
  9224. mg_cry_internal(conn,
  9225. "%s: Not enough memory for environmental variables",
  9226. __func__);
  9227. mg_free(env->buf);
  9228. return -1;
  9229. }
  9230. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  9231. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9232. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9233. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  9234. /* Prepare the environment block */
  9235. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  9236. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  9237. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  9238. #if defined(USE_IPV6)
  9239. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  9240. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  9241. } else
  9242. #endif
  9243. {
  9244. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  9245. }
  9246. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  9247. addenv(env, "REMOTE_ADDR=%s", src_addr);
  9248. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  9249. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  9250. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  9251. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  9252. /* SCRIPT_NAME */
  9253. uri_len = (int)strlen(conn->request_info.local_uri);
  9254. if (conn->path_info == NULL) {
  9255. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  9256. /* URI: /path_to_script/script.cgi */
  9257. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  9258. } else {
  9259. /* URI: /path_to_script/ ... using index.cgi */
  9260. const char *index_file = strrchr(prog, '/');
  9261. if (index_file) {
  9262. addenv(env,
  9263. "SCRIPT_NAME=%s%s",
  9264. conn->request_info.local_uri,
  9265. index_file + 1);
  9266. }
  9267. }
  9268. } else {
  9269. /* URI: /path_to_script/script.cgi/path_info */
  9270. addenv(env,
  9271. "SCRIPT_NAME=%.*s",
  9272. uri_len - (int)strlen(conn->path_info),
  9273. conn->request_info.local_uri);
  9274. }
  9275. addenv(env, "SCRIPT_FILENAME=%s", prog);
  9276. if (conn->path_info == NULL) {
  9277. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  9278. } else {
  9279. addenv(env,
  9280. "PATH_TRANSLATED=%s%s",
  9281. conn->dom_ctx->config[DOCUMENT_ROOT],
  9282. conn->path_info);
  9283. }
  9284. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  9285. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  9286. addenv(env, "CONTENT_TYPE=%s", s);
  9287. }
  9288. if (conn->request_info.query_string != NULL) {
  9289. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  9290. }
  9291. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  9292. addenv(env, "CONTENT_LENGTH=%s", s);
  9293. }
  9294. if ((s = getenv("PATH")) != NULL) {
  9295. addenv(env, "PATH=%s", s);
  9296. }
  9297. if (conn->path_info != NULL) {
  9298. addenv(env, "PATH_INFO=%s", conn->path_info);
  9299. }
  9300. if (conn->status_code > 0) {
  9301. /* CGI error handler should show the status code */
  9302. addenv(env, "STATUS=%d", conn->status_code);
  9303. }
  9304. #if defined(_WIN32)
  9305. if ((s = getenv("COMSPEC")) != NULL) {
  9306. addenv(env, "COMSPEC=%s", s);
  9307. }
  9308. if ((s = getenv("SYSTEMROOT")) != NULL) {
  9309. addenv(env, "SYSTEMROOT=%s", s);
  9310. }
  9311. if ((s = getenv("SystemDrive")) != NULL) {
  9312. addenv(env, "SystemDrive=%s", s);
  9313. }
  9314. if ((s = getenv("ProgramFiles")) != NULL) {
  9315. addenv(env, "ProgramFiles=%s", s);
  9316. }
  9317. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  9318. addenv(env, "ProgramFiles(x86)=%s", s);
  9319. }
  9320. #else
  9321. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  9322. addenv(env, "LD_LIBRARY_PATH=%s", s);
  9323. }
  9324. #endif /* _WIN32 */
  9325. if ((s = getenv("PERLLIB")) != NULL) {
  9326. addenv(env, "PERLLIB=%s", s);
  9327. }
  9328. if (conn->request_info.remote_user != NULL) {
  9329. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  9330. addenv(env, "%s", "AUTH_TYPE=Digest");
  9331. }
  9332. /* Add all headers as HTTP_* variables */
  9333. for (i = 0; i < conn->request_info.num_headers; i++) {
  9334. (void)mg_snprintf(conn,
  9335. &truncated,
  9336. http_var_name,
  9337. sizeof(http_var_name),
  9338. "HTTP_%s",
  9339. conn->request_info.http_headers[i].name);
  9340. if (truncated) {
  9341. mg_cry_internal(conn,
  9342. "%s: HTTP header variable too long [%s]",
  9343. __func__,
  9344. conn->request_info.http_headers[i].name);
  9345. continue;
  9346. }
  9347. /* Convert variable name into uppercase, and change - to _ */
  9348. for (p = http_var_name; *p != '\0'; p++) {
  9349. if (*p == '-') {
  9350. *p = '_';
  9351. }
  9352. *p = (char)toupper((unsigned char)*p);
  9353. }
  9354. addenv(env,
  9355. "%s=%s",
  9356. http_var_name,
  9357. conn->request_info.http_headers[i].value);
  9358. }
  9359. /* Add user-specified variables */
  9360. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9361. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9362. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9363. }
  9364. env->var[env->varused] = NULL;
  9365. env->buf[env->bufused] = '\0';
  9366. return 0;
  9367. }
  9368. /* Data for CGI process control: PID and number of references */
  9369. struct process_control_data {
  9370. pid_t pid;
  9371. int references;
  9372. };
  9373. static int
  9374. abort_process(void *data)
  9375. {
  9376. /* Waitpid checks for child status and won't work for a pid that does not
  9377. * identify a child of the current process. Thus, if the pid is reused,
  9378. * we will not affect a different process. */
  9379. struct process_control_data *proc = (struct process_control_data *)data;
  9380. int status = 0;
  9381. int refs;
  9382. pid_t ret_pid;
  9383. ret_pid = waitpid(proc->pid, &status, WNOHANG);
  9384. if ((ret_pid != (pid_t)-1) && (status == 0)) {
  9385. /* Stop child process */
  9386. DEBUG_TRACE("CGI timer: Stop child process %p\n", proc->pid);
  9387. kill(proc->pid, SIGABRT);
  9388. /* Wait until process is terminated (don't leave zombies) */
  9389. while (waitpid(proc->pid, &status, 0) != (pid_t)-1) /* nop */
  9390. ;
  9391. } else {
  9392. DEBUG_TRACE("CGI timer: Child process %p already stopped\n", proc->pid);
  9393. }
  9394. /* Dec reference counter */
  9395. refs = mg_atomic_dec(&proc->references);
  9396. if (refs == 0) {
  9397. /* no more references - free data */
  9398. mg_free(data);
  9399. }
  9400. return 0;
  9401. }
  9402. /* Local (static) function assumes all arguments are valid. */
  9403. static void
  9404. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9405. {
  9406. char *buf;
  9407. size_t buflen;
  9408. int headers_len, data_len, i, truncated;
  9409. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9410. const char *status, *status_text, *connection_state;
  9411. char *pbuf, dir[PATH_MAX], *p;
  9412. struct mg_request_info ri;
  9413. struct cgi_environment blk;
  9414. FILE *in = NULL, *out = NULL, *err = NULL;
  9415. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9416. pid_t pid = (pid_t)-1;
  9417. struct process_control_data *proc = NULL;
  9418. #if defined(USE_TIMERS)
  9419. double cgi_timeout = -1.0;
  9420. if (conn->dom_ctx->config[CGI_TIMEOUT]) {
  9421. /* Get timeout in seconds */
  9422. cgi_timeout = atof(conn->dom_ctx->config[CGI_TIMEOUT]) * 0.001;
  9423. }
  9424. #endif
  9425. buf = NULL;
  9426. buflen = conn->phys_ctx->max_request_size;
  9427. i = prepare_cgi_environment(conn, prog, &blk);
  9428. if (i != 0) {
  9429. blk.buf = NULL;
  9430. blk.var = NULL;
  9431. goto done;
  9432. }
  9433. /* CGI must be executed in its own directory. 'dir' must point to the
  9434. * directory containing executable program, 'p' must point to the
  9435. * executable program name relative to 'dir'. */
  9436. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9437. if (truncated) {
  9438. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9439. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9440. goto done;
  9441. }
  9442. if ((p = strrchr(dir, '/')) != NULL) {
  9443. *p++ = '\0';
  9444. } else {
  9445. dir[0] = '.';
  9446. dir[1] = '\0';
  9447. p = (char *)prog;
  9448. }
  9449. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9450. status = strerror(ERRNO);
  9451. mg_cry_internal(
  9452. conn,
  9453. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9454. prog,
  9455. status);
  9456. mg_send_http_error(conn,
  9457. 500,
  9458. "Error: Cannot create CGI pipe: %s",
  9459. status);
  9460. goto done;
  9461. }
  9462. proc = (struct process_control_data *)
  9463. mg_malloc_ctx(sizeof(struct process_control_data), conn->phys_ctx);
  9464. if (proc == NULL) {
  9465. mg_cry_internal(conn, "Error: CGI program \"%s\": Out or memory", prog);
  9466. mg_send_http_error(conn, 500, "Error: Out of memory [%s]", prog);
  9467. goto done;
  9468. }
  9469. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9470. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9471. if (pid == (pid_t)-1) {
  9472. status = strerror(ERRNO);
  9473. mg_cry_internal(
  9474. conn,
  9475. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9476. prog,
  9477. status);
  9478. mg_send_http_error(conn,
  9479. 500,
  9480. "Error: Cannot spawn CGI process [%s]: %s",
  9481. prog,
  9482. status);
  9483. mg_free(proc);
  9484. proc = NULL;
  9485. goto done;
  9486. }
  9487. /* Store data in shared process_control_data */
  9488. proc->pid = pid;
  9489. proc->references = 1;
  9490. #if defined(USE_TIMERS)
  9491. if (cgi_timeout > 0.0) {
  9492. proc->references = 2;
  9493. // Start a timer for CGI
  9494. timer_add(conn->phys_ctx,
  9495. cgi_timeout /* in seconds */,
  9496. 0.0,
  9497. 1,
  9498. abort_process,
  9499. (void *)proc);
  9500. }
  9501. #endif
  9502. /* Parent closes only one side of the pipes.
  9503. * If we don't mark them as closed, close() attempt before
  9504. * return from this function throws an exception on Windows.
  9505. * Windows does not like when closed descriptor is closed again. */
  9506. (void)close(fdin[0]);
  9507. (void)close(fdout[1]);
  9508. (void)close(fderr[1]);
  9509. fdin[0] = fdout[1] = fderr[1] = -1;
  9510. if (((in = fdopen(fdin[1], "wb")) == NULL)
  9511. || ((out = fdopen(fdout[0], "rb")) == NULL)
  9512. || ((err = fdopen(fderr[0], "rb")) == NULL)) {
  9513. status = strerror(ERRNO);
  9514. mg_cry_internal(conn,
  9515. "Error: CGI program \"%s\": Can not open fd: %s",
  9516. prog,
  9517. status);
  9518. mg_send_http_error(conn,
  9519. 500,
  9520. "Error: CGI can not open fd\nfdopen: %s",
  9521. status);
  9522. goto done;
  9523. }
  9524. setbuf(in, NULL);
  9525. setbuf(out, NULL);
  9526. setbuf(err, NULL);
  9527. fout.access.fp = out;
  9528. if ((conn->content_len != 0) || (conn->is_chunked)) {
  9529. DEBUG_TRACE("CGI: send body data (%" INT64_FMT ")\n",
  9530. conn->content_len);
  9531. /* This is a POST/PUT request, or another request with body data. */
  9532. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9533. /* Error sending the body data */
  9534. mg_cry_internal(
  9535. conn,
  9536. "Error: CGI program \"%s\": Forward body data failed",
  9537. prog);
  9538. goto done;
  9539. }
  9540. }
  9541. /* Close so child gets an EOF. */
  9542. fclose(in);
  9543. in = NULL;
  9544. fdin[1] = -1;
  9545. /* Now read CGI reply into a buffer. We need to set correct
  9546. * status code, thus we need to see all HTTP headers first.
  9547. * Do not send anything back to client, until we buffer in all
  9548. * HTTP headers. */
  9549. data_len = 0;
  9550. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9551. if (buf == NULL) {
  9552. mg_send_http_error(conn,
  9553. 500,
  9554. "Error: Not enough memory for CGI buffer (%u bytes)",
  9555. (unsigned int)buflen);
  9556. mg_cry_internal(
  9557. conn,
  9558. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9559. "bytes)",
  9560. prog,
  9561. (unsigned int)buflen);
  9562. goto done;
  9563. }
  9564. DEBUG_TRACE("CGI: %s", "wait for response");
  9565. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9566. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9567. if (headers_len <= 0) {
  9568. /* Could not parse the CGI response. Check if some error message on
  9569. * stderr. */
  9570. i = pull_all(err, conn, buf, (int)buflen);
  9571. if (i > 0) {
  9572. /* CGI program explicitly sent an error */
  9573. /* Write the error message to the internal log */
  9574. mg_cry_internal(conn,
  9575. "Error: CGI program \"%s\" sent error "
  9576. "message: [%.*s]",
  9577. prog,
  9578. i,
  9579. buf);
  9580. /* Don't send the error message back to the client */
  9581. mg_send_http_error(conn,
  9582. 500,
  9583. "Error: CGI program \"%s\" failed.",
  9584. prog);
  9585. } else {
  9586. /* CGI program did not explicitly send an error, but a broken
  9587. * respon header */
  9588. mg_cry_internal(conn,
  9589. "Error: CGI program sent malformed or too big "
  9590. "(>%u bytes) HTTP headers: [%.*s]",
  9591. (unsigned)buflen,
  9592. data_len,
  9593. buf);
  9594. mg_send_http_error(conn,
  9595. 500,
  9596. "Error: CGI program sent malformed or too big "
  9597. "(>%u bytes) HTTP headers: [%.*s]",
  9598. (unsigned)buflen,
  9599. data_len,
  9600. buf);
  9601. }
  9602. /* in both cases, abort processing CGI */
  9603. goto done;
  9604. }
  9605. pbuf = buf;
  9606. buf[headers_len - 1] = '\0';
  9607. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9608. /* Make up and send the status line */
  9609. status_text = "OK";
  9610. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9611. != NULL) {
  9612. conn->status_code = atoi(status);
  9613. status_text = status;
  9614. while (isdigit((unsigned char)*status_text) || *status_text == ' ') {
  9615. status_text++;
  9616. }
  9617. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9618. != NULL) {
  9619. conn->status_code = 307;
  9620. } else {
  9621. conn->status_code = 200;
  9622. }
  9623. connection_state =
  9624. get_header(ri.http_headers, ri.num_headers, "Connection");
  9625. if (!header_has_option(connection_state, "keep-alive")) {
  9626. conn->must_close = 1;
  9627. }
  9628. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9629. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9630. /* Send headers */
  9631. for (i = 0; i < ri.num_headers; i++) {
  9632. mg_printf(conn,
  9633. "%s: %s\r\n",
  9634. ri.http_headers[i].name,
  9635. ri.http_headers[i].value);
  9636. }
  9637. mg_write(conn, "\r\n", 2);
  9638. /* Send chunk of data that may have been read after the headers */
  9639. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9640. /* Read the rest of CGI output and send to the client */
  9641. DEBUG_TRACE("CGI: %s", "forward all data");
  9642. send_file_data(conn, &fout, 0, INT64_MAX);
  9643. DEBUG_TRACE("CGI: %s", "all data sent");
  9644. done:
  9645. mg_free(blk.var);
  9646. mg_free(blk.buf);
  9647. if (pid != (pid_t)-1) {
  9648. abort_process((void *)proc);
  9649. }
  9650. if (fdin[0] != -1) {
  9651. close(fdin[0]);
  9652. }
  9653. if (fdout[1] != -1) {
  9654. close(fdout[1]);
  9655. }
  9656. if (fderr[1] != -1) {
  9657. close(fderr[1]);
  9658. }
  9659. if (in != NULL) {
  9660. fclose(in);
  9661. } else if (fdin[1] != -1) {
  9662. close(fdin[1]);
  9663. }
  9664. if (out != NULL) {
  9665. fclose(out);
  9666. } else if (fdout[0] != -1) {
  9667. close(fdout[0]);
  9668. }
  9669. if (err != NULL) {
  9670. fclose(err);
  9671. } else if (fderr[0] != -1) {
  9672. close(fderr[0]);
  9673. }
  9674. mg_free(buf);
  9675. }
  9676. #endif /* !NO_CGI */
  9677. #if !defined(NO_FILES)
  9678. static void
  9679. mkcol(struct mg_connection *conn, const char *path)
  9680. {
  9681. int rc, body_len;
  9682. struct de de;
  9683. char date[64];
  9684. time_t curtime = time(NULL);
  9685. if (conn == NULL) {
  9686. return;
  9687. }
  9688. /* TODO (mid): Check the mg_send_http_error situations in this function
  9689. */
  9690. memset(&de.file, 0, sizeof(de.file));
  9691. if (!mg_stat(conn, path, &de.file)) {
  9692. mg_cry_internal(conn,
  9693. "%s: mg_stat(%s) failed: %s",
  9694. __func__,
  9695. path,
  9696. strerror(ERRNO));
  9697. }
  9698. if (de.file.last_modified) {
  9699. /* TODO (mid): This check does not seem to make any sense ! */
  9700. /* TODO (mid): Add a webdav unit test first, before changing
  9701. * anything here. */
  9702. mg_send_http_error(
  9703. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9704. return;
  9705. }
  9706. body_len = conn->data_len - conn->request_len;
  9707. if (body_len > 0) {
  9708. mg_send_http_error(
  9709. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9710. return;
  9711. }
  9712. rc = mg_mkdir(conn, path, 0755);
  9713. if (rc == 0) {
  9714. conn->status_code = 201;
  9715. gmt_time_string(date, sizeof(date), &curtime);
  9716. mg_printf(conn,
  9717. "HTTP/1.1 %d Created\r\n"
  9718. "Date: %s\r\n",
  9719. conn->status_code,
  9720. date);
  9721. send_static_cache_header(conn);
  9722. send_additional_header(conn);
  9723. mg_printf(conn,
  9724. "Content-Length: 0\r\n"
  9725. "Connection: %s\r\n\r\n",
  9726. suggest_connection_header(conn));
  9727. } else {
  9728. if (errno == EEXIST) {
  9729. mg_send_http_error(
  9730. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9731. } else if (errno == EACCES) {
  9732. mg_send_http_error(
  9733. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9734. } else if (errno == ENOENT) {
  9735. mg_send_http_error(
  9736. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9737. } else {
  9738. mg_send_http_error(
  9739. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9740. }
  9741. }
  9742. }
  9743. static void
  9744. put_file(struct mg_connection *conn, const char *path)
  9745. {
  9746. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9747. const char *range;
  9748. int64_t r1, r2;
  9749. int rc;
  9750. char date[64];
  9751. time_t curtime = time(NULL);
  9752. if (conn == NULL) {
  9753. return;
  9754. }
  9755. if (mg_stat(conn, path, &file.stat)) {
  9756. /* File already exists */
  9757. conn->status_code = 200;
  9758. if (file.stat.is_directory) {
  9759. /* This is an already existing directory,
  9760. * so there is nothing to do for the server. */
  9761. rc = 0;
  9762. } else {
  9763. /* File exists and is not a directory. */
  9764. /* Can it be replaced? */
  9765. #if defined(MG_USE_OPEN_FILE)
  9766. if (file.access.membuf != NULL) {
  9767. /* This is an "in-memory" file, that can not be replaced */
  9768. mg_send_http_error(conn,
  9769. 405,
  9770. "Error: Put not possible\nReplacing %s "
  9771. "is not supported",
  9772. path);
  9773. return;
  9774. }
  9775. #endif
  9776. /* Check if the server may write this file */
  9777. if (access(path, W_OK) == 0) {
  9778. /* Access granted */
  9779. conn->status_code = 200;
  9780. rc = 1;
  9781. } else {
  9782. mg_send_http_error(
  9783. conn,
  9784. 403,
  9785. "Error: Put not possible\nReplacing %s is not allowed",
  9786. path);
  9787. return;
  9788. }
  9789. }
  9790. } else {
  9791. /* File should be created */
  9792. conn->status_code = 201;
  9793. rc = put_dir(conn, path);
  9794. }
  9795. if (rc == 0) {
  9796. /* put_dir returns 0 if path is a directory */
  9797. gmt_time_string(date, sizeof(date), &curtime);
  9798. mg_printf(conn,
  9799. "HTTP/1.1 %d %s\r\n",
  9800. conn->status_code,
  9801. mg_get_response_code_text(NULL, conn->status_code));
  9802. send_no_cache_header(conn);
  9803. send_additional_header(conn);
  9804. mg_printf(conn,
  9805. "Date: %s\r\n"
  9806. "Content-Length: 0\r\n"
  9807. "Connection: %s\r\n\r\n",
  9808. date,
  9809. suggest_connection_header(conn));
  9810. /* Request to create a directory has been fulfilled successfully.
  9811. * No need to put a file. */
  9812. return;
  9813. }
  9814. if (rc == -1) {
  9815. /* put_dir returns -1 if the path is too long */
  9816. mg_send_http_error(conn,
  9817. 414,
  9818. "Error: Path too long\nput_dir(%s): %s",
  9819. path,
  9820. strerror(ERRNO));
  9821. return;
  9822. }
  9823. if (rc == -2) {
  9824. /* put_dir returns -2 if the directory can not be created */
  9825. mg_send_http_error(conn,
  9826. 500,
  9827. "Error: Can not create directory\nput_dir(%s): %s",
  9828. path,
  9829. strerror(ERRNO));
  9830. return;
  9831. }
  9832. /* A file should be created or overwritten. */
  9833. /* Currently CivetWeb does not nead read+write access. */
  9834. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9835. || file.access.fp == NULL) {
  9836. (void)mg_fclose(&file.access);
  9837. mg_send_http_error(conn,
  9838. 500,
  9839. "Error: Can not create file\nfopen(%s): %s",
  9840. path,
  9841. strerror(ERRNO));
  9842. return;
  9843. }
  9844. fclose_on_exec(&file.access, conn);
  9845. range = mg_get_header(conn, "Content-Range");
  9846. r1 = r2 = 0;
  9847. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9848. conn->status_code = 206; /* Partial content */
  9849. fseeko(file.access.fp, r1, SEEK_SET);
  9850. }
  9851. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9852. /* forward_body_data failed.
  9853. * The error code has already been sent to the client,
  9854. * and conn->status_code is already set. */
  9855. (void)mg_fclose(&file.access);
  9856. return;
  9857. }
  9858. if (mg_fclose(&file.access) != 0) {
  9859. /* fclose failed. This might have different reasons, but a likely
  9860. * one is "no space on disk", http 507. */
  9861. conn->status_code = 507;
  9862. }
  9863. gmt_time_string(date, sizeof(date), &curtime);
  9864. mg_printf(conn,
  9865. "HTTP/1.1 %d %s\r\n",
  9866. conn->status_code,
  9867. mg_get_response_code_text(NULL, conn->status_code));
  9868. send_no_cache_header(conn);
  9869. send_additional_header(conn);
  9870. mg_printf(conn,
  9871. "Date: %s\r\n"
  9872. "Content-Length: 0\r\n"
  9873. "Connection: %s\r\n\r\n",
  9874. date,
  9875. suggest_connection_header(conn));
  9876. }
  9877. static void
  9878. delete_file(struct mg_connection *conn, const char *path)
  9879. {
  9880. struct de de;
  9881. memset(&de.file, 0, sizeof(de.file));
  9882. if (!mg_stat(conn, path, &de.file)) {
  9883. /* mg_stat returns 0 if the file does not exist */
  9884. mg_send_http_error(conn,
  9885. 404,
  9886. "Error: Cannot delete file\nFile %s not found",
  9887. path);
  9888. return;
  9889. }
  9890. #if 0 /* Ignore if a file in memory is inside a folder */
  9891. if (de.access.membuf != NULL) {
  9892. /* the file is cached in memory */
  9893. mg_send_http_error(
  9894. conn,
  9895. 405,
  9896. "Error: Delete not possible\nDeleting %s is not supported",
  9897. path);
  9898. return;
  9899. }
  9900. #endif
  9901. if (de.file.is_directory) {
  9902. if (remove_directory(conn, path)) {
  9903. /* Delete is successful: Return 204 without content. */
  9904. mg_send_http_error(conn, 204, "%s", "");
  9905. } else {
  9906. /* Delete is not successful: Return 500 (Server error). */
  9907. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9908. }
  9909. return;
  9910. }
  9911. /* This is an existing file (not a directory).
  9912. * Check if write permission is granted. */
  9913. if (access(path, W_OK) != 0) {
  9914. /* File is read only */
  9915. mg_send_http_error(
  9916. conn,
  9917. 403,
  9918. "Error: Delete not possible\nDeleting %s is not allowed",
  9919. path);
  9920. return;
  9921. }
  9922. /* Try to delete it. */
  9923. if (mg_remove(conn, path) == 0) {
  9924. /* Delete was successful: Return 204 without content. */
  9925. mg_send_http_error(conn, 204, "%s", "");
  9926. } else {
  9927. /* Delete not successful (file locked). */
  9928. mg_send_http_error(conn,
  9929. 423,
  9930. "Error: Cannot delete file\nremove(%s): %s",
  9931. path,
  9932. strerror(ERRNO));
  9933. }
  9934. }
  9935. #endif /* !NO_FILES */
  9936. #if !defined(NO_FILESYSTEMS)
  9937. static void
  9938. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9939. static void
  9940. do_ssi_include(struct mg_connection *conn,
  9941. const char *ssi,
  9942. char *tag,
  9943. int include_level)
  9944. {
  9945. char file_name[MG_BUF_LEN], path[512], *p;
  9946. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9947. size_t len;
  9948. int truncated = 0;
  9949. if (conn == NULL) {
  9950. return;
  9951. }
  9952. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9953. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9954. * always < MG_BUF_LEN. */
  9955. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9956. /* File name is relative to the webserver root */
  9957. file_name[511] = 0;
  9958. (void)mg_snprintf(conn,
  9959. &truncated,
  9960. path,
  9961. sizeof(path),
  9962. "%s/%s",
  9963. conn->dom_ctx->config[DOCUMENT_ROOT],
  9964. file_name);
  9965. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9966. /* File name is relative to the webserver working directory
  9967. * or it is absolute system path */
  9968. file_name[511] = 0;
  9969. (void)
  9970. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9971. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9972. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9973. /* File name is relative to the currect document */
  9974. file_name[511] = 0;
  9975. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9976. if (!truncated) {
  9977. if ((p = strrchr(path, '/')) != NULL) {
  9978. p[1] = '\0';
  9979. }
  9980. len = strlen(path);
  9981. (void)mg_snprintf(conn,
  9982. &truncated,
  9983. path + len,
  9984. sizeof(path) - len,
  9985. "%s",
  9986. file_name);
  9987. }
  9988. } else {
  9989. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9990. return;
  9991. }
  9992. if (truncated) {
  9993. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9994. return;
  9995. }
  9996. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9997. mg_cry_internal(conn,
  9998. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9999. tag,
  10000. path,
  10001. strerror(ERRNO));
  10002. } else {
  10003. fclose_on_exec(&file.access, conn);
  10004. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  10005. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  10006. path)
  10007. > 0) {
  10008. send_ssi_file(conn, path, &file, include_level + 1);
  10009. } else {
  10010. send_file_data(conn, &file, 0, INT64_MAX);
  10011. }
  10012. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  10013. }
  10014. }
  10015. #if !defined(NO_POPEN)
  10016. static void
  10017. do_ssi_exec(struct mg_connection *conn, char *tag)
  10018. {
  10019. char cmd[1024] = "";
  10020. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10021. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  10022. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  10023. } else {
  10024. cmd[1023] = 0;
  10025. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  10026. mg_cry_internal(conn,
  10027. "Cannot SSI #exec: [%s]: %s",
  10028. cmd,
  10029. strerror(ERRNO));
  10030. } else {
  10031. send_file_data(conn, &file, 0, INT64_MAX);
  10032. pclose(file.access.fp);
  10033. }
  10034. }
  10035. }
  10036. #endif /* !NO_POPEN */
  10037. static int
  10038. mg_fgetc(struct mg_file *filep, int offset)
  10039. {
  10040. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  10041. if (filep == NULL) {
  10042. return EOF;
  10043. }
  10044. #if defined(MG_USE_OPEN_FILE)
  10045. if ((filep->access.membuf != NULL) && (offset >= 0)
  10046. && (((unsigned int)(offset)) < filep->stat.size)) {
  10047. return ((const unsigned char *)filep->access.membuf)[offset];
  10048. } else /* else block below */
  10049. #endif
  10050. if (filep->access.fp != NULL) {
  10051. return fgetc(filep->access.fp);
  10052. } else {
  10053. return EOF;
  10054. }
  10055. }
  10056. static void
  10057. send_ssi_file(struct mg_connection *conn,
  10058. const char *path,
  10059. struct mg_file *filep,
  10060. int include_level)
  10061. {
  10062. char buf[MG_BUF_LEN];
  10063. int ch, offset, len, in_tag, in_ssi_tag;
  10064. if (include_level > 10) {
  10065. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  10066. return;
  10067. }
  10068. in_tag = in_ssi_tag = len = offset = 0;
  10069. /* Read file, byte by byte, and look for SSI include tags */
  10070. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  10071. if (in_tag) {
  10072. /* We are in a tag, either SSI tag or html tag */
  10073. if (ch == '>') {
  10074. /* Tag is closing */
  10075. buf[len++] = '>';
  10076. if (in_ssi_tag) {
  10077. /* Handle SSI tag */
  10078. buf[len] = 0;
  10079. if ((len > 12) && !memcmp(buf + 5, "include", 7)) {
  10080. do_ssi_include(conn, path, buf + 12, include_level + 1);
  10081. #if !defined(NO_POPEN)
  10082. } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) {
  10083. do_ssi_exec(conn, buf + 9);
  10084. #endif /* !NO_POPEN */
  10085. } else {
  10086. mg_cry_internal(conn,
  10087. "%s: unknown SSI "
  10088. "command: \"%s\"",
  10089. path,
  10090. buf);
  10091. }
  10092. len = 0;
  10093. in_ssi_tag = in_tag = 0;
  10094. } else {
  10095. /* Not an SSI tag */
  10096. /* Flush buffer */
  10097. (void)mg_write(conn, buf, (size_t)len);
  10098. len = 0;
  10099. in_tag = 0;
  10100. }
  10101. } else {
  10102. /* Tag is still open */
  10103. buf[len++] = (char)(ch & 0xff);
  10104. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  10105. /* All SSI tags start with <!--# */
  10106. in_ssi_tag = 1;
  10107. }
  10108. if ((len + 2) > (int)sizeof(buf)) {
  10109. /* Tag to long for buffer */
  10110. mg_cry_internal(conn, "%s: tag is too large", path);
  10111. return;
  10112. }
  10113. }
  10114. } else {
  10115. /* We are not in a tag yet. */
  10116. if (ch == '<') {
  10117. /* Tag is opening */
  10118. in_tag = 1;
  10119. if (len > 0) {
  10120. /* Flush current buffer.
  10121. * Buffer is filled with "len" bytes. */
  10122. (void)mg_write(conn, buf, (size_t)len);
  10123. }
  10124. /* Store the < */
  10125. len = 1;
  10126. buf[0] = '<';
  10127. } else {
  10128. /* No Tag */
  10129. /* Add data to buffer */
  10130. buf[len++] = (char)(ch & 0xff);
  10131. /* Flush if buffer is full */
  10132. if (len == (int)sizeof(buf)) {
  10133. mg_write(conn, buf, (size_t)len);
  10134. len = 0;
  10135. }
  10136. }
  10137. }
  10138. }
  10139. /* Send the rest of buffered data */
  10140. if (len > 0) {
  10141. mg_write(conn, buf, (size_t)len);
  10142. }
  10143. }
  10144. static void
  10145. handle_ssi_file_request(struct mg_connection *conn,
  10146. const char *path,
  10147. struct mg_file *filep)
  10148. {
  10149. char date[64];
  10150. time_t curtime = time(NULL);
  10151. const char *cors_orig_cfg;
  10152. const char *cors1, *cors2, *cors3;
  10153. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  10154. return;
  10155. }
  10156. cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10157. if (cors_orig_cfg && *cors_orig_cfg && mg_get_header(conn, "Origin")) {
  10158. /* Cross-origin resource sharing (CORS). */
  10159. cors1 = "Access-Control-Allow-Origin: ";
  10160. cors2 = cors_orig_cfg;
  10161. cors3 = "\r\n";
  10162. } else {
  10163. cors1 = cors2 = cors3 = "";
  10164. }
  10165. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  10166. /* File exists (precondition for calling this function),
  10167. * but can not be opened by the server. */
  10168. mg_send_http_error(conn,
  10169. 500,
  10170. "Error: Cannot read file\nfopen(%s): %s",
  10171. path,
  10172. strerror(ERRNO));
  10173. } else {
  10174. conn->must_close = 1;
  10175. gmt_time_string(date, sizeof(date), &curtime);
  10176. fclose_on_exec(&filep->access, conn);
  10177. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  10178. send_no_cache_header(conn);
  10179. send_additional_header(conn);
  10180. mg_printf(conn,
  10181. "%s%s%s"
  10182. "Date: %s\r\n"
  10183. "Content-Type: text/html\r\n"
  10184. "Connection: %s\r\n\r\n",
  10185. cors1,
  10186. cors2,
  10187. cors3,
  10188. date,
  10189. suggest_connection_header(conn));
  10190. send_ssi_file(conn, path, filep, 0);
  10191. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  10192. }
  10193. }
  10194. #endif /* NO_FILESYSTEMS */
  10195. #if !defined(NO_FILES)
  10196. static void
  10197. send_options(struct mg_connection *conn)
  10198. {
  10199. char date[64];
  10200. time_t curtime = time(NULL);
  10201. if (!conn) {
  10202. return;
  10203. }
  10204. conn->status_code = 200;
  10205. conn->must_close = 1;
  10206. gmt_time_string(date, sizeof(date), &curtime);
  10207. /* We do not set a "Cache-Control" header here, but leave the default.
  10208. * Since browsers do not send an OPTIONS request, we can not test the
  10209. * effect anyway. */
  10210. mg_printf(conn,
  10211. "HTTP/1.1 200 OK\r\n"
  10212. "Date: %s\r\n"
  10213. "Connection: %s\r\n"
  10214. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  10215. "PROPFIND, MKCOL\r\n"
  10216. "DAV: 1\r\n",
  10217. date,
  10218. suggest_connection_header(conn));
  10219. send_additional_header(conn);
  10220. mg_printf(conn, "\r\n");
  10221. }
  10222. /* Writes PROPFIND properties for a collection element */
  10223. static int
  10224. print_props(struct mg_connection *conn,
  10225. const char *uri,
  10226. const char *name,
  10227. struct mg_file_stat *filep)
  10228. {
  10229. size_t href_size, i, j;
  10230. int len;
  10231. char *href, mtime[64];
  10232. if ((conn == NULL) || (uri == NULL) || (name == NULL) || (filep == NULL)) {
  10233. return 0;
  10234. }
  10235. /* Estimate worst case size for encoding */
  10236. href_size = (strlen(uri) + strlen(name)) * 3 + 1;
  10237. href = (char *)mg_malloc(href_size);
  10238. if (href == NULL) {
  10239. return 0;
  10240. }
  10241. len = mg_url_encode(uri, href, href_size);
  10242. if (len >= 0) {
  10243. /* Append an extra string */
  10244. mg_url_encode(name, href + len, href_size - (size_t)len);
  10245. }
  10246. /* Directory separator should be preserved. */
  10247. for (i = j = 0; href[i]; j++) {
  10248. if (!strncmp(href + i, "%2f", 3)) {
  10249. href[j] = '/';
  10250. i += 3;
  10251. } else {
  10252. href[j] = href[i++];
  10253. }
  10254. }
  10255. href[j] = '\0';
  10256. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  10257. mg_printf(conn,
  10258. "<d:response>"
  10259. "<d:href>%s</d:href>"
  10260. "<d:propstat>"
  10261. "<d:prop>"
  10262. "<d:resourcetype>%s</d:resourcetype>"
  10263. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  10264. "<d:getlastmodified>%s</d:getlastmodified>"
  10265. "</d:prop>"
  10266. "<d:status>HTTP/1.1 200 OK</d:status>"
  10267. "</d:propstat>"
  10268. "</d:response>\n",
  10269. href,
  10270. filep->is_directory ? "<d:collection/>" : "",
  10271. filep->size,
  10272. mtime);
  10273. mg_free(href);
  10274. return 1;
  10275. }
  10276. static int
  10277. print_dav_dir_entry(struct de *de, void *data)
  10278. {
  10279. struct mg_connection *conn = (struct mg_connection *)data;
  10280. if (!de || !conn
  10281. || !print_props(
  10282. conn, conn->request_info.local_uri, de->file_name, &de->file)) {
  10283. return -1;
  10284. }
  10285. return 0;
  10286. }
  10287. static void
  10288. handle_propfind(struct mg_connection *conn,
  10289. const char *path,
  10290. struct mg_file_stat *filep)
  10291. {
  10292. const char *depth = mg_get_header(conn, "Depth");
  10293. char date[64];
  10294. time_t curtime = time(NULL);
  10295. gmt_time_string(date, sizeof(date), &curtime);
  10296. if (!conn || !path || !filep || !conn->dom_ctx) {
  10297. return;
  10298. }
  10299. conn->must_close = 1;
  10300. conn->status_code = 207;
  10301. mg_printf(conn,
  10302. "HTTP/1.1 207 Multi-Status\r\n"
  10303. "Date: %s\r\n",
  10304. date);
  10305. send_static_cache_header(conn);
  10306. send_additional_header(conn);
  10307. mg_printf(conn,
  10308. "Connection: %s\r\n"
  10309. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  10310. suggest_connection_header(conn));
  10311. mg_printf(conn,
  10312. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  10313. "<d:multistatus xmlns:d='DAV:'>\n");
  10314. /* Print properties for the requested resource itself */
  10315. print_props(conn, conn->request_info.local_uri, "", filep);
  10316. /* If it is a directory, print directory entries too if Depth is not 0
  10317. */
  10318. if (filep->is_directory
  10319. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  10320. "yes")
  10321. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  10322. scan_directory(conn, path, conn, &print_dav_dir_entry);
  10323. }
  10324. mg_printf(conn, "%s\n", "</d:multistatus>");
  10325. }
  10326. #endif
  10327. void
  10328. mg_lock_connection(struct mg_connection *conn)
  10329. {
  10330. if (conn) {
  10331. (void)pthread_mutex_lock(&conn->mutex);
  10332. }
  10333. }
  10334. void
  10335. mg_unlock_connection(struct mg_connection *conn)
  10336. {
  10337. if (conn) {
  10338. (void)pthread_mutex_unlock(&conn->mutex);
  10339. }
  10340. }
  10341. void
  10342. mg_lock_context(struct mg_context *ctx)
  10343. {
  10344. if (ctx) {
  10345. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  10346. }
  10347. }
  10348. void
  10349. mg_unlock_context(struct mg_context *ctx)
  10350. {
  10351. if (ctx) {
  10352. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  10353. }
  10354. }
  10355. #if defined(USE_LUA)
  10356. #include "mod_lua.inl"
  10357. #endif /* USE_LUA */
  10358. #if defined(USE_DUKTAPE)
  10359. #include "mod_duktape.inl"
  10360. #endif /* USE_DUKTAPE */
  10361. #if defined(USE_WEBSOCKET)
  10362. #if !defined(NO_SSL_DL)
  10363. #define SHA_API static
  10364. #include "sha1.inl"
  10365. #endif
  10366. static int
  10367. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  10368. {
  10369. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  10370. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  10371. SHA_CTX sha_ctx;
  10372. int truncated;
  10373. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  10374. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  10375. if (truncated) {
  10376. conn->must_close = 1;
  10377. return 0;
  10378. }
  10379. DEBUG_TRACE("%s", "Send websocket handshake");
  10380. SHA1_Init(&sha_ctx);
  10381. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  10382. SHA1_Final((unsigned char *)sha, &sha_ctx);
  10383. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  10384. mg_printf(conn,
  10385. "HTTP/1.1 101 Switching Protocols\r\n"
  10386. "Upgrade: websocket\r\n"
  10387. "Connection: Upgrade\r\n"
  10388. "Sec-WebSocket-Accept: %s\r\n",
  10389. b64_sha);
  10390. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10391. mg_printf(conn,
  10392. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10393. conn->request_info.acceptedWebSocketSubprotocol);
  10394. } else {
  10395. mg_printf(conn, "%s", "\r\n");
  10396. }
  10397. return 1;
  10398. }
  10399. #if !defined(MG_MAX_UNANSWERED_PING)
  10400. /* Configuration of the maximum number of websocket PINGs that might
  10401. * stay unanswered before the connection is considered broken.
  10402. * Note: The name of this define may still change (until it is
  10403. * defined as a compile parameter in a documentation).
  10404. */
  10405. #define MG_MAX_UNANSWERED_PING (5)
  10406. #endif
  10407. static void
  10408. read_websocket(struct mg_connection *conn,
  10409. mg_websocket_data_handler ws_data_handler,
  10410. void *callback_data)
  10411. {
  10412. /* Pointer to the beginning of the portion of the incoming websocket
  10413. * message queue.
  10414. * The original websocket upgrade request is never removed, so the queue
  10415. * begins after it. */
  10416. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10417. int n, error, exit_by_callback;
  10418. int ret;
  10419. /* body_len is the length of the entire queue in bytes
  10420. * len is the length of the current message
  10421. * data_len is the length of the current message's data payload
  10422. * header_len is the length of the current message's header */
  10423. size_t i, len, mask_len = 0, header_len, body_len;
  10424. uint64_t data_len = 0;
  10425. /* "The masking key is a 32-bit value chosen at random by the client."
  10426. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10427. */
  10428. unsigned char mask[4];
  10429. /* data points to the place where the message is stored when passed to
  10430. * the websocket_data callback. This is either mem on the stack, or a
  10431. * dynamically allocated buffer if it is too large. */
  10432. unsigned char mem[4096];
  10433. unsigned char mop; /* mask flag and opcode */
  10434. /* Variables used for connection monitoring */
  10435. double timeout = -1.0;
  10436. int enable_ping_pong = 0;
  10437. int ping_count = 0;
  10438. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10439. enable_ping_pong =
  10440. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10441. "yes");
  10442. }
  10443. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10444. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10445. }
  10446. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10447. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10448. }
  10449. /* Enter data processing loop */
  10450. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10451. conn->request_info.remote_addr,
  10452. conn->request_info.remote_port);
  10453. conn->in_websocket_handling = 1;
  10454. mg_set_thread_name("wsock");
  10455. /* Loop continuously, reading messages from the socket, invoking the
  10456. * callback, and waiting repeatedly until an error occurs. */
  10457. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10458. header_len = 0;
  10459. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10460. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10461. len = buf[1] & 127;
  10462. mask_len = (buf[1] & 128) ? 4 : 0;
  10463. if ((len < 126) && (body_len >= mask_len)) {
  10464. /* inline 7-bit length field */
  10465. data_len = len;
  10466. header_len = 2 + mask_len;
  10467. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10468. /* 16-bit length field */
  10469. header_len = 4 + mask_len;
  10470. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10471. } else if (body_len >= (10 + mask_len)) {
  10472. /* 64-bit length field */
  10473. uint32_t l1, l2;
  10474. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10475. memcpy(&l2, &buf[6], 4);
  10476. header_len = 10 + mask_len;
  10477. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10478. if (data_len > (uint64_t)0x7FFF0000ul) {
  10479. /* no can do */
  10480. mg_cry_internal(
  10481. conn,
  10482. "%s",
  10483. "websocket out of memory; closing connection");
  10484. break;
  10485. }
  10486. }
  10487. }
  10488. if ((header_len > 0) && (body_len >= header_len)) {
  10489. /* Allocate space to hold websocket payload */
  10490. unsigned char *data = mem;
  10491. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10492. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10493. conn->phys_ctx);
  10494. if (data == NULL) {
  10495. /* Allocation failed, exit the loop and then close the
  10496. * connection */
  10497. mg_cry_internal(
  10498. conn,
  10499. "%s",
  10500. "websocket out of memory; closing connection");
  10501. break;
  10502. }
  10503. }
  10504. /* Copy the mask before we shift the queue and destroy it */
  10505. if (mask_len > 0) {
  10506. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10507. } else {
  10508. memset(mask, 0, sizeof(mask));
  10509. }
  10510. /* Read frame payload from the first message in the queue into
  10511. * data and advance the queue by moving the memory in place. */
  10512. DEBUG_ASSERT(body_len >= header_len);
  10513. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10514. mop = buf[0]; /* current mask and opcode */
  10515. /* Overflow case */
  10516. len = body_len - header_len;
  10517. memcpy(data, buf + header_len, len);
  10518. error = 0;
  10519. while ((uint64_t)len < data_len) {
  10520. n = pull_inner(NULL,
  10521. conn,
  10522. (char *)(data + len),
  10523. (int)(data_len - len),
  10524. timeout);
  10525. if (n <= -2) {
  10526. error = 1;
  10527. break;
  10528. } else if (n > 0) {
  10529. len += (size_t)n;
  10530. } else {
  10531. /* Timeout: should retry */
  10532. /* TODO: retry condition */
  10533. }
  10534. }
  10535. if (error) {
  10536. mg_cry_internal(
  10537. conn,
  10538. "%s",
  10539. "Websocket pull failed; closing connection");
  10540. if (data != mem) {
  10541. mg_free(data);
  10542. }
  10543. break;
  10544. }
  10545. conn->data_len = conn->request_len;
  10546. } else {
  10547. mop = buf[0]; /* current mask and opcode, overwritten by
  10548. * memmove() */
  10549. /* Length of the message being read at the front of the
  10550. * queue. Cast to 31 bit is OK, since we limited
  10551. * data_len before. */
  10552. len = (size_t)data_len + header_len;
  10553. /* Copy the data payload into the data pointer for the
  10554. * callback. Cast to 31 bit is OK, since we
  10555. * limited data_len */
  10556. memcpy(data, buf + header_len, (size_t)data_len);
  10557. /* Move the queue forward len bytes */
  10558. memmove(buf, buf + len, body_len - len);
  10559. /* Mark the queue as advanced */
  10560. conn->data_len -= (int)len;
  10561. }
  10562. /* Apply mask if necessary */
  10563. if (mask_len > 0) {
  10564. for (i = 0; i < (size_t)data_len; i++) {
  10565. data[i] ^= mask[i & 3];
  10566. }
  10567. }
  10568. exit_by_callback = 0;
  10569. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10570. /* filter PONG messages */
  10571. DEBUG_TRACE("PONG from %s:%u",
  10572. conn->request_info.remote_addr,
  10573. conn->request_info.remote_port);
  10574. /* No unanwered PINGs left */
  10575. ping_count = 0;
  10576. } else if (enable_ping_pong
  10577. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10578. /* reply PING messages */
  10579. DEBUG_TRACE("Reply PING from %s:%u",
  10580. conn->request_info.remote_addr,
  10581. conn->request_info.remote_port);
  10582. ret = mg_websocket_write(conn,
  10583. MG_WEBSOCKET_OPCODE_PONG,
  10584. (char *)data,
  10585. (size_t)data_len);
  10586. if (ret <= 0) {
  10587. /* Error: send failed */
  10588. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10589. break;
  10590. }
  10591. } else {
  10592. /* Exit the loop if callback signals to exit (server side),
  10593. * or "connection close" opcode received (client side). */
  10594. if ((ws_data_handler != NULL)
  10595. && !ws_data_handler(conn,
  10596. mop,
  10597. (char *)data,
  10598. (size_t)data_len,
  10599. callback_data)) {
  10600. exit_by_callback = 1;
  10601. }
  10602. }
  10603. /* It a buffer has been allocated, free it again */
  10604. if (data != mem) {
  10605. mg_free(data);
  10606. }
  10607. if (exit_by_callback) {
  10608. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10609. conn->request_info.remote_addr,
  10610. conn->request_info.remote_port);
  10611. break;
  10612. }
  10613. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10614. /* Opcode == 8, connection close */
  10615. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10616. conn->request_info.remote_addr,
  10617. conn->request_info.remote_port);
  10618. break;
  10619. }
  10620. /* Not breaking the loop, process next websocket frame. */
  10621. } else {
  10622. /* Read from the socket into the next available location in the
  10623. * message queue. */
  10624. n = pull_inner(NULL,
  10625. conn,
  10626. conn->buf + conn->data_len,
  10627. conn->buf_size - conn->data_len,
  10628. timeout);
  10629. if (n <= -2) {
  10630. /* Error, no bytes read */
  10631. DEBUG_TRACE("PULL from %s:%u failed",
  10632. conn->request_info.remote_addr,
  10633. conn->request_info.remote_port);
  10634. break;
  10635. }
  10636. if (n > 0) {
  10637. conn->data_len += n;
  10638. /* Reset open PING count */
  10639. ping_count = 0;
  10640. } else {
  10641. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10642. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10643. /* Stop sending PING */
  10644. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10645. "- closing connection",
  10646. ping_count,
  10647. conn->request_info.remote_addr,
  10648. conn->request_info.remote_port);
  10649. break;
  10650. }
  10651. if (enable_ping_pong) {
  10652. /* Send Websocket PING message */
  10653. DEBUG_TRACE("PING to %s:%u",
  10654. conn->request_info.remote_addr,
  10655. conn->request_info.remote_port);
  10656. ret = mg_websocket_write(conn,
  10657. MG_WEBSOCKET_OPCODE_PING,
  10658. NULL,
  10659. 0);
  10660. if (ret <= 0) {
  10661. /* Error: send failed */
  10662. DEBUG_TRACE("Send PING failed (%i)", ret);
  10663. break;
  10664. }
  10665. ping_count++;
  10666. }
  10667. }
  10668. /* Timeout: should retry */
  10669. /* TODO: get timeout def */
  10670. }
  10671. }
  10672. }
  10673. /* Leave data processing loop */
  10674. mg_set_thread_name("worker");
  10675. conn->in_websocket_handling = 0;
  10676. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10677. conn->request_info.remote_addr,
  10678. conn->request_info.remote_port);
  10679. }
  10680. static int
  10681. mg_websocket_write_exec(struct mg_connection *conn,
  10682. int opcode,
  10683. const char *data,
  10684. size_t dataLen,
  10685. uint32_t masking_key)
  10686. {
  10687. unsigned char header[14];
  10688. size_t headerLen;
  10689. int retval;
  10690. #if defined(GCC_DIAGNOSTIC)
  10691. /* Disable spurious conversion warning for GCC */
  10692. #pragma GCC diagnostic push
  10693. #pragma GCC diagnostic ignored "-Wconversion"
  10694. #endif
  10695. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10696. #if defined(GCC_DIAGNOSTIC)
  10697. #pragma GCC diagnostic pop
  10698. #endif
  10699. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10700. if (dataLen < 126) {
  10701. /* inline 7-bit length field */
  10702. header[1] = (unsigned char)dataLen;
  10703. headerLen = 2;
  10704. } else if (dataLen <= 0xFFFF) {
  10705. /* 16-bit length field */
  10706. uint16_t len = htons((uint16_t)dataLen);
  10707. header[1] = 126;
  10708. memcpy(header + 2, &len, 2);
  10709. headerLen = 4;
  10710. } else {
  10711. /* 64-bit length field */
  10712. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10713. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10714. header[1] = 127;
  10715. memcpy(header + 2, &len1, 4);
  10716. memcpy(header + 6, &len2, 4);
  10717. headerLen = 10;
  10718. }
  10719. if (masking_key) {
  10720. /* add mask */
  10721. header[1] |= 0x80;
  10722. memcpy(header + headerLen, &masking_key, 4);
  10723. headerLen += 4;
  10724. }
  10725. /* Note that POSIX/Winsock's send() is threadsafe
  10726. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10727. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10728. * push(), although that is only a problem if the packet is large or
  10729. * outgoing buffer is full). */
  10730. /* TODO: Check if this lock should be moved to user land.
  10731. * Currently the server sets this lock for websockets, but
  10732. * not for any other connection. It must be set for every
  10733. * conn read/written by more than one thread, no matter if
  10734. * it is a websocket or regular connection. */
  10735. (void)mg_lock_connection(conn);
  10736. retval = mg_write(conn, header, headerLen);
  10737. if (retval != (int)headerLen) {
  10738. /* Did not send complete header */
  10739. retval = -1;
  10740. } else {
  10741. if (dataLen > 0) {
  10742. retval = mg_write(conn, data, dataLen);
  10743. }
  10744. /* if dataLen == 0, the header length (2) is returned */
  10745. }
  10746. /* TODO: Remove this unlock as well, when lock is removed. */
  10747. mg_unlock_connection(conn);
  10748. return retval;
  10749. }
  10750. int
  10751. mg_websocket_write(struct mg_connection *conn,
  10752. int opcode,
  10753. const char *data,
  10754. size_t dataLen)
  10755. {
  10756. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10757. }
  10758. static void
  10759. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10760. {
  10761. size_t i = 0;
  10762. i = 0;
  10763. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10764. /* Convert in 32 bit words, if data is 4 byte aligned */
  10765. while (i < (in_len - 3)) {
  10766. *(uint32_t *)(void *)(out + i) =
  10767. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10768. i += 4;
  10769. }
  10770. }
  10771. if (i != in_len) {
  10772. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10773. while (i < in_len) {
  10774. *(uint8_t *)(void *)(out + i) =
  10775. *(uint8_t *)(void *)(in + i)
  10776. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10777. i++;
  10778. }
  10779. }
  10780. }
  10781. int
  10782. mg_websocket_client_write(struct mg_connection *conn,
  10783. int opcode,
  10784. const char *data,
  10785. size_t dataLen)
  10786. {
  10787. int retval = -1;
  10788. char *masked_data =
  10789. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10790. uint32_t masking_key = 0;
  10791. if (masked_data == NULL) {
  10792. /* Return -1 in an error case */
  10793. mg_cry_internal(conn,
  10794. "%s",
  10795. "Cannot allocate buffer for masked websocket response: "
  10796. "Out of memory");
  10797. return -1;
  10798. }
  10799. do {
  10800. /* Get a masking key - but not 0 */
  10801. masking_key = (uint32_t)get_random();
  10802. } while (masking_key == 0);
  10803. mask_data(data, dataLen, masking_key, masked_data);
  10804. retval = mg_websocket_write_exec(
  10805. conn, opcode, masked_data, dataLen, masking_key);
  10806. mg_free(masked_data);
  10807. return retval;
  10808. }
  10809. static void
  10810. handle_websocket_request(struct mg_connection *conn,
  10811. const char *path,
  10812. int is_callback_resource,
  10813. struct mg_websocket_subprotocols *subprotocols,
  10814. mg_websocket_connect_handler ws_connect_handler,
  10815. mg_websocket_ready_handler ws_ready_handler,
  10816. mg_websocket_data_handler ws_data_handler,
  10817. mg_websocket_close_handler ws_close_handler,
  10818. void *cbData)
  10819. {
  10820. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10821. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10822. ptrdiff_t lua_websock = 0;
  10823. #if !defined(USE_LUA)
  10824. (void)path;
  10825. #endif
  10826. /* Step 1: Check websocket protocol version. */
  10827. /* Step 1.1: Check Sec-WebSocket-Key. */
  10828. if (!websock_key) {
  10829. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10830. * requires a Sec-WebSocket-Key header.
  10831. */
  10832. /* It could be the hixie draft version
  10833. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10834. */
  10835. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10836. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10837. char key3[8];
  10838. if ((key1 != NULL) && (key2 != NULL)) {
  10839. /* This version uses 8 byte body data in a GET request */
  10840. conn->content_len = 8;
  10841. if (8 == mg_read(conn, key3, 8)) {
  10842. /* This is the hixie version */
  10843. mg_send_http_error(conn,
  10844. 426,
  10845. "%s",
  10846. "Protocol upgrade to RFC 6455 required");
  10847. return;
  10848. }
  10849. }
  10850. /* This is an unknown version */
  10851. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10852. return;
  10853. }
  10854. /* Step 1.2: Check websocket protocol version. */
  10855. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10856. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10857. /* Reject wrong versions */
  10858. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10859. return;
  10860. }
  10861. /* Step 1.3: Could check for "Host", but we do not really nead this
  10862. * value for anything, so just ignore it. */
  10863. /* Step 2: If a callback is responsible, call it. */
  10864. if (is_callback_resource) {
  10865. /* Step 2.1 check and select subprotocol */
  10866. const char *protocols[64]; // max 64 headers
  10867. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10868. "Sec-WebSocket-Protocol",
  10869. protocols,
  10870. 64);
  10871. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10872. int cnt = 0;
  10873. int idx;
  10874. unsigned long len;
  10875. const char *sep, *curSubProtocol,
  10876. *acceptedWebSocketSubprotocol = NULL;
  10877. /* look for matching subprotocol */
  10878. do {
  10879. const char *protocol = protocols[cnt];
  10880. do {
  10881. sep = strchr(protocol, ',');
  10882. curSubProtocol = protocol;
  10883. len = sep ? (unsigned long)(sep - protocol)
  10884. : (unsigned long)strlen(protocol);
  10885. while (sep && isspace((unsigned char)*++sep))
  10886. ; // ignore leading whitespaces
  10887. protocol = sep;
  10888. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10889. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10890. && (strncmp(curSubProtocol,
  10891. subprotocols->subprotocols[idx],
  10892. len)
  10893. == 0)) {
  10894. acceptedWebSocketSubprotocol =
  10895. subprotocols->subprotocols[idx];
  10896. break;
  10897. }
  10898. }
  10899. } while (sep && !acceptedWebSocketSubprotocol);
  10900. } while (++cnt < nbSubprotocolHeader
  10901. && !acceptedWebSocketSubprotocol);
  10902. conn->request_info.acceptedWebSocketSubprotocol =
  10903. acceptedWebSocketSubprotocol;
  10904. } else if (nbSubprotocolHeader > 0) {
  10905. /* keep legacy behavior */
  10906. const char *protocol = protocols[0];
  10907. /* The protocol is a comma separated list of names. */
  10908. /* The server must only return one value from this list. */
  10909. /* First check if it is a list or just a single value. */
  10910. const char *sep = strrchr(protocol, ',');
  10911. if (sep == NULL) {
  10912. /* Just a single protocol -> accept it. */
  10913. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10914. } else {
  10915. /* Multiple protocols -> accept the last one. */
  10916. /* This is just a quick fix if the client offers multiple
  10917. * protocols. The handler should have a list of accepted
  10918. * protocols on his own
  10919. * and use it to select one protocol among those the client
  10920. * has
  10921. * offered.
  10922. */
  10923. while (isspace((unsigned char)*++sep)) {
  10924. ; /* ignore leading whitespaces */
  10925. }
  10926. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10927. }
  10928. }
  10929. if ((ws_connect_handler != NULL)
  10930. && (ws_connect_handler(conn, cbData) != 0)) {
  10931. /* C callback has returned non-zero, do not proceed with
  10932. * handshake.
  10933. */
  10934. /* Note that C callbacks are no longer called when Lua is
  10935. * responsible, so C can no longer filter callbacks for Lua. */
  10936. return;
  10937. }
  10938. }
  10939. #if defined(USE_LUA)
  10940. /* Step 3: No callback. Check if Lua is responsible. */
  10941. else {
  10942. /* Step 3.1: Check if Lua is responsible. */
  10943. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10944. lua_websock = match_prefix(
  10945. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10946. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10947. path);
  10948. }
  10949. if (lua_websock) {
  10950. /* Step 3.2: Lua is responsible: call it. */
  10951. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10952. if (!conn->lua_websocket_state) {
  10953. /* Lua rejected the new client */
  10954. return;
  10955. }
  10956. }
  10957. }
  10958. #endif
  10959. /* Step 4: Check if there is a responsible websocket handler. */
  10960. if (!is_callback_resource && !lua_websock) {
  10961. /* There is no callback, and Lua is not responsible either. */
  10962. /* Reply with a 404 Not Found. We are still at a standard
  10963. * HTTP request here, before the websocket handshake, so
  10964. * we can still send standard HTTP error replies. */
  10965. mg_send_http_error(conn, 404, "%s", "Not found");
  10966. return;
  10967. }
  10968. /* Step 5: The websocket connection has been accepted */
  10969. if (!send_websocket_handshake(conn, websock_key)) {
  10970. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10971. return;
  10972. }
  10973. /* Step 6: Call the ready handler */
  10974. if (is_callback_resource) {
  10975. if (ws_ready_handler != NULL) {
  10976. ws_ready_handler(conn, cbData);
  10977. }
  10978. #if defined(USE_LUA)
  10979. } else if (lua_websock) {
  10980. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10981. /* the ready handler returned false */
  10982. return;
  10983. }
  10984. #endif
  10985. }
  10986. /* Step 7: Enter the read loop */
  10987. if (is_callback_resource) {
  10988. read_websocket(conn, ws_data_handler, cbData);
  10989. #if defined(USE_LUA)
  10990. } else if (lua_websock) {
  10991. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10992. #endif
  10993. }
  10994. /* Step 8: Call the close handler */
  10995. if (ws_close_handler) {
  10996. ws_close_handler(conn, cbData);
  10997. }
  10998. }
  10999. static int
  11000. is_websocket_protocol(const struct mg_connection *conn)
  11001. {
  11002. const char *upgrade, *connection;
  11003. /* A websocket protocoll has the following HTTP headers:
  11004. *
  11005. * Connection: Upgrade
  11006. * Upgrade: Websocket
  11007. */
  11008. upgrade = mg_get_header(conn, "Upgrade");
  11009. if (upgrade == NULL) {
  11010. return 0; /* fail early, don't waste time checking other header
  11011. * fields
  11012. */
  11013. }
  11014. if (!mg_strcasestr(upgrade, "websocket")) {
  11015. return 0;
  11016. }
  11017. connection = mg_get_header(conn, "Connection");
  11018. if (connection == NULL) {
  11019. return 0;
  11020. }
  11021. if (!mg_strcasestr(connection, "upgrade")) {
  11022. return 0;
  11023. }
  11024. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  11025. * "Sec-WebSocket-Version" are also required.
  11026. * Don't check them here, since even an unsupported websocket protocol
  11027. * request still IS a websocket request (in contrast to a standard HTTP
  11028. * request). It will fail later in handle_websocket_request.
  11029. */
  11030. return 1;
  11031. }
  11032. #endif /* !USE_WEBSOCKET */
  11033. static int
  11034. isbyte(int n)
  11035. {
  11036. return (n >= 0) && (n <= 255);
  11037. }
  11038. static int
  11039. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  11040. {
  11041. int n, a, b, c, d, slash = 32, len = 0;
  11042. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  11043. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  11044. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  11045. && (slash < 33)) {
  11046. len = n;
  11047. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  11048. | (uint32_t)d;
  11049. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  11050. }
  11051. return len;
  11052. }
  11053. static int
  11054. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  11055. {
  11056. int throttle = 0;
  11057. struct vec vec, val;
  11058. uint32_t net, mask;
  11059. char mult;
  11060. double v;
  11061. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  11062. mult = ',';
  11063. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  11064. || (v < 0)
  11065. || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm')
  11066. && (mult != ','))) {
  11067. continue;
  11068. }
  11069. v *= (lowercase(&mult) == 'k')
  11070. ? 1024
  11071. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  11072. if (vec.len == 1 && vec.ptr[0] == '*') {
  11073. throttle = (int)v;
  11074. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  11075. if ((remote_ip & mask) == net) {
  11076. throttle = (int)v;
  11077. }
  11078. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  11079. throttle = (int)v;
  11080. }
  11081. }
  11082. return throttle;
  11083. }
  11084. static uint32_t
  11085. get_remote_ip(const struct mg_connection *conn)
  11086. {
  11087. if (!conn) {
  11088. return 0;
  11089. }
  11090. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  11091. }
  11092. /* The mg_upload function is superseeded by mg_handle_form_request. */
  11093. #include "handle_form.inl"
  11094. #if defined(MG_LEGACY_INTERFACE)
  11095. /* Implement the deprecated mg_upload function by calling the new
  11096. * mg_handle_form_request function. While mg_upload could only handle
  11097. * HTML forms sent as POST request in multipart/form-data format
  11098. * containing only file input elements, mg_handle_form_request can
  11099. * handle all form input elements and all standard request methods. */
  11100. struct mg_upload_user_data {
  11101. struct mg_connection *conn;
  11102. const char *destination_dir;
  11103. int num_uploaded_files;
  11104. };
  11105. /* Helper function for deprecated mg_upload. */
  11106. static int
  11107. mg_upload_field_found(const char *key,
  11108. const char *filename,
  11109. char *path,
  11110. size_t pathlen,
  11111. void *user_data)
  11112. {
  11113. int truncated = 0;
  11114. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11115. (void)key;
  11116. if (!filename) {
  11117. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  11118. return FORM_FIELD_STORAGE_ABORT;
  11119. }
  11120. mg_snprintf(fud->conn,
  11121. &truncated,
  11122. path,
  11123. pathlen - 1,
  11124. "%s/%s",
  11125. fud->destination_dir,
  11126. filename);
  11127. if (truncated) {
  11128. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  11129. return FORM_FIELD_STORAGE_ABORT;
  11130. }
  11131. return FORM_FIELD_STORAGE_STORE;
  11132. }
  11133. /* Helper function for deprecated mg_upload. */
  11134. static int
  11135. mg_upload_field_get(const char *key,
  11136. const char *value,
  11137. size_t value_size,
  11138. void *user_data)
  11139. {
  11140. /* Function should never be called */
  11141. (void)key;
  11142. (void)value;
  11143. (void)value_size;
  11144. (void)user_data;
  11145. return 0;
  11146. }
  11147. /* Helper function for deprecated mg_upload. */
  11148. static int
  11149. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  11150. {
  11151. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  11152. (void)file_size;
  11153. fud->num_uploaded_files++;
  11154. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  11155. return 0;
  11156. }
  11157. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  11158. int
  11159. mg_upload(struct mg_connection *conn, const char *destination_dir)
  11160. {
  11161. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  11162. struct mg_form_data_handler fdh = {mg_upload_field_found,
  11163. mg_upload_field_get,
  11164. mg_upload_field_stored,
  11165. 0};
  11166. int ret;
  11167. fdh.user_data = (void *)&fud;
  11168. ret = mg_handle_form_request(conn, &fdh);
  11169. if (ret < 0) {
  11170. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  11171. }
  11172. return fud.num_uploaded_files;
  11173. }
  11174. #endif
  11175. static int
  11176. get_first_ssl_listener_index(const struct mg_context *ctx)
  11177. {
  11178. unsigned int i;
  11179. int idx = -1;
  11180. if (ctx) {
  11181. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  11182. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  11183. }
  11184. }
  11185. return idx;
  11186. }
  11187. /* Return host (without port) */
  11188. /* Use mg_free to free the result */
  11189. static const char *
  11190. alloc_get_host(struct mg_connection *conn)
  11191. {
  11192. char buf[1025];
  11193. size_t buflen = sizeof(buf);
  11194. const char *host_header = get_header(conn->request_info.http_headers,
  11195. conn->request_info.num_headers,
  11196. "Host");
  11197. char *host;
  11198. if (host_header != NULL) {
  11199. char *pos;
  11200. /* Create a local copy of the "Host" header, since it might be
  11201. * modified here. */
  11202. mg_strlcpy(buf, host_header, buflen);
  11203. buf[buflen - 1] = '\0';
  11204. host = buf;
  11205. while (isspace((unsigned char)*host)) {
  11206. host++;
  11207. }
  11208. /* If the "Host" is an IPv6 address, like [::1], parse until ]
  11209. * is found. */
  11210. if (*host == '[') {
  11211. pos = strchr(host, ']');
  11212. if (!pos) {
  11213. /* Malformed hostname starts with '[', but no ']' found */
  11214. DEBUG_TRACE("%s", "Host name format error '[' without ']'");
  11215. return NULL;
  11216. }
  11217. /* terminate after ']' */
  11218. pos[1] = 0;
  11219. } else {
  11220. /* Otherwise, a ':' separates hostname and port number */
  11221. pos = strchr(host, ':');
  11222. if (pos != NULL) {
  11223. *pos = '\0';
  11224. }
  11225. }
  11226. if (conn->ssl) {
  11227. /* This is a HTTPS connection, maybe we have a hostname
  11228. * from SNI (set in ssl_servername_callback). */
  11229. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  11230. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  11231. /* We are not using the default domain */
  11232. if (mg_strcasecmp(host, sslhost)) {
  11233. /* Mismatch between SNI domain and HTTP domain */
  11234. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  11235. sslhost,
  11236. host);
  11237. return NULL;
  11238. }
  11239. }
  11240. DEBUG_TRACE("HTTPS Host: %s", host);
  11241. } else {
  11242. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  11243. while (dom) {
  11244. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  11245. /* Found matching domain */
  11246. DEBUG_TRACE("HTTP domain %s found",
  11247. dom->config[AUTHENTICATION_DOMAIN]);
  11248. /* TODO: Check if this is a HTTP or HTTPS domain */
  11249. conn->dom_ctx = dom;
  11250. break;
  11251. }
  11252. dom = dom->next;
  11253. }
  11254. DEBUG_TRACE("HTTP Host: %s", host);
  11255. }
  11256. } else {
  11257. sockaddr_to_string(buf, buflen, &conn->client.lsa);
  11258. host = buf;
  11259. DEBUG_TRACE("IP: %s", host);
  11260. }
  11261. return mg_strdup_ctx(host, conn->phys_ctx);
  11262. }
  11263. static void
  11264. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  11265. {
  11266. char target_url[MG_BUF_LEN];
  11267. int truncated = 0;
  11268. conn->must_close = 1;
  11269. /* Send host, port, uri and (if it exists) ?query_string */
  11270. if (conn->host) {
  11271. /* Use "308 Permanent Redirect" */
  11272. int redirect_code = 308;
  11273. /* Create target URL */
  11274. mg_snprintf(
  11275. conn,
  11276. &truncated,
  11277. target_url,
  11278. sizeof(target_url),
  11279. "https://%s:%d%s%s%s",
  11280. conn->host,
  11281. #if defined(USE_IPV6)
  11282. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  11283. == AF_INET6)
  11284. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11285. .lsa.sin6.sin6_port)
  11286. :
  11287. #endif
  11288. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  11289. .lsa.sin.sin_port),
  11290. conn->request_info.local_uri,
  11291. (conn->request_info.query_string == NULL) ? "" : "?",
  11292. (conn->request_info.query_string == NULL)
  11293. ? ""
  11294. : conn->request_info.query_string);
  11295. /* Check overflow in location buffer (will not occur if MG_BUF_LEN
  11296. * is used as buffer size) */
  11297. if (truncated) {
  11298. mg_send_http_error(conn, 500, "%s", "Redirect URL too long");
  11299. return;
  11300. }
  11301. /* Use redirect helper function */
  11302. mg_send_http_redirect(conn, target_url, redirect_code);
  11303. }
  11304. }
  11305. static void
  11306. handler_info_acquire(struct mg_handler_info *handler_info)
  11307. {
  11308. pthread_mutex_lock(&handler_info->refcount_mutex);
  11309. handler_info->refcount++;
  11310. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11311. }
  11312. static void
  11313. handler_info_release(struct mg_handler_info *handler_info)
  11314. {
  11315. pthread_mutex_lock(&handler_info->refcount_mutex);
  11316. handler_info->refcount--;
  11317. pthread_cond_signal(&handler_info->refcount_cond);
  11318. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11319. }
  11320. static void
  11321. handler_info_wait_unused(struct mg_handler_info *handler_info)
  11322. {
  11323. pthread_mutex_lock(&handler_info->refcount_mutex);
  11324. while (handler_info->refcount) {
  11325. pthread_cond_wait(&handler_info->refcount_cond,
  11326. &handler_info->refcount_mutex);
  11327. }
  11328. pthread_mutex_unlock(&handler_info->refcount_mutex);
  11329. }
  11330. static void
  11331. mg_set_handler_type(struct mg_context *phys_ctx,
  11332. struct mg_domain_context *dom_ctx,
  11333. const char *uri,
  11334. int handler_type,
  11335. int is_delete_request,
  11336. mg_request_handler handler,
  11337. struct mg_websocket_subprotocols *subprotocols,
  11338. mg_websocket_connect_handler connect_handler,
  11339. mg_websocket_ready_handler ready_handler,
  11340. mg_websocket_data_handler data_handler,
  11341. mg_websocket_close_handler close_handler,
  11342. mg_authorization_handler auth_handler,
  11343. void *cbdata)
  11344. {
  11345. struct mg_handler_info *tmp_rh, **lastref;
  11346. size_t urilen = strlen(uri);
  11347. if (handler_type == WEBSOCKET_HANDLER) {
  11348. DEBUG_ASSERT(handler == NULL);
  11349. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  11350. || ready_handler != NULL || data_handler != NULL
  11351. || close_handler != NULL);
  11352. DEBUG_ASSERT(auth_handler == NULL);
  11353. if (handler != NULL) {
  11354. return;
  11355. }
  11356. if (!is_delete_request && (connect_handler == NULL)
  11357. && (ready_handler == NULL) && (data_handler == NULL)
  11358. && (close_handler == NULL)) {
  11359. return;
  11360. }
  11361. if (auth_handler != NULL) {
  11362. return;
  11363. }
  11364. } else if (handler_type == REQUEST_HANDLER) {
  11365. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11366. && data_handler == NULL && close_handler == NULL);
  11367. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  11368. DEBUG_ASSERT(auth_handler == NULL);
  11369. if ((connect_handler != NULL) || (ready_handler != NULL)
  11370. || (data_handler != NULL) || (close_handler != NULL)) {
  11371. return;
  11372. }
  11373. if (!is_delete_request && (handler == NULL)) {
  11374. return;
  11375. }
  11376. if (auth_handler != NULL) {
  11377. return;
  11378. }
  11379. } else { /* AUTH_HANDLER */
  11380. DEBUG_ASSERT(handler == NULL);
  11381. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  11382. && data_handler == NULL && close_handler == NULL);
  11383. DEBUG_ASSERT(auth_handler != NULL);
  11384. if (handler != NULL) {
  11385. return;
  11386. }
  11387. if ((connect_handler != NULL) || (ready_handler != NULL)
  11388. || (data_handler != NULL) || (close_handler != NULL)) {
  11389. return;
  11390. }
  11391. if (!is_delete_request && (auth_handler == NULL)) {
  11392. return;
  11393. }
  11394. }
  11395. if (!phys_ctx || !dom_ctx) {
  11396. return;
  11397. }
  11398. mg_lock_context(phys_ctx);
  11399. /* first try to find an existing handler */
  11400. lastref = &(dom_ctx->handlers);
  11401. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  11402. if (tmp_rh->handler_type == handler_type) {
  11403. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11404. if (!is_delete_request) {
  11405. /* update existing handler */
  11406. if (handler_type == REQUEST_HANDLER) {
  11407. /* Wait for end of use before updating */
  11408. handler_info_wait_unused(tmp_rh);
  11409. /* Ok, the handler is no more use -> Update it */
  11410. tmp_rh->handler = handler;
  11411. } else if (handler_type == WEBSOCKET_HANDLER) {
  11412. tmp_rh->subprotocols = subprotocols;
  11413. tmp_rh->connect_handler = connect_handler;
  11414. tmp_rh->ready_handler = ready_handler;
  11415. tmp_rh->data_handler = data_handler;
  11416. tmp_rh->close_handler = close_handler;
  11417. } else { /* AUTH_HANDLER */
  11418. tmp_rh->auth_handler = auth_handler;
  11419. }
  11420. tmp_rh->cbdata = cbdata;
  11421. } else {
  11422. /* remove existing handler */
  11423. if (handler_type == REQUEST_HANDLER) {
  11424. /* Wait for end of use before removing */
  11425. handler_info_wait_unused(tmp_rh);
  11426. /* Ok, the handler is no more used -> Destroy resources
  11427. */
  11428. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11429. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11430. }
  11431. *lastref = tmp_rh->next;
  11432. mg_free(tmp_rh->uri);
  11433. mg_free(tmp_rh);
  11434. }
  11435. mg_unlock_context(phys_ctx);
  11436. return;
  11437. }
  11438. }
  11439. lastref = &(tmp_rh->next);
  11440. }
  11441. if (is_delete_request) {
  11442. /* no handler to set, this was a remove request to a non-existing
  11443. * handler */
  11444. mg_unlock_context(phys_ctx);
  11445. return;
  11446. }
  11447. tmp_rh =
  11448. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11449. 1,
  11450. phys_ctx);
  11451. if (tmp_rh == NULL) {
  11452. mg_unlock_context(phys_ctx);
  11453. mg_cry_ctx_internal(phys_ctx,
  11454. "%s",
  11455. "Cannot create new request handler struct, OOM");
  11456. return;
  11457. }
  11458. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11459. if (!tmp_rh->uri) {
  11460. mg_unlock_context(phys_ctx);
  11461. mg_free(tmp_rh);
  11462. mg_cry_ctx_internal(phys_ctx,
  11463. "%s",
  11464. "Cannot create new request handler struct, OOM");
  11465. return;
  11466. }
  11467. tmp_rh->uri_len = urilen;
  11468. if (handler_type == REQUEST_HANDLER) {
  11469. /* Init refcount mutex and condition */
  11470. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11471. mg_unlock_context(phys_ctx);
  11472. mg_free(tmp_rh);
  11473. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount mutex");
  11474. return;
  11475. }
  11476. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11477. mg_unlock_context(phys_ctx);
  11478. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11479. mg_free(tmp_rh);
  11480. mg_cry_ctx_internal(phys_ctx, "%s", "Cannot init refcount cond");
  11481. return;
  11482. }
  11483. tmp_rh->refcount = 0;
  11484. tmp_rh->handler = handler;
  11485. } else if (handler_type == WEBSOCKET_HANDLER) {
  11486. tmp_rh->subprotocols = subprotocols;
  11487. tmp_rh->connect_handler = connect_handler;
  11488. tmp_rh->ready_handler = ready_handler;
  11489. tmp_rh->data_handler = data_handler;
  11490. tmp_rh->close_handler = close_handler;
  11491. } else { /* AUTH_HANDLER */
  11492. tmp_rh->auth_handler = auth_handler;
  11493. }
  11494. tmp_rh->cbdata = cbdata;
  11495. tmp_rh->handler_type = handler_type;
  11496. tmp_rh->next = NULL;
  11497. *lastref = tmp_rh;
  11498. mg_unlock_context(phys_ctx);
  11499. }
  11500. void
  11501. mg_set_request_handler(struct mg_context *ctx,
  11502. const char *uri,
  11503. mg_request_handler handler,
  11504. void *cbdata)
  11505. {
  11506. mg_set_handler_type(ctx,
  11507. &(ctx->dd),
  11508. uri,
  11509. REQUEST_HANDLER,
  11510. handler == NULL,
  11511. handler,
  11512. NULL,
  11513. NULL,
  11514. NULL,
  11515. NULL,
  11516. NULL,
  11517. NULL,
  11518. cbdata);
  11519. }
  11520. void
  11521. mg_set_websocket_handler(struct mg_context *ctx,
  11522. const char *uri,
  11523. mg_websocket_connect_handler connect_handler,
  11524. mg_websocket_ready_handler ready_handler,
  11525. mg_websocket_data_handler data_handler,
  11526. mg_websocket_close_handler close_handler,
  11527. void *cbdata)
  11528. {
  11529. mg_set_websocket_handler_with_subprotocols(ctx,
  11530. uri,
  11531. NULL,
  11532. connect_handler,
  11533. ready_handler,
  11534. data_handler,
  11535. close_handler,
  11536. cbdata);
  11537. }
  11538. void
  11539. mg_set_websocket_handler_with_subprotocols(
  11540. struct mg_context *ctx,
  11541. const char *uri,
  11542. struct mg_websocket_subprotocols *subprotocols,
  11543. mg_websocket_connect_handler connect_handler,
  11544. mg_websocket_ready_handler ready_handler,
  11545. mg_websocket_data_handler data_handler,
  11546. mg_websocket_close_handler close_handler,
  11547. void *cbdata)
  11548. {
  11549. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11550. && (data_handler == NULL)
  11551. && (close_handler == NULL);
  11552. mg_set_handler_type(ctx,
  11553. &(ctx->dd),
  11554. uri,
  11555. WEBSOCKET_HANDLER,
  11556. is_delete_request,
  11557. NULL,
  11558. subprotocols,
  11559. connect_handler,
  11560. ready_handler,
  11561. data_handler,
  11562. close_handler,
  11563. NULL,
  11564. cbdata);
  11565. }
  11566. void
  11567. mg_set_auth_handler(struct mg_context *ctx,
  11568. const char *uri,
  11569. mg_authorization_handler handler,
  11570. void *cbdata)
  11571. {
  11572. mg_set_handler_type(ctx,
  11573. &(ctx->dd),
  11574. uri,
  11575. AUTH_HANDLER,
  11576. handler == NULL,
  11577. NULL,
  11578. NULL,
  11579. NULL,
  11580. NULL,
  11581. NULL,
  11582. NULL,
  11583. handler,
  11584. cbdata);
  11585. }
  11586. static int
  11587. get_request_handler(struct mg_connection *conn,
  11588. int handler_type,
  11589. mg_request_handler *handler,
  11590. struct mg_websocket_subprotocols **subprotocols,
  11591. mg_websocket_connect_handler *connect_handler,
  11592. mg_websocket_ready_handler *ready_handler,
  11593. mg_websocket_data_handler *data_handler,
  11594. mg_websocket_close_handler *close_handler,
  11595. mg_authorization_handler *auth_handler,
  11596. void **cbdata,
  11597. struct mg_handler_info **handler_info)
  11598. {
  11599. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11600. if (request_info) {
  11601. const char *uri = request_info->local_uri;
  11602. size_t urilen = strlen(uri);
  11603. struct mg_handler_info *tmp_rh;
  11604. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11605. return 0;
  11606. }
  11607. mg_lock_context(conn->phys_ctx);
  11608. /* first try for an exact match */
  11609. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11610. tmp_rh = tmp_rh->next) {
  11611. if (tmp_rh->handler_type == handler_type) {
  11612. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11613. if (handler_type == WEBSOCKET_HANDLER) {
  11614. *subprotocols = tmp_rh->subprotocols;
  11615. *connect_handler = tmp_rh->connect_handler;
  11616. *ready_handler = tmp_rh->ready_handler;
  11617. *data_handler = tmp_rh->data_handler;
  11618. *close_handler = tmp_rh->close_handler;
  11619. } else if (handler_type == REQUEST_HANDLER) {
  11620. *handler = tmp_rh->handler;
  11621. /* Acquire handler and give it back */
  11622. handler_info_acquire(tmp_rh);
  11623. *handler_info = tmp_rh;
  11624. } else { /* AUTH_HANDLER */
  11625. *auth_handler = tmp_rh->auth_handler;
  11626. }
  11627. *cbdata = tmp_rh->cbdata;
  11628. mg_unlock_context(conn->phys_ctx);
  11629. return 1;
  11630. }
  11631. }
  11632. }
  11633. /* next try for a partial match, we will accept uri/something */
  11634. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11635. tmp_rh = tmp_rh->next) {
  11636. if (tmp_rh->handler_type == handler_type) {
  11637. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11638. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11639. if (handler_type == WEBSOCKET_HANDLER) {
  11640. *subprotocols = tmp_rh->subprotocols;
  11641. *connect_handler = tmp_rh->connect_handler;
  11642. *ready_handler = tmp_rh->ready_handler;
  11643. *data_handler = tmp_rh->data_handler;
  11644. *close_handler = tmp_rh->close_handler;
  11645. } else if (handler_type == REQUEST_HANDLER) {
  11646. *handler = tmp_rh->handler;
  11647. /* Acquire handler and give it back */
  11648. handler_info_acquire(tmp_rh);
  11649. *handler_info = tmp_rh;
  11650. } else { /* AUTH_HANDLER */
  11651. *auth_handler = tmp_rh->auth_handler;
  11652. }
  11653. *cbdata = tmp_rh->cbdata;
  11654. mg_unlock_context(conn->phys_ctx);
  11655. return 1;
  11656. }
  11657. }
  11658. }
  11659. /* finally try for pattern match */
  11660. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11661. tmp_rh = tmp_rh->next) {
  11662. if (tmp_rh->handler_type == handler_type) {
  11663. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11664. if (handler_type == WEBSOCKET_HANDLER) {
  11665. *subprotocols = tmp_rh->subprotocols;
  11666. *connect_handler = tmp_rh->connect_handler;
  11667. *ready_handler = tmp_rh->ready_handler;
  11668. *data_handler = tmp_rh->data_handler;
  11669. *close_handler = tmp_rh->close_handler;
  11670. } else if (handler_type == REQUEST_HANDLER) {
  11671. *handler = tmp_rh->handler;
  11672. /* Acquire handler and give it back */
  11673. handler_info_acquire(tmp_rh);
  11674. *handler_info = tmp_rh;
  11675. } else { /* AUTH_HANDLER */
  11676. *auth_handler = tmp_rh->auth_handler;
  11677. }
  11678. *cbdata = tmp_rh->cbdata;
  11679. mg_unlock_context(conn->phys_ctx);
  11680. return 1;
  11681. }
  11682. }
  11683. }
  11684. mg_unlock_context(conn->phys_ctx);
  11685. }
  11686. return 0; /* none found */
  11687. }
  11688. /* Check if the script file is in a path, allowed for script files.
  11689. * This can be used if uploading files is possible not only for the server
  11690. * admin, and the upload mechanism does not check the file extension.
  11691. */
  11692. static int
  11693. is_in_script_path(const struct mg_connection *conn, const char *path)
  11694. {
  11695. /* TODO (Feature): Add config value for allowed script path.
  11696. * Default: All allowed. */
  11697. (void)conn;
  11698. (void)path;
  11699. return 1;
  11700. }
  11701. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11702. static int
  11703. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11704. void *cbdata)
  11705. {
  11706. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11707. if (pcallbacks->websocket_connect) {
  11708. return pcallbacks->websocket_connect(conn);
  11709. }
  11710. /* No handler set - assume "OK" */
  11711. return 0;
  11712. }
  11713. static void
  11714. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11715. {
  11716. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11717. if (pcallbacks->websocket_ready) {
  11718. pcallbacks->websocket_ready(conn);
  11719. }
  11720. }
  11721. static int
  11722. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11723. int bits,
  11724. char *data,
  11725. size_t len,
  11726. void *cbdata)
  11727. {
  11728. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11729. if (pcallbacks->websocket_data) {
  11730. return pcallbacks->websocket_data(conn, bits, data, len);
  11731. }
  11732. /* No handler set - assume "OK" */
  11733. return 1;
  11734. }
  11735. #endif
  11736. /* This is the heart of the Civetweb's logic.
  11737. * This function is called when the request is read, parsed and validated,
  11738. * and Civetweb must decide what action to take: serve a file, or
  11739. * a directory, or call embedded function, etcetera. */
  11740. static void
  11741. handle_request(struct mg_connection *conn)
  11742. {
  11743. struct mg_request_info *ri = &conn->request_info;
  11744. char path[PATH_MAX];
  11745. int uri_len, ssl_index;
  11746. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11747. is_put_or_delete_request = 0, is_callback_resource = 0;
  11748. int i;
  11749. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11750. mg_request_handler callback_handler = NULL;
  11751. struct mg_handler_info *handler_info = NULL;
  11752. struct mg_websocket_subprotocols *subprotocols;
  11753. mg_websocket_connect_handler ws_connect_handler = NULL;
  11754. mg_websocket_ready_handler ws_ready_handler = NULL;
  11755. mg_websocket_data_handler ws_data_handler = NULL;
  11756. mg_websocket_close_handler ws_close_handler = NULL;
  11757. void *callback_data = NULL;
  11758. mg_authorization_handler auth_handler = NULL;
  11759. void *auth_callback_data = NULL;
  11760. int handler_type;
  11761. time_t curtime = time(NULL);
  11762. char date[64];
  11763. path[0] = 0;
  11764. /* 1. get the request url */
  11765. /* 1.1. split into url and query string */
  11766. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11767. != NULL) {
  11768. *((char *)conn->request_info.query_string++) = '\0';
  11769. }
  11770. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11771. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11772. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11773. if (ssl_index >= 0) {
  11774. redirect_to_https_port(conn, ssl_index);
  11775. } else {
  11776. /* A http to https forward port has been specified,
  11777. * but no https port to forward to. */
  11778. mg_send_http_error(conn,
  11779. 503,
  11780. "%s",
  11781. "Error: SSL forward not configured properly");
  11782. mg_cry_internal(conn,
  11783. "%s",
  11784. "Can not redirect to SSL, no SSL port available");
  11785. }
  11786. return;
  11787. }
  11788. uri_len = (int)strlen(ri->local_uri);
  11789. /* 1.3. decode url (if config says so) */
  11790. if (should_decode_url(conn)) {
  11791. mg_url_decode(
  11792. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11793. }
  11794. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11795. * not possible */
  11796. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11797. /* step 1. completed, the url is known now */
  11798. uri_len = (int)strlen(ri->local_uri);
  11799. DEBUG_TRACE("URL: %s", ri->local_uri);
  11800. /* 2. if this ip has limited speed, set it for this connection */
  11801. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11802. get_remote_ip(conn),
  11803. ri->local_uri);
  11804. /* 3. call a "handle everything" callback, if registered */
  11805. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11806. /* Note that since V1.7 the "begin_request" function is called
  11807. * before an authorization check. If an authorization check is
  11808. * required, use a request_handler instead. */
  11809. i = conn->phys_ctx->callbacks.begin_request(conn);
  11810. if (i > 0) {
  11811. /* callback already processed the request. Store the
  11812. return value as a status code for the access log. */
  11813. conn->status_code = i;
  11814. discard_unread_request_data(conn);
  11815. return;
  11816. } else if (i == 0) {
  11817. /* civetweb should process the request */
  11818. } else {
  11819. /* unspecified - may change with the next version */
  11820. return;
  11821. }
  11822. }
  11823. /* request not yet handled by a handler or redirect, so the request
  11824. * is processed here */
  11825. /* 4. Check for CORS preflight requests and handle them (if configured).
  11826. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11827. */
  11828. if (!strcmp(ri->request_method, "OPTIONS")) {
  11829. /* Send a response to CORS preflights only if
  11830. * access_control_allow_methods is not NULL and not an empty string.
  11831. * In this case, scripts can still handle CORS. */
  11832. const char *cors_meth_cfg =
  11833. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11834. const char *cors_orig_cfg =
  11835. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11836. const char *cors_origin =
  11837. get_header(ri->http_headers, ri->num_headers, "Origin");
  11838. const char *cors_acrm = get_header(ri->http_headers,
  11839. ri->num_headers,
  11840. "Access-Control-Request-Method");
  11841. /* Todo: check if cors_origin is in cors_orig_cfg.
  11842. * Or, let the client check this. */
  11843. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11844. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11845. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11846. /* This is a valid CORS preflight, and the server is configured
  11847. * to
  11848. * handle it automatically. */
  11849. const char *cors_acrh =
  11850. get_header(ri->http_headers,
  11851. ri->num_headers,
  11852. "Access-Control-Request-Headers");
  11853. gmt_time_string(date, sizeof(date), &curtime);
  11854. mg_printf(conn,
  11855. "HTTP/1.1 200 OK\r\n"
  11856. "Date: %s\r\n"
  11857. "Access-Control-Allow-Origin: %s\r\n"
  11858. "Access-Control-Allow-Methods: %s\r\n"
  11859. "Content-Length: 0\r\n"
  11860. "Connection: %s\r\n",
  11861. date,
  11862. cors_orig_cfg,
  11863. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11864. suggest_connection_header(conn));
  11865. if (cors_acrh != NULL) {
  11866. /* CORS request is asking for additional headers */
  11867. const char *cors_hdr_cfg =
  11868. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11869. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11870. /* Allow only if access_control_allow_headers is
  11871. * not NULL and not an empty string. If this
  11872. * configuration is set to *, allow everything.
  11873. * Otherwise this configuration must be a list
  11874. * of allowed HTTP header names. */
  11875. mg_printf(conn,
  11876. "Access-Control-Allow-Headers: %s\r\n",
  11877. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11878. : cors_hdr_cfg));
  11879. }
  11880. }
  11881. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11882. mg_printf(conn, "\r\n");
  11883. return;
  11884. }
  11885. }
  11886. /* 5. interpret the url to find out how the request must be handled
  11887. */
  11888. /* 5.1. first test, if the request targets the regular http(s)://
  11889. * protocol namespace or the websocket ws(s):// protocol namespace.
  11890. */
  11891. is_websocket_request = is_websocket_protocol(conn);
  11892. #if defined(USE_WEBSOCKET)
  11893. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11894. #else
  11895. handler_type = REQUEST_HANDLER;
  11896. #endif /* defined(USE_WEBSOCKET) */
  11897. /* 5.2. check if the request will be handled by a callback */
  11898. if (get_request_handler(conn,
  11899. handler_type,
  11900. &callback_handler,
  11901. &subprotocols,
  11902. &ws_connect_handler,
  11903. &ws_ready_handler,
  11904. &ws_data_handler,
  11905. &ws_close_handler,
  11906. NULL,
  11907. &callback_data,
  11908. &handler_info)) {
  11909. /* 5.2.1. A callback will handle this request. All requests
  11910. * handled
  11911. * by a callback have to be considered as requests to a script
  11912. * resource. */
  11913. is_callback_resource = 1;
  11914. is_script_resource = 1;
  11915. is_put_or_delete_request = is_put_or_delete_method(conn);
  11916. } else {
  11917. no_callback_resource:
  11918. /* 5.2.2. No callback is responsible for this request. The URI
  11919. * addresses a file based resource (static content or Lua/cgi
  11920. * scripts in the file system). */
  11921. is_callback_resource = 0;
  11922. interpret_uri(conn,
  11923. path,
  11924. sizeof(path),
  11925. &file.stat,
  11926. &is_found,
  11927. &is_script_resource,
  11928. &is_websocket_request,
  11929. &is_put_or_delete_request);
  11930. }
  11931. /* 6. authorization check */
  11932. /* 6.1. a custom authorization handler is installed */
  11933. if (get_request_handler(conn,
  11934. AUTH_HANDLER,
  11935. NULL,
  11936. NULL,
  11937. NULL,
  11938. NULL,
  11939. NULL,
  11940. NULL,
  11941. &auth_handler,
  11942. &auth_callback_data,
  11943. NULL)) {
  11944. if (!auth_handler(conn, auth_callback_data)) {
  11945. return;
  11946. }
  11947. } else if (is_put_or_delete_request && !is_script_resource
  11948. && !is_callback_resource) {
  11949. /* 6.2. this request is a PUT/DELETE to a real file */
  11950. /* 6.2.1. thus, the server must have real files */
  11951. #if defined(NO_FILES)
  11952. if (1) {
  11953. #else
  11954. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11955. #endif
  11956. /* This server does not have any real files, thus the
  11957. * PUT/DELETE methods are not valid. */
  11958. mg_send_http_error(conn,
  11959. 405,
  11960. "%s method not allowed",
  11961. conn->request_info.request_method);
  11962. return;
  11963. }
  11964. #if !defined(NO_FILES)
  11965. /* 6.2.2. Check if put authorization for static files is
  11966. * available.
  11967. */
  11968. if (!is_authorized_for_put(conn)) {
  11969. send_authorization_request(conn, NULL);
  11970. return;
  11971. }
  11972. #endif
  11973. } else {
  11974. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11975. * or it is a PUT or DELETE request to a resource that does not
  11976. * correspond to a file. Check authorization. */
  11977. if (!check_authorization(conn, path)) {
  11978. send_authorization_request(conn, NULL);
  11979. return;
  11980. }
  11981. }
  11982. /* request is authorized or does not need authorization */
  11983. /* 7. check if there are request handlers for this uri */
  11984. if (is_callback_resource) {
  11985. if (!is_websocket_request) {
  11986. i = callback_handler(conn, callback_data);
  11987. /* Callback handler will not be used anymore. Release it */
  11988. handler_info_release(handler_info);
  11989. if (i > 0) {
  11990. /* Do nothing, callback has served the request. Store
  11991. * then return value as status code for the log and discard
  11992. * all data from the client not used by the callback. */
  11993. conn->status_code = i;
  11994. discard_unread_request_data(conn);
  11995. } else {
  11996. /* The handler did NOT handle the request. */
  11997. /* Some proper reactions would be:
  11998. * a) close the connections without sending anything
  11999. * b) send a 404 not found
  12000. * c) try if there is a file matching the URI
  12001. * It would be possible to do a, b or c in the callback
  12002. * implementation, and return 1 - we cannot do anything
  12003. * here, that is not possible in the callback.
  12004. *
  12005. * TODO: What would be the best reaction here?
  12006. * (Note: The reaction may change, if there is a better
  12007. *idea.)
  12008. */
  12009. /* For the moment, use option c: We look for a proper file,
  12010. * but since a file request is not always a script resource,
  12011. * the authorization check might be different. */
  12012. interpret_uri(conn,
  12013. path,
  12014. sizeof(path),
  12015. &file.stat,
  12016. &is_found,
  12017. &is_script_resource,
  12018. &is_websocket_request,
  12019. &is_put_or_delete_request);
  12020. callback_handler = NULL;
  12021. /* Here we are at a dead end:
  12022. * According to URI matching, a callback should be
  12023. * responsible for handling the request,
  12024. * we called it, but the callback declared itself
  12025. * not responsible.
  12026. * We use a goto here, to get out of this dead end,
  12027. * and continue with the default handling.
  12028. * A goto here is simpler and better to understand
  12029. * than some curious loop. */
  12030. goto no_callback_resource;
  12031. }
  12032. } else {
  12033. #if defined(USE_WEBSOCKET)
  12034. handle_websocket_request(conn,
  12035. path,
  12036. is_callback_resource,
  12037. subprotocols,
  12038. ws_connect_handler,
  12039. ws_ready_handler,
  12040. ws_data_handler,
  12041. ws_close_handler,
  12042. callback_data);
  12043. #endif
  12044. }
  12045. return;
  12046. }
  12047. /* 8. handle websocket requests */
  12048. #if defined(USE_WEBSOCKET)
  12049. if (is_websocket_request) {
  12050. if (is_script_resource) {
  12051. if (is_in_script_path(conn, path)) {
  12052. /* Websocket Lua script */
  12053. handle_websocket_request(conn,
  12054. path,
  12055. 0 /* Lua Script */,
  12056. NULL,
  12057. NULL,
  12058. NULL,
  12059. NULL,
  12060. NULL,
  12061. conn->phys_ctx->user_data);
  12062. } else {
  12063. /* Script was in an illegal path */
  12064. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12065. }
  12066. } else {
  12067. #if defined(MG_LEGACY_INTERFACE)
  12068. handle_websocket_request(
  12069. conn,
  12070. path,
  12071. !is_script_resource /* could be deprecated global callback */,
  12072. NULL,
  12073. deprecated_websocket_connect_wrapper,
  12074. deprecated_websocket_ready_wrapper,
  12075. deprecated_websocket_data_wrapper,
  12076. NULL,
  12077. conn->phys_ctx->user_data);
  12078. #else
  12079. mg_send_http_error(conn, 404, "%s", "Not found");
  12080. #endif
  12081. }
  12082. return;
  12083. } else
  12084. #endif
  12085. #if defined(NO_FILES)
  12086. /* 9a. In case the server uses only callbacks, this uri is
  12087. * unknown.
  12088. * Then, all request handling ends here. */
  12089. mg_send_http_error(conn, 404, "%s", "Not Found");
  12090. #else
  12091. /* 9b. This request is either for a static file or resource handled
  12092. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  12093. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  12094. mg_send_http_error(conn, 404, "%s", "Not Found");
  12095. return;
  12096. }
  12097. /* 10. Request is handled by a script */
  12098. if (is_script_resource) {
  12099. handle_file_based_request(conn, path, &file);
  12100. return;
  12101. }
  12102. /* 11. Handle put/delete/mkcol requests */
  12103. if (is_put_or_delete_request) {
  12104. /* 11.1. PUT method */
  12105. if (!strcmp(ri->request_method, "PUT")) {
  12106. put_file(conn, path);
  12107. return;
  12108. }
  12109. /* 11.2. DELETE method */
  12110. if (!strcmp(ri->request_method, "DELETE")) {
  12111. delete_file(conn, path);
  12112. return;
  12113. }
  12114. /* 11.3. MKCOL method */
  12115. if (!strcmp(ri->request_method, "MKCOL")) {
  12116. mkcol(conn, path);
  12117. return;
  12118. }
  12119. /* 11.4. PATCH method
  12120. * This method is not supported for static resources,
  12121. * only for scripts (Lua, CGI) and callbacks. */
  12122. mg_send_http_error(conn,
  12123. 405,
  12124. "%s method not allowed",
  12125. conn->request_info.request_method);
  12126. return;
  12127. }
  12128. /* 11. File does not exist, or it was configured that it should be
  12129. * hidden */
  12130. if (!is_found || (must_hide_file(conn, path))) {
  12131. mg_send_http_error(conn, 404, "%s", "Not found");
  12132. return;
  12133. }
  12134. /* 12. Directory uris should end with a slash */
  12135. if (file.stat.is_directory && (uri_len > 0)
  12136. && (ri->local_uri[uri_len - 1] != '/')) {
  12137. gmt_time_string(date, sizeof(date), &curtime);
  12138. mg_printf(conn,
  12139. "HTTP/1.1 301 Moved Permanently\r\n"
  12140. "Location: %s/\r\n"
  12141. "Date: %s\r\n"
  12142. /* "Cache-Control: private\r\n" (= default) */
  12143. "Content-Length: 0\r\n"
  12144. "Connection: %s\r\n",
  12145. ri->request_uri,
  12146. date,
  12147. suggest_connection_header(conn));
  12148. send_additional_header(conn);
  12149. mg_printf(conn, "\r\n");
  12150. return;
  12151. }
  12152. /* 13. Handle other methods than GET/HEAD */
  12153. /* 13.1. Handle PROPFIND */
  12154. if (!strcmp(ri->request_method, "PROPFIND")) {
  12155. handle_propfind(conn, path, &file.stat);
  12156. return;
  12157. }
  12158. /* 13.2. Handle OPTIONS for files */
  12159. if (!strcmp(ri->request_method, "OPTIONS")) {
  12160. /* This standard handler is only used for real files.
  12161. * Scripts should support the OPTIONS method themselves, to allow a
  12162. * maximum flexibility.
  12163. * Lua and CGI scripts may fully support CORS this way (including
  12164. * preflights). */
  12165. send_options(conn);
  12166. return;
  12167. }
  12168. /* 13.3. everything but GET and HEAD (e.g. POST) */
  12169. if ((0 != strcmp(ri->request_method, "GET"))
  12170. && (0 != strcmp(ri->request_method, "HEAD"))) {
  12171. mg_send_http_error(conn,
  12172. 405,
  12173. "%s method not allowed",
  12174. conn->request_info.request_method);
  12175. return;
  12176. }
  12177. /* 14. directories */
  12178. if (file.stat.is_directory) {
  12179. /* Substitute files have already been handled above. */
  12180. /* Here we can either generate and send a directory listing,
  12181. * or send an "access denied" error. */
  12182. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  12183. "yes")) {
  12184. handle_directory_request(conn, path);
  12185. } else {
  12186. mg_send_http_error(conn,
  12187. 403,
  12188. "%s",
  12189. "Error: Directory listing denied");
  12190. }
  12191. return;
  12192. }
  12193. /* 15. read a normal file with GET or HEAD */
  12194. handle_file_based_request(conn, path, &file);
  12195. #endif /* !defined(NO_FILES) */
  12196. }
  12197. #if !defined(NO_FILESYSTEMS)
  12198. static void
  12199. handle_file_based_request(struct mg_connection *conn,
  12200. const char *path,
  12201. struct mg_file *file)
  12202. {
  12203. if (!conn || !conn->dom_ctx) {
  12204. return;
  12205. }
  12206. if (0) {
  12207. #if defined(USE_LUA)
  12208. } else if (match_prefix(
  12209. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  12210. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  12211. path)
  12212. > 0) {
  12213. if (is_in_script_path(conn, path)) {
  12214. /* Lua server page: an SSI like page containing mostly plain
  12215. * html
  12216. * code
  12217. * plus some tags with server generated contents. */
  12218. handle_lsp_request(conn, path, file, NULL);
  12219. } else {
  12220. /* Script was in an illegal path */
  12221. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12222. }
  12223. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  12224. strlen(
  12225. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  12226. path)
  12227. > 0) {
  12228. if (is_in_script_path(conn, path)) {
  12229. /* Lua in-server module script: a CGI like script used to
  12230. * generate
  12231. * the
  12232. * entire reply. */
  12233. mg_exec_lua_script(conn, path, NULL);
  12234. } else {
  12235. /* Script was in an illegal path */
  12236. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12237. }
  12238. #endif
  12239. #if defined(USE_DUKTAPE)
  12240. } else if (match_prefix(
  12241. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  12242. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  12243. path)
  12244. > 0) {
  12245. if (is_in_script_path(conn, path)) {
  12246. /* Call duktape to generate the page */
  12247. mg_exec_duktape_script(conn, path);
  12248. } else {
  12249. /* Script was in an illegal path */
  12250. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12251. }
  12252. #endif
  12253. #if !defined(NO_CGI)
  12254. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  12255. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  12256. path)
  12257. > 0) {
  12258. if (is_in_script_path(conn, path)) {
  12259. /* CGI scripts may support all HTTP methods */
  12260. handle_cgi_request(conn, path);
  12261. } else {
  12262. /* Script was in an illegal path */
  12263. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12264. }
  12265. #endif /* !NO_CGI */
  12266. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  12267. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  12268. path)
  12269. > 0) {
  12270. if (is_in_script_path(conn, path)) {
  12271. handle_ssi_file_request(conn, path, file);
  12272. } else {
  12273. /* Script was in an illegal path */
  12274. mg_send_http_error(conn, 403, "%s", "Forbidden");
  12275. }
  12276. #if !defined(NO_CACHING)
  12277. } else if ((!conn->in_error_handler)
  12278. && is_not_modified(conn, &file->stat)) {
  12279. /* Send 304 "Not Modified" - this must not send any body data */
  12280. handle_not_modified_static_file_request(conn, file);
  12281. #endif /* !NO_CACHING */
  12282. } else {
  12283. handle_static_file_request(conn, path, file, NULL, NULL);
  12284. }
  12285. }
  12286. #endif /* NO_FILESYSTEMS */
  12287. static void
  12288. close_all_listening_sockets(struct mg_context *ctx)
  12289. {
  12290. unsigned int i;
  12291. if (!ctx) {
  12292. return;
  12293. }
  12294. for (i = 0; i < ctx->num_listening_sockets; i++) {
  12295. closesocket(ctx->listening_sockets[i].sock);
  12296. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  12297. }
  12298. mg_free(ctx->listening_sockets);
  12299. ctx->listening_sockets = NULL;
  12300. mg_free(ctx->listening_socket_fds);
  12301. ctx->listening_socket_fds = NULL;
  12302. }
  12303. /* Valid listening port specification is: [ip_address:]port[s]
  12304. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  12305. * Examples for IPv6: [::]:80, [::1]:80,
  12306. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  12307. * see https://tools.ietf.org/html/rfc3513#section-2.2
  12308. * In order to bind to both, IPv4 and IPv6, you can either add
  12309. * both ports using 8080,[::]:8080, or the short form +8080.
  12310. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  12311. * one only accepting IPv4 the other only IPv6. +8080 creates
  12312. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  12313. * environment, they might work differently, or might not work
  12314. * at all - it must be tested what options work best in the
  12315. * relevant network environment.
  12316. */
  12317. static int
  12318. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  12319. {
  12320. unsigned int a, b, c, d, port;
  12321. int ch, len;
  12322. const char *cb;
  12323. #if defined(USE_IPV6)
  12324. char buf[100] = {0};
  12325. #endif
  12326. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  12327. * Also, all-zeroes in the socket address means binding to all addresses
  12328. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  12329. memset(so, 0, sizeof(*so));
  12330. so->lsa.sin.sin_family = AF_INET;
  12331. *ip_version = 0;
  12332. /* Initialize port and len as invalid. */
  12333. port = 0;
  12334. len = 0;
  12335. /* Test for different ways to format this string */
  12336. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  12337. == 5) {
  12338. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  12339. so->lsa.sin.sin_addr.s_addr =
  12340. htonl((a << 24) | (b << 16) | (c << 8) | d);
  12341. so->lsa.sin.sin_port = htons((uint16_t)port);
  12342. *ip_version = 4;
  12343. #if defined(USE_IPV6)
  12344. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  12345. && mg_inet_pton(
  12346. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  12347. /* IPv6 address, examples: see above */
  12348. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  12349. */
  12350. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12351. *ip_version = 6;
  12352. #endif
  12353. } else if ((vec->ptr[0] == '+')
  12354. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  12355. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  12356. /* Add 1 to len for the + character we skipped before */
  12357. len++;
  12358. #if defined(USE_IPV6)
  12359. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  12360. so->lsa.sin6.sin6_family = AF_INET6;
  12361. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  12362. *ip_version = 4 + 6;
  12363. #else
  12364. /* Bind to IPv4 only, since IPv6 is not built in. */
  12365. so->lsa.sin.sin_port = htons((uint16_t)port);
  12366. *ip_version = 4;
  12367. #endif
  12368. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  12369. /* If only port is specified, bind to IPv4, INADDR_ANY */
  12370. so->lsa.sin.sin_port = htons((uint16_t)port);
  12371. *ip_version = 4;
  12372. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  12373. /* String could be a hostname. This check algotithm
  12374. * will only work for RFC 952 compliant hostnames,
  12375. * starting with a letter, containing only letters,
  12376. * digits and hyphen ('-'). Newer specs may allow
  12377. * more, but this is not guaranteed here, since it
  12378. * may interfere with rules for port option lists. */
  12379. /* According to RFC 1035, hostnames are restricted to 255 characters
  12380. * in total (63 between two dots). */
  12381. char hostname[256];
  12382. size_t hostnlen = (size_t)(cb - vec->ptr);
  12383. if (hostnlen >= sizeof(hostname)) {
  12384. /* This would be invalid in any case */
  12385. *ip_version = 0;
  12386. return 0;
  12387. }
  12388. memcpy(hostname, vec->ptr, hostnlen);
  12389. hostname[hostnlen] = 0;
  12390. if (mg_inet_pton(
  12391. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  12392. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12393. *ip_version = 4;
  12394. so->lsa.sin.sin_family = AF_INET;
  12395. so->lsa.sin.sin_port = htons((uint16_t)port);
  12396. len += (int)(hostnlen + 1);
  12397. } else {
  12398. port = 0;
  12399. len = 0;
  12400. }
  12401. #if defined(USE_IPV6)
  12402. } else if (mg_inet_pton(AF_INET6,
  12403. vec->ptr,
  12404. &so->lsa.sin6,
  12405. sizeof(so->lsa.sin6))) {
  12406. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  12407. *ip_version = 6;
  12408. so->lsa.sin6.sin6_family = AF_INET6;
  12409. so->lsa.sin.sin_port = htons((uint16_t)port);
  12410. len += (int)(hostnlen + 1);
  12411. } else {
  12412. port = 0;
  12413. len = 0;
  12414. }
  12415. #endif
  12416. }
  12417. } else {
  12418. /* Parsing failure. */
  12419. }
  12420. /* sscanf and the option splitting code ensure the following condition
  12421. */
  12422. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  12423. *ip_version = 0;
  12424. return 0;
  12425. }
  12426. ch = vec->ptr[len]; /* Next character after the port number */
  12427. so->is_ssl = (ch == 's');
  12428. so->ssl_redir = (ch == 'r');
  12429. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  12430. if (is_valid_port(port)
  12431. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12432. return 1;
  12433. }
  12434. /* Reset ip_version to 0 if there is an error */
  12435. *ip_version = 0;
  12436. return 0;
  12437. }
  12438. /* Is there any SSL port in use? */
  12439. static int
  12440. is_ssl_port_used(const char *ports)
  12441. {
  12442. if (ports) {
  12443. /* There are several different allowed syntax variants:
  12444. * - "80" for a single port using every network interface
  12445. * - "localhost:80" for a single port using only localhost
  12446. * - "80,localhost:8080" for two ports, one bound to localhost
  12447. * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound
  12448. * to IPv4 localhost, one to IPv6 localhost
  12449. * - "+80" use port 80 for IPv4 and IPv6
  12450. * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS),
  12451. * for both: IPv4 and IPv4
  12452. * - "+443s,localhost:8080" port 443 (HTTPS) for every interface,
  12453. * additionally port 8080 bound to localhost connections
  12454. *
  12455. * If we just look for 's' anywhere in the string, "localhost:80"
  12456. * will be detected as SSL (false positive).
  12457. * Looking for 's' after a digit may cause false positives in
  12458. * "my24service:8080".
  12459. * Looking from 's' backward if there are only ':' and numbers
  12460. * before will not work for "24service:8080" (non SSL, port 8080)
  12461. * or "24s" (SSL, port 24).
  12462. *
  12463. * Remark: Initially hostnames were not allowed to start with a
  12464. * digit (according to RFC 952), this was allowed later (RFC 1123,
  12465. * Section 2.1).
  12466. *
  12467. * To get this correct, the entire string must be parsed as a whole,
  12468. * reading it as a list element for element and parsing with an
  12469. * algorithm equivalent to parse_port_string.
  12470. *
  12471. * In fact, we use local interface names here, not arbitrary hostnames,
  12472. * so in most cases the only name will be "localhost".
  12473. *
  12474. * So, for now, we use this simple algorithm, that may still return
  12475. * a false positive in bizarre cases.
  12476. */
  12477. int i;
  12478. int portslen = (int)strlen(ports);
  12479. char prevIsNumber = 0;
  12480. for (i = 0; i < portslen; i++) {
  12481. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12482. return 1;
  12483. }
  12484. if (ports[i] >= '0' && ports[i] <= '9') {
  12485. prevIsNumber = 1;
  12486. } else {
  12487. prevIsNumber = 0;
  12488. }
  12489. }
  12490. }
  12491. return 0;
  12492. }
  12493. static int
  12494. set_ports_option(struct mg_context *phys_ctx)
  12495. {
  12496. const char *list;
  12497. int on = 1;
  12498. #if defined(USE_IPV6)
  12499. int off = 0;
  12500. #endif
  12501. struct vec vec;
  12502. struct socket so, *ptr;
  12503. struct mg_pollfd *pfd;
  12504. union usa usa;
  12505. socklen_t len;
  12506. int ip_version;
  12507. int portsTotal = 0;
  12508. int portsOk = 0;
  12509. if (!phys_ctx) {
  12510. return 0;
  12511. }
  12512. memset(&so, 0, sizeof(so));
  12513. memset(&usa, 0, sizeof(usa));
  12514. len = sizeof(usa);
  12515. list = phys_ctx->dd.config[LISTENING_PORTS];
  12516. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12517. portsTotal++;
  12518. if (!parse_port_string(&vec, &so, &ip_version)) {
  12519. mg_cry_ctx_internal(
  12520. phys_ctx,
  12521. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12522. (int)vec.len,
  12523. vec.ptr,
  12524. portsTotal,
  12525. "[IP_ADDRESS:]PORT[s|r]");
  12526. continue;
  12527. }
  12528. #if !defined(NO_SSL)
  12529. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12530. mg_cry_ctx_internal(phys_ctx,
  12531. "Cannot add SSL socket (entry %i)",
  12532. portsTotal);
  12533. continue;
  12534. }
  12535. #endif
  12536. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12537. == INVALID_SOCKET) {
  12538. mg_cry_ctx_internal(phys_ctx,
  12539. "cannot create socket (entry %i)",
  12540. portsTotal);
  12541. continue;
  12542. }
  12543. #if defined(_WIN32)
  12544. /* Windows SO_REUSEADDR lets many procs binds to a
  12545. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12546. * if someone already has the socket -- DTL */
  12547. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12548. * Windows might need a few seconds before
  12549. * the same port can be used again in the
  12550. * same process, so a short Sleep may be
  12551. * required between mg_stop and mg_start.
  12552. */
  12553. if (setsockopt(so.sock,
  12554. SOL_SOCKET,
  12555. SO_EXCLUSIVEADDRUSE,
  12556. (SOCK_OPT_TYPE)&on,
  12557. sizeof(on))
  12558. != 0) {
  12559. /* Set reuse option, but don't abort on errors. */
  12560. mg_cry_ctx_internal(
  12561. phys_ctx,
  12562. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12563. portsTotal);
  12564. }
  12565. #else
  12566. if (setsockopt(so.sock,
  12567. SOL_SOCKET,
  12568. SO_REUSEADDR,
  12569. (SOCK_OPT_TYPE)&on,
  12570. sizeof(on))
  12571. != 0) {
  12572. /* Set reuse option, but don't abort on errors. */
  12573. mg_cry_ctx_internal(
  12574. phys_ctx,
  12575. "cannot set socket option SO_REUSEADDR (entry %i)",
  12576. portsTotal);
  12577. }
  12578. #endif
  12579. if (ip_version > 4) {
  12580. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12581. #if defined(USE_IPV6)
  12582. if (ip_version > 6) {
  12583. if (so.lsa.sa.sa_family == AF_INET6
  12584. && setsockopt(so.sock,
  12585. IPPROTO_IPV6,
  12586. IPV6_V6ONLY,
  12587. (void *)&off,
  12588. sizeof(off))
  12589. != 0) {
  12590. /* Set IPv6 only option, but don't abort on errors. */
  12591. mg_cry_ctx_internal(
  12592. phys_ctx,
  12593. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12594. portsTotal);
  12595. }
  12596. } else {
  12597. if (so.lsa.sa.sa_family == AF_INET6
  12598. && setsockopt(so.sock,
  12599. IPPROTO_IPV6,
  12600. IPV6_V6ONLY,
  12601. (void *)&on,
  12602. sizeof(on))
  12603. != 0) {
  12604. /* Set IPv6 only option, but don't abort on errors. */
  12605. mg_cry_ctx_internal(
  12606. phys_ctx,
  12607. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12608. portsTotal);
  12609. }
  12610. }
  12611. #else
  12612. mg_cry_ctx_internal(phys_ctx, "%s", "IPv6 not available");
  12613. closesocket(so.sock);
  12614. so.sock = INVALID_SOCKET;
  12615. continue;
  12616. #endif
  12617. }
  12618. if (so.lsa.sa.sa_family == AF_INET) {
  12619. len = sizeof(so.lsa.sin);
  12620. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12621. mg_cry_ctx_internal(phys_ctx,
  12622. "cannot bind to %.*s: %d (%s)",
  12623. (int)vec.len,
  12624. vec.ptr,
  12625. (int)ERRNO,
  12626. strerror(errno));
  12627. closesocket(so.sock);
  12628. so.sock = INVALID_SOCKET;
  12629. continue;
  12630. }
  12631. }
  12632. #if defined(USE_IPV6)
  12633. else if (so.lsa.sa.sa_family == AF_INET6) {
  12634. len = sizeof(so.lsa.sin6);
  12635. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12636. mg_cry_ctx_internal(phys_ctx,
  12637. "cannot bind to IPv6 %.*s: %d (%s)",
  12638. (int)vec.len,
  12639. vec.ptr,
  12640. (int)ERRNO,
  12641. strerror(errno));
  12642. closesocket(so.sock);
  12643. so.sock = INVALID_SOCKET;
  12644. continue;
  12645. }
  12646. }
  12647. #endif
  12648. else {
  12649. mg_cry_ctx_internal(
  12650. phys_ctx,
  12651. "cannot bind: address family not supported (entry %i)",
  12652. portsTotal);
  12653. closesocket(so.sock);
  12654. so.sock = INVALID_SOCKET;
  12655. continue;
  12656. }
  12657. if (listen(so.sock, SOMAXCONN) != 0) {
  12658. mg_cry_ctx_internal(phys_ctx,
  12659. "cannot listen to %.*s: %d (%s)",
  12660. (int)vec.len,
  12661. vec.ptr,
  12662. (int)ERRNO,
  12663. strerror(errno));
  12664. closesocket(so.sock);
  12665. so.sock = INVALID_SOCKET;
  12666. continue;
  12667. }
  12668. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12669. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12670. int err = (int)ERRNO;
  12671. mg_cry_ctx_internal(phys_ctx,
  12672. "call to getsockname failed %.*s: %d (%s)",
  12673. (int)vec.len,
  12674. vec.ptr,
  12675. err,
  12676. strerror(errno));
  12677. closesocket(so.sock);
  12678. so.sock = INVALID_SOCKET;
  12679. continue;
  12680. }
  12681. /* Update lsa port in case of random free ports */
  12682. #if defined(USE_IPV6)
  12683. if (so.lsa.sa.sa_family == AF_INET6) {
  12684. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12685. } else
  12686. #endif
  12687. {
  12688. so.lsa.sin.sin_port = usa.sin.sin_port;
  12689. }
  12690. if ((ptr = (struct socket *)
  12691. mg_realloc_ctx(phys_ctx->listening_sockets,
  12692. (phys_ctx->num_listening_sockets + 1)
  12693. * sizeof(phys_ctx->listening_sockets[0]),
  12694. phys_ctx))
  12695. == NULL) {
  12696. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12697. closesocket(so.sock);
  12698. so.sock = INVALID_SOCKET;
  12699. continue;
  12700. }
  12701. if ((pfd = (struct mg_pollfd *)
  12702. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12703. (phys_ctx->num_listening_sockets + 1)
  12704. * sizeof(phys_ctx->listening_socket_fds[0]),
  12705. phys_ctx))
  12706. == NULL) {
  12707. mg_cry_ctx_internal(phys_ctx, "%s", "Out of memory");
  12708. closesocket(so.sock);
  12709. so.sock = INVALID_SOCKET;
  12710. mg_free(ptr);
  12711. continue;
  12712. }
  12713. set_close_on_exec(so.sock, NULL, phys_ctx);
  12714. phys_ctx->listening_sockets = ptr;
  12715. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12716. phys_ctx->listening_socket_fds = pfd;
  12717. phys_ctx->num_listening_sockets++;
  12718. portsOk++;
  12719. }
  12720. if (portsOk != portsTotal) {
  12721. close_all_listening_sockets(phys_ctx);
  12722. portsOk = 0;
  12723. }
  12724. return portsOk;
  12725. }
  12726. static const char *
  12727. header_val(const struct mg_connection *conn, const char *header)
  12728. {
  12729. const char *header_value;
  12730. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12731. return "-";
  12732. } else {
  12733. return header_value;
  12734. }
  12735. }
  12736. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12737. static void log_access(const struct mg_connection *conn);
  12738. #include "external_log_access.inl"
  12739. #elif !defined(NO_FILESYSTEMS)
  12740. static void
  12741. log_access(const struct mg_connection *conn)
  12742. {
  12743. const struct mg_request_info *ri;
  12744. struct mg_file fi;
  12745. char date[64], src_addr[IP_ADDR_STR_LEN];
  12746. struct tm *tm;
  12747. const char *referer;
  12748. const char *user_agent;
  12749. char buf[4096];
  12750. if (!conn || !conn->dom_ctx) {
  12751. return;
  12752. }
  12753. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12754. if (mg_fopen(conn,
  12755. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12756. MG_FOPEN_MODE_APPEND,
  12757. &fi)
  12758. == 0) {
  12759. fi.access.fp = NULL;
  12760. }
  12761. } else {
  12762. fi.access.fp = NULL;
  12763. }
  12764. /* Log is written to a file and/or a callback. If both are not set,
  12765. * executing the rest of the function is pointless. */
  12766. if ((fi.access.fp == NULL)
  12767. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12768. return;
  12769. }
  12770. tm = localtime(&conn->conn_birth_time);
  12771. if (tm != NULL) {
  12772. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12773. } else {
  12774. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12775. date[sizeof(date) - 1] = '\0';
  12776. }
  12777. ri = &conn->request_info;
  12778. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12779. referer = header_val(conn, "Referer");
  12780. user_agent = header_val(conn, "User-Agent");
  12781. mg_snprintf(conn,
  12782. NULL, /* Ignore truncation in access log */
  12783. buf,
  12784. sizeof(buf),
  12785. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12786. src_addr,
  12787. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12788. date,
  12789. ri->request_method ? ri->request_method : "-",
  12790. ri->request_uri ? ri->request_uri : "-",
  12791. ri->query_string ? "?" : "",
  12792. ri->query_string ? ri->query_string : "",
  12793. ri->http_version,
  12794. conn->status_code,
  12795. conn->num_bytes_sent,
  12796. referer,
  12797. user_agent);
  12798. if (conn->phys_ctx->callbacks.log_access) {
  12799. conn->phys_ctx->callbacks.log_access(conn, buf);
  12800. }
  12801. if (fi.access.fp) {
  12802. int ok = 1;
  12803. flockfile(fi.access.fp);
  12804. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12805. ok = 0;
  12806. }
  12807. if (fflush(fi.access.fp) != 0) {
  12808. ok = 0;
  12809. }
  12810. funlockfile(fi.access.fp);
  12811. if (mg_fclose(&fi.access) != 0) {
  12812. ok = 0;
  12813. }
  12814. if (!ok) {
  12815. mg_cry_internal(conn,
  12816. "Error writing log file %s",
  12817. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12818. }
  12819. }
  12820. }
  12821. #else
  12822. #error Must either enable filesystems or provide a custom log_access implementation
  12823. #endif /* Externally provided function */
  12824. /* Verify given socket address against the ACL.
  12825. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12826. */
  12827. static int
  12828. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12829. {
  12830. int allowed, flag;
  12831. uint32_t net, mask;
  12832. struct vec vec;
  12833. if (phys_ctx) {
  12834. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12835. /* If any ACL is set, deny by default */
  12836. allowed = (list == NULL) ? '+' : '-';
  12837. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12838. flag = vec.ptr[0];
  12839. if ((flag != '+' && flag != '-')
  12840. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12841. mg_cry_ctx_internal(phys_ctx,
  12842. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12843. __func__);
  12844. return -1;
  12845. }
  12846. if (net == (remote_ip & mask)) {
  12847. allowed = flag;
  12848. }
  12849. }
  12850. return allowed == '+';
  12851. }
  12852. return -1;
  12853. }
  12854. #if !defined(_WIN32)
  12855. static int
  12856. set_uid_option(struct mg_context *phys_ctx)
  12857. {
  12858. int success = 0;
  12859. if (phys_ctx) {
  12860. /* We are currently running as curr_uid. */
  12861. const uid_t curr_uid = getuid();
  12862. /* If set, we want to run as run_as_user. */
  12863. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12864. const struct passwd *to_pw = NULL;
  12865. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12866. /* run_as_user does not exist on the system. We can't proceed
  12867. * further. */
  12868. mg_cry_ctx_internal(phys_ctx,
  12869. "%s: unknown user [%s]",
  12870. __func__,
  12871. run_as_user);
  12872. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12873. /* There was either no request to change user, or we're already
  12874. * running as run_as_user. Nothing else to do.
  12875. */
  12876. success = 1;
  12877. } else {
  12878. /* Valid change request. */
  12879. if (setgid(to_pw->pw_gid) == -1) {
  12880. mg_cry_ctx_internal(phys_ctx,
  12881. "%s: setgid(%s): %s",
  12882. __func__,
  12883. run_as_user,
  12884. strerror(errno));
  12885. } else if (setgroups(0, NULL) == -1) {
  12886. mg_cry_ctx_internal(phys_ctx,
  12887. "%s: setgroups(): %s",
  12888. __func__,
  12889. strerror(errno));
  12890. } else if (setuid(to_pw->pw_uid) == -1) {
  12891. mg_cry_ctx_internal(phys_ctx,
  12892. "%s: setuid(%s): %s",
  12893. __func__,
  12894. run_as_user,
  12895. strerror(errno));
  12896. } else {
  12897. success = 1;
  12898. }
  12899. }
  12900. }
  12901. return success;
  12902. }
  12903. #endif /* !_WIN32 */
  12904. static void
  12905. tls_dtor(void *key)
  12906. {
  12907. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12908. /* key == pthread_getspecific(sTlsKey); */
  12909. if (tls) {
  12910. if (tls->is_master == 2) {
  12911. tls->is_master = -3; /* Mark memory as dead */
  12912. mg_free(tls);
  12913. }
  12914. }
  12915. pthread_setspecific(sTlsKey, NULL);
  12916. }
  12917. #if !defined(NO_SSL)
  12918. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12919. struct mg_domain_context *dom_ctx,
  12920. const char *pem,
  12921. const char *chain);
  12922. static const char *ssl_error(void);
  12923. static int
  12924. refresh_trust(struct mg_connection *conn)
  12925. {
  12926. static int reload_lock = 0;
  12927. static long int data_check = 0;
  12928. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12929. struct stat cert_buf;
  12930. long int t;
  12931. const char *pem;
  12932. const char *chain;
  12933. int should_verify_peer;
  12934. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12935. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12936. * refresh_trust still can not work. */
  12937. return 0;
  12938. }
  12939. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12940. if (chain == NULL) {
  12941. /* pem is not NULL here */
  12942. chain = pem;
  12943. }
  12944. if (*chain == 0) {
  12945. chain = NULL;
  12946. }
  12947. t = data_check;
  12948. if (stat(pem, &cert_buf) != -1) {
  12949. t = (long int)cert_buf.st_mtime;
  12950. }
  12951. if (data_check != t) {
  12952. data_check = t;
  12953. should_verify_peer = 0;
  12954. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12955. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12956. == 0) {
  12957. should_verify_peer = 1;
  12958. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12959. "optional")
  12960. == 0) {
  12961. should_verify_peer = 1;
  12962. }
  12963. }
  12964. if (should_verify_peer) {
  12965. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12966. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12967. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12968. ca_file,
  12969. ca_path)
  12970. != 1) {
  12971. mg_cry_ctx_internal(
  12972. conn->phys_ctx,
  12973. "SSL_CTX_load_verify_locations error: %s "
  12974. "ssl_verify_peer requires setting "
  12975. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12976. "present in "
  12977. "the .conf file?",
  12978. ssl_error());
  12979. return 0;
  12980. }
  12981. }
  12982. if (1 == mg_atomic_inc(p_reload_lock)) {
  12983. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12984. == 0) {
  12985. return 0;
  12986. }
  12987. *p_reload_lock = 0;
  12988. }
  12989. }
  12990. /* lock while cert is reloading */
  12991. while (*p_reload_lock) {
  12992. sleep(1);
  12993. }
  12994. return 1;
  12995. }
  12996. #if defined(OPENSSL_API_1_1)
  12997. #else
  12998. static pthread_mutex_t *ssl_mutexes;
  12999. #endif /* OPENSSL_API_1_1 */
  13000. static int
  13001. sslize(struct mg_connection *conn,
  13002. SSL_CTX *s,
  13003. int (*func)(SSL *),
  13004. volatile int *stop_server,
  13005. const struct mg_client_options *client_options)
  13006. {
  13007. int ret, err;
  13008. int short_trust;
  13009. unsigned timeout = 1024;
  13010. unsigned i;
  13011. if (!conn) {
  13012. return 0;
  13013. }
  13014. short_trust =
  13015. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  13016. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  13017. if (short_trust) {
  13018. int trust_ret = refresh_trust(conn);
  13019. if (!trust_ret) {
  13020. return trust_ret;
  13021. }
  13022. }
  13023. conn->ssl = SSL_new(s);
  13024. if (conn->ssl == NULL) {
  13025. return 0;
  13026. }
  13027. SSL_set_app_data(conn->ssl, (char *)conn);
  13028. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  13029. if (ret != 1) {
  13030. err = SSL_get_error(conn->ssl, ret);
  13031. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  13032. SSL_free(conn->ssl);
  13033. conn->ssl = NULL;
  13034. OPENSSL_REMOVE_THREAD_STATE();
  13035. return 0;
  13036. }
  13037. if (client_options) {
  13038. if (client_options->host_name) {
  13039. SSL_set_tlsext_host_name(conn->ssl, client_options->host_name);
  13040. }
  13041. }
  13042. /* Reuse the request timeout for the SSL_Accept/SSL_connect timeout */
  13043. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  13044. /* NOTE: The loop below acts as a back-off, so we can end
  13045. * up sleeping for more (or less) than the REQUEST_TIMEOUT. */
  13046. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]);
  13047. }
  13048. /* SSL functions may fail and require to be called again:
  13049. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  13050. * Here "func" could be SSL_connect or SSL_accept. */
  13051. for (i = 0; i <= timeout; i += 50) {
  13052. ret = func(conn->ssl);
  13053. if (ret != 1) {
  13054. err = SSL_get_error(conn->ssl, ret);
  13055. if ((err == SSL_ERROR_WANT_CONNECT)
  13056. || (err == SSL_ERROR_WANT_ACCEPT)
  13057. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  13058. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  13059. if (*stop_server) {
  13060. /* Don't wait if the server is going to be stopped. */
  13061. break;
  13062. }
  13063. if (err == SSL_ERROR_WANT_X509_LOOKUP) {
  13064. /* Simply retry the function call. */
  13065. mg_sleep(50);
  13066. } else {
  13067. /* Need to retry the function call "later".
  13068. * See https://linux.die.net/man/3/ssl_get_error
  13069. * This is typical for non-blocking sockets. */
  13070. struct mg_pollfd pfd;
  13071. pfd.fd = conn->client.sock;
  13072. pfd.events = ((err == SSL_ERROR_WANT_CONNECT)
  13073. || (err == SSL_ERROR_WANT_WRITE))
  13074. ? POLLOUT
  13075. : POLLIN;
  13076. mg_poll(&pfd, 1, 50, stop_server);
  13077. }
  13078. } else if (err == SSL_ERROR_SYSCALL) {
  13079. /* This is an IO error. Look at errno. */
  13080. err = errno;
  13081. mg_cry_internal(conn, "SSL syscall error %i", err);
  13082. break;
  13083. } else {
  13084. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  13085. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  13086. break;
  13087. }
  13088. ERR_clear_error();
  13089. } else {
  13090. /* success */
  13091. break;
  13092. }
  13093. }
  13094. if (ret != 1) {
  13095. SSL_free(conn->ssl);
  13096. conn->ssl = NULL;
  13097. OPENSSL_REMOVE_THREAD_STATE();
  13098. return 0;
  13099. }
  13100. return 1;
  13101. }
  13102. /* Return OpenSSL error message (from CRYPTO lib) */
  13103. static const char *
  13104. ssl_error(void)
  13105. {
  13106. unsigned long err;
  13107. err = ERR_get_error();
  13108. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  13109. }
  13110. static int
  13111. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  13112. {
  13113. int i;
  13114. const char hexdigit[] = "0123456789abcdef";
  13115. if ((memlen <= 0) || (buflen <= 0)) {
  13116. return 0;
  13117. }
  13118. if (buflen < (3 * memlen)) {
  13119. return 0;
  13120. }
  13121. for (i = 0; i < memlen; i++) {
  13122. if (i > 0) {
  13123. buf[3 * i - 1] = ' ';
  13124. }
  13125. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  13126. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  13127. }
  13128. buf[3 * memlen - 1] = 0;
  13129. return 1;
  13130. }
  13131. static void
  13132. ssl_get_client_cert_info(struct mg_connection *conn)
  13133. {
  13134. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  13135. if (cert) {
  13136. char str_subject[1024];
  13137. char str_issuer[1024];
  13138. char str_finger[1024];
  13139. unsigned char buf[256];
  13140. char *str_serial = NULL;
  13141. unsigned int ulen;
  13142. int ilen;
  13143. unsigned char *tmp_buf;
  13144. unsigned char *tmp_p;
  13145. /* Handle to algorithm used for fingerprint */
  13146. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  13147. /* Get Subject and issuer */
  13148. X509_NAME *subj = X509_get_subject_name(cert);
  13149. X509_NAME *iss = X509_get_issuer_name(cert);
  13150. /* Get serial number */
  13151. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  13152. /* Translate serial number to a hex string */
  13153. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  13154. str_serial = BN_bn2hex(serial_bn);
  13155. BN_free(serial_bn);
  13156. /* Translate subject and issuer to a string */
  13157. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  13158. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  13159. /* Calculate SHA1 fingerprint and store as a hex string */
  13160. ulen = 0;
  13161. /* ASN1_digest is deprecated. Do the calculation manually,
  13162. * using EVP_Digest. */
  13163. ilen = i2d_X509(cert, NULL);
  13164. tmp_buf = (ilen > 0)
  13165. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  13166. conn->phys_ctx)
  13167. : NULL;
  13168. if (tmp_buf) {
  13169. tmp_p = tmp_buf;
  13170. (void)i2d_X509(cert, &tmp_p);
  13171. if (!EVP_Digest(
  13172. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  13173. ulen = 0;
  13174. }
  13175. mg_free(tmp_buf);
  13176. }
  13177. if (!hexdump2string(
  13178. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  13179. *str_finger = 0;
  13180. }
  13181. conn->request_info.client_cert = (struct mg_client_cert *)
  13182. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  13183. if (conn->request_info.client_cert) {
  13184. conn->request_info.client_cert->peer_cert = (void *)cert;
  13185. conn->request_info.client_cert->subject =
  13186. mg_strdup_ctx(str_subject, conn->phys_ctx);
  13187. conn->request_info.client_cert->issuer =
  13188. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  13189. conn->request_info.client_cert->serial =
  13190. mg_strdup_ctx(str_serial, conn->phys_ctx);
  13191. conn->request_info.client_cert->finger =
  13192. mg_strdup_ctx(str_finger, conn->phys_ctx);
  13193. } else {
  13194. mg_cry_internal(conn,
  13195. "%s",
  13196. "Out of memory: Cannot allocate memory for client "
  13197. "certificate");
  13198. }
  13199. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  13200. * see https://linux.die.net/man/3/bn_bn2hex */
  13201. OPENSSL_free(str_serial);
  13202. }
  13203. }
  13204. #if defined(OPENSSL_API_1_1)
  13205. #else
  13206. static void
  13207. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  13208. {
  13209. (void)line;
  13210. (void)file;
  13211. if (mode & 1) {
  13212. /* 1 is CRYPTO_LOCK */
  13213. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  13214. } else {
  13215. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  13216. }
  13217. }
  13218. #endif /* OPENSSL_API_1_1 */
  13219. #if !defined(NO_SSL_DL)
  13220. static void *
  13221. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  13222. {
  13223. union {
  13224. void *p;
  13225. void (*fp)(void);
  13226. } u;
  13227. void *dll_handle;
  13228. struct ssl_func *fp;
  13229. int ok;
  13230. int truncated = 0;
  13231. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  13232. mg_snprintf(NULL,
  13233. NULL, /* No truncation check for ebuf */
  13234. ebuf,
  13235. ebuf_len,
  13236. "%s: cannot load %s",
  13237. __func__,
  13238. dll_name);
  13239. return NULL;
  13240. }
  13241. ok = 1;
  13242. for (fp = sw; fp->name != NULL; fp++) {
  13243. #if defined(_WIN32)
  13244. /* GetProcAddress() returns pointer to function */
  13245. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  13246. #else
  13247. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  13248. * pointers to function pointers. We need to use a union to make a
  13249. * cast. */
  13250. u.p = dlsym(dll_handle, fp->name);
  13251. #endif /* _WIN32 */
  13252. if (u.fp == NULL) {
  13253. if (ok) {
  13254. mg_snprintf(NULL,
  13255. &truncated,
  13256. ebuf,
  13257. ebuf_len,
  13258. "%s: %s: cannot find %s",
  13259. __func__,
  13260. dll_name,
  13261. fp->name);
  13262. ok = 0;
  13263. } else {
  13264. size_t cur_len = strlen(ebuf);
  13265. if (!truncated) {
  13266. mg_snprintf(NULL,
  13267. &truncated,
  13268. ebuf + cur_len,
  13269. ebuf_len - cur_len - 3,
  13270. ", %s",
  13271. fp->name);
  13272. if (truncated) {
  13273. /* If truncated, add "..." */
  13274. strcat(ebuf, "...");
  13275. }
  13276. }
  13277. }
  13278. /* Debug:
  13279. * printf("Missing function: %s\n", fp->name); */
  13280. } else {
  13281. fp->ptr = u.fp;
  13282. }
  13283. }
  13284. if (!ok) {
  13285. (void)dlclose(dll_handle);
  13286. return NULL;
  13287. }
  13288. return dll_handle;
  13289. }
  13290. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  13291. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  13292. #endif /* NO_SSL_DL */
  13293. #if defined(SSL_ALREADY_INITIALIZED)
  13294. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  13295. #else
  13296. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  13297. #endif
  13298. static int
  13299. initialize_ssl(char *ebuf, size_t ebuf_len)
  13300. {
  13301. #if defined(OPENSSL_API_1_1)
  13302. if (ebuf_len > 0) {
  13303. ebuf[0] = 0;
  13304. }
  13305. #if !defined(NO_SSL_DL)
  13306. if (!cryptolib_dll_handle) {
  13307. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13308. if (!cryptolib_dll_handle) {
  13309. mg_snprintf(NULL,
  13310. NULL, /* No truncation check for ebuf */
  13311. ebuf,
  13312. ebuf_len,
  13313. "%s: error loading library %s",
  13314. __func__,
  13315. CRYPTO_LIB);
  13316. DEBUG_TRACE("%s", ebuf);
  13317. return 0;
  13318. }
  13319. }
  13320. #endif /* NO_SSL_DL */
  13321. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13322. return 1;
  13323. }
  13324. #else /* not OPENSSL_API_1_1 */
  13325. int i, num_locks;
  13326. size_t size;
  13327. if (ebuf_len > 0) {
  13328. ebuf[0] = 0;
  13329. }
  13330. #if !defined(NO_SSL_DL)
  13331. if (!cryptolib_dll_handle) {
  13332. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  13333. if (!cryptolib_dll_handle) {
  13334. mg_snprintf(NULL,
  13335. NULL, /* No truncation check for ebuf */
  13336. ebuf,
  13337. ebuf_len,
  13338. "%s: error loading library %s",
  13339. __func__,
  13340. CRYPTO_LIB);
  13341. DEBUG_TRACE("%s", ebuf);
  13342. return 0;
  13343. }
  13344. }
  13345. #endif /* NO_SSL_DL */
  13346. if (mg_atomic_inc(&cryptolib_users) > 1) {
  13347. return 1;
  13348. }
  13349. /* Initialize locking callbacks, needed for thread safety.
  13350. * http://www.openssl.org/support/faq.html#PROG1
  13351. */
  13352. num_locks = CRYPTO_num_locks();
  13353. if (num_locks < 0) {
  13354. num_locks = 0;
  13355. }
  13356. size = sizeof(pthread_mutex_t) * ((size_t)(num_locks));
  13357. /* allocate mutex array, if required */
  13358. if (num_locks == 0) {
  13359. /* No mutex array required */
  13360. ssl_mutexes = NULL;
  13361. } else {
  13362. /* Mutex array required - allocate it */
  13363. ssl_mutexes = (pthread_mutex_t *)mg_malloc(size);
  13364. /* Check OOM */
  13365. if (ssl_mutexes == NULL) {
  13366. mg_snprintf(NULL,
  13367. NULL, /* No truncation check for ebuf */
  13368. ebuf,
  13369. ebuf_len,
  13370. "%s: cannot allocate mutexes: %s",
  13371. __func__,
  13372. ssl_error());
  13373. DEBUG_TRACE("%s", ebuf);
  13374. return 0;
  13375. }
  13376. /* initialize mutex array */
  13377. for (i = 0; i < num_locks; i++) {
  13378. if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) {
  13379. mg_snprintf(NULL,
  13380. NULL, /* No truncation check for ebuf */
  13381. ebuf,
  13382. ebuf_len,
  13383. "%s: error initializing mutex %i of %i",
  13384. __func__,
  13385. i,
  13386. num_locks);
  13387. DEBUG_TRACE("%s", ebuf);
  13388. mg_free(ssl_mutexes);
  13389. return 0;
  13390. }
  13391. }
  13392. }
  13393. CRYPTO_set_locking_callback(&ssl_locking_callback);
  13394. CRYPTO_set_id_callback(&mg_current_thread_id);
  13395. #endif /* OPENSSL_API_1_1 */
  13396. #if !defined(NO_SSL_DL)
  13397. if (!ssllib_dll_handle) {
  13398. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  13399. if (!ssllib_dll_handle) {
  13400. #if !defined(OPENSSL_API_1_1)
  13401. mg_free(ssl_mutexes);
  13402. #endif
  13403. DEBUG_TRACE("%s", ebuf);
  13404. return 0;
  13405. }
  13406. }
  13407. #endif /* NO_SSL_DL */
  13408. #if defined(OPENSSL_API_1_1)
  13409. /* Initialize SSL library */
  13410. OPENSSL_init_ssl(0, NULL);
  13411. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  13412. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  13413. NULL);
  13414. #else
  13415. /* Initialize SSL library */
  13416. SSL_library_init();
  13417. SSL_load_error_strings();
  13418. #endif
  13419. return 1;
  13420. }
  13421. static int
  13422. ssl_use_pem_file(struct mg_context *phys_ctx,
  13423. struct mg_domain_context *dom_ctx,
  13424. const char *pem,
  13425. const char *chain)
  13426. {
  13427. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13428. mg_cry_ctx_internal(phys_ctx,
  13429. "%s: cannot open certificate file %s: %s",
  13430. __func__,
  13431. pem,
  13432. ssl_error());
  13433. return 0;
  13434. }
  13435. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  13436. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  13437. mg_cry_ctx_internal(phys_ctx,
  13438. "%s: cannot open private key file %s: %s",
  13439. __func__,
  13440. pem,
  13441. ssl_error());
  13442. return 0;
  13443. }
  13444. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  13445. mg_cry_ctx_internal(phys_ctx,
  13446. "%s: certificate and private key do not match: %s",
  13447. __func__,
  13448. pem);
  13449. return 0;
  13450. }
  13451. /* In contrast to OpenSSL, wolfSSL does not support certificate
  13452. * chain files that contain private keys and certificates in
  13453. * SSL_CTX_use_certificate_chain_file.
  13454. * The CivetWeb-Server used pem-Files that contained both information.
  13455. * In order to make wolfSSL work, it is split in two files.
  13456. * One file that contains key and certificate used by the server and
  13457. * an optional chain file for the ssl stack.
  13458. */
  13459. if (chain) {
  13460. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  13461. mg_cry_ctx_internal(phys_ctx,
  13462. "%s: cannot use certificate chain file %s: %s",
  13463. __func__,
  13464. chain,
  13465. ssl_error());
  13466. return 0;
  13467. }
  13468. }
  13469. return 1;
  13470. }
  13471. #if defined(OPENSSL_API_1_1)
  13472. static unsigned long
  13473. ssl_get_protocol(int version_id)
  13474. {
  13475. long unsigned ret = (long unsigned)SSL_OP_ALL;
  13476. if (version_id > 0)
  13477. ret |= SSL_OP_NO_SSLv2;
  13478. if (version_id > 1)
  13479. ret |= SSL_OP_NO_SSLv3;
  13480. if (version_id > 2)
  13481. ret |= SSL_OP_NO_TLSv1;
  13482. if (version_id > 3)
  13483. ret |= SSL_OP_NO_TLSv1_1;
  13484. if (version_id > 4)
  13485. ret |= SSL_OP_NO_TLSv1_2;
  13486. #if defined(SSL_OP_NO_TLSv1_3)
  13487. if (version_id > 5)
  13488. ret |= SSL_OP_NO_TLSv1_3;
  13489. #endif
  13490. return ret;
  13491. }
  13492. #else
  13493. static long
  13494. ssl_get_protocol(int version_id)
  13495. {
  13496. long ret = (long)SSL_OP_ALL;
  13497. if (version_id > 0)
  13498. ret |= SSL_OP_NO_SSLv2;
  13499. if (version_id > 1)
  13500. ret |= SSL_OP_NO_SSLv3;
  13501. if (version_id > 2)
  13502. ret |= SSL_OP_NO_TLSv1;
  13503. if (version_id > 3)
  13504. ret |= SSL_OP_NO_TLSv1_1;
  13505. if (version_id > 4)
  13506. ret |= SSL_OP_NO_TLSv1_2;
  13507. #if defined(SSL_OP_NO_TLSv1_3)
  13508. if (version_id > 5)
  13509. ret |= SSL_OP_NO_TLSv1_3;
  13510. #endif
  13511. return ret;
  13512. }
  13513. #endif /* OPENSSL_API_1_1 */
  13514. /* SSL callback documentation:
  13515. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  13516. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  13517. * https://linux.die.net/man/3/ssl_set_info_callback */
  13518. /* Note: There is no "const" for the first argument in the documentation
  13519. * examples, however some (maybe most, but not all) headers of OpenSSL versions
  13520. * / OpenSSL compatibility layers have it. Having a different definition will
  13521. * cause a warning in C and an error in C++. Use "const SSL *", while
  13522. * automatical conversion from "SSL *" works for all compilers, but not other
  13523. * way around */
  13524. static void
  13525. ssl_info_callback(const SSL *ssl, int what, int ret)
  13526. {
  13527. (void)ret;
  13528. if (what & SSL_CB_HANDSHAKE_START) {
  13529. SSL_get_app_data(ssl);
  13530. }
  13531. if (what & SSL_CB_HANDSHAKE_DONE) {
  13532. /* TODO: check for openSSL 1.1 */
  13533. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13534. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13535. }
  13536. }
  13537. static int
  13538. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13539. {
  13540. struct mg_context *ctx = (struct mg_context *)arg;
  13541. struct mg_domain_context *dom =
  13542. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13543. #if defined(GCC_DIAGNOSTIC)
  13544. #pragma GCC diagnostic push
  13545. #pragma GCC diagnostic ignored "-Wcast-align"
  13546. #endif /* defined(GCC_DIAGNOSTIC) */
  13547. /* We used an aligned pointer in SSL_set_app_data */
  13548. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13549. #if defined(GCC_DIAGNOSTIC)
  13550. #pragma GCC diagnostic pop
  13551. #endif /* defined(GCC_DIAGNOSTIC) */
  13552. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13553. (void)ad;
  13554. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13555. DEBUG_TRACE("%s", "internal error - assertion failed");
  13556. return SSL_TLSEXT_ERR_NOACK;
  13557. }
  13558. /* Old clients (Win XP) will not support SNI. Then, there
  13559. * is no server name available in the request - we can
  13560. * only work with the default certificate.
  13561. * Multiple HTTPS hosts on one IP+port are only possible
  13562. * with a certificate containing all alternative names.
  13563. */
  13564. if ((servername == NULL) || (*servername == 0)) {
  13565. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13566. conn->dom_ctx = &(ctx->dd);
  13567. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13568. return SSL_TLSEXT_ERR_NOACK;
  13569. }
  13570. DEBUG_TRACE("TLS connection to host %s", servername);
  13571. while (dom) {
  13572. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13573. /* Found matching domain */
  13574. DEBUG_TRACE("TLS domain %s found",
  13575. dom->config[AUTHENTICATION_DOMAIN]);
  13576. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13577. conn->dom_ctx = dom;
  13578. return SSL_TLSEXT_ERR_OK;
  13579. }
  13580. dom = dom->next;
  13581. }
  13582. /* Default domain */
  13583. DEBUG_TRACE("TLS default domain %s used",
  13584. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13585. conn->dom_ctx = &(ctx->dd);
  13586. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13587. return SSL_TLSEXT_ERR_OK;
  13588. }
  13589. /* Setup SSL CTX as required by CivetWeb */
  13590. static int
  13591. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13592. struct mg_domain_context *dom_ctx,
  13593. const char *pem,
  13594. const char *chain)
  13595. {
  13596. int callback_ret;
  13597. int should_verify_peer;
  13598. int peer_certificate_optional;
  13599. const char *ca_path;
  13600. const char *ca_file;
  13601. int use_default_verify_paths;
  13602. int verify_depth;
  13603. struct timespec now_mt;
  13604. md5_byte_t ssl_context_id[16];
  13605. md5_state_t md5state;
  13606. int protocol_ver;
  13607. #if defined(OPENSSL_API_1_1)
  13608. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13609. mg_cry_ctx_internal(phys_ctx,
  13610. "SSL_CTX_new (server) error: %s",
  13611. ssl_error());
  13612. return 0;
  13613. }
  13614. #else
  13615. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13616. mg_cry_ctx_internal(phys_ctx,
  13617. "SSL_CTX_new (server) error: %s",
  13618. ssl_error());
  13619. return 0;
  13620. }
  13621. #endif /* OPENSSL_API_1_1 */
  13622. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13623. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13624. | SSL_OP_NO_TLSv1_1);
  13625. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13626. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13627. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13628. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13629. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13630. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13631. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13632. #if defined(SSL_OP_NO_RENEGOTIATION)
  13633. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_RENEGOTIATION);
  13634. #endif
  13635. #if !defined(NO_SSL_DL)
  13636. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13637. #endif /* NO_SSL_DL */
  13638. /* In SSL documentation examples callback defined without const specifier
  13639. * 'void (*)(SSL *, int, int)' See:
  13640. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13641. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13642. * But in the source code const SSL is used:
  13643. * 'void (*)(const SSL *, int, int)' See:
  13644. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13645. * Problem about wrong documentation described, but not resolved:
  13646. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13647. * Wrong const cast ignored on C or can be suppressed by compiler flags.
  13648. * But when compiled with modern C++ compiler, correct const should be
  13649. * provided
  13650. */
  13651. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13652. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13653. ssl_servername_callback);
  13654. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13655. /* If a callback has been specified, call it. */
  13656. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13657. ? 0
  13658. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13659. phys_ctx->user_data));
  13660. /* If callback returns 0, civetweb sets up the SSL certificate.
  13661. * If it returns 1, civetweb assumes the calback already did this.
  13662. * If it returns -1, initializing ssl fails. */
  13663. if (callback_ret < 0) {
  13664. mg_cry_ctx_internal(phys_ctx,
  13665. "SSL callback returned error: %i",
  13666. callback_ret);
  13667. return 0;
  13668. }
  13669. if (callback_ret > 0) {
  13670. /* Callback did everything. */
  13671. return 1;
  13672. }
  13673. /* Use some combination of start time, domain and port as a SSL
  13674. * context ID. This should be unique on the current machine. */
  13675. md5_init(&md5state);
  13676. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13677. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13678. md5_append(&md5state,
  13679. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13680. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13681. md5_append(&md5state,
  13682. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13683. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13684. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13685. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13686. md5_finish(&md5state, ssl_context_id);
  13687. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13688. (unsigned char *)ssl_context_id,
  13689. sizeof(ssl_context_id));
  13690. if (pem != NULL) {
  13691. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13692. return 0;
  13693. }
  13694. }
  13695. /* Should we support client certificates? */
  13696. /* Default is "no". */
  13697. should_verify_peer = 0;
  13698. peer_certificate_optional = 0;
  13699. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13700. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13701. /* Yes, they are mandatory */
  13702. should_verify_peer = 1;
  13703. peer_certificate_optional = 0;
  13704. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13705. "optional")
  13706. == 0) {
  13707. /* Yes, they are optional */
  13708. should_verify_peer = 1;
  13709. peer_certificate_optional = 1;
  13710. }
  13711. }
  13712. use_default_verify_paths =
  13713. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13714. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13715. == 0);
  13716. if (should_verify_peer) {
  13717. ca_path = dom_ctx->config[SSL_CA_PATH];
  13718. ca_file = dom_ctx->config[SSL_CA_FILE];
  13719. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13720. != 1) {
  13721. mg_cry_ctx_internal(phys_ctx,
  13722. "SSL_CTX_load_verify_locations error: %s "
  13723. "ssl_verify_peer requires setting "
  13724. "either ssl_ca_path or ssl_ca_file. "
  13725. "Is any of them present in the "
  13726. ".conf file?",
  13727. ssl_error());
  13728. return 0;
  13729. }
  13730. if (peer_certificate_optional) {
  13731. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13732. } else {
  13733. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13734. SSL_VERIFY_PEER
  13735. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13736. NULL);
  13737. }
  13738. if (use_default_verify_paths
  13739. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13740. mg_cry_ctx_internal(phys_ctx,
  13741. "SSL_CTX_set_default_verify_paths error: %s",
  13742. ssl_error());
  13743. return 0;
  13744. }
  13745. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13746. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13747. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13748. }
  13749. }
  13750. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13751. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13752. dom_ctx->config[SSL_CIPHER_LIST])
  13753. != 1) {
  13754. mg_cry_ctx_internal(phys_ctx,
  13755. "SSL_CTX_set_cipher_list error: %s",
  13756. ssl_error());
  13757. }
  13758. }
  13759. return 1;
  13760. }
  13761. /* Check if SSL is required.
  13762. * If so, dynamically load SSL library
  13763. * and set up ctx->ssl_ctx pointer. */
  13764. static int
  13765. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13766. {
  13767. void *ssl_ctx = 0;
  13768. int callback_ret;
  13769. const char *pem;
  13770. const char *chain;
  13771. char ebuf[128];
  13772. if (!phys_ctx) {
  13773. return 0;
  13774. }
  13775. if (!dom_ctx) {
  13776. dom_ctx = &(phys_ctx->dd);
  13777. }
  13778. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13779. /* No SSL port is set. No need to setup SSL. */
  13780. return 1;
  13781. }
  13782. /* Check for external SSL_CTX */
  13783. callback_ret =
  13784. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13785. ? 0
  13786. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13787. phys_ctx->user_data));
  13788. if (callback_ret < 0) {
  13789. mg_cry_ctx_internal(phys_ctx,
  13790. "external_ssl_ctx callback returned error: %i",
  13791. callback_ret);
  13792. return 0;
  13793. } else if (callback_ret > 0) {
  13794. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13795. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13796. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  13797. return 0;
  13798. }
  13799. return 1;
  13800. }
  13801. /* else: external_ssl_ctx does not exist or returns 0,
  13802. * CivetWeb should continue initializing SSL */
  13803. /* If PEM file is not specified and the init_ssl callback
  13804. * is not specified, setup will fail. */
  13805. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13806. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13807. /* No certificate and no callback:
  13808. * Essential data to set up TLS is missing.
  13809. */
  13810. mg_cry_ctx_internal(phys_ctx,
  13811. "Initializing SSL failed: -%s is not set",
  13812. config_options[SSL_CERTIFICATE].name);
  13813. return 0;
  13814. }
  13815. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13816. if (chain == NULL) {
  13817. chain = pem;
  13818. }
  13819. if ((chain != NULL) && (*chain == 0)) {
  13820. chain = NULL;
  13821. }
  13822. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13823. mg_cry_ctx_internal(phys_ctx, "%s", ebuf);
  13824. return 0;
  13825. }
  13826. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13827. }
  13828. static void
  13829. uninitialize_ssl(void)
  13830. {
  13831. #if defined(OPENSSL_API_1_1)
  13832. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13833. /* Shutdown according to
  13834. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13835. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13836. */
  13837. CONF_modules_unload(1);
  13838. #else
  13839. int i;
  13840. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13841. /* Shutdown according to
  13842. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13843. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13844. */
  13845. CRYPTO_set_locking_callback(NULL);
  13846. CRYPTO_set_id_callback(NULL);
  13847. ENGINE_cleanup();
  13848. CONF_modules_unload(1);
  13849. ERR_free_strings();
  13850. EVP_cleanup();
  13851. CRYPTO_cleanup_all_ex_data();
  13852. OPENSSL_REMOVE_THREAD_STATE();
  13853. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13854. pthread_mutex_destroy(&ssl_mutexes[i]);
  13855. }
  13856. mg_free(ssl_mutexes);
  13857. ssl_mutexes = NULL;
  13858. #endif /* OPENSSL_API_1_1 */
  13859. }
  13860. }
  13861. #endif /* !NO_SSL */
  13862. #if !defined(NO_FILESYSTEMS)
  13863. static int
  13864. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13865. {
  13866. if (phys_ctx) {
  13867. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13868. const char *path;
  13869. struct mg_connection fc;
  13870. if (!dom_ctx) {
  13871. dom_ctx = &(phys_ctx->dd);
  13872. }
  13873. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13874. if ((path != NULL)
  13875. && !mg_stat(fake_connection(&fc, phys_ctx), path, &file.stat)) {
  13876. mg_cry_ctx_internal(phys_ctx,
  13877. "Cannot open %s: %s",
  13878. path,
  13879. strerror(ERRNO));
  13880. return 0;
  13881. }
  13882. return 1;
  13883. }
  13884. return 0;
  13885. }
  13886. #endif /* NO_FILESYSTEMS */
  13887. static int
  13888. set_acl_option(struct mg_context *phys_ctx)
  13889. {
  13890. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13891. }
  13892. static void
  13893. reset_per_request_attributes(struct mg_connection *conn)
  13894. {
  13895. if (!conn) {
  13896. return;
  13897. }
  13898. conn->connection_type =
  13899. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13900. conn->num_bytes_sent = conn->consumed_content = 0;
  13901. conn->path_info = NULL;
  13902. conn->status_code = -1;
  13903. conn->content_len = -1;
  13904. conn->is_chunked = 0;
  13905. conn->must_close = 0;
  13906. conn->request_len = 0;
  13907. conn->throttle = 0;
  13908. conn->accept_gzip = 0;
  13909. conn->response_info.content_length = conn->request_info.content_length = -1;
  13910. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13911. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13912. conn->response_info.status_text = NULL;
  13913. conn->response_info.status_code = 0;
  13914. conn->request_info.remote_user = NULL;
  13915. conn->request_info.request_method = NULL;
  13916. conn->request_info.request_uri = NULL;
  13917. conn->request_info.local_uri = NULL;
  13918. #if defined(MG_LEGACY_INTERFACE)
  13919. /* Legacy before split into local_uri and request_uri */
  13920. conn->request_info.uri = NULL;
  13921. #endif
  13922. }
  13923. static int
  13924. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13925. {
  13926. if (setsockopt(sock,
  13927. IPPROTO_TCP,
  13928. TCP_NODELAY,
  13929. (SOCK_OPT_TYPE)&nodelay_on,
  13930. sizeof(nodelay_on))
  13931. != 0) {
  13932. /* Error */
  13933. return 1;
  13934. }
  13935. /* OK */
  13936. return 0;
  13937. }
  13938. static void
  13939. close_socket_gracefully(struct mg_connection *conn)
  13940. {
  13941. #if defined(_WIN32)
  13942. char buf[MG_BUF_LEN];
  13943. int n;
  13944. #endif
  13945. struct linger linger;
  13946. int error_code = 0;
  13947. int linger_timeout = -2;
  13948. socklen_t opt_len = sizeof(error_code);
  13949. if (!conn) {
  13950. return;
  13951. }
  13952. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13953. * "Note that enabling a nonzero timeout on a nonblocking socket
  13954. * is not recommended.", so set it to blocking now */
  13955. set_blocking_mode(conn->client.sock);
  13956. /* Send FIN to the client */
  13957. shutdown(conn->client.sock, SHUTDOWN_WR);
  13958. #if defined(_WIN32)
  13959. /* Read and discard pending incoming data. If we do not do that and
  13960. * close
  13961. * the socket, the data in the send buffer may be discarded. This
  13962. * behaviour is seen on Windows, when client keeps sending data
  13963. * when server decides to close the connection; then when client
  13964. * does recv() it gets no data back. */
  13965. do {
  13966. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13967. } while (n > 0);
  13968. #endif
  13969. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13970. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13971. }
  13972. /* Set linger option according to configuration */
  13973. if (linger_timeout >= 0) {
  13974. /* Set linger option to avoid socket hanging out after close. This
  13975. * prevent ephemeral port exhaust problem under high QPS. */
  13976. linger.l_onoff = 1;
  13977. #if defined(_MSC_VER)
  13978. #pragma warning(push)
  13979. #pragma warning(disable : 4244)
  13980. #endif
  13981. #if defined(GCC_DIAGNOSTIC)
  13982. #pragma GCC diagnostic push
  13983. #pragma GCC diagnostic ignored "-Wconversion"
  13984. #endif
  13985. /* Data type of linger structure elements may differ,
  13986. * so we don't know what cast we need here.
  13987. * Disable type conversion warnings. */
  13988. linger.l_linger = (linger_timeout + 999) / 1000;
  13989. #if defined(GCC_DIAGNOSTIC)
  13990. #pragma GCC diagnostic pop
  13991. #endif
  13992. #if defined(_MSC_VER)
  13993. #pragma warning(pop)
  13994. #endif
  13995. } else {
  13996. linger.l_onoff = 0;
  13997. linger.l_linger = 0;
  13998. }
  13999. if (linger_timeout < -1) {
  14000. /* Default: don't configure any linger */
  14001. } else if (getsockopt(conn->client.sock,
  14002. SOL_SOCKET,
  14003. SO_ERROR,
  14004. #if defined(_WIN32) /* WinSock uses different data type here */
  14005. (char *)&error_code,
  14006. #else
  14007. &error_code,
  14008. #endif
  14009. &opt_len)
  14010. != 0) {
  14011. /* Cannot determine if socket is already closed. This should
  14012. * not occur and never did in a test. Log an error message
  14013. * and continue. */
  14014. mg_cry_internal(conn,
  14015. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  14016. __func__,
  14017. strerror(ERRNO));
  14018. #if defined(_WIN32)
  14019. } else if (error_code == WSAECONNRESET) {
  14020. #else
  14021. } else if (error_code == ECONNRESET) {
  14022. #endif
  14023. /* Socket already closed by client/peer, close socket without linger
  14024. */
  14025. } else {
  14026. /* Set linger timeout */
  14027. if (setsockopt(conn->client.sock,
  14028. SOL_SOCKET,
  14029. SO_LINGER,
  14030. (char *)&linger,
  14031. sizeof(linger))
  14032. != 0) {
  14033. mg_cry_internal(
  14034. conn,
  14035. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  14036. __func__,
  14037. linger.l_onoff,
  14038. linger.l_linger,
  14039. strerror(ERRNO));
  14040. }
  14041. }
  14042. /* Now we know that our FIN is ACK-ed, safe to close */
  14043. closesocket(conn->client.sock);
  14044. conn->client.sock = INVALID_SOCKET;
  14045. }
  14046. static void
  14047. close_connection(struct mg_connection *conn)
  14048. {
  14049. #if defined(USE_SERVER_STATS)
  14050. conn->conn_state = 6; /* to close */
  14051. #endif
  14052. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14053. if (conn->lua_websocket_state) {
  14054. lua_websocket_close(conn, conn->lua_websocket_state);
  14055. conn->lua_websocket_state = NULL;
  14056. }
  14057. #endif
  14058. mg_lock_connection(conn);
  14059. /* Set close flag, so keep-alive loops will stop */
  14060. conn->must_close = 1;
  14061. /* call the connection_close callback if assigned */
  14062. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  14063. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14064. conn->phys_ctx->callbacks.connection_close(conn);
  14065. }
  14066. }
  14067. /* Reset user data, after close callback is called.
  14068. * Do not reuse it. If the user needs a destructor,
  14069. * it must be done in the connection_close callback. */
  14070. mg_set_user_connection_data(conn, NULL);
  14071. #if defined(USE_SERVER_STATS)
  14072. conn->conn_state = 7; /* closing */
  14073. #endif
  14074. #if !defined(NO_SSL)
  14075. if (conn->ssl != NULL) {
  14076. /* Run SSL_shutdown twice to ensure completely close SSL connection
  14077. */
  14078. SSL_shutdown(conn->ssl);
  14079. SSL_free(conn->ssl);
  14080. OPENSSL_REMOVE_THREAD_STATE();
  14081. conn->ssl = NULL;
  14082. }
  14083. #endif
  14084. if (conn->client.sock != INVALID_SOCKET) {
  14085. close_socket_gracefully(conn);
  14086. conn->client.sock = INVALID_SOCKET;
  14087. }
  14088. if (conn->host) {
  14089. mg_free((void *)conn->host);
  14090. conn->host = NULL;
  14091. }
  14092. mg_unlock_connection(conn);
  14093. #if defined(USE_SERVER_STATS)
  14094. conn->conn_state = 8; /* closed */
  14095. #endif
  14096. }
  14097. void
  14098. mg_close_connection(struct mg_connection *conn)
  14099. {
  14100. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  14101. return;
  14102. }
  14103. #if defined(USE_WEBSOCKET)
  14104. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14105. if (conn->in_websocket_handling) {
  14106. /* Set close flag, so the server thread can exit. */
  14107. conn->must_close = 1;
  14108. return;
  14109. }
  14110. }
  14111. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14112. unsigned int i;
  14113. /* client context: loops must end */
  14114. conn->phys_ctx->stop_flag = 1;
  14115. conn->must_close = 1;
  14116. /* We need to get the client thread out of the select/recv call
  14117. * here. */
  14118. /* Since we use a sleep quantum of some seconds to check for recv
  14119. * timeouts, we will just wait a few seconds in mg_join_thread. */
  14120. /* join worker thread */
  14121. for (i = 0; i < conn->phys_ctx->cfg_worker_threads; i++) {
  14122. mg_join_thread(conn->phys_ctx->worker_threadids[i]);
  14123. }
  14124. }
  14125. #endif /* defined(USE_WEBSOCKET) */
  14126. close_connection(conn);
  14127. #if !defined(NO_SSL)
  14128. if (((conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT)
  14129. || (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT))
  14130. && (conn->phys_ctx->dd.ssl_ctx != NULL)) {
  14131. SSL_CTX_free(conn->phys_ctx->dd.ssl_ctx);
  14132. }
  14133. #endif
  14134. #if defined(USE_WEBSOCKET)
  14135. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  14136. mg_free(conn->phys_ctx->worker_threadids);
  14137. (void)pthread_mutex_destroy(&conn->mutex);
  14138. mg_free(conn);
  14139. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  14140. mg_free(conn);
  14141. }
  14142. #else
  14143. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  14144. mg_free(conn);
  14145. }
  14146. #endif /* defined(USE_WEBSOCKET) */
  14147. }
  14148. static struct mg_connection *
  14149. mg_connect_client_impl(const struct mg_client_options *client_options,
  14150. int use_ssl,
  14151. char *ebuf,
  14152. size_t ebuf_len)
  14153. {
  14154. struct mg_connection *conn = NULL;
  14155. SOCKET sock;
  14156. union usa sa;
  14157. struct sockaddr *psa;
  14158. socklen_t len;
  14159. unsigned max_req_size =
  14160. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  14161. /* Size of structures, aligned to 8 bytes */
  14162. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  14163. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  14164. conn =
  14165. (struct mg_connection *)mg_calloc(1,
  14166. conn_size + ctx_size + max_req_size);
  14167. if (conn == NULL) {
  14168. mg_snprintf(NULL,
  14169. NULL, /* No truncation check for ebuf */
  14170. ebuf,
  14171. ebuf_len,
  14172. "calloc(): %s",
  14173. strerror(ERRNO));
  14174. return NULL;
  14175. }
  14176. #if defined(GCC_DIAGNOSTIC)
  14177. #pragma GCC diagnostic push
  14178. #pragma GCC diagnostic ignored "-Wcast-align"
  14179. #endif /* defined(GCC_DIAGNOSTIC) */
  14180. /* conn_size is aligned to 8 bytes */
  14181. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  14182. #if defined(GCC_DIAGNOSTIC)
  14183. #pragma GCC diagnostic pop
  14184. #endif /* defined(GCC_DIAGNOSTIC) */
  14185. conn->buf = (((char *)conn) + conn_size + ctx_size);
  14186. conn->buf_size = (int)max_req_size;
  14187. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  14188. conn->dom_ctx = &(conn->phys_ctx->dd);
  14189. if (!connect_socket(conn->phys_ctx,
  14190. client_options->host,
  14191. client_options->port,
  14192. use_ssl,
  14193. ebuf,
  14194. ebuf_len,
  14195. &sock,
  14196. &sa)) {
  14197. /* ebuf is set by connect_socket,
  14198. * free all memory and return NULL; */
  14199. mg_free(conn);
  14200. return NULL;
  14201. }
  14202. #if !defined(NO_SSL)
  14203. #if defined(OPENSSL_API_1_1)
  14204. if (use_ssl
  14205. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(TLS_client_method()))
  14206. == NULL) {
  14207. mg_snprintf(NULL,
  14208. NULL, /* No truncation check for ebuf */
  14209. ebuf,
  14210. ebuf_len,
  14211. "SSL_CTX_new error: %s",
  14212. ssl_error());
  14213. closesocket(sock);
  14214. mg_free(conn);
  14215. return NULL;
  14216. }
  14217. #else
  14218. if (use_ssl
  14219. && (conn->dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  14220. == NULL) {
  14221. mg_snprintf(NULL,
  14222. NULL, /* No truncation check for ebuf */
  14223. ebuf,
  14224. ebuf_len,
  14225. "SSL_CTX_new error: %s",
  14226. ssl_error());
  14227. closesocket(sock);
  14228. mg_free(conn);
  14229. return NULL;
  14230. }
  14231. #endif /* OPENSSL_API_1_1 */
  14232. #endif /* NO_SSL */
  14233. #if defined(USE_IPV6)
  14234. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  14235. : sizeof(conn->client.rsa.sin6);
  14236. psa = (sa.sa.sa_family == AF_INET)
  14237. ? (struct sockaddr *)&(conn->client.rsa.sin)
  14238. : (struct sockaddr *)&(conn->client.rsa.sin6);
  14239. #else
  14240. len = sizeof(conn->client.rsa.sin);
  14241. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  14242. #endif
  14243. conn->client.sock = sock;
  14244. conn->client.lsa = sa;
  14245. if (getsockname(sock, psa, &len) != 0) {
  14246. mg_cry_internal(conn,
  14247. "%s: getsockname() failed: %s",
  14248. __func__,
  14249. strerror(ERRNO));
  14250. }
  14251. conn->client.is_ssl = use_ssl ? 1 : 0;
  14252. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  14253. mg_snprintf(NULL,
  14254. NULL, /* No truncation check for ebuf */
  14255. ebuf,
  14256. ebuf_len,
  14257. "Can not create mutex");
  14258. #if !defined(NO_SSL)
  14259. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14260. #endif
  14261. closesocket(sock);
  14262. mg_free(conn);
  14263. return NULL;
  14264. }
  14265. #if !defined(NO_SSL)
  14266. if (use_ssl) {
  14267. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  14268. * SSL_CTX_set_verify call is needed to switch off server
  14269. * certificate checking, which is off by default in OpenSSL and
  14270. * on in yaSSL. */
  14271. /* TODO: SSL_CTX_set_verify(conn->dom_ctx,
  14272. * SSL_VERIFY_PEER, verify_ssl_server); */
  14273. if (client_options->client_cert) {
  14274. if (!ssl_use_pem_file(conn->phys_ctx,
  14275. conn->dom_ctx,
  14276. client_options->client_cert,
  14277. NULL)) {
  14278. mg_snprintf(NULL,
  14279. NULL, /* No truncation check for ebuf */
  14280. ebuf,
  14281. ebuf_len,
  14282. "Can not use SSL client certificate");
  14283. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14284. closesocket(sock);
  14285. mg_free(conn);
  14286. return NULL;
  14287. }
  14288. }
  14289. if (client_options->server_cert) {
  14290. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  14291. client_options->server_cert,
  14292. NULL)
  14293. != 1) {
  14294. mg_cry_internal(conn,
  14295. "SSL_CTX_load_verify_locations error: %s ",
  14296. ssl_error());
  14297. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14298. closesocket(sock);
  14299. mg_free(conn);
  14300. return NULL;
  14301. }
  14302. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  14303. } else {
  14304. SSL_CTX_set_verify(conn->dom_ctx->ssl_ctx, SSL_VERIFY_NONE, NULL);
  14305. }
  14306. if (!sslize(conn,
  14307. conn->dom_ctx->ssl_ctx,
  14308. SSL_connect,
  14309. &(conn->phys_ctx->stop_flag),
  14310. client_options)) {
  14311. mg_snprintf(NULL,
  14312. NULL, /* No truncation check for ebuf */
  14313. ebuf,
  14314. ebuf_len,
  14315. "SSL connection error");
  14316. SSL_CTX_free(conn->dom_ctx->ssl_ctx);
  14317. closesocket(sock);
  14318. mg_free(conn);
  14319. return NULL;
  14320. }
  14321. }
  14322. #endif
  14323. return conn;
  14324. }
  14325. CIVETWEB_API struct mg_connection *
  14326. mg_connect_client_secure(const struct mg_client_options *client_options,
  14327. char *error_buffer,
  14328. size_t error_buffer_size)
  14329. {
  14330. return mg_connect_client_impl(client_options,
  14331. 1,
  14332. error_buffer,
  14333. error_buffer_size);
  14334. }
  14335. struct mg_connection *
  14336. mg_connect_client(const char *host,
  14337. int port,
  14338. int use_ssl,
  14339. char *error_buffer,
  14340. size_t error_buffer_size)
  14341. {
  14342. struct mg_client_options opts;
  14343. memset(&opts, 0, sizeof(opts));
  14344. opts.host = host;
  14345. opts.port = port;
  14346. return mg_connect_client_impl(&opts,
  14347. use_ssl,
  14348. error_buffer,
  14349. error_buffer_size);
  14350. }
  14351. static const struct {
  14352. const char *proto;
  14353. size_t proto_len;
  14354. unsigned default_port;
  14355. } abs_uri_protocols[] = {{"http://", 7, 80},
  14356. {"https://", 8, 443},
  14357. {"ws://", 5, 80},
  14358. {"wss://", 6, 443},
  14359. {NULL, 0, 0}};
  14360. /* Check if the uri is valid.
  14361. * return 0 for invalid uri,
  14362. * return 1 for *,
  14363. * return 2 for relative uri,
  14364. * return 3 for absolute uri without port,
  14365. * return 4 for absolute uri with port */
  14366. static int
  14367. get_uri_type(const char *uri)
  14368. {
  14369. int i;
  14370. const char *hostend, *portbegin;
  14371. char *portend;
  14372. unsigned long port;
  14373. /* According to the HTTP standard
  14374. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  14375. * URI can be an asterisk (*) or should start with slash (relative uri),
  14376. * or it should start with the protocol (absolute uri). */
  14377. if ((uri[0] == '*') && (uri[1] == '\0')) {
  14378. /* asterisk */
  14379. return 1;
  14380. }
  14381. /* Valid URIs according to RFC 3986
  14382. * (https://www.ietf.org/rfc/rfc3986.txt)
  14383. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  14384. * and unreserved characters A-Z a-z 0-9 and -._~
  14385. * and % encoded symbols.
  14386. */
  14387. for (i = 0; uri[i] != 0; i++) {
  14388. if (uri[i] < 33) {
  14389. /* control characters and spaces are invalid */
  14390. return 0;
  14391. }
  14392. if (uri[i] > 126) {
  14393. /* non-ascii characters must be % encoded */
  14394. return 0;
  14395. } else {
  14396. switch (uri[i]) {
  14397. case '"': /* 34 */
  14398. case '<': /* 60 */
  14399. case '>': /* 62 */
  14400. case '\\': /* 92 */
  14401. case '^': /* 94 */
  14402. case '`': /* 96 */
  14403. case '{': /* 123 */
  14404. case '|': /* 124 */
  14405. case '}': /* 125 */
  14406. return 0;
  14407. default:
  14408. /* character is ok */
  14409. break;
  14410. }
  14411. }
  14412. }
  14413. /* A relative uri starts with a / character */
  14414. if (uri[0] == '/') {
  14415. /* relative uri */
  14416. return 2;
  14417. }
  14418. /* It could be an absolute uri: */
  14419. /* This function only checks if the uri is valid, not if it is
  14420. * addressing the current server. So civetweb can also be used
  14421. * as a proxy server. */
  14422. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14423. if (mg_strncasecmp(uri,
  14424. abs_uri_protocols[i].proto,
  14425. abs_uri_protocols[i].proto_len)
  14426. == 0) {
  14427. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  14428. if (!hostend) {
  14429. return 0;
  14430. }
  14431. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  14432. if (!portbegin) {
  14433. return 3;
  14434. }
  14435. port = strtoul(portbegin + 1, &portend, 10);
  14436. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  14437. return 0;
  14438. }
  14439. return 4;
  14440. }
  14441. }
  14442. return 0;
  14443. }
  14444. /* Return NULL or the relative uri at the current server */
  14445. static const char *
  14446. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  14447. {
  14448. const char *server_domain;
  14449. size_t server_domain_len;
  14450. size_t request_domain_len = 0;
  14451. unsigned long port = 0;
  14452. int i, auth_domain_check_enabled;
  14453. const char *hostbegin = NULL;
  14454. const char *hostend = NULL;
  14455. const char *portbegin;
  14456. char *portend;
  14457. auth_domain_check_enabled =
  14458. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  14459. /* DNS is case insensitive, so use case insensitive string compare here
  14460. */
  14461. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  14462. if (mg_strncasecmp(uri,
  14463. abs_uri_protocols[i].proto,
  14464. abs_uri_protocols[i].proto_len)
  14465. == 0) {
  14466. hostbegin = uri + abs_uri_protocols[i].proto_len;
  14467. hostend = strchr(hostbegin, '/');
  14468. if (!hostend) {
  14469. return 0;
  14470. }
  14471. portbegin = strchr(hostbegin, ':');
  14472. if ((!portbegin) || (portbegin > hostend)) {
  14473. port = abs_uri_protocols[i].default_port;
  14474. request_domain_len = (size_t)(hostend - hostbegin);
  14475. } else {
  14476. port = strtoul(portbegin + 1, &portend, 10);
  14477. if ((portend != hostend) || (port <= 0)
  14478. || !is_valid_port(port)) {
  14479. return 0;
  14480. }
  14481. request_domain_len = (size_t)(portbegin - hostbegin);
  14482. }
  14483. /* protocol found, port set */
  14484. break;
  14485. }
  14486. }
  14487. if (!port) {
  14488. /* port remains 0 if the protocol is not found */
  14489. return 0;
  14490. }
  14491. /* Check if the request is directed to a different server. */
  14492. /* First check if the port is the same (IPv4 and IPv6). */
  14493. #if defined(USE_IPV6)
  14494. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  14495. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  14496. /* Request is directed to a different port */
  14497. return 0;
  14498. }
  14499. } else
  14500. #endif
  14501. {
  14502. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  14503. /* Request is directed to a different port */
  14504. return 0;
  14505. }
  14506. }
  14507. /* Finally check if the server corresponds to the authentication
  14508. * domain of the server (the server domain).
  14509. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14510. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14511. * but do not allow substrings (like
  14512. * http://notmydomain.com/path/file.ext
  14513. * or http://mydomain.com.fake/path/file.ext).
  14514. */
  14515. if (auth_domain_check_enabled) {
  14516. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14517. server_domain_len = strlen(server_domain);
  14518. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14519. return 0;
  14520. }
  14521. if ((request_domain_len == server_domain_len)
  14522. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14523. /* Request is directed to this server - full name match. */
  14524. } else {
  14525. if (request_domain_len < (server_domain_len + 2)) {
  14526. /* Request is directed to another server: The server name
  14527. * is longer than the request name.
  14528. * Drop this case here to avoid overflows in the
  14529. * following checks. */
  14530. return 0;
  14531. }
  14532. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14533. /* Request is directed to another server: It could be a
  14534. * substring
  14535. * like notmyserver.com */
  14536. return 0;
  14537. }
  14538. if (0
  14539. != memcmp(server_domain,
  14540. hostbegin + request_domain_len - server_domain_len,
  14541. server_domain_len)) {
  14542. /* Request is directed to another server:
  14543. * The server name is different. */
  14544. return 0;
  14545. }
  14546. }
  14547. }
  14548. return hostend;
  14549. }
  14550. static int
  14551. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14552. {
  14553. if (ebuf_len > 0) {
  14554. ebuf[0] = '\0';
  14555. }
  14556. *err = 0;
  14557. reset_per_request_attributes(conn);
  14558. if (!conn) {
  14559. mg_snprintf(conn,
  14560. NULL, /* No truncation check for ebuf */
  14561. ebuf,
  14562. ebuf_len,
  14563. "%s",
  14564. "Internal error");
  14565. *err = 500;
  14566. return 0;
  14567. }
  14568. /* Set the time the request was received. This value should be used for
  14569. * timeouts. */
  14570. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14571. conn->request_len =
  14572. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14573. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14574. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14575. mg_snprintf(conn,
  14576. NULL, /* No truncation check for ebuf */
  14577. ebuf,
  14578. ebuf_len,
  14579. "%s",
  14580. "Invalid message size");
  14581. *err = 500;
  14582. return 0;
  14583. }
  14584. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14585. mg_snprintf(conn,
  14586. NULL, /* No truncation check for ebuf */
  14587. ebuf,
  14588. ebuf_len,
  14589. "%s",
  14590. "Message too large");
  14591. *err = 413;
  14592. return 0;
  14593. }
  14594. if (conn->request_len <= 0) {
  14595. if (conn->data_len > 0) {
  14596. mg_snprintf(conn,
  14597. NULL, /* No truncation check for ebuf */
  14598. ebuf,
  14599. ebuf_len,
  14600. "%s",
  14601. "Malformed message");
  14602. *err = 400;
  14603. } else {
  14604. /* Server did not recv anything -> just close the connection */
  14605. conn->must_close = 1;
  14606. mg_snprintf(conn,
  14607. NULL, /* No truncation check for ebuf */
  14608. ebuf,
  14609. ebuf_len,
  14610. "%s",
  14611. "No data received");
  14612. *err = 0;
  14613. }
  14614. return 0;
  14615. }
  14616. return 1;
  14617. }
  14618. static int
  14619. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14620. {
  14621. const char *cl;
  14622. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14623. return 0;
  14624. }
  14625. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14626. <= 0) {
  14627. mg_snprintf(conn,
  14628. NULL, /* No truncation check for ebuf */
  14629. ebuf,
  14630. ebuf_len,
  14631. "%s",
  14632. "Bad request");
  14633. *err = 400;
  14634. return 0;
  14635. }
  14636. /* Message is a valid request */
  14637. /* Is there a "host" ? */
  14638. if (conn->host != NULL) {
  14639. mg_free((void *)conn->host);
  14640. }
  14641. conn->host = alloc_get_host(conn);
  14642. if (!conn->host) {
  14643. mg_snprintf(conn,
  14644. NULL, /* No truncation check for ebuf */
  14645. ebuf,
  14646. ebuf_len,
  14647. "%s",
  14648. "Bad request: Host mismatch");
  14649. *err = 400;
  14650. return 0;
  14651. }
  14652. if (((cl = get_header(conn->request_info.http_headers,
  14653. conn->request_info.num_headers,
  14654. "Transfer-Encoding"))
  14655. != NULL)
  14656. && mg_strcasecmp(cl, "identity")) {
  14657. if (mg_strcasecmp(cl, "chunked")) {
  14658. mg_snprintf(conn,
  14659. NULL, /* No truncation check for ebuf */
  14660. ebuf,
  14661. ebuf_len,
  14662. "%s",
  14663. "Bad request");
  14664. *err = 400;
  14665. return 0;
  14666. }
  14667. conn->is_chunked = 1;
  14668. conn->content_len = 0; /* not yet read */
  14669. } else if ((cl = get_header(conn->request_info.http_headers,
  14670. conn->request_info.num_headers,
  14671. "Content-Length"))
  14672. != NULL) {
  14673. /* Request has content length set */
  14674. char *endptr = NULL;
  14675. conn->content_len = strtoll(cl, &endptr, 10);
  14676. if ((endptr == cl) || (conn->content_len < 0)) {
  14677. mg_snprintf(conn,
  14678. NULL, /* No truncation check for ebuf */
  14679. ebuf,
  14680. ebuf_len,
  14681. "%s",
  14682. "Bad request");
  14683. *err = 411;
  14684. return 0;
  14685. }
  14686. /* Publish the content length back to the request info. */
  14687. conn->request_info.content_length = conn->content_len;
  14688. } else {
  14689. /* There is no exception, see RFC7230. */
  14690. conn->content_len = 0;
  14691. }
  14692. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14693. return 1;
  14694. }
  14695. /* conn is assumed to be valid in this internal function */
  14696. static int
  14697. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14698. {
  14699. const char *cl;
  14700. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14701. return 0;
  14702. }
  14703. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14704. <= 0) {
  14705. mg_snprintf(conn,
  14706. NULL, /* No truncation check for ebuf */
  14707. ebuf,
  14708. ebuf_len,
  14709. "%s",
  14710. "Bad response");
  14711. *err = 400;
  14712. return 0;
  14713. }
  14714. /* Message is a valid response */
  14715. if (((cl = get_header(conn->response_info.http_headers,
  14716. conn->response_info.num_headers,
  14717. "Transfer-Encoding"))
  14718. != NULL)
  14719. && mg_strcasecmp(cl, "identity")) {
  14720. if (mg_strcasecmp(cl, "chunked")) {
  14721. mg_snprintf(conn,
  14722. NULL, /* No truncation check for ebuf */
  14723. ebuf,
  14724. ebuf_len,
  14725. "%s",
  14726. "Bad request");
  14727. *err = 400;
  14728. return 0;
  14729. }
  14730. conn->is_chunked = 1;
  14731. conn->content_len = 0; /* not yet read */
  14732. } else if ((cl = get_header(conn->response_info.http_headers,
  14733. conn->response_info.num_headers,
  14734. "Content-Length"))
  14735. != NULL) {
  14736. char *endptr = NULL;
  14737. conn->content_len = strtoll(cl, &endptr, 10);
  14738. if ((endptr == cl) || (conn->content_len < 0)) {
  14739. mg_snprintf(conn,
  14740. NULL, /* No truncation check for ebuf */
  14741. ebuf,
  14742. ebuf_len,
  14743. "%s",
  14744. "Bad request");
  14745. *err = 411;
  14746. return 0;
  14747. }
  14748. /* Publish the content length back to the response info. */
  14749. conn->response_info.content_length = conn->content_len;
  14750. /* TODO: check if it is still used in response_info */
  14751. conn->request_info.content_length = conn->content_len;
  14752. /* TODO: we should also consider HEAD method */
  14753. if (conn->response_info.status_code == 304) {
  14754. conn->content_len = 0;
  14755. }
  14756. } else {
  14757. /* TODO: we should also consider HEAD method */
  14758. if (((conn->response_info.status_code >= 100)
  14759. && (conn->response_info.status_code <= 199))
  14760. || (conn->response_info.status_code == 204)
  14761. || (conn->response_info.status_code == 304)) {
  14762. conn->content_len = 0;
  14763. } else {
  14764. conn->content_len = -1; /* unknown content length */
  14765. }
  14766. }
  14767. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14768. return 1;
  14769. }
  14770. int
  14771. mg_get_response(struct mg_connection *conn,
  14772. char *ebuf,
  14773. size_t ebuf_len,
  14774. int timeout)
  14775. {
  14776. int err, ret;
  14777. char txt[32]; /* will not overflow */
  14778. char *save_timeout;
  14779. char *new_timeout;
  14780. if (ebuf_len > 0) {
  14781. ebuf[0] = '\0';
  14782. }
  14783. if (!conn) {
  14784. mg_snprintf(conn,
  14785. NULL, /* No truncation check for ebuf */
  14786. ebuf,
  14787. ebuf_len,
  14788. "%s",
  14789. "Parameter error");
  14790. return -1;
  14791. }
  14792. /* Reset the previous responses */
  14793. conn->data_len = 0;
  14794. /* Implementation of API function for HTTP clients */
  14795. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14796. if (timeout >= 0) {
  14797. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14798. new_timeout = txt;
  14799. } else {
  14800. new_timeout = NULL;
  14801. }
  14802. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14803. ret = get_response(conn, ebuf, ebuf_len, &err);
  14804. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14805. #if defined(MG_LEGACY_INTERFACE)
  14806. /* TODO: 1) uri is deprecated;
  14807. * 2) here, ri.uri is the http response code */
  14808. conn->request_info.uri = conn->request_info.request_uri;
  14809. #endif
  14810. conn->request_info.local_uri = conn->request_info.request_uri;
  14811. /* TODO (mid): Define proper return values - maybe return length?
  14812. * For the first test use <0 for error and >0 for OK */
  14813. return (ret == 0) ? -1 : +1;
  14814. }
  14815. struct mg_connection *
  14816. mg_download(const char *host,
  14817. int port,
  14818. int use_ssl,
  14819. char *ebuf,
  14820. size_t ebuf_len,
  14821. const char *fmt,
  14822. ...)
  14823. {
  14824. struct mg_connection *conn;
  14825. va_list ap;
  14826. int i;
  14827. int reqerr;
  14828. if (ebuf_len > 0) {
  14829. ebuf[0] = '\0';
  14830. }
  14831. va_start(ap, fmt);
  14832. /* open a connection */
  14833. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14834. if (conn != NULL) {
  14835. i = mg_vprintf(conn, fmt, ap);
  14836. if (i <= 0) {
  14837. mg_snprintf(conn,
  14838. NULL, /* No truncation check for ebuf */
  14839. ebuf,
  14840. ebuf_len,
  14841. "%s",
  14842. "Error sending request");
  14843. } else {
  14844. /* make sure the buffer is clear */
  14845. conn->data_len = 0;
  14846. get_response(conn, ebuf, ebuf_len, &reqerr);
  14847. #if defined(MG_LEGACY_INTERFACE)
  14848. /* TODO: 1) uri is deprecated;
  14849. * 2) here, ri.uri is the http response code */
  14850. conn->request_info.uri = conn->request_info.request_uri;
  14851. #endif
  14852. conn->request_info.local_uri = conn->request_info.request_uri;
  14853. }
  14854. }
  14855. /* if an error occurred, close the connection */
  14856. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14857. mg_close_connection(conn);
  14858. conn = NULL;
  14859. }
  14860. va_end(ap);
  14861. return conn;
  14862. }
  14863. struct websocket_client_thread_data {
  14864. struct mg_connection *conn;
  14865. mg_websocket_data_handler data_handler;
  14866. mg_websocket_close_handler close_handler;
  14867. void *callback_data;
  14868. };
  14869. #if defined(USE_WEBSOCKET)
  14870. #if defined(_WIN32)
  14871. static unsigned __stdcall websocket_client_thread(void *data)
  14872. #else
  14873. static void *
  14874. websocket_client_thread(void *data)
  14875. #endif
  14876. {
  14877. struct websocket_client_thread_data *cdata =
  14878. (struct websocket_client_thread_data *)data;
  14879. void *user_thread_ptr = NULL;
  14880. #if !defined(_WIN32)
  14881. struct sigaction sa;
  14882. /* Ignore SIGPIPE */
  14883. memset(&sa, 0, sizeof(sa));
  14884. sa.sa_handler = SIG_IGN;
  14885. sigaction(SIGPIPE, &sa, NULL);
  14886. #endif
  14887. mg_set_thread_name("ws-clnt");
  14888. if (cdata->conn->phys_ctx) {
  14889. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14890. /* 3 indicates a websocket client thread */
  14891. /* TODO: check if conn->phys_ctx can be set */
  14892. user_thread_ptr = cdata->conn->phys_ctx->callbacks.init_thread(
  14893. cdata->conn->phys_ctx, 3);
  14894. }
  14895. }
  14896. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14897. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14898. if (cdata->close_handler != NULL) {
  14899. cdata->close_handler(cdata->conn, cdata->callback_data);
  14900. }
  14901. /* The websocket_client context has only this thread. If it runs out,
  14902. set the stop_flag to 2 (= "stopped"). */
  14903. cdata->conn->phys_ctx->stop_flag = 2;
  14904. if (cdata->conn->phys_ctx->callbacks.exit_thread) {
  14905. cdata->conn->phys_ctx->callbacks.exit_thread(cdata->conn->phys_ctx,
  14906. 3,
  14907. user_thread_ptr);
  14908. }
  14909. mg_free((void *)cdata);
  14910. #if defined(_WIN32)
  14911. return 0;
  14912. #else
  14913. return NULL;
  14914. #endif
  14915. }
  14916. #endif
  14917. struct mg_connection *
  14918. mg_connect_websocket_client(const char *host,
  14919. int port,
  14920. int use_ssl,
  14921. char *error_buffer,
  14922. size_t error_buffer_size,
  14923. const char *path,
  14924. const char *origin,
  14925. mg_websocket_data_handler data_func,
  14926. mg_websocket_close_handler close_func,
  14927. void *user_data)
  14928. {
  14929. struct mg_connection *conn = NULL;
  14930. #if defined(USE_WEBSOCKET)
  14931. struct websocket_client_thread_data *thread_data;
  14932. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14933. static const char *handshake_req;
  14934. if (origin != NULL) {
  14935. handshake_req = "GET %s HTTP/1.1\r\n"
  14936. "Host: %s\r\n"
  14937. "Upgrade: websocket\r\n"
  14938. "Connection: Upgrade\r\n"
  14939. "Sec-WebSocket-Key: %s\r\n"
  14940. "Sec-WebSocket-Version: 13\r\n"
  14941. "Origin: %s\r\n"
  14942. "\r\n";
  14943. } else {
  14944. handshake_req = "GET %s HTTP/1.1\r\n"
  14945. "Host: %s\r\n"
  14946. "Upgrade: websocket\r\n"
  14947. "Connection: Upgrade\r\n"
  14948. "Sec-WebSocket-Key: %s\r\n"
  14949. "Sec-WebSocket-Version: 13\r\n"
  14950. "\r\n";
  14951. }
  14952. #if defined(__clang__)
  14953. #pragma clang diagnostic push
  14954. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  14955. #endif
  14956. /* Establish the client connection and request upgrade */
  14957. conn = mg_download(host,
  14958. port,
  14959. use_ssl,
  14960. error_buffer,
  14961. error_buffer_size,
  14962. handshake_req,
  14963. path,
  14964. host,
  14965. magic,
  14966. origin);
  14967. #if defined(__clang__)
  14968. #pragma clang diagnostic pop
  14969. #endif
  14970. /* Connection object will be null if something goes wrong */
  14971. if (conn == NULL) {
  14972. if (!*error_buffer) {
  14973. /* There should be already an error message */
  14974. mg_snprintf(conn,
  14975. NULL, /* No truncation check for ebuf */
  14976. error_buffer,
  14977. error_buffer_size,
  14978. "Unexpected error");
  14979. }
  14980. return NULL;
  14981. }
  14982. if (conn->response_info.status_code != 101) {
  14983. /* We sent an "upgrade" request. For a correct websocket
  14984. * protocol handshake, we expect a "101 Continue" response.
  14985. * Otherwise it is a protocol violation. Maybe the HTTP
  14986. * Server does not know websockets. */
  14987. if (!*error_buffer) {
  14988. /* set an error, if not yet set */
  14989. mg_snprintf(conn,
  14990. NULL, /* No truncation check for ebuf */
  14991. error_buffer,
  14992. error_buffer_size,
  14993. "Unexpected server reply");
  14994. }
  14995. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14996. mg_close_connection(conn);
  14997. return NULL;
  14998. }
  14999. thread_data = (struct websocket_client_thread_data *)mg_calloc_ctx(
  15000. 1, sizeof(struct websocket_client_thread_data), conn->phys_ctx);
  15001. if (!thread_data) {
  15002. DEBUG_TRACE("%s\r\n", "Out of memory");
  15003. mg_close_connection(conn);
  15004. return NULL;
  15005. }
  15006. thread_data->conn = conn;
  15007. thread_data->data_handler = data_func;
  15008. thread_data->close_handler = close_func;
  15009. thread_data->callback_data = user_data;
  15010. conn->phys_ctx->worker_threadids =
  15011. (pthread_t *)mg_calloc_ctx(1, sizeof(pthread_t), conn->phys_ctx);
  15012. if (!conn->phys_ctx->worker_threadids) {
  15013. DEBUG_TRACE("%s\r\n", "Out of memory");
  15014. mg_free(thread_data);
  15015. mg_close_connection(conn);
  15016. return NULL;
  15017. }
  15018. /* Now upgrade to ws/wss client context */
  15019. conn->phys_ctx->user_data = user_data;
  15020. conn->phys_ctx->context_type = CONTEXT_WS_CLIENT;
  15021. conn->phys_ctx->cfg_worker_threads = 1; /* one worker thread */
  15022. /* Start a thread to read the websocket client connection
  15023. * This thread will automatically stop when mg_disconnect is
  15024. * called on the client connection */
  15025. if (mg_start_thread_with_id(websocket_client_thread,
  15026. thread_data,
  15027. conn->phys_ctx->worker_threadids)
  15028. != 0) {
  15029. conn->phys_ctx->cfg_worker_threads = 0;
  15030. mg_free(thread_data);
  15031. mg_close_connection(conn);
  15032. conn = NULL;
  15033. DEBUG_TRACE("%s",
  15034. "Websocket client connect thread could not be started\r\n");
  15035. }
  15036. #else
  15037. /* Appease "unused parameter" warnings */
  15038. (void)host;
  15039. (void)port;
  15040. (void)use_ssl;
  15041. (void)error_buffer;
  15042. (void)error_buffer_size;
  15043. (void)path;
  15044. (void)origin;
  15045. (void)user_data;
  15046. (void)data_func;
  15047. (void)close_func;
  15048. #endif
  15049. return conn;
  15050. }
  15051. /* Prepare connection data structure */
  15052. static void
  15053. init_connection(struct mg_connection *conn)
  15054. {
  15055. /* Is keep alive allowed by the server */
  15056. int keep_alive_enabled =
  15057. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  15058. if (!keep_alive_enabled) {
  15059. conn->must_close = 1;
  15060. }
  15061. /* Important: on new connection, reset the receiving buffer. Credit
  15062. * goes to crule42. */
  15063. conn->data_len = 0;
  15064. conn->handled_requests = 0;
  15065. mg_set_user_connection_data(conn, NULL);
  15066. #if defined(USE_SERVER_STATS)
  15067. conn->conn_state = 2; /* init */
  15068. #endif
  15069. /* call the init_connection callback if assigned */
  15070. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  15071. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  15072. void *conn_data = NULL;
  15073. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  15074. mg_set_user_connection_data(conn, conn_data);
  15075. }
  15076. }
  15077. }
  15078. /* Process a connection - may handle multiple requests
  15079. * using the same connection.
  15080. * Must be called with a valid connection (conn and
  15081. * conn->phys_ctx must be valid).
  15082. */
  15083. static void
  15084. process_new_connection(struct mg_connection *conn)
  15085. {
  15086. struct mg_request_info *ri = &conn->request_info;
  15087. int keep_alive, discard_len;
  15088. char ebuf[100];
  15089. const char *hostend;
  15090. int reqerr, uri_type;
  15091. #if defined(USE_SERVER_STATS)
  15092. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  15093. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  15094. if (mcon > (conn->phys_ctx->max_connections)) {
  15095. /* could use atomic compare exchange, but this
  15096. * seems overkill for statistics data */
  15097. conn->phys_ctx->max_connections = mcon;
  15098. }
  15099. #endif
  15100. init_connection(conn);
  15101. DEBUG_TRACE("Start processing connection from %s",
  15102. conn->request_info.remote_addr);
  15103. /* Loop over multiple requests sent using the same connection
  15104. * (while "keep alive"). */
  15105. do {
  15106. DEBUG_TRACE("calling get_request (%i times for this connection)",
  15107. conn->handled_requests + 1);
  15108. #if defined(USE_SERVER_STATS)
  15109. conn->conn_state = 3; /* ready */
  15110. #endif
  15111. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  15112. /* The request sent by the client could not be understood by
  15113. * the server, or it was incomplete or a timeout. Send an
  15114. * error message and close the connection. */
  15115. if (reqerr > 0) {
  15116. DEBUG_ASSERT(ebuf[0] != '\0');
  15117. mg_send_http_error(conn, reqerr, "%s", ebuf);
  15118. }
  15119. } else if (strcmp(ri->http_version, "1.0")
  15120. && strcmp(ri->http_version, "1.1")) {
  15121. mg_snprintf(conn,
  15122. NULL, /* No truncation check for ebuf */
  15123. ebuf,
  15124. sizeof(ebuf),
  15125. "Bad HTTP version: [%s]",
  15126. ri->http_version);
  15127. mg_send_http_error(conn, 505, "%s", ebuf);
  15128. }
  15129. if (ebuf[0] == '\0') {
  15130. uri_type = get_uri_type(conn->request_info.request_uri);
  15131. switch (uri_type) {
  15132. case 1:
  15133. /* Asterisk */
  15134. conn->request_info.local_uri = NULL;
  15135. break;
  15136. case 2:
  15137. /* relative uri */
  15138. conn->request_info.local_uri = conn->request_info.request_uri;
  15139. break;
  15140. case 3:
  15141. case 4:
  15142. /* absolute uri (with/without port) */
  15143. hostend = get_rel_url_at_current_server(
  15144. conn->request_info.request_uri, conn);
  15145. if (hostend) {
  15146. conn->request_info.local_uri = hostend;
  15147. } else {
  15148. conn->request_info.local_uri = NULL;
  15149. }
  15150. break;
  15151. default:
  15152. mg_snprintf(conn,
  15153. NULL, /* No truncation check for ebuf */
  15154. ebuf,
  15155. sizeof(ebuf),
  15156. "Invalid URI");
  15157. mg_send_http_error(conn, 400, "%s", ebuf);
  15158. conn->request_info.local_uri = NULL;
  15159. break;
  15160. }
  15161. #if defined(MG_LEGACY_INTERFACE)
  15162. /* Legacy before split into local_uri and request_uri */
  15163. conn->request_info.uri = conn->request_info.local_uri;
  15164. #endif
  15165. }
  15166. DEBUG_TRACE("http: %s, error: %s",
  15167. (ri->http_version ? ri->http_version : "none"),
  15168. (ebuf[0] ? ebuf : "none"));
  15169. if (ebuf[0] == '\0') {
  15170. if (conn->request_info.local_uri) {
  15171. /* handle request to local server */
  15172. #if defined(USE_SERVER_STATS)
  15173. conn->conn_state = 4; /* processing */
  15174. #endif
  15175. handle_request(conn);
  15176. #if defined(USE_SERVER_STATS)
  15177. conn->conn_state = 5; /* processed */
  15178. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  15179. conn->consumed_content);
  15180. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  15181. conn->num_bytes_sent);
  15182. #endif
  15183. DEBUG_TRACE("%s", "handle_request done");
  15184. if (conn->phys_ctx->callbacks.end_request != NULL) {
  15185. conn->phys_ctx->callbacks.end_request(conn,
  15186. conn->status_code);
  15187. DEBUG_TRACE("%s", "end_request callback done");
  15188. }
  15189. log_access(conn);
  15190. } else {
  15191. /* TODO: handle non-local request (PROXY) */
  15192. conn->must_close = 1;
  15193. }
  15194. } else {
  15195. conn->must_close = 1;
  15196. }
  15197. if (ri->remote_user != NULL) {
  15198. mg_free((void *)ri->remote_user);
  15199. /* Important! When having connections with and without auth
  15200. * would cause double free and then crash */
  15201. ri->remote_user = NULL;
  15202. }
  15203. /* NOTE(lsm): order is important here. should_keep_alive() call
  15204. * is using parsed request, which will be invalid after
  15205. * memmove's below.
  15206. * Therefore, memorize should_keep_alive() result now for later
  15207. * use in loop exit condition. */
  15208. /* Enable it only if this request is completely discardable. */
  15209. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  15210. && (conn->content_len >= 0) && (conn->request_len > 0)
  15211. && ((conn->is_chunked == 4)
  15212. || (!conn->is_chunked
  15213. && ((conn->consumed_content == conn->content_len)
  15214. || ((conn->request_len + conn->content_len)
  15215. <= conn->data_len))));
  15216. if (keep_alive) {
  15217. /* Discard all buffered data for this request */
  15218. discard_len =
  15219. ((conn->request_len + conn->content_len) < conn->data_len)
  15220. ? (int)(conn->request_len + conn->content_len)
  15221. : conn->data_len;
  15222. conn->data_len -= discard_len;
  15223. if (conn->data_len > 0) {
  15224. DEBUG_TRACE("discard_len = %d", discard_len);
  15225. memmove(conn->buf,
  15226. conn->buf + discard_len,
  15227. (size_t)conn->data_len);
  15228. }
  15229. }
  15230. DEBUG_ASSERT(conn->data_len >= 0);
  15231. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  15232. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  15233. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  15234. (long int)conn->data_len,
  15235. (long int)conn->buf_size);
  15236. break;
  15237. }
  15238. conn->handled_requests++;
  15239. } while (keep_alive);
  15240. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  15241. conn->request_info.remote_addr,
  15242. difftime(time(NULL), conn->conn_birth_time));
  15243. close_connection(conn);
  15244. #if defined(USE_SERVER_STATS)
  15245. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  15246. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  15247. #endif
  15248. }
  15249. #if defined(ALTERNATIVE_QUEUE)
  15250. static void
  15251. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15252. {
  15253. unsigned int i;
  15254. while (!ctx->stop_flag) {
  15255. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15256. /* find a free worker slot and signal it */
  15257. if (ctx->client_socks[i].in_use == 2) {
  15258. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15259. if ((ctx->client_socks[i].in_use == 2) && !ctx->stop_flag) {
  15260. ctx->client_socks[i] = *sp;
  15261. ctx->client_socks[i].in_use = 1;
  15262. /* socket has been moved to the consumer */
  15263. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15264. (void)event_signal(ctx->client_wait_events[i]);
  15265. return;
  15266. }
  15267. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15268. }
  15269. }
  15270. /* queue is full */
  15271. mg_sleep(1);
  15272. }
  15273. /* must consume */
  15274. set_blocking_mode(sp->sock);
  15275. closesocket(sp->sock);
  15276. }
  15277. static int
  15278. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15279. {
  15280. DEBUG_TRACE("%s", "going idle");
  15281. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15282. ctx->client_socks[thread_index].in_use = 2;
  15283. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15284. event_wait(ctx->client_wait_events[thread_index]);
  15285. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15286. *sp = ctx->client_socks[thread_index];
  15287. if (ctx->stop_flag) {
  15288. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15289. if (sp->in_use == 1) {
  15290. /* must consume */
  15291. set_blocking_mode(sp->sock);
  15292. closesocket(sp->sock);
  15293. }
  15294. return 0;
  15295. }
  15296. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15297. if (sp->in_use == 1) {
  15298. DEBUG_TRACE("grabbed socket %d, going busy", sp->sock);
  15299. return 1;
  15300. }
  15301. /* must not reach here */
  15302. DEBUG_ASSERT(0);
  15303. return 0;
  15304. }
  15305. #else /* ALTERNATIVE_QUEUE */
  15306. /* Worker threads take accepted socket from the queue */
  15307. static int
  15308. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  15309. {
  15310. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15311. (void)thread_index;
  15312. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15313. DEBUG_TRACE("%s", "going idle");
  15314. /* If the queue is empty, wait. We're idle at this point. */
  15315. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  15316. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  15317. }
  15318. /* If we're stopping, sq_head may be equal to sq_tail. */
  15319. if (ctx->sq_head > ctx->sq_tail) {
  15320. /* Copy socket from the queue and increment tail */
  15321. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  15322. ctx->sq_tail++;
  15323. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  15324. /* Wrap pointers if needed */
  15325. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  15326. ctx->sq_tail -= QUEUE_SIZE(ctx);
  15327. ctx->sq_head -= QUEUE_SIZE(ctx);
  15328. }
  15329. }
  15330. (void)pthread_cond_signal(&ctx->sq_empty);
  15331. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15332. return !ctx->stop_flag;
  15333. #undef QUEUE_SIZE
  15334. }
  15335. /* Master thread adds accepted socket to a queue */
  15336. static void
  15337. produce_socket(struct mg_context *ctx, const struct socket *sp)
  15338. {
  15339. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  15340. if (!ctx) {
  15341. return;
  15342. }
  15343. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15344. /* If the queue is full, wait */
  15345. while ((ctx->stop_flag == 0)
  15346. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  15347. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  15348. }
  15349. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  15350. /* Copy socket to the queue and increment head */
  15351. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  15352. ctx->sq_head++;
  15353. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  15354. }
  15355. (void)pthread_cond_signal(&ctx->sq_full);
  15356. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15357. #undef QUEUE_SIZE
  15358. }
  15359. #endif /* ALTERNATIVE_QUEUE */
  15360. static void
  15361. worker_thread_run(struct mg_connection *conn)
  15362. {
  15363. struct mg_context *ctx = conn->phys_ctx;
  15364. int thread_index;
  15365. struct mg_workerTLS tls;
  15366. #if defined(MG_LEGACY_INTERFACE)
  15367. uint32_t addr;
  15368. #endif
  15369. mg_set_thread_name("worker");
  15370. tls.is_master = 0;
  15371. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15372. #if defined(_WIN32)
  15373. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15374. #endif
  15375. /* Initialize thread local storage before calling any callback */
  15376. pthread_setspecific(sTlsKey, &tls);
  15377. /* Check if there is a user callback */
  15378. if (ctx->callbacks.init_thread) {
  15379. /* call init_thread for a worker thread (type 1), and store the return
  15380. * value */
  15381. tls.user_ptr = ctx->callbacks.init_thread(ctx, 1);
  15382. } else {
  15383. /* No callback: set user pointer to NULL */
  15384. tls.user_ptr = NULL;
  15385. }
  15386. /* Connection structure has been pre-allocated */
  15387. thread_index = (int)(conn - ctx->worker_connections);
  15388. if ((thread_index < 0)
  15389. || ((unsigned)thread_index >= (unsigned)ctx->cfg_worker_threads)) {
  15390. mg_cry_ctx_internal(ctx,
  15391. "Internal error: Invalid worker index %i",
  15392. thread_index);
  15393. return;
  15394. }
  15395. /* Request buffers are not pre-allocated. They are private to the
  15396. * request and do not contain any state information that might be
  15397. * of interest to anyone observing a server status. */
  15398. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  15399. if (conn->buf == NULL) {
  15400. mg_cry_ctx_internal(
  15401. ctx,
  15402. "Out of memory: Cannot allocate buffer for worker %i",
  15403. thread_index);
  15404. return;
  15405. }
  15406. conn->buf_size = (int)ctx->max_request_size;
  15407. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  15408. conn->host = NULL; /* until we have more information. */
  15409. conn->tls_user_ptr = tls.user_ptr; /* store ptr for quick access */
  15410. conn->request_info.user_data = ctx->user_data;
  15411. /* Allocate a mutex for this connection to allow communication both
  15412. * within the request handler and from elsewhere in the application
  15413. */
  15414. if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) {
  15415. mg_free(conn->buf);
  15416. mg_cry_ctx_internal(ctx, "%s", "Cannot create mutex");
  15417. return;
  15418. }
  15419. #if defined(USE_SERVER_STATS)
  15420. conn->conn_state = 1; /* not consumed */
  15421. #endif
  15422. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  15423. * signal sq_empty condvar to wake up the master waiting in
  15424. * produce_socket() */
  15425. while (consume_socket(ctx, &conn->client, thread_index)) {
  15426. conn->conn_birth_time = time(NULL);
  15427. /* Fill in IP, port info early so even if SSL setup below fails,
  15428. * error handler would have the corresponding info.
  15429. * Thanks to Johannes Winkelmann for the patch.
  15430. */
  15431. #if defined(USE_IPV6)
  15432. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  15433. conn->request_info.remote_port =
  15434. ntohs(conn->client.rsa.sin6.sin6_port);
  15435. } else
  15436. #endif
  15437. {
  15438. conn->request_info.remote_port =
  15439. ntohs(conn->client.rsa.sin.sin_port);
  15440. }
  15441. sockaddr_to_string(conn->request_info.remote_addr,
  15442. sizeof(conn->request_info.remote_addr),
  15443. &conn->client.rsa);
  15444. DEBUG_TRACE("Start processing connection from %s",
  15445. conn->request_info.remote_addr);
  15446. conn->request_info.is_ssl = conn->client.is_ssl;
  15447. if (conn->client.is_ssl) {
  15448. #if !defined(NO_SSL)
  15449. /* HTTPS connection */
  15450. if (sslize(conn,
  15451. conn->dom_ctx->ssl_ctx,
  15452. SSL_accept,
  15453. &(conn->phys_ctx->stop_flag),
  15454. NULL)) {
  15455. /* conn->dom_ctx is set in get_request */
  15456. /* Get SSL client certificate information (if set) */
  15457. ssl_get_client_cert_info(conn);
  15458. /* process HTTPS connection */
  15459. process_new_connection(conn);
  15460. /* Free client certificate info */
  15461. if (conn->request_info.client_cert) {
  15462. mg_free((void *)(conn->request_info.client_cert->subject));
  15463. mg_free((void *)(conn->request_info.client_cert->issuer));
  15464. mg_free((void *)(conn->request_info.client_cert->serial));
  15465. mg_free((void *)(conn->request_info.client_cert->finger));
  15466. /* Free certificate memory */
  15467. X509_free(
  15468. (X509 *)conn->request_info.client_cert->peer_cert);
  15469. conn->request_info.client_cert->peer_cert = 0;
  15470. conn->request_info.client_cert->subject = 0;
  15471. conn->request_info.client_cert->issuer = 0;
  15472. conn->request_info.client_cert->serial = 0;
  15473. conn->request_info.client_cert->finger = 0;
  15474. mg_free(conn->request_info.client_cert);
  15475. conn->request_info.client_cert = 0;
  15476. }
  15477. } else {
  15478. /* make sure the connection is cleaned up on SSL failure */
  15479. close_connection(conn);
  15480. }
  15481. #endif
  15482. } else {
  15483. /* process HTTP connection */
  15484. process_new_connection(conn);
  15485. }
  15486. DEBUG_TRACE("%s", "Connection closed");
  15487. }
  15488. /* Call exit thread user callback */
  15489. if (ctx->callbacks.exit_thread) {
  15490. ctx->callbacks.exit_thread(ctx, 1, tls.user_ptr);
  15491. }
  15492. /* delete thread local storage objects */
  15493. pthread_setspecific(sTlsKey, NULL);
  15494. #if defined(_WIN32)
  15495. CloseHandle(tls.pthread_cond_helper_mutex);
  15496. #endif
  15497. pthread_mutex_destroy(&conn->mutex);
  15498. /* Free the request buffer. */
  15499. conn->buf_size = 0;
  15500. mg_free(conn->buf);
  15501. conn->buf = NULL;
  15502. #if defined(USE_SERVER_STATS)
  15503. conn->conn_state = 9; /* done */
  15504. #endif
  15505. DEBUG_TRACE("%s", "exiting");
  15506. }
  15507. /* Threads have different return types on Windows and Unix. */
  15508. #if defined(_WIN32)
  15509. static unsigned __stdcall worker_thread(void *thread_func_param)
  15510. {
  15511. worker_thread_run((struct mg_connection *)thread_func_param);
  15512. return 0;
  15513. }
  15514. #else
  15515. static void *
  15516. worker_thread(void *thread_func_param)
  15517. {
  15518. struct sigaction sa;
  15519. /* Ignore SIGPIPE */
  15520. memset(&sa, 0, sizeof(sa));
  15521. sa.sa_handler = SIG_IGN;
  15522. sigaction(SIGPIPE, &sa, NULL);
  15523. worker_thread_run((struct mg_connection *)thread_func_param);
  15524. return NULL;
  15525. }
  15526. #endif /* _WIN32 */
  15527. /* This is an internal function, thus all arguments are expected to be
  15528. * valid - a NULL check is not required. */
  15529. static void
  15530. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  15531. {
  15532. struct socket so;
  15533. char src_addr[IP_ADDR_STR_LEN];
  15534. socklen_t len = sizeof(so.rsa);
  15535. int on = 1;
  15536. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  15537. == INVALID_SOCKET) {
  15538. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  15539. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  15540. mg_cry_ctx_internal(ctx,
  15541. "%s: %s is not allowed to connect",
  15542. __func__,
  15543. src_addr);
  15544. closesocket(so.sock);
  15545. } else {
  15546. /* Put so socket structure into the queue */
  15547. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  15548. set_close_on_exec(so.sock, NULL, ctx);
  15549. so.is_ssl = listener->is_ssl;
  15550. so.ssl_redir = listener->ssl_redir;
  15551. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  15552. mg_cry_ctx_internal(ctx,
  15553. "%s: getsockname() failed: %s",
  15554. __func__,
  15555. strerror(ERRNO));
  15556. }
  15557. /* Set TCP keep-alive. This is needed because if HTTP-level
  15558. * keep-alive
  15559. * is enabled, and client resets the connection, server won't get
  15560. * TCP FIN or RST and will keep the connection open forever. With
  15561. * TCP keep-alive, next keep-alive handshake will figure out that
  15562. * the client is down and will close the server end.
  15563. * Thanks to Igor Klopov who suggested the patch. */
  15564. if (setsockopt(so.sock,
  15565. SOL_SOCKET,
  15566. SO_KEEPALIVE,
  15567. (SOCK_OPT_TYPE)&on,
  15568. sizeof(on))
  15569. != 0) {
  15570. mg_cry_ctx_internal(
  15571. ctx,
  15572. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15573. __func__,
  15574. strerror(ERRNO));
  15575. }
  15576. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15577. * to effectively fill up the underlying IP packet payload and
  15578. * reduce the overhead of sending lots of small buffers. However
  15579. * this hurts the server's throughput (ie. operations per second)
  15580. * when HTTP 1.1 persistent connections are used and the responses
  15581. * are relatively small (eg. less than 1400 bytes).
  15582. */
  15583. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15584. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15585. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15586. mg_cry_ctx_internal(
  15587. ctx,
  15588. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15589. __func__,
  15590. strerror(ERRNO));
  15591. }
  15592. }
  15593. /* The "non blocking" property should already be
  15594. * inherited from the parent socket. Set it for
  15595. * non-compliant socket implementations. */
  15596. set_non_blocking_mode(so.sock);
  15597. so.in_use = 0;
  15598. produce_socket(ctx, &so);
  15599. }
  15600. }
  15601. static void
  15602. master_thread_run(struct mg_context *ctx)
  15603. {
  15604. struct mg_workerTLS tls;
  15605. struct mg_pollfd *pfd;
  15606. unsigned int i;
  15607. unsigned int workerthreadcount;
  15608. if (!ctx) {
  15609. return;
  15610. }
  15611. mg_set_thread_name("master");
  15612. /* Increase priority of the master thread */
  15613. #if defined(_WIN32)
  15614. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15615. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15616. int min_prio = sched_get_priority_min(SCHED_RR);
  15617. int max_prio = sched_get_priority_max(SCHED_RR);
  15618. if ((min_prio >= 0) && (max_prio >= 0)
  15619. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15620. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15621. struct sched_param sched_param = {0};
  15622. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15623. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15624. }
  15625. #endif
  15626. /* Initialize thread local storage */
  15627. #if defined(_WIN32)
  15628. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15629. #endif
  15630. tls.is_master = 1;
  15631. pthread_setspecific(sTlsKey, &tls);
  15632. if (ctx->callbacks.init_thread) {
  15633. /* Callback for the master thread (type 0) */
  15634. tls.user_ptr = ctx->callbacks.init_thread(ctx, 0);
  15635. } else {
  15636. tls.user_ptr = NULL;
  15637. }
  15638. /* Server starts *now* */
  15639. ctx->start_time = time(NULL);
  15640. /* Start the server */
  15641. pfd = ctx->listening_socket_fds;
  15642. while (ctx->stop_flag == 0) {
  15643. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15644. pfd[i].fd = ctx->listening_sockets[i].sock;
  15645. pfd[i].events = POLLIN;
  15646. }
  15647. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15648. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15649. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15650. * successful poll, and POLLIN is defined as
  15651. * (POLLRDNORM | POLLRDBAND)
  15652. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15653. * pfd[i].revents == POLLIN. */
  15654. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15655. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15656. }
  15657. }
  15658. }
  15659. }
  15660. /* Here stop_flag is 1 - Initiate shutdown. */
  15661. DEBUG_TRACE("%s", "stopping workers");
  15662. /* Stop signal received: somebody called mg_stop. Quit. */
  15663. close_all_listening_sockets(ctx);
  15664. /* Wakeup workers that are waiting for connections to handle. */
  15665. #if defined(ALTERNATIVE_QUEUE)
  15666. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15667. event_signal(ctx->client_wait_events[i]);
  15668. }
  15669. #else
  15670. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15671. pthread_cond_broadcast(&ctx->sq_full);
  15672. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15673. #endif
  15674. /* Join all worker threads to avoid leaking threads. */
  15675. workerthreadcount = ctx->cfg_worker_threads;
  15676. for (i = 0; i < workerthreadcount; i++) {
  15677. if (ctx->worker_threadids[i] != 0) {
  15678. mg_join_thread(ctx->worker_threadids[i]);
  15679. }
  15680. }
  15681. #if defined(USE_LUA)
  15682. /* Free Lua state of lua background task */
  15683. if (ctx->lua_background_state) {
  15684. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15685. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15686. if (lua_istable(lstate, -1)) {
  15687. reg_boolean(lstate, "shutdown", 1);
  15688. lua_pop(lstate, 1);
  15689. mg_sleep(2);
  15690. }
  15691. lua_close(lstate);
  15692. ctx->lua_background_state = 0;
  15693. }
  15694. #endif
  15695. DEBUG_TRACE("%s", "exiting");
  15696. /* call exit thread callback */
  15697. if (ctx->callbacks.exit_thread) {
  15698. /* Callback for the master thread (type 0) */
  15699. ctx->callbacks.exit_thread(ctx, 0, tls.user_ptr);
  15700. }
  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. mg_free(ctx->worker_threadids);
  15797. /* Deallocate worker thread ID array */
  15798. mg_free(ctx->worker_connections);
  15799. /* deallocate system name string */
  15800. mg_free(ctx->systemName);
  15801. /* Deallocate context itself */
  15802. mg_free(ctx);
  15803. }
  15804. void
  15805. mg_stop(struct mg_context *ctx)
  15806. {
  15807. pthread_t mt;
  15808. if (!ctx) {
  15809. return;
  15810. }
  15811. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15812. * two threads is not allowed. */
  15813. mt = ctx->masterthreadid;
  15814. if (mt == 0) {
  15815. return;
  15816. }
  15817. ctx->masterthreadid = 0;
  15818. /* Set stop flag, so all threads know they have to exit. */
  15819. ctx->stop_flag = 1;
  15820. /* Wait until everything has stopped. */
  15821. while (ctx->stop_flag != 2) {
  15822. (void)mg_sleep(10);
  15823. }
  15824. mg_join_thread(mt);
  15825. free_context(ctx);
  15826. #if defined(_WIN32)
  15827. (void)WSACleanup();
  15828. #endif /* _WIN32 */
  15829. }
  15830. static void
  15831. get_system_name(char **sysName)
  15832. {
  15833. #if defined(_WIN32)
  15834. #if !defined(__SYMBIAN32__)
  15835. #if defined(_WIN32_WCE)
  15836. *sysName = mg_strdup("WinCE");
  15837. #else
  15838. char name[128];
  15839. DWORD dwVersion = 0;
  15840. DWORD dwMajorVersion = 0;
  15841. DWORD dwMinorVersion = 0;
  15842. DWORD dwBuild = 0;
  15843. BOOL wowRet, isWoW = FALSE;
  15844. #if defined(_MSC_VER)
  15845. #pragma warning(push)
  15846. /* GetVersion was declared deprecated */
  15847. #pragma warning(disable : 4996)
  15848. #endif
  15849. dwVersion = GetVersion();
  15850. #if defined(_MSC_VER)
  15851. #pragma warning(pop)
  15852. #endif
  15853. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15854. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15855. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15856. (void)dwBuild;
  15857. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15858. sprintf(name,
  15859. "Windows %u.%u%s",
  15860. (unsigned)dwMajorVersion,
  15861. (unsigned)dwMinorVersion,
  15862. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15863. *sysName = mg_strdup(name);
  15864. #endif
  15865. #else
  15866. *sysName = mg_strdup("Symbian");
  15867. #endif
  15868. #else
  15869. struct utsname name;
  15870. memset(&name, 0, sizeof(name));
  15871. uname(&name);
  15872. *sysName = mg_strdup(name.sysname);
  15873. #endif
  15874. }
  15875. struct mg_context *
  15876. mg_start(const struct mg_callbacks *callbacks,
  15877. void *user_data,
  15878. const char **options)
  15879. {
  15880. struct mg_context *ctx;
  15881. const char *name, *value, *default_value;
  15882. int idx, ok, workerthreadcount;
  15883. unsigned int i;
  15884. int itmp;
  15885. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15886. struct mg_workerTLS tls;
  15887. #if defined(_WIN32)
  15888. WSADATA data;
  15889. WSAStartup(MAKEWORD(2, 2), &data);
  15890. #endif /* _WIN32 */
  15891. /* Allocate context and initialize reasonable general case defaults. */
  15892. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15893. return NULL;
  15894. }
  15895. /* Random number generator will initialize at the first call */
  15896. ctx->dd.auth_nonce_mask =
  15897. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15898. if (mg_init_library_called == 0) {
  15899. /* Legacy INIT, if mg_start is called without mg_init_library.
  15900. * Note: This may cause a memory leak */
  15901. const char *ports_option =
  15902. config_options[LISTENING_PORTS].default_value;
  15903. if (options) {
  15904. const char **run_options = options;
  15905. const char *optname = config_options[LISTENING_PORTS].name;
  15906. /* Try to find the "listening_ports" option */
  15907. while (*run_options) {
  15908. if (!strcmp(*run_options, optname)) {
  15909. ports_option = run_options[1];
  15910. }
  15911. run_options += 2;
  15912. }
  15913. }
  15914. if (is_ssl_port_used(ports_option)) {
  15915. /* Initialize with SSL support */
  15916. mg_init_library(MG_FEATURES_TLS);
  15917. } else {
  15918. /* Initialize without SSL support */
  15919. mg_init_library(MG_FEATURES_DEFAULT);
  15920. }
  15921. }
  15922. tls.is_master = -1;
  15923. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15924. #if defined(_WIN32)
  15925. tls.pthread_cond_helper_mutex = NULL;
  15926. #endif
  15927. pthread_setspecific(sTlsKey, &tls);
  15928. ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr));
  15929. #if !defined(ALTERNATIVE_QUEUE)
  15930. ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL));
  15931. ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL));
  15932. #endif
  15933. ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr));
  15934. if (!ok) {
  15935. /* Fatal error - abort start. However, this situation should never
  15936. * occur in practice. */
  15937. mg_cry_ctx_internal(ctx,
  15938. "%s",
  15939. "Cannot initialize thread synchronization objects");
  15940. mg_free(ctx);
  15941. pthread_setspecific(sTlsKey, NULL);
  15942. return NULL;
  15943. }
  15944. if (callbacks) {
  15945. ctx->callbacks = *callbacks;
  15946. exit_callback = callbacks->exit_context;
  15947. ctx->callbacks.exit_context = 0;
  15948. }
  15949. ctx->user_data = user_data;
  15950. ctx->dd.handlers = NULL;
  15951. ctx->dd.next = NULL;
  15952. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15953. ctx->dd.shared_lua_websockets = NULL;
  15954. #endif
  15955. /* Store options */
  15956. while (options && (name = *options++) != NULL) {
  15957. if ((idx = get_option_index(name)) == -1) {
  15958. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  15959. free_context(ctx);
  15960. pthread_setspecific(sTlsKey, NULL);
  15961. return NULL;
  15962. } else if ((value = *options++) == NULL) {
  15963. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  15964. free_context(ctx);
  15965. pthread_setspecific(sTlsKey, NULL);
  15966. return NULL;
  15967. }
  15968. if (ctx->dd.config[idx] != NULL) {
  15969. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  15970. mg_free(ctx->dd.config[idx]);
  15971. }
  15972. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15973. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15974. }
  15975. /* Set default value if needed */
  15976. for (i = 0; config_options[i].name != NULL; i++) {
  15977. default_value = config_options[i].default_value;
  15978. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15979. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15980. }
  15981. }
  15982. /* Request size option */
  15983. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15984. if (itmp < 1024) {
  15985. mg_cry_ctx_internal(ctx, "%s", "max_request_size too small");
  15986. free_context(ctx);
  15987. pthread_setspecific(sTlsKey, NULL);
  15988. return NULL;
  15989. }
  15990. ctx->max_request_size = (unsigned)itmp;
  15991. /* Worker thread count option */
  15992. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15993. if (workerthreadcount > MAX_WORKER_THREADS) {
  15994. mg_cry_ctx_internal(ctx, "%s", "Too many worker threads");
  15995. free_context(ctx);
  15996. pthread_setspecific(sTlsKey, NULL);
  15997. return NULL;
  15998. }
  15999. if (workerthreadcount <= 0) {
  16000. mg_cry_ctx_internal(ctx, "%s", "Invalid number of worker threads");
  16001. free_context(ctx);
  16002. pthread_setspecific(sTlsKey, NULL);
  16003. return NULL;
  16004. }
  16005. /* Document root */
  16006. #if defined(NO_FILES)
  16007. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  16008. mg_cry_ctx_internal(ctx, "%s", "Document root must not be set");
  16009. free_context(ctx);
  16010. pthread_setspecific(sTlsKey, NULL);
  16011. return NULL;
  16012. }
  16013. #endif
  16014. get_system_name(&ctx->systemName);
  16015. #if defined(USE_LUA)
  16016. /* If a Lua background script has been configured, start it. */
  16017. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  16018. char ebuf[256];
  16019. struct vec opt_vec;
  16020. struct vec eq_vec;
  16021. const char *sparams;
  16022. lua_State *state = mg_prepare_lua_context_script(
  16023. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  16024. if (!state) {
  16025. mg_cry_ctx_internal(ctx, "lua_background_script error: %s", ebuf);
  16026. free_context(ctx);
  16027. pthread_setspecific(sTlsKey, NULL);
  16028. return NULL;
  16029. }
  16030. ctx->lua_background_state = (void *)state;
  16031. lua_newtable(state);
  16032. reg_boolean(state, "shutdown", 0);
  16033. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  16034. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  16035. reg_llstring(
  16036. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  16037. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  16038. break;
  16039. }
  16040. lua_setglobal(state, LUABACKGROUNDPARAMS);
  16041. } else {
  16042. ctx->lua_background_state = 0;
  16043. }
  16044. #endif
  16045. /* NOTE(lsm): order is important here. SSL certificates must
  16046. * be initialized before listening ports. UID must be set last. */
  16047. if (
  16048. #if !defined(NO_FILESYSTEMS)
  16049. !set_gpass_option(ctx, NULL) ||
  16050. #endif
  16051. #if !defined(NO_SSL)
  16052. !init_ssl_ctx(ctx, NULL) ||
  16053. #endif
  16054. !set_ports_option(ctx) ||
  16055. #if !defined(_WIN32)
  16056. !set_uid_option(ctx) ||
  16057. #endif
  16058. !set_acl_option(ctx)) {
  16059. free_context(ctx);
  16060. pthread_setspecific(sTlsKey, NULL);
  16061. return NULL;
  16062. }
  16063. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  16064. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16065. sizeof(pthread_t),
  16066. ctx);
  16067. if (ctx->worker_threadids == NULL) {
  16068. mg_cry_ctx_internal(ctx,
  16069. "%s",
  16070. "Not enough memory for worker thread ID array");
  16071. free_context(ctx);
  16072. pthread_setspecific(sTlsKey, NULL);
  16073. return NULL;
  16074. }
  16075. ctx->worker_connections =
  16076. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  16077. sizeof(struct mg_connection),
  16078. ctx);
  16079. if (ctx->worker_connections == NULL) {
  16080. mg_cry_ctx_internal(
  16081. ctx, "%s", "Not enough memory for worker thread connection array");
  16082. free_context(ctx);
  16083. pthread_setspecific(sTlsKey, NULL);
  16084. return NULL;
  16085. }
  16086. #if defined(ALTERNATIVE_QUEUE)
  16087. ctx->client_wait_events =
  16088. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  16089. ctx->cfg_worker_threads,
  16090. ctx);
  16091. if (ctx->client_wait_events == NULL) {
  16092. mg_cry_ctx_internal(ctx,
  16093. "%s",
  16094. "Not enough memory for worker event array");
  16095. mg_free(ctx->worker_threadids);
  16096. free_context(ctx);
  16097. pthread_setspecific(sTlsKey, NULL);
  16098. return NULL;
  16099. }
  16100. ctx->client_socks =
  16101. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  16102. ctx->cfg_worker_threads,
  16103. ctx);
  16104. if (ctx->client_socks == NULL) {
  16105. mg_cry_ctx_internal(ctx,
  16106. "%s",
  16107. "Not enough memory for worker socket array");
  16108. mg_free(ctx->client_wait_events);
  16109. mg_free(ctx->worker_threadids);
  16110. free_context(ctx);
  16111. pthread_setspecific(sTlsKey, NULL);
  16112. return NULL;
  16113. }
  16114. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  16115. ctx->client_wait_events[i] = event_create();
  16116. if (ctx->client_wait_events[i] == 0) {
  16117. mg_cry_ctx_internal(ctx, "Error creating worker event %i", i);
  16118. while (i > 0) {
  16119. i--;
  16120. event_destroy(ctx->client_wait_events[i]);
  16121. }
  16122. mg_free(ctx->client_socks);
  16123. mg_free(ctx->client_wait_events);
  16124. mg_free(ctx->worker_threadids);
  16125. free_context(ctx);
  16126. pthread_setspecific(sTlsKey, NULL);
  16127. return NULL;
  16128. }
  16129. }
  16130. #endif
  16131. #if defined(USE_TIMERS)
  16132. if (timers_init(ctx) != 0) {
  16133. mg_cry_ctx_internal(ctx, "%s", "Error creating timers");
  16134. free_context(ctx);
  16135. pthread_setspecific(sTlsKey, NULL);
  16136. return NULL;
  16137. }
  16138. #endif
  16139. /* Context has been created - init user libraries */
  16140. if (ctx->callbacks.init_context) {
  16141. ctx->callbacks.init_context(ctx);
  16142. }
  16143. ctx->callbacks.exit_context = exit_callback;
  16144. ctx->context_type = CONTEXT_SERVER; /* server context */
  16145. /* Start master (listening) thread */
  16146. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  16147. /* Start worker threads */
  16148. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  16149. /* worker_thread sets up the other fields */
  16150. ctx->worker_connections[i].phys_ctx = ctx;
  16151. if (mg_start_thread_with_id(worker_thread,
  16152. &ctx->worker_connections[i],
  16153. &ctx->worker_threadids[i])
  16154. != 0) {
  16155. /* thread was not created */
  16156. if (i > 0) {
  16157. mg_cry_ctx_internal(ctx,
  16158. "Cannot start worker thread %i: error %ld",
  16159. i + 1,
  16160. (long)ERRNO);
  16161. } else {
  16162. mg_cry_ctx_internal(ctx,
  16163. "Cannot create threads: error %ld",
  16164. (long)ERRNO);
  16165. free_context(ctx);
  16166. pthread_setspecific(sTlsKey, NULL);
  16167. return NULL;
  16168. }
  16169. break;
  16170. }
  16171. }
  16172. pthread_setspecific(sTlsKey, NULL);
  16173. return ctx;
  16174. }
  16175. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16176. /* Add an additional domain to an already running web server. */
  16177. int
  16178. mg_start_domain(struct mg_context *ctx, const char **options)
  16179. {
  16180. const char *name;
  16181. const char *value;
  16182. const char *default_value;
  16183. struct mg_domain_context *new_dom;
  16184. struct mg_domain_context *dom;
  16185. int idx, i;
  16186. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  16187. return -1;
  16188. }
  16189. new_dom = (struct mg_domain_context *)
  16190. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  16191. if (!new_dom) {
  16192. /* Out of memory */
  16193. return -6;
  16194. }
  16195. /* Store options - TODO: unite duplicate code */
  16196. while (options && (name = *options++) != NULL) {
  16197. if ((idx = get_option_index(name)) == -1) {
  16198. mg_cry_ctx_internal(ctx, "Invalid option: %s", name);
  16199. mg_free(new_dom);
  16200. return -2;
  16201. } else if ((value = *options++) == NULL) {
  16202. mg_cry_ctx_internal(ctx, "%s: option value cannot be NULL", name);
  16203. mg_free(new_dom);
  16204. return -2;
  16205. }
  16206. if (new_dom->config[idx] != NULL) {
  16207. mg_cry_ctx_internal(ctx, "warning: %s: duplicate option", name);
  16208. mg_free(new_dom->config[idx]);
  16209. }
  16210. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  16211. DEBUG_TRACE("[%s] -> [%s]", name, value);
  16212. }
  16213. /* Authentication domain is mandatory */
  16214. /* TODO: Maybe use a new option hostname? */
  16215. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  16216. mg_cry_ctx_internal(ctx, "%s", "authentication domain required");
  16217. mg_free(new_dom);
  16218. return -4;
  16219. }
  16220. /* Set default value if needed. Take the config value from
  16221. * ctx as a default value. */
  16222. for (i = 0; config_options[i].name != NULL; i++) {
  16223. default_value = ctx->dd.config[i];
  16224. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  16225. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  16226. }
  16227. }
  16228. new_dom->handlers = NULL;
  16229. new_dom->next = NULL;
  16230. new_dom->nonce_count = 0;
  16231. new_dom->auth_nonce_mask =
  16232. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  16233. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  16234. new_dom->shared_lua_websockets = NULL;
  16235. #endif
  16236. if (!init_ssl_ctx(ctx, new_dom)) {
  16237. /* Init SSL failed */
  16238. mg_free(new_dom);
  16239. return -3;
  16240. }
  16241. /* Add element to linked list. */
  16242. mg_lock_context(ctx);
  16243. idx = 0;
  16244. dom = &(ctx->dd);
  16245. for (;;) {
  16246. if (!mg_strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  16247. dom->config[AUTHENTICATION_DOMAIN])) {
  16248. /* Domain collision */
  16249. mg_cry_ctx_internal(ctx,
  16250. "domain %s already in use",
  16251. new_dom->config[AUTHENTICATION_DOMAIN]);
  16252. mg_free(new_dom);
  16253. return -5;
  16254. }
  16255. /* Count number of domains */
  16256. idx++;
  16257. if (dom->next == NULL) {
  16258. dom->next = new_dom;
  16259. break;
  16260. }
  16261. dom = dom->next;
  16262. }
  16263. mg_unlock_context(ctx);
  16264. /* Return domain number */
  16265. return idx;
  16266. }
  16267. #endif
  16268. /* Feature check API function */
  16269. unsigned
  16270. mg_check_feature(unsigned feature)
  16271. {
  16272. static const unsigned feature_set = 0
  16273. /* Set bits for available features according to API documentation.
  16274. * This bit mask is created at compile time, according to the active
  16275. * preprocessor defines. It is a single const value at runtime. */
  16276. #if !defined(NO_FILES)
  16277. | MG_FEATURES_FILES
  16278. #endif
  16279. #if !defined(NO_SSL)
  16280. | MG_FEATURES_SSL
  16281. #endif
  16282. #if !defined(NO_CGI)
  16283. | MG_FEATURES_CGI
  16284. #endif
  16285. #if defined(USE_IPV6)
  16286. | MG_FEATURES_IPV6
  16287. #endif
  16288. #if defined(USE_WEBSOCKET)
  16289. | MG_FEATURES_WEBSOCKET
  16290. #endif
  16291. #if defined(USE_LUA)
  16292. | MG_FEATURES_LUA
  16293. #endif
  16294. #if defined(USE_DUKTAPE)
  16295. | MG_FEATURES_SSJS
  16296. #endif
  16297. #if !defined(NO_CACHING)
  16298. | MG_FEATURES_CACHE
  16299. #endif
  16300. #if defined(USE_SERVER_STATS)
  16301. | MG_FEATURES_STATS
  16302. #endif
  16303. #if defined(USE_ZLIB)
  16304. | MG_FEATURES_COMPRESSION
  16305. #endif
  16306. /* Set some extra bits not defined in the API documentation.
  16307. * These bits may change without further notice. */
  16308. #if defined(MG_LEGACY_INTERFACE)
  16309. | 0x00008000u
  16310. #endif
  16311. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16312. | 0x00004000u
  16313. #endif
  16314. #if defined(MEMORY_DEBUGGING)
  16315. | 0x00001000u
  16316. #endif
  16317. #if defined(USE_TIMERS)
  16318. | 0x00020000u
  16319. #endif
  16320. #if !defined(NO_NONCE_CHECK)
  16321. | 0x00040000u
  16322. #endif
  16323. #if !defined(NO_POPEN)
  16324. | 0x00080000u
  16325. #endif
  16326. ;
  16327. return (feature & feature_set);
  16328. }
  16329. static size_t
  16330. mg_str_append(char **dst, char *end, const char *src)
  16331. {
  16332. size_t len = strlen(src);
  16333. if (*dst != end) {
  16334. /* Append src if enough space, or close dst. */
  16335. if ((size_t)(end - *dst) > len) {
  16336. strcpy(*dst, src);
  16337. *dst += len;
  16338. } else {
  16339. *dst = end;
  16340. }
  16341. }
  16342. return len;
  16343. }
  16344. /* Get system information. It can be printed or stored by the caller.
  16345. * Return the size of available information. */
  16346. int
  16347. mg_get_system_info(char *buffer, int buflen)
  16348. {
  16349. char *end, *append_eoobj = NULL, block[256];
  16350. size_t system_info_length = 0;
  16351. #if defined(_WIN32)
  16352. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16353. #else
  16354. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16355. #endif
  16356. if ((buffer == NULL) || (buflen < 1)) {
  16357. buflen = 0;
  16358. end = buffer;
  16359. } else {
  16360. *buffer = 0;
  16361. end = buffer + buflen;
  16362. }
  16363. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16364. /* has enough space to append eoobj */
  16365. append_eoobj = buffer;
  16366. end -= sizeof(eoobj) - 1;
  16367. }
  16368. system_info_length += mg_str_append(&buffer, end, "{");
  16369. /* Server version */
  16370. {
  16371. const char *version = mg_version();
  16372. mg_snprintf(NULL,
  16373. NULL,
  16374. block,
  16375. sizeof(block),
  16376. "%s\"version\" : \"%s\"",
  16377. eol,
  16378. version);
  16379. system_info_length += mg_str_append(&buffer, end, block);
  16380. }
  16381. /* System info */
  16382. {
  16383. #if defined(_WIN32)
  16384. DWORD dwVersion = 0;
  16385. DWORD dwMajorVersion = 0;
  16386. DWORD dwMinorVersion = 0;
  16387. SYSTEM_INFO si;
  16388. GetSystemInfo(&si);
  16389. #if defined(_MSC_VER)
  16390. #pragma warning(push)
  16391. /* GetVersion was declared deprecated */
  16392. #pragma warning(disable : 4996)
  16393. #endif
  16394. dwVersion = GetVersion();
  16395. #if defined(_MSC_VER)
  16396. #pragma warning(pop)
  16397. #endif
  16398. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  16399. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  16400. mg_snprintf(NULL,
  16401. NULL,
  16402. block,
  16403. sizeof(block),
  16404. ",%s\"os\" : \"Windows %u.%u\"",
  16405. eol,
  16406. (unsigned)dwMajorVersion,
  16407. (unsigned)dwMinorVersion);
  16408. system_info_length += mg_str_append(&buffer, end, block);
  16409. mg_snprintf(NULL,
  16410. NULL,
  16411. block,
  16412. sizeof(block),
  16413. ",%s\"cpu\" : \"type %u, cores %u, mask %x\"",
  16414. eol,
  16415. (unsigned)si.wProcessorArchitecture,
  16416. (unsigned)si.dwNumberOfProcessors,
  16417. (unsigned)si.dwActiveProcessorMask);
  16418. system_info_length += mg_str_append(&buffer, end, block);
  16419. #else
  16420. struct utsname name;
  16421. memset(&name, 0, sizeof(name));
  16422. uname(&name);
  16423. mg_snprintf(NULL,
  16424. NULL,
  16425. block,
  16426. sizeof(block),
  16427. ",%s\"os\" : \"%s %s (%s) - %s\"",
  16428. eol,
  16429. name.sysname,
  16430. name.version,
  16431. name.release,
  16432. name.machine);
  16433. system_info_length += mg_str_append(&buffer, end, block);
  16434. #endif
  16435. }
  16436. /* Features */
  16437. {
  16438. mg_snprintf(NULL,
  16439. NULL,
  16440. block,
  16441. sizeof(block),
  16442. ",%s\"features\" : %lu"
  16443. ",%s\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\"",
  16444. eol,
  16445. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  16446. eol,
  16447. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  16448. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  16449. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  16450. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  16451. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  16452. : "",
  16453. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  16454. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  16455. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  16456. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "");
  16457. system_info_length += mg_str_append(&buffer, end, block);
  16458. #if defined(USE_LUA)
  16459. mg_snprintf(NULL,
  16460. NULL,
  16461. block,
  16462. sizeof(block),
  16463. ",%s\"lua_version\" : \"%u (%s)\"",
  16464. eol,
  16465. (unsigned)LUA_VERSION_NUM,
  16466. LUA_RELEASE);
  16467. system_info_length += mg_str_append(&buffer, end, block);
  16468. #endif
  16469. #if defined(USE_DUKTAPE)
  16470. mg_snprintf(NULL,
  16471. NULL,
  16472. block,
  16473. sizeof(block),
  16474. ",%s\"javascript\" : \"Duktape %u.%u.%u\"",
  16475. eol,
  16476. (unsigned)DUK_VERSION / 10000,
  16477. ((unsigned)DUK_VERSION / 100) % 100,
  16478. (unsigned)DUK_VERSION % 100);
  16479. system_info_length += mg_str_append(&buffer, end, block);
  16480. #endif
  16481. }
  16482. /* Build date */
  16483. {
  16484. #if defined(GCC_DIAGNOSTIC)
  16485. #if GCC_VERSION >= 40900
  16486. #pragma GCC diagnostic push
  16487. /* Disable bogus compiler warning -Wdate-time, appeared in gcc5 */
  16488. #pragma GCC diagnostic ignored "-Wdate-time"
  16489. #endif
  16490. #endif
  16491. mg_snprintf(NULL,
  16492. NULL,
  16493. block,
  16494. sizeof(block),
  16495. ",%s\"build\" : \"%s\"",
  16496. eol,
  16497. __DATE__);
  16498. #if defined(GCC_DIAGNOSTIC)
  16499. #if GCC_VERSION >= 40900
  16500. #pragma GCC diagnostic pop
  16501. #endif
  16502. #endif
  16503. system_info_length += mg_str_append(&buffer, end, block);
  16504. }
  16505. /* Compiler information */
  16506. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  16507. {
  16508. #if defined(_MSC_VER)
  16509. mg_snprintf(NULL,
  16510. NULL,
  16511. block,
  16512. sizeof(block),
  16513. ",%s\"compiler\" : \"MSC: %u (%u)\"",
  16514. eol,
  16515. (unsigned)_MSC_VER,
  16516. (unsigned)_MSC_FULL_VER);
  16517. system_info_length += mg_str_append(&buffer, end, block);
  16518. #elif defined(__MINGW64__)
  16519. mg_snprintf(NULL,
  16520. NULL,
  16521. block,
  16522. sizeof(block),
  16523. ",%s\"compiler\" : \"MinGW64: %u.%u\"",
  16524. eol,
  16525. (unsigned)__MINGW64_VERSION_MAJOR,
  16526. (unsigned)__MINGW64_VERSION_MINOR);
  16527. system_info_length += mg_str_append(&buffer, end, block);
  16528. mg_snprintf(NULL,
  16529. NULL,
  16530. block,
  16531. sizeof(block),
  16532. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16533. eol,
  16534. (unsigned)__MINGW32_MAJOR_VERSION,
  16535. (unsigned)__MINGW32_MINOR_VERSION);
  16536. system_info_length += mg_str_append(&buffer, end, block);
  16537. #elif defined(__MINGW32__)
  16538. mg_snprintf(NULL,
  16539. NULL,
  16540. block,
  16541. sizeof(block),
  16542. ",%s\"compiler\" : \"MinGW32: %u.%u\"",
  16543. eol,
  16544. (unsigned)__MINGW32_MAJOR_VERSION,
  16545. (unsigned)__MINGW32_MINOR_VERSION);
  16546. system_info_length += mg_str_append(&buffer, end, block);
  16547. #elif defined(__clang__)
  16548. mg_snprintf(NULL,
  16549. NULL,
  16550. block,
  16551. sizeof(block),
  16552. ",%s\"compiler\" : \"clang: %u.%u.%u (%s)\"",
  16553. eol,
  16554. __clang_major__,
  16555. __clang_minor__,
  16556. __clang_patchlevel__,
  16557. __clang_version__);
  16558. system_info_length += mg_str_append(&buffer, end, block);
  16559. #elif defined(__GNUC__)
  16560. mg_snprintf(NULL,
  16561. NULL,
  16562. block,
  16563. sizeof(block),
  16564. ",%s\"compiler\" : \"gcc: %u.%u.%u\"",
  16565. eol,
  16566. (unsigned)__GNUC__,
  16567. (unsigned)__GNUC_MINOR__,
  16568. (unsigned)__GNUC_PATCHLEVEL__);
  16569. system_info_length += mg_str_append(&buffer, end, block);
  16570. #elif defined(__INTEL_COMPILER)
  16571. mg_snprintf(NULL,
  16572. NULL,
  16573. block,
  16574. sizeof(block),
  16575. ",%s\"compiler\" : \"Intel C/C++: %u\"",
  16576. eol,
  16577. (unsigned)__INTEL_COMPILER);
  16578. system_info_length += mg_str_append(&buffer, end, block);
  16579. #elif defined(__BORLANDC__)
  16580. mg_snprintf(NULL,
  16581. NULL,
  16582. block,
  16583. sizeof(block),
  16584. ",%s\"compiler\" : \"Borland C: 0x%x\"",
  16585. eol,
  16586. (unsigned)__BORLANDC__);
  16587. system_info_length += mg_str_append(&buffer, end, block);
  16588. #elif defined(__SUNPRO_C)
  16589. mg_snprintf(NULL,
  16590. NULL,
  16591. block,
  16592. sizeof(block),
  16593. ",%s\"compiler\" : \"Solaris: 0x%x\"",
  16594. eol,
  16595. (unsigned)__SUNPRO_C);
  16596. system_info_length += mg_str_append(&buffer, end, block);
  16597. #else
  16598. mg_snprintf(NULL,
  16599. NULL,
  16600. block,
  16601. sizeof(block),
  16602. ",%s\"compiler\" : \"other\"",
  16603. eol);
  16604. system_info_length += mg_str_append(&buffer, end, block);
  16605. #endif
  16606. }
  16607. /* Determine 32/64 bit data mode.
  16608. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16609. {
  16610. mg_snprintf(NULL,
  16611. NULL,
  16612. block,
  16613. sizeof(block),
  16614. ",%s\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16615. "char:%u/%u, "
  16616. "ptr:%u, size:%u, time:%u\"",
  16617. eol,
  16618. (unsigned)sizeof(short),
  16619. (unsigned)sizeof(int),
  16620. (unsigned)sizeof(long),
  16621. (unsigned)sizeof(long long),
  16622. (unsigned)sizeof(float),
  16623. (unsigned)sizeof(double),
  16624. (unsigned)sizeof(long double),
  16625. (unsigned)sizeof(char),
  16626. (unsigned)sizeof(wchar_t),
  16627. (unsigned)sizeof(void *),
  16628. (unsigned)sizeof(size_t),
  16629. (unsigned)sizeof(time_t));
  16630. system_info_length += mg_str_append(&buffer, end, block);
  16631. }
  16632. /* Terminate string */
  16633. if (append_eoobj) {
  16634. strcat(append_eoobj, eoobj);
  16635. }
  16636. system_info_length += sizeof(eoobj) - 1;
  16637. return (int)system_info_length;
  16638. }
  16639. /* Get context information. It can be printed or stored by the caller.
  16640. * Return the size of available information. */
  16641. int
  16642. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16643. {
  16644. #if defined(USE_SERVER_STATS)
  16645. char *end, *append_eoobj = NULL, block[256];
  16646. size_t context_info_length = 0;
  16647. #if defined(_WIN32)
  16648. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16649. #else
  16650. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16651. #endif
  16652. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16653. if ((buffer == NULL) || (buflen < 1)) {
  16654. buflen = 0;
  16655. end = buffer;
  16656. } else {
  16657. *buffer = 0;
  16658. end = buffer + buflen;
  16659. }
  16660. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16661. /* has enough space to append eoobj */
  16662. append_eoobj = buffer;
  16663. end -= sizeof(eoobj) - 1;
  16664. }
  16665. context_info_length += mg_str_append(&buffer, end, "{");
  16666. if (ms) { /* <-- should be always true */
  16667. /* Memory information */
  16668. mg_snprintf(NULL,
  16669. NULL,
  16670. block,
  16671. sizeof(block),
  16672. "%s\"memory\" : {%s"
  16673. "\"blocks\" : %i,%s"
  16674. "\"used\" : %" INT64_FMT ",%s"
  16675. "\"maxUsed\" : %" INT64_FMT "%s"
  16676. "}",
  16677. eol,
  16678. eol,
  16679. ms->blockCount,
  16680. eol,
  16681. ms->totalMemUsed,
  16682. eol,
  16683. ms->maxMemUsed,
  16684. eol);
  16685. context_info_length += mg_str_append(&buffer, end, block);
  16686. }
  16687. if (ctx) {
  16688. /* Declare all variables at begin of the block, to comply
  16689. * with old C standards. */
  16690. char start_time_str[64] = {0};
  16691. char now_str[64] = {0};
  16692. time_t start_time = ctx->start_time;
  16693. time_t now = time(NULL);
  16694. /* Connections information */
  16695. mg_snprintf(NULL,
  16696. NULL,
  16697. block,
  16698. sizeof(block),
  16699. ",%s\"connections\" : {%s"
  16700. "\"active\" : %i,%s"
  16701. "\"maxActive\" : %i,%s"
  16702. "\"total\" : %" INT64_FMT "%s"
  16703. "}",
  16704. eol,
  16705. eol,
  16706. ctx->active_connections,
  16707. eol,
  16708. ctx->max_connections,
  16709. eol,
  16710. ctx->total_connections,
  16711. eol);
  16712. context_info_length += mg_str_append(&buffer, end, block);
  16713. /* Requests information */
  16714. mg_snprintf(NULL,
  16715. NULL,
  16716. block,
  16717. sizeof(block),
  16718. ",%s\"requests\" : {%s"
  16719. "\"total\" : %" INT64_FMT "%s"
  16720. "}",
  16721. eol,
  16722. eol,
  16723. ctx->total_requests,
  16724. eol);
  16725. context_info_length += mg_str_append(&buffer, end, block);
  16726. /* Data information */
  16727. mg_snprintf(NULL,
  16728. NULL,
  16729. block,
  16730. sizeof(block),
  16731. ",%s\"data\" : {%s"
  16732. "\"read\" : %" INT64_FMT ",%s"
  16733. "\"written\" : %" INT64_FMT "%s"
  16734. "}",
  16735. eol,
  16736. eol,
  16737. ctx->total_data_read,
  16738. eol,
  16739. ctx->total_data_written,
  16740. eol);
  16741. context_info_length += mg_str_append(&buffer, end, block);
  16742. /* Execution time information */
  16743. gmt_time_string(start_time_str,
  16744. sizeof(start_time_str) - 1,
  16745. &start_time);
  16746. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16747. mg_snprintf(NULL,
  16748. NULL,
  16749. block,
  16750. sizeof(block),
  16751. ",%s\"time\" : {%s"
  16752. "\"uptime\" : %.0f,%s"
  16753. "\"start\" : \"%s\",%s"
  16754. "\"now\" : \"%s\"%s"
  16755. "}",
  16756. eol,
  16757. eol,
  16758. difftime(now, start_time),
  16759. eol,
  16760. start_time_str,
  16761. eol,
  16762. now_str,
  16763. eol);
  16764. context_info_length += mg_str_append(&buffer, end, block);
  16765. }
  16766. /* Terminate string */
  16767. if (append_eoobj) {
  16768. strcat(append_eoobj, eoobj);
  16769. }
  16770. context_info_length += sizeof(eoobj) - 1;
  16771. return (int)context_info_length;
  16772. #else
  16773. (void)ctx;
  16774. if ((buffer != NULL) && (buflen > 0)) {
  16775. *buffer = 0;
  16776. }
  16777. return 0;
  16778. #endif
  16779. }
  16780. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16781. /* Get connection information. It can be printed or stored by the caller.
  16782. * Return the size of available information. */
  16783. int
  16784. mg_get_connection_info(const struct mg_context *ctx,
  16785. int idx,
  16786. char *buffer,
  16787. int buflen)
  16788. {
  16789. const struct mg_connection *conn;
  16790. const struct mg_request_info *ri;
  16791. char *end, *append_eoobj = NULL, block[256];
  16792. size_t connection_info_length = 0;
  16793. int state = 0;
  16794. const char *state_str = "unknown";
  16795. #if defined(_WIN32)
  16796. static const char eol[] = "\r\n", eoobj[] = "\r\n}\r\n";
  16797. #else
  16798. static const char eol[] = "\n", eoobj[] = "\n}\n";
  16799. #endif
  16800. if ((buffer == NULL) || (buflen < 1)) {
  16801. buflen = 0;
  16802. end = buffer;
  16803. } else {
  16804. *buffer = 0;
  16805. end = buffer + buflen;
  16806. }
  16807. if (buflen > (int)(sizeof(eoobj) - 1)) {
  16808. /* has enough space to append eoobj */
  16809. append_eoobj = buffer;
  16810. end -= sizeof(eoobj) - 1;
  16811. }
  16812. if ((ctx == NULL) || (idx < 0)) {
  16813. /* Parameter error */
  16814. return 0;
  16815. }
  16816. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16817. /* Out of range */
  16818. return 0;
  16819. }
  16820. /* Take connection [idx]. This connection is not locked in
  16821. * any way, so some other thread might use it. */
  16822. conn = (ctx->worker_connections) + idx;
  16823. /* Initialize output string */
  16824. connection_info_length += mg_str_append(&buffer, end, "{");
  16825. /* Init variables */
  16826. ri = &(conn->request_info);
  16827. #if defined(USE_SERVER_STATS)
  16828. state = conn->conn_state;
  16829. /* State as string */
  16830. switch (state) {
  16831. case 0:
  16832. state_str = "undefined";
  16833. break;
  16834. case 1:
  16835. state_str = "not used";
  16836. break;
  16837. case 2:
  16838. state_str = "init";
  16839. break;
  16840. case 3:
  16841. state_str = "ready";
  16842. break;
  16843. case 4:
  16844. state_str = "processing";
  16845. break;
  16846. case 5:
  16847. state_str = "processed";
  16848. break;
  16849. case 6:
  16850. state_str = "to close";
  16851. break;
  16852. case 7:
  16853. state_str = "closing";
  16854. break;
  16855. case 8:
  16856. state_str = "closed";
  16857. break;
  16858. case 9:
  16859. state_str = "done";
  16860. break;
  16861. }
  16862. #endif
  16863. /* Connection info */
  16864. if ((state >= 3) && (state < 9)) {
  16865. mg_snprintf(NULL,
  16866. NULL,
  16867. block,
  16868. sizeof(block),
  16869. "%s\"connection\" : {%s"
  16870. "\"remote\" : {%s"
  16871. "\"protocol\" : \"%s\",%s"
  16872. "\"addr\" : \"%s\",%s"
  16873. "\"port\" : %u%s"
  16874. "},%s"
  16875. "\"handled_requests\" : %u%s"
  16876. "}",
  16877. eol,
  16878. eol,
  16879. eol,
  16880. get_proto_name(conn),
  16881. eol,
  16882. ri->remote_addr,
  16883. eol,
  16884. ri->remote_port,
  16885. eol,
  16886. eol,
  16887. conn->handled_requests,
  16888. eol);
  16889. connection_info_length += mg_str_append(&buffer, end, block);
  16890. }
  16891. /* Request info */
  16892. if ((state >= 4) && (state < 6)) {
  16893. mg_snprintf(NULL,
  16894. NULL,
  16895. block,
  16896. sizeof(block),
  16897. "%s%s\"request_info\" : {%s"
  16898. "\"method\" : \"%s\",%s"
  16899. "\"uri\" : \"%s\",%s"
  16900. "\"query\" : %s%s%s%s"
  16901. "}",
  16902. (connection_info_length > 1 ? "," : ""),
  16903. eol,
  16904. eol,
  16905. ri->request_method,
  16906. eol,
  16907. ri->request_uri,
  16908. eol,
  16909. ri->query_string ? "\"" : "",
  16910. ri->query_string ? ri->query_string : "null",
  16911. ri->query_string ? "\"" : "",
  16912. eol);
  16913. connection_info_length += mg_str_append(&buffer, end, block);
  16914. }
  16915. /* Execution time information */
  16916. if ((state >= 2) && (state < 9)) {
  16917. char start_time_str[64] = {0};
  16918. char now_str[64] = {0};
  16919. time_t start_time = conn->conn_birth_time;
  16920. time_t now = time(NULL);
  16921. gmt_time_string(start_time_str,
  16922. sizeof(start_time_str) - 1,
  16923. &start_time);
  16924. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16925. mg_snprintf(NULL,
  16926. NULL,
  16927. block,
  16928. sizeof(block),
  16929. "%s%s\"time\" : {%s"
  16930. "\"uptime\" : %.0f,%s"
  16931. "\"start\" : \"%s\",%s"
  16932. "\"now\" : \"%s\"%s"
  16933. "}",
  16934. (connection_info_length > 1 ? "," : ""),
  16935. eol,
  16936. eol,
  16937. difftime(now, start_time),
  16938. eol,
  16939. start_time_str,
  16940. eol,
  16941. now_str,
  16942. eol);
  16943. connection_info_length += mg_str_append(&buffer, end, block);
  16944. }
  16945. /* Remote user name */
  16946. if ((ri->remote_user) && (state < 9)) {
  16947. mg_snprintf(NULL,
  16948. NULL,
  16949. block,
  16950. sizeof(block),
  16951. "%s%s\"user\" : {%s"
  16952. "\"name\" : \"%s\",%s"
  16953. "}",
  16954. (connection_info_length > 1 ? "," : ""),
  16955. eol,
  16956. eol,
  16957. ri->remote_user,
  16958. eol);
  16959. connection_info_length += mg_str_append(&buffer, end, block);
  16960. }
  16961. /* Data block */
  16962. if (state >= 3) {
  16963. mg_snprintf(NULL,
  16964. NULL,
  16965. block,
  16966. sizeof(block),
  16967. "%s%s\"data\" : {%s"
  16968. "\"read\" : %" INT64_FMT ",%s"
  16969. "\"written\" : %" INT64_FMT "%s"
  16970. "}",
  16971. (connection_info_length > 1 ? "," : ""),
  16972. eol,
  16973. eol,
  16974. conn->consumed_content,
  16975. eol,
  16976. conn->num_bytes_sent,
  16977. eol);
  16978. connection_info_length += mg_str_append(&buffer, end, block);
  16979. }
  16980. /* State */
  16981. mg_snprintf(NULL,
  16982. NULL,
  16983. block,
  16984. sizeof(block),
  16985. "%s%s\"state\" : \"%s\"",
  16986. (connection_info_length > 1 ? "," : ""),
  16987. eol,
  16988. state_str);
  16989. connection_info_length += mg_str_append(&buffer, end, block);
  16990. /* Terminate string */
  16991. if (append_eoobj) {
  16992. strcat(append_eoobj, eoobj);
  16993. }
  16994. connection_info_length += sizeof(eoobj) - 1;
  16995. return (int)connection_info_length;
  16996. }
  16997. #endif
  16998. /* Initialize this library. This function does not need to be thread safe.
  16999. */
  17000. unsigned
  17001. mg_init_library(unsigned features)
  17002. {
  17003. #if !defined(NO_SSL)
  17004. char ebuf[128];
  17005. #endif
  17006. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  17007. unsigned features_inited = features_to_init;
  17008. if (mg_init_library_called <= 0) {
  17009. /* Not initialized yet */
  17010. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  17011. return 0;
  17012. }
  17013. }
  17014. mg_global_lock();
  17015. if (mg_init_library_called <= 0) {
  17016. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  17017. /* Fatal error - abort start. However, this situation should
  17018. * never occur in practice. */
  17019. mg_global_unlock();
  17020. return 0;
  17021. }
  17022. #if defined(_WIN32)
  17023. (void)pthread_mutex_init(&global_log_file_lock, &pthread_mutex_attr);
  17024. #else
  17025. pthread_mutexattr_init(&pthread_mutex_attr);
  17026. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  17027. #endif
  17028. #if defined(USE_LUA)
  17029. lua_init_optional_libraries();
  17030. #endif
  17031. }
  17032. mg_global_unlock();
  17033. #if !defined(NO_SSL)
  17034. if (features_to_init & MG_FEATURES_SSL) {
  17035. if (!mg_ssl_initialized) {
  17036. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  17037. mg_ssl_initialized = 1;
  17038. } else {
  17039. (void)ebuf;
  17040. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  17041. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  17042. }
  17043. } else {
  17044. /* ssl already initialized */
  17045. }
  17046. }
  17047. #endif
  17048. /* Start WinSock for Windows */
  17049. mg_global_lock();
  17050. if (mg_init_library_called <= 0) {
  17051. #if defined(_WIN32)
  17052. WSADATA data;
  17053. WSAStartup(MAKEWORD(2, 2), &data);
  17054. #endif /* _WIN32 */
  17055. mg_init_library_called = 1;
  17056. } else {
  17057. mg_init_library_called++;
  17058. }
  17059. mg_global_unlock();
  17060. return features_inited;
  17061. }
  17062. /* Un-initialize this library. */
  17063. unsigned
  17064. mg_exit_library(void)
  17065. {
  17066. if (mg_init_library_called <= 0) {
  17067. return 0;
  17068. }
  17069. mg_global_lock();
  17070. mg_init_library_called--;
  17071. if (mg_init_library_called == 0) {
  17072. #if defined(_WIN32)
  17073. (void)WSACleanup();
  17074. #endif /* _WIN32 */
  17075. #if !defined(NO_SSL)
  17076. if (mg_ssl_initialized) {
  17077. uninitialize_ssl();
  17078. mg_ssl_initialized = 0;
  17079. }
  17080. #endif
  17081. #if defined(_WIN32)
  17082. (void)pthread_mutex_destroy(&global_log_file_lock);
  17083. #else
  17084. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  17085. #endif
  17086. (void)pthread_key_delete(sTlsKey);
  17087. #if defined(USE_LUA)
  17088. lua_exit_optional_libraries();
  17089. #endif
  17090. mg_global_unlock();
  17091. (void)pthread_mutex_destroy(&global_lock_mutex);
  17092. return 1;
  17093. }
  17094. mg_global_unlock();
  17095. return 1;
  17096. }
  17097. /* End of civetweb.c */