civetweb.c 515 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303
  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. /* Disable unused macros warnings - not all defines are required
  24. * for all systems and all compilers. */
  25. #pragma GCC diagnostic ignored "-Wunused-macros"
  26. /* A padding warning is just plain useless */
  27. #pragma GCC diagnostic ignored "-Wpadded"
  28. #endif
  29. #if defined(__clang__) /* GCC does not (yet) support this pragma */
  30. /* We must set some flags for the headers we include. These flags
  31. * are reserved ids according to C99, so we need to disable a
  32. * warning for that. */
  33. #pragma GCC diagnostic push
  34. #pragma GCC diagnostic ignored "-Wreserved-id-macro"
  35. #endif
  36. #if defined(_WIN32)
  37. #if !defined(_CRT_SECURE_NO_WARNINGS)
  38. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  39. #endif
  40. #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */
  41. #define _WIN32_WINNT 0x0501
  42. #endif
  43. #else
  44. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  45. #define _GNU_SOURCE /* for setgroups() */
  46. #endif
  47. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  48. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  49. #endif
  50. #if !defined(_LARGEFILE_SOURCE)
  51. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  52. #endif
  53. #if !defined(_FILE_OFFSET_BITS)
  54. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  55. #endif
  56. #if !defined(__STDC_FORMAT_MACROS)
  57. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  58. #endif
  59. #if !defined(__STDC_LIMIT_MACROS)
  60. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  61. #endif
  62. #if !defined(_DARWIN_UNLIMITED_SELECT)
  63. #define _DARWIN_UNLIMITED_SELECT
  64. #endif
  65. #if defined(__sun)
  66. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  67. #define __inline inline /* not recognized on older compiler versions */
  68. #endif
  69. #endif
  70. #if defined(__clang__)
  71. /* Enable reserved-id-macro warning again. */
  72. #pragma GCC diagnostic pop
  73. #endif
  74. #if defined(USE_LUA)
  75. #define USE_TIMERS
  76. #endif
  77. #if defined(_MSC_VER)
  78. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  79. #pragma warning(disable : 4306)
  80. /* conditional expression is constant: introduced by FD_SET(..) */
  81. #pragma warning(disable : 4127)
  82. /* non-constant aggregate initializer: issued due to missing C99 support */
  83. #pragma warning(disable : 4204)
  84. /* padding added after data member */
  85. #pragma warning(disable : 4820)
  86. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  87. #pragma warning(disable : 4668)
  88. /* no function prototype given: converting '()' to '(void)' */
  89. #pragma warning(disable : 4255)
  90. /* function has been selected for automatic inline expansion */
  91. #pragma warning(disable : 4711)
  92. #endif
  93. /* This code uses static_assert to check some conditions.
  94. * Unfortunately some compilers still do not support it, so we have a
  95. * replacement function here. */
  96. #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L
  97. #define mg_static_assert _Static_assert
  98. #elif defined(__cplusplus) && __cplusplus >= 201103L
  99. #define mg_static_assert static_assert
  100. #else
  101. char static_assert_replacement[1];
  102. #define mg_static_assert(cond, txt) \
  103. extern char static_assert_replacement[(cond) ? 1 : -1]
  104. #endif
  105. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  106. "int data type size check");
  107. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  108. "pointer data type size check");
  109. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  110. /* Alternative queue is well tested and should be the new default */
  111. #if defined(NO_ALTERNATIVE_QUEUE)
  112. #if defined(ALTERNATIVE_QUEUE)
  113. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  114. #endif
  115. #else
  116. #define ALTERNATIVE_QUEUE
  117. #endif
  118. /* DTL -- including winsock2.h works better if lean and mean */
  119. #if !defined(WIN32_LEAN_AND_MEAN)
  120. #define WIN32_LEAN_AND_MEAN
  121. #endif
  122. #if defined(__SYMBIAN32__)
  123. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  124. * Symbian is no longer maintained since 2014-01-01.
  125. * Recent versions of CivetWeb are no longer tested for Symbian.
  126. * It makes no sense, to support an abandoned operating system.
  127. * All remaining "#ifdef __SYMBIAN__" cases will be dropped from
  128. * the code sooner or later.
  129. */
  130. #pragma message \
  131. "Symbian is no longer maintained. CivetWeb will drop Symbian support."
  132. #define NO_SSL /* SSL is not supported */
  133. #define NO_CGI /* CGI is not supported */
  134. #define PATH_MAX FILENAME_MAX
  135. #endif /* __SYMBIAN32__ */
  136. #if !defined(CIVETWEB_HEADER_INCLUDED)
  137. /* Include the header file here, so the CivetWeb interface is defined for the
  138. * entire implementation, including the following forward definitions. */
  139. #include "civetweb.h"
  140. #endif
  141. #if !defined(DEBUG_TRACE)
  142. #if defined(DEBUG)
  143. static void DEBUG_TRACE_FUNC(const char *func,
  144. unsigned line,
  145. PRINTF_FORMAT_STRING(const char *fmt),
  146. ...) PRINTF_ARGS(3, 4);
  147. #define DEBUG_TRACE(fmt, ...) \
  148. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  149. #define NEED_DEBUG_TRACE_FUNC
  150. #else
  151. #define DEBUG_TRACE(fmt, ...) \
  152. do { \
  153. } while (0)
  154. #endif /* DEBUG */
  155. #endif /* DEBUG_TRACE */
  156. #if !defined(DEBUG_ASSERT)
  157. #if defined(DEBUG)
  158. #define DEBUG_ASSERT(cond) \
  159. do { \
  160. if (!(cond)) { \
  161. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  162. exit(2); /* Exit with error */ \
  163. } \
  164. } while (0)
  165. #else
  166. #define DEBUG_ASSERT(cond)
  167. #endif /* DEBUG */
  168. #endif
  169. #if !defined(IGNORE_UNUSED_RESULT)
  170. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  171. #endif
  172. #if defined(__GNUC__) || defined(__MINGW32__)
  173. /* GCC unused function attribute seems fundamentally broken.
  174. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  175. * OR UNUSED" for individual functions failed.
  176. * Either the compiler creates an "unused-function" warning if a
  177. * function is not marked with __attribute__((unused)).
  178. * On the other hand, if the function is marked with this attribute,
  179. * but is used, the compiler raises a completely idiotic
  180. * "used-but-marked-unused" warning - and
  181. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  182. * raises error: unknown option after "#pragma GCC diagnostic".
  183. * Disable this warning completely, until the GCC guys sober up
  184. * again.
  185. */
  186. #pragma GCC diagnostic ignored "-Wunused-function"
  187. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  188. #else
  189. #define FUNCTION_MAY_BE_UNUSED
  190. #endif
  191. /* Some ANSI #includes are not available on Windows CE */
  192. #if !defined(_WIN32_WCE)
  193. #include <sys/types.h>
  194. #include <sys/stat.h>
  195. #include <errno.h>
  196. #include <signal.h>
  197. #include <fcntl.h>
  198. #endif /* !_WIN32_WCE */
  199. #if defined(__clang__)
  200. /* When using -Weverything, clang does not accept it's own headers
  201. * in a release build configuration. Disable what is too much in
  202. * -Weverything. */
  203. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  204. #endif
  205. #if defined(__GNUC__) || defined(__MINGW32__)
  206. /* Who on earth came to the conclusion, using __DATE__ should rise
  207. * an "expansion of date or time macro is not reproducible"
  208. * warning. That's exactly what was intended by using this macro.
  209. * Just disable this nonsense warning. */
  210. /* And disabling them does not work either:
  211. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  212. * #pragma clang diagnostic ignored "-Wdate-time"
  213. * So we just have to disable ALL warnings for some lines
  214. * of code.
  215. * This seems to be a known GCC bug, not resolved since 2012:
  216. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  217. */
  218. #endif
  219. #if defined(__MACH__) /* Apple OSX section */
  220. #if defined(__clang__)
  221. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  222. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  223. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  224. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  225. #endif
  226. #endif
  227. #define CLOCK_MONOTONIC (1)
  228. #define CLOCK_REALTIME (2)
  229. #include <sys/errno.h>
  230. #include <sys/time.h>
  231. #include <mach/clock.h>
  232. #include <mach/mach.h>
  233. #include <mach/mach_time.h>
  234. /* clock_gettime is not implemented on OSX prior to 10.12 */
  235. static int
  236. _civet_clock_gettime(int clk_id, struct timespec *t)
  237. {
  238. memset(t, 0, sizeof(*t));
  239. if (clk_id == CLOCK_REALTIME) {
  240. struct timeval now;
  241. int rv = gettimeofday(&now, NULL);
  242. if (rv) {
  243. return rv;
  244. }
  245. t->tv_sec = now.tv_sec;
  246. t->tv_nsec = now.tv_usec * 1000;
  247. return 0;
  248. } else if (clk_id == CLOCK_MONOTONIC) {
  249. static uint64_t clock_start_time = 0;
  250. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  251. uint64_t now = mach_absolute_time();
  252. if (clock_start_time == 0) {
  253. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  254. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  255. /* appease "unused variable" warning for release builds */
  256. (void)mach_status;
  257. clock_start_time = now;
  258. }
  259. now = (uint64_t)((double)(now - clock_start_time)
  260. * (double)timebase_ifo.numer
  261. / (double)timebase_ifo.denom);
  262. t->tv_sec = now / 1000000000;
  263. t->tv_nsec = now % 1000000000;
  264. return 0;
  265. }
  266. return -1; /* EINVAL - Clock ID is unknown */
  267. }
  268. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  269. #if defined(__CLOCK_AVAILABILITY)
  270. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  271. * declared but it may be NULL at runtime. So we need to check before using
  272. * it. */
  273. static int
  274. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  275. {
  276. if (clock_gettime) {
  277. return clock_gettime(clk_id, t);
  278. }
  279. return _civet_clock_gettime(clk_id, t);
  280. }
  281. #define clock_gettime _civet_safe_clock_gettime
  282. #else
  283. #define clock_gettime _civet_clock_gettime
  284. #endif
  285. #endif
  286. #include <time.h>
  287. #include <stdlib.h>
  288. #include <stdarg.h>
  289. #include <string.h>
  290. #include <ctype.h>
  291. #include <limits.h>
  292. #include <stddef.h>
  293. #include <stdio.h>
  294. #include <stdint.h>
  295. #if !defined(INT64_MAX)
  296. #define INT64_MAX (9223372036854775807)
  297. #endif
  298. #if !defined(MAX_WORKER_THREADS)
  299. #define MAX_WORKER_THREADS (1024 * 64)
  300. #endif
  301. #if !defined(SOCKET_TIMEOUT_QUANTUM) /* in ms */
  302. #define SOCKET_TIMEOUT_QUANTUM (2000)
  303. #endif
  304. #define SHUTDOWN_RD (0)
  305. #define SHUTDOWN_WR (1)
  306. #define SHUTDOWN_BOTH (2)
  307. mg_static_assert(MAX_WORKER_THREADS >= 1,
  308. "worker threads must be a positive number");
  309. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  310. "size_t data type size check");
  311. #if defined(_WIN32) && !defined(__SYMBIAN32__) /* WINDOWS include block */
  312. #include <windows.h>
  313. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  314. #include <ws2tcpip.h>
  315. typedef const char *SOCK_OPT_TYPE;
  316. #if !defined(PATH_MAX)
  317. #define W_PATH_MAX (MAX_PATH)
  318. /* at most three UTF-8 chars per wchar_t */
  319. #define PATH_MAX (W_PATH_MAX * 3)
  320. #else
  321. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  322. #endif
  323. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  324. #if !defined(_IN_PORT_T)
  325. #if !defined(in_port_t)
  326. #define in_port_t u_short
  327. #endif
  328. #endif
  329. #if !defined(_WIN32_WCE)
  330. #include <process.h>
  331. #include <direct.h>
  332. #include <io.h>
  333. #else /* _WIN32_WCE */
  334. #define NO_CGI /* WinCE has no pipes */
  335. #define NO_POPEN /* WinCE has no popen */
  336. typedef long off_t;
  337. #define errno ((int)(GetLastError()))
  338. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  339. #endif /* _WIN32_WCE */
  340. #define MAKEUQUAD(lo, hi) \
  341. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  342. #define RATE_DIFF (10000000) /* 100 nsecs */
  343. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  344. #define SYS2UNIX_TIME(lo, hi) \
  345. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  346. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  347. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  348. * Also use _strtoui64 on modern M$ compilers */
  349. #if defined(_MSC_VER)
  350. #if (_MSC_VER < 1300)
  351. #define STRX(x) #x
  352. #define STR(x) STRX(x)
  353. #define __func__ __FILE__ ":" STR(__LINE__)
  354. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  355. #define strtoll(x, y, z) (_atoi64(x))
  356. #else
  357. #define __func__ __FUNCTION__
  358. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  359. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  360. #endif
  361. #endif /* _MSC_VER */
  362. #define ERRNO ((int)(GetLastError()))
  363. #define NO_SOCKLEN_T
  364. #if defined(_WIN64) || defined(__MINGW64__)
  365. #define SSL_LIB "ssleay64.dll"
  366. #define CRYPTO_LIB "libeay64.dll"
  367. #else
  368. #define SSL_LIB "ssleay32.dll"
  369. #define CRYPTO_LIB "libeay32.dll"
  370. #endif
  371. #define O_NONBLOCK (0)
  372. #if !defined(W_OK)
  373. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  374. #endif
  375. #if !defined(EWOULDBLOCK)
  376. #define EWOULDBLOCK WSAEWOULDBLOCK
  377. #endif /* !EWOULDBLOCK */
  378. #define _POSIX_
  379. #define INT64_FMT "I64d"
  380. #define UINT64_FMT "I64u"
  381. #define WINCDECL __cdecl
  382. #define vsnprintf_impl _vsnprintf
  383. #define access _access
  384. #define mg_sleep(x) (Sleep(x))
  385. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  386. #if !defined(popen)
  387. #define popen(x, y) (_popen(x, y))
  388. #endif
  389. #if !defined(pclose)
  390. #define pclose(x) (_pclose(x))
  391. #endif
  392. #define close(x) (_close(x))
  393. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  394. #define RTLD_LAZY (0)
  395. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  396. #define fdopen(x, y) (_fdopen((x), (y)))
  397. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  398. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  399. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  400. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  401. #define sleep(x) (Sleep((x)*1000))
  402. #define rmdir(x) (_rmdir(x))
  403. #if defined(_WIN64) || !defined(__MINGW32__)
  404. /* Only MinGW 32 bit is missing this function */
  405. #define timegm(x) (_mkgmtime(x))
  406. #else
  407. time_t timegm(struct tm *tm);
  408. #define NEED_TIMEGM
  409. #endif
  410. #if !defined(fileno)
  411. #define fileno(x) (_fileno(x))
  412. #endif /* !fileno MINGW #defines fileno */
  413. typedef HANDLE pthread_mutex_t;
  414. typedef DWORD pthread_key_t;
  415. typedef HANDLE pthread_t;
  416. typedef struct {
  417. CRITICAL_SECTION threadIdSec;
  418. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  419. } pthread_cond_t;
  420. #if !defined(__clockid_t_defined)
  421. typedef DWORD clockid_t;
  422. #endif
  423. #if !defined(CLOCK_MONOTONIC)
  424. #define CLOCK_MONOTONIC (1)
  425. #endif
  426. #if !defined(CLOCK_REALTIME)
  427. #define CLOCK_REALTIME (2)
  428. #endif
  429. #if !defined(CLOCK_THREAD)
  430. #define CLOCK_THREAD (3)
  431. #endif
  432. #if !defined(CLOCK_PROCESS)
  433. #define CLOCK_PROCESS (4)
  434. #endif
  435. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  436. #define _TIMESPEC_DEFINED
  437. #endif
  438. #if !defined(_TIMESPEC_DEFINED)
  439. struct timespec {
  440. time_t tv_sec; /* seconds */
  441. long tv_nsec; /* nanoseconds */
  442. };
  443. #endif
  444. #if !defined(WIN_PTHREADS_TIME_H)
  445. #define MUST_IMPLEMENT_CLOCK_GETTIME
  446. #endif
  447. #if defined(MUST_IMPLEMENT_CLOCK_GETTIME)
  448. #define clock_gettime mg_clock_gettime
  449. static int
  450. clock_gettime(clockid_t clk_id, struct timespec *tp)
  451. {
  452. FILETIME ft;
  453. ULARGE_INTEGER li, li2;
  454. BOOL ok = FALSE;
  455. double d;
  456. static double perfcnt_per_sec = 0.0;
  457. static BOOL initialized = FALSE;
  458. if (!initialized) {
  459. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  460. perfcnt_per_sec = 1.0 / li.QuadPart;
  461. initialized = TRUE;
  462. }
  463. if (tp) {
  464. memset(tp, 0, sizeof(*tp));
  465. if (clk_id == CLOCK_REALTIME) {
  466. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  467. GetSystemTimeAsFileTime(&ft);
  468. li.LowPart = ft.dwLowDateTime;
  469. li.HighPart = ft.dwHighDateTime;
  470. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  471. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  472. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  473. ok = TRUE;
  474. /* END: CLOCK_REALTIME */
  475. } else if (clk_id == CLOCK_MONOTONIC) {
  476. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  477. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  478. d = li.QuadPart * perfcnt_per_sec;
  479. tp->tv_sec = (time_t)d;
  480. d -= (double)tp->tv_sec;
  481. tp->tv_nsec = (long)(d * 1.0E9);
  482. ok = TRUE;
  483. /* END: CLOCK_MONOTONIC */
  484. } else if (clk_id == CLOCK_THREAD) {
  485. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  486. FILETIME t_create, t_exit, t_kernel, t_user;
  487. if (GetThreadTimes(GetCurrentThread(),
  488. &t_create,
  489. &t_exit,
  490. &t_kernel,
  491. &t_user)) {
  492. li.LowPart = t_user.dwLowDateTime;
  493. li.HighPart = t_user.dwHighDateTime;
  494. li2.LowPart = t_kernel.dwLowDateTime;
  495. li2.HighPart = t_kernel.dwHighDateTime;
  496. li.QuadPart += li2.QuadPart;
  497. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  498. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  499. ok = TRUE;
  500. }
  501. /* END: CLOCK_THREAD */
  502. } else if (clk_id == CLOCK_PROCESS) {
  503. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  504. FILETIME t_create, t_exit, t_kernel, t_user;
  505. if (GetProcessTimes(GetCurrentProcess(),
  506. &t_create,
  507. &t_exit,
  508. &t_kernel,
  509. &t_user)) {
  510. li.LowPart = t_user.dwLowDateTime;
  511. li.HighPart = t_user.dwHighDateTime;
  512. li2.LowPart = t_kernel.dwLowDateTime;
  513. li2.HighPart = t_kernel.dwHighDateTime;
  514. li.QuadPart += li2.QuadPart;
  515. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  516. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  517. ok = TRUE;
  518. }
  519. /* END: CLOCK_PROCESS */
  520. } else {
  521. /* BEGIN: unknown clock */
  522. /* ok = FALSE; already set by init */
  523. /* END: unknown clock */
  524. }
  525. }
  526. return ok ? 0 : -1;
  527. }
  528. #endif
  529. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  530. static int pthread_mutex_lock(pthread_mutex_t *);
  531. static int pthread_mutex_unlock(pthread_mutex_t *);
  532. static void path_to_unicode(const struct mg_connection *conn,
  533. const char *path,
  534. wchar_t *wbuf,
  535. size_t wbuf_len);
  536. /* All file operations need to be rewritten to solve #246. */
  537. struct mg_file;
  538. static const char *
  539. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  540. /* POSIX dirent interface */
  541. struct dirent {
  542. char d_name[PATH_MAX];
  543. };
  544. typedef struct DIR {
  545. HANDLE handle;
  546. WIN32_FIND_DATAW info;
  547. struct dirent result;
  548. } DIR;
  549. #if defined(_WIN32) && !defined(POLLIN)
  550. #if !defined(HAVE_POLL)
  551. struct pollfd {
  552. SOCKET fd;
  553. short events;
  554. short revents;
  555. };
  556. #define POLLIN (0x0300)
  557. #endif
  558. #endif
  559. /* Mark required libraries */
  560. #if defined(_MSC_VER)
  561. #pragma comment(lib, "Ws2_32.lib")
  562. #endif
  563. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  564. WINDOWS / UNIX include block */
  565. #include <sys/wait.h>
  566. #include <sys/socket.h>
  567. #include <sys/poll.h>
  568. #include <netinet/in.h>
  569. #include <arpa/inet.h>
  570. #include <sys/time.h>
  571. #include <sys/utsname.h>
  572. #include <stdint.h>
  573. #include <inttypes.h>
  574. #include <netdb.h>
  575. #include <netinet/tcp.h>
  576. typedef const void *SOCK_OPT_TYPE;
  577. #if defined(ANDROID)
  578. typedef unsigned short int in_port_t;
  579. #endif
  580. #include <pwd.h>
  581. #include <unistd.h>
  582. #include <grp.h>
  583. #include <dirent.h>
  584. #define vsnprintf_impl vsnprintf
  585. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  586. #include <dlfcn.h>
  587. #endif
  588. #include <pthread.h>
  589. #if defined(__MACH__)
  590. #define SSL_LIB "libssl.dylib"
  591. #define CRYPTO_LIB "libcrypto.dylib"
  592. #else
  593. #if !defined(SSL_LIB)
  594. #define SSL_LIB "libssl.so"
  595. #endif
  596. #if !defined(CRYPTO_LIB)
  597. #define CRYPTO_LIB "libcrypto.so"
  598. #endif
  599. #endif
  600. #if !defined(O_BINARY)
  601. #define O_BINARY (0)
  602. #endif /* O_BINARY */
  603. #define closesocket(a) (close(a))
  604. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  605. #define mg_remove(conn, x) (remove(x))
  606. #define mg_sleep(x) (usleep((x)*1000))
  607. #define mg_opendir(conn, x) (opendir(x))
  608. #define mg_closedir(x) (closedir(x))
  609. #define mg_readdir(x) (readdir(x))
  610. #define ERRNO (errno)
  611. #define INVALID_SOCKET (-1)
  612. #define INT64_FMT PRId64
  613. #define UINT64_FMT PRIu64
  614. typedef int SOCKET;
  615. #define WINCDECL
  616. #if defined(__hpux)
  617. /* HPUX 11 does not have monotonic, fall back to realtime */
  618. #if !defined(CLOCK_MONOTONIC)
  619. #define CLOCK_MONOTONIC CLOCK_REALTIME
  620. #endif
  621. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  622. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  623. * the prototypes use int* rather than socklen_t* which matches the
  624. * actual library expectation. When called with the wrong size arg
  625. * accept() returns a zero client inet addr and check_acl() always
  626. * fails. Since socklen_t is widely used below, just force replace
  627. * their typedef with int. - DTL
  628. */
  629. #define socklen_t int
  630. #endif /* hpux */
  631. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  632. WINDOWS / UNIX include block */
  633. /* In case our C library is missing "timegm", provide an implementation */
  634. #if defined(NEED_TIMEGM)
  635. static inline int
  636. is_leap(int y)
  637. {
  638. return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
  639. }
  640. static inline int
  641. count_leap(int y)
  642. {
  643. return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400;
  644. }
  645. time_t
  646. timegm(struct tm *tm)
  647. {
  648. static const unsigned short ydays[] = {
  649. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
  650. int year = tm->tm_year + 1900;
  651. int mon = tm->tm_mon;
  652. int mday = tm->tm_mday - 1;
  653. int hour = tm->tm_hour;
  654. int min = tm->tm_min;
  655. int sec = tm->tm_sec;
  656. if (year < 1970 || mon < 0 || mon > 11 || mday < 0
  657. || (mday >= ydays[mon + 1] - ydays[mon]
  658. + (mon == 1 && is_leap(year) ? 1 : 0)) || hour < 0
  659. || hour > 23
  660. || min < 0
  661. || min > 59
  662. || sec < 0
  663. || sec > 60)
  664. return -1;
  665. time_t res = year - 1970;
  666. res *= 365;
  667. res += mday;
  668. res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0);
  669. res += count_leap(year);
  670. res *= 24;
  671. res += hour;
  672. res *= 60;
  673. res += min;
  674. res *= 60;
  675. res += sec;
  676. return res;
  677. }
  678. #endif /* NEED_TIMEGM */
  679. /* va_copy should always be a macro, C99 and C++11 - DTL */
  680. #if !defined(va_copy)
  681. #define va_copy(x, y) ((x) = (y))
  682. #endif
  683. #if defined(_WIN32)
  684. /* Create substitutes for POSIX functions in Win32. */
  685. #if defined(__MINGW32__)
  686. /* Show no warning in case system functions are not used. */
  687. #pragma GCC diagnostic push
  688. #pragma GCC diagnostic ignored "-Wunused-function"
  689. #endif
  690. static CRITICAL_SECTION global_log_file_lock;
  691. FUNCTION_MAY_BE_UNUSED
  692. static DWORD
  693. pthread_self(void)
  694. {
  695. return GetCurrentThreadId();
  696. }
  697. FUNCTION_MAY_BE_UNUSED
  698. static int
  699. pthread_key_create(
  700. pthread_key_t *key,
  701. void (*_ignored)(void *) /* destructor not supported for Windows */
  702. )
  703. {
  704. (void)_ignored;
  705. if ((key != 0)) {
  706. *key = TlsAlloc();
  707. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  708. }
  709. return -2;
  710. }
  711. FUNCTION_MAY_BE_UNUSED
  712. static int
  713. pthread_key_delete(pthread_key_t key)
  714. {
  715. return TlsFree(key) ? 0 : 1;
  716. }
  717. FUNCTION_MAY_BE_UNUSED
  718. static int
  719. pthread_setspecific(pthread_key_t key, void *value)
  720. {
  721. return TlsSetValue(key, value) ? 0 : 1;
  722. }
  723. FUNCTION_MAY_BE_UNUSED
  724. static void *
  725. pthread_getspecific(pthread_key_t key)
  726. {
  727. return TlsGetValue(key);
  728. }
  729. #if defined(__MINGW32__)
  730. /* Enable unused function warning again */
  731. #pragma GCC diagnostic pop
  732. #endif
  733. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  734. #else
  735. static pthread_mutexattr_t pthread_mutex_attr;
  736. #endif /* _WIN32 */
  737. #define PASSWORDS_FILE_NAME ".htpasswd"
  738. #define CGI_ENVIRONMENT_SIZE (4096)
  739. #define MAX_CGI_ENVIR_VARS (256)
  740. #define MG_BUF_LEN (8192)
  741. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  742. #if defined(_WIN32_WCE)
  743. /* Create substitutes for POSIX functions in Win32. */
  744. #if defined(__MINGW32__)
  745. /* Show no warning in case system functions are not used. */
  746. #pragma GCC diagnostic push
  747. #pragma GCC diagnostic ignored "-Wunused-function"
  748. #endif
  749. FUNCTION_MAY_BE_UNUSED
  750. static time_t
  751. time(time_t *ptime)
  752. {
  753. time_t t;
  754. SYSTEMTIME st;
  755. FILETIME ft;
  756. GetSystemTime(&st);
  757. SystemTimeToFileTime(&st, &ft);
  758. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  759. if (ptime != NULL) {
  760. *ptime = t;
  761. }
  762. return t;
  763. }
  764. FUNCTION_MAY_BE_UNUSED
  765. static struct tm *
  766. localtime_s(const time_t *ptime, struct tm *ptm)
  767. {
  768. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  769. FILETIME ft, lft;
  770. SYSTEMTIME st;
  771. TIME_ZONE_INFORMATION tzinfo;
  772. if (ptm == NULL) {
  773. return NULL;
  774. }
  775. *(int64_t *)&ft = t;
  776. FileTimeToLocalFileTime(&ft, &lft);
  777. FileTimeToSystemTime(&lft, &st);
  778. ptm->tm_year = st.wYear - 1900;
  779. ptm->tm_mon = st.wMonth - 1;
  780. ptm->tm_wday = st.wDayOfWeek;
  781. ptm->tm_mday = st.wDay;
  782. ptm->tm_hour = st.wHour;
  783. ptm->tm_min = st.wMinute;
  784. ptm->tm_sec = st.wSecond;
  785. ptm->tm_yday = 0; /* hope nobody uses this */
  786. ptm->tm_isdst =
  787. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  788. return ptm;
  789. }
  790. FUNCTION_MAY_BE_UNUSED
  791. static struct tm *
  792. gmtime_s(const time_t *ptime, struct tm *ptm)
  793. {
  794. /* FIXME(lsm): fix this. */
  795. return localtime_s(ptime, ptm);
  796. }
  797. static int mg_atomic_inc(volatile int *addr);
  798. static struct tm tm_array[MAX_WORKER_THREADS];
  799. static int tm_index = 0;
  800. FUNCTION_MAY_BE_UNUSED
  801. static struct tm *
  802. localtime(const time_t *ptime)
  803. {
  804. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  805. return localtime_s(ptime, tm_array + i);
  806. }
  807. FUNCTION_MAY_BE_UNUSED
  808. static struct tm *
  809. gmtime(const time_t *ptime)
  810. {
  811. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  812. return gmtime_s(ptime, tm_array + i);
  813. }
  814. FUNCTION_MAY_BE_UNUSED
  815. static size_t
  816. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  817. {
  818. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  819. * for WinCE"); */
  820. return 0;
  821. }
  822. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  823. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  824. #define remove(f) mg_remove(NULL, f)
  825. FUNCTION_MAY_BE_UNUSED
  826. static int
  827. rename(const char *a, const char *b)
  828. {
  829. wchar_t wa[W_PATH_MAX];
  830. wchar_t wb[W_PATH_MAX];
  831. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  832. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  833. return MoveFileW(wa, wb) ? 0 : -1;
  834. }
  835. struct stat {
  836. int64_t st_size;
  837. time_t st_mtime;
  838. };
  839. FUNCTION_MAY_BE_UNUSED
  840. static int
  841. stat(const char *name, struct stat *st)
  842. {
  843. wchar_t wbuf[W_PATH_MAX];
  844. WIN32_FILE_ATTRIBUTE_DATA attr;
  845. time_t creation_time, write_time;
  846. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  847. memset(&attr, 0, sizeof(attr));
  848. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  849. st->st_size =
  850. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  851. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  852. attr.ftLastWriteTime.dwHighDateTime);
  853. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  854. attr.ftCreationTime.dwHighDateTime);
  855. if (creation_time > write_time) {
  856. st->st_mtime = creation_time;
  857. } else {
  858. st->st_mtime = write_time;
  859. }
  860. return 0;
  861. }
  862. #define access(x, a) 1 /* not required anyway */
  863. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  864. /* Values from errno.h in Windows SDK (Visual Studio). */
  865. #define EEXIST 17
  866. #define EACCES 13
  867. #define ENOENT 2
  868. #if defined(__MINGW32__)
  869. /* Enable unused function warning again */
  870. #pragma GCC diagnostic pop
  871. #endif
  872. #endif /* defined(_WIN32_WCE) */
  873. #if defined(__GNUC__) || defined(__MINGW32__)
  874. /* Show no warning in case system functions are not used. */
  875. #define GCC_VERSION \
  876. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  877. #if GCC_VERSION >= 40500
  878. #pragma GCC diagnostic push
  879. #pragma GCC diagnostic ignored "-Wunused-function"
  880. #endif /* GCC_VERSION >= 40500 */
  881. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  882. #if defined(__clang__)
  883. /* Show no warning in case system functions are not used. */
  884. #pragma clang diagnostic push
  885. #pragma clang diagnostic ignored "-Wunused-function"
  886. #endif
  887. static pthread_mutex_t global_lock_mutex;
  888. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  889. /* Forward declaration for Windows */
  890. FUNCTION_MAY_BE_UNUSED
  891. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  892. FUNCTION_MAY_BE_UNUSED
  893. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  894. #endif
  895. FUNCTION_MAY_BE_UNUSED
  896. static void
  897. mg_global_lock(void)
  898. {
  899. (void)pthread_mutex_lock(&global_lock_mutex);
  900. }
  901. FUNCTION_MAY_BE_UNUSED
  902. static void
  903. mg_global_unlock(void)
  904. {
  905. (void)pthread_mutex_unlock(&global_lock_mutex);
  906. }
  907. FUNCTION_MAY_BE_UNUSED
  908. static int
  909. mg_atomic_inc(volatile int *addr)
  910. {
  911. int ret;
  912. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  913. /* Depending on the SDK, this function uses either
  914. * (volatile unsigned int *) or (volatile LONG *),
  915. * so whatever you use, the other SDK is likely to raise a warning. */
  916. ret = InterlockedIncrement((volatile long *)addr);
  917. #elif defined(__GNUC__) \
  918. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  919. && !defined(NO_ATOMICS)
  920. ret = __sync_add_and_fetch(addr, 1);
  921. #else
  922. mg_global_lock();
  923. ret = (++(*addr));
  924. mg_global_unlock();
  925. #endif
  926. return ret;
  927. }
  928. FUNCTION_MAY_BE_UNUSED
  929. static int
  930. mg_atomic_dec(volatile int *addr)
  931. {
  932. int ret;
  933. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  934. /* Depending on the SDK, this function uses either
  935. * (volatile unsigned int *) or (volatile LONG *),
  936. * so whatever you use, the other SDK is likely to raise a warning. */
  937. ret = InterlockedDecrement((volatile long *)addr);
  938. #elif defined(__GNUC__) \
  939. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  940. && !defined(NO_ATOMICS)
  941. ret = __sync_sub_and_fetch(addr, 1);
  942. #else
  943. mg_global_lock();
  944. ret = (--(*addr));
  945. mg_global_unlock();
  946. #endif
  947. return ret;
  948. }
  949. #if defined(USE_SERVER_STATS)
  950. static int64_t
  951. mg_atomic_add(volatile int64_t *addr, int64_t value)
  952. {
  953. int64_t ret;
  954. #if defined(_WIN64) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  955. ret = InterlockedAdd64(addr, value);
  956. #elif defined(__GNUC__) \
  957. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  958. && !defined(NO_ATOMICS)
  959. ret = __sync_add_and_fetch(addr, value);
  960. #else
  961. mg_global_lock();
  962. *addr += value;
  963. ret = (*addr);
  964. mg_global_unlock();
  965. #endif
  966. return ret;
  967. }
  968. #endif
  969. #if defined(__GNUC__)
  970. /* Show no warning in case system functions are not used. */
  971. #if GCC_VERSION >= 40500
  972. #pragma GCC diagnostic pop
  973. #endif /* GCC_VERSION >= 40500 */
  974. #endif /* defined(__GNUC__) */
  975. #if defined(__clang__)
  976. /* Show no warning in case system functions are not used. */
  977. #pragma clang diagnostic pop
  978. #endif
  979. #if defined(USE_SERVER_STATS)
  980. struct mg_memory_stat {
  981. volatile int64_t totalMemUsed;
  982. volatile int64_t maxMemUsed;
  983. volatile int blockCount;
  984. };
  985. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  986. static void *
  987. mg_malloc_ex(size_t size,
  988. struct mg_context *ctx,
  989. const char *file,
  990. unsigned line)
  991. {
  992. void *data = malloc(size + 2 * sizeof(uintptr_t));
  993. void *memory = 0;
  994. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  995. #if defined(MEMORY_DEBUGGING)
  996. char mallocStr[256];
  997. #else
  998. (void)file;
  999. (void)line;
  1000. #endif
  1001. if (data) {
  1002. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  1003. if (mmem > mstat->maxMemUsed) {
  1004. /* could use atomic compare exchange, but this
  1005. * seems overkill for statistics data */
  1006. mstat->maxMemUsed = mmem;
  1007. }
  1008. mg_atomic_inc(&mstat->blockCount);
  1009. ((uintptr_t *)data)[0] = size;
  1010. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  1011. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1012. }
  1013. #if defined(MEMORY_DEBUGGING)
  1014. sprintf(mallocStr,
  1015. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  1016. memory,
  1017. (unsigned long)size,
  1018. (unsigned long)mstat->totalMemUsed,
  1019. (unsigned long)mstat->blockCount,
  1020. file,
  1021. line);
  1022. #if defined(_WIN32)
  1023. OutputDebugStringA(mallocStr);
  1024. #else
  1025. DEBUG_TRACE("%s", mallocStr);
  1026. #endif
  1027. #endif
  1028. return memory;
  1029. }
  1030. static void *
  1031. mg_calloc_ex(size_t count,
  1032. size_t size,
  1033. struct mg_context *ctx,
  1034. const char *file,
  1035. unsigned line)
  1036. {
  1037. void *data = mg_malloc_ex(size * count, ctx, file, line);
  1038. if (data) {
  1039. memset(data, 0, size * count);
  1040. }
  1041. return data;
  1042. }
  1043. static void
  1044. mg_free_ex(void *memory, const char *file, unsigned line)
  1045. {
  1046. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1047. #if defined(MEMORY_DEBUGGING)
  1048. char mallocStr[256];
  1049. #else
  1050. (void)file;
  1051. (void)line;
  1052. #endif
  1053. if (memory) {
  1054. uintptr_t size = ((uintptr_t *)data)[0];
  1055. struct mg_memory_stat *mstat =
  1056. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  1057. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  1058. mg_atomic_dec(&mstat->blockCount);
  1059. #if defined(MEMORY_DEBUGGING)
  1060. sprintf(mallocStr,
  1061. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  1062. memory,
  1063. (unsigned long)size,
  1064. (unsigned long)mstat->totalMemUsed,
  1065. (unsigned long)mstat->blockCount,
  1066. file,
  1067. line);
  1068. #if defined(_WIN32)
  1069. OutputDebugStringA(mallocStr);
  1070. #else
  1071. DEBUG_TRACE("%s", mallocStr);
  1072. #endif
  1073. #endif
  1074. free(data);
  1075. }
  1076. }
  1077. static void *
  1078. mg_realloc_ex(void *memory,
  1079. size_t newsize,
  1080. struct mg_context *ctx,
  1081. const char *file,
  1082. unsigned line)
  1083. {
  1084. void *data;
  1085. void *_realloc;
  1086. uintptr_t oldsize;
  1087. #if defined(MEMORY_DEBUGGING)
  1088. char mallocStr[256];
  1089. #else
  1090. (void)file;
  1091. (void)line;
  1092. #endif
  1093. if (newsize) {
  1094. if (memory) {
  1095. /* Reallocate existing block */
  1096. struct mg_memory_stat *mstat;
  1097. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1098. oldsize = ((uintptr_t *)data)[0];
  1099. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1100. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1101. if (_realloc) {
  1102. data = _realloc;
  1103. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1104. #if defined(MEMORY_DEBUGGING)
  1105. sprintf(mallocStr,
  1106. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1107. memory,
  1108. (unsigned long)oldsize,
  1109. (unsigned long)mstat->totalMemUsed,
  1110. (unsigned long)mstat->blockCount,
  1111. file,
  1112. line);
  1113. #if defined(_WIN32)
  1114. OutputDebugStringA(mallocStr);
  1115. #else
  1116. DEBUG_TRACE("%s", mallocStr);
  1117. #endif
  1118. #endif
  1119. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1120. #if defined(MEMORY_DEBUGGING)
  1121. sprintf(mallocStr,
  1122. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1123. memory,
  1124. (unsigned long)newsize,
  1125. (unsigned long)mstat->totalMemUsed,
  1126. (unsigned long)mstat->blockCount,
  1127. file,
  1128. line);
  1129. #if defined(_WIN32)
  1130. OutputDebugStringA(mallocStr);
  1131. #else
  1132. DEBUG_TRACE("%s", mallocStr);
  1133. #endif
  1134. #endif
  1135. *(uintptr_t *)data = newsize;
  1136. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1137. } else {
  1138. #if defined(MEMORY_DEBUGGING)
  1139. #if defined(_WIN32)
  1140. OutputDebugStringA("MEM: realloc failed\n");
  1141. #else
  1142. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1143. #endif
  1144. #endif
  1145. return _realloc;
  1146. }
  1147. } else {
  1148. /* Allocate new block */
  1149. data = mg_malloc_ex(newsize, ctx, file, line);
  1150. }
  1151. } else {
  1152. /* Free existing block */
  1153. data = 0;
  1154. mg_free_ex(memory, file, line);
  1155. }
  1156. return data;
  1157. }
  1158. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1159. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1160. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1161. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1162. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1163. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1164. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1165. #else /* USE_SERVER_STATS */
  1166. static __inline void *
  1167. mg_malloc(size_t a)
  1168. {
  1169. return malloc(a);
  1170. }
  1171. static __inline void *
  1172. mg_calloc(size_t a, size_t b)
  1173. {
  1174. return calloc(a, b);
  1175. }
  1176. static __inline void *
  1177. mg_realloc(void *a, size_t b)
  1178. {
  1179. return realloc(a, b);
  1180. }
  1181. static __inline void
  1182. mg_free(void *a)
  1183. {
  1184. free(a);
  1185. }
  1186. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1187. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1188. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1189. #define mg_free_ctx(a, c) mg_free(a)
  1190. #endif /* USE_SERVER_STATS */
  1191. static void mg_vsnprintf(const struct mg_connection *conn,
  1192. int *truncated,
  1193. char *buf,
  1194. size_t buflen,
  1195. const char *fmt,
  1196. va_list ap);
  1197. static void mg_snprintf(const struct mg_connection *conn,
  1198. int *truncated,
  1199. char *buf,
  1200. size_t buflen,
  1201. PRINTF_FORMAT_STRING(const char *fmt),
  1202. ...) PRINTF_ARGS(5, 6);
  1203. /* This following lines are just meant as a reminder to use the mg-functions
  1204. * for memory management */
  1205. #if defined(malloc)
  1206. #undef malloc
  1207. #endif
  1208. #if defined(calloc)
  1209. #undef calloc
  1210. #endif
  1211. #if defined(realloc)
  1212. #undef realloc
  1213. #endif
  1214. #if defined(free)
  1215. #undef free
  1216. #endif
  1217. #if defined(snprintf)
  1218. #undef snprintf
  1219. #endif
  1220. #if defined(vsnprintf)
  1221. #undef vsnprintf
  1222. #endif
  1223. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1224. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1225. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1226. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1227. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1228. #if defined(_WIN32)
  1229. /* vsnprintf must not be used in any system,
  1230. * but this define only works well for Windows. */
  1231. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1232. #endif
  1233. /* mg_init_library counter */
  1234. static int mg_init_library_called = 0;
  1235. #if !defined(NO_SSL)
  1236. static int mg_ssl_initialized = 0;
  1237. #endif
  1238. static pthread_key_t sTlsKey; /* Thread local storage index */
  1239. static int thread_idx_max = 0;
  1240. #if defined(MG_LEGACY_INTERFACE)
  1241. #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE
  1242. #endif
  1243. struct mg_workerTLS {
  1244. int is_master;
  1245. unsigned long thread_idx;
  1246. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1247. HANDLE pthread_cond_helper_mutex;
  1248. struct mg_workerTLS *next_waiting_thread;
  1249. #endif
  1250. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  1251. char txtbuf[4];
  1252. #endif
  1253. };
  1254. #if defined(__GNUC__) || defined(__MINGW32__)
  1255. /* Show no warning in case system functions are not used. */
  1256. #if GCC_VERSION >= 40500
  1257. #pragma GCC diagnostic push
  1258. #pragma GCC diagnostic ignored "-Wunused-function"
  1259. #endif /* GCC_VERSION >= 40500 */
  1260. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1261. #if defined(__clang__)
  1262. /* Show no warning in case system functions are not used. */
  1263. #pragma clang diagnostic push
  1264. #pragma clang diagnostic ignored "-Wunused-function"
  1265. #endif
  1266. /* Get a unique thread ID as unsigned long, independent from the data type
  1267. * of thread IDs defined by the operating system API.
  1268. * If two calls to mg_current_thread_id return the same value, they calls
  1269. * are done from the same thread. If they return different values, they are
  1270. * done from different threads. (Provided this function is used in the same
  1271. * process context and threads are not repeatedly created and deleted, but
  1272. * CivetWeb does not do that).
  1273. * This function must match the signature required for SSL id callbacks:
  1274. * CRYPTO_set_id_callback
  1275. */
  1276. FUNCTION_MAY_BE_UNUSED
  1277. static unsigned long
  1278. mg_current_thread_id(void)
  1279. {
  1280. #if defined(_WIN32)
  1281. return GetCurrentThreadId();
  1282. #else
  1283. #if defined(__clang__)
  1284. #pragma clang diagnostic push
  1285. #pragma clang diagnostic ignored "-Wunreachable-code"
  1286. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1287. * or not, so one of the two conditions will be unreachable by construction.
  1288. * Unfortunately the C standard does not define a way to check this at
  1289. * compile time, since the #if preprocessor conditions can not use the sizeof
  1290. * operator as an argument. */
  1291. #endif
  1292. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1293. /* This is the problematic case for CRYPTO_set_id_callback:
  1294. * The OS pthread_t can not be cast to unsigned long. */
  1295. struct mg_workerTLS *tls =
  1296. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1297. if (tls == NULL) {
  1298. /* SSL called from an unknown thread: Create some thread index.
  1299. */
  1300. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1301. tls->is_master = -2; /* -2 means "3rd party thread" */
  1302. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1303. pthread_setspecific(sTlsKey, tls);
  1304. }
  1305. return tls->thread_idx;
  1306. } else {
  1307. /* pthread_t may be any data type, so a simple cast to unsigned long
  1308. * can rise a warning/error, depending on the platform.
  1309. * Here memcpy is used as an anything-to-anything cast. */
  1310. unsigned long ret = 0;
  1311. pthread_t t = pthread_self();
  1312. memcpy(&ret, &t, sizeof(pthread_t));
  1313. return ret;
  1314. }
  1315. #if defined(__clang__)
  1316. #pragma clang diagnostic pop
  1317. #endif
  1318. #endif
  1319. }
  1320. FUNCTION_MAY_BE_UNUSED
  1321. static uint64_t
  1322. mg_get_current_time_ns(void)
  1323. {
  1324. struct timespec tsnow;
  1325. clock_gettime(CLOCK_REALTIME, &tsnow);
  1326. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1327. }
  1328. #if defined(__GNUC__)
  1329. /* Show no warning in case system functions are not used. */
  1330. #if GCC_VERSION >= 40500
  1331. #pragma GCC diagnostic pop
  1332. #endif /* GCC_VERSION >= 40500 */
  1333. #endif /* defined(__GNUC__) */
  1334. #if defined(__clang__)
  1335. /* Show no warning in case system functions are not used. */
  1336. #pragma clang diagnostic pop
  1337. #endif
  1338. #if defined(NEED_DEBUG_TRACE_FUNC)
  1339. static void
  1340. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1341. {
  1342. va_list args;
  1343. uint64_t nsnow;
  1344. static uint64_t nslast;
  1345. struct timespec tsnow;
  1346. /* Get some operating system independent thread id */
  1347. unsigned long thread_id = mg_current_thread_id();
  1348. clock_gettime(CLOCK_REALTIME, &tsnow);
  1349. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1350. + ((uint64_t)tsnow.tv_nsec);
  1351. if (!nslast) {
  1352. nslast = nsnow;
  1353. }
  1354. flockfile(stdout);
  1355. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1356. (unsigned long)tsnow.tv_sec,
  1357. (unsigned long)tsnow.tv_nsec,
  1358. nsnow - nslast,
  1359. thread_id,
  1360. func,
  1361. line);
  1362. va_start(args, fmt);
  1363. vprintf(fmt, args);
  1364. va_end(args);
  1365. putchar('\n');
  1366. fflush(stdout);
  1367. funlockfile(stdout);
  1368. nslast = nsnow;
  1369. }
  1370. #endif /* NEED_DEBUG_TRACE_FUNC */
  1371. #define MD5_STATIC static
  1372. #include "md5.inl"
  1373. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1374. #if defined(NO_SOCKLEN_T)
  1375. typedef int socklen_t;
  1376. #endif /* NO_SOCKLEN_T */
  1377. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1378. #if !defined(MSG_NOSIGNAL)
  1379. #define MSG_NOSIGNAL (0)
  1380. #endif
  1381. #if !defined(SOMAXCONN)
  1382. #define SOMAXCONN (100)
  1383. #endif
  1384. /* Size of the accepted socket queue */
  1385. #if !defined(MGSQLEN)
  1386. #define MGSQLEN (20)
  1387. #endif
  1388. #if defined(NO_SSL)
  1389. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1390. typedef struct SSL_CTX SSL_CTX;
  1391. #else
  1392. #if defined(NO_SSL_DL)
  1393. #include <openssl/ssl.h>
  1394. #include <openssl/err.h>
  1395. #include <openssl/crypto.h>
  1396. #include <openssl/x509.h>
  1397. #include <openssl/pem.h>
  1398. #include <openssl/engine.h>
  1399. #include <openssl/conf.h>
  1400. #include <openssl/dh.h>
  1401. #include <openssl/bn.h>
  1402. #include <openssl/opensslv.h>
  1403. #if defined(WOLFSSL_VERSION)
  1404. /* Additional defines for WolfSSL, see
  1405. * https://github.com/civetweb/civetweb/issues/583 */
  1406. #include "wolfssl_extras.inl"
  1407. #endif
  1408. #else
  1409. /* SSL loaded dynamically from DLL.
  1410. * I put the prototypes here to be independent from OpenSSL source
  1411. * installation. */
  1412. typedef struct ssl_st SSL;
  1413. typedef struct ssl_method_st SSL_METHOD;
  1414. typedef struct ssl_ctx_st SSL_CTX;
  1415. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1416. typedef struct x509_name X509_NAME;
  1417. typedef struct asn1_integer ASN1_INTEGER;
  1418. typedef struct bignum BIGNUM;
  1419. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1420. typedef struct evp_md EVP_MD;
  1421. typedef struct x509 X509;
  1422. #define SSL_CTRL_OPTIONS (32)
  1423. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1424. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1425. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1426. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1427. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1428. #define SSL_VERIFY_NONE (0)
  1429. #define SSL_VERIFY_PEER (1)
  1430. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1431. #define SSL_VERIFY_CLIENT_ONCE (4)
  1432. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1433. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1434. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1435. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1436. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1437. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1438. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1439. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1440. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1441. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1442. #define SSL_CB_HANDSHAKE_START (0x10)
  1443. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1444. #define SSL_ERROR_NONE (0)
  1445. #define SSL_ERROR_SSL (1)
  1446. #define SSL_ERROR_WANT_READ (2)
  1447. #define SSL_ERROR_WANT_WRITE (3)
  1448. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1449. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1450. #define SSL_ERROR_ZERO_RETURN (6)
  1451. #define SSL_ERROR_WANT_CONNECT (7)
  1452. #define SSL_ERROR_WANT_ACCEPT (8)
  1453. #define TLSEXT_TYPE_server_name (0)
  1454. #define TLSEXT_NAMETYPE_host_name (0)
  1455. #define SSL_TLSEXT_ERR_OK (0)
  1456. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1457. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1458. #define SSL_TLSEXT_ERR_NOACK (3)
  1459. struct ssl_func {
  1460. const char *name; /* SSL function name */
  1461. void (*ptr)(void); /* Function pointer */
  1462. };
  1463. #if defined(OPENSSL_API_1_1)
  1464. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1465. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1466. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1467. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1468. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1469. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1470. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1471. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1472. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1473. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1474. #define OPENSSL_init_ssl \
  1475. (*(int (*)(uint64_t opts, \
  1476. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1477. #define SSL_CTX_use_PrivateKey_file \
  1478. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1479. #define SSL_CTX_use_certificate_file \
  1480. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1481. #define SSL_CTX_set_default_passwd_cb \
  1482. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1483. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1484. #define SSL_CTX_use_certificate_chain_file \
  1485. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1486. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1487. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1488. #define SSL_CTX_set_verify \
  1489. (*(void (*)(SSL_CTX *, \
  1490. int, \
  1491. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1492. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1493. #define SSL_CTX_load_verify_locations \
  1494. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1495. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1496. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1497. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1498. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1499. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1500. #define SSL_CIPHER_get_name \
  1501. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1502. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1503. #define SSL_CTX_set_session_id_context \
  1504. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1505. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1506. #define SSL_CTX_set_cipher_list \
  1507. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1508. #define SSL_CTX_set_options \
  1509. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1510. #define SSL_CTX_set_info_callback \
  1511. (*(void (*)(SSL_CTX * ctx, \
  1512. void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1513. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1514. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1515. #define SSL_CTX_callback_ctrl \
  1516. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1517. #define SSL_get_servername \
  1518. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1519. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1520. #define SSL_CTX_clear_options(ctx, op) \
  1521. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1522. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1523. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1524. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1525. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1526. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1527. SSL_CTX_callback_ctrl(ctx, \
  1528. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1529. (void (*)(void))cb)
  1530. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1531. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1532. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1533. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1534. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1535. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1536. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1537. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1538. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1539. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1540. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1541. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1542. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1543. #define X509_NAME_oneline \
  1544. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1545. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1546. #define EVP_get_digestbyname \
  1547. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1548. #define EVP_Digest \
  1549. (*(int (*)( \
  1550. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1551. crypto_sw[10].ptr)
  1552. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1553. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1554. #define ASN1_INTEGER_to_BN \
  1555. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1556. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1557. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1558. #define OPENSSL_free(a) CRYPTO_free(a)
  1559. /* init_ssl_ctx() function updates this array.
  1560. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1561. * of respective functions. The macros above (like SSL_connect()) are really
  1562. * just calling these functions indirectly via the pointer. */
  1563. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1564. {"SSL_accept", NULL},
  1565. {"SSL_connect", NULL},
  1566. {"SSL_read", NULL},
  1567. {"SSL_write", NULL},
  1568. {"SSL_get_error", NULL},
  1569. {"SSL_set_fd", NULL},
  1570. {"SSL_new", NULL},
  1571. {"SSL_CTX_new", NULL},
  1572. {"TLS_server_method", NULL},
  1573. {"OPENSSL_init_ssl", NULL},
  1574. {"SSL_CTX_use_PrivateKey_file", NULL},
  1575. {"SSL_CTX_use_certificate_file", NULL},
  1576. {"SSL_CTX_set_default_passwd_cb", NULL},
  1577. {"SSL_CTX_free", NULL},
  1578. {"SSL_CTX_use_certificate_chain_file", NULL},
  1579. {"TLS_client_method", NULL},
  1580. {"SSL_pending", NULL},
  1581. {"SSL_CTX_set_verify", NULL},
  1582. {"SSL_shutdown", NULL},
  1583. {"SSL_CTX_load_verify_locations", NULL},
  1584. {"SSL_CTX_set_default_verify_paths", NULL},
  1585. {"SSL_CTX_set_verify_depth", NULL},
  1586. {"SSL_get_peer_certificate", NULL},
  1587. {"SSL_get_version", NULL},
  1588. {"SSL_get_current_cipher", NULL},
  1589. {"SSL_CIPHER_get_name", NULL},
  1590. {"SSL_CTX_check_private_key", NULL},
  1591. {"SSL_CTX_set_session_id_context", NULL},
  1592. {"SSL_CTX_ctrl", NULL},
  1593. {"SSL_CTX_set_cipher_list", NULL},
  1594. {"SSL_CTX_set_options", NULL},
  1595. {"SSL_CTX_set_info_callback", NULL},
  1596. {"SSL_get_ex_data", NULL},
  1597. {"SSL_set_ex_data", NULL},
  1598. {"SSL_CTX_callback_ctrl", NULL},
  1599. {"SSL_get_servername", NULL},
  1600. {"SSL_set_SSL_CTX", NULL},
  1601. {NULL, NULL}};
  1602. /* Similar array as ssl_sw. These functions could be located in different
  1603. * lib. */
  1604. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1605. {"ERR_error_string", NULL},
  1606. {"ERR_remove_state", NULL},
  1607. {"CONF_modules_unload", NULL},
  1608. {"X509_free", NULL},
  1609. {"X509_get_subject_name", NULL},
  1610. {"X509_get_issuer_name", NULL},
  1611. {"X509_NAME_oneline", NULL},
  1612. {"X509_get_serialNumber", NULL},
  1613. {"EVP_get_digestbyname", NULL},
  1614. {"EVP_Digest", NULL},
  1615. {"i2d_X509", NULL},
  1616. {"BN_bn2hex", NULL},
  1617. {"ASN1_INTEGER_to_BN", NULL},
  1618. {"BN_free", NULL},
  1619. {"CRYPTO_free", NULL},
  1620. {NULL, NULL}};
  1621. #else
  1622. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1623. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1624. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1625. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1626. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1627. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1628. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1629. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1630. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1631. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1632. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1633. #define SSL_CTX_use_PrivateKey_file \
  1634. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1635. #define SSL_CTX_use_certificate_file \
  1636. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1637. #define SSL_CTX_set_default_passwd_cb \
  1638. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1639. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1640. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1641. #define SSL_CTX_use_certificate_chain_file \
  1642. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1643. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1644. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1645. #define SSL_CTX_set_verify \
  1646. (*(void (*)(SSL_CTX *, \
  1647. int, \
  1648. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1649. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1650. #define SSL_CTX_load_verify_locations \
  1651. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1652. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1653. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1654. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1655. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1656. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1657. #define SSL_CIPHER_get_name \
  1658. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1659. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1660. #define SSL_CTX_set_session_id_context \
  1661. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1662. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1663. #define SSL_CTX_set_cipher_list \
  1664. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1665. #define SSL_CTX_set_info_callback \
  1666. (*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1667. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1668. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1669. #define SSL_CTX_callback_ctrl \
  1670. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1671. #define SSL_get_servername \
  1672. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1673. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1674. #define SSL_CTX_set_options(ctx, op) \
  1675. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1676. #define SSL_CTX_clear_options(ctx, op) \
  1677. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1678. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1679. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1680. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1681. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1682. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1683. SSL_CTX_callback_ctrl(ctx, \
  1684. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1685. (void (*)(void))cb)
  1686. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1687. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1688. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1689. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1690. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1691. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1692. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1693. #define CRYPTO_set_locking_callback \
  1694. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1695. #define CRYPTO_set_id_callback \
  1696. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1697. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1698. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1699. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1700. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1701. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1702. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1703. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1704. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1705. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1706. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1707. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1708. #define X509_NAME_oneline \
  1709. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1710. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1711. #define i2c_ASN1_INTEGER \
  1712. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1713. #define EVP_get_digestbyname \
  1714. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1715. #define EVP_Digest \
  1716. (*(int (*)( \
  1717. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1718. crypto_sw[18].ptr)
  1719. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1720. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1721. #define ASN1_INTEGER_to_BN \
  1722. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1723. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1724. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1725. #define OPENSSL_free(a) CRYPTO_free(a)
  1726. /* init_ssl_ctx() function updates this array.
  1727. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1728. * of respective functions. The macros above (like SSL_connect()) are really
  1729. * just calling these functions indirectly via the pointer. */
  1730. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1731. {"SSL_accept", NULL},
  1732. {"SSL_connect", NULL},
  1733. {"SSL_read", NULL},
  1734. {"SSL_write", NULL},
  1735. {"SSL_get_error", NULL},
  1736. {"SSL_set_fd", NULL},
  1737. {"SSL_new", NULL},
  1738. {"SSL_CTX_new", NULL},
  1739. {"SSLv23_server_method", NULL},
  1740. {"SSL_library_init", NULL},
  1741. {"SSL_CTX_use_PrivateKey_file", NULL},
  1742. {"SSL_CTX_use_certificate_file", NULL},
  1743. {"SSL_CTX_set_default_passwd_cb", NULL},
  1744. {"SSL_CTX_free", NULL},
  1745. {"SSL_load_error_strings", NULL},
  1746. {"SSL_CTX_use_certificate_chain_file", NULL},
  1747. {"SSLv23_client_method", NULL},
  1748. {"SSL_pending", NULL},
  1749. {"SSL_CTX_set_verify", NULL},
  1750. {"SSL_shutdown", NULL},
  1751. {"SSL_CTX_load_verify_locations", NULL},
  1752. {"SSL_CTX_set_default_verify_paths", NULL},
  1753. {"SSL_CTX_set_verify_depth", NULL},
  1754. {"SSL_get_peer_certificate", NULL},
  1755. {"SSL_get_version", NULL},
  1756. {"SSL_get_current_cipher", NULL},
  1757. {"SSL_CIPHER_get_name", NULL},
  1758. {"SSL_CTX_check_private_key", NULL},
  1759. {"SSL_CTX_set_session_id_context", NULL},
  1760. {"SSL_CTX_ctrl", NULL},
  1761. {"SSL_CTX_set_cipher_list", NULL},
  1762. {"SSL_CTX_set_info_callback", NULL},
  1763. {"SSL_get_ex_data", NULL},
  1764. {"SSL_set_ex_data", NULL},
  1765. {"SSL_CTX_callback_ctrl", NULL},
  1766. {"SSL_get_servername", NULL},
  1767. {"SSL_set_SSL_CTX", NULL},
  1768. {NULL, NULL}};
  1769. /* Similar array as ssl_sw. These functions could be located in different
  1770. * lib. */
  1771. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1772. {"CRYPTO_set_locking_callback", NULL},
  1773. {"CRYPTO_set_id_callback", NULL},
  1774. {"ERR_get_error", NULL},
  1775. {"ERR_error_string", NULL},
  1776. {"ERR_remove_state", NULL},
  1777. {"ERR_free_strings", NULL},
  1778. {"ENGINE_cleanup", NULL},
  1779. {"CONF_modules_unload", NULL},
  1780. {"CRYPTO_cleanup_all_ex_data", NULL},
  1781. {"EVP_cleanup", NULL},
  1782. {"X509_free", NULL},
  1783. {"X509_get_subject_name", NULL},
  1784. {"X509_get_issuer_name", NULL},
  1785. {"X509_NAME_oneline", NULL},
  1786. {"X509_get_serialNumber", NULL},
  1787. {"i2c_ASN1_INTEGER", NULL},
  1788. {"EVP_get_digestbyname", NULL},
  1789. {"EVP_Digest", NULL},
  1790. {"i2d_X509", NULL},
  1791. {"BN_bn2hex", NULL},
  1792. {"ASN1_INTEGER_to_BN", NULL},
  1793. {"BN_free", NULL},
  1794. {"CRYPTO_free", NULL},
  1795. {NULL, NULL}};
  1796. #endif /* OPENSSL_API_1_1 */
  1797. #endif /* NO_SSL_DL */
  1798. #endif /* NO_SSL */
  1799. #if !defined(NO_CACHING)
  1800. static const char *month_names[] = {"Jan",
  1801. "Feb",
  1802. "Mar",
  1803. "Apr",
  1804. "May",
  1805. "Jun",
  1806. "Jul",
  1807. "Aug",
  1808. "Sep",
  1809. "Oct",
  1810. "Nov",
  1811. "Dec"};
  1812. #endif /* !NO_CACHING */
  1813. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1814. * the
  1815. * union u. */
  1816. union usa {
  1817. struct sockaddr sa;
  1818. struct sockaddr_in sin;
  1819. #if defined(USE_IPV6)
  1820. struct sockaddr_in6 sin6;
  1821. #endif
  1822. };
  1823. /* Describes a string (chunk of memory). */
  1824. struct vec {
  1825. const char *ptr;
  1826. size_t len;
  1827. };
  1828. struct mg_file_stat {
  1829. /* File properties filled by mg_stat: */
  1830. uint64_t size;
  1831. time_t last_modified;
  1832. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1833. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1834. * case we need a "Content-Eencoding: gzip" header */
  1835. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1836. };
  1837. struct mg_file_in_memory {
  1838. char *p;
  1839. uint32_t pos;
  1840. char mode;
  1841. };
  1842. struct mg_file_access {
  1843. /* File properties filled by mg_fopen: */
  1844. FILE *fp;
  1845. #if defined(MG_USE_OPEN_FILE)
  1846. /* TODO (low): Remove obsolete "file in memory" implementation.
  1847. * In an "early 2017" discussion at Google groups
  1848. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  1849. * we decided to get rid of this feature (after some fade-out
  1850. * phase). */
  1851. const char *membuf;
  1852. #endif
  1853. };
  1854. struct mg_file {
  1855. struct mg_file_stat stat;
  1856. struct mg_file_access access;
  1857. };
  1858. #if defined(MG_USE_OPEN_FILE)
  1859. #define STRUCT_FILE_INITIALIZER \
  1860. { \
  1861. { \
  1862. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1863. } \
  1864. , \
  1865. { \
  1866. (FILE *) NULL, (const char *)NULL \
  1867. } \
  1868. }
  1869. #else
  1870. #define STRUCT_FILE_INITIALIZER \
  1871. { \
  1872. { \
  1873. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1874. } \
  1875. , \
  1876. { \
  1877. (FILE *) NULL \
  1878. } \
  1879. }
  1880. #endif
  1881. /* Describes listening socket, or socket which was accept()-ed by the master
  1882. * thread and queued for future handling by the worker thread. */
  1883. struct socket {
  1884. SOCKET sock; /* Listening socket */
  1885. union usa lsa; /* Local socket address */
  1886. union usa rsa; /* Remote socket address */
  1887. unsigned char is_ssl; /* Is port SSL-ed */
  1888. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1889. * port */
  1890. unsigned char in_use; /* Is valid */
  1891. };
  1892. /* Enum const for all options must be in sync with
  1893. * static struct mg_option config_options[]
  1894. * This is tested in the unit test (test/private.c)
  1895. * "Private Config Options"
  1896. */
  1897. enum {
  1898. LISTENING_PORTS,
  1899. NUM_THREADS,
  1900. RUN_AS_USER,
  1901. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1902. * socket option typedef TCP_NODELAY. */
  1903. MAX_REQUEST_SIZE,
  1904. LINGER_TIMEOUT,
  1905. #if defined(__linux__)
  1906. ALLOW_SENDFILE_CALL,
  1907. #endif
  1908. #if defined(_WIN32)
  1909. CASE_SENSITIVE_FILES,
  1910. #endif
  1911. THROTTLE,
  1912. ACCESS_LOG_FILE,
  1913. ERROR_LOG_FILE,
  1914. ENABLE_KEEP_ALIVE,
  1915. REQUEST_TIMEOUT,
  1916. KEEP_ALIVE_TIMEOUT,
  1917. #if defined(USE_WEBSOCKET)
  1918. WEBSOCKET_TIMEOUT,
  1919. ENABLE_WEBSOCKET_PING_PONG,
  1920. #endif
  1921. DECODE_URL,
  1922. #if defined(USE_LUA)
  1923. LUA_BACKGROUND_SCRIPT,
  1924. LUA_BACKGROUND_SCRIPT_PARAMS,
  1925. #endif
  1926. DOCUMENT_ROOT,
  1927. CGI_EXTENSIONS,
  1928. CGI_ENVIRONMENT,
  1929. PUT_DELETE_PASSWORDS_FILE,
  1930. CGI_INTERPRETER,
  1931. PROTECT_URI,
  1932. AUTHENTICATION_DOMAIN,
  1933. ENABLE_AUTH_DOMAIN_CHECK,
  1934. SSI_EXTENSIONS,
  1935. ENABLE_DIRECTORY_LISTING,
  1936. GLOBAL_PASSWORDS_FILE,
  1937. INDEX_FILES,
  1938. ACCESS_CONTROL_LIST,
  1939. EXTRA_MIME_TYPES,
  1940. SSL_CERTIFICATE,
  1941. SSL_CERTIFICATE_CHAIN,
  1942. URL_REWRITE_PATTERN,
  1943. HIDE_FILES,
  1944. SSL_DO_VERIFY_PEER,
  1945. SSL_CA_PATH,
  1946. SSL_CA_FILE,
  1947. SSL_VERIFY_DEPTH,
  1948. SSL_DEFAULT_VERIFY_PATHS,
  1949. SSL_CIPHER_LIST,
  1950. SSL_PROTOCOL_VERSION,
  1951. SSL_SHORT_TRUST,
  1952. #if defined(USE_LUA)
  1953. LUA_PRELOAD_FILE,
  1954. LUA_SCRIPT_EXTENSIONS,
  1955. LUA_SERVER_PAGE_EXTENSIONS,
  1956. #endif
  1957. #if defined(USE_DUKTAPE)
  1958. DUKTAPE_SCRIPT_EXTENSIONS,
  1959. #endif
  1960. #if defined(USE_WEBSOCKET)
  1961. WEBSOCKET_ROOT,
  1962. #endif
  1963. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1964. LUA_WEBSOCKET_EXTENSIONS,
  1965. #endif
  1966. ACCESS_CONTROL_ALLOW_ORIGIN,
  1967. ACCESS_CONTROL_ALLOW_METHODS,
  1968. ACCESS_CONTROL_ALLOW_HEADERS,
  1969. ERROR_PAGES,
  1970. #if !defined(NO_CACHING)
  1971. STATIC_FILE_MAX_AGE,
  1972. #endif
  1973. #if !defined(NO_SSL)
  1974. STRICT_HTTPS_MAX_AGE,
  1975. #endif
  1976. ADDITIONAL_HEADER,
  1977. ALLOW_INDEX_SCRIPT_SUB_RES,
  1978. NUM_OPTIONS
  1979. };
  1980. /* Config option name, config types, default value.
  1981. * Must be in the same order as the enum const above.
  1982. */
  1983. static struct mg_option config_options[] = {
  1984. /* Once for each server */
  1985. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1986. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1987. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1988. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1989. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1990. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1991. #if defined(__linux__)
  1992. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1993. #endif
  1994. #if defined(_WIN32)
  1995. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1996. #endif
  1997. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1998. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1999. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2000. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2001. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2002. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2003. #if defined(USE_WEBSOCKET)
  2004. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2005. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2006. #endif
  2007. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2008. #if defined(USE_LUA)
  2009. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2010. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2011. #endif
  2012. /* Once for each domain */
  2013. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2014. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2015. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2016. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2017. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2018. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2019. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2020. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2021. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2022. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2023. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2024. {"index_files",
  2025. MG_CONFIG_TYPE_STRING_LIST,
  2026. #if defined(USE_LUA)
  2027. "index.xhtml,index.html,index.htm,"
  2028. "index.lp,index.lsp,index.lua,index.cgi,"
  2029. "index.shtml,index.php"},
  2030. #else
  2031. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2032. #endif
  2033. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2034. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2035. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2036. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2037. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2038. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2039. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2040. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2041. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2042. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2043. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2044. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2045. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2046. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2047. #if defined(USE_LUA)
  2048. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2049. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2050. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2051. #endif
  2052. #if defined(USE_DUKTAPE)
  2053. /* The support for duktape is still in alpha version state.
  2054. * The name of this config option might change. */
  2055. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2056. #endif
  2057. #if defined(USE_WEBSOCKET)
  2058. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2059. #endif
  2060. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2061. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2062. #endif
  2063. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2064. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2065. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2066. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2067. #if !defined(NO_CACHING)
  2068. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2069. #endif
  2070. #if !defined(NO_SSL)
  2071. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2072. #endif
  2073. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2074. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2075. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2076. /* Check if the config_options and the corresponding enum have compatible
  2077. * sizes. */
  2078. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2079. == (NUM_OPTIONS + 1),
  2080. "config_options and enum not sync");
  2081. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2082. struct mg_handler_info {
  2083. /* Name/Pattern of the URI. */
  2084. char *uri;
  2085. size_t uri_len;
  2086. /* handler type */
  2087. int handler_type;
  2088. /* Handler for http/https or authorization requests. */
  2089. mg_request_handler handler;
  2090. unsigned int refcount;
  2091. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2092. pthread_cond_t
  2093. refcount_cond; /* Signaled when handler refcount is decremented */
  2094. /* Handler for ws/wss (websocket) requests. */
  2095. mg_websocket_connect_handler connect_handler;
  2096. mg_websocket_ready_handler ready_handler;
  2097. mg_websocket_data_handler data_handler;
  2098. mg_websocket_close_handler close_handler;
  2099. /* accepted subprotocols for ws/wss requests. */
  2100. struct mg_websocket_subprotocols *subprotocols;
  2101. /* Handler for authorization requests */
  2102. mg_authorization_handler auth_handler;
  2103. /* User supplied argument for the handler function. */
  2104. void *cbdata;
  2105. /* next handler in a linked list */
  2106. struct mg_handler_info *next;
  2107. };
  2108. enum {
  2109. CONTEXT_INVALID,
  2110. CONTEXT_SERVER,
  2111. CONTEXT_HTTP_CLIENT,
  2112. CONTEXT_WS_CLIENT
  2113. };
  2114. struct mg_domain_context {
  2115. SSL_CTX *ssl_ctx; /* SSL context */
  2116. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2117. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2118. /* Server nonce */
  2119. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2120. unsigned long nonce_count; /* Used nonces, used for authentication */
  2121. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2122. /* linked list of shared lua websockets */
  2123. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2124. #endif
  2125. /* Linked list of domains */
  2126. struct mg_domain_context *next;
  2127. };
  2128. struct mg_context {
  2129. /* Part 1 - Physical context:
  2130. * This holds threads, ports, timeouts, ...
  2131. * set for the entire server, independent from the
  2132. * addressed hostname.
  2133. */
  2134. /* Connection related */
  2135. int context_type; /* See CONTEXT_* above */
  2136. struct socket *listening_sockets;
  2137. struct pollfd *listening_socket_fds;
  2138. unsigned int num_listening_sockets;
  2139. struct mg_connection *worker_connections; /* The connection struct, pre-
  2140. * allocated for each worker */
  2141. #if defined(USE_SERVER_STATS)
  2142. int active_connections;
  2143. int max_connections;
  2144. int64_t total_connections;
  2145. int64_t total_requests;
  2146. int64_t total_data_read;
  2147. int64_t total_data_written;
  2148. #endif
  2149. /* Thread related */
  2150. volatile int stop_flag; /* Should we stop event loop */
  2151. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2152. pthread_t masterthreadid; /* The master thread ID */
  2153. unsigned int
  2154. cfg_worker_threads; /* The number of configured worker threads. */
  2155. pthread_t *worker_threadids; /* The worker thread IDs */
  2156. /* Connection to thread dispatching */
  2157. #if defined(ALTERNATIVE_QUEUE)
  2158. struct socket *client_socks;
  2159. void **client_wait_events;
  2160. #else
  2161. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2162. volatile int sq_head; /* Head of the socket queue */
  2163. volatile int sq_tail; /* Tail of the socket queue */
  2164. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2165. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2166. #endif
  2167. /* Memory related */
  2168. unsigned int max_request_size; /* The max request size */
  2169. #if defined(USE_SERVER_STATS)
  2170. struct mg_memory_stat ctx_memory;
  2171. #endif
  2172. /* Operating system related */
  2173. char *systemName; /* What operating system is running */
  2174. time_t start_time; /* Server start time, used for authentication
  2175. * and for diagnstics. */
  2176. #if defined(USE_TIMERS)
  2177. struct ttimers *timers;
  2178. #endif
  2179. /* Lua specific: Background operations and shared websockets */
  2180. #if defined(USE_LUA)
  2181. void *lua_background_state;
  2182. #endif
  2183. /* Server nonce */
  2184. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2185. /* Server callbacks */
  2186. struct mg_callbacks callbacks; /* User-defined callback function */
  2187. void *user_data; /* User-defined data */
  2188. /* Part 2 - Logical domain:
  2189. * This holds hostname, TLS certificate, document root, ...
  2190. * set for a domain hosted at the server.
  2191. * There may be multiple domains hosted at one physical server.
  2192. * The default domain "dd" is the first element of a list of
  2193. * domains.
  2194. */
  2195. struct mg_domain_context dd; /* default domain */
  2196. };
  2197. #if defined(USE_SERVER_STATS)
  2198. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2199. static struct mg_memory_stat *
  2200. get_memory_stat(struct mg_context *ctx)
  2201. {
  2202. if (ctx) {
  2203. return &(ctx->ctx_memory);
  2204. }
  2205. return &mg_common_memory;
  2206. }
  2207. #endif
  2208. enum {
  2209. CONNECTION_TYPE_INVALID,
  2210. CONNECTION_TYPE_REQUEST,
  2211. CONNECTION_TYPE_RESPONSE
  2212. };
  2213. struct mg_connection {
  2214. int connection_type; /* see CONNECTION_TYPE_* above */
  2215. struct mg_request_info request_info;
  2216. struct mg_response_info response_info;
  2217. struct mg_context *phys_ctx;
  2218. struct mg_domain_context *dom_ctx;
  2219. #if defined(USE_SERVER_STATS)
  2220. int conn_state; /* 0 = undef, numerical value may change in different
  2221. * versions. For the current definition, see
  2222. * mg_get_connection_info_impl */
  2223. #endif
  2224. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2225. SSL *ssl; /* SSL descriptor */
  2226. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2227. struct socket client; /* Connected client */
  2228. time_t conn_birth_time; /* Time (wall clock) when connection was
  2229. * established */
  2230. struct timespec req_time; /* Time (since system start) when the request
  2231. * was received */
  2232. int64_t num_bytes_sent; /* Total bytes sent to client */
  2233. int64_t content_len; /* Content-Length header value */
  2234. int64_t consumed_content; /* How many bytes of content have been read */
  2235. int is_chunked; /* Transfer-Encoding is chunked:
  2236. * 0 = not chunked,
  2237. * 1 = chunked, do data read yet,
  2238. * 2 = chunked, some data read,
  2239. * 3 = chunked, all data read
  2240. */
  2241. size_t chunk_remainder; /* Unread data from the last chunk */
  2242. char *buf; /* Buffer for received data */
  2243. char *path_info; /* PATH_INFO part of the URL */
  2244. int must_close; /* 1 if connection must be closed */
  2245. int accept_gzip; /* 1 if gzip encoding is accepted */
  2246. int in_error_handler; /* 1 if in handler for user defined error
  2247. * pages */
  2248. #if defined(USE_WEBSOCKET)
  2249. int in_websocket_handling; /* 1 if in read_websocket */
  2250. #endif
  2251. int handled_requests; /* Number of requests handled by this connection
  2252. */
  2253. int buf_size; /* Buffer size */
  2254. int request_len; /* Size of the request + headers in a buffer */
  2255. int data_len; /* Total size of data in a buffer */
  2256. int status_code; /* HTTP reply status code, e.g. 200 */
  2257. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2258. * throttle */
  2259. time_t last_throttle_time; /* Last time throttled data was sent */
  2260. int64_t last_throttle_bytes; /* Bytes sent this second */
  2261. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2262. * atomic transmissions for websockets */
  2263. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2264. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2265. #endif
  2266. int thread_index; /* Thread index within ctx */
  2267. };
  2268. /* Directory entry */
  2269. struct de {
  2270. struct mg_connection *conn;
  2271. char *file_name;
  2272. struct mg_file_stat file;
  2273. };
  2274. #if defined(USE_WEBSOCKET)
  2275. static int is_websocket_protocol(const struct mg_connection *conn);
  2276. #else
  2277. #define is_websocket_protocol(conn) (0)
  2278. #endif
  2279. #define mg_cry_internal(conn, fmt, ...) \
  2280. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2281. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2282. const char *func,
  2283. unsigned line,
  2284. const char *fmt,
  2285. ...) PRINTF_ARGS(4, 5);
  2286. #if !defined(NO_THREAD_NAME)
  2287. #if defined(_WIN32) && defined(_MSC_VER)
  2288. /* Set the thread name for debugging purposes in Visual Studio
  2289. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2290. */
  2291. #pragma pack(push, 8)
  2292. typedef struct tagTHREADNAME_INFO {
  2293. DWORD dwType; /* Must be 0x1000. */
  2294. LPCSTR szName; /* Pointer to name (in user addr space). */
  2295. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2296. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2297. } THREADNAME_INFO;
  2298. #pragma pack(pop)
  2299. #elif defined(__linux__)
  2300. #include <sys/prctl.h>
  2301. #include <sys/sendfile.h>
  2302. #if defined(ALTERNATIVE_QUEUE)
  2303. #include <sys/eventfd.h>
  2304. #endif /* ALTERNATIVE_QUEUE */
  2305. #if defined(ALTERNATIVE_QUEUE)
  2306. static void *
  2307. event_create(void)
  2308. {
  2309. int evhdl = eventfd(0, EFD_CLOEXEC);
  2310. int *ret;
  2311. if (evhdl == -1) {
  2312. /* Linux uses -1 on error, Windows NULL. */
  2313. /* However, Linux does not return 0 on success either. */
  2314. return 0;
  2315. }
  2316. ret = (int *)mg_malloc(sizeof(int));
  2317. if (ret) {
  2318. *ret = evhdl;
  2319. } else {
  2320. (void)close(evhdl);
  2321. }
  2322. return (void *)ret;
  2323. }
  2324. static int
  2325. event_wait(void *eventhdl)
  2326. {
  2327. uint64_t u;
  2328. int evhdl, s;
  2329. if (!eventhdl) {
  2330. /* error */
  2331. return 0;
  2332. }
  2333. evhdl = *(int *)eventhdl;
  2334. s = (int)read(evhdl, &u, sizeof(u));
  2335. if (s != sizeof(u)) {
  2336. /* error */
  2337. return 0;
  2338. }
  2339. (void)u; /* the value is not required */
  2340. return 1;
  2341. }
  2342. static int
  2343. event_signal(void *eventhdl)
  2344. {
  2345. uint64_t u = 1;
  2346. int evhdl, s;
  2347. if (!eventhdl) {
  2348. /* error */
  2349. return 0;
  2350. }
  2351. evhdl = *(int *)eventhdl;
  2352. s = (int)write(evhdl, &u, sizeof(u));
  2353. if (s != sizeof(u)) {
  2354. /* error */
  2355. return 0;
  2356. }
  2357. return 1;
  2358. }
  2359. static void
  2360. event_destroy(void *eventhdl)
  2361. {
  2362. int evhdl;
  2363. if (!eventhdl) {
  2364. /* error */
  2365. return;
  2366. }
  2367. evhdl = *(int *)eventhdl;
  2368. close(evhdl);
  2369. mg_free(eventhdl);
  2370. }
  2371. #endif
  2372. #endif
  2373. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2374. struct posix_event {
  2375. pthread_mutex_t mutex;
  2376. pthread_cond_t cond;
  2377. };
  2378. static void *
  2379. event_create(void)
  2380. {
  2381. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2382. if (ret == 0) {
  2383. /* out of memory */
  2384. return 0;
  2385. }
  2386. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2387. /* pthread mutex not available */
  2388. mg_free(ret);
  2389. return 0;
  2390. }
  2391. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2392. /* pthread cond not available */
  2393. pthread_mutex_destroy(&(ret->mutex));
  2394. mg_free(ret);
  2395. return 0;
  2396. }
  2397. return (void *)ret;
  2398. }
  2399. static int
  2400. event_wait(void *eventhdl)
  2401. {
  2402. struct posix_event *ev = (struct posix_event *)eventhdl;
  2403. pthread_mutex_lock(&(ev->mutex));
  2404. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2405. pthread_mutex_unlock(&(ev->mutex));
  2406. return 1;
  2407. }
  2408. static int
  2409. event_signal(void *eventhdl)
  2410. {
  2411. struct posix_event *ev = (struct posix_event *)eventhdl;
  2412. pthread_mutex_lock(&(ev->mutex));
  2413. pthread_cond_signal(&(ev->cond));
  2414. pthread_mutex_unlock(&(ev->mutex));
  2415. return 1;
  2416. }
  2417. static void
  2418. event_destroy(void *eventhdl)
  2419. {
  2420. struct posix_event *ev = (struct posix_event *)eventhdl;
  2421. pthread_cond_destroy(&(ev->cond));
  2422. pthread_mutex_destroy(&(ev->mutex));
  2423. mg_free(ev);
  2424. }
  2425. #endif
  2426. static void
  2427. mg_set_thread_name(const char *name)
  2428. {
  2429. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2430. mg_snprintf(
  2431. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2432. #if defined(_WIN32)
  2433. #if defined(_MSC_VER)
  2434. /* Windows and Visual Studio Compiler */
  2435. __try
  2436. {
  2437. THREADNAME_INFO info;
  2438. info.dwType = 0x1000;
  2439. info.szName = threadName;
  2440. info.dwThreadID = ~0U;
  2441. info.dwFlags = 0;
  2442. RaiseException(0x406D1388,
  2443. 0,
  2444. sizeof(info) / sizeof(ULONG_PTR),
  2445. (ULONG_PTR *)&info);
  2446. }
  2447. __except(EXCEPTION_EXECUTE_HANDLER)
  2448. {
  2449. }
  2450. #elif defined(__MINGW32__)
  2451. /* No option known to set thread name for MinGW */
  2452. #endif
  2453. #elif defined(__GLIBC__) \
  2454. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2455. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2456. (void)pthread_setname_np(pthread_self(), threadName);
  2457. #elif defined(__linux__)
  2458. /* on linux we can use the old prctl function */
  2459. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2460. #endif
  2461. }
  2462. #else /* !defined(NO_THREAD_NAME) */
  2463. void
  2464. mg_set_thread_name(const char *threadName)
  2465. {
  2466. }
  2467. #endif
  2468. #if defined(MG_LEGACY_INTERFACE)
  2469. const char **
  2470. mg_get_valid_option_names(void)
  2471. {
  2472. /* This function is deprecated. Use mg_get_valid_options instead. */
  2473. static const char *
  2474. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2475. int i;
  2476. for (i = 0; config_options[i].name != NULL; i++) {
  2477. data[i * 2] = config_options[i].name;
  2478. data[i * 2 + 1] = config_options[i].default_value;
  2479. }
  2480. return data;
  2481. }
  2482. #endif
  2483. const struct mg_option *
  2484. mg_get_valid_options(void)
  2485. {
  2486. return config_options;
  2487. }
  2488. /* Do not open file (used in is_file_in_memory) */
  2489. #define MG_FOPEN_MODE_NONE (0)
  2490. /* Open file for read only access */
  2491. #define MG_FOPEN_MODE_READ (1)
  2492. /* Open file for writing, create and overwrite */
  2493. #define MG_FOPEN_MODE_WRITE (2)
  2494. /* Open file for writing, create and append */
  2495. #define MG_FOPEN_MODE_APPEND (4)
  2496. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2497. * output filep and return 1, otherwise return 0 and don't modify anything.
  2498. */
  2499. static int
  2500. open_file_in_memory(const struct mg_connection *conn,
  2501. const char *path,
  2502. struct mg_file *filep,
  2503. int mode)
  2504. {
  2505. #if defined(MG_USE_OPEN_FILE)
  2506. size_t size = 0;
  2507. const char *buf = NULL;
  2508. if (!conn) {
  2509. return 0;
  2510. }
  2511. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2512. return 0;
  2513. }
  2514. if (conn->phys_ctx->callbacks.open_file) {
  2515. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2516. if (buf != NULL) {
  2517. if (filep == NULL) {
  2518. /* This is a file in memory, but we cannot store the
  2519. * properties
  2520. * now.
  2521. * Called from "is_file_in_memory" function. */
  2522. return 1;
  2523. }
  2524. /* NOTE: override filep->size only on success. Otherwise, it
  2525. * might
  2526. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2527. filep->access.membuf = buf;
  2528. filep->access.fp = NULL;
  2529. /* Size was set by the callback */
  2530. filep->stat.size = size;
  2531. /* Assume the data may change during runtime by setting
  2532. * last_modified = now */
  2533. filep->stat.last_modified = time(NULL);
  2534. filep->stat.is_directory = 0;
  2535. filep->stat.is_gzipped = 0;
  2536. }
  2537. }
  2538. return (buf != NULL);
  2539. #else
  2540. (void)conn;
  2541. (void)path;
  2542. (void)filep;
  2543. (void)mode;
  2544. return 0;
  2545. #endif
  2546. }
  2547. static int
  2548. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2549. {
  2550. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2551. }
  2552. static int
  2553. is_file_opened(const struct mg_file_access *fileacc)
  2554. {
  2555. if (!fileacc) {
  2556. return 0;
  2557. }
  2558. #if defined(MG_USE_OPEN_FILE)
  2559. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2560. #else
  2561. return (fileacc->fp != NULL);
  2562. #endif
  2563. }
  2564. static int mg_stat(const struct mg_connection *conn,
  2565. const char *path,
  2566. struct mg_file_stat *filep);
  2567. /* mg_fopen will open a file either in memory or on the disk.
  2568. * The input parameter path is a string in UTF-8 encoding.
  2569. * The input parameter mode is MG_FOPEN_MODE_*
  2570. * On success, either fp or membuf will be set in the output
  2571. * struct file. All status members will also be set.
  2572. * The function returns 1 on success, 0 on error. */
  2573. static int
  2574. mg_fopen(const struct mg_connection *conn,
  2575. const char *path,
  2576. int mode,
  2577. struct mg_file *filep)
  2578. {
  2579. int found;
  2580. if (!filep) {
  2581. return 0;
  2582. }
  2583. filep->access.fp = NULL;
  2584. #if defined(MG_USE_OPEN_FILE)
  2585. filep->access.membuf = NULL;
  2586. #endif
  2587. if (!is_file_in_memory(conn, path)) {
  2588. /* filep is initialized in mg_stat: all fields with memset to,
  2589. * some fields like size and modification date with values */
  2590. found = mg_stat(conn, path, &(filep->stat));
  2591. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2592. /* file does not exist and will not be created */
  2593. return 0;
  2594. }
  2595. #if defined(_WIN32)
  2596. {
  2597. wchar_t wbuf[W_PATH_MAX];
  2598. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2599. switch (mode) {
  2600. case MG_FOPEN_MODE_READ:
  2601. filep->access.fp = _wfopen(wbuf, L"rb");
  2602. break;
  2603. case MG_FOPEN_MODE_WRITE:
  2604. filep->access.fp = _wfopen(wbuf, L"wb");
  2605. break;
  2606. case MG_FOPEN_MODE_APPEND:
  2607. filep->access.fp = _wfopen(wbuf, L"ab");
  2608. break;
  2609. }
  2610. }
  2611. #else
  2612. /* Linux et al already use unicode. No need to convert. */
  2613. switch (mode) {
  2614. case MG_FOPEN_MODE_READ:
  2615. filep->access.fp = fopen(path, "r");
  2616. break;
  2617. case MG_FOPEN_MODE_WRITE:
  2618. filep->access.fp = fopen(path, "w");
  2619. break;
  2620. case MG_FOPEN_MODE_APPEND:
  2621. filep->access.fp = fopen(path, "a");
  2622. break;
  2623. }
  2624. #endif
  2625. if (!found) {
  2626. /* File did not exist before fopen was called.
  2627. * Maybe it has been created now. Get stat info
  2628. * like creation time now. */
  2629. found = mg_stat(conn, path, &(filep->stat));
  2630. (void)found;
  2631. }
  2632. /* file is on disk */
  2633. return (filep->access.fp != NULL);
  2634. } else {
  2635. #if defined(MG_USE_OPEN_FILE)
  2636. /* is_file_in_memory returned true */
  2637. if (open_file_in_memory(conn, path, filep, mode)) {
  2638. /* file is in memory */
  2639. return (filep->access.membuf != NULL);
  2640. }
  2641. #endif
  2642. }
  2643. /* Open failed */
  2644. return 0;
  2645. }
  2646. /* return 0 on success, just like fclose */
  2647. static int
  2648. mg_fclose(struct mg_file_access *fileacc)
  2649. {
  2650. int ret = -1;
  2651. if (fileacc != NULL) {
  2652. if (fileacc->fp != NULL) {
  2653. ret = fclose(fileacc->fp);
  2654. #if defined(MG_USE_OPEN_FILE)
  2655. } else if (fileacc->membuf != NULL) {
  2656. ret = 0;
  2657. #endif
  2658. }
  2659. /* reset all members of fileacc */
  2660. memset(fileacc, 0, sizeof(*fileacc));
  2661. }
  2662. return ret;
  2663. }
  2664. static void
  2665. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2666. {
  2667. for (; *src != '\0' && n > 1; n--) {
  2668. *dst++ = *src++;
  2669. }
  2670. *dst = '\0';
  2671. }
  2672. static int
  2673. lowercase(const char *s)
  2674. {
  2675. return tolower(*(const unsigned char *)s);
  2676. }
  2677. int
  2678. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2679. {
  2680. int diff = 0;
  2681. if (len > 0) {
  2682. do {
  2683. diff = lowercase(s1++) - lowercase(s2++);
  2684. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2685. }
  2686. return diff;
  2687. }
  2688. int
  2689. mg_strcasecmp(const char *s1, const char *s2)
  2690. {
  2691. int diff;
  2692. do {
  2693. diff = lowercase(s1++) - lowercase(s2++);
  2694. } while (diff == 0 && s1[-1] != '\0');
  2695. return diff;
  2696. }
  2697. static char *
  2698. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2699. {
  2700. char *p;
  2701. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2702. * defined */
  2703. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2704. mg_strlcpy(p, ptr, len + 1);
  2705. }
  2706. return p;
  2707. }
  2708. static char *
  2709. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2710. {
  2711. return mg_strndup_ctx(str, strlen(str), ctx);
  2712. }
  2713. static char *
  2714. mg_strdup(const char *str)
  2715. {
  2716. return mg_strndup_ctx(str, strlen(str), NULL);
  2717. }
  2718. static const char *
  2719. mg_strcasestr(const char *big_str, const char *small_str)
  2720. {
  2721. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2722. if (big_len >= small_len) {
  2723. for (i = 0; i <= (big_len - small_len); i++) {
  2724. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2725. return big_str + i;
  2726. }
  2727. }
  2728. }
  2729. return NULL;
  2730. }
  2731. /* Return null terminated string of given maximum length.
  2732. * Report errors if length is exceeded. */
  2733. static void
  2734. mg_vsnprintf(const struct mg_connection *conn,
  2735. int *truncated,
  2736. char *buf,
  2737. size_t buflen,
  2738. const char *fmt,
  2739. va_list ap)
  2740. {
  2741. int n, ok;
  2742. if (buflen == 0) {
  2743. if (truncated) {
  2744. *truncated = 1;
  2745. }
  2746. return;
  2747. }
  2748. #if defined(__clang__)
  2749. #pragma clang diagnostic push
  2750. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2751. /* Using fmt as a non-literal is intended here, since it is mostly called
  2752. * indirectly by mg_snprintf */
  2753. #endif
  2754. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2755. ok = (n >= 0) && ((size_t)n < buflen);
  2756. #if defined(__clang__)
  2757. #pragma clang diagnostic pop
  2758. #endif
  2759. if (ok) {
  2760. if (truncated) {
  2761. *truncated = 0;
  2762. }
  2763. } else {
  2764. if (truncated) {
  2765. *truncated = 1;
  2766. }
  2767. mg_cry_internal(conn,
  2768. "truncating vsnprintf buffer: [%.*s]",
  2769. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2770. buf);
  2771. n = (int)buflen - 1;
  2772. }
  2773. buf[n] = '\0';
  2774. }
  2775. static void
  2776. mg_snprintf(const struct mg_connection *conn,
  2777. int *truncated,
  2778. char *buf,
  2779. size_t buflen,
  2780. const char *fmt,
  2781. ...)
  2782. {
  2783. va_list ap;
  2784. va_start(ap, fmt);
  2785. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2786. va_end(ap);
  2787. }
  2788. static int
  2789. get_option_index(const char *name)
  2790. {
  2791. int i;
  2792. for (i = 0; config_options[i].name != NULL; i++) {
  2793. if (strcmp(config_options[i].name, name) == 0) {
  2794. return i;
  2795. }
  2796. }
  2797. return -1;
  2798. }
  2799. const char *
  2800. mg_get_option(const struct mg_context *ctx, const char *name)
  2801. {
  2802. int i;
  2803. if ((i = get_option_index(name)) == -1) {
  2804. return NULL;
  2805. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2806. return "";
  2807. } else {
  2808. return ctx->dd.config[i];
  2809. }
  2810. }
  2811. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2812. struct mg_context *
  2813. mg_get_context(const struct mg_connection *conn)
  2814. {
  2815. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2816. }
  2817. void *
  2818. mg_get_user_data(const struct mg_context *ctx)
  2819. {
  2820. return (ctx == NULL) ? NULL : ctx->user_data;
  2821. }
  2822. void
  2823. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2824. {
  2825. if (conn != NULL) {
  2826. conn->request_info.conn_data = data;
  2827. }
  2828. }
  2829. void *
  2830. mg_get_user_connection_data(const struct mg_connection *conn)
  2831. {
  2832. if (conn != NULL) {
  2833. return conn->request_info.conn_data;
  2834. }
  2835. return NULL;
  2836. }
  2837. #if defined(MG_LEGACY_INTERFACE)
  2838. /* Deprecated: Use mg_get_server_ports instead. */
  2839. size_t
  2840. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2841. {
  2842. size_t i;
  2843. if (!ctx) {
  2844. return 0;
  2845. }
  2846. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2847. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2848. ports[i] =
  2849. #if defined(USE_IPV6)
  2850. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2851. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2852. :
  2853. #endif
  2854. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2855. }
  2856. return i;
  2857. }
  2858. #endif
  2859. int
  2860. mg_get_server_ports(const struct mg_context *ctx,
  2861. int size,
  2862. struct mg_server_ports *ports)
  2863. {
  2864. int i, cnt = 0;
  2865. if (size <= 0) {
  2866. return -1;
  2867. }
  2868. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2869. if (!ctx) {
  2870. return -1;
  2871. }
  2872. if (!ctx->listening_sockets) {
  2873. return -1;
  2874. }
  2875. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2876. ports[cnt].port =
  2877. #if defined(USE_IPV6)
  2878. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2879. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2880. :
  2881. #endif
  2882. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2883. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2884. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2885. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2886. /* IPv4 */
  2887. ports[cnt].protocol = 1;
  2888. cnt++;
  2889. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2890. /* IPv6 */
  2891. ports[cnt].protocol = 3;
  2892. cnt++;
  2893. }
  2894. }
  2895. return cnt;
  2896. }
  2897. static void
  2898. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2899. {
  2900. buf[0] = '\0';
  2901. if (!usa) {
  2902. return;
  2903. }
  2904. if (usa->sa.sa_family == AF_INET) {
  2905. getnameinfo(&usa->sa,
  2906. sizeof(usa->sin),
  2907. buf,
  2908. (unsigned)len,
  2909. NULL,
  2910. 0,
  2911. NI_NUMERICHOST);
  2912. }
  2913. #if defined(USE_IPV6)
  2914. else if (usa->sa.sa_family == AF_INET6) {
  2915. getnameinfo(&usa->sa,
  2916. sizeof(usa->sin6),
  2917. buf,
  2918. (unsigned)len,
  2919. NULL,
  2920. 0,
  2921. NI_NUMERICHOST);
  2922. }
  2923. #endif
  2924. }
  2925. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2926. * included in all responses other than 100, 101, 5xx. */
  2927. static void
  2928. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2929. {
  2930. #if !defined(REENTRANT_TIME)
  2931. struct tm *tm;
  2932. tm = ((t != NULL) ? gmtime(t) : NULL);
  2933. if (tm != NULL) {
  2934. #else
  2935. struct tm _tm;
  2936. struct tm *tm = &_tm;
  2937. if (t != NULL) {
  2938. gmtime_r(t, tm);
  2939. #endif
  2940. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2941. } else {
  2942. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2943. buf[buf_len - 1] = '\0';
  2944. }
  2945. }
  2946. /* difftime for struct timespec. Return value is in seconds. */
  2947. static double
  2948. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2949. {
  2950. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2951. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2952. }
  2953. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2954. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2955. const char *func,
  2956. unsigned line,
  2957. const char *fmt,
  2958. va_list ap);
  2959. #include "external_mg_cry_internal_impl.inl"
  2960. #else
  2961. /* Print error message to the opened error log stream. */
  2962. static void
  2963. mg_cry_internal_impl(const struct mg_connection *conn,
  2964. const char *func,
  2965. unsigned line,
  2966. const char *fmt,
  2967. va_list ap)
  2968. {
  2969. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2970. struct mg_file fi;
  2971. time_t timestamp;
  2972. /* Unused, in the RELEASE build */
  2973. (void)func;
  2974. (void)line;
  2975. #if defined(__GNUC__) || defined(__MINGW32__)
  2976. #pragma GCC diagnostic push
  2977. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2978. #endif
  2979. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2980. #if defined(__GNUC__) || defined(__MINGW32__)
  2981. #pragma GCC diagnostic pop
  2982. #endif
  2983. buf[sizeof(buf) - 1] = 0;
  2984. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2985. if (!conn) {
  2986. puts(buf);
  2987. return;
  2988. }
  2989. /* Do not lock when getting the callback value, here and below.
  2990. * I suppose this is fine, since function cannot disappear in the
  2991. * same way string option can. */
  2992. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2993. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2994. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2995. if (mg_fopen(conn,
  2996. conn->dom_ctx->config[ERROR_LOG_FILE],
  2997. MG_FOPEN_MODE_APPEND,
  2998. &fi) == 0) {
  2999. fi.access.fp = NULL;
  3000. }
  3001. } else {
  3002. fi.access.fp = NULL;
  3003. }
  3004. if (fi.access.fp != NULL) {
  3005. flockfile(fi.access.fp);
  3006. timestamp = time(NULL);
  3007. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3008. fprintf(fi.access.fp,
  3009. "[%010lu] [error] [client %s] ",
  3010. (unsigned long)timestamp,
  3011. src_addr);
  3012. if (conn->request_info.request_method != NULL) {
  3013. fprintf(fi.access.fp,
  3014. "%s %s: ",
  3015. conn->request_info.request_method,
  3016. conn->request_info.request_uri
  3017. ? conn->request_info.request_uri
  3018. : "");
  3019. }
  3020. fprintf(fi.access.fp, "%s", buf);
  3021. fputc('\n', fi.access.fp);
  3022. fflush(fi.access.fp);
  3023. funlockfile(fi.access.fp);
  3024. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3025. * mg_cry here anyway ;-) */
  3026. }
  3027. }
  3028. }
  3029. #endif /* Externally provided function */
  3030. static void
  3031. mg_cry_internal_wrap(const struct mg_connection *conn,
  3032. const char *func,
  3033. unsigned line,
  3034. const char *fmt,
  3035. ...)
  3036. {
  3037. va_list ap;
  3038. va_start(ap, fmt);
  3039. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3040. va_end(ap);
  3041. }
  3042. void
  3043. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3044. {
  3045. va_list ap;
  3046. va_start(ap, fmt);
  3047. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3048. va_end(ap);
  3049. }
  3050. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3051. /* Return fake connection structure. Used for logging, if connection
  3052. * is not applicable at the moment of logging. */
  3053. static struct mg_connection *
  3054. fc(struct mg_context *ctx)
  3055. {
  3056. static struct mg_connection fake_connection;
  3057. fake_connection.phys_ctx = ctx;
  3058. fake_connection.dom_ctx = &(ctx->dd);
  3059. return &fake_connection;
  3060. }
  3061. const char *
  3062. mg_version(void)
  3063. {
  3064. return CIVETWEB_VERSION;
  3065. }
  3066. const struct mg_request_info *
  3067. mg_get_request_info(const struct mg_connection *conn)
  3068. {
  3069. if (!conn) {
  3070. return NULL;
  3071. }
  3072. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3073. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3074. char txt[16];
  3075. struct mg_workerTLS *tls =
  3076. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3077. sprintf(txt, "%03i", conn->response_info.status_code);
  3078. if (strlen(txt) == 3) {
  3079. memcpy(tls->txtbuf, txt, 4);
  3080. } else {
  3081. strcpy(tls->txtbuf, "ERR");
  3082. }
  3083. ((struct mg_connection *)conn)->request_info.local_uri =
  3084. ((struct mg_connection *)conn)->request_info.request_uri =
  3085. tls->txtbuf; /* use thread safe buffer */
  3086. ((struct mg_connection *)conn)->request_info.num_headers =
  3087. conn->response_info.num_headers;
  3088. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3089. conn->response_info.http_headers,
  3090. sizeof(conn->response_info.http_headers));
  3091. } else
  3092. #endif
  3093. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3094. return NULL;
  3095. }
  3096. return &conn->request_info;
  3097. }
  3098. const struct mg_response_info *
  3099. mg_get_response_info(const struct mg_connection *conn)
  3100. {
  3101. if (!conn) {
  3102. return NULL;
  3103. }
  3104. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3105. return NULL;
  3106. }
  3107. return &conn->response_info;
  3108. }
  3109. static const char *
  3110. get_proto_name(const struct mg_connection *conn)
  3111. {
  3112. #if defined(__clang__)
  3113. #pragma clang diagnostic push
  3114. #pragma clang diagnostic ignored "-Wunreachable-code"
  3115. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3116. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3117. * unreachable, but splitting into four different #ifdef clauses here is more
  3118. * complicated.
  3119. */
  3120. #endif
  3121. const struct mg_request_info *ri = &conn->request_info;
  3122. const char *proto =
  3123. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3124. : (ri->is_ssl ? "https" : "http"));
  3125. return proto;
  3126. #if defined(__clang__)
  3127. #pragma clang diagnostic pop
  3128. #endif
  3129. }
  3130. int
  3131. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3132. {
  3133. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3134. return -1;
  3135. } else {
  3136. int truncated = 0;
  3137. const struct mg_request_info *ri = &conn->request_info;
  3138. const char *proto = get_proto_name(conn);
  3139. if (ri->local_uri == NULL) {
  3140. return -1;
  3141. }
  3142. if ((ri->request_uri != NULL)
  3143. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3144. /* The request uri is different from the local uri.
  3145. * This is usually if an absolute URI, including server
  3146. * name has been provided. */
  3147. mg_snprintf(conn,
  3148. &truncated,
  3149. buf,
  3150. buflen,
  3151. "%s://%s",
  3152. proto,
  3153. ri->request_uri);
  3154. if (truncated) {
  3155. return -1;
  3156. }
  3157. return 0;
  3158. } else {
  3159. /* The common case is a relative URI, so we have to
  3160. * construct an absolute URI from server name and port */
  3161. #if defined(USE_IPV6)
  3162. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3163. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3164. : htons(conn->client.lsa.sin.sin_port);
  3165. #else
  3166. int port = htons(conn->client.lsa.sin.sin_port);
  3167. #endif
  3168. int def_port = ri->is_ssl ? 443 : 80;
  3169. int auth_domain_check_enabled =
  3170. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3171. && (!mg_strcasecmp(
  3172. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  3173. "yes"));
  3174. const char *server_domain =
  3175. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3176. char portstr[16];
  3177. char server_ip[48];
  3178. if (port != def_port) {
  3179. sprintf(portstr, ":%u", (unsigned)port);
  3180. } else {
  3181. portstr[0] = 0;
  3182. }
  3183. if (!auth_domain_check_enabled || !server_domain) {
  3184. sockaddr_to_string(server_ip,
  3185. sizeof(server_ip),
  3186. &conn->client.lsa);
  3187. server_domain = server_ip;
  3188. }
  3189. mg_snprintf(conn,
  3190. &truncated,
  3191. buf,
  3192. buflen,
  3193. "%s://%s%s%s",
  3194. proto,
  3195. server_domain,
  3196. portstr,
  3197. ri->local_uri);
  3198. if (truncated) {
  3199. return -1;
  3200. }
  3201. return 0;
  3202. }
  3203. }
  3204. }
  3205. /* Skip the characters until one of the delimiters characters found.
  3206. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3207. * Advance pointer to buffer to the next word. Return found 0-terminated
  3208. * word.
  3209. * Delimiters can be quoted with quotechar. */
  3210. static char *
  3211. skip_quoted(char **buf,
  3212. const char *delimiters,
  3213. const char *whitespace,
  3214. char quotechar)
  3215. {
  3216. char *p, *begin_word, *end_word, *end_whitespace;
  3217. begin_word = *buf;
  3218. end_word = begin_word + strcspn(begin_word, delimiters);
  3219. /* Check for quotechar */
  3220. if (end_word > begin_word) {
  3221. p = end_word - 1;
  3222. while (*p == quotechar) {
  3223. /* While the delimiter is quoted, look for the next delimiter.
  3224. */
  3225. /* This happens, e.g., in calls from parse_auth_header,
  3226. * if the user name contains a " character. */
  3227. /* If there is anything beyond end_word, copy it. */
  3228. if (*end_word != '\0') {
  3229. size_t end_off = strcspn(end_word + 1, delimiters);
  3230. memmove(p, end_word, end_off + 1);
  3231. p += end_off; /* p must correspond to end_word - 1 */
  3232. end_word += end_off + 1;
  3233. } else {
  3234. *p = '\0';
  3235. break;
  3236. }
  3237. }
  3238. for (p++; p < end_word; p++) {
  3239. *p = '\0';
  3240. }
  3241. }
  3242. if (*end_word == '\0') {
  3243. *buf = end_word;
  3244. } else {
  3245. #if defined(__GNUC__) || defined(__MINGW32__)
  3246. /* Disable spurious conversion warning for GCC */
  3247. #if GCC_VERSION >= 40500
  3248. #pragma GCC diagnostic push
  3249. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3250. #endif /* GCC_VERSION >= 40500 */
  3251. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3252. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3253. #if defined(__GNUC__) || defined(__MINGW32__)
  3254. #if GCC_VERSION >= 40500
  3255. #pragma GCC diagnostic pop
  3256. #endif /* GCC_VERSION >= 40500 */
  3257. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3258. for (p = end_word; p < end_whitespace; p++) {
  3259. *p = '\0';
  3260. }
  3261. *buf = end_whitespace;
  3262. }
  3263. return begin_word;
  3264. }
  3265. /* Return HTTP header value, or NULL if not found. */
  3266. static const char *
  3267. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3268. {
  3269. int i;
  3270. for (i = 0; i < num_hdr; i++) {
  3271. if (!mg_strcasecmp(name, hdr[i].name)) {
  3272. return hdr[i].value;
  3273. }
  3274. }
  3275. return NULL;
  3276. }
  3277. #if defined(USE_WEBSOCKET)
  3278. /* Retrieve requested HTTP header multiple values, and return the number of
  3279. * found occurrences */
  3280. static int
  3281. get_req_headers(const struct mg_request_info *ri,
  3282. const char *name,
  3283. const char **output,
  3284. int output_max_size)
  3285. {
  3286. int i;
  3287. int cnt = 0;
  3288. if (ri) {
  3289. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3290. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3291. output[cnt++] = ri->http_headers[i].value;
  3292. }
  3293. }
  3294. }
  3295. return cnt;
  3296. }
  3297. #endif
  3298. const char *
  3299. mg_get_header(const struct mg_connection *conn, const char *name)
  3300. {
  3301. if (!conn) {
  3302. return NULL;
  3303. }
  3304. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3305. return get_header(conn->request_info.http_headers,
  3306. conn->request_info.num_headers,
  3307. name);
  3308. }
  3309. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3310. return get_header(conn->response_info.http_headers,
  3311. conn->response_info.num_headers,
  3312. name);
  3313. }
  3314. return NULL;
  3315. }
  3316. static const char *
  3317. get_http_version(const struct mg_connection *conn)
  3318. {
  3319. if (!conn) {
  3320. return NULL;
  3321. }
  3322. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3323. return conn->request_info.http_version;
  3324. }
  3325. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3326. return conn->response_info.http_version;
  3327. }
  3328. return NULL;
  3329. }
  3330. /* A helper function for traversing a comma separated list of values.
  3331. * It returns a list pointer shifted to the next value, or NULL if the end
  3332. * of the list found.
  3333. * Value is stored in val vector. If value has form "x=y", then eq_val
  3334. * vector is initialized to point to the "y" part, and val vector length
  3335. * is adjusted to point only to "x". */
  3336. static const char *
  3337. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3338. {
  3339. int end;
  3340. reparse:
  3341. if (val == NULL || list == NULL || *list == '\0') {
  3342. /* End of the list */
  3343. return NULL;
  3344. }
  3345. /* Skip over leading LWS */
  3346. while (*list == ' ' || *list == '\t')
  3347. list++;
  3348. val->ptr = list;
  3349. if ((list = strchr(val->ptr, ',')) != NULL) {
  3350. /* Comma found. Store length and shift the list ptr */
  3351. val->len = ((size_t)(list - val->ptr));
  3352. list++;
  3353. } else {
  3354. /* This value is the last one */
  3355. list = val->ptr + strlen(val->ptr);
  3356. val->len = ((size_t)(list - val->ptr));
  3357. }
  3358. /* Adjust length for trailing LWS */
  3359. end = (int)val->len - 1;
  3360. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3361. end--;
  3362. val->len = (size_t)(end + 1);
  3363. if (val->len == 0) {
  3364. /* Ignore any empty entries. */
  3365. goto reparse;
  3366. }
  3367. if (eq_val != NULL) {
  3368. /* Value has form "x=y", adjust pointers and lengths
  3369. * so that val points to "x", and eq_val points to "y". */
  3370. eq_val->len = 0;
  3371. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3372. if (eq_val->ptr != NULL) {
  3373. eq_val->ptr++; /* Skip over '=' character */
  3374. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3375. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3376. }
  3377. }
  3378. return list;
  3379. }
  3380. /* A helper function for checking if a comma separated list of values
  3381. * contains
  3382. * the given option (case insensitvely).
  3383. * 'header' can be NULL, in which case false is returned. */
  3384. static int
  3385. header_has_option(const char *header, const char *option)
  3386. {
  3387. struct vec opt_vec;
  3388. struct vec eq_vec;
  3389. DEBUG_ASSERT(option != NULL);
  3390. DEBUG_ASSERT(option[0] != '\0');
  3391. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3392. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3393. return 1;
  3394. }
  3395. return 0;
  3396. }
  3397. /* Perform case-insensitive match of string against pattern */
  3398. static ptrdiff_t
  3399. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3400. {
  3401. const char *or_str;
  3402. ptrdiff_t i, j, len, res;
  3403. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3404. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3405. return (res > 0) ? res : match_prefix(or_str + 1,
  3406. (size_t)((pattern + pattern_len)
  3407. - (or_str + 1)),
  3408. str);
  3409. }
  3410. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3411. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3412. continue;
  3413. } else if (pattern[i] == '$') {
  3414. return (str[j] == '\0') ? j : -1;
  3415. } else if (pattern[i] == '*') {
  3416. i++;
  3417. if (pattern[i] == '*') {
  3418. i++;
  3419. len = strlen(str + j);
  3420. } else {
  3421. len = strcspn(str + j, "/");
  3422. }
  3423. if (i == (ptrdiff_t)pattern_len) {
  3424. return j + len;
  3425. }
  3426. do {
  3427. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3428. } while (res == -1 && len-- > 0);
  3429. return (res == -1) ? -1 : j + res + len;
  3430. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3431. return -1;
  3432. }
  3433. }
  3434. return (ptrdiff_t)j;
  3435. }
  3436. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3437. * This function must tolerate situations when connection info is not
  3438. * set up, for example if request parsing failed. */
  3439. static int
  3440. should_keep_alive(const struct mg_connection *conn)
  3441. {
  3442. const char *http_version;
  3443. const char *header;
  3444. /* First satisfy needs of the server */
  3445. if ((conn == NULL) || conn->must_close) {
  3446. /* Close, if civetweb framework needs to close */
  3447. return 0;
  3448. }
  3449. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3450. /* Close, if keep alive is not enabled */
  3451. return 0;
  3452. }
  3453. /* Check explicit wish of the client */
  3454. header = mg_get_header(conn, "Connection");
  3455. if (header) {
  3456. /* If there is a connection header from the client, obey */
  3457. if (header_has_option(header, "keep-alive")) {
  3458. return 1;
  3459. }
  3460. return 0;
  3461. }
  3462. /* Use default of the standard */
  3463. http_version = get_http_version(conn);
  3464. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3465. /* HTTP 1.1 default is keep alive */
  3466. return 1;
  3467. }
  3468. /* HTTP 1.0 (and earlier) default is to close the connection */
  3469. return 0;
  3470. }
  3471. static int
  3472. should_decode_url(const struct mg_connection *conn)
  3473. {
  3474. if (!conn || !conn->dom_ctx) {
  3475. return 0;
  3476. }
  3477. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3478. }
  3479. static const char *
  3480. suggest_connection_header(const struct mg_connection *conn)
  3481. {
  3482. return should_keep_alive(conn) ? "keep-alive" : "close";
  3483. }
  3484. static int
  3485. send_no_cache_header(struct mg_connection *conn)
  3486. {
  3487. /* Send all current and obsolete cache opt-out directives. */
  3488. return mg_printf(conn,
  3489. "Cache-Control: no-cache, no-store, "
  3490. "must-revalidate, private, max-age=0\r\n"
  3491. "Pragma: no-cache\r\n"
  3492. "Expires: 0\r\n");
  3493. }
  3494. static int
  3495. send_static_cache_header(struct mg_connection *conn)
  3496. {
  3497. #if !defined(NO_CACHING)
  3498. /* Read the server config to check how long a file may be cached.
  3499. * The configuration is in seconds. */
  3500. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3501. if (max_age <= 0) {
  3502. /* 0 means "do not cache". All values <0 are reserved
  3503. * and may be used differently in the future. */
  3504. /* If a file should not be cached, do not only send
  3505. * max-age=0, but also pragmas and Expires headers. */
  3506. return send_no_cache_header(conn);
  3507. }
  3508. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3509. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3510. /* See also https://www.mnot.net/cache_docs/ */
  3511. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3512. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3513. * leap
  3514. * year to 31622400 seconds. For the moment, we just send whatever has
  3515. * been configured, still the behavior for >1 year should be considered
  3516. * as undefined. */
  3517. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3518. #else /* NO_CACHING */
  3519. return send_no_cache_header(conn);
  3520. #endif /* !NO_CACHING */
  3521. }
  3522. static int
  3523. send_additional_header(struct mg_connection *conn)
  3524. {
  3525. int i = 0;
  3526. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3527. #if !defined(NO_SSL)
  3528. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3529. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3530. if (max_age >= 0) {
  3531. i += mg_printf(conn,
  3532. "Strict-Transport-Security: max-age=%u\r\n",
  3533. (unsigned)max_age);
  3534. }
  3535. }
  3536. #endif
  3537. if (header && header[0]) {
  3538. i += mg_printf(conn, "%s\r\n", header);
  3539. }
  3540. return i;
  3541. }
  3542. static void handle_file_based_request(struct mg_connection *conn,
  3543. const char *path,
  3544. struct mg_file *filep);
  3545. const char *
  3546. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3547. {
  3548. /* See IANA HTTP status code assignment:
  3549. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3550. */
  3551. switch (response_code) {
  3552. /* RFC2616 Section 10.1 - Informational 1xx */
  3553. case 100:
  3554. return "Continue"; /* RFC2616 Section 10.1.1 */
  3555. case 101:
  3556. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3557. case 102:
  3558. return "Processing"; /* RFC2518 Section 10.1 */
  3559. /* RFC2616 Section 10.2 - Successful 2xx */
  3560. case 200:
  3561. return "OK"; /* RFC2616 Section 10.2.1 */
  3562. case 201:
  3563. return "Created"; /* RFC2616 Section 10.2.2 */
  3564. case 202:
  3565. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3566. case 203:
  3567. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3568. case 204:
  3569. return "No Content"; /* RFC2616 Section 10.2.5 */
  3570. case 205:
  3571. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3572. case 206:
  3573. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3574. case 207:
  3575. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3576. */
  3577. case 208:
  3578. return "Already Reported"; /* RFC5842 Section 7.1 */
  3579. case 226:
  3580. return "IM used"; /* RFC3229 Section 10.4.1 */
  3581. /* RFC2616 Section 10.3 - Redirection 3xx */
  3582. case 300:
  3583. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3584. case 301:
  3585. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3586. case 302:
  3587. return "Found"; /* RFC2616 Section 10.3.3 */
  3588. case 303:
  3589. return "See Other"; /* RFC2616 Section 10.3.4 */
  3590. case 304:
  3591. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3592. case 305:
  3593. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3594. case 307:
  3595. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3596. case 308:
  3597. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3598. /* RFC2616 Section 10.4 - Client Error 4xx */
  3599. case 400:
  3600. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3601. case 401:
  3602. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3603. case 402:
  3604. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3605. case 403:
  3606. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3607. case 404:
  3608. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3609. case 405:
  3610. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3611. case 406:
  3612. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3613. case 407:
  3614. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3615. case 408:
  3616. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3617. case 409:
  3618. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3619. case 410:
  3620. return "Gone"; /* RFC2616 Section 10.4.11 */
  3621. case 411:
  3622. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3623. case 412:
  3624. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3625. case 413:
  3626. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3627. case 414:
  3628. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3629. case 415:
  3630. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3631. case 416:
  3632. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3633. */
  3634. case 417:
  3635. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3636. case 421:
  3637. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3638. case 422:
  3639. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3640. * Section 11.2 */
  3641. case 423:
  3642. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3643. case 424:
  3644. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3645. * Section 11.4 */
  3646. case 426:
  3647. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3648. case 428:
  3649. return "Precondition Required"; /* RFC 6585, Section 3 */
  3650. case 429:
  3651. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3652. case 431:
  3653. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3654. case 451:
  3655. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3656. * Section 3 */
  3657. /* RFC2616 Section 10.5 - Server Error 5xx */
  3658. case 500:
  3659. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3660. case 501:
  3661. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3662. case 502:
  3663. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3664. case 503:
  3665. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3666. case 504:
  3667. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3668. case 505:
  3669. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3670. case 506:
  3671. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3672. case 507:
  3673. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3674. * Section 11.5 */
  3675. case 508:
  3676. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3677. case 510:
  3678. return "Not Extended"; /* RFC 2774, Section 7 */
  3679. case 511:
  3680. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3681. /* Other status codes, not shown in the IANA HTTP status code
  3682. * assignment.
  3683. * E.g., "de facto" standards due to common use, ... */
  3684. case 418:
  3685. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3686. case 419:
  3687. return "Authentication Timeout"; /* common use */
  3688. case 420:
  3689. return "Enhance Your Calm"; /* common use */
  3690. case 440:
  3691. return "Login Timeout"; /* common use */
  3692. case 509:
  3693. return "Bandwidth Limit Exceeded"; /* common use */
  3694. default:
  3695. /* This error code is unknown. This should not happen. */
  3696. if (conn) {
  3697. mg_cry_internal(conn,
  3698. "Unknown HTTP response code: %u",
  3699. response_code);
  3700. }
  3701. /* Return at least a category according to RFC 2616 Section 10. */
  3702. if (response_code >= 100 && response_code < 200) {
  3703. /* Unknown informational status code */
  3704. return "Information";
  3705. }
  3706. if (response_code >= 200 && response_code < 300) {
  3707. /* Unknown success code */
  3708. return "Success";
  3709. }
  3710. if (response_code >= 300 && response_code < 400) {
  3711. /* Unknown redirection code */
  3712. return "Redirection";
  3713. }
  3714. if (response_code >= 400 && response_code < 500) {
  3715. /* Unknown request error code */
  3716. return "Client Error";
  3717. }
  3718. if (response_code >= 500 && response_code < 600) {
  3719. /* Unknown server error code */
  3720. return "Server Error";
  3721. }
  3722. /* Response code not even within reasonable range */
  3723. return "";
  3724. }
  3725. }
  3726. static void
  3727. mg_send_http_error_impl(struct mg_connection *conn,
  3728. int status,
  3729. const char *fmt,
  3730. va_list args)
  3731. {
  3732. char errmsg_buf[MG_BUF_LEN];
  3733. char path_buf[PATH_MAX];
  3734. va_list ap;
  3735. int len, i, page_handler_found, scope, truncated, has_body;
  3736. char date[64];
  3737. time_t curtime = time(NULL);
  3738. const char *error_handler = NULL;
  3739. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3740. const char *error_page_file_ext, *tstr;
  3741. int handled_by_callback = 0;
  3742. const char *status_text = mg_get_response_code_text(conn, status);
  3743. if ((conn == NULL) || (fmt == NULL)) {
  3744. return;
  3745. }
  3746. /* Set status (for log) */
  3747. conn->status_code = status;
  3748. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3749. has_body = ((status > 199) && (status != 204) && (status != 304));
  3750. /* Prepare message in buf, if required */
  3751. if (has_body || (!conn->in_error_handler
  3752. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3753. /* Store error message in errmsg_buf */
  3754. va_copy(ap, args);
  3755. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3756. va_end(ap);
  3757. /* In a debug build, print all html errors */
  3758. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3759. }
  3760. /* If there is a http_error callback, call it.
  3761. * But don't do it recursively, if callback calls mg_send_http_error again.
  3762. */
  3763. if (!conn->in_error_handler
  3764. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3765. /* Mark in_error_handler to avoid recursion and call user callback. */
  3766. conn->in_error_handler = 1;
  3767. handled_by_callback =
  3768. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3769. == 0);
  3770. conn->in_error_handler = 0;
  3771. }
  3772. if (!handled_by_callback) {
  3773. /* Check for recursion */
  3774. if (conn->in_error_handler) {
  3775. DEBUG_TRACE(
  3776. "Recursion when handling error %u - fall back to default",
  3777. status);
  3778. } else {
  3779. /* Send user defined error pages, if defined */
  3780. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3781. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3782. page_handler_found = 0;
  3783. if (error_handler != NULL) {
  3784. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3785. switch (scope) {
  3786. case 1: /* Handler for specific error, e.g. 404 error */
  3787. mg_snprintf(conn,
  3788. &truncated,
  3789. path_buf,
  3790. sizeof(path_buf) - 32,
  3791. "%serror%03u.",
  3792. error_handler,
  3793. status);
  3794. break;
  3795. case 2: /* Handler for error group, e.g., 5xx error
  3796. * handler
  3797. * for all server errors (500-599) */
  3798. mg_snprintf(conn,
  3799. &truncated,
  3800. path_buf,
  3801. sizeof(path_buf) - 32,
  3802. "%serror%01uxx.",
  3803. error_handler,
  3804. status / 100);
  3805. break;
  3806. default: /* Handler for all errors */
  3807. mg_snprintf(conn,
  3808. &truncated,
  3809. path_buf,
  3810. sizeof(path_buf) - 32,
  3811. "%serror.",
  3812. error_handler);
  3813. break;
  3814. }
  3815. /* String truncation in buf may only occur if
  3816. * error_handler is too long. This string is
  3817. * from the config, not from a client. */
  3818. (void)truncated;
  3819. len = (int)strlen(path_buf);
  3820. tstr = strchr(error_page_file_ext, '.');
  3821. while (tstr) {
  3822. for (i = 1;
  3823. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3824. i++) {
  3825. /* buffer overrun is not possible here, since
  3826. * (i < 32) && (len < sizeof(path_buf) - 32)
  3827. * ==> (i + len) < sizeof(path_buf) */
  3828. path_buf[len + i - 1] = tstr[i];
  3829. }
  3830. /* buffer overrun is not possible here, since
  3831. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3832. * ==> (i + len) <= sizeof(path_buf) */
  3833. path_buf[len + i - 1] = 0;
  3834. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3835. DEBUG_TRACE("Check error page %s - found",
  3836. path_buf);
  3837. page_handler_found = 1;
  3838. break;
  3839. }
  3840. DEBUG_TRACE("Check error page %s - not found",
  3841. path_buf);
  3842. tstr = strchr(tstr + i, '.');
  3843. }
  3844. }
  3845. }
  3846. if (page_handler_found) {
  3847. conn->in_error_handler = 1;
  3848. handle_file_based_request(conn, path_buf, &error_page_file);
  3849. conn->in_error_handler = 0;
  3850. return;
  3851. }
  3852. }
  3853. /* No custom error page. Send default error page. */
  3854. gmt_time_string(date, sizeof(date), &curtime);
  3855. conn->must_close = 1;
  3856. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3857. send_no_cache_header(conn);
  3858. send_additional_header(conn);
  3859. if (has_body) {
  3860. mg_printf(conn,
  3861. "%s",
  3862. "Content-Type: text/plain; charset=utf-8\r\n");
  3863. }
  3864. mg_printf(conn,
  3865. "Date: %s\r\n"
  3866. "Connection: close\r\n\r\n",
  3867. date);
  3868. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3869. if (has_body) {
  3870. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3871. if (fmt != NULL) { /* <-- should be always true */
  3872. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3873. }
  3874. } else {
  3875. /* No body allowed. Close the connection. */
  3876. DEBUG_TRACE("Error %i", status);
  3877. }
  3878. }
  3879. }
  3880. void
  3881. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3882. {
  3883. va_list ap;
  3884. va_start(ap, fmt);
  3885. mg_send_http_error_impl(conn, status, fmt, ap);
  3886. va_end(ap);
  3887. }
  3888. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3889. /* Create substitutes for POSIX functions in Win32. */
  3890. #if defined(__MINGW32__)
  3891. /* Show no warning in case system functions are not used. */
  3892. #pragma GCC diagnostic push
  3893. #pragma GCC diagnostic ignored "-Wunused-function"
  3894. #endif
  3895. FUNCTION_MAY_BE_UNUSED
  3896. static int
  3897. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3898. {
  3899. (void)unused;
  3900. *mutex = CreateMutex(NULL, FALSE, NULL);
  3901. return (*mutex == NULL) ? -1 : 0;
  3902. }
  3903. FUNCTION_MAY_BE_UNUSED
  3904. static int
  3905. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3906. {
  3907. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3908. }
  3909. FUNCTION_MAY_BE_UNUSED
  3910. static int
  3911. pthread_mutex_lock(pthread_mutex_t *mutex)
  3912. {
  3913. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  3914. : -1;
  3915. }
  3916. #if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS)
  3917. FUNCTION_MAY_BE_UNUSED
  3918. static int
  3919. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3920. {
  3921. switch (WaitForSingleObject(*mutex, 0)) {
  3922. case WAIT_OBJECT_0:
  3923. return 0;
  3924. case WAIT_TIMEOUT:
  3925. return -2; /* EBUSY */
  3926. }
  3927. return -1;
  3928. }
  3929. #endif
  3930. FUNCTION_MAY_BE_UNUSED
  3931. static int
  3932. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3933. {
  3934. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3935. }
  3936. FUNCTION_MAY_BE_UNUSED
  3937. static int
  3938. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3939. {
  3940. (void)unused;
  3941. InitializeCriticalSection(&cv->threadIdSec);
  3942. cv->waiting_thread = NULL;
  3943. return 0;
  3944. }
  3945. FUNCTION_MAY_BE_UNUSED
  3946. static int
  3947. pthread_cond_timedwait(pthread_cond_t *cv,
  3948. pthread_mutex_t *mutex,
  3949. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  3950. {
  3951. struct mg_workerTLS **ptls,
  3952. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3953. int ok;
  3954. int64_t nsnow, nswaitabs, nswaitrel;
  3955. DWORD mswaitrel;
  3956. EnterCriticalSection(&cv->threadIdSec);
  3957. /* Add this thread to cv's waiting list */
  3958. ptls = &cv->waiting_thread;
  3959. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3960. ;
  3961. tls->next_waiting_thread = NULL;
  3962. *ptls = tls;
  3963. LeaveCriticalSection(&cv->threadIdSec);
  3964. if (abstime) {
  3965. nsnow = mg_get_current_time_ns();
  3966. nswaitabs =
  3967. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3968. nswaitrel = nswaitabs - nsnow;
  3969. if (nswaitrel < 0) {
  3970. nswaitrel = 0;
  3971. }
  3972. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3973. } else {
  3974. mswaitrel = (DWORD)INFINITE;
  3975. }
  3976. pthread_mutex_unlock(mutex);
  3977. ok = (WAIT_OBJECT_0
  3978. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3979. if (!ok) {
  3980. ok = 1;
  3981. EnterCriticalSection(&cv->threadIdSec);
  3982. ptls = &cv->waiting_thread;
  3983. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3984. if (*ptls == tls) {
  3985. *ptls = tls->next_waiting_thread;
  3986. ok = 0;
  3987. break;
  3988. }
  3989. }
  3990. LeaveCriticalSection(&cv->threadIdSec);
  3991. if (ok) {
  3992. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  3993. (DWORD)INFINITE);
  3994. }
  3995. }
  3996. /* This thread has been removed from cv's waiting list */
  3997. pthread_mutex_lock(mutex);
  3998. return ok ? 0 : -1;
  3999. }
  4000. FUNCTION_MAY_BE_UNUSED
  4001. static int
  4002. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4003. {
  4004. return pthread_cond_timedwait(cv, mutex, NULL);
  4005. }
  4006. FUNCTION_MAY_BE_UNUSED
  4007. static int
  4008. pthread_cond_signal(pthread_cond_t *cv)
  4009. {
  4010. HANDLE wkup = NULL;
  4011. BOOL ok = FALSE;
  4012. EnterCriticalSection(&cv->threadIdSec);
  4013. if (cv->waiting_thread) {
  4014. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4015. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4016. ok = SetEvent(wkup);
  4017. DEBUG_ASSERT(ok);
  4018. }
  4019. LeaveCriticalSection(&cv->threadIdSec);
  4020. return ok ? 0 : 1;
  4021. }
  4022. FUNCTION_MAY_BE_UNUSED
  4023. static int
  4024. pthread_cond_broadcast(pthread_cond_t *cv)
  4025. {
  4026. EnterCriticalSection(&cv->threadIdSec);
  4027. while (cv->waiting_thread) {
  4028. pthread_cond_signal(cv);
  4029. }
  4030. LeaveCriticalSection(&cv->threadIdSec);
  4031. return 0;
  4032. }
  4033. FUNCTION_MAY_BE_UNUSED
  4034. static int
  4035. pthread_cond_destroy(pthread_cond_t *cv)
  4036. {
  4037. EnterCriticalSection(&cv->threadIdSec);
  4038. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4039. LeaveCriticalSection(&cv->threadIdSec);
  4040. DeleteCriticalSection(&cv->threadIdSec);
  4041. return 0;
  4042. }
  4043. #if defined(ALTERNATIVE_QUEUE)
  4044. FUNCTION_MAY_BE_UNUSED
  4045. static void *
  4046. event_create(void)
  4047. {
  4048. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4049. }
  4050. FUNCTION_MAY_BE_UNUSED
  4051. static int
  4052. event_wait(void *eventhdl)
  4053. {
  4054. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4055. return (res == WAIT_OBJECT_0);
  4056. }
  4057. FUNCTION_MAY_BE_UNUSED
  4058. static int
  4059. event_signal(void *eventhdl)
  4060. {
  4061. return (int)SetEvent((HANDLE)eventhdl);
  4062. }
  4063. FUNCTION_MAY_BE_UNUSED
  4064. static void
  4065. event_destroy(void *eventhdl)
  4066. {
  4067. CloseHandle((HANDLE)eventhdl);
  4068. }
  4069. #endif
  4070. #if defined(__MINGW32__)
  4071. /* Enable unused function warning again */
  4072. #pragma GCC diagnostic pop
  4073. #endif
  4074. /* For Windows, change all slashes to backslashes in path names. */
  4075. static void
  4076. change_slashes_to_backslashes(char *path)
  4077. {
  4078. int i;
  4079. for (i = 0; path[i] != '\0'; i++) {
  4080. if (path[i] == '/') {
  4081. path[i] = '\\';
  4082. }
  4083. /* remove double backslash (check i > 0 to preserve UNC paths,
  4084. * like \\server\file.txt) */
  4085. if ((path[i] == '\\') && (i > 0)) {
  4086. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4087. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4088. }
  4089. }
  4090. }
  4091. }
  4092. static int
  4093. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4094. {
  4095. int diff;
  4096. do {
  4097. diff = tolower(*s1) - tolower(*s2);
  4098. s1++;
  4099. s2++;
  4100. } while ((diff == 0) && (s1[-1] != '\0'));
  4101. return diff;
  4102. }
  4103. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4104. * wbuf and wbuf_len is a target buffer and its length. */
  4105. static void
  4106. path_to_unicode(const struct mg_connection *conn,
  4107. const char *path,
  4108. wchar_t *wbuf,
  4109. size_t wbuf_len)
  4110. {
  4111. char buf[PATH_MAX], buf2[PATH_MAX];
  4112. wchar_t wbuf2[W_PATH_MAX + 1];
  4113. DWORD long_len, err;
  4114. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4115. mg_strlcpy(buf, path, sizeof(buf));
  4116. change_slashes_to_backslashes(buf);
  4117. /* Convert to Unicode and back. If doubly-converted string does not
  4118. * match the original, something is fishy, reject. */
  4119. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4120. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4121. WideCharToMultiByte(
  4122. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4123. if (strcmp(buf, buf2) != 0) {
  4124. wbuf[0] = L'\0';
  4125. }
  4126. /* Windows file systems are not case sensitive, but you can still use
  4127. * uppercase and lowercase letters (on all modern file systems).
  4128. * The server can check if the URI uses the same upper/lowercase
  4129. * letters an the file system, effectively making Windows servers
  4130. * case sensitive (like Linux servers are). It is still not possible
  4131. * to use two files with the same name in different cases on Windows
  4132. * (like /a and /A) - this would be possible in Linux.
  4133. * As a default, Windows is not case sensitive, but the case sensitive
  4134. * file name check can be activated by an additional configuration. */
  4135. if (conn) {
  4136. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4137. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4138. "yes")) {
  4139. /* Use case sensitive compare function */
  4140. fcompare = wcscmp;
  4141. }
  4142. }
  4143. (void)conn; /* conn is currently unused */
  4144. #if !defined(_WIN32_WCE)
  4145. /* Only accept a full file path, not a Windows short (8.3) path. */
  4146. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4147. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4148. if (long_len == 0) {
  4149. err = GetLastError();
  4150. if (err == ERROR_FILE_NOT_FOUND) {
  4151. /* File does not exist. This is not always a problem here. */
  4152. return;
  4153. }
  4154. }
  4155. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4156. /* Short name is used. */
  4157. wbuf[0] = L'\0';
  4158. }
  4159. #else
  4160. (void)long_len;
  4161. (void)wbuf2;
  4162. (void)err;
  4163. if (strchr(path, '~')) {
  4164. wbuf[0] = L'\0';
  4165. }
  4166. #endif
  4167. }
  4168. /* Windows happily opens files with some garbage at the end of file name.
  4169. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4170. * "a.cgi", despite one would expect an error back.
  4171. * This function returns non-0 if path ends with some garbage. */
  4172. static int
  4173. path_cannot_disclose_cgi(const char *path)
  4174. {
  4175. static const char *allowed_last_characters = "_-";
  4176. int last = path[strlen(path) - 1];
  4177. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  4178. }
  4179. static int
  4180. mg_stat(const struct mg_connection *conn,
  4181. const char *path,
  4182. struct mg_file_stat *filep)
  4183. {
  4184. wchar_t wbuf[W_PATH_MAX];
  4185. WIN32_FILE_ATTRIBUTE_DATA info;
  4186. time_t creation_time;
  4187. if (!filep) {
  4188. return 0;
  4189. }
  4190. memset(filep, 0, sizeof(*filep));
  4191. if (conn && is_file_in_memory(conn, path)) {
  4192. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4193. * memset */
  4194. /* Quick fix (for 1.9.x): */
  4195. /* mg_stat must fill all fields, also for files in memory */
  4196. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4197. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4198. filep->size = tmp_file.stat.size;
  4199. filep->location = 2;
  4200. /* TODO: for 1.10: restructure how files in memory are handled */
  4201. /* The "file in memory" feature is a candidate for deletion.
  4202. * Please join the discussion at
  4203. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4204. */
  4205. filep->last_modified = time(NULL); /* TODO */
  4206. /* last_modified = now ... assumes the file may change during
  4207. * runtime,
  4208. * so every mg_fopen call may return different data */
  4209. /* last_modified = conn->phys_ctx.start_time;
  4210. * May be used it the data does not change during runtime. This
  4211. * allows
  4212. * browser caching. Since we do not know, we have to assume the file
  4213. * in memory may change. */
  4214. return 1;
  4215. }
  4216. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4217. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  4218. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4219. filep->last_modified =
  4220. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4221. info.ftLastWriteTime.dwHighDateTime);
  4222. /* On Windows, the file creation time can be higher than the
  4223. * modification time, e.g. when a file is copied.
  4224. * Since the Last-Modified timestamp is used for caching
  4225. * it should be based on the most recent timestamp. */
  4226. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4227. info.ftCreationTime.dwHighDateTime);
  4228. if (creation_time > filep->last_modified) {
  4229. filep->last_modified = creation_time;
  4230. }
  4231. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4232. /* If file name is fishy, reset the file structure and return
  4233. * error.
  4234. * Note it is important to reset, not just return the error, cause
  4235. * functions like is_file_opened() check the struct. */
  4236. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  4237. memset(filep, 0, sizeof(*filep));
  4238. return 0;
  4239. }
  4240. return 1;
  4241. }
  4242. return 0;
  4243. }
  4244. static int
  4245. mg_remove(const struct mg_connection *conn, const char *path)
  4246. {
  4247. wchar_t wbuf[W_PATH_MAX];
  4248. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4249. return DeleteFileW(wbuf) ? 0 : -1;
  4250. }
  4251. static int
  4252. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4253. {
  4254. wchar_t wbuf[W_PATH_MAX];
  4255. (void)mode;
  4256. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4257. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4258. }
  4259. /* Create substitutes for POSIX functions in Win32. */
  4260. #if defined(__MINGW32__)
  4261. /* Show no warning in case system functions are not used. */
  4262. #pragma GCC diagnostic push
  4263. #pragma GCC diagnostic ignored "-Wunused-function"
  4264. #endif
  4265. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4266. FUNCTION_MAY_BE_UNUSED
  4267. static DIR *
  4268. mg_opendir(const struct mg_connection *conn, const char *name)
  4269. {
  4270. DIR *dir = NULL;
  4271. wchar_t wpath[W_PATH_MAX];
  4272. DWORD attrs;
  4273. if (name == NULL) {
  4274. SetLastError(ERROR_BAD_ARGUMENTS);
  4275. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4276. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4277. } else {
  4278. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4279. attrs = GetFileAttributesW(wpath);
  4280. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4281. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4282. (void)wcscat(wpath, L"\\*");
  4283. dir->handle = FindFirstFileW(wpath, &dir->info);
  4284. dir->result.d_name[0] = '\0';
  4285. } else {
  4286. mg_free(dir);
  4287. dir = NULL;
  4288. }
  4289. }
  4290. return dir;
  4291. }
  4292. FUNCTION_MAY_BE_UNUSED
  4293. static int
  4294. mg_closedir(DIR *dir)
  4295. {
  4296. int result = 0;
  4297. if (dir != NULL) {
  4298. if (dir->handle != INVALID_HANDLE_VALUE)
  4299. result = FindClose(dir->handle) ? 0 : -1;
  4300. mg_free(dir);
  4301. } else {
  4302. result = -1;
  4303. SetLastError(ERROR_BAD_ARGUMENTS);
  4304. }
  4305. return result;
  4306. }
  4307. FUNCTION_MAY_BE_UNUSED
  4308. static struct dirent *
  4309. mg_readdir(DIR *dir)
  4310. {
  4311. struct dirent *result = 0;
  4312. if (dir) {
  4313. if (dir->handle != INVALID_HANDLE_VALUE) {
  4314. result = &dir->result;
  4315. (void)WideCharToMultiByte(CP_UTF8,
  4316. 0,
  4317. dir->info.cFileName,
  4318. -1,
  4319. result->d_name,
  4320. sizeof(result->d_name),
  4321. NULL,
  4322. NULL);
  4323. if (!FindNextFileW(dir->handle, &dir->info)) {
  4324. (void)FindClose(dir->handle);
  4325. dir->handle = INVALID_HANDLE_VALUE;
  4326. }
  4327. } else {
  4328. SetLastError(ERROR_FILE_NOT_FOUND);
  4329. }
  4330. } else {
  4331. SetLastError(ERROR_BAD_ARGUMENTS);
  4332. }
  4333. return result;
  4334. }
  4335. #if !defined(HAVE_POLL)
  4336. FUNCTION_MAY_BE_UNUSED
  4337. static int
  4338. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4339. {
  4340. struct timeval tv;
  4341. fd_set set;
  4342. unsigned int i;
  4343. int result;
  4344. SOCKET maxfd = 0;
  4345. memset(&tv, 0, sizeof(tv));
  4346. tv.tv_sec = milliseconds / 1000;
  4347. tv.tv_usec = (milliseconds % 1000) * 1000;
  4348. FD_ZERO(&set);
  4349. for (i = 0; i < n; i++) {
  4350. FD_SET((SOCKET)pfd[i].fd, &set);
  4351. pfd[i].revents = 0;
  4352. if (pfd[i].fd > maxfd) {
  4353. maxfd = pfd[i].fd;
  4354. }
  4355. }
  4356. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  4357. for (i = 0; i < n; i++) {
  4358. if (FD_ISSET(pfd[i].fd, &set)) {
  4359. pfd[i].revents = POLLIN;
  4360. }
  4361. }
  4362. }
  4363. /* We should subtract the time used in select from remaining
  4364. * "milliseconds", in particular if called from mg_poll with a
  4365. * timeout quantum.
  4366. * Unfortunately, the remaining time is not stored in "tv" in all
  4367. * implementations, so the result in "tv" must be considered undefined.
  4368. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4369. return result;
  4370. }
  4371. #endif /* HAVE_POLL */
  4372. #if defined(__MINGW32__)
  4373. /* Enable unused function warning again */
  4374. #pragma GCC diagnostic pop
  4375. #endif
  4376. static void
  4377. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4378. {
  4379. (void)conn; /* Unused. */
  4380. #if defined(_WIN32_WCE)
  4381. (void)sock;
  4382. #else
  4383. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4384. #endif
  4385. }
  4386. int
  4387. mg_start_thread(mg_thread_func_t f, void *p)
  4388. {
  4389. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4390. /* Compile-time option to control stack size, e.g.
  4391. * -DUSE_STACK_SIZE=16384
  4392. */
  4393. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4394. == ((uintptr_t)(-1L)))
  4395. ? -1
  4396. : 0);
  4397. #else
  4398. return (
  4399. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4400. ? -1
  4401. : 0);
  4402. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4403. }
  4404. /* Start a thread storing the thread context. */
  4405. static int
  4406. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4407. void *p,
  4408. pthread_t *threadidptr)
  4409. {
  4410. uintptr_t uip;
  4411. HANDLE threadhandle;
  4412. int result = -1;
  4413. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4414. threadhandle = (HANDLE)uip;
  4415. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4416. *threadidptr = threadhandle;
  4417. result = 0;
  4418. }
  4419. return result;
  4420. }
  4421. /* Wait for a thread to finish. */
  4422. static int
  4423. mg_join_thread(pthread_t threadid)
  4424. {
  4425. int result;
  4426. DWORD dwevent;
  4427. result = -1;
  4428. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4429. if (dwevent == WAIT_FAILED) {
  4430. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4431. } else {
  4432. if (dwevent == WAIT_OBJECT_0) {
  4433. CloseHandle(threadid);
  4434. result = 0;
  4435. }
  4436. }
  4437. return result;
  4438. }
  4439. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4440. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4441. /* Create substitutes for POSIX functions in Win32. */
  4442. #if defined(__MINGW32__)
  4443. /* Show no warning in case system functions are not used. */
  4444. #pragma GCC diagnostic push
  4445. #pragma GCC diagnostic ignored "-Wunused-function"
  4446. #endif
  4447. FUNCTION_MAY_BE_UNUSED
  4448. static HANDLE
  4449. dlopen(const char *dll_name, int flags)
  4450. {
  4451. wchar_t wbuf[W_PATH_MAX];
  4452. (void)flags;
  4453. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4454. return LoadLibraryW(wbuf);
  4455. }
  4456. FUNCTION_MAY_BE_UNUSED
  4457. static int
  4458. dlclose(void *handle)
  4459. {
  4460. int result;
  4461. if (FreeLibrary((HMODULE)handle) != 0) {
  4462. result = 0;
  4463. } else {
  4464. result = -1;
  4465. }
  4466. return result;
  4467. }
  4468. #if defined(__MINGW32__)
  4469. /* Enable unused function warning again */
  4470. #pragma GCC diagnostic pop
  4471. #endif
  4472. #endif
  4473. #if !defined(NO_CGI)
  4474. #define SIGKILL (0)
  4475. static int
  4476. kill(pid_t pid, int sig_num)
  4477. {
  4478. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4479. (void)CloseHandle((HANDLE)pid);
  4480. return 0;
  4481. }
  4482. static void
  4483. trim_trailing_whitespaces(char *s)
  4484. {
  4485. char *e = s + strlen(s) - 1;
  4486. while ((e > s) && isspace(*(unsigned char *)e)) {
  4487. *e-- = '\0';
  4488. }
  4489. }
  4490. static pid_t
  4491. spawn_process(struct mg_connection *conn,
  4492. const char *prog,
  4493. char *envblk,
  4494. char *envp[],
  4495. int fdin[2],
  4496. int fdout[2],
  4497. int fderr[2],
  4498. const char *dir)
  4499. {
  4500. HANDLE me;
  4501. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4502. cmdline[PATH_MAX], buf[PATH_MAX];
  4503. int truncated;
  4504. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4505. STARTUPINFOA si;
  4506. PROCESS_INFORMATION pi = {0};
  4507. (void)envp;
  4508. memset(&si, 0, sizeof(si));
  4509. si.cb = sizeof(si);
  4510. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4511. si.wShowWindow = SW_HIDE;
  4512. me = GetCurrentProcess();
  4513. DuplicateHandle(me,
  4514. (HANDLE)_get_osfhandle(fdin[0]),
  4515. me,
  4516. &si.hStdInput,
  4517. 0,
  4518. TRUE,
  4519. DUPLICATE_SAME_ACCESS);
  4520. DuplicateHandle(me,
  4521. (HANDLE)_get_osfhandle(fdout[1]),
  4522. me,
  4523. &si.hStdOutput,
  4524. 0,
  4525. TRUE,
  4526. DUPLICATE_SAME_ACCESS);
  4527. DuplicateHandle(me,
  4528. (HANDLE)_get_osfhandle(fderr[1]),
  4529. me,
  4530. &si.hStdError,
  4531. 0,
  4532. TRUE,
  4533. DUPLICATE_SAME_ACCESS);
  4534. /* Mark handles that should not be inherited. See
  4535. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4536. */
  4537. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4538. HANDLE_FLAG_INHERIT,
  4539. 0);
  4540. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4541. HANDLE_FLAG_INHERIT,
  4542. 0);
  4543. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4544. HANDLE_FLAG_INHERIT,
  4545. 0);
  4546. /* If CGI file is a script, try to read the interpreter line */
  4547. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4548. if (interp == NULL) {
  4549. buf[0] = buf[1] = '\0';
  4550. /* Read the first line of the script into the buffer */
  4551. mg_snprintf(
  4552. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4553. if (truncated) {
  4554. pi.hProcess = (pid_t)-1;
  4555. goto spawn_cleanup;
  4556. }
  4557. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4558. #if defined(MG_USE_OPEN_FILE)
  4559. p = (char *)file.access.membuf;
  4560. #else
  4561. p = (char *)NULL;
  4562. #endif
  4563. mg_fgets(buf, sizeof(buf), &file, &p);
  4564. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4565. buf[sizeof(buf) - 1] = '\0';
  4566. }
  4567. if ((buf[0] == '#') && (buf[1] == '!')) {
  4568. trim_trailing_whitespaces(buf + 2);
  4569. } else {
  4570. buf[2] = '\0';
  4571. }
  4572. interp = buf + 2;
  4573. }
  4574. if (interp[0] != '\0') {
  4575. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4576. interp = full_interp;
  4577. }
  4578. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4579. if (interp[0] != '\0') {
  4580. mg_snprintf(conn,
  4581. &truncated,
  4582. cmdline,
  4583. sizeof(cmdline),
  4584. "\"%s\" \"%s\\%s\"",
  4585. interp,
  4586. full_dir,
  4587. prog);
  4588. } else {
  4589. mg_snprintf(conn,
  4590. &truncated,
  4591. cmdline,
  4592. sizeof(cmdline),
  4593. "\"%s\\%s\"",
  4594. full_dir,
  4595. prog);
  4596. }
  4597. if (truncated) {
  4598. pi.hProcess = (pid_t)-1;
  4599. goto spawn_cleanup;
  4600. }
  4601. DEBUG_TRACE("Running [%s]", cmdline);
  4602. if (CreateProcessA(NULL,
  4603. cmdline,
  4604. NULL,
  4605. NULL,
  4606. TRUE,
  4607. CREATE_NEW_PROCESS_GROUP,
  4608. envblk,
  4609. NULL,
  4610. &si,
  4611. &pi) == 0) {
  4612. mg_cry_internal(
  4613. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4614. pi.hProcess = (pid_t)-1;
  4615. /* goto spawn_cleanup; */
  4616. }
  4617. spawn_cleanup:
  4618. (void)CloseHandle(si.hStdOutput);
  4619. (void)CloseHandle(si.hStdError);
  4620. (void)CloseHandle(si.hStdInput);
  4621. if (pi.hThread != NULL) {
  4622. (void)CloseHandle(pi.hThread);
  4623. }
  4624. return (pid_t)pi.hProcess;
  4625. }
  4626. #endif /* !NO_CGI */
  4627. static int
  4628. set_blocking_mode(SOCKET sock)
  4629. {
  4630. unsigned long non_blocking = 0;
  4631. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4632. }
  4633. static int
  4634. set_non_blocking_mode(SOCKET sock)
  4635. {
  4636. unsigned long non_blocking = 1;
  4637. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4638. }
  4639. #else
  4640. static int
  4641. mg_stat(const struct mg_connection *conn,
  4642. const char *path,
  4643. struct mg_file_stat *filep)
  4644. {
  4645. struct stat st;
  4646. if (!filep) {
  4647. return 0;
  4648. }
  4649. memset(filep, 0, sizeof(*filep));
  4650. if (conn && is_file_in_memory(conn, path)) {
  4651. /* Quick fix (for 1.9.x): */
  4652. /* mg_stat must fill all fields, also for files in memory */
  4653. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4654. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4655. filep->size = tmp_file.stat.size;
  4656. filep->last_modified = time(NULL);
  4657. filep->location = 2;
  4658. /* TODO: remove legacy "files in memory" feature */
  4659. return 1;
  4660. }
  4661. if (0 == stat(path, &st)) {
  4662. filep->size = (uint64_t)(st.st_size);
  4663. filep->last_modified = st.st_mtime;
  4664. filep->is_directory = S_ISDIR(st.st_mode);
  4665. return 1;
  4666. }
  4667. return 0;
  4668. }
  4669. static void
  4670. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4671. {
  4672. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4673. if (conn) {
  4674. mg_cry_internal(conn,
  4675. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4676. __func__,
  4677. strerror(ERRNO));
  4678. }
  4679. }
  4680. }
  4681. int
  4682. mg_start_thread(mg_thread_func_t func, void *param)
  4683. {
  4684. pthread_t thread_id;
  4685. pthread_attr_t attr;
  4686. int result;
  4687. (void)pthread_attr_init(&attr);
  4688. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4689. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4690. /* Compile-time option to control stack size,
  4691. * e.g. -DUSE_STACK_SIZE=16384 */
  4692. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4693. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4694. result = pthread_create(&thread_id, &attr, func, param);
  4695. pthread_attr_destroy(&attr);
  4696. return result;
  4697. }
  4698. /* Start a thread storing the thread context. */
  4699. static int
  4700. mg_start_thread_with_id(mg_thread_func_t func,
  4701. void *param,
  4702. pthread_t *threadidptr)
  4703. {
  4704. pthread_t thread_id;
  4705. pthread_attr_t attr;
  4706. int result;
  4707. (void)pthread_attr_init(&attr);
  4708. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4709. /* Compile-time option to control stack size,
  4710. * e.g. -DUSE_STACK_SIZE=16384 */
  4711. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4712. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4713. result = pthread_create(&thread_id, &attr, func, param);
  4714. pthread_attr_destroy(&attr);
  4715. if ((result == 0) && (threadidptr != NULL)) {
  4716. *threadidptr = thread_id;
  4717. }
  4718. return result;
  4719. }
  4720. /* Wait for a thread to finish. */
  4721. static int
  4722. mg_join_thread(pthread_t threadid)
  4723. {
  4724. int result;
  4725. result = pthread_join(threadid, NULL);
  4726. return result;
  4727. }
  4728. #if !defined(NO_CGI)
  4729. static pid_t
  4730. spawn_process(struct mg_connection *conn,
  4731. const char *prog,
  4732. char *envblk,
  4733. char *envp[],
  4734. int fdin[2],
  4735. int fdout[2],
  4736. int fderr[2],
  4737. const char *dir)
  4738. {
  4739. pid_t pid;
  4740. const char *interp;
  4741. (void)envblk;
  4742. if (conn == NULL) {
  4743. return 0;
  4744. }
  4745. if ((pid = fork()) == -1) {
  4746. /* Parent */
  4747. mg_send_http_error(conn,
  4748. 500,
  4749. "Error: Creating CGI process\nfork(): %s",
  4750. strerror(ERRNO));
  4751. } else if (pid == 0) {
  4752. /* Child */
  4753. if (chdir(dir) != 0) {
  4754. mg_cry_internal(
  4755. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4756. } else if (dup2(fdin[0], 0) == -1) {
  4757. mg_cry_internal(conn,
  4758. "%s: dup2(%d, 0): %s",
  4759. __func__,
  4760. fdin[0],
  4761. strerror(ERRNO));
  4762. } else if (dup2(fdout[1], 1) == -1) {
  4763. mg_cry_internal(conn,
  4764. "%s: dup2(%d, 1): %s",
  4765. __func__,
  4766. fdout[1],
  4767. strerror(ERRNO));
  4768. } else if (dup2(fderr[1], 2) == -1) {
  4769. mg_cry_internal(conn,
  4770. "%s: dup2(%d, 2): %s",
  4771. __func__,
  4772. fderr[1],
  4773. strerror(ERRNO));
  4774. } else {
  4775. /* Keep stderr and stdout in two different pipes.
  4776. * Stdout will be sent back to the client,
  4777. * stderr should go into a server error log. */
  4778. (void)close(fdin[0]);
  4779. (void)close(fdout[1]);
  4780. (void)close(fderr[1]);
  4781. /* Close write end fdin and read end fdout and fderr */
  4782. (void)close(fdin[1]);
  4783. (void)close(fdout[0]);
  4784. (void)close(fderr[0]);
  4785. /* After exec, all signal handlers are restored to their default
  4786. * values, with one exception of SIGCHLD. According to
  4787. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4788. * will leave unchanged after exec if it was set to be ignored.
  4789. * Restore it to default action. */
  4790. signal(SIGCHLD, SIG_DFL);
  4791. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4792. if (interp == NULL) {
  4793. (void)execle(prog, prog, NULL, envp);
  4794. mg_cry_internal(conn,
  4795. "%s: execle(%s): %s",
  4796. __func__,
  4797. prog,
  4798. strerror(ERRNO));
  4799. } else {
  4800. (void)execle(interp, interp, prog, NULL, envp);
  4801. mg_cry_internal(conn,
  4802. "%s: execle(%s %s): %s",
  4803. __func__,
  4804. interp,
  4805. prog,
  4806. strerror(ERRNO));
  4807. }
  4808. }
  4809. exit(EXIT_FAILURE);
  4810. }
  4811. return pid;
  4812. }
  4813. #endif /* !NO_CGI */
  4814. static int
  4815. set_non_blocking_mode(SOCKET sock)
  4816. {
  4817. int flags = fcntl(sock, F_GETFL, 0);
  4818. if (flags < 0) {
  4819. return -1;
  4820. }
  4821. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4822. return -1;
  4823. }
  4824. return 0;
  4825. }
  4826. static int
  4827. set_blocking_mode(SOCKET sock)
  4828. {
  4829. int flags = fcntl(sock, F_GETFL, 0);
  4830. if (flags < 0) {
  4831. return -1;
  4832. }
  4833. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4834. return -1;
  4835. }
  4836. return 0;
  4837. }
  4838. #endif /* _WIN32 / else */
  4839. /* End of initial operating system specific define block. */
  4840. /* Get a random number (independent of C rand function) */
  4841. static uint64_t
  4842. get_random(void)
  4843. {
  4844. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4845. static uint64_t lcg = 0; /* Linear congruential generator */
  4846. uint64_t now = mg_get_current_time_ns();
  4847. if (lfsr == 0) {
  4848. /* lfsr will be only 0 if has not been initialized,
  4849. * so this code is called only once. */
  4850. lfsr = mg_get_current_time_ns();
  4851. lcg = mg_get_current_time_ns();
  4852. } else {
  4853. /* Get the next step of both random number generators. */
  4854. lfsr = (lfsr >> 1)
  4855. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4856. << 63);
  4857. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4858. }
  4859. /* Combining two pseudo-random number generators and a high resolution
  4860. * part
  4861. * of the current server time will make it hard (impossible?) to guess
  4862. * the
  4863. * next number. */
  4864. return (lfsr ^ lcg ^ now);
  4865. }
  4866. static int
  4867. mg_poll(struct pollfd *pfd,
  4868. unsigned int n,
  4869. int milliseconds,
  4870. volatile int *stop_server)
  4871. {
  4872. /* Call poll, but only for a maximum time of a few seconds.
  4873. * This will allow to stop the server after some seconds, instead
  4874. * of having to wait for a long socket timeout. */
  4875. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4876. do {
  4877. int result;
  4878. if (*stop_server) {
  4879. /* Shut down signal */
  4880. return -2;
  4881. }
  4882. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4883. ms_now = milliseconds;
  4884. }
  4885. result = poll(pfd, n, ms_now);
  4886. if (result != 0) {
  4887. /* Poll returned either success (1) or error (-1).
  4888. * Forward both to the caller. */
  4889. return result;
  4890. }
  4891. /* Poll returned timeout (0). */
  4892. if (milliseconds > 0) {
  4893. milliseconds -= ms_now;
  4894. }
  4895. } while (milliseconds != 0);
  4896. /* timeout: return 0 */
  4897. return 0;
  4898. }
  4899. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4900. * descriptor.
  4901. * Return value:
  4902. * >=0 .. number of bytes successfully written
  4903. * -1 .. timeout
  4904. * -2 .. error
  4905. */
  4906. static int
  4907. push_inner(struct mg_context *ctx,
  4908. FILE *fp,
  4909. SOCKET sock,
  4910. SSL *ssl,
  4911. const char *buf,
  4912. int len,
  4913. double timeout)
  4914. {
  4915. uint64_t start = 0, now = 0, timeout_ns = 0;
  4916. int n, err;
  4917. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4918. #if defined(_WIN32)
  4919. typedef int len_t;
  4920. #else
  4921. typedef size_t len_t;
  4922. #endif
  4923. if (timeout > 0) {
  4924. now = mg_get_current_time_ns();
  4925. start = now;
  4926. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4927. }
  4928. if (ctx == NULL) {
  4929. return -2;
  4930. }
  4931. #if defined(NO_SSL)
  4932. if (ssl) {
  4933. return -2;
  4934. }
  4935. #endif
  4936. /* Try to read until it succeeds, fails, times out, or the server
  4937. * shuts down. */
  4938. for (;;) {
  4939. #if !defined(NO_SSL)
  4940. if (ssl != NULL) {
  4941. n = SSL_write(ssl, buf, len);
  4942. if (n <= 0) {
  4943. err = SSL_get_error(ssl, n);
  4944. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4945. err = ERRNO;
  4946. } else if ((err == SSL_ERROR_WANT_READ)
  4947. || (err == SSL_ERROR_WANT_WRITE)) {
  4948. n = 0;
  4949. } else {
  4950. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4951. return -2;
  4952. }
  4953. } else {
  4954. err = 0;
  4955. }
  4956. } else
  4957. #endif
  4958. if (fp != NULL) {
  4959. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4960. if (ferror(fp)) {
  4961. n = -1;
  4962. err = ERRNO;
  4963. } else {
  4964. err = 0;
  4965. }
  4966. } else {
  4967. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4968. err = (n < 0) ? ERRNO : 0;
  4969. #if defined(_WIN32)
  4970. if (err == WSAEWOULDBLOCK) {
  4971. err = 0;
  4972. n = 0;
  4973. }
  4974. #else
  4975. if (err == EWOULDBLOCK) {
  4976. err = 0;
  4977. n = 0;
  4978. }
  4979. #endif
  4980. if (n < 0) {
  4981. /* shutdown of the socket at client side */
  4982. return -2;
  4983. }
  4984. }
  4985. if (ctx->stop_flag) {
  4986. return -2;
  4987. }
  4988. if ((n > 0) || ((n == 0) && (len == 0))) {
  4989. /* some data has been read, or no data was requested */
  4990. return n;
  4991. }
  4992. if (n < 0) {
  4993. /* socket error - check errno */
  4994. DEBUG_TRACE("send() failed, error %d", err);
  4995. /* TODO (mid): error handling depending on the error code.
  4996. * These codes are different between Windows and Linux.
  4997. * Currently there is no problem with failing send calls,
  4998. * if there is a reproducible situation, it should be
  4999. * investigated in detail.
  5000. */
  5001. return -2;
  5002. }
  5003. /* Only in case n=0 (timeout), repeat calling the write function */
  5004. /* If send failed, wait before retry */
  5005. if (fp != NULL) {
  5006. /* For files, just wait a fixed time.
  5007. * Maybe it helps, maybe not. */
  5008. mg_sleep(5);
  5009. } else {
  5010. /* For sockets, wait for the socket using select */
  5011. fd_set wfds;
  5012. struct timeval tv;
  5013. int sret;
  5014. #if defined(__GNUC__) || defined(__MINGW32__)
  5015. /* GCC seems to have a flaw with it's own socket macros:
  5016. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  5017. */
  5018. #pragma GCC diagnostic push
  5019. #pragma GCC diagnostic ignored "-Wsign-conversion"
  5020. #endif
  5021. FD_ZERO(&wfds);
  5022. FD_SET(sock, &wfds);
  5023. tv.tv_sec = (time_t)(ms_wait / 1000);
  5024. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  5025. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  5026. #if defined(__GNUC__) || defined(__MINGW32__)
  5027. #pragma GCC diagnostic pop
  5028. #endif
  5029. if (sret > 0) {
  5030. /* We got ready to write. Don't check the timeout
  5031. * but directly go back to write again. */
  5032. continue;
  5033. }
  5034. }
  5035. if (timeout > 0) {
  5036. now = mg_get_current_time_ns();
  5037. if ((now - start) > timeout_ns) {
  5038. /* Timeout */
  5039. break;
  5040. }
  5041. }
  5042. }
  5043. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5044. used */
  5045. return -1;
  5046. }
  5047. static int64_t
  5048. push_all(struct mg_context *ctx,
  5049. FILE *fp,
  5050. SOCKET sock,
  5051. SSL *ssl,
  5052. const char *buf,
  5053. int64_t len)
  5054. {
  5055. double timeout = -1.0;
  5056. int64_t n, nwritten = 0;
  5057. if (ctx == NULL) {
  5058. return -1;
  5059. }
  5060. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5061. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5062. }
  5063. while ((len > 0) && (ctx->stop_flag == 0)) {
  5064. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  5065. if (n < 0) {
  5066. if (nwritten == 0) {
  5067. nwritten = n; /* Propagate the error */
  5068. }
  5069. break;
  5070. } else if (n == 0) {
  5071. break; /* No more data to write */
  5072. } else {
  5073. nwritten += n;
  5074. len -= n;
  5075. }
  5076. }
  5077. return nwritten;
  5078. }
  5079. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5080. * Return value:
  5081. * >=0 .. number of bytes successfully read
  5082. * -1 .. timeout
  5083. * -2 .. error
  5084. */
  5085. static int
  5086. pull_inner(FILE *fp,
  5087. struct mg_connection *conn,
  5088. char *buf,
  5089. int len,
  5090. double timeout)
  5091. {
  5092. int nread, err = 0;
  5093. #if defined(_WIN32)
  5094. typedef int len_t;
  5095. #else
  5096. typedef size_t len_t;
  5097. #endif
  5098. #if !defined(NO_SSL)
  5099. int ssl_pending;
  5100. #endif
  5101. /* We need an additional wait loop around this, because in some cases
  5102. * with TLSwe may get data from the socket but not from SSL_read.
  5103. * In this case we need to repeat at least once.
  5104. */
  5105. if (fp != NULL) {
  5106. #if !defined(_WIN32_WCE)
  5107. /* Use read() instead of fread(), because if we're reading from the
  5108. * CGI pipe, fread() may block until IO buffer is filled up. We
  5109. * cannot afford to block and must pass all read bytes immediately
  5110. * to the client. */
  5111. nread = (int)read(fileno(fp), buf, (size_t)len);
  5112. #else
  5113. /* WinCE does not support CGI pipes */
  5114. nread = (int)fread(buf, 1, (size_t)len, fp);
  5115. #endif
  5116. err = (nread < 0) ? ERRNO : 0;
  5117. if ((nread == 0) && (len > 0)) {
  5118. /* Should get data, but got EOL */
  5119. return -2;
  5120. }
  5121. #if !defined(NO_SSL)
  5122. } else if ((conn->ssl != NULL)
  5123. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5124. /* We already know there is no more data buffered in conn->buf
  5125. * but there is more available in the SSL layer. So don't poll
  5126. * conn->client.sock yet. */
  5127. if (ssl_pending > len) {
  5128. ssl_pending = len;
  5129. }
  5130. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5131. if (nread <= 0) {
  5132. err = SSL_get_error(conn->ssl, nread);
  5133. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5134. err = ERRNO;
  5135. } else if ((err == SSL_ERROR_WANT_READ)
  5136. || (err == SSL_ERROR_WANT_WRITE)) {
  5137. nread = 0;
  5138. } else {
  5139. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5140. return -1;
  5141. }
  5142. } else {
  5143. err = 0;
  5144. }
  5145. } else if (conn->ssl != NULL) {
  5146. struct pollfd pfd[1];
  5147. int pollres;
  5148. pfd[0].fd = conn->client.sock;
  5149. pfd[0].events = POLLIN;
  5150. pollres = mg_poll(pfd,
  5151. 1,
  5152. (int)(timeout * 1000.0),
  5153. &(conn->phys_ctx->stop_flag));
  5154. if (conn->phys_ctx->stop_flag) {
  5155. return -2;
  5156. }
  5157. if (pollres > 0) {
  5158. nread = SSL_read(conn->ssl, buf, len);
  5159. if (nread <= 0) {
  5160. err = SSL_get_error(conn->ssl, nread);
  5161. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5162. err = ERRNO;
  5163. } else if ((err == SSL_ERROR_WANT_READ)
  5164. || (err == SSL_ERROR_WANT_WRITE)) {
  5165. nread = 0;
  5166. } else {
  5167. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5168. return -2;
  5169. }
  5170. } else {
  5171. err = 0;
  5172. }
  5173. } else if (pollres < 0) {
  5174. /* Error */
  5175. return -2;
  5176. } else {
  5177. /* pollres = 0 means timeout */
  5178. nread = 0;
  5179. }
  5180. #endif
  5181. } else {
  5182. struct pollfd pfd[1];
  5183. int pollres;
  5184. pfd[0].fd = conn->client.sock;
  5185. pfd[0].events = POLLIN;
  5186. pollres = mg_poll(pfd,
  5187. 1,
  5188. (int)(timeout * 1000.0),
  5189. &(conn->phys_ctx->stop_flag));
  5190. if (conn->phys_ctx->stop_flag) {
  5191. return -2;
  5192. }
  5193. if (pollres > 0) {
  5194. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5195. err = (nread < 0) ? ERRNO : 0;
  5196. if (nread <= 0) {
  5197. /* shutdown of the socket at client side */
  5198. return -2;
  5199. }
  5200. } else if (pollres < 0) {
  5201. /* error callint poll */
  5202. return -2;
  5203. } else {
  5204. /* pollres = 0 means timeout */
  5205. nread = 0;
  5206. }
  5207. }
  5208. if (conn->phys_ctx->stop_flag) {
  5209. return -2;
  5210. }
  5211. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5212. /* some data has been read, or no data was requested */
  5213. return nread;
  5214. }
  5215. if (nread < 0) {
  5216. /* socket error - check errno */
  5217. #if defined(_WIN32)
  5218. if (err == WSAEWOULDBLOCK) {
  5219. /* TODO (low): check if this is still required */
  5220. /* standard case if called from close_socket_gracefully */
  5221. return -2;
  5222. } else if (err == WSAETIMEDOUT) {
  5223. /* TODO (low): check if this is still required */
  5224. /* timeout is handled by the while loop */
  5225. return 0;
  5226. } else if (err == WSAECONNABORTED) {
  5227. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5228. return -2;
  5229. } else {
  5230. DEBUG_TRACE("recv() failed, error %d", err);
  5231. return -2;
  5232. }
  5233. #else
  5234. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5235. * if the timeout is reached and if the socket was set to non-
  5236. * blocking in close_socket_gracefully, so we can not distinguish
  5237. * here. We have to wait for the timeout in both cases for now.
  5238. */
  5239. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5240. /* TODO (low): check if this is still required */
  5241. /* EAGAIN/EWOULDBLOCK:
  5242. * standard case if called from close_socket_gracefully
  5243. * => should return -1 */
  5244. /* or timeout occurred
  5245. * => the code must stay in the while loop */
  5246. /* EINTR can be generated on a socket with a timeout set even
  5247. * when SA_RESTART is effective for all relevant signals
  5248. * (see signal(7)).
  5249. * => stay in the while loop */
  5250. } else {
  5251. DEBUG_TRACE("recv() failed, error %d", err);
  5252. return -2;
  5253. }
  5254. #endif
  5255. }
  5256. /* Timeout occurred, but no data available. */
  5257. return -1;
  5258. }
  5259. static int
  5260. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5261. {
  5262. int n, nread = 0;
  5263. double timeout = -1.0;
  5264. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5265. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5266. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5267. }
  5268. if (timeout >= 0.0) {
  5269. start_time = mg_get_current_time_ns();
  5270. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5271. }
  5272. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5273. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5274. if (n == -2) {
  5275. if (nread == 0) {
  5276. nread = -1; /* Propagate the error */
  5277. }
  5278. break;
  5279. } else if (n == -1) {
  5280. /* timeout */
  5281. if (timeout >= 0.0) {
  5282. now = mg_get_current_time_ns();
  5283. if ((now - start_time) <= timeout_ns) {
  5284. continue;
  5285. }
  5286. }
  5287. break;
  5288. } else if (n == 0) {
  5289. break; /* No more data to read */
  5290. } else {
  5291. conn->consumed_content += n;
  5292. nread += n;
  5293. len -= n;
  5294. }
  5295. }
  5296. return nread;
  5297. }
  5298. static void
  5299. discard_unread_request_data(struct mg_connection *conn)
  5300. {
  5301. char buf[MG_BUF_LEN];
  5302. size_t to_read;
  5303. int nread;
  5304. if (conn == NULL) {
  5305. return;
  5306. }
  5307. to_read = sizeof(buf);
  5308. if (conn->is_chunked) {
  5309. /* Chunked encoding: 3=chunk read completely
  5310. * completely */
  5311. while (conn->is_chunked != 3) {
  5312. nread = mg_read(conn, buf, to_read);
  5313. if (nread <= 0) {
  5314. break;
  5315. }
  5316. }
  5317. } else {
  5318. /* Not chunked: content length is known */
  5319. while (conn->consumed_content < conn->content_len) {
  5320. if (to_read
  5321. > (size_t)(conn->content_len - conn->consumed_content)) {
  5322. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5323. }
  5324. nread = mg_read(conn, buf, to_read);
  5325. if (nread <= 0) {
  5326. break;
  5327. }
  5328. }
  5329. }
  5330. }
  5331. static int
  5332. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5333. {
  5334. int64_t n, buffered_len, nread;
  5335. int64_t len64 =
  5336. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5337. * int, we may not read more
  5338. * bytes */
  5339. const char *body;
  5340. if (conn == NULL) {
  5341. return 0;
  5342. }
  5343. /* If Content-Length is not set for a request with body data
  5344. * (e.g., a PUT or POST request), we do not know in advance
  5345. * how much data should be read. */
  5346. if (conn->consumed_content == 0) {
  5347. if (conn->is_chunked == 1) {
  5348. conn->content_len = len64;
  5349. conn->is_chunked = 2;
  5350. } else if (conn->content_len == -1) {
  5351. /* The body data is completed when the connection
  5352. * is closed. */
  5353. conn->content_len = INT64_MAX;
  5354. conn->must_close = 1;
  5355. }
  5356. }
  5357. nread = 0;
  5358. if (conn->consumed_content < conn->content_len) {
  5359. /* Adjust number of bytes to read. */
  5360. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5361. if (left_to_read < len64) {
  5362. /* Do not read more than the total content length of the
  5363. * request.
  5364. */
  5365. len64 = left_to_read;
  5366. }
  5367. /* Return buffered data */
  5368. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5369. - conn->consumed_content;
  5370. if (buffered_len > 0) {
  5371. if (len64 < buffered_len) {
  5372. buffered_len = len64;
  5373. }
  5374. body = conn->buf + conn->request_len + conn->consumed_content;
  5375. memcpy(buf, body, (size_t)buffered_len);
  5376. len64 -= buffered_len;
  5377. conn->consumed_content += buffered_len;
  5378. nread += buffered_len;
  5379. buf = (char *)buf + buffered_len;
  5380. }
  5381. /* We have returned all buffered data. Read new data from the remote
  5382. * socket.
  5383. */
  5384. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5385. nread += n;
  5386. } else {
  5387. nread = ((nread > 0) ? nread : n);
  5388. }
  5389. }
  5390. return (int)nread;
  5391. }
  5392. static char
  5393. mg_getc(struct mg_connection *conn)
  5394. {
  5395. char c;
  5396. if (conn == NULL) {
  5397. return 0;
  5398. }
  5399. if (mg_read_inner(conn, &c, 1) <= 0) {
  5400. return (char)0;
  5401. }
  5402. return c;
  5403. }
  5404. int
  5405. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5406. {
  5407. if (len > INT_MAX) {
  5408. len = INT_MAX;
  5409. }
  5410. if (conn == NULL) {
  5411. return 0;
  5412. }
  5413. if (conn->is_chunked) {
  5414. size_t all_read = 0;
  5415. while (len > 0) {
  5416. if (conn->is_chunked == 3) {
  5417. /* No more data left to read */
  5418. return 0;
  5419. }
  5420. if (conn->chunk_remainder) {
  5421. /* copy from the remainder of the last received chunk */
  5422. long read_ret;
  5423. size_t read_now =
  5424. ((conn->chunk_remainder > len) ? (len)
  5425. : (conn->chunk_remainder));
  5426. conn->content_len += (int)read_now;
  5427. read_ret =
  5428. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5429. if (read_ret < 1) {
  5430. /* read error */
  5431. return -1;
  5432. }
  5433. all_read += (size_t)read_ret;
  5434. conn->chunk_remainder -= (size_t)read_ret;
  5435. len -= (size_t)read_ret;
  5436. if (conn->chunk_remainder == 0) {
  5437. /* Add data bytes in the current chunk have been read,
  5438. * so we are expecting \r\n now. */
  5439. char x1, x2;
  5440. conn->content_len += 2;
  5441. x1 = mg_getc(conn);
  5442. x2 = mg_getc(conn);
  5443. if ((x1 != '\r') || (x2 != '\n')) {
  5444. /* Protocol violation */
  5445. return -1;
  5446. }
  5447. }
  5448. } else {
  5449. /* fetch a new chunk */
  5450. int i = 0;
  5451. char lenbuf[64];
  5452. char *end = 0;
  5453. unsigned long chunkSize = 0;
  5454. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5455. conn->content_len++;
  5456. lenbuf[i] = mg_getc(conn);
  5457. if ((i > 0) && (lenbuf[i] == '\r')
  5458. && (lenbuf[i - 1] != '\r')) {
  5459. continue;
  5460. }
  5461. if ((i > 1) && (lenbuf[i] == '\n')
  5462. && (lenbuf[i - 1] == '\r')) {
  5463. lenbuf[i + 1] = 0;
  5464. chunkSize = strtoul(lenbuf, &end, 16);
  5465. if (chunkSize == 0) {
  5466. /* regular end of content */
  5467. conn->is_chunked = 3;
  5468. }
  5469. break;
  5470. }
  5471. if (!isxdigit(lenbuf[i])) {
  5472. /* illegal character for chunk length */
  5473. return -1;
  5474. }
  5475. }
  5476. if ((end == NULL) || (*end != '\r')) {
  5477. /* chunksize not set correctly */
  5478. return -1;
  5479. }
  5480. if (chunkSize == 0) {
  5481. break;
  5482. }
  5483. conn->chunk_remainder = chunkSize;
  5484. }
  5485. }
  5486. return (int)all_read;
  5487. }
  5488. return mg_read_inner(conn, buf, len);
  5489. }
  5490. int
  5491. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5492. {
  5493. time_t now;
  5494. int64_t n, total, allowed;
  5495. if (conn == NULL) {
  5496. return 0;
  5497. }
  5498. if (conn->throttle > 0) {
  5499. if ((now = time(NULL)) != conn->last_throttle_time) {
  5500. conn->last_throttle_time = now;
  5501. conn->last_throttle_bytes = 0;
  5502. }
  5503. allowed = conn->throttle - conn->last_throttle_bytes;
  5504. if (allowed > (int64_t)len) {
  5505. allowed = (int64_t)len;
  5506. }
  5507. if ((total = push_all(conn->phys_ctx,
  5508. NULL,
  5509. conn->client.sock,
  5510. conn->ssl,
  5511. (const char *)buf,
  5512. (int64_t)allowed)) == allowed) {
  5513. buf = (const char *)buf + total;
  5514. conn->last_throttle_bytes += total;
  5515. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5516. allowed = (conn->throttle > ((int64_t)len - total))
  5517. ? (int64_t)len - total
  5518. : conn->throttle;
  5519. if ((n = push_all(conn->phys_ctx,
  5520. NULL,
  5521. conn->client.sock,
  5522. conn->ssl,
  5523. (const char *)buf,
  5524. (int64_t)allowed)) != allowed) {
  5525. break;
  5526. }
  5527. sleep(1);
  5528. conn->last_throttle_bytes = allowed;
  5529. conn->last_throttle_time = time(NULL);
  5530. buf = (const char *)buf + n;
  5531. total += n;
  5532. }
  5533. }
  5534. } else {
  5535. total = push_all(conn->phys_ctx,
  5536. NULL,
  5537. conn->client.sock,
  5538. conn->ssl,
  5539. (const char *)buf,
  5540. (int64_t)len);
  5541. }
  5542. if (total > 0) {
  5543. conn->num_bytes_sent += total;
  5544. }
  5545. return (int)total;
  5546. }
  5547. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5548. int
  5549. mg_send_chunk(struct mg_connection *conn,
  5550. const char *chunk,
  5551. unsigned int chunk_len)
  5552. {
  5553. char lenbuf[16];
  5554. size_t lenbuf_len;
  5555. int ret;
  5556. int t;
  5557. /* First store the length information in a text buffer. */
  5558. sprintf(lenbuf, "%x\r\n", chunk_len);
  5559. lenbuf_len = strlen(lenbuf);
  5560. /* Then send length information, chunk and terminating \r\n. */
  5561. ret = mg_write(conn, lenbuf, lenbuf_len);
  5562. if (ret != (int)lenbuf_len) {
  5563. return -1;
  5564. }
  5565. t = ret;
  5566. ret = mg_write(conn, chunk, chunk_len);
  5567. if (ret != (int)chunk_len) {
  5568. return -1;
  5569. }
  5570. t += ret;
  5571. ret = mg_write(conn, "\r\n", 2);
  5572. if (ret != 2) {
  5573. return -1;
  5574. }
  5575. t += ret;
  5576. return t;
  5577. }
  5578. #if defined(__GNUC__) || defined(__MINGW32__)
  5579. /* This block forwards format strings to printf implementations,
  5580. * so we need to disable the format-nonliteral warning. */
  5581. #pragma GCC diagnostic push
  5582. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5583. #endif
  5584. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5585. static int
  5586. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5587. {
  5588. va_list ap_copy;
  5589. size_t size = MG_BUF_LEN / 4;
  5590. int len = -1;
  5591. *buf = NULL;
  5592. while (len < 0) {
  5593. if (*buf) {
  5594. mg_free(*buf);
  5595. }
  5596. size *= 4;
  5597. *buf = (char *)mg_malloc(size);
  5598. if (!*buf) {
  5599. break;
  5600. }
  5601. va_copy(ap_copy, ap);
  5602. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5603. va_end(ap_copy);
  5604. (*buf)[size - 1] = 0;
  5605. }
  5606. return len;
  5607. }
  5608. /* Print message to buffer. If buffer is large enough to hold the message,
  5609. * return buffer. If buffer is to small, allocate large enough buffer on
  5610. * heap,
  5611. * and return allocated buffer. */
  5612. static int
  5613. alloc_vprintf(char **out_buf,
  5614. char *prealloc_buf,
  5615. size_t prealloc_size,
  5616. const char *fmt,
  5617. va_list ap)
  5618. {
  5619. va_list ap_copy;
  5620. int len;
  5621. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5622. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5623. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5624. * Therefore, we make two passes: on first pass, get required message
  5625. * length.
  5626. * On second pass, actually print the message. */
  5627. va_copy(ap_copy, ap);
  5628. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5629. va_end(ap_copy);
  5630. if (len < 0) {
  5631. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5632. * Switch to alternative code path that uses incremental
  5633. * allocations.
  5634. */
  5635. va_copy(ap_copy, ap);
  5636. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5637. va_end(ap_copy);
  5638. } else if ((size_t)(len) >= prealloc_size) {
  5639. /* The pre-allocated buffer not large enough. */
  5640. /* Allocate a new buffer. */
  5641. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5642. if (!*out_buf) {
  5643. /* Allocation failed. Return -1 as "out of memory" error. */
  5644. return -1;
  5645. }
  5646. /* Buffer allocation successful. Store the string there. */
  5647. va_copy(ap_copy, ap);
  5648. IGNORE_UNUSED_RESULT(
  5649. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5650. va_end(ap_copy);
  5651. } else {
  5652. /* The pre-allocated buffer is large enough.
  5653. * Use it to store the string and return the address. */
  5654. va_copy(ap_copy, ap);
  5655. IGNORE_UNUSED_RESULT(
  5656. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5657. va_end(ap_copy);
  5658. *out_buf = prealloc_buf;
  5659. }
  5660. return len;
  5661. }
  5662. #if defined(__GNUC__) || defined(__MINGW32__)
  5663. /* Enable format-nonliteral warning again. */
  5664. #pragma GCC diagnostic pop
  5665. #endif
  5666. static int
  5667. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5668. {
  5669. char mem[MG_BUF_LEN];
  5670. char *buf = NULL;
  5671. int len;
  5672. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5673. len = mg_write(conn, buf, (size_t)len);
  5674. }
  5675. if ((buf != mem) && (buf != NULL)) {
  5676. mg_free(buf);
  5677. }
  5678. return len;
  5679. }
  5680. int
  5681. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5682. {
  5683. va_list ap;
  5684. int result;
  5685. va_start(ap, fmt);
  5686. result = mg_vprintf(conn, fmt, ap);
  5687. va_end(ap);
  5688. return result;
  5689. }
  5690. int
  5691. mg_url_decode(const char *src,
  5692. int src_len,
  5693. char *dst,
  5694. int dst_len,
  5695. int is_form_url_encoded)
  5696. {
  5697. int i, j, a, b;
  5698. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5699. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5700. if ((i < src_len - 2) && (src[i] == '%')
  5701. && isxdigit(*(const unsigned char *)(src + i + 1))
  5702. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5703. a = tolower(*(const unsigned char *)(src + i + 1));
  5704. b = tolower(*(const unsigned char *)(src + i + 2));
  5705. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5706. i += 2;
  5707. } else if (is_form_url_encoded && (src[i] == '+')) {
  5708. dst[j] = ' ';
  5709. } else {
  5710. dst[j] = src[i];
  5711. }
  5712. }
  5713. dst[j] = '\0'; /* Null-terminate the destination */
  5714. return (i >= src_len) ? j : -1;
  5715. }
  5716. int
  5717. mg_get_var(const char *data,
  5718. size_t data_len,
  5719. const char *name,
  5720. char *dst,
  5721. size_t dst_len)
  5722. {
  5723. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5724. }
  5725. int
  5726. mg_get_var2(const char *data,
  5727. size_t data_len,
  5728. const char *name,
  5729. char *dst,
  5730. size_t dst_len,
  5731. size_t occurrence)
  5732. {
  5733. const char *p, *e, *s;
  5734. size_t name_len;
  5735. int len;
  5736. if ((dst == NULL) || (dst_len == 0)) {
  5737. len = -2;
  5738. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5739. len = -1;
  5740. dst[0] = '\0';
  5741. } else {
  5742. name_len = strlen(name);
  5743. e = data + data_len;
  5744. len = -1;
  5745. dst[0] = '\0';
  5746. /* data is "var1=val1&var2=val2...". Find variable first */
  5747. for (p = data; p + name_len < e; p++) {
  5748. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5749. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5750. /* Point p to variable value */
  5751. p += name_len + 1;
  5752. /* Point s to the end of the value */
  5753. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5754. if (s == NULL) {
  5755. s = e;
  5756. }
  5757. DEBUG_ASSERT(s >= p);
  5758. if (s < p) {
  5759. return -3;
  5760. }
  5761. /* Decode variable into destination buffer */
  5762. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5763. /* Redirect error code from -1 to -2 (destination buffer too
  5764. * small). */
  5765. if (len == -1) {
  5766. len = -2;
  5767. }
  5768. break;
  5769. }
  5770. }
  5771. }
  5772. return len;
  5773. }
  5774. /* HCP24: some changes to compare hole var_name */
  5775. int
  5776. mg_get_cookie(const char *cookie_header,
  5777. const char *var_name,
  5778. char *dst,
  5779. size_t dst_size)
  5780. {
  5781. const char *s, *p, *end;
  5782. int name_len, len = -1;
  5783. if ((dst == NULL) || (dst_size == 0)) {
  5784. return -2;
  5785. }
  5786. dst[0] = '\0';
  5787. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5788. return -1;
  5789. }
  5790. name_len = (int)strlen(var_name);
  5791. end = s + strlen(s);
  5792. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5793. if (s[name_len] == '=') {
  5794. /* HCP24: now check is it a substring or a full cookie name */
  5795. if ((s == cookie_header) || (s[-1] == ' ')) {
  5796. s += name_len + 1;
  5797. if ((p = strchr(s, ' ')) == NULL) {
  5798. p = end;
  5799. }
  5800. if (p[-1] == ';') {
  5801. p--;
  5802. }
  5803. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5804. s++;
  5805. p--;
  5806. }
  5807. if ((size_t)(p - s) < dst_size) {
  5808. len = (int)(p - s);
  5809. mg_strlcpy(dst, s, (size_t)len + 1);
  5810. } else {
  5811. len = -3;
  5812. }
  5813. break;
  5814. }
  5815. }
  5816. }
  5817. return len;
  5818. }
  5819. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5820. static void
  5821. base64_encode(const unsigned char *src, int src_len, char *dst)
  5822. {
  5823. static const char *b64 =
  5824. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5825. int i, j, a, b, c;
  5826. for (i = j = 0; i < src_len; i += 3) {
  5827. a = src[i];
  5828. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5829. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5830. dst[j++] = b64[a >> 2];
  5831. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5832. if (i + 1 < src_len) {
  5833. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5834. }
  5835. if (i + 2 < src_len) {
  5836. dst[j++] = b64[c & 63];
  5837. }
  5838. }
  5839. while (j % 4 != 0) {
  5840. dst[j++] = '=';
  5841. }
  5842. dst[j++] = '\0';
  5843. }
  5844. #endif
  5845. #if defined(USE_LUA)
  5846. static unsigned char
  5847. b64reverse(char letter)
  5848. {
  5849. if ((letter >= 'A') && (letter <= 'Z')) {
  5850. return letter - 'A';
  5851. }
  5852. if ((letter >= 'a') && (letter <= 'z')) {
  5853. return letter - 'a' + 26;
  5854. }
  5855. if ((letter >= '0') && (letter <= '9')) {
  5856. return letter - '0' + 52;
  5857. }
  5858. if (letter == '+') {
  5859. return 62;
  5860. }
  5861. if (letter == '/') {
  5862. return 63;
  5863. }
  5864. if (letter == '=') {
  5865. return 255; /* normal end */
  5866. }
  5867. return 254; /* error */
  5868. }
  5869. static int
  5870. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5871. {
  5872. int i;
  5873. unsigned char a, b, c, d;
  5874. *dst_len = 0;
  5875. for (i = 0; i < src_len; i += 4) {
  5876. a = b64reverse(src[i]);
  5877. if (a >= 254) {
  5878. return i;
  5879. }
  5880. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5881. if (b >= 254) {
  5882. return i + 1;
  5883. }
  5884. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5885. if (c == 254) {
  5886. return i + 2;
  5887. }
  5888. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5889. if (d == 254) {
  5890. return i + 3;
  5891. }
  5892. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5893. if (c != 255) {
  5894. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5895. if (d != 255) {
  5896. dst[(*dst_len)++] = (c << 6) + d;
  5897. }
  5898. }
  5899. }
  5900. return -1;
  5901. }
  5902. #endif
  5903. static int
  5904. is_put_or_delete_method(const struct mg_connection *conn)
  5905. {
  5906. if (conn) {
  5907. const char *s = conn->request_info.request_method;
  5908. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5909. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5910. }
  5911. return 0;
  5912. }
  5913. #if !defined(NO_FILES)
  5914. static int
  5915. extention_matches_script(
  5916. struct mg_connection *conn, /* in: request (must be valid) */
  5917. const char *filename /* in: filename (must be valid) */
  5918. )
  5919. {
  5920. #if !defined(NO_CGI)
  5921. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  5922. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  5923. filename) > 0) {
  5924. return 1;
  5925. }
  5926. #endif
  5927. #if defined(USE_LUA)
  5928. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  5929. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5930. filename) > 0) {
  5931. return 1;
  5932. }
  5933. #endif
  5934. #if defined(USE_DUKTAPE)
  5935. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5936. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5937. filename) > 0) {
  5938. return 1;
  5939. }
  5940. #endif
  5941. /* filename and conn could be unused, if all preocessor conditions
  5942. * are false (no script language supported). */
  5943. (void)filename;
  5944. (void)conn;
  5945. return 0;
  5946. }
  5947. /* For given directory path, substitute it to valid index file.
  5948. * Return 1 if index file has been found, 0 if not found.
  5949. * If the file is found, it's stats is returned in stp. */
  5950. static int
  5951. substitute_index_file(struct mg_connection *conn,
  5952. char *path,
  5953. size_t path_len,
  5954. struct mg_file_stat *filestat)
  5955. {
  5956. const char *list = conn->dom_ctx->config[INDEX_FILES];
  5957. struct vec filename_vec;
  5958. size_t n = strlen(path);
  5959. int found = 0;
  5960. /* The 'path' given to us points to the directory. Remove all trailing
  5961. * directory separator characters from the end of the path, and
  5962. * then append single directory separator character. */
  5963. while ((n > 0) && (path[n - 1] == '/')) {
  5964. n--;
  5965. }
  5966. path[n] = '/';
  5967. /* Traverse index files list. For each entry, append it to the given
  5968. * path and see if the file exists. If it exists, break the loop */
  5969. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5970. /* Ignore too long entries that may overflow path buffer */
  5971. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  5972. continue;
  5973. }
  5974. /* Prepare full path to the index file */
  5975. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5976. /* Does it exist? */
  5977. if (mg_stat(conn, path, filestat)) {
  5978. /* Yes it does, break the loop */
  5979. found = 1;
  5980. break;
  5981. }
  5982. }
  5983. /* If no index file exists, restore directory path */
  5984. if (!found) {
  5985. path[n] = '\0';
  5986. }
  5987. return found;
  5988. }
  5989. #endif
  5990. static void
  5991. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  5992. char *filename, /* out: filename */
  5993. size_t filename_buf_len, /* in: size of filename buffer */
  5994. struct mg_file_stat *filestat, /* out: file status structure */
  5995. int *is_found, /* out: file found (directly) */
  5996. int *is_script_resource, /* out: handled by a script? */
  5997. int *is_websocket_request, /* out: websocket connetion? */
  5998. int *is_put_or_delete_request /* out: put/delete a file? */
  5999. )
  6000. {
  6001. char const *accept_encoding;
  6002. #if !defined(NO_FILES)
  6003. const char *uri = conn->request_info.local_uri;
  6004. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6005. const char *rewrite;
  6006. struct vec a, b;
  6007. ptrdiff_t match_len;
  6008. char gz_path[PATH_MAX];
  6009. int truncated;
  6010. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6011. char *tmp_str;
  6012. size_t tmp_str_len, sep_pos;
  6013. int allow_substitute_script_subresources;
  6014. #endif
  6015. #else
  6016. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6017. #endif
  6018. /* Step 1: Set all initially unknown outputs to zero */
  6019. memset(filestat, 0, sizeof(*filestat));
  6020. *filename = 0;
  6021. *is_found = 0;
  6022. *is_script_resource = 0;
  6023. /* Step 2: Check if the request attempts to modify the file system */
  6024. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6025. /* Step 3: Check if it is a websocket request, and modify the document
  6026. * root if required */
  6027. #if defined(USE_WEBSOCKET)
  6028. *is_websocket_request = is_websocket_protocol(conn);
  6029. #if !defined(NO_FILES)
  6030. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6031. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6032. }
  6033. #endif /* !NO_FILES */
  6034. #else /* USE_WEBSOCKET */
  6035. *is_websocket_request = 0;
  6036. #endif /* USE_WEBSOCKET */
  6037. /* Step 4: Check if gzip encoded response is allowed */
  6038. conn->accept_gzip = 0;
  6039. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6040. if (strstr(accept_encoding, "gzip") != NULL) {
  6041. conn->accept_gzip = 1;
  6042. }
  6043. }
  6044. #if !defined(NO_FILES)
  6045. /* Step 5: If there is no root directory, don't look for files. */
  6046. /* Note that root == NULL is a regular use case here. This occurs,
  6047. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6048. * config is not required. */
  6049. if (root == NULL) {
  6050. /* all file related outputs have already been set to 0, just return
  6051. */
  6052. return;
  6053. }
  6054. /* Step 6: Determine the local file path from the root path and the
  6055. * request uri. */
  6056. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6057. * part of the path one byte on the right. */
  6058. mg_snprintf(
  6059. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6060. if (truncated) {
  6061. goto interpret_cleanup;
  6062. }
  6063. /* Step 7: URI rewriting */
  6064. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6065. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6066. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6067. mg_snprintf(conn,
  6068. &truncated,
  6069. filename,
  6070. filename_buf_len - 1,
  6071. "%.*s%s",
  6072. (int)b.len,
  6073. b.ptr,
  6074. uri + match_len);
  6075. break;
  6076. }
  6077. }
  6078. if (truncated) {
  6079. goto interpret_cleanup;
  6080. }
  6081. /* Step 8: Check if the file exists at the server */
  6082. /* Local file path and name, corresponding to requested URI
  6083. * is now stored in "filename" variable. */
  6084. if (mg_stat(conn, filename, filestat)) {
  6085. int uri_len = (int)strlen(uri);
  6086. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6087. /* 8.1: File exists. */
  6088. *is_found = 1;
  6089. /* 8.2: Check if it is a script type. */
  6090. if (extention_matches_script(conn, filename)) {
  6091. /* The request addresses a CGI resource, Lua script or
  6092. * server-side javascript.
  6093. * The URI corresponds to the script itself (like
  6094. * /path/script.cgi), and there is no additional resource
  6095. * path (like /path/script.cgi/something).
  6096. * Requests that modify (replace or delete) a resource, like
  6097. * PUT and DELETE requests, should replace/delete the script
  6098. * file.
  6099. * Requests that read or write from/to a resource, like GET and
  6100. * POST requests, should call the script and return the
  6101. * generated response. */
  6102. *is_script_resource = (!*is_put_or_delete_request);
  6103. }
  6104. /* 8.3: If the request target is a directory, there could be
  6105. * a substitute file (index.html, index.cgi, ...). */
  6106. if (filestat->is_directory && is_uri_end_slash) {
  6107. /* Use a local copy here, since substitute_index_file will
  6108. * change the content of the file status */
  6109. struct mg_file_stat tmp_filestat;
  6110. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6111. if (substitute_index_file(
  6112. conn, filename, filename_buf_len, &tmp_filestat)) {
  6113. /* Substitute file found. Copy stat to the output, then
  6114. * check if the file is a script file */
  6115. *filestat = tmp_filestat;
  6116. if (extention_matches_script(conn, filename)) {
  6117. /* Substitute file is a script file */
  6118. *is_script_resource = 1;
  6119. } else {
  6120. /* Substitute file is a regular file */
  6121. *is_script_resource = 0;
  6122. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6123. }
  6124. }
  6125. /* If there is no substitute file, the server could return
  6126. * a directory listing in a later step */
  6127. }
  6128. return;
  6129. }
  6130. /* Step 9: Check for zipped files: */
  6131. /* If we can't find the actual file, look for the file
  6132. * with the same name but a .gz extension. If we find it,
  6133. * use that and set the gzipped flag in the file struct
  6134. * to indicate that the response need to have the content-
  6135. * encoding: gzip header.
  6136. * We can only do this if the browser declares support. */
  6137. if (conn->accept_gzip) {
  6138. mg_snprintf(
  6139. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6140. if (truncated) {
  6141. goto interpret_cleanup;
  6142. }
  6143. if (mg_stat(conn, gz_path, filestat)) {
  6144. if (filestat) {
  6145. filestat->is_gzipped = 1;
  6146. *is_found = 1;
  6147. }
  6148. /* Currently gz files can not be scripts. */
  6149. return;
  6150. }
  6151. }
  6152. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6153. /* Step 10: Script resources may handle sub-resources */
  6154. /* Support PATH_INFO for CGI scripts. */
  6155. tmp_str_len = strlen(filename);
  6156. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6157. if (!tmp_str) {
  6158. /* Out of memory */
  6159. goto interpret_cleanup;
  6160. }
  6161. memcpy(tmp_str, filename, tmp_str_len + 1);
  6162. /* Check config, if index scripts may have sub-resources */
  6163. allow_substitute_script_subresources =
  6164. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6165. "yes");
  6166. sep_pos = tmp_str_len;
  6167. while (sep_pos > 0) {
  6168. sep_pos--;
  6169. if (tmp_str[sep_pos] == '/') {
  6170. int is_script = 0, does_exist = 0;
  6171. tmp_str[sep_pos] = 0;
  6172. if (tmp_str[0]) {
  6173. is_script = extention_matches_script(conn, tmp_str);
  6174. does_exist = mg_stat(conn, tmp_str, filestat);
  6175. }
  6176. if (does_exist && is_script) {
  6177. filename[sep_pos] = 0;
  6178. memmove(filename + sep_pos + 2,
  6179. filename + sep_pos + 1,
  6180. strlen(filename + sep_pos + 1) + 1);
  6181. conn->path_info = filename + sep_pos + 1;
  6182. filename[sep_pos + 1] = '/';
  6183. *is_script_resource = 1;
  6184. *is_found = 1;
  6185. break;
  6186. }
  6187. if (allow_substitute_script_subresources) {
  6188. if (substitute_index_file(
  6189. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6190. /* some intermediate directory has an index file */
  6191. if (extention_matches_script(conn, tmp_str)) {
  6192. char *tmp_str2;
  6193. DEBUG_TRACE("Substitute script %s serving path %s",
  6194. tmp_str,
  6195. filename);
  6196. /* this index file is a script */
  6197. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6198. conn->phys_ctx);
  6199. mg_snprintf(conn,
  6200. &truncated,
  6201. filename,
  6202. filename_buf_len,
  6203. "%s//%s",
  6204. tmp_str,
  6205. tmp_str2);
  6206. mg_free(tmp_str2);
  6207. if (truncated) {
  6208. mg_free(tmp_str);
  6209. goto interpret_cleanup;
  6210. }
  6211. sep_pos = strlen(tmp_str);
  6212. filename[sep_pos] = 0;
  6213. conn->path_info = filename + sep_pos + 1;
  6214. *is_script_resource = 1;
  6215. *is_found = 1;
  6216. break;
  6217. } else {
  6218. DEBUG_TRACE("Substitute file %s serving path %s",
  6219. tmp_str,
  6220. filename);
  6221. /* non-script files will not have sub-resources */
  6222. filename[sep_pos] = 0;
  6223. conn->path_info = 0;
  6224. *is_script_resource = 0;
  6225. *is_found = 0;
  6226. break;
  6227. }
  6228. }
  6229. }
  6230. tmp_str[sep_pos] = '/';
  6231. }
  6232. }
  6233. mg_free(tmp_str);
  6234. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6235. #endif /* !defined(NO_FILES) */
  6236. return;
  6237. #if !defined(NO_FILES)
  6238. /* Reset all outputs */
  6239. interpret_cleanup:
  6240. memset(filestat, 0, sizeof(*filestat));
  6241. *filename = 0;
  6242. *is_found = 0;
  6243. *is_script_resource = 0;
  6244. *is_websocket_request = 0;
  6245. *is_put_or_delete_request = 0;
  6246. #endif /* !defined(NO_FILES) */
  6247. }
  6248. /* Check whether full request is buffered. Return:
  6249. * -1 if request or response is malformed
  6250. * 0 if request or response is not yet fully buffered
  6251. * >0 actual request length, including last \r\n\r\n */
  6252. static int
  6253. get_http_header_len(const char *buf, int buflen)
  6254. {
  6255. int i;
  6256. for (i = 0; i < buflen; i++) {
  6257. /* Do an unsigned comparison in some conditions below */
  6258. const unsigned char c = ((const unsigned char *)buf)[i];
  6259. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6260. && !isprint(c)) {
  6261. /* abort scan as soon as one malformed character is found */
  6262. return -1;
  6263. }
  6264. if (i < buflen - 1) {
  6265. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6266. /* Two newline, no carriage return - not standard compliant,
  6267. * but
  6268. * it
  6269. * should be accepted */
  6270. return i + 2;
  6271. }
  6272. }
  6273. if (i < buflen - 3) {
  6274. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6275. && (buf[i + 3] == '\n')) {
  6276. /* Two \r\n - standard compliant */
  6277. return i + 4;
  6278. }
  6279. }
  6280. }
  6281. return 0;
  6282. }
  6283. #if !defined(NO_CACHING)
  6284. /* Convert month to the month number. Return -1 on error, or month number */
  6285. static int
  6286. get_month_index(const char *s)
  6287. {
  6288. size_t i;
  6289. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6290. if (!strcmp(s, month_names[i])) {
  6291. return (int)i;
  6292. }
  6293. }
  6294. return -1;
  6295. }
  6296. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6297. static time_t
  6298. parse_date_string(const char *datetime)
  6299. {
  6300. char month_str[32] = {0};
  6301. int second, minute, hour, day, month, year;
  6302. time_t result = (time_t)0;
  6303. struct tm tm;
  6304. if ((sscanf(datetime,
  6305. "%d/%3s/%d %d:%d:%d",
  6306. &day,
  6307. month_str,
  6308. &year,
  6309. &hour,
  6310. &minute,
  6311. &second) == 6) || (sscanf(datetime,
  6312. "%d %3s %d %d:%d:%d",
  6313. &day,
  6314. month_str,
  6315. &year,
  6316. &hour,
  6317. &minute,
  6318. &second) == 6)
  6319. || (sscanf(datetime,
  6320. "%*3s, %d %3s %d %d:%d:%d",
  6321. &day,
  6322. month_str,
  6323. &year,
  6324. &hour,
  6325. &minute,
  6326. &second) == 6) || (sscanf(datetime,
  6327. "%d-%3s-%d %d:%d:%d",
  6328. &day,
  6329. month_str,
  6330. &year,
  6331. &hour,
  6332. &minute,
  6333. &second) == 6)) {
  6334. month = get_month_index(month_str);
  6335. if ((month >= 0) && (year >= 1970)) {
  6336. memset(&tm, 0, sizeof(tm));
  6337. tm.tm_year = year - 1900;
  6338. tm.tm_mon = month;
  6339. tm.tm_mday = day;
  6340. tm.tm_hour = hour;
  6341. tm.tm_min = minute;
  6342. tm.tm_sec = second;
  6343. result = timegm(&tm);
  6344. }
  6345. }
  6346. return result;
  6347. }
  6348. #endif /* !NO_CACHING */
  6349. /* Protect against directory disclosure attack by removing '..',
  6350. * excessive '/' and '\' characters */
  6351. static void
  6352. remove_double_dots_and_double_slashes(char *s)
  6353. {
  6354. char *p = s;
  6355. while ((s[0] == '.') && (s[1] == '.')) {
  6356. s++;
  6357. }
  6358. while (*s != '\0') {
  6359. *p++ = *s++;
  6360. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6361. /* Skip all following slashes, backslashes and double-dots */
  6362. while (s[0] != '\0') {
  6363. if ((s[0] == '/') || (s[0] == '\\')) {
  6364. s++;
  6365. } else if ((s[0] == '.') && (s[1] == '.')) {
  6366. s += 2;
  6367. } else {
  6368. break;
  6369. }
  6370. }
  6371. }
  6372. }
  6373. *p = '\0';
  6374. }
  6375. static const struct {
  6376. const char *extension;
  6377. size_t ext_len;
  6378. const char *mime_type;
  6379. } builtin_mime_types[] = {
  6380. /* IANA registered MIME types
  6381. * (http://www.iana.org/assignments/media-types)
  6382. * application types */
  6383. {".doc", 4, "application/msword"},
  6384. {".eps", 4, "application/postscript"},
  6385. {".exe", 4, "application/octet-stream"},
  6386. {".js", 3, "application/javascript"},
  6387. {".json", 5, "application/json"},
  6388. {".pdf", 4, "application/pdf"},
  6389. {".ps", 3, "application/postscript"},
  6390. {".rtf", 4, "application/rtf"},
  6391. {".xhtml", 6, "application/xhtml+xml"},
  6392. {".xsl", 4, "application/xml"},
  6393. {".xslt", 5, "application/xml"},
  6394. /* fonts */
  6395. {".ttf", 4, "application/font-sfnt"},
  6396. {".cff", 4, "application/font-sfnt"},
  6397. {".otf", 4, "application/font-sfnt"},
  6398. {".aat", 4, "application/font-sfnt"},
  6399. {".sil", 4, "application/font-sfnt"},
  6400. {".pfr", 4, "application/font-tdpfr"},
  6401. {".woff", 5, "application/font-woff"},
  6402. /* audio */
  6403. {".mp3", 4, "audio/mpeg"},
  6404. {".oga", 4, "audio/ogg"},
  6405. {".ogg", 4, "audio/ogg"},
  6406. /* image */
  6407. {".gif", 4, "image/gif"},
  6408. {".ief", 4, "image/ief"},
  6409. {".jpeg", 5, "image/jpeg"},
  6410. {".jpg", 4, "image/jpeg"},
  6411. {".jpm", 4, "image/jpm"},
  6412. {".jpx", 4, "image/jpx"},
  6413. {".png", 4, "image/png"},
  6414. {".svg", 4, "image/svg+xml"},
  6415. {".tif", 4, "image/tiff"},
  6416. {".tiff", 5, "image/tiff"},
  6417. /* model */
  6418. {".wrl", 4, "model/vrml"},
  6419. /* text */
  6420. {".css", 4, "text/css"},
  6421. {".csv", 4, "text/csv"},
  6422. {".htm", 4, "text/html"},
  6423. {".html", 5, "text/html"},
  6424. {".sgm", 4, "text/sgml"},
  6425. {".shtm", 5, "text/html"},
  6426. {".shtml", 6, "text/html"},
  6427. {".txt", 4, "text/plain"},
  6428. {".xml", 4, "text/xml"},
  6429. /* video */
  6430. {".mov", 4, "video/quicktime"},
  6431. {".mp4", 4, "video/mp4"},
  6432. {".mpeg", 5, "video/mpeg"},
  6433. {".mpg", 4, "video/mpeg"},
  6434. {".ogv", 4, "video/ogg"},
  6435. {".qt", 3, "video/quicktime"},
  6436. /* not registered types
  6437. * (http://reference.sitepoint.com/html/mime-types-full,
  6438. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6439. {".arj", 4, "application/x-arj-compressed"},
  6440. {".gz", 3, "application/x-gunzip"},
  6441. {".rar", 4, "application/x-arj-compressed"},
  6442. {".swf", 4, "application/x-shockwave-flash"},
  6443. {".tar", 4, "application/x-tar"},
  6444. {".tgz", 4, "application/x-tar-gz"},
  6445. {".torrent", 8, "application/x-bittorrent"},
  6446. {".ppt", 4, "application/x-mspowerpoint"},
  6447. {".xls", 4, "application/x-msexcel"},
  6448. {".zip", 4, "application/x-zip-compressed"},
  6449. {".aac",
  6450. 4,
  6451. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6452. {".aif", 4, "audio/x-aif"},
  6453. {".m3u", 4, "audio/x-mpegurl"},
  6454. {".mid", 4, "audio/x-midi"},
  6455. {".ra", 3, "audio/x-pn-realaudio"},
  6456. {".ram", 4, "audio/x-pn-realaudio"},
  6457. {".wav", 4, "audio/x-wav"},
  6458. {".bmp", 4, "image/bmp"},
  6459. {".ico", 4, "image/x-icon"},
  6460. {".pct", 4, "image/x-pct"},
  6461. {".pict", 5, "image/pict"},
  6462. {".rgb", 4, "image/x-rgb"},
  6463. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6464. {".asf", 4, "video/x-ms-asf"},
  6465. {".avi", 4, "video/x-msvideo"},
  6466. {".m4v", 4, "video/x-m4v"},
  6467. {NULL, 0, NULL}};
  6468. const char *
  6469. mg_get_builtin_mime_type(const char *path)
  6470. {
  6471. const char *ext;
  6472. size_t i, path_len;
  6473. path_len = strlen(path);
  6474. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6475. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6476. if ((path_len > builtin_mime_types[i].ext_len)
  6477. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6478. return builtin_mime_types[i].mime_type;
  6479. }
  6480. }
  6481. return "text/plain";
  6482. }
  6483. /* Look at the "path" extension and figure what mime type it has.
  6484. * Store mime type in the vector. */
  6485. static void
  6486. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6487. {
  6488. struct vec ext_vec, mime_vec;
  6489. const char *list, *ext;
  6490. size_t path_len;
  6491. path_len = strlen(path);
  6492. if ((conn == NULL) || (vec == NULL)) {
  6493. if (vec != NULL) {
  6494. memset(vec, '\0', sizeof(struct vec));
  6495. }
  6496. return;
  6497. }
  6498. /* Scan user-defined mime types first, in case user wants to
  6499. * override default mime types. */
  6500. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6501. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6502. /* ext now points to the path suffix */
  6503. ext = path + path_len - ext_vec.len;
  6504. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6505. *vec = mime_vec;
  6506. return;
  6507. }
  6508. }
  6509. vec->ptr = mg_get_builtin_mime_type(path);
  6510. vec->len = strlen(vec->ptr);
  6511. }
  6512. /* Stringify binary data. Output buffer must be twice as big as input,
  6513. * because each byte takes 2 bytes in string representation */
  6514. static void
  6515. bin2str(char *to, const unsigned char *p, size_t len)
  6516. {
  6517. static const char *hex = "0123456789abcdef";
  6518. for (; len--; p++) {
  6519. *to++ = hex[p[0] >> 4];
  6520. *to++ = hex[p[0] & 0x0f];
  6521. }
  6522. *to = '\0';
  6523. }
  6524. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6525. */
  6526. char *
  6527. mg_md5(char buf[33], ...)
  6528. {
  6529. md5_byte_t hash[16];
  6530. const char *p;
  6531. va_list ap;
  6532. md5_state_t ctx;
  6533. md5_init(&ctx);
  6534. va_start(ap, buf);
  6535. while ((p = va_arg(ap, const char *)) != NULL) {
  6536. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6537. }
  6538. va_end(ap);
  6539. md5_finish(&ctx, hash);
  6540. bin2str(buf, hash, sizeof(hash));
  6541. return buf;
  6542. }
  6543. /* Check the user's password, return 1 if OK */
  6544. static int
  6545. check_password(const char *method,
  6546. const char *ha1,
  6547. const char *uri,
  6548. const char *nonce,
  6549. const char *nc,
  6550. const char *cnonce,
  6551. const char *qop,
  6552. const char *response)
  6553. {
  6554. char ha2[32 + 1], expected_response[32 + 1];
  6555. /* Some of the parameters may be NULL */
  6556. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6557. || (qop == NULL) || (response == NULL)) {
  6558. return 0;
  6559. }
  6560. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6561. if (strlen(response) != 32) {
  6562. return 0;
  6563. }
  6564. mg_md5(ha2, method, ":", uri, NULL);
  6565. mg_md5(expected_response,
  6566. ha1,
  6567. ":",
  6568. nonce,
  6569. ":",
  6570. nc,
  6571. ":",
  6572. cnonce,
  6573. ":",
  6574. qop,
  6575. ":",
  6576. ha2,
  6577. NULL);
  6578. return mg_strcasecmp(response, expected_response) == 0;
  6579. }
  6580. /* Use the global passwords file, if specified by auth_gpass option,
  6581. * or search for .htpasswd in the requested directory. */
  6582. static void
  6583. open_auth_file(struct mg_connection *conn,
  6584. const char *path,
  6585. struct mg_file *filep)
  6586. {
  6587. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6588. char name[PATH_MAX];
  6589. const char *p, *e,
  6590. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6591. int truncated;
  6592. if (gpass != NULL) {
  6593. /* Use global passwords file */
  6594. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6595. #if defined(DEBUG)
  6596. /* Use mg_cry_internal here, since gpass has been configured. */
  6597. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6598. #endif
  6599. }
  6600. /* Important: using local struct mg_file to test path for
  6601. * is_directory flag. If filep is used, mg_stat() makes it
  6602. * appear as if auth file was opened.
  6603. * TODO(mid): Check if this is still required after rewriting
  6604. * mg_stat */
  6605. } else if (mg_stat(conn, path, &filep->stat)
  6606. && filep->stat.is_directory) {
  6607. mg_snprintf(conn,
  6608. &truncated,
  6609. name,
  6610. sizeof(name),
  6611. "%s/%s",
  6612. path,
  6613. PASSWORDS_FILE_NAME);
  6614. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6615. #if defined(DEBUG)
  6616. /* Don't use mg_cry_internal here, but only a trace, since this
  6617. * is
  6618. * a typical case. It will occur for every directory
  6619. * without a password file. */
  6620. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6621. #endif
  6622. }
  6623. } else {
  6624. /* Try to find .htpasswd in requested directory. */
  6625. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6626. if (e[0] == '/') {
  6627. break;
  6628. }
  6629. }
  6630. mg_snprintf(conn,
  6631. &truncated,
  6632. name,
  6633. sizeof(name),
  6634. "%.*s/%s",
  6635. (int)(e - p),
  6636. p,
  6637. PASSWORDS_FILE_NAME);
  6638. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6639. #if defined(DEBUG)
  6640. /* Don't use mg_cry_internal here, but only a trace, since this
  6641. * is
  6642. * a typical case. It will occur for every directory
  6643. * without a password file. */
  6644. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6645. #endif
  6646. }
  6647. }
  6648. }
  6649. }
  6650. /* Parsed Authorization header */
  6651. struct ah {
  6652. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6653. };
  6654. /* Return 1 on success. Always initializes the ah structure. */
  6655. static int
  6656. parse_auth_header(struct mg_connection *conn,
  6657. char *buf,
  6658. size_t buf_size,
  6659. struct ah *ah)
  6660. {
  6661. char *name, *value, *s;
  6662. const char *auth_header;
  6663. uint64_t nonce;
  6664. if (!ah || !conn) {
  6665. return 0;
  6666. }
  6667. (void)memset(ah, 0, sizeof(*ah));
  6668. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6669. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6670. return 0;
  6671. }
  6672. /* Make modifiable copy of the auth header */
  6673. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6674. s = buf;
  6675. /* Parse authorization header */
  6676. for (;;) {
  6677. /* Gobble initial spaces */
  6678. while (isspace(*(unsigned char *)s)) {
  6679. s++;
  6680. }
  6681. name = skip_quoted(&s, "=", " ", 0);
  6682. /* Value is either quote-delimited, or ends at first comma or space.
  6683. */
  6684. if (s[0] == '\"') {
  6685. s++;
  6686. value = skip_quoted(&s, "\"", " ", '\\');
  6687. if (s[0] == ',') {
  6688. s++;
  6689. }
  6690. } else {
  6691. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6692. * spaces */
  6693. }
  6694. if (*name == '\0') {
  6695. break;
  6696. }
  6697. if (!strcmp(name, "username")) {
  6698. ah->user = value;
  6699. } else if (!strcmp(name, "cnonce")) {
  6700. ah->cnonce = value;
  6701. } else if (!strcmp(name, "response")) {
  6702. ah->response = value;
  6703. } else if (!strcmp(name, "uri")) {
  6704. ah->uri = value;
  6705. } else if (!strcmp(name, "qop")) {
  6706. ah->qop = value;
  6707. } else if (!strcmp(name, "nc")) {
  6708. ah->nc = value;
  6709. } else if (!strcmp(name, "nonce")) {
  6710. ah->nonce = value;
  6711. }
  6712. }
  6713. #if !defined(NO_NONCE_CHECK)
  6714. /* Read the nonce from the response. */
  6715. if (ah->nonce == NULL) {
  6716. return 0;
  6717. }
  6718. s = NULL;
  6719. nonce = strtoull(ah->nonce, &s, 10);
  6720. if ((s == NULL) || (*s != 0)) {
  6721. return 0;
  6722. }
  6723. /* Convert the nonce from the client to a number. */
  6724. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6725. /* The converted number corresponds to the time the nounce has been
  6726. * created. This should not be earlier than the server start. */
  6727. /* Server side nonce check is valuable in all situations but one:
  6728. * if the server restarts frequently, but the client should not see
  6729. * that, so the server should accept nonces from previous starts. */
  6730. /* However, the reasonable default is to not accept a nonce from a
  6731. * previous start, so if anyone changed the access rights between
  6732. * two restarts, a new login is required. */
  6733. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6734. /* nonce is from a previous start of the server and no longer valid
  6735. * (replay attack?) */
  6736. return 0;
  6737. }
  6738. /* Check if the nonce is too high, so it has not (yet) been used by the
  6739. * server. */
  6740. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6741. + conn->dom_ctx->nonce_count)) {
  6742. return 0;
  6743. }
  6744. #else
  6745. (void)nonce;
  6746. #endif
  6747. /* CGI needs it as REMOTE_USER */
  6748. if (ah->user != NULL) {
  6749. conn->request_info.remote_user =
  6750. mg_strdup_ctx(ah->user, conn->phys_ctx);
  6751. } else {
  6752. return 0;
  6753. }
  6754. return 1;
  6755. }
  6756. static const char *
  6757. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6758. {
  6759. #if defined(MG_USE_OPEN_FILE)
  6760. const char *eof;
  6761. size_t len;
  6762. const char *memend;
  6763. #else
  6764. (void)p; /* parameter is unused */
  6765. #endif
  6766. if (!filep) {
  6767. return NULL;
  6768. }
  6769. #if defined(MG_USE_OPEN_FILE)
  6770. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6771. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6772. /* Search for \n from p till the end of stream */
  6773. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6774. if (eof != NULL) {
  6775. eof += 1; /* Include \n */
  6776. } else {
  6777. eof = memend; /* Copy remaining data */
  6778. }
  6779. len =
  6780. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6781. memcpy(buf, *p, len);
  6782. buf[len] = '\0';
  6783. *p += len;
  6784. return len ? eof : NULL;
  6785. } else /* filep->access.fp block below */
  6786. #endif
  6787. if (filep->access.fp != NULL) {
  6788. return fgets(buf, (int)size, filep->access.fp);
  6789. } else {
  6790. return NULL;
  6791. }
  6792. }
  6793. /* Define the initial recursion depth for procesesing htpasswd files that
  6794. * include other htpasswd
  6795. * (or even the same) files. It is not difficult to provide a file or files
  6796. * s.t. they force civetweb
  6797. * to infinitely recurse and then crash.
  6798. */
  6799. #define INITIAL_DEPTH 9
  6800. #if INITIAL_DEPTH <= 0
  6801. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6802. #endif
  6803. struct read_auth_file_struct {
  6804. struct mg_connection *conn;
  6805. struct ah ah;
  6806. const char *domain;
  6807. char buf[256 + 256 + 40];
  6808. const char *f_user;
  6809. const char *f_domain;
  6810. const char *f_ha1;
  6811. };
  6812. static int
  6813. read_auth_file(struct mg_file *filep,
  6814. struct read_auth_file_struct *workdata,
  6815. int depth)
  6816. {
  6817. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  6818. int is_authorized = 0;
  6819. struct mg_file fp;
  6820. size_t l;
  6821. if (!filep || !workdata || (0 == depth)) {
  6822. return 0;
  6823. }
  6824. /* Loop over passwords file */
  6825. #if defined(MG_USE_OPEN_FILE)
  6826. p = (char *)filep->access.membuf;
  6827. #endif
  6828. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6829. l = strlen(workdata->buf);
  6830. while (l > 0) {
  6831. if (isspace(workdata->buf[l - 1])
  6832. || iscntrl(workdata->buf[l - 1])) {
  6833. l--;
  6834. workdata->buf[l] = 0;
  6835. } else
  6836. break;
  6837. }
  6838. if (l < 1) {
  6839. continue;
  6840. }
  6841. workdata->f_user = workdata->buf;
  6842. if (workdata->f_user[0] == ':') {
  6843. /* user names may not contain a ':' and may not be empty,
  6844. * so lines starting with ':' may be used for a special purpose
  6845. */
  6846. if (workdata->f_user[1] == '#') {
  6847. /* :# is a comment */
  6848. continue;
  6849. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6850. if (mg_fopen(workdata->conn,
  6851. workdata->f_user + 9,
  6852. MG_FOPEN_MODE_READ,
  6853. &fp)) {
  6854. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6855. (void)mg_fclose(
  6856. &fp.access); /* ignore error on read only file */
  6857. /* No need to continue processing files once we have a
  6858. * match, since nothing will reset it back
  6859. * to 0.
  6860. */
  6861. if (is_authorized) {
  6862. return is_authorized;
  6863. }
  6864. } else {
  6865. mg_cry_internal(workdata->conn,
  6866. "%s: cannot open authorization file: %s",
  6867. __func__,
  6868. workdata->buf);
  6869. }
  6870. continue;
  6871. }
  6872. /* everything is invalid for the moment (might change in the
  6873. * future) */
  6874. mg_cry_internal(workdata->conn,
  6875. "%s: syntax error in authorization file: %s",
  6876. __func__,
  6877. workdata->buf);
  6878. continue;
  6879. }
  6880. workdata->f_domain = strchr(workdata->f_user, ':');
  6881. if (workdata->f_domain == NULL) {
  6882. mg_cry_internal(workdata->conn,
  6883. "%s: syntax error in authorization file: %s",
  6884. __func__,
  6885. workdata->buf);
  6886. continue;
  6887. }
  6888. *(char *)(workdata->f_domain) = 0;
  6889. (workdata->f_domain)++;
  6890. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6891. if (workdata->f_ha1 == NULL) {
  6892. mg_cry_internal(workdata->conn,
  6893. "%s: syntax error in authorization file: %s",
  6894. __func__,
  6895. workdata->buf);
  6896. continue;
  6897. }
  6898. *(char *)(workdata->f_ha1) = 0;
  6899. (workdata->f_ha1)++;
  6900. if (!strcmp(workdata->ah.user, workdata->f_user)
  6901. && !strcmp(workdata->domain, workdata->f_domain)) {
  6902. return check_password(workdata->conn->request_info.request_method,
  6903. workdata->f_ha1,
  6904. workdata->ah.uri,
  6905. workdata->ah.nonce,
  6906. workdata->ah.nc,
  6907. workdata->ah.cnonce,
  6908. workdata->ah.qop,
  6909. workdata->ah.response);
  6910. }
  6911. }
  6912. return is_authorized;
  6913. }
  6914. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6915. static int
  6916. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  6917. {
  6918. struct read_auth_file_struct workdata;
  6919. char buf[MG_BUF_LEN];
  6920. if (!conn || !conn->dom_ctx) {
  6921. return 0;
  6922. }
  6923. memset(&workdata, 0, sizeof(workdata));
  6924. workdata.conn = conn;
  6925. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6926. return 0;
  6927. }
  6928. if (realm) {
  6929. workdata.domain = realm;
  6930. } else {
  6931. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  6932. }
  6933. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6934. }
  6935. /* Public function to check http digest authentication header */
  6936. int
  6937. mg_check_digest_access_authentication(struct mg_connection *conn,
  6938. const char *realm,
  6939. const char *filename)
  6940. {
  6941. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6942. int auth;
  6943. if (!conn || !filename) {
  6944. return -1;
  6945. }
  6946. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  6947. return -2;
  6948. }
  6949. auth = authorize(conn, &file, realm);
  6950. mg_fclose(&file.access);
  6951. return auth;
  6952. }
  6953. /* Return 1 if request is authorised, 0 otherwise. */
  6954. static int
  6955. check_authorization(struct mg_connection *conn, const char *path)
  6956. {
  6957. char fname[PATH_MAX];
  6958. struct vec uri_vec, filename_vec;
  6959. const char *list;
  6960. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6961. int authorized = 1, truncated;
  6962. if (!conn || !conn->dom_ctx) {
  6963. return 0;
  6964. }
  6965. list = conn->dom_ctx->config[PROTECT_URI];
  6966. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6967. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6968. mg_snprintf(conn,
  6969. &truncated,
  6970. fname,
  6971. sizeof(fname),
  6972. "%.*s",
  6973. (int)filename_vec.len,
  6974. filename_vec.ptr);
  6975. if (truncated
  6976. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6977. mg_cry_internal(conn,
  6978. "%s: cannot open %s: %s",
  6979. __func__,
  6980. fname,
  6981. strerror(errno));
  6982. }
  6983. break;
  6984. }
  6985. }
  6986. if (!is_file_opened(&file.access)) {
  6987. open_auth_file(conn, path, &file);
  6988. }
  6989. if (is_file_opened(&file.access)) {
  6990. authorized = authorize(conn, &file, NULL);
  6991. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6992. }
  6993. return authorized;
  6994. }
  6995. /* Internal function. Assumes conn is valid */
  6996. static void
  6997. send_authorization_request(struct mg_connection *conn, const char *realm)
  6998. {
  6999. char date[64];
  7000. time_t curtime = time(NULL);
  7001. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7002. if (!realm) {
  7003. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7004. }
  7005. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7006. nonce += conn->dom_ctx->nonce_count;
  7007. ++conn->dom_ctx->nonce_count;
  7008. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7009. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7010. conn->status_code = 401;
  7011. conn->must_close = 1;
  7012. gmt_time_string(date, sizeof(date), &curtime);
  7013. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7014. send_no_cache_header(conn);
  7015. send_additional_header(conn);
  7016. mg_printf(conn,
  7017. "Date: %s\r\n"
  7018. "Connection: %s\r\n"
  7019. "Content-Length: 0\r\n"
  7020. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7021. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7022. date,
  7023. suggest_connection_header(conn),
  7024. realm,
  7025. nonce);
  7026. }
  7027. /* Interface function. Parameters are provided by the user, so do
  7028. * at least some basic checks.
  7029. */
  7030. int
  7031. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7032. const char *realm)
  7033. {
  7034. if (conn && conn->dom_ctx) {
  7035. send_authorization_request(conn, realm);
  7036. return 0;
  7037. }
  7038. return -1;
  7039. }
  7040. #if !defined(NO_FILES)
  7041. static int
  7042. is_authorized_for_put(struct mg_connection *conn)
  7043. {
  7044. if (conn) {
  7045. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7046. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7047. int ret = 0;
  7048. if (passfile != NULL
  7049. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7050. ret = authorize(conn, &file, NULL);
  7051. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7052. }
  7053. return ret;
  7054. }
  7055. return 0;
  7056. }
  7057. #endif
  7058. int
  7059. mg_modify_passwords_file(const char *fname,
  7060. const char *domain,
  7061. const char *user,
  7062. const char *pass)
  7063. {
  7064. int found, i;
  7065. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7066. FILE *fp, *fp2;
  7067. found = 0;
  7068. fp = fp2 = NULL;
  7069. /* Regard empty password as no password - remove user record. */
  7070. if ((pass != NULL) && (pass[0] == '\0')) {
  7071. pass = NULL;
  7072. }
  7073. /* Other arguments must not be empty */
  7074. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7075. return 0;
  7076. }
  7077. /* Using the given file format, user name and domain must not contain
  7078. * ':'
  7079. */
  7080. if (strchr(user, ':') != NULL) {
  7081. return 0;
  7082. }
  7083. if (strchr(domain, ':') != NULL) {
  7084. return 0;
  7085. }
  7086. /* Do not allow control characters like newline in user name and domain.
  7087. * Do not allow excessively long names either. */
  7088. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7089. if (iscntrl(user[i])) {
  7090. return 0;
  7091. }
  7092. }
  7093. if (user[i]) {
  7094. return 0;
  7095. }
  7096. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7097. if (iscntrl(domain[i])) {
  7098. return 0;
  7099. }
  7100. }
  7101. if (domain[i]) {
  7102. return 0;
  7103. }
  7104. /* The maximum length of the path to the password file is limited */
  7105. if ((strlen(fname) + 4) >= PATH_MAX) {
  7106. return 0;
  7107. }
  7108. /* Create a temporary file name. Length has been checked before. */
  7109. strcpy(tmp, fname);
  7110. strcat(tmp, ".tmp");
  7111. /* Create the file if does not exist */
  7112. /* Use of fopen here is OK, since fname is only ASCII */
  7113. if ((fp = fopen(fname, "a+")) != NULL) {
  7114. (void)fclose(fp);
  7115. }
  7116. /* Open the given file and temporary file */
  7117. if ((fp = fopen(fname, "r")) == NULL) {
  7118. return 0;
  7119. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7120. fclose(fp);
  7121. return 0;
  7122. }
  7123. /* Copy the stuff to temporary file */
  7124. while (fgets(line, sizeof(line), fp) != NULL) {
  7125. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7126. continue;
  7127. }
  7128. u[255] = 0;
  7129. d[255] = 0;
  7130. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7131. found++;
  7132. if (pass != NULL) {
  7133. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7134. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7135. }
  7136. } else {
  7137. fprintf(fp2, "%s", line);
  7138. }
  7139. }
  7140. /* If new user, just add it */
  7141. if (!found && (pass != NULL)) {
  7142. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7143. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7144. }
  7145. /* Close files */
  7146. fclose(fp);
  7147. fclose(fp2);
  7148. /* Put the temp file in place of real file */
  7149. IGNORE_UNUSED_RESULT(remove(fname));
  7150. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7151. return 1;
  7152. }
  7153. static int
  7154. is_valid_port(unsigned long port)
  7155. {
  7156. return (port <= 0xffff);
  7157. }
  7158. static int
  7159. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7160. {
  7161. struct addrinfo hints, *res, *ressave;
  7162. int func_ret = 0;
  7163. int gai_ret;
  7164. memset(&hints, 0, sizeof(struct addrinfo));
  7165. hints.ai_family = af;
  7166. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7167. if (gai_ret != 0) {
  7168. /* gai_strerror could be used to convert gai_ret to a string */
  7169. /* POSIX return values: see
  7170. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7171. */
  7172. /* Windows return values: see
  7173. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7174. */
  7175. return 0;
  7176. }
  7177. ressave = res;
  7178. while (res) {
  7179. if (dstlen >= (size_t)res->ai_addrlen) {
  7180. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7181. func_ret = 1;
  7182. }
  7183. res = res->ai_next;
  7184. }
  7185. freeaddrinfo(ressave);
  7186. return func_ret;
  7187. }
  7188. static int
  7189. connect_socket(struct mg_context *ctx /* may be NULL */,
  7190. const char *host,
  7191. int port,
  7192. int use_ssl,
  7193. char *ebuf,
  7194. size_t ebuf_len,
  7195. SOCKET *sock /* output: socket, must not be NULL */,
  7196. union usa *sa /* output: socket address, must not be NULL */
  7197. )
  7198. {
  7199. int ip_ver = 0;
  7200. int conn_ret = -1;
  7201. *sock = INVALID_SOCKET;
  7202. memset(sa, 0, sizeof(*sa));
  7203. if (ebuf_len > 0) {
  7204. *ebuf = 0;
  7205. }
  7206. if (host == NULL) {
  7207. mg_snprintf(NULL,
  7208. NULL, /* No truncation check for ebuf */
  7209. ebuf,
  7210. ebuf_len,
  7211. "%s",
  7212. "NULL host");
  7213. return 0;
  7214. }
  7215. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7216. mg_snprintf(NULL,
  7217. NULL, /* No truncation check for ebuf */
  7218. ebuf,
  7219. ebuf_len,
  7220. "%s",
  7221. "invalid port");
  7222. return 0;
  7223. }
  7224. #if !defined(NO_SSL)
  7225. #if !defined(NO_SSL_DL)
  7226. #if defined(OPENSSL_API_1_1)
  7227. if (use_ssl && (TLS_client_method == NULL)) {
  7228. mg_snprintf(NULL,
  7229. NULL, /* No truncation check for ebuf */
  7230. ebuf,
  7231. ebuf_len,
  7232. "%s",
  7233. "SSL is not initialized");
  7234. return 0;
  7235. }
  7236. #else
  7237. if (use_ssl && (SSLv23_client_method == NULL)) {
  7238. mg_snprintf(NULL,
  7239. NULL, /* No truncation check for ebuf */
  7240. ebuf,
  7241. ebuf_len,
  7242. "%s",
  7243. "SSL is not initialized");
  7244. return 0;
  7245. }
  7246. #endif /* OPENSSL_API_1_1 */
  7247. #else
  7248. (void)use_ssl;
  7249. #endif /* NO_SSL_DL */
  7250. #else
  7251. (void)use_ssl;
  7252. #endif /* !defined(NO_SSL) */
  7253. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7254. sa->sin.sin_family = AF_INET;
  7255. sa->sin.sin_port = htons((uint16_t)port);
  7256. ip_ver = 4;
  7257. #if defined(USE_IPV6)
  7258. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7259. sa->sin6.sin6_family = AF_INET6;
  7260. sa->sin6.sin6_port = htons((uint16_t)port);
  7261. ip_ver = 6;
  7262. } else if (host[0] == '[') {
  7263. /* While getaddrinfo on Windows will work with [::1],
  7264. * getaddrinfo on Linux only works with ::1 (without []). */
  7265. size_t l = strlen(host + 1);
  7266. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7267. if (h) {
  7268. h[l - 1] = 0;
  7269. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7270. sa->sin6.sin6_family = AF_INET6;
  7271. sa->sin6.sin6_port = htons((uint16_t)port);
  7272. ip_ver = 6;
  7273. }
  7274. mg_free(h);
  7275. }
  7276. #endif
  7277. }
  7278. if (ip_ver == 0) {
  7279. mg_snprintf(NULL,
  7280. NULL, /* No truncation check for ebuf */
  7281. ebuf,
  7282. ebuf_len,
  7283. "%s",
  7284. "host not found");
  7285. return 0;
  7286. }
  7287. if (ip_ver == 4) {
  7288. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7289. }
  7290. #if defined(USE_IPV6)
  7291. else if (ip_ver == 6) {
  7292. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7293. }
  7294. #endif
  7295. if (*sock == INVALID_SOCKET) {
  7296. mg_snprintf(NULL,
  7297. NULL, /* No truncation check for ebuf */
  7298. ebuf,
  7299. ebuf_len,
  7300. "socket(): %s",
  7301. strerror(ERRNO));
  7302. return 0;
  7303. }
  7304. if (0 != set_non_blocking_mode(*sock)) {
  7305. mg_snprintf(NULL,
  7306. NULL, /* No truncation check for ebuf */
  7307. ebuf,
  7308. ebuf_len,
  7309. "Cannot set socket to non-blocking: %s",
  7310. strerror(ERRNO));
  7311. closesocket(*sock);
  7312. *sock = INVALID_SOCKET;
  7313. return 0;
  7314. }
  7315. set_close_on_exec(*sock, fc(ctx));
  7316. if (ip_ver == 4) {
  7317. /* connected with IPv4 */
  7318. conn_ret = connect(*sock,
  7319. (struct sockaddr *)((void *)&sa->sin),
  7320. sizeof(sa->sin));
  7321. }
  7322. #if defined(USE_IPV6)
  7323. else if (ip_ver == 6) {
  7324. /* connected with IPv6 */
  7325. conn_ret = connect(*sock,
  7326. (struct sockaddr *)((void *)&sa->sin6),
  7327. sizeof(sa->sin6));
  7328. }
  7329. #endif
  7330. if (conn_ret != 0) {
  7331. fd_set fdset;
  7332. struct timeval timeout;
  7333. int sockerr = -1;
  7334. void *psockerr = &sockerr;
  7335. #if defined(_WIN32)
  7336. int len = (int)sizeof(sockerr);
  7337. #else
  7338. socklen_t len = (socklen_t)sizeof(sockerr);
  7339. #endif
  7340. FD_ZERO(&fdset);
  7341. FD_SET(*sock, &fdset);
  7342. timeout.tv_sec = 10; /* 10 second timeout */
  7343. timeout.tv_usec = 0;
  7344. if (select((int)(*sock) + 1, NULL, &fdset, NULL, &timeout) != 1) {
  7345. /* Not connected */
  7346. mg_snprintf(NULL,
  7347. NULL, /* No truncation check for ebuf */
  7348. ebuf,
  7349. ebuf_len,
  7350. "connect(%s:%d): timeout",
  7351. host,
  7352. port);
  7353. closesocket(*sock);
  7354. *sock = INVALID_SOCKET;
  7355. return 0;
  7356. }
  7357. #if defined(_WIN32)
  7358. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7359. #else
  7360. getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7361. #endif
  7362. if (sockerr != 0) {
  7363. /* Not connected */
  7364. mg_snprintf(NULL,
  7365. NULL, /* No truncation check for ebuf */
  7366. ebuf,
  7367. ebuf_len,
  7368. "connect(%s:%d): error %s",
  7369. host,
  7370. port,
  7371. strerror(sockerr));
  7372. closesocket(*sock);
  7373. *sock = INVALID_SOCKET;
  7374. return 0;
  7375. }
  7376. }
  7377. return 1;
  7378. }
  7379. int
  7380. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7381. {
  7382. static const char *dont_escape = "._-$,;~()";
  7383. static const char *hex = "0123456789abcdef";
  7384. char *pos = dst;
  7385. const char *end = dst + dst_len - 1;
  7386. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7387. if (isalnum(*(const unsigned char *)src)
  7388. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7389. *pos = *src;
  7390. } else if (pos + 2 < end) {
  7391. pos[0] = '%';
  7392. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7393. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7394. pos += 2;
  7395. } else {
  7396. break;
  7397. }
  7398. }
  7399. *pos = '\0';
  7400. return (*src == '\0') ? (int)(pos - dst) : -1;
  7401. }
  7402. /* Return 0 on success, non-zero if an error occurs. */
  7403. static int
  7404. print_dir_entry(struct de *de)
  7405. {
  7406. size_t hrefsize;
  7407. char *href;
  7408. char size[64], mod[64];
  7409. #if defined(REENTRANT_TIME)
  7410. struct tm _tm;
  7411. struct tm *tm = &_tm;
  7412. #else
  7413. struct tm *tm;
  7414. #endif
  7415. hrefsize = PATH_MAX * 3; /* worst case */
  7416. href = (char *)mg_malloc(hrefsize);
  7417. if (href == NULL) {
  7418. return -1;
  7419. }
  7420. if (de->file.is_directory) {
  7421. mg_snprintf(de->conn,
  7422. NULL, /* Buffer is big enough */
  7423. size,
  7424. sizeof(size),
  7425. "%s",
  7426. "[DIRECTORY]");
  7427. } else {
  7428. /* We use (signed) cast below because MSVC 6 compiler cannot
  7429. * convert unsigned __int64 to double. Sigh. */
  7430. if (de->file.size < 1024) {
  7431. mg_snprintf(de->conn,
  7432. NULL, /* Buffer is big enough */
  7433. size,
  7434. sizeof(size),
  7435. "%d",
  7436. (int)de->file.size);
  7437. } else if (de->file.size < 0x100000) {
  7438. mg_snprintf(de->conn,
  7439. NULL, /* Buffer is big enough */
  7440. size,
  7441. sizeof(size),
  7442. "%.1fk",
  7443. (double)de->file.size / 1024.0);
  7444. } else if (de->file.size < 0x40000000) {
  7445. mg_snprintf(de->conn,
  7446. NULL, /* Buffer is big enough */
  7447. size,
  7448. sizeof(size),
  7449. "%.1fM",
  7450. (double)de->file.size / 1048576);
  7451. } else {
  7452. mg_snprintf(de->conn,
  7453. NULL, /* Buffer is big enough */
  7454. size,
  7455. sizeof(size),
  7456. "%.1fG",
  7457. (double)de->file.size / 1073741824);
  7458. }
  7459. }
  7460. /* Note: mg_snprintf will not cause a buffer overflow above.
  7461. * So, string truncation checks are not required here. */
  7462. #if defined(REENTRANT_TIME)
  7463. localtime_r(&de->file.last_modified, tm);
  7464. #else
  7465. tm = localtime(&de->file.last_modified);
  7466. #endif
  7467. if (tm != NULL) {
  7468. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7469. } else {
  7470. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7471. mod[sizeof(mod) - 1] = '\0';
  7472. }
  7473. mg_url_encode(de->file_name, href, hrefsize);
  7474. mg_printf(de->conn,
  7475. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7476. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7477. de->conn->request_info.local_uri,
  7478. href,
  7479. de->file.is_directory ? "/" : "",
  7480. de->file_name,
  7481. de->file.is_directory ? "/" : "",
  7482. mod,
  7483. size);
  7484. mg_free(href);
  7485. return 0;
  7486. }
  7487. /* This function is called from send_directory() and used for
  7488. * sorting directory entries by size, or name, or modification time.
  7489. * On windows, __cdecl specification is needed in case if project is built
  7490. * with __stdcall convention. qsort always requires __cdels callback. */
  7491. static int WINCDECL
  7492. compare_dir_entries(const void *p1, const void *p2)
  7493. {
  7494. if (p1 && p2) {
  7495. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7496. const char *query_string = a->conn->request_info.query_string;
  7497. int cmp_result = 0;
  7498. if (query_string == NULL) {
  7499. query_string = "na";
  7500. }
  7501. if (a->file.is_directory && !b->file.is_directory) {
  7502. return -1; /* Always put directories on top */
  7503. } else if (!a->file.is_directory && b->file.is_directory) {
  7504. return 1; /* Always put directories on top */
  7505. } else if (*query_string == 'n') {
  7506. cmp_result = strcmp(a->file_name, b->file_name);
  7507. } else if (*query_string == 's') {
  7508. cmp_result = (a->file.size == b->file.size)
  7509. ? 0
  7510. : ((a->file.size > b->file.size) ? 1 : -1);
  7511. } else if (*query_string == 'd') {
  7512. cmp_result =
  7513. (a->file.last_modified == b->file.last_modified)
  7514. ? 0
  7515. : ((a->file.last_modified > b->file.last_modified) ? 1
  7516. : -1);
  7517. }
  7518. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7519. }
  7520. return 0;
  7521. }
  7522. static int
  7523. must_hide_file(struct mg_connection *conn, const char *path)
  7524. {
  7525. if (conn && conn->dom_ctx) {
  7526. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7527. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7528. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7529. || ((pattern != NULL)
  7530. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7531. }
  7532. return 0;
  7533. }
  7534. static int
  7535. scan_directory(struct mg_connection *conn,
  7536. const char *dir,
  7537. void *data,
  7538. int (*cb)(struct de *, void *))
  7539. {
  7540. char path[PATH_MAX];
  7541. struct dirent *dp;
  7542. DIR *dirp;
  7543. struct de de;
  7544. int truncated;
  7545. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7546. return 0;
  7547. } else {
  7548. de.conn = conn;
  7549. while ((dp = mg_readdir(dirp)) != NULL) {
  7550. /* Do not show current dir and hidden files */
  7551. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7552. || must_hide_file(conn, dp->d_name)) {
  7553. continue;
  7554. }
  7555. mg_snprintf(
  7556. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7557. /* If we don't memset stat structure to zero, mtime will have
  7558. * garbage and strftime() will segfault later on in
  7559. * print_dir_entry(). memset is required only if mg_stat()
  7560. * fails. For more details, see
  7561. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7562. memset(&de.file, 0, sizeof(de.file));
  7563. if (truncated) {
  7564. /* If the path is not complete, skip processing. */
  7565. continue;
  7566. }
  7567. if (!mg_stat(conn, path, &de.file)) {
  7568. mg_cry_internal(conn,
  7569. "%s: mg_stat(%s) failed: %s",
  7570. __func__,
  7571. path,
  7572. strerror(ERRNO));
  7573. }
  7574. de.file_name = dp->d_name;
  7575. cb(&de, data);
  7576. }
  7577. (void)mg_closedir(dirp);
  7578. }
  7579. return 1;
  7580. }
  7581. #if !defined(NO_FILES)
  7582. static int
  7583. remove_directory(struct mg_connection *conn, const char *dir)
  7584. {
  7585. char path[PATH_MAX];
  7586. struct dirent *dp;
  7587. DIR *dirp;
  7588. struct de de;
  7589. int truncated;
  7590. int ok = 1;
  7591. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7592. return 0;
  7593. } else {
  7594. de.conn = conn;
  7595. while ((dp = mg_readdir(dirp)) != NULL) {
  7596. /* Do not show current dir (but show hidden files as they will
  7597. * also be removed) */
  7598. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7599. continue;
  7600. }
  7601. mg_snprintf(
  7602. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7603. /* If we don't memset stat structure to zero, mtime will have
  7604. * garbage and strftime() will segfault later on in
  7605. * print_dir_entry(). memset is required only if mg_stat()
  7606. * fails. For more details, see
  7607. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7608. memset(&de.file, 0, sizeof(de.file));
  7609. if (truncated) {
  7610. /* Do not delete anything shorter */
  7611. ok = 0;
  7612. continue;
  7613. }
  7614. if (!mg_stat(conn, path, &de.file)) {
  7615. mg_cry_internal(conn,
  7616. "%s: mg_stat(%s) failed: %s",
  7617. __func__,
  7618. path,
  7619. strerror(ERRNO));
  7620. ok = 0;
  7621. }
  7622. if (de.file.is_directory) {
  7623. if (remove_directory(conn, path) == 0) {
  7624. ok = 0;
  7625. }
  7626. } else {
  7627. /* This will fail file is the file is in memory */
  7628. if (mg_remove(conn, path) == 0) {
  7629. ok = 0;
  7630. }
  7631. }
  7632. }
  7633. (void)mg_closedir(dirp);
  7634. IGNORE_UNUSED_RESULT(rmdir(dir));
  7635. }
  7636. return ok;
  7637. }
  7638. #endif
  7639. struct dir_scan_data {
  7640. struct de *entries;
  7641. unsigned int num_entries;
  7642. unsigned int arr_size;
  7643. };
  7644. /* Behaves like realloc(), but frees original pointer on failure */
  7645. static void *
  7646. realloc2(void *ptr, size_t size)
  7647. {
  7648. void *new_ptr = mg_realloc(ptr, size);
  7649. if (new_ptr == NULL) {
  7650. mg_free(ptr);
  7651. }
  7652. return new_ptr;
  7653. }
  7654. static int
  7655. dir_scan_callback(struct de *de, void *data)
  7656. {
  7657. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7658. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7659. dsd->arr_size *= 2;
  7660. dsd->entries =
  7661. (struct de *)realloc2(dsd->entries,
  7662. dsd->arr_size * sizeof(dsd->entries[0]));
  7663. }
  7664. if (dsd->entries == NULL) {
  7665. /* TODO(lsm, low): propagate an error to the caller */
  7666. dsd->num_entries = 0;
  7667. } else {
  7668. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7669. dsd->entries[dsd->num_entries].file = de->file;
  7670. dsd->entries[dsd->num_entries].conn = de->conn;
  7671. dsd->num_entries++;
  7672. }
  7673. return 0;
  7674. }
  7675. static void
  7676. handle_directory_request(struct mg_connection *conn, const char *dir)
  7677. {
  7678. unsigned int i;
  7679. int sort_direction;
  7680. struct dir_scan_data data = {NULL, 0, 128};
  7681. char date[64];
  7682. time_t curtime = time(NULL);
  7683. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7684. mg_send_http_error(conn,
  7685. 500,
  7686. "Error: Cannot open directory\nopendir(%s): %s",
  7687. dir,
  7688. strerror(ERRNO));
  7689. return;
  7690. }
  7691. gmt_time_string(date, sizeof(date), &curtime);
  7692. if (!conn) {
  7693. return;
  7694. }
  7695. sort_direction = ((conn->request_info.query_string != NULL)
  7696. && (conn->request_info.query_string[1] == 'd'))
  7697. ? 'a'
  7698. : 'd';
  7699. conn->must_close = 1;
  7700. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7701. send_static_cache_header(conn);
  7702. send_additional_header(conn);
  7703. mg_printf(conn,
  7704. "Date: %s\r\n"
  7705. "Connection: close\r\n"
  7706. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7707. date);
  7708. mg_printf(conn,
  7709. "<html><head><title>Index of %s</title>"
  7710. "<style>th {text-align: left;}</style></head>"
  7711. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7712. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7713. "<th><a href=\"?d%c\">Modified</a></th>"
  7714. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7715. "<tr><td colspan=\"3\"><hr></td></tr>",
  7716. conn->request_info.local_uri,
  7717. conn->request_info.local_uri,
  7718. sort_direction,
  7719. sort_direction,
  7720. sort_direction);
  7721. /* Print first entry - link to a parent directory */
  7722. mg_printf(conn,
  7723. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7724. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7725. conn->request_info.local_uri,
  7726. "..",
  7727. "Parent directory",
  7728. "-",
  7729. "-");
  7730. /* Sort and print directory entries */
  7731. if (data.entries != NULL) {
  7732. qsort(data.entries,
  7733. (size_t)data.num_entries,
  7734. sizeof(data.entries[0]),
  7735. compare_dir_entries);
  7736. for (i = 0; i < data.num_entries; i++) {
  7737. print_dir_entry(&data.entries[i]);
  7738. mg_free(data.entries[i].file_name);
  7739. }
  7740. mg_free(data.entries);
  7741. }
  7742. mg_printf(conn, "%s", "</table></body></html>");
  7743. conn->status_code = 200;
  7744. }
  7745. /* Send len bytes from the opened file to the client. */
  7746. static void
  7747. send_file_data(struct mg_connection *conn,
  7748. struct mg_file *filep,
  7749. int64_t offset,
  7750. int64_t len)
  7751. {
  7752. char buf[MG_BUF_LEN];
  7753. int to_read, num_read, num_written;
  7754. int64_t size;
  7755. if (!filep || !conn) {
  7756. return;
  7757. }
  7758. /* Sanity check the offset */
  7759. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7760. : (int64_t)(filep->stat.size);
  7761. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7762. #if defined(MG_USE_OPEN_FILE)
  7763. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7764. /* file stored in memory */
  7765. if (len > size - offset) {
  7766. len = size - offset;
  7767. }
  7768. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7769. } else /* else block below */
  7770. #endif
  7771. if (len > 0 && filep->access.fp != NULL) {
  7772. /* file stored on disk */
  7773. #if defined(__linux__)
  7774. /* sendfile is only available for Linux */
  7775. if ((conn->ssl == 0) && (conn->throttle == 0)
  7776. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  7777. "yes"))) {
  7778. off_t sf_offs = (off_t)offset;
  7779. ssize_t sf_sent;
  7780. int sf_file = fileno(filep->access.fp);
  7781. int loop_cnt = 0;
  7782. do {
  7783. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7784. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7785. size_t sf_tosend =
  7786. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7787. sf_sent =
  7788. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7789. if (sf_sent > 0) {
  7790. len -= sf_sent;
  7791. offset += sf_sent;
  7792. } else if (loop_cnt == 0) {
  7793. /* This file can not be sent using sendfile.
  7794. * This might be the case for pseudo-files in the
  7795. * /sys/ and /proc/ file system.
  7796. * Use the regular user mode copy code instead. */
  7797. break;
  7798. } else if (sf_sent == 0) {
  7799. /* No error, but 0 bytes sent. May be EOF? */
  7800. return;
  7801. }
  7802. loop_cnt++;
  7803. } while ((len > 0) && (sf_sent >= 0));
  7804. if (sf_sent > 0) {
  7805. return; /* OK */
  7806. }
  7807. /* sf_sent<0 means error, thus fall back to the classic way */
  7808. /* This is always the case, if sf_file is not a "normal" file,
  7809. * e.g., for sending data from the output of a CGI process. */
  7810. offset = (int64_t)sf_offs;
  7811. }
  7812. #endif
  7813. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7814. mg_cry_internal(conn,
  7815. "%s: fseeko() failed: %s",
  7816. __func__,
  7817. strerror(ERRNO));
  7818. mg_send_http_error(
  7819. conn,
  7820. 500,
  7821. "%s",
  7822. "Error: Unable to access file at requested position.");
  7823. } else {
  7824. while (len > 0) {
  7825. /* Calculate how much to read from the file in the buffer */
  7826. to_read = sizeof(buf);
  7827. if ((int64_t)to_read > len) {
  7828. to_read = (int)len;
  7829. }
  7830. /* Read from file, exit the loop on error */
  7831. if ((num_read =
  7832. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7833. <= 0) {
  7834. break;
  7835. }
  7836. /* Send read bytes to the client, exit the loop on error */
  7837. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7838. != num_read) {
  7839. break;
  7840. }
  7841. /* Both read and were successful, adjust counters */
  7842. len -= num_written;
  7843. }
  7844. }
  7845. }
  7846. }
  7847. static int
  7848. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7849. {
  7850. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7851. }
  7852. static void
  7853. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7854. {
  7855. if ((filestat != NULL) && (buf != NULL)) {
  7856. mg_snprintf(NULL,
  7857. NULL, /* All calls to construct_etag use 64 byte buffer */
  7858. buf,
  7859. buf_len,
  7860. "\"%lx.%" INT64_FMT "\"",
  7861. (unsigned long)filestat->last_modified,
  7862. filestat->size);
  7863. }
  7864. }
  7865. static void
  7866. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7867. {
  7868. if (filep != NULL && filep->fp != NULL) {
  7869. #if defined(_WIN32)
  7870. (void)conn; /* Unused. */
  7871. #else
  7872. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7873. mg_cry_internal(conn,
  7874. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7875. __func__,
  7876. strerror(ERRNO));
  7877. }
  7878. #endif
  7879. }
  7880. }
  7881. #if defined(USE_ZLIB)
  7882. #include "mod_zlib.inl"
  7883. #endif
  7884. static void
  7885. handle_static_file_request(struct mg_connection *conn,
  7886. const char *path,
  7887. struct mg_file *filep,
  7888. const char *mime_type,
  7889. const char *additional_headers)
  7890. {
  7891. char date[64], lm[64], etag[64];
  7892. char range[128]; /* large enough, so there will be no overflow */
  7893. const char *msg = "OK", *hdr;
  7894. time_t curtime = time(NULL);
  7895. int64_t cl, r1, r2;
  7896. struct vec mime_vec;
  7897. int n, truncated;
  7898. char gz_path[PATH_MAX];
  7899. const char *encoding = "";
  7900. const char *cors1, *cors2, *cors3;
  7901. int is_head_request;
  7902. #if defined(USE_ZLIB)
  7903. int allow_on_the_fly_compression = 1; /* TODO: get from config */
  7904. #endif
  7905. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  7906. return;
  7907. }
  7908. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  7909. if (mime_type == NULL) {
  7910. get_mime_type(conn, path, &mime_vec);
  7911. } else {
  7912. mime_vec.ptr = mime_type;
  7913. mime_vec.len = strlen(mime_type);
  7914. }
  7915. if (filep->stat.size > INT64_MAX) {
  7916. mg_send_http_error(conn,
  7917. 500,
  7918. "Error: File size is too large to send\n%" INT64_FMT,
  7919. filep->stat.size);
  7920. return;
  7921. }
  7922. cl = (int64_t)filep->stat.size;
  7923. conn->status_code = 200;
  7924. range[0] = '\0';
  7925. #if defined(USE_ZLIB)
  7926. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7927. * it's important to rewrite the filename after resolving
  7928. * the mime type from it, to preserve the actual file's type */
  7929. if (!conn->accept_gzip) {
  7930. allow_on_the_fly_compression = 0;
  7931. }
  7932. #endif
  7933. if (filep->stat.is_gzipped) {
  7934. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7935. if (truncated) {
  7936. mg_send_http_error(conn,
  7937. 500,
  7938. "Error: Path of zipped file too long (%s)",
  7939. path);
  7940. return;
  7941. }
  7942. path = gz_path;
  7943. encoding = "Content-Encoding: gzip\r\n";
  7944. #if defined(USE_ZLIB)
  7945. /* File is already compressed. No "on the fly" compression. */
  7946. allow_on_the_fly_compression = 0;
  7947. #endif
  7948. }
  7949. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7950. mg_send_http_error(conn,
  7951. 500,
  7952. "Error: Cannot open file\nfopen(%s): %s",
  7953. path,
  7954. strerror(ERRNO));
  7955. return;
  7956. }
  7957. fclose_on_exec(&filep->access, conn);
  7958. /* If Range: header specified, act accordingly */
  7959. r1 = r2 = 0;
  7960. hdr = mg_get_header(conn, "Range");
  7961. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7962. && (r1 >= 0) && (r2 >= 0)) {
  7963. /* actually, range requests don't play well with a pre-gzipped
  7964. * file (since the range is specified in the uncompressed space) */
  7965. if (filep->stat.is_gzipped) {
  7966. mg_send_http_error(
  7967. conn,
  7968. 416, /* 416 = Range Not Satisfiable */
  7969. "%s",
  7970. "Error: Range requests in gzipped files are not supported");
  7971. (void)mg_fclose(
  7972. &filep->access); /* ignore error on read only file */
  7973. return;
  7974. }
  7975. conn->status_code = 206;
  7976. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7977. mg_snprintf(conn,
  7978. NULL, /* range buffer is big enough */
  7979. range,
  7980. sizeof(range),
  7981. "Content-Range: bytes "
  7982. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7983. r1,
  7984. r1 + cl - 1,
  7985. filep->stat.size);
  7986. msg = "Partial Content";
  7987. #if defined(USE_ZLIB)
  7988. /* Do not compress ranges. */
  7989. allow_on_the_fly_compression = 0;
  7990. #endif
  7991. }
  7992. hdr = mg_get_header(conn, "Origin");
  7993. if (hdr) {
  7994. /* Cross-origin resource sharing (CORS), see
  7995. * http://www.html5rocks.com/en/tutorials/cors/,
  7996. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  7997. * -
  7998. * preflight is not supported for files. */
  7999. cors1 = "Access-Control-Allow-Origin: ";
  8000. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8001. cors3 = "\r\n";
  8002. } else {
  8003. cors1 = cors2 = cors3 = "";
  8004. }
  8005. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8006. * according to
  8007. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8008. gmt_time_string(date, sizeof(date), &curtime);
  8009. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8010. construct_etag(etag, sizeof(etag), &filep->stat);
  8011. /* Send header */
  8012. (void)mg_printf(conn,
  8013. "HTTP/1.1 %d %s\r\n"
  8014. "%s%s%s" /* CORS */
  8015. "Date: %s\r\n"
  8016. "Last-Modified: %s\r\n"
  8017. "Etag: %s\r\n"
  8018. "Content-Type: %.*s\r\n"
  8019. "Connection: %s\r\n",
  8020. conn->status_code,
  8021. msg,
  8022. cors1,
  8023. cors2,
  8024. cors3,
  8025. date,
  8026. lm,
  8027. etag,
  8028. (int)mime_vec.len,
  8029. mime_vec.ptr,
  8030. suggest_connection_header(conn));
  8031. send_static_cache_header(conn);
  8032. send_additional_header(conn);
  8033. #if defined(USE_ZLIB)
  8034. /* On the fly compression allowed */
  8035. if (allow_on_the_fly_compression) {
  8036. /* For on the fly compression, we don't know the content size in
  8037. * advance, so we have to use chunked encoding */
  8038. (void)mg_printf(conn,
  8039. "Content-Encoding: gzip\r\n"
  8040. "Transfer-Encoding: chunked\r\n");
  8041. } else
  8042. #endif
  8043. {
  8044. /* Without on-the-fly compression, we know the content-length
  8045. * and we can use ranges (with on-the-fly compression we cannot).
  8046. * So we send these response headers only in this case. */
  8047. (void)mg_printf(conn,
  8048. "Content-Length: %" INT64_FMT "\r\n"
  8049. "Accept-Ranges: bytes\r\n"
  8050. "%s" /* range */
  8051. "%s" /* encoding */,
  8052. cl,
  8053. range,
  8054. encoding);
  8055. }
  8056. /* The previous code must not add any header starting with X- to make
  8057. * sure no one of the additional_headers is included twice */
  8058. if (additional_headers != NULL) {
  8059. (void)mg_printf(conn,
  8060. "%.*s\r\n\r\n",
  8061. (int)strlen(additional_headers),
  8062. additional_headers);
  8063. } else {
  8064. (void)mg_printf(conn, "\r\n");
  8065. }
  8066. if (!is_head_request) {
  8067. #if defined(USE_ZLIB)
  8068. if (allow_on_the_fly_compression) {
  8069. /* Compress and send */
  8070. send_compressed_data(conn, filep);
  8071. } else
  8072. #endif
  8073. {
  8074. /* Send file directly */
  8075. send_file_data(conn, filep, r1, cl);
  8076. }
  8077. }
  8078. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8079. }
  8080. #if !defined(NO_CACHING)
  8081. /* Return True if we should reply 304 Not Modified. */
  8082. static int
  8083. is_not_modified(const struct mg_connection *conn,
  8084. const struct mg_file_stat *filestat)
  8085. {
  8086. char etag[64];
  8087. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8088. const char *inm = mg_get_header(conn, "If-None-Match");
  8089. construct_etag(etag, sizeof(etag), filestat);
  8090. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8091. || ((ims != NULL)
  8092. && (filestat->last_modified <= parse_date_string(ims)));
  8093. }
  8094. static void
  8095. handle_not_modified_static_file_request(struct mg_connection *conn,
  8096. struct mg_file *filep)
  8097. {
  8098. char date[64], lm[64], etag[64];
  8099. time_t curtime = time(NULL);
  8100. if ((conn == NULL) || (filep == NULL)) {
  8101. return;
  8102. }
  8103. conn->status_code = 304;
  8104. gmt_time_string(date, sizeof(date), &curtime);
  8105. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8106. construct_etag(etag, sizeof(etag), &filep->stat);
  8107. (void)mg_printf(conn,
  8108. "HTTP/1.1 %d %s\r\n"
  8109. "Date: %s\r\n",
  8110. conn->status_code,
  8111. mg_get_response_code_text(conn, conn->status_code),
  8112. date);
  8113. send_static_cache_header(conn);
  8114. send_additional_header(conn);
  8115. (void)mg_printf(conn,
  8116. "Last-Modified: %s\r\n"
  8117. "Etag: %s\r\n"
  8118. "Connection: %s\r\n"
  8119. "\r\n",
  8120. lm,
  8121. etag,
  8122. suggest_connection_header(conn));
  8123. }
  8124. #endif
  8125. void
  8126. mg_send_file(struct mg_connection *conn, const char *path)
  8127. {
  8128. mg_send_mime_file(conn, path, NULL);
  8129. }
  8130. void
  8131. mg_send_mime_file(struct mg_connection *conn,
  8132. const char *path,
  8133. const char *mime_type)
  8134. {
  8135. mg_send_mime_file2(conn, path, mime_type, NULL);
  8136. }
  8137. void
  8138. mg_send_mime_file2(struct mg_connection *conn,
  8139. const char *path,
  8140. const char *mime_type,
  8141. const char *additional_headers)
  8142. {
  8143. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8144. if (!conn) {
  8145. /* No conn */
  8146. return;
  8147. }
  8148. if (mg_stat(conn, path, &file.stat)) {
  8149. #if !defined(NO_CACHING)
  8150. if (is_not_modified(conn, &file.stat)) {
  8151. /* Send 304 "Not Modified" - this must not send any body data */
  8152. handle_not_modified_static_file_request(conn, &file);
  8153. } else
  8154. #endif /* NO_CACHING */
  8155. if (file.stat.is_directory) {
  8156. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8157. "yes")) {
  8158. handle_directory_request(conn, path);
  8159. } else {
  8160. mg_send_http_error(conn,
  8161. 403,
  8162. "%s",
  8163. "Error: Directory listing denied");
  8164. }
  8165. } else {
  8166. handle_static_file_request(
  8167. conn, path, &file, mime_type, additional_headers);
  8168. }
  8169. } else {
  8170. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8171. }
  8172. }
  8173. /* For a given PUT path, create all intermediate subdirectories.
  8174. * Return 0 if the path itself is a directory.
  8175. * Return 1 if the path leads to a file.
  8176. * Return -1 for if the path is too long.
  8177. * Return -2 if path can not be created.
  8178. */
  8179. static int
  8180. put_dir(struct mg_connection *conn, const char *path)
  8181. {
  8182. char buf[PATH_MAX];
  8183. const char *s, *p;
  8184. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8185. size_t len;
  8186. int res = 1;
  8187. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8188. len = (size_t)(p - path);
  8189. if (len >= sizeof(buf)) {
  8190. /* path too long */
  8191. res = -1;
  8192. break;
  8193. }
  8194. memcpy(buf, path, len);
  8195. buf[len] = '\0';
  8196. /* Try to create intermediate directory */
  8197. DEBUG_TRACE("mkdir(%s)", buf);
  8198. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8199. /* path does not exixt and can not be created */
  8200. res = -2;
  8201. break;
  8202. }
  8203. /* Is path itself a directory? */
  8204. if (p[1] == '\0') {
  8205. res = 0;
  8206. }
  8207. }
  8208. return res;
  8209. }
  8210. static void
  8211. remove_bad_file(const struct mg_connection *conn, const char *path)
  8212. {
  8213. int r = mg_remove(conn, path);
  8214. if (r != 0) {
  8215. mg_cry_internal(conn,
  8216. "%s: Cannot remove invalid file %s",
  8217. __func__,
  8218. path);
  8219. }
  8220. }
  8221. long long
  8222. mg_store_body(struct mg_connection *conn, const char *path)
  8223. {
  8224. char buf[MG_BUF_LEN];
  8225. long long len = 0;
  8226. int ret, n;
  8227. struct mg_file fi;
  8228. if (conn->consumed_content != 0) {
  8229. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8230. return -11;
  8231. }
  8232. ret = put_dir(conn, path);
  8233. if (ret < 0) {
  8234. /* -1 for path too long,
  8235. * -2 for path can not be created. */
  8236. return ret;
  8237. }
  8238. if (ret != 1) {
  8239. /* Return 0 means, path itself is a directory. */
  8240. return 0;
  8241. }
  8242. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8243. return -12;
  8244. }
  8245. ret = mg_read(conn, buf, sizeof(buf));
  8246. while (ret > 0) {
  8247. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8248. if (n != ret) {
  8249. (void)mg_fclose(
  8250. &fi.access); /* File is bad and will be removed anyway. */
  8251. remove_bad_file(conn, path);
  8252. return -13;
  8253. }
  8254. len += ret;
  8255. ret = mg_read(conn, buf, sizeof(buf));
  8256. }
  8257. /* File is open for writing. If fclose fails, there was probably an
  8258. * error flushing the buffer to disk, so the file on disk might be
  8259. * broken. Delete it and return an error to the caller. */
  8260. if (mg_fclose(&fi.access) != 0) {
  8261. remove_bad_file(conn, path);
  8262. return -14;
  8263. }
  8264. return len;
  8265. }
  8266. /* Parse a buffer:
  8267. * Forward the string pointer till the end of a word, then
  8268. * terminate it and forward till the begin of the next word.
  8269. */
  8270. static int
  8271. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8272. {
  8273. /* Forward until a space is found - use isgraph here */
  8274. /* See http://www.cplusplus.com/reference/cctype/ */
  8275. while (isgraph(**ppw)) {
  8276. (*ppw)++;
  8277. }
  8278. /* Check end of word */
  8279. if (eol) {
  8280. /* must be a end of line */
  8281. if ((**ppw != '\r') && (**ppw != '\n')) {
  8282. return -1;
  8283. }
  8284. } else {
  8285. /* must be a end of a word, but not a line */
  8286. if (**ppw != ' ') {
  8287. return -1;
  8288. }
  8289. }
  8290. /* Terminate and forward to the next word */
  8291. do {
  8292. **ppw = 0;
  8293. (*ppw)++;
  8294. } while ((**ppw) && isspace(**ppw));
  8295. /* Check after term */
  8296. if (!eol) {
  8297. /* if it's not the end of line, there must be a next word */
  8298. if (!isgraph(**ppw)) {
  8299. return -1;
  8300. }
  8301. }
  8302. /* ok */
  8303. return 1;
  8304. }
  8305. /* Parse HTTP headers from the given buffer, advance buf pointer
  8306. * to the point where parsing stopped.
  8307. * All parameters must be valid pointers (not NULL).
  8308. * Return <0 on error. */
  8309. static int
  8310. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8311. {
  8312. int i;
  8313. int num_headers = 0;
  8314. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8315. char *dp = *buf;
  8316. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8317. dp++;
  8318. }
  8319. if (dp == *buf) {
  8320. /* End of headers reached. */
  8321. break;
  8322. }
  8323. if (*dp != ':') {
  8324. /* This is not a valid field. */
  8325. return -1;
  8326. }
  8327. /* End of header key (*dp == ':') */
  8328. /* Truncate here and set the key name */
  8329. *dp = 0;
  8330. hdr[i].name = *buf;
  8331. do {
  8332. dp++;
  8333. } while (*dp == ' ');
  8334. /* The rest of the line is the value */
  8335. hdr[i].value = dp;
  8336. *buf = dp + strcspn(dp, "\r\n");
  8337. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8338. *buf = NULL;
  8339. }
  8340. num_headers = i + 1;
  8341. if (*buf) {
  8342. (*buf)[0] = 0;
  8343. (*buf)[1] = 0;
  8344. *buf += 2;
  8345. } else {
  8346. *buf = dp;
  8347. break;
  8348. }
  8349. if ((*buf)[0] == '\r') {
  8350. /* This is the end of the header */
  8351. break;
  8352. }
  8353. }
  8354. return num_headers;
  8355. }
  8356. struct mg_http_method_info {
  8357. const char *name;
  8358. int request_has_body;
  8359. int response_has_body;
  8360. int is_safe;
  8361. int is_idempotent;
  8362. int is_cacheable;
  8363. };
  8364. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8365. static struct mg_http_method_info http_methods[] = {
  8366. /* HTTP (RFC 2616) */
  8367. {"GET", 0, 1, 1, 1, 1},
  8368. {"POST", 1, 1, 0, 0, 0},
  8369. {"PUT", 1, 0, 0, 1, 0},
  8370. {"DELETE", 0, 0, 0, 1, 0},
  8371. {"HEAD", 0, 0, 1, 1, 1},
  8372. {"OPTIONS", 0, 0, 1, 1, 0},
  8373. {"CONNECT", 1, 1, 0, 0, 0},
  8374. /* TRACE method (RFC 2616) is not supported for security reasons */
  8375. /* PATCH method (RFC 5789) */
  8376. {"PATCH", 1, 0, 0, 0, 0},
  8377. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8378. /* WEBDAV (RFC 2518) */
  8379. {"PROPFIND", 0, 1, 1, 1, 0},
  8380. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8381. * Some PROPFIND results MAY be cached, with care,
  8382. * as there is no cache validation mechanism for
  8383. * most properties. This method is both safe and
  8384. * idempotent (see Section 9.1 of [RFC2616]). */
  8385. {"MKCOL", 0, 0, 0, 1, 0},
  8386. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8387. * When MKCOL is invoked without a request body,
  8388. * the newly created collection SHOULD have no
  8389. * members. A MKCOL request message may contain
  8390. * a message body. The precise behavior of a MKCOL
  8391. * request when the body is present is undefined,
  8392. * ... ==> We do not support MKCOL with body data.
  8393. * This method is idempotent, but not safe (see
  8394. * Section 9.1 of [RFC2616]). Responses to this
  8395. * method MUST NOT be cached. */
  8396. /* Unsupported WEBDAV Methods: */
  8397. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8398. /* + 11 methods from RFC 3253 */
  8399. /* ORDERPATCH (RFC 3648) */
  8400. /* ACL (RFC 3744) */
  8401. /* SEARCH (RFC 5323) */
  8402. /* + MicroSoft extensions
  8403. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8404. /* REPORT method (RFC 3253) */
  8405. {"REPORT", 1, 1, 1, 1, 1},
  8406. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8407. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8408. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8409. * to be useful for REST in case a "GET request with body" is
  8410. * required. */
  8411. {NULL, 0, 0, 0, 0, 0}
  8412. /* end of list */
  8413. };
  8414. static const struct mg_http_method_info *
  8415. get_http_method_info(const char *method)
  8416. {
  8417. /* Check if the method is known to the server. The list of all known
  8418. * HTTP methods can be found here at
  8419. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8420. */
  8421. const struct mg_http_method_info *m = http_methods;
  8422. while (m->name) {
  8423. if (!strcmp(m->name, method)) {
  8424. return m;
  8425. }
  8426. m++;
  8427. }
  8428. return NULL;
  8429. }
  8430. static int
  8431. is_valid_http_method(const char *method)
  8432. {
  8433. return (get_http_method_info(method) != NULL);
  8434. }
  8435. /* Parse HTTP request, fill in mg_request_info structure.
  8436. * This function modifies the buffer by NUL-terminating
  8437. * HTTP request components, header names and header values.
  8438. * Parameters:
  8439. * buf (in/out): pointer to the HTTP header to parse and split
  8440. * len (in): length of HTTP header buffer
  8441. * re (out): parsed header as mg_request_info
  8442. * buf and ri must be valid pointers (not NULL), len>0.
  8443. * Returns <0 on error. */
  8444. static int
  8445. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8446. {
  8447. int request_length;
  8448. int init_skip = 0;
  8449. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8450. * remote_port */
  8451. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8452. NULL;
  8453. ri->num_headers = 0;
  8454. /* RFC says that all initial whitespaces should be ingored */
  8455. /* This included all leading \r and \n (isspace) */
  8456. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8457. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8458. buf++;
  8459. len--;
  8460. init_skip++;
  8461. }
  8462. if (len == 0) {
  8463. /* Incomplete request */
  8464. return 0;
  8465. }
  8466. /* Control characters are not allowed, including zero */
  8467. if (iscntrl(*(unsigned char *)buf)) {
  8468. return -1;
  8469. }
  8470. /* Find end of HTTP header */
  8471. request_length = get_http_header_len(buf, len);
  8472. if (request_length <= 0) {
  8473. return request_length;
  8474. }
  8475. buf[request_length - 1] = '\0';
  8476. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8477. return -1;
  8478. }
  8479. /* The first word has to be the HTTP method */
  8480. ri->request_method = buf;
  8481. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8482. return -1;
  8483. }
  8484. /* Check for a valid http method */
  8485. if (!is_valid_http_method(ri->request_method)) {
  8486. return -1;
  8487. }
  8488. /* The second word is the URI */
  8489. ri->request_uri = buf;
  8490. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8491. return -1;
  8492. }
  8493. /* Next would be the HTTP version */
  8494. ri->http_version = buf;
  8495. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8496. return -1;
  8497. }
  8498. /* Check for a valid HTTP version key */
  8499. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8500. /* Invalid request */
  8501. return -1;
  8502. }
  8503. ri->http_version += 5;
  8504. /* Parse all HTTP headers */
  8505. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8506. if (ri->num_headers < 0) {
  8507. /* Error while parsing headers */
  8508. return -1;
  8509. }
  8510. return request_length + init_skip;
  8511. }
  8512. static int
  8513. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8514. {
  8515. int response_length;
  8516. int init_skip = 0;
  8517. char *tmp, *tmp2;
  8518. long l;
  8519. /* Initialize elements. */
  8520. ri->http_version = ri->status_text = NULL;
  8521. ri->num_headers = ri->status_code = 0;
  8522. /* RFC says that all initial whitespaces should be ingored */
  8523. /* This included all leading \r and \n (isspace) */
  8524. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8525. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8526. buf++;
  8527. len--;
  8528. init_skip++;
  8529. }
  8530. if (len == 0) {
  8531. /* Incomplete request */
  8532. return 0;
  8533. }
  8534. /* Control characters are not allowed, including zero */
  8535. if (iscntrl(*(unsigned char *)buf)) {
  8536. return -1;
  8537. }
  8538. /* Find end of HTTP header */
  8539. response_length = get_http_header_len(buf, len);
  8540. if (response_length <= 0) {
  8541. return response_length;
  8542. }
  8543. buf[response_length - 1] = '\0';
  8544. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8545. return -1;
  8546. }
  8547. /* The first word is the HTTP version */
  8548. /* Check for a valid HTTP version key */
  8549. if (strncmp(buf, "HTTP/", 5) != 0) {
  8550. /* Invalid request */
  8551. return -1;
  8552. }
  8553. buf += 5;
  8554. if (!isgraph(buf[0])) {
  8555. /* Invalid request */
  8556. return -1;
  8557. }
  8558. ri->http_version = buf;
  8559. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8560. return -1;
  8561. }
  8562. /* The second word is the status as a number */
  8563. tmp = buf;
  8564. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8565. return -1;
  8566. }
  8567. l = strtol(tmp, &tmp2, 10);
  8568. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8569. /* Everything else but a 3 digit code is invalid */
  8570. return -1;
  8571. }
  8572. ri->status_code = (int)l;
  8573. /* The rest of the line is the status text */
  8574. ri->status_text = buf;
  8575. /* Find end of status text */
  8576. /* isgraph or isspace = isprint */
  8577. while (isprint(*buf)) {
  8578. buf++;
  8579. }
  8580. if ((*buf != '\r') && (*buf != '\n')) {
  8581. return -1;
  8582. }
  8583. /* Terminate string and forward buf to next line */
  8584. do {
  8585. *buf = 0;
  8586. buf++;
  8587. } while ((*buf) && isspace(*buf));
  8588. /* Parse all HTTP headers */
  8589. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8590. if (ri->num_headers < 0) {
  8591. /* Error while parsing headers */
  8592. return -1;
  8593. }
  8594. return response_length + init_skip;
  8595. }
  8596. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8597. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8598. * buffer (which marks the end of HTTP request). Buffer buf may already
  8599. * have some data. The length of the data is stored in nread.
  8600. * Upon every read operation, increase nread by the number of bytes read. */
  8601. static int
  8602. read_message(FILE *fp,
  8603. struct mg_connection *conn,
  8604. char *buf,
  8605. int bufsiz,
  8606. int *nread)
  8607. {
  8608. int request_len, n = 0;
  8609. struct timespec last_action_time;
  8610. double request_timeout;
  8611. if (!conn) {
  8612. return 0;
  8613. }
  8614. memset(&last_action_time, 0, sizeof(last_action_time));
  8615. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8616. /* value of request_timeout is in seconds, config in milliseconds */
  8617. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8618. } else {
  8619. request_timeout = -1.0;
  8620. }
  8621. if (conn->handled_requests > 0) {
  8622. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8623. request_timeout =
  8624. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8625. }
  8626. }
  8627. request_len = get_http_header_len(buf, *nread);
  8628. /* first time reading from this connection */
  8629. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8630. while (request_len == 0) {
  8631. /* Full request not yet received */
  8632. if (conn->phys_ctx->stop_flag != 0) {
  8633. /* Server is to be stopped. */
  8634. return -1;
  8635. }
  8636. if (*nread >= bufsiz) {
  8637. /* Request too long */
  8638. return -2;
  8639. }
  8640. n = pull_inner(
  8641. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8642. if (n == -2) {
  8643. /* Receive error */
  8644. return -1;
  8645. }
  8646. if (n > 0) {
  8647. *nread += n;
  8648. request_len = get_http_header_len(buf, *nread);
  8649. } else {
  8650. request_len = 0;
  8651. }
  8652. if ((request_len == 0) && (request_timeout >= 0)) {
  8653. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8654. > request_timeout) {
  8655. /* Timeout */
  8656. return -1;
  8657. }
  8658. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8659. }
  8660. }
  8661. return request_len;
  8662. }
  8663. #if !defined(NO_CGI) || !defined(NO_FILES)
  8664. static int
  8665. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8666. {
  8667. const char *expect, *body;
  8668. char buf[MG_BUF_LEN];
  8669. int to_read, nread, success = 0;
  8670. int64_t buffered_len;
  8671. double timeout = -1.0;
  8672. if (!conn) {
  8673. return 0;
  8674. }
  8675. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8676. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8677. }
  8678. expect = mg_get_header(conn, "Expect");
  8679. DEBUG_ASSERT(fp != NULL);
  8680. if (!fp) {
  8681. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8682. return 0;
  8683. }
  8684. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8685. /* Content length is not specified by the client. */
  8686. mg_send_http_error(conn,
  8687. 411,
  8688. "%s",
  8689. "Error: Client did not specify content length");
  8690. } else if ((expect != NULL)
  8691. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8692. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8693. */
  8694. mg_send_http_error(conn,
  8695. 417,
  8696. "Error: Can not fulfill expectation %s",
  8697. expect);
  8698. } else {
  8699. if (expect != NULL) {
  8700. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8701. conn->status_code = 100;
  8702. } else {
  8703. conn->status_code = 200;
  8704. }
  8705. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8706. - conn->consumed_content;
  8707. DEBUG_ASSERT(buffered_len >= 0);
  8708. DEBUG_ASSERT(conn->consumed_content == 0);
  8709. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8710. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8711. return 0;
  8712. }
  8713. if (buffered_len > 0) {
  8714. if ((int64_t)buffered_len > conn->content_len) {
  8715. buffered_len = (int)conn->content_len;
  8716. }
  8717. body = conn->buf + conn->request_len + conn->consumed_content;
  8718. push_all(
  8719. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8720. conn->consumed_content += buffered_len;
  8721. }
  8722. nread = 0;
  8723. while (conn->consumed_content < conn->content_len) {
  8724. to_read = sizeof(buf);
  8725. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8726. to_read = (int)(conn->content_len - conn->consumed_content);
  8727. }
  8728. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8729. if (nread == -2) {
  8730. /* error */
  8731. break;
  8732. }
  8733. if (nread > 0) {
  8734. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  8735. != nread) {
  8736. break;
  8737. }
  8738. }
  8739. conn->consumed_content += nread;
  8740. }
  8741. if (conn->consumed_content == conn->content_len) {
  8742. success = (nread >= 0);
  8743. }
  8744. /* Each error code path in this function must send an error */
  8745. if (!success) {
  8746. /* NOTE: Maybe some data has already been sent. */
  8747. /* TODO (low): If some data has been sent, a correct error
  8748. * reply can no longer be sent, so just close the connection */
  8749. mg_send_http_error(conn, 500, "%s", "");
  8750. }
  8751. }
  8752. return success;
  8753. }
  8754. #endif
  8755. #if !defined(NO_CGI)
  8756. /* This structure helps to create an environment for the spawned CGI
  8757. * program.
  8758. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8759. * last element must be NULL.
  8760. * However, on Windows there is a requirement that all these
  8761. * VARIABLE=VALUE\0
  8762. * strings must reside in a contiguous buffer. The end of the buffer is
  8763. * marked by two '\0' characters.
  8764. * We satisfy both worlds: we create an envp array (which is vars), all
  8765. * entries are actually pointers inside buf. */
  8766. struct cgi_environment {
  8767. struct mg_connection *conn;
  8768. /* Data block */
  8769. char *buf; /* Environment buffer */
  8770. size_t buflen; /* Space available in buf */
  8771. size_t bufused; /* Space taken in buf */
  8772. /* Index block */
  8773. char **var; /* char **envp */
  8774. size_t varlen; /* Number of variables available in var */
  8775. size_t varused; /* Number of variables stored in var */
  8776. };
  8777. static void addenv(struct cgi_environment *env,
  8778. PRINTF_FORMAT_STRING(const char *fmt),
  8779. ...) PRINTF_ARGS(2, 3);
  8780. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8781. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8782. static void
  8783. addenv(struct cgi_environment *env, const char *fmt, ...)
  8784. {
  8785. size_t n, space;
  8786. int truncated = 0;
  8787. char *added;
  8788. va_list ap;
  8789. /* Calculate how much space is left in the buffer */
  8790. space = (env->buflen - env->bufused);
  8791. /* Calculate an estimate for the required space */
  8792. n = strlen(fmt) + 2 + 128;
  8793. do {
  8794. if (space <= n) {
  8795. /* Allocate new buffer */
  8796. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  8797. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  8798. if (!added) {
  8799. /* Out of memory */
  8800. mg_cry_internal(
  8801. env->conn,
  8802. "%s: Cannot allocate memory for CGI variable [%s]",
  8803. __func__,
  8804. fmt);
  8805. return;
  8806. }
  8807. env->buf = added;
  8808. env->buflen = n;
  8809. space = (env->buflen - env->bufused);
  8810. }
  8811. /* Make a pointer to the free space int the buffer */
  8812. added = env->buf + env->bufused;
  8813. /* Copy VARIABLE=VALUE\0 string into the free space */
  8814. va_start(ap, fmt);
  8815. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  8816. va_end(ap);
  8817. /* Do not add truncated strings to the environment */
  8818. if (truncated) {
  8819. /* Reallocate the buffer */
  8820. space = 0;
  8821. n = 1;
  8822. }
  8823. } while (truncated);
  8824. /* Calculate number of bytes added to the environment */
  8825. n = strlen(added) + 1;
  8826. env->bufused += n;
  8827. /* Now update the variable index */
  8828. space = (env->varlen - env->varused);
  8829. if (space < 2) {
  8830. mg_cry_internal(env->conn,
  8831. "%s: Cannot register CGI variable [%s]",
  8832. __func__,
  8833. fmt);
  8834. return;
  8835. }
  8836. /* Append a pointer to the added string into the envp array */
  8837. env->var[env->varused] = added;
  8838. env->varused++;
  8839. }
  8840. /* Return 0 on success, non-zero if an error occurs. */
  8841. static int
  8842. prepare_cgi_environment(struct mg_connection *conn,
  8843. const char *prog,
  8844. struct cgi_environment *env)
  8845. {
  8846. const char *s;
  8847. struct vec var_vec;
  8848. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8849. int i, truncated, uri_len;
  8850. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8851. return -1;
  8852. }
  8853. env->conn = conn;
  8854. env->buflen = CGI_ENVIRONMENT_SIZE;
  8855. env->bufused = 0;
  8856. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  8857. if (env->buf == NULL) {
  8858. mg_cry_internal(conn,
  8859. "%s: Not enough memory for environmental buffer",
  8860. __func__);
  8861. return -1;
  8862. }
  8863. env->varlen = MAX_CGI_ENVIR_VARS;
  8864. env->varused = 0;
  8865. env->var =
  8866. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  8867. if (env->var == NULL) {
  8868. mg_cry_internal(conn,
  8869. "%s: Not enough memory for environmental variables",
  8870. __func__);
  8871. mg_free(env->buf);
  8872. return -1;
  8873. }
  8874. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  8875. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8876. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8877. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  8878. /* Prepare the environment block */
  8879. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8880. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8881. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8882. #if defined(USE_IPV6)
  8883. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8884. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8885. } else
  8886. #endif
  8887. {
  8888. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8889. }
  8890. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8891. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8892. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8893. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8894. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8895. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8896. /* SCRIPT_NAME */
  8897. uri_len = (int)strlen(conn->request_info.local_uri);
  8898. if (conn->path_info == NULL) {
  8899. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8900. /* URI: /path_to_script/script.cgi */
  8901. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8902. } else {
  8903. /* URI: /path_to_script/ ... using index.cgi */
  8904. const char *index_file = strrchr(prog, '/');
  8905. if (index_file) {
  8906. addenv(env,
  8907. "SCRIPT_NAME=%s%s",
  8908. conn->request_info.local_uri,
  8909. index_file + 1);
  8910. }
  8911. }
  8912. } else {
  8913. /* URI: /path_to_script/script.cgi/path_info */
  8914. addenv(env,
  8915. "SCRIPT_NAME=%.*s",
  8916. uri_len - (int)strlen(conn->path_info),
  8917. conn->request_info.local_uri);
  8918. }
  8919. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8920. if (conn->path_info == NULL) {
  8921. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8922. } else {
  8923. addenv(env,
  8924. "PATH_TRANSLATED=%s%s",
  8925. conn->dom_ctx->config[DOCUMENT_ROOT],
  8926. conn->path_info);
  8927. }
  8928. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8929. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8930. addenv(env, "CONTENT_TYPE=%s", s);
  8931. }
  8932. if (conn->request_info.query_string != NULL) {
  8933. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8934. }
  8935. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8936. addenv(env, "CONTENT_LENGTH=%s", s);
  8937. }
  8938. if ((s = getenv("PATH")) != NULL) {
  8939. addenv(env, "PATH=%s", s);
  8940. }
  8941. if (conn->path_info != NULL) {
  8942. addenv(env, "PATH_INFO=%s", conn->path_info);
  8943. }
  8944. if (conn->status_code > 0) {
  8945. /* CGI error handler should show the status code */
  8946. addenv(env, "STATUS=%d", conn->status_code);
  8947. }
  8948. #if defined(_WIN32)
  8949. if ((s = getenv("COMSPEC")) != NULL) {
  8950. addenv(env, "COMSPEC=%s", s);
  8951. }
  8952. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8953. addenv(env, "SYSTEMROOT=%s", s);
  8954. }
  8955. if ((s = getenv("SystemDrive")) != NULL) {
  8956. addenv(env, "SystemDrive=%s", s);
  8957. }
  8958. if ((s = getenv("ProgramFiles")) != NULL) {
  8959. addenv(env, "ProgramFiles=%s", s);
  8960. }
  8961. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8962. addenv(env, "ProgramFiles(x86)=%s", s);
  8963. }
  8964. #else
  8965. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8966. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8967. }
  8968. #endif /* _WIN32 */
  8969. if ((s = getenv("PERLLIB")) != NULL) {
  8970. addenv(env, "PERLLIB=%s", s);
  8971. }
  8972. if (conn->request_info.remote_user != NULL) {
  8973. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8974. addenv(env, "%s", "AUTH_TYPE=Digest");
  8975. }
  8976. /* Add all headers as HTTP_* variables */
  8977. for (i = 0; i < conn->request_info.num_headers; i++) {
  8978. (void)mg_snprintf(conn,
  8979. &truncated,
  8980. http_var_name,
  8981. sizeof(http_var_name),
  8982. "HTTP_%s",
  8983. conn->request_info.http_headers[i].name);
  8984. if (truncated) {
  8985. mg_cry_internal(conn,
  8986. "%s: HTTP header variable too long [%s]",
  8987. __func__,
  8988. conn->request_info.http_headers[i].name);
  8989. continue;
  8990. }
  8991. /* Convert variable name into uppercase, and change - to _ */
  8992. for (p = http_var_name; *p != '\0'; p++) {
  8993. if (*p == '-') {
  8994. *p = '_';
  8995. }
  8996. *p = (char)toupper(*(unsigned char *)p);
  8997. }
  8998. addenv(env,
  8999. "%s=%s",
  9000. http_var_name,
  9001. conn->request_info.http_headers[i].value);
  9002. }
  9003. /* Add user-specified variables */
  9004. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9005. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9006. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9007. }
  9008. env->var[env->varused] = NULL;
  9009. env->buf[env->bufused] = '\0';
  9010. return 0;
  9011. }
  9012. static void
  9013. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9014. {
  9015. char *buf;
  9016. size_t buflen;
  9017. int headers_len, data_len, i, truncated;
  9018. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9019. const char *status, *status_text, *connection_state;
  9020. char *pbuf, dir[PATH_MAX], *p;
  9021. struct mg_request_info ri;
  9022. struct cgi_environment blk;
  9023. FILE *in = NULL, *out = NULL, *err = NULL;
  9024. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9025. pid_t pid = (pid_t)-1;
  9026. if (conn == NULL) {
  9027. return;
  9028. }
  9029. buf = NULL;
  9030. buflen = conn->phys_ctx->max_request_size;
  9031. i = prepare_cgi_environment(conn, prog, &blk);
  9032. if (i != 0) {
  9033. blk.buf = NULL;
  9034. blk.var = NULL;
  9035. goto done;
  9036. }
  9037. /* CGI must be executed in its own directory. 'dir' must point to the
  9038. * directory containing executable program, 'p' must point to the
  9039. * executable program name relative to 'dir'. */
  9040. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9041. if (truncated) {
  9042. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9043. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9044. goto done;
  9045. }
  9046. if ((p = strrchr(dir, '/')) != NULL) {
  9047. *p++ = '\0';
  9048. } else {
  9049. dir[0] = '.';
  9050. dir[1] = '\0';
  9051. p = (char *)prog;
  9052. }
  9053. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9054. status = strerror(ERRNO);
  9055. mg_cry_internal(
  9056. conn,
  9057. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9058. prog,
  9059. status);
  9060. mg_send_http_error(conn,
  9061. 500,
  9062. "Error: Cannot create CGI pipe: %s",
  9063. status);
  9064. goto done;
  9065. }
  9066. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9067. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9068. if (pid == (pid_t)-1) {
  9069. status = strerror(ERRNO);
  9070. mg_cry_internal(
  9071. conn,
  9072. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9073. prog,
  9074. status);
  9075. mg_send_http_error(conn,
  9076. 500,
  9077. "Error: Cannot spawn CGI process [%s]: %s",
  9078. prog,
  9079. status);
  9080. goto done;
  9081. }
  9082. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  9083. */
  9084. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  9085. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  9086. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  9087. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  9088. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  9089. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  9090. /* Parent closes only one side of the pipes.
  9091. * If we don't mark them as closed, close() attempt before
  9092. * return from this function throws an exception on Windows.
  9093. * Windows does not like when closed descriptor is closed again. */
  9094. (void)close(fdin[0]);
  9095. (void)close(fdout[1]);
  9096. (void)close(fderr[1]);
  9097. fdin[0] = fdout[1] = fderr[1] = -1;
  9098. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  9099. status = strerror(ERRNO);
  9100. mg_cry_internal(conn,
  9101. "Error: CGI program \"%s\": Can not open stdin: %s",
  9102. prog,
  9103. status);
  9104. mg_send_http_error(conn,
  9105. 500,
  9106. "Error: CGI can not open fdin\nfopen: %s",
  9107. status);
  9108. goto done;
  9109. }
  9110. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  9111. status = strerror(ERRNO);
  9112. mg_cry_internal(conn,
  9113. "Error: CGI program \"%s\": Can not open stdout: %s",
  9114. prog,
  9115. status);
  9116. mg_send_http_error(conn,
  9117. 500,
  9118. "Error: CGI can not open fdout\nfopen: %s",
  9119. status);
  9120. goto done;
  9121. }
  9122. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  9123. status = strerror(ERRNO);
  9124. mg_cry_internal(conn,
  9125. "Error: CGI program \"%s\": Can not open stderr: %s",
  9126. prog,
  9127. status);
  9128. mg_send_http_error(conn,
  9129. 500,
  9130. "Error: CGI can not open fderr\nfopen: %s",
  9131. status);
  9132. goto done;
  9133. }
  9134. setbuf(in, NULL);
  9135. setbuf(out, NULL);
  9136. setbuf(err, NULL);
  9137. fout.access.fp = out;
  9138. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  9139. DEBUG_TRACE("CGI: send body data (%lli)\n",
  9140. (signed long long)conn->request_info.content_length);
  9141. /* This is a POST/PUT request, or another request with body data. */
  9142. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9143. /* Error sending the body data */
  9144. mg_cry_internal(
  9145. conn,
  9146. "Error: CGI program \"%s\": Forward body data failed",
  9147. prog);
  9148. goto done;
  9149. }
  9150. }
  9151. /* Close so child gets an EOF. */
  9152. fclose(in);
  9153. in = NULL;
  9154. fdin[1] = -1;
  9155. /* Now read CGI reply into a buffer. We need to set correct
  9156. * status code, thus we need to see all HTTP headers first.
  9157. * Do not send anything back to client, until we buffer in all
  9158. * HTTP headers. */
  9159. data_len = 0;
  9160. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9161. if (buf == NULL) {
  9162. mg_send_http_error(conn,
  9163. 500,
  9164. "Error: Not enough memory for CGI buffer (%u bytes)",
  9165. (unsigned int)buflen);
  9166. mg_cry_internal(
  9167. conn,
  9168. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9169. "bytes)",
  9170. prog,
  9171. (unsigned int)buflen);
  9172. goto done;
  9173. }
  9174. DEBUG_TRACE("CGI: %s", "wait for response");
  9175. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9176. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9177. if (headers_len <= 0) {
  9178. /* Could not parse the CGI response. Check if some error message on
  9179. * stderr. */
  9180. i = pull_all(err, conn, buf, (int)buflen);
  9181. if (i > 0) {
  9182. /* CGI program explicitly sent an error */
  9183. /* Write the error message to the internal log */
  9184. mg_cry_internal(conn,
  9185. "Error: CGI program \"%s\" sent error "
  9186. "message: [%.*s]",
  9187. prog,
  9188. i,
  9189. buf);
  9190. /* Don't send the error message back to the client */
  9191. mg_send_http_error(conn,
  9192. 500,
  9193. "Error: CGI program \"%s\" failed.",
  9194. prog);
  9195. } else {
  9196. /* CGI program did not explicitly send an error, but a broken
  9197. * respon header */
  9198. mg_cry_internal(conn,
  9199. "Error: CGI program sent malformed or too big "
  9200. "(>%u bytes) HTTP headers: [%.*s]",
  9201. (unsigned)buflen,
  9202. data_len,
  9203. buf);
  9204. mg_send_http_error(conn,
  9205. 500,
  9206. "Error: CGI program sent malformed or too big "
  9207. "(>%u bytes) HTTP headers: [%.*s]",
  9208. (unsigned)buflen,
  9209. data_len,
  9210. buf);
  9211. }
  9212. /* in both cases, abort processing CGI */
  9213. goto done;
  9214. }
  9215. pbuf = buf;
  9216. buf[headers_len - 1] = '\0';
  9217. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9218. /* Make up and send the status line */
  9219. status_text = "OK";
  9220. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9221. != NULL) {
  9222. conn->status_code = atoi(status);
  9223. status_text = status;
  9224. while (isdigit(*(const unsigned char *)status_text)
  9225. || *status_text == ' ') {
  9226. status_text++;
  9227. }
  9228. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9229. != NULL) {
  9230. conn->status_code = 302;
  9231. } else {
  9232. conn->status_code = 200;
  9233. }
  9234. connection_state =
  9235. get_header(ri.http_headers, ri.num_headers, "Connection");
  9236. if (!header_has_option(connection_state, "keep-alive")) {
  9237. conn->must_close = 1;
  9238. }
  9239. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9240. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9241. /* Send headers */
  9242. for (i = 0; i < ri.num_headers; i++) {
  9243. mg_printf(conn,
  9244. "%s: %s\r\n",
  9245. ri.http_headers[i].name,
  9246. ri.http_headers[i].value);
  9247. }
  9248. mg_write(conn, "\r\n", 2);
  9249. /* Send chunk of data that may have been read after the headers */
  9250. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9251. /* Read the rest of CGI output and send to the client */
  9252. DEBUG_TRACE("CGI: %s", "forward all data");
  9253. send_file_data(conn, &fout, 0, INT64_MAX);
  9254. DEBUG_TRACE("CGI: %s", "all data sent");
  9255. done:
  9256. mg_free(blk.var);
  9257. mg_free(blk.buf);
  9258. if (pid != (pid_t)-1) {
  9259. kill(pid, SIGKILL);
  9260. #if !defined(_WIN32)
  9261. {
  9262. int st;
  9263. while (waitpid(pid, &st, 0) != -1)
  9264. ; /* clean zombies */
  9265. }
  9266. #endif
  9267. }
  9268. if (fdin[0] != -1) {
  9269. close(fdin[0]);
  9270. }
  9271. if (fdout[1] != -1) {
  9272. close(fdout[1]);
  9273. }
  9274. if (in != NULL) {
  9275. fclose(in);
  9276. } else if (fdin[1] != -1) {
  9277. close(fdin[1]);
  9278. }
  9279. if (out != NULL) {
  9280. fclose(out);
  9281. } else if (fdout[0] != -1) {
  9282. close(fdout[0]);
  9283. }
  9284. if (err != NULL) {
  9285. fclose(err);
  9286. } else if (fderr[0] != -1) {
  9287. close(fderr[0]);
  9288. }
  9289. if (buf != NULL) {
  9290. mg_free(buf);
  9291. }
  9292. }
  9293. #endif /* !NO_CGI */
  9294. #if !defined(NO_FILES)
  9295. static void
  9296. mkcol(struct mg_connection *conn, const char *path)
  9297. {
  9298. int rc, body_len;
  9299. struct de de;
  9300. char date[64];
  9301. time_t curtime = time(NULL);
  9302. if (conn == NULL) {
  9303. return;
  9304. }
  9305. /* TODO (mid): Check the mg_send_http_error situations in this function
  9306. */
  9307. memset(&de.file, 0, sizeof(de.file));
  9308. if (!mg_stat(conn, path, &de.file)) {
  9309. mg_cry_internal(conn,
  9310. "%s: mg_stat(%s) failed: %s",
  9311. __func__,
  9312. path,
  9313. strerror(ERRNO));
  9314. }
  9315. if (de.file.last_modified) {
  9316. /* TODO (mid): This check does not seem to make any sense ! */
  9317. /* TODO (mid): Add a webdav unit test first, before changing
  9318. * anything here. */
  9319. mg_send_http_error(
  9320. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9321. return;
  9322. }
  9323. body_len = conn->data_len - conn->request_len;
  9324. if (body_len > 0) {
  9325. mg_send_http_error(
  9326. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9327. return;
  9328. }
  9329. rc = mg_mkdir(conn, path, 0755);
  9330. if (rc == 0) {
  9331. conn->status_code = 201;
  9332. gmt_time_string(date, sizeof(date), &curtime);
  9333. mg_printf(conn,
  9334. "HTTP/1.1 %d Created\r\n"
  9335. "Date: %s\r\n",
  9336. conn->status_code,
  9337. date);
  9338. send_static_cache_header(conn);
  9339. send_additional_header(conn);
  9340. mg_printf(conn,
  9341. "Content-Length: 0\r\n"
  9342. "Connection: %s\r\n\r\n",
  9343. suggest_connection_header(conn));
  9344. } else {
  9345. if (errno == EEXIST) {
  9346. mg_send_http_error(
  9347. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9348. } else if (errno == EACCES) {
  9349. mg_send_http_error(
  9350. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9351. } else if (errno == ENOENT) {
  9352. mg_send_http_error(
  9353. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9354. } else {
  9355. mg_send_http_error(
  9356. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9357. }
  9358. }
  9359. }
  9360. static void
  9361. put_file(struct mg_connection *conn, const char *path)
  9362. {
  9363. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9364. const char *range;
  9365. int64_t r1, r2;
  9366. int rc;
  9367. char date[64];
  9368. time_t curtime = time(NULL);
  9369. if (conn == NULL) {
  9370. return;
  9371. }
  9372. if (mg_stat(conn, path, &file.stat)) {
  9373. /* File already exists */
  9374. conn->status_code = 200;
  9375. if (file.stat.is_directory) {
  9376. /* This is an already existing directory,
  9377. * so there is nothing to do for the server. */
  9378. rc = 0;
  9379. } else {
  9380. /* File exists and is not a directory. */
  9381. /* Can it be replaced? */
  9382. #if defined(MG_USE_OPEN_FILE)
  9383. if (file.access.membuf != NULL) {
  9384. /* This is an "in-memory" file, that can not be replaced */
  9385. mg_send_http_error(conn,
  9386. 405,
  9387. "Error: Put not possible\nReplacing %s "
  9388. "is not supported",
  9389. path);
  9390. return;
  9391. }
  9392. #endif
  9393. /* Check if the server may write this file */
  9394. if (access(path, W_OK) == 0) {
  9395. /* Access granted */
  9396. conn->status_code = 200;
  9397. rc = 1;
  9398. } else {
  9399. mg_send_http_error(
  9400. conn,
  9401. 403,
  9402. "Error: Put not possible\nReplacing %s is not allowed",
  9403. path);
  9404. return;
  9405. }
  9406. }
  9407. } else {
  9408. /* File should be created */
  9409. conn->status_code = 201;
  9410. rc = put_dir(conn, path);
  9411. }
  9412. if (rc == 0) {
  9413. /* put_dir returns 0 if path is a directory */
  9414. gmt_time_string(date, sizeof(date), &curtime);
  9415. mg_printf(conn,
  9416. "HTTP/1.1 %d %s\r\n",
  9417. conn->status_code,
  9418. mg_get_response_code_text(NULL, conn->status_code));
  9419. send_no_cache_header(conn);
  9420. send_additional_header(conn);
  9421. mg_printf(conn,
  9422. "Date: %s\r\n"
  9423. "Content-Length: 0\r\n"
  9424. "Connection: %s\r\n\r\n",
  9425. date,
  9426. suggest_connection_header(conn));
  9427. /* Request to create a directory has been fulfilled successfully.
  9428. * No need to put a file. */
  9429. return;
  9430. }
  9431. if (rc == -1) {
  9432. /* put_dir returns -1 if the path is too long */
  9433. mg_send_http_error(conn,
  9434. 414,
  9435. "Error: Path too long\nput_dir(%s): %s",
  9436. path,
  9437. strerror(ERRNO));
  9438. return;
  9439. }
  9440. if (rc == -2) {
  9441. /* put_dir returns -2 if the directory can not be created */
  9442. mg_send_http_error(conn,
  9443. 500,
  9444. "Error: Can not create directory\nput_dir(%s): %s",
  9445. path,
  9446. strerror(ERRNO));
  9447. return;
  9448. }
  9449. /* A file should be created or overwritten. */
  9450. /* Currently CivetWeb does not nead read+write access. */
  9451. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9452. || file.access.fp == NULL) {
  9453. (void)mg_fclose(&file.access);
  9454. mg_send_http_error(conn,
  9455. 500,
  9456. "Error: Can not create file\nfopen(%s): %s",
  9457. path,
  9458. strerror(ERRNO));
  9459. return;
  9460. }
  9461. fclose_on_exec(&file.access, conn);
  9462. range = mg_get_header(conn, "Content-Range");
  9463. r1 = r2 = 0;
  9464. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9465. conn->status_code = 206; /* Partial content */
  9466. fseeko(file.access.fp, r1, SEEK_SET);
  9467. }
  9468. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9469. /* forward_body_data failed.
  9470. * The error code has already been sent to the client,
  9471. * and conn->status_code is already set. */
  9472. (void)mg_fclose(&file.access);
  9473. return;
  9474. }
  9475. if (mg_fclose(&file.access) != 0) {
  9476. /* fclose failed. This might have different reasons, but a likely
  9477. * one is "no space on disk", http 507. */
  9478. conn->status_code = 507;
  9479. }
  9480. gmt_time_string(date, sizeof(date), &curtime);
  9481. mg_printf(conn,
  9482. "HTTP/1.1 %d %s\r\n",
  9483. conn->status_code,
  9484. mg_get_response_code_text(NULL, conn->status_code));
  9485. send_no_cache_header(conn);
  9486. send_additional_header(conn);
  9487. mg_printf(conn,
  9488. "Date: %s\r\n"
  9489. "Content-Length: 0\r\n"
  9490. "Connection: %s\r\n\r\n",
  9491. date,
  9492. suggest_connection_header(conn));
  9493. }
  9494. static void
  9495. delete_file(struct mg_connection *conn, const char *path)
  9496. {
  9497. struct de de;
  9498. memset(&de.file, 0, sizeof(de.file));
  9499. if (!mg_stat(conn, path, &de.file)) {
  9500. /* mg_stat returns 0 if the file does not exist */
  9501. mg_send_http_error(conn,
  9502. 404,
  9503. "Error: Cannot delete file\nFile %s not found",
  9504. path);
  9505. return;
  9506. }
  9507. #if 0 /* Ignore if a file in memory is inside a folder */
  9508. if (de.access.membuf != NULL) {
  9509. /* the file is cached in memory */
  9510. mg_send_http_error(
  9511. conn,
  9512. 405,
  9513. "Error: Delete not possible\nDeleting %s is not supported",
  9514. path);
  9515. return;
  9516. }
  9517. #endif
  9518. if (de.file.is_directory) {
  9519. if (remove_directory(conn, path)) {
  9520. /* Delete is successful: Return 204 without content. */
  9521. mg_send_http_error(conn, 204, "%s", "");
  9522. } else {
  9523. /* Delete is not successful: Return 500 (Server error). */
  9524. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9525. }
  9526. return;
  9527. }
  9528. /* This is an existing file (not a directory).
  9529. * Check if write permission is granted. */
  9530. if (access(path, W_OK) != 0) {
  9531. /* File is read only */
  9532. mg_send_http_error(
  9533. conn,
  9534. 403,
  9535. "Error: Delete not possible\nDeleting %s is not allowed",
  9536. path);
  9537. return;
  9538. }
  9539. /* Try to delete it. */
  9540. if (mg_remove(conn, path) == 0) {
  9541. /* Delete was successful: Return 204 without content. */
  9542. mg_send_http_error(conn, 204, "%s", "");
  9543. } else {
  9544. /* Delete not successful (file locked). */
  9545. mg_send_http_error(conn,
  9546. 423,
  9547. "Error: Cannot delete file\nremove(%s): %s",
  9548. path,
  9549. strerror(ERRNO));
  9550. }
  9551. }
  9552. #endif /* !NO_FILES */
  9553. static void
  9554. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9555. static void
  9556. do_ssi_include(struct mg_connection *conn,
  9557. const char *ssi,
  9558. char *tag,
  9559. int include_level)
  9560. {
  9561. char file_name[MG_BUF_LEN], path[512], *p;
  9562. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9563. size_t len;
  9564. int truncated = 0;
  9565. if (conn == NULL) {
  9566. return;
  9567. }
  9568. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9569. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9570. * always < MG_BUF_LEN. */
  9571. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9572. /* File name is relative to the webserver root */
  9573. file_name[511] = 0;
  9574. (void)mg_snprintf(conn,
  9575. &truncated,
  9576. path,
  9577. sizeof(path),
  9578. "%s/%s",
  9579. conn->dom_ctx->config[DOCUMENT_ROOT],
  9580. file_name);
  9581. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9582. /* File name is relative to the webserver working directory
  9583. * or it is absolute system path */
  9584. file_name[511] = 0;
  9585. (void)
  9586. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9587. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9588. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9589. /* File name is relative to the currect document */
  9590. file_name[511] = 0;
  9591. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9592. if (!truncated) {
  9593. if ((p = strrchr(path, '/')) != NULL) {
  9594. p[1] = '\0';
  9595. }
  9596. len = strlen(path);
  9597. (void)mg_snprintf(conn,
  9598. &truncated,
  9599. path + len,
  9600. sizeof(path) - len,
  9601. "%s",
  9602. file_name);
  9603. }
  9604. } else {
  9605. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9606. return;
  9607. }
  9608. if (truncated) {
  9609. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9610. return;
  9611. }
  9612. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9613. mg_cry_internal(conn,
  9614. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9615. tag,
  9616. path,
  9617. strerror(ERRNO));
  9618. } else {
  9619. fclose_on_exec(&file.access, conn);
  9620. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9621. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9622. path) > 0) {
  9623. send_ssi_file(conn, path, &file, include_level + 1);
  9624. } else {
  9625. send_file_data(conn, &file, 0, INT64_MAX);
  9626. }
  9627. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9628. }
  9629. }
  9630. #if !defined(NO_POPEN)
  9631. static void
  9632. do_ssi_exec(struct mg_connection *conn, char *tag)
  9633. {
  9634. char cmd[1024] = "";
  9635. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9636. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9637. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  9638. } else {
  9639. cmd[1023] = 0;
  9640. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9641. mg_cry_internal(conn,
  9642. "Cannot SSI #exec: [%s]: %s",
  9643. cmd,
  9644. strerror(ERRNO));
  9645. } else {
  9646. send_file_data(conn, &file, 0, INT64_MAX);
  9647. pclose(file.access.fp);
  9648. }
  9649. }
  9650. }
  9651. #endif /* !NO_POPEN */
  9652. static int
  9653. mg_fgetc(struct mg_file *filep, int offset)
  9654. {
  9655. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  9656. if (filep == NULL) {
  9657. return EOF;
  9658. }
  9659. #if defined(MG_USE_OPEN_FILE)
  9660. if ((filep->access.membuf != NULL) && (offset >= 0)
  9661. && (((unsigned int)(offset)) < filep->stat.size)) {
  9662. return ((const unsigned char *)filep->access.membuf)[offset];
  9663. } else /* else block below */
  9664. #endif
  9665. if (filep->access.fp != NULL) {
  9666. return fgetc(filep->access.fp);
  9667. } else {
  9668. return EOF;
  9669. }
  9670. }
  9671. static void
  9672. send_ssi_file(struct mg_connection *conn,
  9673. const char *path,
  9674. struct mg_file *filep,
  9675. int include_level)
  9676. {
  9677. char buf[MG_BUF_LEN];
  9678. int ch, offset, len, in_tag, in_ssi_tag;
  9679. if (include_level > 10) {
  9680. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  9681. return;
  9682. }
  9683. in_tag = in_ssi_tag = len = offset = 0;
  9684. /* Read file, byte by byte, and look for SSI include tags */
  9685. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9686. if (in_tag) {
  9687. /* We are in a tag, either SSI tag or html tag */
  9688. if (ch == '>') {
  9689. /* Tag is closing */
  9690. buf[len++] = '>';
  9691. if (in_ssi_tag) {
  9692. /* Handle SSI tag */
  9693. buf[len] = 0;
  9694. if (!memcmp(buf + 5, "include", 7)) {
  9695. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9696. #if !defined(NO_POPEN)
  9697. } else if (!memcmp(buf + 5, "exec", 4)) {
  9698. do_ssi_exec(conn, buf + 9);
  9699. #endif /* !NO_POPEN */
  9700. } else {
  9701. mg_cry_internal(conn,
  9702. "%s: unknown SSI "
  9703. "command: \"%s\"",
  9704. path,
  9705. buf);
  9706. }
  9707. len = 0;
  9708. in_ssi_tag = in_tag = 0;
  9709. } else {
  9710. /* Not an SSI tag */
  9711. /* Flush buffer */
  9712. (void)mg_write(conn, buf, (size_t)len);
  9713. len = 0;
  9714. in_tag = 0;
  9715. }
  9716. } else {
  9717. /* Tag is still open */
  9718. buf[len++] = (char)(ch & 0xff);
  9719. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9720. /* All SSI tags start with <!--# */
  9721. in_ssi_tag = 1;
  9722. }
  9723. if ((len + 2) > (int)sizeof(buf)) {
  9724. /* Tag to long for buffer */
  9725. mg_cry_internal(conn, "%s: tag is too large", path);
  9726. return;
  9727. }
  9728. }
  9729. } else {
  9730. /* We are not in a tag yet. */
  9731. if (ch == '<') {
  9732. /* Tag is opening */
  9733. in_tag = 1;
  9734. if (len > 0) {
  9735. /* Flush current buffer.
  9736. * Buffer is filled with "len" bytes. */
  9737. (void)mg_write(conn, buf, (size_t)len);
  9738. }
  9739. /* Store the < */
  9740. len = 1;
  9741. buf[0] = '<';
  9742. } else {
  9743. /* No Tag */
  9744. /* Add data to buffer */
  9745. buf[len++] = (char)(ch & 0xff);
  9746. /* Flush if buffer is full */
  9747. if (len == (int)sizeof(buf)) {
  9748. mg_write(conn, buf, (size_t)len);
  9749. len = 0;
  9750. }
  9751. }
  9752. }
  9753. }
  9754. /* Send the rest of buffered data */
  9755. if (len > 0) {
  9756. mg_write(conn, buf, (size_t)len);
  9757. }
  9758. }
  9759. static void
  9760. handle_ssi_file_request(struct mg_connection *conn,
  9761. const char *path,
  9762. struct mg_file *filep)
  9763. {
  9764. char date[64];
  9765. time_t curtime = time(NULL);
  9766. const char *cors1, *cors2, *cors3;
  9767. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  9768. return;
  9769. }
  9770. if (mg_get_header(conn, "Origin")) {
  9771. /* Cross-origin resource sharing (CORS). */
  9772. cors1 = "Access-Control-Allow-Origin: ";
  9773. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9774. cors3 = "\r\n";
  9775. } else {
  9776. cors1 = cors2 = cors3 = "";
  9777. }
  9778. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9779. /* File exists (precondition for calling this function),
  9780. * but can not be opened by the server. */
  9781. mg_send_http_error(conn,
  9782. 500,
  9783. "Error: Cannot read file\nfopen(%s): %s",
  9784. path,
  9785. strerror(ERRNO));
  9786. } else {
  9787. conn->must_close = 1;
  9788. gmt_time_string(date, sizeof(date), &curtime);
  9789. fclose_on_exec(&filep->access, conn);
  9790. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  9791. send_no_cache_header(conn);
  9792. send_additional_header(conn);
  9793. mg_printf(conn,
  9794. "%s%s%s"
  9795. "Date: %s\r\n"
  9796. "Content-Type: text/html\r\n"
  9797. "Connection: %s\r\n\r\n",
  9798. cors1,
  9799. cors2,
  9800. cors3,
  9801. date,
  9802. suggest_connection_header(conn));
  9803. send_ssi_file(conn, path, filep, 0);
  9804. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  9805. }
  9806. }
  9807. #if !defined(NO_FILES)
  9808. static void
  9809. send_options(struct mg_connection *conn)
  9810. {
  9811. char date[64];
  9812. time_t curtime = time(NULL);
  9813. if (!conn) {
  9814. return;
  9815. }
  9816. conn->status_code = 200;
  9817. conn->must_close = 1;
  9818. gmt_time_string(date, sizeof(date), &curtime);
  9819. /* We do not set a "Cache-Control" header here, but leave the default.
  9820. * Since browsers do not send an OPTIONS request, we can not test the
  9821. * effect anyway. */
  9822. mg_printf(conn,
  9823. "HTTP/1.1 200 OK\r\n"
  9824. "Date: %s\r\n"
  9825. "Connection: %s\r\n"
  9826. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  9827. "PROPFIND, MKCOL\r\n"
  9828. "DAV: 1\r\n",
  9829. date,
  9830. suggest_connection_header(conn));
  9831. send_additional_header(conn);
  9832. mg_printf(conn, "\r\n");
  9833. }
  9834. /* Writes PROPFIND properties for a collection element */
  9835. static void
  9836. print_props(struct mg_connection *conn,
  9837. const char *uri,
  9838. struct mg_file_stat *filep)
  9839. {
  9840. char mtime[64];
  9841. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  9842. return;
  9843. }
  9844. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  9845. mg_printf(conn,
  9846. "<d:response>"
  9847. "<d:href>%s</d:href>"
  9848. "<d:propstat>"
  9849. "<d:prop>"
  9850. "<d:resourcetype>%s</d:resourcetype>"
  9851. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  9852. "<d:getlastmodified>%s</d:getlastmodified>"
  9853. "</d:prop>"
  9854. "<d:status>HTTP/1.1 200 OK</d:status>"
  9855. "</d:propstat>"
  9856. "</d:response>\n",
  9857. uri,
  9858. filep->is_directory ? "<d:collection/>" : "",
  9859. filep->size,
  9860. mtime);
  9861. }
  9862. static int
  9863. print_dav_dir_entry(struct de *de, void *data)
  9864. {
  9865. char href[PATH_MAX];
  9866. int truncated;
  9867. struct mg_connection *conn = (struct mg_connection *)data;
  9868. if (!de || !conn) {
  9869. return -1;
  9870. }
  9871. mg_snprintf(conn,
  9872. &truncated,
  9873. href,
  9874. sizeof(href),
  9875. "%s%s",
  9876. conn->request_info.local_uri,
  9877. de->file_name);
  9878. if (!truncated) {
  9879. size_t href_encoded_size;
  9880. char *href_encoded;
  9881. href_encoded_size = PATH_MAX * 3; /* worst case */
  9882. href_encoded = (char *)mg_malloc(href_encoded_size);
  9883. if (href_encoded == NULL) {
  9884. return -1;
  9885. }
  9886. mg_url_encode(href, href_encoded, href_encoded_size);
  9887. print_props(conn, href_encoded, &de->file);
  9888. mg_free(href_encoded);
  9889. }
  9890. return 0;
  9891. }
  9892. static void
  9893. handle_propfind(struct mg_connection *conn,
  9894. const char *path,
  9895. struct mg_file_stat *filep)
  9896. {
  9897. const char *depth = mg_get_header(conn, "Depth");
  9898. char date[64];
  9899. time_t curtime = time(NULL);
  9900. gmt_time_string(date, sizeof(date), &curtime);
  9901. if (!conn || !path || !filep || !conn->dom_ctx) {
  9902. return;
  9903. }
  9904. conn->must_close = 1;
  9905. conn->status_code = 207;
  9906. mg_printf(conn,
  9907. "HTTP/1.1 207 Multi-Status\r\n"
  9908. "Date: %s\r\n",
  9909. date);
  9910. send_static_cache_header(conn);
  9911. send_additional_header(conn);
  9912. mg_printf(conn,
  9913. "Connection: %s\r\n"
  9914. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9915. suggest_connection_header(conn));
  9916. mg_printf(conn,
  9917. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9918. "<d:multistatus xmlns:d='DAV:'>\n");
  9919. /* Print properties for the requested resource itself */
  9920. print_props(conn, conn->request_info.local_uri, filep);
  9921. /* If it is a directory, print directory entries too if Depth is not 0
  9922. */
  9923. if (filep->is_directory
  9924. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9925. "yes")
  9926. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9927. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9928. }
  9929. mg_printf(conn, "%s\n", "</d:multistatus>");
  9930. }
  9931. #endif
  9932. void
  9933. mg_lock_connection(struct mg_connection *conn)
  9934. {
  9935. if (conn) {
  9936. (void)pthread_mutex_lock(&conn->mutex);
  9937. }
  9938. }
  9939. void
  9940. mg_unlock_connection(struct mg_connection *conn)
  9941. {
  9942. if (conn) {
  9943. (void)pthread_mutex_unlock(&conn->mutex);
  9944. }
  9945. }
  9946. void
  9947. mg_lock_context(struct mg_context *ctx)
  9948. {
  9949. if (ctx) {
  9950. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9951. }
  9952. }
  9953. void
  9954. mg_unlock_context(struct mg_context *ctx)
  9955. {
  9956. if (ctx) {
  9957. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9958. }
  9959. }
  9960. #if defined(USE_TIMERS)
  9961. #define TIMER_API static
  9962. #include "timer.inl"
  9963. #endif /* USE_TIMERS */
  9964. #if defined(USE_LUA)
  9965. #include "mod_lua.inl"
  9966. #endif /* USE_LUA */
  9967. #if defined(USE_DUKTAPE)
  9968. #include "mod_duktape.inl"
  9969. #endif /* USE_DUKTAPE */
  9970. #if defined(USE_WEBSOCKET)
  9971. #if !defined(NO_SSL_DL)
  9972. #define SHA_API static
  9973. #include "sha1.inl"
  9974. #endif
  9975. static int
  9976. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9977. {
  9978. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9979. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9980. SHA_CTX sha_ctx;
  9981. int truncated;
  9982. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9983. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9984. if (truncated) {
  9985. conn->must_close = 1;
  9986. return 0;
  9987. }
  9988. DEBUG_TRACE("%s", "Send websocket handshake");
  9989. SHA1_Init(&sha_ctx);
  9990. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9991. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9992. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9993. mg_printf(conn,
  9994. "HTTP/1.1 101 Switching Protocols\r\n"
  9995. "Upgrade: websocket\r\n"
  9996. "Connection: Upgrade\r\n"
  9997. "Sec-WebSocket-Accept: %s\r\n",
  9998. b64_sha);
  9999. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10000. mg_printf(conn,
  10001. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10002. conn->request_info.acceptedWebSocketSubprotocol);
  10003. } else {
  10004. mg_printf(conn, "%s", "\r\n");
  10005. }
  10006. return 1;
  10007. }
  10008. #if !defined(MG_MAX_UNANSWERED_PING)
  10009. /* Configuration of the maximum number of websocket PINGs that might
  10010. * stay unanswered before the connection is considered broken.
  10011. * Note: The name of this define may still change (until it is
  10012. * defined as a compile parameter in a documentation).
  10013. */
  10014. #define MG_MAX_UNANSWERED_PING (5)
  10015. #endif
  10016. static void
  10017. read_websocket(struct mg_connection *conn,
  10018. mg_websocket_data_handler ws_data_handler,
  10019. void *callback_data)
  10020. {
  10021. /* Pointer to the beginning of the portion of the incoming websocket
  10022. * message queue.
  10023. * The original websocket upgrade request is never removed, so the queue
  10024. * begins after it. */
  10025. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10026. int n, error, exit_by_callback;
  10027. int ret;
  10028. /* body_len is the length of the entire queue in bytes
  10029. * len is the length of the current message
  10030. * data_len is the length of the current message's data payload
  10031. * header_len is the length of the current message's header */
  10032. size_t i, len, mask_len = 0, header_len, body_len;
  10033. uint64_t data_len = 0;
  10034. /* "The masking key is a 32-bit value chosen at random by the client."
  10035. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10036. */
  10037. unsigned char mask[4];
  10038. /* data points to the place where the message is stored when passed to
  10039. * the websocket_data callback. This is either mem on the stack, or a
  10040. * dynamically allocated buffer if it is too large. */
  10041. unsigned char mem[4096];
  10042. unsigned char mop; /* mask flag and opcode */
  10043. /* Variables used for connection monitoring */
  10044. double timeout = -1.0;
  10045. int enable_ping_pong = 0;
  10046. int ping_count = 0;
  10047. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10048. enable_ping_pong =
  10049. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10050. "yes");
  10051. }
  10052. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10053. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10054. }
  10055. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10056. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10057. }
  10058. /* Enter data processing loop */
  10059. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10060. conn->request_info.remote_addr,
  10061. conn->request_info.remote_port);
  10062. conn->in_websocket_handling = 1;
  10063. mg_set_thread_name("wsock");
  10064. /* Loop continuously, reading messages from the socket, invoking the
  10065. * callback, and waiting repeatedly until an error occurs. */
  10066. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10067. header_len = 0;
  10068. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10069. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10070. len = buf[1] & 127;
  10071. mask_len = (buf[1] & 128) ? 4 : 0;
  10072. if ((len < 126) && (body_len >= mask_len)) {
  10073. /* inline 7-bit length field */
  10074. data_len = len;
  10075. header_len = 2 + mask_len;
  10076. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10077. /* 16-bit length field */
  10078. header_len = 4 + mask_len;
  10079. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10080. } else if (body_len >= (10 + mask_len)) {
  10081. /* 64-bit length field */
  10082. uint32_t l1, l2;
  10083. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10084. memcpy(&l2, &buf[6], 4);
  10085. header_len = 10 + mask_len;
  10086. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10087. if (data_len > (uint64_t)0x7FFF0000ul) {
  10088. /* no can do */
  10089. mg_cry_internal(
  10090. conn,
  10091. "%s",
  10092. "websocket out of memory; closing connection");
  10093. break;
  10094. }
  10095. }
  10096. }
  10097. if ((header_len > 0) && (body_len >= header_len)) {
  10098. /* Allocate space to hold websocket payload */
  10099. unsigned char *data = mem;
  10100. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10101. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10102. conn->phys_ctx);
  10103. if (data == NULL) {
  10104. /* Allocation failed, exit the loop and then close the
  10105. * connection */
  10106. mg_cry_internal(
  10107. conn,
  10108. "%s",
  10109. "websocket out of memory; closing connection");
  10110. break;
  10111. }
  10112. }
  10113. /* Copy the mask before we shift the queue and destroy it */
  10114. if (mask_len > 0) {
  10115. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10116. } else {
  10117. memset(mask, 0, sizeof(mask));
  10118. }
  10119. /* Read frame payload from the first message in the queue into
  10120. * data and advance the queue by moving the memory in place. */
  10121. DEBUG_ASSERT(body_len >= header_len);
  10122. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10123. mop = buf[0]; /* current mask and opcode */
  10124. /* Overflow case */
  10125. len = body_len - header_len;
  10126. memcpy(data, buf + header_len, len);
  10127. error = 0;
  10128. while ((uint64_t)len < data_len) {
  10129. n = pull_inner(NULL,
  10130. conn,
  10131. (char *)(data + len),
  10132. (int)(data_len - len),
  10133. timeout);
  10134. if (n <= -2) {
  10135. error = 1;
  10136. break;
  10137. } else if (n > 0) {
  10138. len += (size_t)n;
  10139. } else {
  10140. /* Timeout: should retry */
  10141. /* TODO: retry condition */
  10142. }
  10143. }
  10144. if (error) {
  10145. mg_cry_internal(
  10146. conn,
  10147. "%s",
  10148. "Websocket pull failed; closing connection");
  10149. if (data != mem) {
  10150. mg_free(data);
  10151. }
  10152. break;
  10153. }
  10154. conn->data_len = conn->request_len;
  10155. } else {
  10156. mop = buf[0]; /* current mask and opcode, overwritten by
  10157. * memmove() */
  10158. /* Length of the message being read at the front of the
  10159. * queue. Cast to 31 bit is OK, since we limited
  10160. * data_len before. */
  10161. len = (size_t)data_len + header_len;
  10162. /* Copy the data payload into the data pointer for the
  10163. * callback. Cast to 31 bit is OK, since we
  10164. * limited data_len */
  10165. memcpy(data, buf + header_len, (size_t)data_len);
  10166. /* Move the queue forward len bytes */
  10167. memmove(buf, buf + len, body_len - len);
  10168. /* Mark the queue as advanced */
  10169. conn->data_len -= (int)len;
  10170. }
  10171. /* Apply mask if necessary */
  10172. if (mask_len > 0) {
  10173. for (i = 0; i < (size_t)data_len; i++) {
  10174. data[i] ^= mask[i & 3];
  10175. }
  10176. }
  10177. exit_by_callback = 0;
  10178. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10179. /* filter PONG messages */
  10180. DEBUG_TRACE("PONG from %s:%u",
  10181. conn->request_info.remote_addr,
  10182. conn->request_info.remote_port);
  10183. /* No unanwered PINGs left */
  10184. ping_count = 0;
  10185. } else if (enable_ping_pong
  10186. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10187. /* reply PING messages */
  10188. DEBUG_TRACE("Reply PING from %s:%u",
  10189. conn->request_info.remote_addr,
  10190. conn->request_info.remote_port);
  10191. ret = mg_websocket_write(conn,
  10192. MG_WEBSOCKET_OPCODE_PONG,
  10193. (char *)data,
  10194. (size_t)data_len);
  10195. if (ret <= 0) {
  10196. /* Error: send failed */
  10197. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10198. break;
  10199. }
  10200. } else {
  10201. /* Exit the loop if callback signals to exit (server side),
  10202. * or "connection close" opcode received (client side). */
  10203. if ((ws_data_handler != NULL)
  10204. && !ws_data_handler(conn,
  10205. mop,
  10206. (char *)data,
  10207. (size_t)data_len,
  10208. callback_data)) {
  10209. exit_by_callback = 1;
  10210. }
  10211. }
  10212. /* It a buffer has been allocated, free it again */
  10213. if (data != mem) {
  10214. mg_free(data);
  10215. }
  10216. if (exit_by_callback) {
  10217. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10218. conn->request_info.remote_addr,
  10219. conn->request_info.remote_port);
  10220. break;
  10221. }
  10222. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10223. /* Opcode == 8, connection close */
  10224. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10225. conn->request_info.remote_addr,
  10226. conn->request_info.remote_port);
  10227. break;
  10228. }
  10229. /* Not breaking the loop, process next websocket frame. */
  10230. } else {
  10231. /* Read from the socket into the next available location in the
  10232. * message queue. */
  10233. n = pull_inner(NULL,
  10234. conn,
  10235. conn->buf + conn->data_len,
  10236. conn->buf_size - conn->data_len,
  10237. timeout);
  10238. if (n <= -2) {
  10239. /* Error, no bytes read */
  10240. DEBUG_TRACE("PULL from %s:%u failed",
  10241. conn->request_info.remote_addr,
  10242. conn->request_info.remote_port);
  10243. break;
  10244. }
  10245. if (n > 0) {
  10246. conn->data_len += n;
  10247. /* Reset open PING count */
  10248. ping_count = 0;
  10249. } else {
  10250. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10251. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10252. /* Stop sending PING */
  10253. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10254. "- closing connection",
  10255. ping_count,
  10256. conn->request_info.remote_addr,
  10257. conn->request_info.remote_port);
  10258. break;
  10259. }
  10260. if (enable_ping_pong) {
  10261. /* Send Websocket PING message */
  10262. DEBUG_TRACE("PING to %s:%u",
  10263. conn->request_info.remote_addr,
  10264. conn->request_info.remote_port);
  10265. ret = mg_websocket_write(conn,
  10266. MG_WEBSOCKET_OPCODE_PING,
  10267. NULL,
  10268. 0);
  10269. if (ret <= 0) {
  10270. /* Error: send failed */
  10271. DEBUG_TRACE("Send PING failed (%i)", ret);
  10272. break;
  10273. }
  10274. ping_count++;
  10275. }
  10276. }
  10277. /* Timeout: should retry */
  10278. /* TODO: get timeout def */
  10279. }
  10280. }
  10281. }
  10282. /* Leave data processing loop */
  10283. mg_set_thread_name("worker");
  10284. conn->in_websocket_handling = 0;
  10285. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10286. conn->request_info.remote_addr,
  10287. conn->request_info.remote_port);
  10288. }
  10289. static int
  10290. mg_websocket_write_exec(struct mg_connection *conn,
  10291. int opcode,
  10292. const char *data,
  10293. size_t dataLen,
  10294. uint32_t masking_key)
  10295. {
  10296. unsigned char header[14];
  10297. size_t headerLen;
  10298. int retval;
  10299. #if defined(__GNUC__) || defined(__MINGW32__)
  10300. /* Disable spurious conversion warning for GCC */
  10301. #pragma GCC diagnostic push
  10302. #pragma GCC diagnostic ignored "-Wconversion"
  10303. #endif
  10304. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10305. #if defined(__GNUC__) || defined(__MINGW32__)
  10306. #pragma GCC diagnostic pop
  10307. #endif
  10308. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10309. if (dataLen < 126) {
  10310. /* inline 7-bit length field */
  10311. header[1] = (unsigned char)dataLen;
  10312. headerLen = 2;
  10313. } else if (dataLen <= 0xFFFF) {
  10314. /* 16-bit length field */
  10315. uint16_t len = htons((uint16_t)dataLen);
  10316. header[1] = 126;
  10317. memcpy(header + 2, &len, 2);
  10318. headerLen = 4;
  10319. } else {
  10320. /* 64-bit length field */
  10321. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10322. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10323. header[1] = 127;
  10324. memcpy(header + 2, &len1, 4);
  10325. memcpy(header + 6, &len2, 4);
  10326. headerLen = 10;
  10327. }
  10328. if (masking_key) {
  10329. /* add mask */
  10330. header[1] |= 0x80;
  10331. memcpy(header + headerLen, &masking_key, 4);
  10332. headerLen += 4;
  10333. }
  10334. /* Note that POSIX/Winsock's send() is threadsafe
  10335. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10336. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10337. * push(), although that is only a problem if the packet is large or
  10338. * outgoing buffer is full). */
  10339. /* TODO: Check if this lock should be moved to user land.
  10340. * Currently the server sets this lock for websockets, but
  10341. * not for any other connection. It must be set for every
  10342. * conn read/written by more than one thread, no matter if
  10343. * it is a websocket or regular connection. */
  10344. (void)mg_lock_connection(conn);
  10345. retval = mg_write(conn, header, headerLen);
  10346. if (retval != (int)headerLen) {
  10347. /* Did not send complete header */
  10348. retval = -1;
  10349. } else {
  10350. if (dataLen > 0) {
  10351. retval = mg_write(conn, data, dataLen);
  10352. }
  10353. /* if dataLen == 0, the header length (2) is returned */
  10354. }
  10355. /* TODO: Remove this unlock as well, when lock is removed. */
  10356. mg_unlock_connection(conn);
  10357. return retval;
  10358. }
  10359. int
  10360. mg_websocket_write(struct mg_connection *conn,
  10361. int opcode,
  10362. const char *data,
  10363. size_t dataLen)
  10364. {
  10365. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10366. }
  10367. static void
  10368. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10369. {
  10370. size_t i = 0;
  10371. i = 0;
  10372. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10373. /* Convert in 32 bit words, if data is 4 byte aligned */
  10374. while (i < (in_len - 3)) {
  10375. *(uint32_t *)(void *)(out + i) =
  10376. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10377. i += 4;
  10378. }
  10379. }
  10380. if (i != in_len) {
  10381. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10382. while (i < in_len) {
  10383. *(uint8_t *)(void *)(out + i) =
  10384. *(uint8_t *)(void *)(in + i)
  10385. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10386. i++;
  10387. }
  10388. }
  10389. }
  10390. int
  10391. mg_websocket_client_write(struct mg_connection *conn,
  10392. int opcode,
  10393. const char *data,
  10394. size_t dataLen)
  10395. {
  10396. int retval = -1;
  10397. char *masked_data =
  10398. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10399. uint32_t masking_key = 0;
  10400. if (masked_data == NULL) {
  10401. /* Return -1 in an error case */
  10402. mg_cry_internal(conn,
  10403. "%s",
  10404. "Cannot allocate buffer for masked websocket response: "
  10405. "Out of memory");
  10406. return -1;
  10407. }
  10408. do {
  10409. /* Get a masking key - but not 0 */
  10410. masking_key = (uint32_t)get_random();
  10411. } while (masking_key == 0);
  10412. mask_data(data, dataLen, masking_key, masked_data);
  10413. retval = mg_websocket_write_exec(
  10414. conn, opcode, masked_data, dataLen, masking_key);
  10415. mg_free(masked_data);
  10416. return retval;
  10417. }
  10418. static void
  10419. handle_websocket_request(struct mg_connection *conn,
  10420. const char *path,
  10421. int is_callback_resource,
  10422. struct mg_websocket_subprotocols *subprotocols,
  10423. mg_websocket_connect_handler ws_connect_handler,
  10424. mg_websocket_ready_handler ws_ready_handler,
  10425. mg_websocket_data_handler ws_data_handler,
  10426. mg_websocket_close_handler ws_close_handler,
  10427. void *cbData)
  10428. {
  10429. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10430. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10431. ptrdiff_t lua_websock = 0;
  10432. #if !defined(USE_LUA)
  10433. (void)path;
  10434. #endif
  10435. /* Step 1: Check websocket protocol version. */
  10436. /* Step 1.1: Check Sec-WebSocket-Key. */
  10437. if (!websock_key) {
  10438. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10439. * requires a Sec-WebSocket-Key header.
  10440. */
  10441. /* It could be the hixie draft version
  10442. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10443. */
  10444. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10445. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10446. char key3[8];
  10447. if ((key1 != NULL) && (key2 != NULL)) {
  10448. /* This version uses 8 byte body data in a GET request */
  10449. conn->content_len = 8;
  10450. if (8 == mg_read(conn, key3, 8)) {
  10451. /* This is the hixie version */
  10452. mg_send_http_error(conn,
  10453. 426,
  10454. "%s",
  10455. "Protocol upgrade to RFC 6455 required");
  10456. return;
  10457. }
  10458. }
  10459. /* This is an unknown version */
  10460. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10461. return;
  10462. }
  10463. /* Step 1.2: Check websocket protocol version. */
  10464. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10465. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10466. /* Reject wrong versions */
  10467. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10468. return;
  10469. }
  10470. /* Step 1.3: Could check for "Host", but we do not really nead this
  10471. * value for anything, so just ignore it. */
  10472. /* Step 2: If a callback is responsible, call it. */
  10473. if (is_callback_resource) {
  10474. /* Step 2.1 check and select subprotocol */
  10475. const char *protocols[64]; // max 64 headers
  10476. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10477. "Sec-WebSocket-Protocol",
  10478. protocols,
  10479. 64);
  10480. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10481. int cnt = 0;
  10482. int idx;
  10483. unsigned long len;
  10484. const char *sep, *curSubProtocol,
  10485. *acceptedWebSocketSubprotocol = NULL;
  10486. /* look for matching subprotocol */
  10487. do {
  10488. const char *protocol = protocols[cnt];
  10489. do {
  10490. sep = strchr(protocol, ',');
  10491. curSubProtocol = protocol;
  10492. len = sep ? (unsigned long)(sep - protocol)
  10493. : (unsigned long)strlen(protocol);
  10494. while (sep && isspace(*++sep))
  10495. ; // ignore leading whitespaces
  10496. protocol = sep;
  10497. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10498. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10499. && (strncmp(curSubProtocol,
  10500. subprotocols->subprotocols[idx],
  10501. len) == 0)) {
  10502. acceptedWebSocketSubprotocol =
  10503. subprotocols->subprotocols[idx];
  10504. break;
  10505. }
  10506. }
  10507. } while (sep && !acceptedWebSocketSubprotocol);
  10508. } while (++cnt < nbSubprotocolHeader
  10509. && !acceptedWebSocketSubprotocol);
  10510. conn->request_info.acceptedWebSocketSubprotocol =
  10511. acceptedWebSocketSubprotocol;
  10512. } else if (nbSubprotocolHeader > 0) {
  10513. /* keep legacy behavior */
  10514. const char *protocol = protocols[0];
  10515. /* The protocol is a comma separated list of names. */
  10516. /* The server must only return one value from this list. */
  10517. /* First check if it is a list or just a single value. */
  10518. const char *sep = strrchr(protocol, ',');
  10519. if (sep == NULL) {
  10520. /* Just a single protocol -> accept it. */
  10521. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10522. } else {
  10523. /* Multiple protocols -> accept the last one. */
  10524. /* This is just a quick fix if the client offers multiple
  10525. * protocols. The handler should have a list of accepted
  10526. * protocols on his own
  10527. * and use it to select one protocol among those the client
  10528. * has
  10529. * offered.
  10530. */
  10531. while (isspace(*++sep)) {
  10532. ; /* ignore leading whitespaces */
  10533. }
  10534. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10535. }
  10536. }
  10537. if ((ws_connect_handler != NULL)
  10538. && (ws_connect_handler(conn, cbData) != 0)) {
  10539. /* C callback has returned non-zero, do not proceed with
  10540. * handshake.
  10541. */
  10542. /* Note that C callbacks are no longer called when Lua is
  10543. * responsible, so C can no longer filter callbacks for Lua. */
  10544. return;
  10545. }
  10546. }
  10547. #if defined(USE_LUA)
  10548. /* Step 3: No callback. Check if Lua is responsible. */
  10549. else {
  10550. /* Step 3.1: Check if Lua is responsible. */
  10551. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10552. lua_websock = match_prefix(
  10553. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10554. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10555. path);
  10556. }
  10557. if (lua_websock) {
  10558. /* Step 3.2: Lua is responsible: call it. */
  10559. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10560. if (!conn->lua_websocket_state) {
  10561. /* Lua rejected the new client */
  10562. return;
  10563. }
  10564. }
  10565. }
  10566. #endif
  10567. /* Step 4: Check if there is a responsible websocket handler. */
  10568. if (!is_callback_resource && !lua_websock) {
  10569. /* There is no callback, and Lua is not responsible either. */
  10570. /* Reply with a 404 Not Found. We are still at a standard
  10571. * HTTP request here, before the websocket handshake, so
  10572. * we can still send standard HTTP error replies. */
  10573. mg_send_http_error(conn, 404, "%s", "Not found");
  10574. return;
  10575. }
  10576. /* Step 5: The websocket connection has been accepted */
  10577. if (!send_websocket_handshake(conn, websock_key)) {
  10578. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10579. return;
  10580. }
  10581. /* Step 6: Call the ready handler */
  10582. if (is_callback_resource) {
  10583. if (ws_ready_handler != NULL) {
  10584. ws_ready_handler(conn, cbData);
  10585. }
  10586. #if defined(USE_LUA)
  10587. } else if (lua_websock) {
  10588. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10589. /* the ready handler returned false */
  10590. return;
  10591. }
  10592. #endif
  10593. }
  10594. /* Step 7: Enter the read loop */
  10595. if (is_callback_resource) {
  10596. read_websocket(conn, ws_data_handler, cbData);
  10597. #if defined(USE_LUA)
  10598. } else if (lua_websock) {
  10599. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10600. #endif
  10601. }
  10602. /* Step 8: Call the close handler */
  10603. if (ws_close_handler) {
  10604. ws_close_handler(conn, cbData);
  10605. }
  10606. }
  10607. static int
  10608. is_websocket_protocol(const struct mg_connection *conn)
  10609. {
  10610. const char *upgrade, *connection;
  10611. /* A websocket protocoll has the following HTTP headers:
  10612. *
  10613. * Connection: Upgrade
  10614. * Upgrade: Websocket
  10615. */
  10616. upgrade = mg_get_header(conn, "Upgrade");
  10617. if (upgrade == NULL) {
  10618. return 0; /* fail early, don't waste time checking other header
  10619. * fields
  10620. */
  10621. }
  10622. if (!mg_strcasestr(upgrade, "websocket")) {
  10623. return 0;
  10624. }
  10625. connection = mg_get_header(conn, "Connection");
  10626. if (connection == NULL) {
  10627. return 0;
  10628. }
  10629. if (!mg_strcasestr(connection, "upgrade")) {
  10630. return 0;
  10631. }
  10632. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10633. * "Sec-WebSocket-Version" are also required.
  10634. * Don't check them here, since even an unsupported websocket protocol
  10635. * request still IS a websocket request (in contrast to a standard HTTP
  10636. * request). It will fail later in handle_websocket_request.
  10637. */
  10638. return 1;
  10639. }
  10640. #endif /* !USE_WEBSOCKET */
  10641. static int
  10642. isbyte(int n)
  10643. {
  10644. return (n >= 0) && (n <= 255);
  10645. }
  10646. static int
  10647. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10648. {
  10649. int n, a, b, c, d, slash = 32, len = 0;
  10650. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10651. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10652. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10653. && (slash < 33)) {
  10654. len = n;
  10655. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10656. | (uint32_t)d;
  10657. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10658. }
  10659. return len;
  10660. }
  10661. static int
  10662. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10663. {
  10664. int throttle = 0;
  10665. struct vec vec, val;
  10666. uint32_t net, mask;
  10667. char mult;
  10668. double v;
  10669. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  10670. mult = ',';
  10671. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  10672. || (v < 0) || ((lowercase(&mult) != 'k')
  10673. && (lowercase(&mult) != 'm') && (mult != ','))) {
  10674. continue;
  10675. }
  10676. v *= (lowercase(&mult) == 'k')
  10677. ? 1024
  10678. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  10679. if (vec.len == 1 && vec.ptr[0] == '*') {
  10680. throttle = (int)v;
  10681. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  10682. if ((remote_ip & mask) == net) {
  10683. throttle = (int)v;
  10684. }
  10685. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  10686. throttle = (int)v;
  10687. }
  10688. }
  10689. return throttle;
  10690. }
  10691. static uint32_t
  10692. get_remote_ip(const struct mg_connection *conn)
  10693. {
  10694. if (!conn) {
  10695. return 0;
  10696. }
  10697. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  10698. }
  10699. /* The mg_upload function is superseeded by mg_handle_form_request. */
  10700. #include "handle_form.inl"
  10701. #if defined(MG_LEGACY_INTERFACE)
  10702. /* Implement the deprecated mg_upload function by calling the new
  10703. * mg_handle_form_request function. While mg_upload could only handle
  10704. * HTML forms sent as POST request in multipart/form-data format
  10705. * containing only file input elements, mg_handle_form_request can
  10706. * handle all form input elements and all standard request methods. */
  10707. struct mg_upload_user_data {
  10708. struct mg_connection *conn;
  10709. const char *destination_dir;
  10710. int num_uploaded_files;
  10711. };
  10712. /* Helper function for deprecated mg_upload. */
  10713. static int
  10714. mg_upload_field_found(const char *key,
  10715. const char *filename,
  10716. char *path,
  10717. size_t pathlen,
  10718. void *user_data)
  10719. {
  10720. int truncated = 0;
  10721. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10722. (void)key;
  10723. if (!filename) {
  10724. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  10725. return FORM_FIELD_STORAGE_ABORT;
  10726. }
  10727. mg_snprintf(fud->conn,
  10728. &truncated,
  10729. path,
  10730. pathlen - 1,
  10731. "%s/%s",
  10732. fud->destination_dir,
  10733. filename);
  10734. if (truncated) {
  10735. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  10736. return FORM_FIELD_STORAGE_ABORT;
  10737. }
  10738. return FORM_FIELD_STORAGE_STORE;
  10739. }
  10740. /* Helper function for deprecated mg_upload. */
  10741. static int
  10742. mg_upload_field_get(const char *key,
  10743. const char *value,
  10744. size_t value_size,
  10745. void *user_data)
  10746. {
  10747. /* Function should never be called */
  10748. (void)key;
  10749. (void)value;
  10750. (void)value_size;
  10751. (void)user_data;
  10752. return 0;
  10753. }
  10754. /* Helper function for deprecated mg_upload. */
  10755. static int
  10756. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  10757. {
  10758. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10759. (void)file_size;
  10760. fud->num_uploaded_files++;
  10761. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  10762. return 0;
  10763. }
  10764. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  10765. int
  10766. mg_upload(struct mg_connection *conn, const char *destination_dir)
  10767. {
  10768. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  10769. struct mg_form_data_handler fdh = {mg_upload_field_found,
  10770. mg_upload_field_get,
  10771. mg_upload_field_stored,
  10772. 0};
  10773. int ret;
  10774. fdh.user_data = (void *)&fud;
  10775. ret = mg_handle_form_request(conn, &fdh);
  10776. if (ret < 0) {
  10777. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  10778. }
  10779. return fud.num_uploaded_files;
  10780. }
  10781. #endif
  10782. static int
  10783. get_first_ssl_listener_index(const struct mg_context *ctx)
  10784. {
  10785. unsigned int i;
  10786. int idx = -1;
  10787. if (ctx) {
  10788. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  10789. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  10790. }
  10791. }
  10792. return idx;
  10793. }
  10794. /* Return host (without port) */
  10795. /* Use mg_free to free the result */
  10796. static const char *
  10797. alloc_get_host(struct mg_connection *conn)
  10798. {
  10799. char host[1025];
  10800. const char *host_header;
  10801. size_t hostlen;
  10802. host_header = get_header(conn->request_info.http_headers,
  10803. conn->request_info.num_headers,
  10804. "Host");
  10805. hostlen = sizeof(host);
  10806. if (host_header != NULL) {
  10807. char *pos;
  10808. mg_strlcpy(host, host_header, hostlen);
  10809. host[hostlen - 1] = '\0';
  10810. pos = strchr(host, ':');
  10811. if (pos != NULL) {
  10812. *pos = '\0';
  10813. }
  10814. if (conn->ssl) {
  10815. /* This is a HTTPS connection, maybe we have a hostname
  10816. * from SNI (set in ssl_servername_callback). */
  10817. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  10818. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  10819. /* We are not using the default domain */
  10820. if (mg_strcasecmp(host, sslhost)) {
  10821. /* Mismatch between SNI domain and HTTP domain */
  10822. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  10823. sslhost,
  10824. host);
  10825. return NULL;
  10826. }
  10827. }
  10828. DEBUG_TRACE("HTTPS Host: %s", host);
  10829. } else {
  10830. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  10831. while (dom) {
  10832. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  10833. /* Found matching domain */
  10834. DEBUG_TRACE("HTTP domain %s found",
  10835. dom->config[AUTHENTICATION_DOMAIN]);
  10836. /* TODO: Check if this is a HTTP or HTTPS domain */
  10837. conn->dom_ctx = dom;
  10838. break;
  10839. }
  10840. dom = dom->next;
  10841. }
  10842. DEBUG_TRACE("HTTP Host: %s", host);
  10843. }
  10844. } else {
  10845. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  10846. DEBUG_TRACE("IP: %s", host);
  10847. }
  10848. return mg_strdup_ctx(host, conn->phys_ctx);
  10849. }
  10850. static void
  10851. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  10852. {
  10853. conn->must_close = 1;
  10854. /* Send host, port, uri and (if it exists) ?query_string */
  10855. if (conn->host) {
  10856. mg_printf(conn,
  10857. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  10858. conn->host,
  10859. #if defined(USE_IPV6)
  10860. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  10861. == AF_INET6)
  10862. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  10863. .lsa.sin6.sin6_port)
  10864. :
  10865. #endif
  10866. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  10867. .lsa.sin.sin_port),
  10868. conn->request_info.local_uri,
  10869. (conn->request_info.query_string == NULL) ? "" : "?",
  10870. (conn->request_info.query_string == NULL)
  10871. ? ""
  10872. : conn->request_info.query_string);
  10873. }
  10874. }
  10875. static void
  10876. handler_info_acquire(struct mg_handler_info *handler_info)
  10877. {
  10878. pthread_mutex_lock(&handler_info->refcount_mutex);
  10879. handler_info->refcount++;
  10880. pthread_mutex_unlock(&handler_info->refcount_mutex);
  10881. }
  10882. static void
  10883. handler_info_release(struct mg_handler_info *handler_info)
  10884. {
  10885. pthread_mutex_lock(&handler_info->refcount_mutex);
  10886. handler_info->refcount--;
  10887. pthread_cond_signal(&handler_info->refcount_cond);
  10888. pthread_mutex_unlock(&handler_info->refcount_mutex);
  10889. }
  10890. static void
  10891. handler_info_wait_unused(struct mg_handler_info *handler_info)
  10892. {
  10893. pthread_mutex_lock(&handler_info->refcount_mutex);
  10894. while (handler_info->refcount) {
  10895. pthread_cond_wait(&handler_info->refcount_cond,
  10896. &handler_info->refcount_mutex);
  10897. }
  10898. pthread_mutex_unlock(&handler_info->refcount_mutex);
  10899. }
  10900. static void
  10901. mg_set_handler_type(struct mg_context *phys_ctx,
  10902. struct mg_domain_context *dom_ctx,
  10903. const char *uri,
  10904. int handler_type,
  10905. int is_delete_request,
  10906. mg_request_handler handler,
  10907. struct mg_websocket_subprotocols *subprotocols,
  10908. mg_websocket_connect_handler connect_handler,
  10909. mg_websocket_ready_handler ready_handler,
  10910. mg_websocket_data_handler data_handler,
  10911. mg_websocket_close_handler close_handler,
  10912. mg_authorization_handler auth_handler,
  10913. void *cbdata)
  10914. {
  10915. struct mg_handler_info *tmp_rh, **lastref;
  10916. size_t urilen = strlen(uri);
  10917. if (handler_type == WEBSOCKET_HANDLER) {
  10918. DEBUG_ASSERT(handler == NULL);
  10919. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  10920. || ready_handler != NULL
  10921. || data_handler != NULL
  10922. || close_handler != NULL);
  10923. DEBUG_ASSERT(auth_handler == NULL);
  10924. if (handler != NULL) {
  10925. return;
  10926. }
  10927. if (!is_delete_request && (connect_handler == NULL)
  10928. && (ready_handler == NULL) && (data_handler == NULL)
  10929. && (close_handler == NULL)) {
  10930. return;
  10931. }
  10932. if (auth_handler != NULL) {
  10933. return;
  10934. }
  10935. } else if (handler_type == REQUEST_HANDLER) {
  10936. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  10937. && data_handler == NULL
  10938. && close_handler == NULL);
  10939. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  10940. DEBUG_ASSERT(auth_handler == NULL);
  10941. if ((connect_handler != NULL) || (ready_handler != NULL)
  10942. || (data_handler != NULL) || (close_handler != NULL)) {
  10943. return;
  10944. }
  10945. if (!is_delete_request && (handler == NULL)) {
  10946. return;
  10947. }
  10948. if (auth_handler != NULL) {
  10949. return;
  10950. }
  10951. } else { /* AUTH_HANDLER */
  10952. DEBUG_ASSERT(handler == NULL);
  10953. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  10954. && data_handler == NULL
  10955. && close_handler == NULL);
  10956. DEBUG_ASSERT(auth_handler != NULL);
  10957. if (handler != NULL) {
  10958. return;
  10959. }
  10960. if ((connect_handler != NULL) || (ready_handler != NULL)
  10961. || (data_handler != NULL) || (close_handler != NULL)) {
  10962. return;
  10963. }
  10964. if (!is_delete_request && (auth_handler == NULL)) {
  10965. return;
  10966. }
  10967. }
  10968. if (!phys_ctx || !dom_ctx) {
  10969. return;
  10970. }
  10971. mg_lock_context(phys_ctx);
  10972. /* first try to find an existing handler */
  10973. lastref = &(dom_ctx->handlers);
  10974. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  10975. if (tmp_rh->handler_type == handler_type) {
  10976. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10977. if (!is_delete_request) {
  10978. /* update existing handler */
  10979. if (handler_type == REQUEST_HANDLER) {
  10980. /* Wait for end of use before updating */
  10981. handler_info_wait_unused(tmp_rh);
  10982. /* Ok, the handler is no more use -> Update it */
  10983. tmp_rh->handler = handler;
  10984. } else if (handler_type == WEBSOCKET_HANDLER) {
  10985. tmp_rh->subprotocols = subprotocols;
  10986. tmp_rh->connect_handler = connect_handler;
  10987. tmp_rh->ready_handler = ready_handler;
  10988. tmp_rh->data_handler = data_handler;
  10989. tmp_rh->close_handler = close_handler;
  10990. } else { /* AUTH_HANDLER */
  10991. tmp_rh->auth_handler = auth_handler;
  10992. }
  10993. tmp_rh->cbdata = cbdata;
  10994. } else {
  10995. /* remove existing handler */
  10996. if (handler_type == REQUEST_HANDLER) {
  10997. /* Wait for end of use before removing */
  10998. handler_info_wait_unused(tmp_rh);
  10999. /* Ok, the handler is no more used -> Destroy resources
  11000. */
  11001. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11002. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11003. }
  11004. *lastref = tmp_rh->next;
  11005. mg_free(tmp_rh->uri);
  11006. mg_free(tmp_rh);
  11007. }
  11008. mg_unlock_context(phys_ctx);
  11009. return;
  11010. }
  11011. }
  11012. lastref = &(tmp_rh->next);
  11013. }
  11014. if (is_delete_request) {
  11015. /* no handler to set, this was a remove request to a non-existing
  11016. * handler */
  11017. mg_unlock_context(phys_ctx);
  11018. return;
  11019. }
  11020. tmp_rh =
  11021. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11022. 1,
  11023. phys_ctx);
  11024. if (tmp_rh == NULL) {
  11025. mg_unlock_context(phys_ctx);
  11026. mg_cry_internal(fc(phys_ctx),
  11027. "%s",
  11028. "Cannot create new request handler struct, OOM");
  11029. return;
  11030. }
  11031. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11032. if (!tmp_rh->uri) {
  11033. mg_unlock_context(phys_ctx);
  11034. mg_free(tmp_rh);
  11035. mg_cry_internal(fc(phys_ctx),
  11036. "%s",
  11037. "Cannot create new request handler struct, OOM");
  11038. return;
  11039. }
  11040. tmp_rh->uri_len = urilen;
  11041. if (handler_type == REQUEST_HANDLER) {
  11042. /* Init refcount mutex and condition */
  11043. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11044. mg_unlock_context(phys_ctx);
  11045. mg_free(tmp_rh);
  11046. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");
  11047. return;
  11048. }
  11049. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11050. mg_unlock_context(phys_ctx);
  11051. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11052. mg_free(tmp_rh);
  11053. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");
  11054. return;
  11055. }
  11056. tmp_rh->refcount = 0;
  11057. tmp_rh->handler = handler;
  11058. } else if (handler_type == WEBSOCKET_HANDLER) {
  11059. tmp_rh->subprotocols = subprotocols;
  11060. tmp_rh->connect_handler = connect_handler;
  11061. tmp_rh->ready_handler = ready_handler;
  11062. tmp_rh->data_handler = data_handler;
  11063. tmp_rh->close_handler = close_handler;
  11064. } else { /* AUTH_HANDLER */
  11065. tmp_rh->auth_handler = auth_handler;
  11066. }
  11067. tmp_rh->cbdata = cbdata;
  11068. tmp_rh->handler_type = handler_type;
  11069. tmp_rh->next = NULL;
  11070. *lastref = tmp_rh;
  11071. mg_unlock_context(phys_ctx);
  11072. }
  11073. void
  11074. mg_set_request_handler(struct mg_context *ctx,
  11075. const char *uri,
  11076. mg_request_handler handler,
  11077. void *cbdata)
  11078. {
  11079. mg_set_handler_type(ctx,
  11080. &(ctx->dd),
  11081. uri,
  11082. REQUEST_HANDLER,
  11083. handler == NULL,
  11084. handler,
  11085. NULL,
  11086. NULL,
  11087. NULL,
  11088. NULL,
  11089. NULL,
  11090. NULL,
  11091. cbdata);
  11092. }
  11093. void
  11094. mg_set_websocket_handler(struct mg_context *ctx,
  11095. const char *uri,
  11096. mg_websocket_connect_handler connect_handler,
  11097. mg_websocket_ready_handler ready_handler,
  11098. mg_websocket_data_handler data_handler,
  11099. mg_websocket_close_handler close_handler,
  11100. void *cbdata)
  11101. {
  11102. mg_set_websocket_handler_with_subprotocols(ctx,
  11103. uri,
  11104. NULL,
  11105. connect_handler,
  11106. ready_handler,
  11107. data_handler,
  11108. close_handler,
  11109. cbdata);
  11110. }
  11111. void
  11112. mg_set_websocket_handler_with_subprotocols(
  11113. struct mg_context *ctx,
  11114. const char *uri,
  11115. struct mg_websocket_subprotocols *subprotocols,
  11116. mg_websocket_connect_handler connect_handler,
  11117. mg_websocket_ready_handler ready_handler,
  11118. mg_websocket_data_handler data_handler,
  11119. mg_websocket_close_handler close_handler,
  11120. void *cbdata)
  11121. {
  11122. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11123. && (data_handler == NULL)
  11124. && (close_handler == NULL);
  11125. mg_set_handler_type(ctx,
  11126. &(ctx->dd),
  11127. uri,
  11128. WEBSOCKET_HANDLER,
  11129. is_delete_request,
  11130. NULL,
  11131. subprotocols,
  11132. connect_handler,
  11133. ready_handler,
  11134. data_handler,
  11135. close_handler,
  11136. NULL,
  11137. cbdata);
  11138. }
  11139. void
  11140. mg_set_auth_handler(struct mg_context *ctx,
  11141. const char *uri,
  11142. mg_request_handler handler,
  11143. void *cbdata)
  11144. {
  11145. mg_set_handler_type(ctx,
  11146. &(ctx->dd),
  11147. uri,
  11148. AUTH_HANDLER,
  11149. handler == NULL,
  11150. NULL,
  11151. NULL,
  11152. NULL,
  11153. NULL,
  11154. NULL,
  11155. NULL,
  11156. handler,
  11157. cbdata);
  11158. }
  11159. static int
  11160. get_request_handler(struct mg_connection *conn,
  11161. int handler_type,
  11162. mg_request_handler *handler,
  11163. struct mg_websocket_subprotocols **subprotocols,
  11164. mg_websocket_connect_handler *connect_handler,
  11165. mg_websocket_ready_handler *ready_handler,
  11166. mg_websocket_data_handler *data_handler,
  11167. mg_websocket_close_handler *close_handler,
  11168. mg_authorization_handler *auth_handler,
  11169. void **cbdata,
  11170. struct mg_handler_info **handler_info)
  11171. {
  11172. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11173. if (request_info) {
  11174. const char *uri = request_info->local_uri;
  11175. size_t urilen = strlen(uri);
  11176. struct mg_handler_info *tmp_rh;
  11177. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11178. return 0;
  11179. }
  11180. mg_lock_context(conn->phys_ctx);
  11181. /* first try for an exact match */
  11182. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11183. tmp_rh = tmp_rh->next) {
  11184. if (tmp_rh->handler_type == handler_type) {
  11185. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11186. if (handler_type == WEBSOCKET_HANDLER) {
  11187. *subprotocols = tmp_rh->subprotocols;
  11188. *connect_handler = tmp_rh->connect_handler;
  11189. *ready_handler = tmp_rh->ready_handler;
  11190. *data_handler = tmp_rh->data_handler;
  11191. *close_handler = tmp_rh->close_handler;
  11192. } else if (handler_type == REQUEST_HANDLER) {
  11193. *handler = tmp_rh->handler;
  11194. /* Acquire handler and give it back */
  11195. handler_info_acquire(tmp_rh);
  11196. *handler_info = tmp_rh;
  11197. } else { /* AUTH_HANDLER */
  11198. *auth_handler = tmp_rh->auth_handler;
  11199. }
  11200. *cbdata = tmp_rh->cbdata;
  11201. mg_unlock_context(conn->phys_ctx);
  11202. return 1;
  11203. }
  11204. }
  11205. }
  11206. /* next try for a partial match, we will accept uri/something */
  11207. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11208. tmp_rh = tmp_rh->next) {
  11209. if (tmp_rh->handler_type == handler_type) {
  11210. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11211. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11212. if (handler_type == WEBSOCKET_HANDLER) {
  11213. *subprotocols = tmp_rh->subprotocols;
  11214. *connect_handler = tmp_rh->connect_handler;
  11215. *ready_handler = tmp_rh->ready_handler;
  11216. *data_handler = tmp_rh->data_handler;
  11217. *close_handler = tmp_rh->close_handler;
  11218. } else if (handler_type == REQUEST_HANDLER) {
  11219. *handler = tmp_rh->handler;
  11220. /* Acquire handler and give it back */
  11221. handler_info_acquire(tmp_rh);
  11222. *handler_info = tmp_rh;
  11223. } else { /* AUTH_HANDLER */
  11224. *auth_handler = tmp_rh->auth_handler;
  11225. }
  11226. *cbdata = tmp_rh->cbdata;
  11227. mg_unlock_context(conn->phys_ctx);
  11228. return 1;
  11229. }
  11230. }
  11231. }
  11232. /* finally try for pattern match */
  11233. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11234. tmp_rh = tmp_rh->next) {
  11235. if (tmp_rh->handler_type == handler_type) {
  11236. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11237. if (handler_type == WEBSOCKET_HANDLER) {
  11238. *subprotocols = tmp_rh->subprotocols;
  11239. *connect_handler = tmp_rh->connect_handler;
  11240. *ready_handler = tmp_rh->ready_handler;
  11241. *data_handler = tmp_rh->data_handler;
  11242. *close_handler = tmp_rh->close_handler;
  11243. } else if (handler_type == REQUEST_HANDLER) {
  11244. *handler = tmp_rh->handler;
  11245. /* Acquire handler and give it back */
  11246. handler_info_acquire(tmp_rh);
  11247. *handler_info = tmp_rh;
  11248. } else { /* AUTH_HANDLER */
  11249. *auth_handler = tmp_rh->auth_handler;
  11250. }
  11251. *cbdata = tmp_rh->cbdata;
  11252. mg_unlock_context(conn->phys_ctx);
  11253. return 1;
  11254. }
  11255. }
  11256. }
  11257. mg_unlock_context(conn->phys_ctx);
  11258. }
  11259. return 0; /* none found */
  11260. }
  11261. /* Check if the script file is in a path, allowed for script files.
  11262. * This can be used if uploading files is possible not only for the server
  11263. * admin, and the upload mechanism does not check the file extension.
  11264. */
  11265. static int
  11266. is_in_script_path(const struct mg_connection *conn, const char *path)
  11267. {
  11268. /* TODO (Feature): Add config value for allowed script path.
  11269. * Default: All allowed. */
  11270. (void)conn;
  11271. (void)path;
  11272. return 1;
  11273. }
  11274. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11275. static int
  11276. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11277. void *cbdata)
  11278. {
  11279. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11280. if (pcallbacks->websocket_connect) {
  11281. return pcallbacks->websocket_connect(conn);
  11282. }
  11283. /* No handler set - assume "OK" */
  11284. return 0;
  11285. }
  11286. static void
  11287. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11288. {
  11289. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11290. if (pcallbacks->websocket_ready) {
  11291. pcallbacks->websocket_ready(conn);
  11292. }
  11293. }
  11294. static int
  11295. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11296. int bits,
  11297. char *data,
  11298. size_t len,
  11299. void *cbdata)
  11300. {
  11301. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11302. if (pcallbacks->websocket_data) {
  11303. return pcallbacks->websocket_data(conn, bits, data, len);
  11304. }
  11305. /* No handler set - assume "OK" */
  11306. return 1;
  11307. }
  11308. #endif
  11309. /* This is the heart of the Civetweb's logic.
  11310. * This function is called when the request is read, parsed and validated,
  11311. * and Civetweb must decide what action to take: serve a file, or
  11312. * a directory, or call embedded function, etcetera. */
  11313. static void
  11314. handle_request(struct mg_connection *conn)
  11315. {
  11316. struct mg_request_info *ri = &conn->request_info;
  11317. char path[PATH_MAX];
  11318. int uri_len, ssl_index;
  11319. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11320. is_put_or_delete_request = 0, is_callback_resource = 0;
  11321. int i;
  11322. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11323. mg_request_handler callback_handler = NULL;
  11324. struct mg_handler_info *handler_info = NULL;
  11325. struct mg_websocket_subprotocols *subprotocols;
  11326. mg_websocket_connect_handler ws_connect_handler = NULL;
  11327. mg_websocket_ready_handler ws_ready_handler = NULL;
  11328. mg_websocket_data_handler ws_data_handler = NULL;
  11329. mg_websocket_close_handler ws_close_handler = NULL;
  11330. void *callback_data = NULL;
  11331. mg_authorization_handler auth_handler = NULL;
  11332. void *auth_callback_data = NULL;
  11333. int handler_type;
  11334. time_t curtime = time(NULL);
  11335. char date[64];
  11336. path[0] = 0;
  11337. /* 1. get the request url */
  11338. /* 1.1. split into url and query string */
  11339. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11340. != NULL) {
  11341. *((char *)conn->request_info.query_string++) = '\0';
  11342. }
  11343. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11344. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11345. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11346. if (ssl_index >= 0) {
  11347. redirect_to_https_port(conn, ssl_index);
  11348. } else {
  11349. /* A http to https forward port has been specified,
  11350. * but no https port to forward to. */
  11351. mg_send_http_error(conn,
  11352. 503,
  11353. "%s",
  11354. "Error: SSL forward not configured properly");
  11355. mg_cry_internal(conn,
  11356. "%s",
  11357. "Can not redirect to SSL, no SSL port available");
  11358. }
  11359. return;
  11360. }
  11361. uri_len = (int)strlen(ri->local_uri);
  11362. /* 1.3. decode url (if config says so) */
  11363. if (should_decode_url(conn)) {
  11364. mg_url_decode(
  11365. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11366. }
  11367. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11368. * not possible */
  11369. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11370. /* step 1. completed, the url is known now */
  11371. uri_len = (int)strlen(ri->local_uri);
  11372. DEBUG_TRACE("URL: %s", ri->local_uri);
  11373. /* 2. if this ip has limited speed, set it for this connection */
  11374. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11375. get_remote_ip(conn),
  11376. ri->local_uri);
  11377. /* 3. call a "handle everything" callback, if registered */
  11378. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11379. /* Note that since V1.7 the "begin_request" function is called
  11380. * before an authorization check. If an authorization check is
  11381. * required, use a request_handler instead. */
  11382. i = conn->phys_ctx->callbacks.begin_request(conn);
  11383. if (i > 0) {
  11384. /* callback already processed the request. Store the
  11385. return value as a status code for the access log. */
  11386. conn->status_code = i;
  11387. discard_unread_request_data(conn);
  11388. return;
  11389. } else if (i == 0) {
  11390. /* civetweb should process the request */
  11391. } else {
  11392. /* unspecified - may change with the next version */
  11393. return;
  11394. }
  11395. }
  11396. /* request not yet handled by a handler or redirect, so the request
  11397. * is processed here */
  11398. /* 4. Check for CORS preflight requests and handle them (if configured).
  11399. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11400. */
  11401. if (!strcmp(ri->request_method, "OPTIONS")) {
  11402. /* Send a response to CORS preflights only if
  11403. * access_control_allow_methods is not NULL and not an empty string.
  11404. * In this case, scripts can still handle CORS. */
  11405. const char *cors_meth_cfg =
  11406. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11407. const char *cors_orig_cfg =
  11408. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11409. const char *cors_origin =
  11410. get_header(ri->http_headers, ri->num_headers, "Origin");
  11411. const char *cors_acrm = get_header(ri->http_headers,
  11412. ri->num_headers,
  11413. "Access-Control-Request-Method");
  11414. /* Todo: check if cors_origin is in cors_orig_cfg.
  11415. * Or, let the client check this. */
  11416. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11417. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11418. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11419. /* This is a valid CORS preflight, and the server is configured
  11420. * to
  11421. * handle it automatically. */
  11422. const char *cors_acrh =
  11423. get_header(ri->http_headers,
  11424. ri->num_headers,
  11425. "Access-Control-Request-Headers");
  11426. gmt_time_string(date, sizeof(date), &curtime);
  11427. mg_printf(conn,
  11428. "HTTP/1.1 200 OK\r\n"
  11429. "Date: %s\r\n"
  11430. "Access-Control-Allow-Origin: %s\r\n"
  11431. "Access-Control-Allow-Methods: %s\r\n"
  11432. "Content-Length: 0\r\n"
  11433. "Connection: %s\r\n",
  11434. date,
  11435. cors_orig_cfg,
  11436. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11437. suggest_connection_header(conn));
  11438. if (cors_acrh != NULL) {
  11439. /* CORS request is asking for additional headers */
  11440. const char *cors_hdr_cfg =
  11441. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11442. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11443. /* Allow only if access_control_allow_headers is
  11444. * not NULL and not an empty string. If this
  11445. * configuration is set to *, allow everything.
  11446. * Otherwise this configuration must be a list
  11447. * of allowed HTTP header names. */
  11448. mg_printf(conn,
  11449. "Access-Control-Allow-Headers: %s\r\n",
  11450. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11451. : cors_hdr_cfg));
  11452. }
  11453. }
  11454. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11455. mg_printf(conn, "\r\n");
  11456. return;
  11457. }
  11458. }
  11459. /* 5. interpret the url to find out how the request must be handled
  11460. */
  11461. /* 5.1. first test, if the request targets the regular http(s)://
  11462. * protocol namespace or the websocket ws(s):// protocol namespace.
  11463. */
  11464. is_websocket_request = is_websocket_protocol(conn);
  11465. #if defined(USE_WEBSOCKET)
  11466. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11467. #else
  11468. handler_type = REQUEST_HANDLER;
  11469. #endif /* defined(USE_WEBSOCKET) */
  11470. /* 5.2. check if the request will be handled by a callback */
  11471. if (get_request_handler(conn,
  11472. handler_type,
  11473. &callback_handler,
  11474. &subprotocols,
  11475. &ws_connect_handler,
  11476. &ws_ready_handler,
  11477. &ws_data_handler,
  11478. &ws_close_handler,
  11479. NULL,
  11480. &callback_data,
  11481. &handler_info)) {
  11482. /* 5.2.1. A callback will handle this request. All requests
  11483. * handled
  11484. * by a callback have to be considered as requests to a script
  11485. * resource. */
  11486. is_callback_resource = 1;
  11487. is_script_resource = 1;
  11488. is_put_or_delete_request = is_put_or_delete_method(conn);
  11489. } else {
  11490. no_callback_resource:
  11491. /* 5.2.2. No callback is responsible for this request. The URI
  11492. * addresses a file based resource (static content or Lua/cgi
  11493. * scripts in the file system). */
  11494. is_callback_resource = 0;
  11495. interpret_uri(conn,
  11496. path,
  11497. sizeof(path),
  11498. &file.stat,
  11499. &is_found,
  11500. &is_script_resource,
  11501. &is_websocket_request,
  11502. &is_put_or_delete_request);
  11503. }
  11504. /* 6. authorization check */
  11505. /* 6.1. a custom authorization handler is installed */
  11506. if (get_request_handler(conn,
  11507. AUTH_HANDLER,
  11508. NULL,
  11509. NULL,
  11510. NULL,
  11511. NULL,
  11512. NULL,
  11513. NULL,
  11514. &auth_handler,
  11515. &auth_callback_data,
  11516. NULL)) {
  11517. if (!auth_handler(conn, auth_callback_data)) {
  11518. return;
  11519. }
  11520. } else if (is_put_or_delete_request && !is_script_resource
  11521. && !is_callback_resource) {
  11522. /* 6.2. this request is a PUT/DELETE to a real file */
  11523. /* 6.2.1. thus, the server must have real files */
  11524. #if defined(NO_FILES)
  11525. if (1) {
  11526. #else
  11527. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11528. #endif
  11529. /* This server does not have any real files, thus the
  11530. * PUT/DELETE methods are not valid. */
  11531. mg_send_http_error(conn,
  11532. 405,
  11533. "%s method not allowed",
  11534. conn->request_info.request_method);
  11535. return;
  11536. }
  11537. #if !defined(NO_FILES)
  11538. /* 6.2.2. Check if put authorization for static files is
  11539. * available.
  11540. */
  11541. if (!is_authorized_for_put(conn)) {
  11542. send_authorization_request(conn, NULL);
  11543. return;
  11544. }
  11545. #endif
  11546. } else {
  11547. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11548. * or it is a PUT or DELETE request to a resource that does not
  11549. * correspond to a file. Check authorization. */
  11550. if (!check_authorization(conn, path)) {
  11551. send_authorization_request(conn, NULL);
  11552. return;
  11553. }
  11554. }
  11555. /* request is authorized or does not need authorization */
  11556. /* 7. check if there are request handlers for this uri */
  11557. if (is_callback_resource) {
  11558. if (!is_websocket_request) {
  11559. i = callback_handler(conn, callback_data);
  11560. /* Callback handler will not be used anymore. Release it */
  11561. handler_info_release(handler_info);
  11562. if (i > 0) {
  11563. /* Do nothing, callback has served the request. Store
  11564. * then return value as status code for the log and discard
  11565. * all data from the client not used by the callback. */
  11566. conn->status_code = i;
  11567. discard_unread_request_data(conn);
  11568. } else {
  11569. /* The handler did NOT handle the request. */
  11570. /* Some proper reactions would be:
  11571. * a) close the connections without sending anything
  11572. * b) send a 404 not found
  11573. * c) try if there is a file matching the URI
  11574. * It would be possible to do a, b or c in the callback
  11575. * implementation, and return 1 - we cannot do anything
  11576. * here, that is not possible in the callback.
  11577. *
  11578. * TODO: What would be the best reaction here?
  11579. * (Note: The reaction may change, if there is a better
  11580. *idea.)
  11581. */
  11582. /* For the moment, use option c: We look for a proper file,
  11583. * but since a file request is not always a script resource,
  11584. * the authorization check might be different. */
  11585. interpret_uri(conn,
  11586. path,
  11587. sizeof(path),
  11588. &file.stat,
  11589. &is_found,
  11590. &is_script_resource,
  11591. &is_websocket_request,
  11592. &is_put_or_delete_request);
  11593. callback_handler = NULL;
  11594. /* Here we are at a dead end:
  11595. * According to URI matching, a callback should be
  11596. * responsible for handling the request,
  11597. * we called it, but the callback declared itself
  11598. * not responsible.
  11599. * We use a goto here, to get out of this dead end,
  11600. * and continue with the default handling.
  11601. * A goto here is simpler and better to understand
  11602. * than some curious loop. */
  11603. goto no_callback_resource;
  11604. }
  11605. } else {
  11606. #if defined(USE_WEBSOCKET)
  11607. handle_websocket_request(conn,
  11608. path,
  11609. is_callback_resource,
  11610. subprotocols,
  11611. ws_connect_handler,
  11612. ws_ready_handler,
  11613. ws_data_handler,
  11614. ws_close_handler,
  11615. callback_data);
  11616. #endif
  11617. }
  11618. return;
  11619. }
  11620. /* 8. handle websocket requests */
  11621. #if defined(USE_WEBSOCKET)
  11622. if (is_websocket_request) {
  11623. if (is_script_resource) {
  11624. if (is_in_script_path(conn, path)) {
  11625. /* Websocket Lua script */
  11626. handle_websocket_request(conn,
  11627. path,
  11628. 0 /* Lua Script */,
  11629. NULL,
  11630. NULL,
  11631. NULL,
  11632. NULL,
  11633. NULL,
  11634. conn->phys_ctx->user_data);
  11635. } else {
  11636. /* Script was in an illegal path */
  11637. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11638. }
  11639. } else {
  11640. #if defined(MG_LEGACY_INTERFACE)
  11641. handle_websocket_request(
  11642. conn,
  11643. path,
  11644. !is_script_resource /* could be deprecated global callback */,
  11645. NULL,
  11646. deprecated_websocket_connect_wrapper,
  11647. deprecated_websocket_ready_wrapper,
  11648. deprecated_websocket_data_wrapper,
  11649. NULL,
  11650. conn->phys_ctx->user_data);
  11651. #else
  11652. mg_send_http_error(conn, 404, "%s", "Not found");
  11653. #endif
  11654. }
  11655. return;
  11656. } else
  11657. #endif
  11658. #if defined(NO_FILES)
  11659. /* 9a. In case the server uses only callbacks, this uri is
  11660. * unknown.
  11661. * Then, all request handling ends here. */
  11662. mg_send_http_error(conn, 404, "%s", "Not Found");
  11663. #else
  11664. /* 9b. This request is either for a static file or resource handled
  11665. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  11666. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11667. mg_send_http_error(conn, 404, "%s", "Not Found");
  11668. return;
  11669. }
  11670. /* 10. Request is handled by a script */
  11671. if (is_script_resource) {
  11672. handle_file_based_request(conn, path, &file);
  11673. return;
  11674. }
  11675. /* 11. Handle put/delete/mkcol requests */
  11676. if (is_put_or_delete_request) {
  11677. /* 11.1. PUT method */
  11678. if (!strcmp(ri->request_method, "PUT")) {
  11679. put_file(conn, path);
  11680. return;
  11681. }
  11682. /* 11.2. DELETE method */
  11683. if (!strcmp(ri->request_method, "DELETE")) {
  11684. delete_file(conn, path);
  11685. return;
  11686. }
  11687. /* 11.3. MKCOL method */
  11688. if (!strcmp(ri->request_method, "MKCOL")) {
  11689. mkcol(conn, path);
  11690. return;
  11691. }
  11692. /* 11.4. PATCH method
  11693. * This method is not supported for static resources,
  11694. * only for scripts (Lua, CGI) and callbacks. */
  11695. mg_send_http_error(conn,
  11696. 405,
  11697. "%s method not allowed",
  11698. conn->request_info.request_method);
  11699. return;
  11700. }
  11701. /* 11. File does not exist, or it was configured that it should be
  11702. * hidden */
  11703. if (!is_found || (must_hide_file(conn, path))) {
  11704. mg_send_http_error(conn, 404, "%s", "Not found");
  11705. return;
  11706. }
  11707. /* 12. Directory uris should end with a slash */
  11708. if (file.stat.is_directory && (uri_len > 0)
  11709. && (ri->local_uri[uri_len - 1] != '/')) {
  11710. gmt_time_string(date, sizeof(date), &curtime);
  11711. mg_printf(conn,
  11712. "HTTP/1.1 301 Moved Permanently\r\n"
  11713. "Location: %s/\r\n"
  11714. "Date: %s\r\n"
  11715. /* "Cache-Control: private\r\n" (= default) */
  11716. "Content-Length: 0\r\n"
  11717. "Connection: %s\r\n",
  11718. ri->request_uri,
  11719. date,
  11720. suggest_connection_header(conn));
  11721. send_additional_header(conn);
  11722. mg_printf(conn, "\r\n");
  11723. return;
  11724. }
  11725. /* 13. Handle other methods than GET/HEAD */
  11726. /* 13.1. Handle PROPFIND */
  11727. if (!strcmp(ri->request_method, "PROPFIND")) {
  11728. handle_propfind(conn, path, &file.stat);
  11729. return;
  11730. }
  11731. /* 13.2. Handle OPTIONS for files */
  11732. if (!strcmp(ri->request_method, "OPTIONS")) {
  11733. /* This standard handler is only used for real files.
  11734. * Scripts should support the OPTIONS method themselves, to allow a
  11735. * maximum flexibility.
  11736. * Lua and CGI scripts may fully support CORS this way (including
  11737. * preflights). */
  11738. send_options(conn);
  11739. return;
  11740. }
  11741. /* 13.3. everything but GET and HEAD (e.g. POST) */
  11742. if ((0 != strcmp(ri->request_method, "GET"))
  11743. && (0 != strcmp(ri->request_method, "HEAD"))) {
  11744. mg_send_http_error(conn,
  11745. 405,
  11746. "%s method not allowed",
  11747. conn->request_info.request_method);
  11748. return;
  11749. }
  11750. /* 14. directories */
  11751. if (file.stat.is_directory) {
  11752. /* Substitute files have already been handled above. */
  11753. /* Here we can either generate and send a directory listing,
  11754. * or send an "access denied" error. */
  11755. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11756. "yes")) {
  11757. handle_directory_request(conn, path);
  11758. } else {
  11759. mg_send_http_error(conn,
  11760. 403,
  11761. "%s",
  11762. "Error: Directory listing denied");
  11763. }
  11764. return;
  11765. }
  11766. handle_file_based_request(conn, path, &file);
  11767. #endif /* !defined(NO_FILES) */
  11768. #if 0
  11769. /* Perform redirect and auth checks before calling begin_request()
  11770. * handler.
  11771. * Otherwise, begin_request() would need to perform auth checks and
  11772. * redirects. */
  11773. #endif
  11774. }
  11775. static void
  11776. handle_file_based_request(struct mg_connection *conn,
  11777. const char *path,
  11778. struct mg_file *file)
  11779. {
  11780. if (!conn || !conn->dom_ctx) {
  11781. return;
  11782. }
  11783. if (0) {
  11784. #if defined(USE_LUA)
  11785. } else if (match_prefix(
  11786. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  11787. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  11788. path) > 0) {
  11789. if (is_in_script_path(conn, path)) {
  11790. /* Lua server page: an SSI like page containing mostly plain
  11791. * html
  11792. * code
  11793. * plus some tags with server generated contents. */
  11794. handle_lsp_request(conn, path, file, NULL);
  11795. } else {
  11796. /* Script was in an illegal path */
  11797. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11798. }
  11799. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  11800. strlen(
  11801. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  11802. path) > 0) {
  11803. if (is_in_script_path(conn, path)) {
  11804. /* Lua in-server module script: a CGI like script used to
  11805. * generate
  11806. * the
  11807. * entire reply. */
  11808. mg_exec_lua_script(conn, path, NULL);
  11809. } else {
  11810. /* Script was in an illegal path */
  11811. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11812. }
  11813. #endif
  11814. #if defined(USE_DUKTAPE)
  11815. } else if (match_prefix(
  11816. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  11817. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  11818. path) > 0) {
  11819. if (is_in_script_path(conn, path)) {
  11820. /* Call duktape to generate the page */
  11821. mg_exec_duktape_script(conn, path);
  11822. } else {
  11823. /* Script was in an illegal path */
  11824. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11825. }
  11826. #endif
  11827. #if !defined(NO_CGI)
  11828. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  11829. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  11830. path) > 0) {
  11831. if (is_in_script_path(conn, path)) {
  11832. /* CGI scripts may support all HTTP methods */
  11833. handle_cgi_request(conn, path);
  11834. } else {
  11835. /* Script was in an illegal path */
  11836. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11837. }
  11838. #endif /* !NO_CGI */
  11839. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  11840. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  11841. path) > 0) {
  11842. if (is_in_script_path(conn, path)) {
  11843. handle_ssi_file_request(conn, path, file);
  11844. } else {
  11845. /* Script was in an illegal path */
  11846. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11847. }
  11848. #if !defined(NO_CACHING)
  11849. } else if ((!conn->in_error_handler)
  11850. && is_not_modified(conn, &file->stat)) {
  11851. /* Send 304 "Not Modified" - this must not send any body data */
  11852. handle_not_modified_static_file_request(conn, file);
  11853. #endif /* !NO_CACHING */
  11854. } else {
  11855. handle_static_file_request(conn, path, file, NULL, NULL);
  11856. }
  11857. }
  11858. static void
  11859. close_all_listening_sockets(struct mg_context *ctx)
  11860. {
  11861. unsigned int i;
  11862. if (!ctx) {
  11863. return;
  11864. }
  11865. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11866. closesocket(ctx->listening_sockets[i].sock);
  11867. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  11868. }
  11869. mg_free(ctx->listening_sockets);
  11870. ctx->listening_sockets = NULL;
  11871. mg_free(ctx->listening_socket_fds);
  11872. ctx->listening_socket_fds = NULL;
  11873. }
  11874. /* Valid listening port specification is: [ip_address:]port[s]
  11875. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  11876. * Examples for IPv6: [::]:80, [::1]:80,
  11877. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  11878. * see https://tools.ietf.org/html/rfc3513#section-2.2
  11879. * In order to bind to both, IPv4 and IPv6, you can either add
  11880. * both ports using 8080,[::]:8080, or the short form +8080.
  11881. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  11882. * one only accepting IPv4 the other only IPv6. +8080 creates
  11883. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  11884. * environment, they might work differently, or might not work
  11885. * at all - it must be tested what options work best in the
  11886. * relevant network environment.
  11887. */
  11888. static int
  11889. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  11890. {
  11891. unsigned int a, b, c, d, port;
  11892. int ch, len;
  11893. const char *cb;
  11894. #if defined(USE_IPV6)
  11895. char buf[100] = {0};
  11896. #endif
  11897. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  11898. * Also, all-zeroes in the socket address means binding to all addresses
  11899. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  11900. memset(so, 0, sizeof(*so));
  11901. so->lsa.sin.sin_family = AF_INET;
  11902. *ip_version = 0;
  11903. /* Initialize port and len as invalid. */
  11904. port = 0;
  11905. len = 0;
  11906. /* Test for different ways to format this string */
  11907. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  11908. == 5) {
  11909. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  11910. so->lsa.sin.sin_addr.s_addr =
  11911. htonl((a << 24) | (b << 16) | (c << 8) | d);
  11912. so->lsa.sin.sin_port = htons((uint16_t)port);
  11913. *ip_version = 4;
  11914. #if defined(USE_IPV6)
  11915. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  11916. && mg_inet_pton(
  11917. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  11918. /* IPv6 address, examples: see above */
  11919. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  11920. */
  11921. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11922. *ip_version = 6;
  11923. #endif
  11924. } else if ((vec->ptr[0] == '+')
  11925. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  11926. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  11927. /* Add 1 to len for the + character we skipped before */
  11928. len++;
  11929. #if defined(USE_IPV6)
  11930. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  11931. so->lsa.sin6.sin6_family = AF_INET6;
  11932. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11933. *ip_version = 4 + 6;
  11934. #else
  11935. /* Bind to IPv4 only, since IPv6 is not built in. */
  11936. so->lsa.sin.sin_port = htons((uint16_t)port);
  11937. *ip_version = 4;
  11938. #endif
  11939. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  11940. /* If only port is specified, bind to IPv4, INADDR_ANY */
  11941. so->lsa.sin.sin_port = htons((uint16_t)port);
  11942. *ip_version = 4;
  11943. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  11944. /* Could be a hostname */
  11945. /* Will only work for RFC 952 compliant hostnames,
  11946. * starting with a letter, containing only letters,
  11947. * digits and hyphen ('-'). Newer specs may allow
  11948. * more, but this is not guaranteed here, since it
  11949. * may interfere with rules for port option lists. */
  11950. *(char *)cb = 0; /* Use a const cast here and modify the string.
  11951. * We are going to restore the string later. */
  11952. if (mg_inet_pton(
  11953. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  11954. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11955. *ip_version = 4;
  11956. so->lsa.sin.sin_family = AF_INET;
  11957. so->lsa.sin.sin_port = htons((uint16_t)port);
  11958. len += (int)(cb - vec->ptr) + 1;
  11959. } else {
  11960. port = 0;
  11961. len = 0;
  11962. }
  11963. #if defined(USE_IPV6)
  11964. } else if (mg_inet_pton(AF_INET6,
  11965. vec->ptr,
  11966. &so->lsa.sin6,
  11967. sizeof(so->lsa.sin6))) {
  11968. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11969. *ip_version = 6;
  11970. so->lsa.sin6.sin6_family = AF_INET6;
  11971. so->lsa.sin.sin_port = htons((uint16_t)port);
  11972. len += (int)(cb - vec->ptr) + 1;
  11973. } else {
  11974. port = 0;
  11975. len = 0;
  11976. }
  11977. #endif
  11978. }
  11979. *(char *)cb = ':'; /* restore the string */
  11980. } else {
  11981. /* Parsing failure. */
  11982. }
  11983. /* sscanf and the option splitting code ensure the following condition
  11984. */
  11985. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  11986. *ip_version = 0;
  11987. return 0;
  11988. }
  11989. ch = vec->ptr[len]; /* Next character after the port number */
  11990. so->is_ssl = (ch == 's');
  11991. so->ssl_redir = (ch == 'r');
  11992. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  11993. if (is_valid_port(port)
  11994. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  11995. return 1;
  11996. }
  11997. /* Reset ip_version to 0 of there is an error */
  11998. *ip_version = 0;
  11999. return 0;
  12000. }
  12001. /* Is there any SSL port in use? */
  12002. static int
  12003. is_ssl_port_used(const char *ports)
  12004. {
  12005. if (ports) {
  12006. if (strchr(ports, 's')) {
  12007. return 1;
  12008. }
  12009. if (strchr(ports, 'r')) {
  12010. return 1;
  12011. }
  12012. }
  12013. return 0;
  12014. }
  12015. static int
  12016. set_ports_option(struct mg_context *phys_ctx)
  12017. {
  12018. const char *list;
  12019. int on = 1;
  12020. #if defined(USE_IPV6)
  12021. int off = 0;
  12022. #endif
  12023. struct vec vec;
  12024. struct socket so, *ptr;
  12025. struct pollfd *pfd;
  12026. union usa usa;
  12027. socklen_t len;
  12028. int ip_version;
  12029. int portsTotal = 0;
  12030. int portsOk = 0;
  12031. if (!phys_ctx) {
  12032. return 0;
  12033. }
  12034. memset(&so, 0, sizeof(so));
  12035. memset(&usa, 0, sizeof(usa));
  12036. len = sizeof(usa);
  12037. list = phys_ctx->dd.config[LISTENING_PORTS];
  12038. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12039. portsTotal++;
  12040. if (!parse_port_string(&vec, &so, &ip_version)) {
  12041. mg_cry_internal(
  12042. fc(phys_ctx),
  12043. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12044. (int)vec.len,
  12045. vec.ptr,
  12046. portsTotal,
  12047. "[IP_ADDRESS:]PORT[s|r]");
  12048. continue;
  12049. }
  12050. #if !defined(NO_SSL)
  12051. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12052. mg_cry_internal(fc(phys_ctx),
  12053. "Cannot add SSL socket (entry %i)",
  12054. portsTotal);
  12055. continue;
  12056. }
  12057. #endif
  12058. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12059. == INVALID_SOCKET) {
  12060. mg_cry_internal(fc(phys_ctx),
  12061. "cannot create socket (entry %i)",
  12062. portsTotal);
  12063. continue;
  12064. }
  12065. #if defined(_WIN32)
  12066. /* Windows SO_REUSEADDR lets many procs binds to a
  12067. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12068. * if someone already has the socket -- DTL */
  12069. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12070. * Windows might need a few seconds before
  12071. * the same port can be used again in the
  12072. * same process, so a short Sleep may be
  12073. * required between mg_stop and mg_start.
  12074. */
  12075. if (setsockopt(so.sock,
  12076. SOL_SOCKET,
  12077. SO_EXCLUSIVEADDRUSE,
  12078. (SOCK_OPT_TYPE)&on,
  12079. sizeof(on)) != 0) {
  12080. /* Set reuse option, but don't abort on errors. */
  12081. mg_cry_internal(
  12082. fc(phys_ctx),
  12083. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12084. portsTotal);
  12085. }
  12086. #else
  12087. if (setsockopt(so.sock,
  12088. SOL_SOCKET,
  12089. SO_REUSEADDR,
  12090. (SOCK_OPT_TYPE)&on,
  12091. sizeof(on)) != 0) {
  12092. /* Set reuse option, but don't abort on errors. */
  12093. mg_cry_internal(fc(phys_ctx),
  12094. "cannot set socket option SO_REUSEADDR (entry %i)",
  12095. portsTotal);
  12096. }
  12097. #endif
  12098. if (ip_version > 4) {
  12099. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12100. #if defined(USE_IPV6)
  12101. if (ip_version > 6) {
  12102. if (so.lsa.sa.sa_family == AF_INET6
  12103. && setsockopt(so.sock,
  12104. IPPROTO_IPV6,
  12105. IPV6_V6ONLY,
  12106. (void *)&off,
  12107. sizeof(off)) != 0) {
  12108. /* Set IPv6 only option, but don't abort on errors. */
  12109. mg_cry_internal(
  12110. fc(phys_ctx),
  12111. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12112. portsTotal);
  12113. }
  12114. } else {
  12115. if (so.lsa.sa.sa_family == AF_INET6
  12116. && setsockopt(so.sock,
  12117. IPPROTO_IPV6,
  12118. IPV6_V6ONLY,
  12119. (void *)&on,
  12120. sizeof(on)) != 0) {
  12121. /* Set IPv6 only option, but don't abort on errors. */
  12122. mg_cry_internal(
  12123. fc(phys_ctx),
  12124. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12125. portsTotal);
  12126. }
  12127. }
  12128. #else
  12129. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  12130. closesocket(so.sock);
  12131. so.sock = INVALID_SOCKET;
  12132. continue;
  12133. #endif
  12134. }
  12135. if (so.lsa.sa.sa_family == AF_INET) {
  12136. len = sizeof(so.lsa.sin);
  12137. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12138. mg_cry_internal(fc(phys_ctx),
  12139. "cannot bind to %.*s: %d (%s)",
  12140. (int)vec.len,
  12141. vec.ptr,
  12142. (int)ERRNO,
  12143. strerror(errno));
  12144. closesocket(so.sock);
  12145. so.sock = INVALID_SOCKET;
  12146. continue;
  12147. }
  12148. }
  12149. #if defined(USE_IPV6)
  12150. else if (so.lsa.sa.sa_family == AF_INET6) {
  12151. len = sizeof(so.lsa.sin6);
  12152. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12153. mg_cry_internal(fc(phys_ctx),
  12154. "cannot bind to IPv6 %.*s: %d (%s)",
  12155. (int)vec.len,
  12156. vec.ptr,
  12157. (int)ERRNO,
  12158. strerror(errno));
  12159. closesocket(so.sock);
  12160. so.sock = INVALID_SOCKET;
  12161. continue;
  12162. }
  12163. }
  12164. #endif
  12165. else {
  12166. mg_cry_internal(
  12167. fc(phys_ctx),
  12168. "cannot bind: address family not supported (entry %i)",
  12169. portsTotal);
  12170. closesocket(so.sock);
  12171. so.sock = INVALID_SOCKET;
  12172. continue;
  12173. }
  12174. if (listen(so.sock, SOMAXCONN) != 0) {
  12175. mg_cry_internal(fc(phys_ctx),
  12176. "cannot listen to %.*s: %d (%s)",
  12177. (int)vec.len,
  12178. vec.ptr,
  12179. (int)ERRNO,
  12180. strerror(errno));
  12181. closesocket(so.sock);
  12182. so.sock = INVALID_SOCKET;
  12183. continue;
  12184. }
  12185. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12186. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12187. int err = (int)ERRNO;
  12188. mg_cry_internal(fc(phys_ctx),
  12189. "call to getsockname failed %.*s: %d (%s)",
  12190. (int)vec.len,
  12191. vec.ptr,
  12192. err,
  12193. strerror(errno));
  12194. closesocket(so.sock);
  12195. so.sock = INVALID_SOCKET;
  12196. continue;
  12197. }
  12198. /* Update lsa port in case of random free ports */
  12199. #if defined(USE_IPV6)
  12200. if (so.lsa.sa.sa_family == AF_INET6) {
  12201. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12202. } else
  12203. #endif
  12204. {
  12205. so.lsa.sin.sin_port = usa.sin.sin_port;
  12206. }
  12207. if ((ptr = (struct socket *)
  12208. mg_realloc_ctx(phys_ctx->listening_sockets,
  12209. (phys_ctx->num_listening_sockets + 1)
  12210. * sizeof(phys_ctx->listening_sockets[0]),
  12211. phys_ctx)) == NULL) {
  12212. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12213. closesocket(so.sock);
  12214. so.sock = INVALID_SOCKET;
  12215. continue;
  12216. }
  12217. if ((pfd = (struct pollfd *)
  12218. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12219. (phys_ctx->num_listening_sockets + 1)
  12220. * sizeof(phys_ctx->listening_socket_fds[0]),
  12221. phys_ctx)) == NULL) {
  12222. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12223. closesocket(so.sock);
  12224. so.sock = INVALID_SOCKET;
  12225. mg_free(ptr);
  12226. continue;
  12227. }
  12228. set_close_on_exec(so.sock, fc(phys_ctx));
  12229. phys_ctx->listening_sockets = ptr;
  12230. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12231. phys_ctx->listening_socket_fds = pfd;
  12232. phys_ctx->num_listening_sockets++;
  12233. portsOk++;
  12234. }
  12235. if (portsOk != portsTotal) {
  12236. close_all_listening_sockets(phys_ctx);
  12237. portsOk = 0;
  12238. }
  12239. return portsOk;
  12240. }
  12241. static const char *
  12242. header_val(const struct mg_connection *conn, const char *header)
  12243. {
  12244. const char *header_value;
  12245. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12246. return "-";
  12247. } else {
  12248. return header_value;
  12249. }
  12250. }
  12251. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12252. static void log_access(const struct mg_connection *conn);
  12253. #include "external_log_access.inl"
  12254. #else
  12255. static void
  12256. log_access(const struct mg_connection *conn)
  12257. {
  12258. const struct mg_request_info *ri;
  12259. struct mg_file fi;
  12260. char date[64], src_addr[IP_ADDR_STR_LEN];
  12261. struct tm *tm;
  12262. const char *referer;
  12263. const char *user_agent;
  12264. char buf[4096];
  12265. if (!conn || !conn->dom_ctx) {
  12266. return;
  12267. }
  12268. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12269. if (mg_fopen(conn,
  12270. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12271. MG_FOPEN_MODE_APPEND,
  12272. &fi) == 0) {
  12273. fi.access.fp = NULL;
  12274. }
  12275. } else {
  12276. fi.access.fp = NULL;
  12277. }
  12278. /* Log is written to a file and/or a callback. If both are not set,
  12279. * executing the rest of the function is pointless. */
  12280. if ((fi.access.fp == NULL)
  12281. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12282. return;
  12283. }
  12284. tm = localtime(&conn->conn_birth_time);
  12285. if (tm != NULL) {
  12286. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12287. } else {
  12288. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12289. date[sizeof(date) - 1] = '\0';
  12290. }
  12291. ri = &conn->request_info;
  12292. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12293. referer = header_val(conn, "Referer");
  12294. user_agent = header_val(conn, "User-Agent");
  12295. mg_snprintf(conn,
  12296. NULL, /* Ignore truncation in access log */
  12297. buf,
  12298. sizeof(buf),
  12299. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12300. src_addr,
  12301. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12302. date,
  12303. ri->request_method ? ri->request_method : "-",
  12304. ri->request_uri ? ri->request_uri : "-",
  12305. ri->query_string ? "?" : "",
  12306. ri->query_string ? ri->query_string : "",
  12307. ri->http_version,
  12308. conn->status_code,
  12309. conn->num_bytes_sent,
  12310. referer,
  12311. user_agent);
  12312. if (conn->phys_ctx->callbacks.log_access) {
  12313. conn->phys_ctx->callbacks.log_access(conn, buf);
  12314. }
  12315. if (fi.access.fp) {
  12316. int ok = 1;
  12317. flockfile(fi.access.fp);
  12318. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12319. ok = 0;
  12320. }
  12321. if (fflush(fi.access.fp) != 0) {
  12322. ok = 0;
  12323. }
  12324. funlockfile(fi.access.fp);
  12325. if (mg_fclose(&fi.access) != 0) {
  12326. ok = 0;
  12327. }
  12328. if (!ok) {
  12329. mg_cry_internal(conn,
  12330. "Error writing log file %s",
  12331. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12332. }
  12333. }
  12334. }
  12335. #endif /* Externally provided function */
  12336. /* Verify given socket address against the ACL.
  12337. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12338. */
  12339. static int
  12340. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12341. {
  12342. int allowed, flag;
  12343. uint32_t net, mask;
  12344. struct vec vec;
  12345. if (phys_ctx) {
  12346. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12347. /* If any ACL is set, deny by default */
  12348. allowed = (list == NULL) ? '+' : '-';
  12349. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12350. flag = vec.ptr[0];
  12351. if ((flag != '+' && flag != '-')
  12352. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12353. mg_cry_internal(fc(phys_ctx),
  12354. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12355. __func__);
  12356. return -1;
  12357. }
  12358. if (net == (remote_ip & mask)) {
  12359. allowed = flag;
  12360. }
  12361. }
  12362. return allowed == '+';
  12363. }
  12364. return -1;
  12365. }
  12366. #if !defined(_WIN32)
  12367. static int
  12368. set_uid_option(struct mg_context *phys_ctx)
  12369. {
  12370. int success = 0;
  12371. if (phys_ctx) {
  12372. /* We are currently running as curr_uid. */
  12373. const uid_t curr_uid = getuid();
  12374. /* If set, we want to run as run_as_user. */
  12375. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12376. const struct passwd *to_pw = NULL;
  12377. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12378. /* run_as_user does not exist on the system. We can't proceed
  12379. * further. */
  12380. mg_cry_internal(fc(phys_ctx),
  12381. "%s: unknown user [%s]",
  12382. __func__,
  12383. run_as_user);
  12384. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12385. /* There was either no request to change user, or we're already
  12386. * running as run_as_user. Nothing else to do.
  12387. */
  12388. success = 1;
  12389. } else {
  12390. /* Valid change request. */
  12391. if (setgid(to_pw->pw_gid) == -1) {
  12392. mg_cry_internal(fc(phys_ctx),
  12393. "%s: setgid(%s): %s",
  12394. __func__,
  12395. run_as_user,
  12396. strerror(errno));
  12397. } else if (setgroups(0, NULL) == -1) {
  12398. mg_cry_internal(fc(phys_ctx),
  12399. "%s: setgroups(): %s",
  12400. __func__,
  12401. strerror(errno));
  12402. } else if (setuid(to_pw->pw_uid) == -1) {
  12403. mg_cry_internal(fc(phys_ctx),
  12404. "%s: setuid(%s): %s",
  12405. __func__,
  12406. run_as_user,
  12407. strerror(errno));
  12408. } else {
  12409. success = 1;
  12410. }
  12411. }
  12412. }
  12413. return success;
  12414. }
  12415. #endif /* !_WIN32 */
  12416. static void
  12417. tls_dtor(void *key)
  12418. {
  12419. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12420. /* key == pthread_getspecific(sTlsKey); */
  12421. if (tls) {
  12422. if (tls->is_master == 2) {
  12423. tls->is_master = -3; /* Mark memory as dead */
  12424. mg_free(tls);
  12425. }
  12426. }
  12427. pthread_setspecific(sTlsKey, NULL);
  12428. }
  12429. #if !defined(NO_SSL)
  12430. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12431. struct mg_domain_context *dom_ctx,
  12432. const char *pem,
  12433. const char *chain);
  12434. static const char *ssl_error(void);
  12435. static int
  12436. refresh_trust(struct mg_connection *conn)
  12437. {
  12438. static int reload_lock = 0;
  12439. static long int data_check = 0;
  12440. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12441. struct stat cert_buf;
  12442. long int t;
  12443. const char *pem;
  12444. const char *chain;
  12445. int should_verify_peer;
  12446. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12447. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12448. * refresh_trust still can not work. */
  12449. return 0;
  12450. }
  12451. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12452. if (chain == NULL) {
  12453. /* pem is not NULL here */
  12454. chain = pem;
  12455. }
  12456. if (*chain == 0) {
  12457. chain = NULL;
  12458. }
  12459. t = data_check;
  12460. if (stat(pem, &cert_buf) != -1) {
  12461. t = (long int)cert_buf.st_mtime;
  12462. }
  12463. if (data_check != t) {
  12464. data_check = t;
  12465. should_verify_peer = 0;
  12466. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12467. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12468. == 0) {
  12469. should_verify_peer = 1;
  12470. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12471. "optional") == 0) {
  12472. should_verify_peer = 1;
  12473. }
  12474. }
  12475. if (should_verify_peer) {
  12476. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12477. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12478. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12479. ca_file,
  12480. ca_path) != 1) {
  12481. mg_cry_internal(
  12482. fc(conn->phys_ctx),
  12483. "SSL_CTX_load_verify_locations error: %s "
  12484. "ssl_verify_peer requires setting "
  12485. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12486. "present in "
  12487. "the .conf file?",
  12488. ssl_error());
  12489. return 0;
  12490. }
  12491. }
  12492. if (1 == mg_atomic_inc(p_reload_lock)) {
  12493. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12494. == 0) {
  12495. return 0;
  12496. }
  12497. *p_reload_lock = 0;
  12498. }
  12499. }
  12500. /* lock while cert is reloading */
  12501. while (*p_reload_lock) {
  12502. sleep(1);
  12503. }
  12504. return 1;
  12505. }
  12506. #if defined(OPENSSL_API_1_1)
  12507. #else
  12508. static pthread_mutex_t *ssl_mutexes;
  12509. #endif /* OPENSSL_API_1_1 */
  12510. static int
  12511. sslize(struct mg_connection *conn,
  12512. SSL_CTX *s,
  12513. int (*func)(SSL *),
  12514. volatile int *stop_server)
  12515. {
  12516. int ret, err;
  12517. int short_trust;
  12518. unsigned i;
  12519. if (!conn) {
  12520. return 0;
  12521. }
  12522. short_trust =
  12523. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  12524. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  12525. if (short_trust) {
  12526. int trust_ret = refresh_trust(conn);
  12527. if (!trust_ret) {
  12528. return trust_ret;
  12529. }
  12530. }
  12531. conn->ssl = SSL_new(s);
  12532. if (conn->ssl == NULL) {
  12533. return 0;
  12534. }
  12535. SSL_set_app_data(conn->ssl, (char *)conn);
  12536. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  12537. if (ret != 1) {
  12538. err = SSL_get_error(conn->ssl, ret);
  12539. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  12540. SSL_free(conn->ssl);
  12541. conn->ssl = NULL;
  12542. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12543. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12544. #if !defined(OPENSSL_API_1_1)
  12545. ERR_remove_state(0);
  12546. #endif
  12547. return 0;
  12548. }
  12549. /* SSL functions may fail and require to be called again:
  12550. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  12551. * Here "func" could be SSL_connect or SSL_accept. */
  12552. for (i = 16; i <= 1024; i *= 2) {
  12553. ret = func(conn->ssl);
  12554. if (ret != 1) {
  12555. err = SSL_get_error(conn->ssl, ret);
  12556. if ((err == SSL_ERROR_WANT_CONNECT)
  12557. || (err == SSL_ERROR_WANT_ACCEPT)
  12558. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  12559. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  12560. /* Need to retry the function call "later".
  12561. * See https://linux.die.net/man/3/ssl_get_error
  12562. * This is typical for non-blocking sockets. */
  12563. if (*stop_server) {
  12564. /* Don't wait if the server is going to be stopped. */
  12565. break;
  12566. }
  12567. mg_sleep(i);
  12568. } else if (err == SSL_ERROR_SYSCALL) {
  12569. /* This is an IO error. Look at errno. */
  12570. err = errno;
  12571. mg_cry_internal(conn, "SSL syscall error %i", err);
  12572. break;
  12573. } else {
  12574. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  12575. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  12576. break;
  12577. }
  12578. } else {
  12579. /* success */
  12580. break;
  12581. }
  12582. }
  12583. if (ret != 1) {
  12584. SSL_free(conn->ssl);
  12585. conn->ssl = NULL;
  12586. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12587. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12588. #if !defined(OPENSSL_API_1_1)
  12589. ERR_remove_state(0);
  12590. #endif
  12591. return 0;
  12592. }
  12593. return 1;
  12594. }
  12595. /* Return OpenSSL error message (from CRYPTO lib) */
  12596. static const char *
  12597. ssl_error(void)
  12598. {
  12599. unsigned long err;
  12600. err = ERR_get_error();
  12601. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  12602. }
  12603. static int
  12604. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  12605. {
  12606. int i;
  12607. const char hexdigit[] = "0123456789abcdef";
  12608. if ((memlen <= 0) || (buflen <= 0)) {
  12609. return 0;
  12610. }
  12611. if (buflen < (3 * memlen)) {
  12612. return 0;
  12613. }
  12614. for (i = 0; i < memlen; i++) {
  12615. if (i > 0) {
  12616. buf[3 * i - 1] = ' ';
  12617. }
  12618. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  12619. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  12620. }
  12621. buf[3 * memlen - 1] = 0;
  12622. return 1;
  12623. }
  12624. static void
  12625. ssl_get_client_cert_info(struct mg_connection *conn)
  12626. {
  12627. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  12628. if (cert) {
  12629. char str_subject[1024];
  12630. char str_issuer[1024];
  12631. char str_finger[1024];
  12632. unsigned char buf[256];
  12633. char *str_serial = NULL;
  12634. unsigned int ulen;
  12635. int ilen;
  12636. unsigned char *tmp_buf;
  12637. unsigned char *tmp_p;
  12638. /* Handle to algorithm used for fingerprint */
  12639. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  12640. /* Get Subject and issuer */
  12641. X509_NAME *subj = X509_get_subject_name(cert);
  12642. X509_NAME *iss = X509_get_issuer_name(cert);
  12643. /* Get serial number */
  12644. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  12645. /* Translate serial number to a hex string */
  12646. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  12647. str_serial = BN_bn2hex(serial_bn);
  12648. BN_free(serial_bn);
  12649. /* Translate subject and issuer to a string */
  12650. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  12651. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  12652. /* Calculate SHA1 fingerprint and store as a hex string */
  12653. ulen = 0;
  12654. /* ASN1_digest is deprecated. Do the calculation manually,
  12655. * using EVP_Digest. */
  12656. ilen = i2d_X509(cert, NULL);
  12657. tmp_buf = (ilen > 0)
  12658. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  12659. conn->phys_ctx)
  12660. : NULL;
  12661. if (tmp_buf) {
  12662. tmp_p = tmp_buf;
  12663. (void)i2d_X509(cert, &tmp_p);
  12664. if (!EVP_Digest(
  12665. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  12666. ulen = 0;
  12667. }
  12668. mg_free(tmp_buf);
  12669. }
  12670. if (!hexdump2string(
  12671. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  12672. *str_finger = 0;
  12673. }
  12674. conn->request_info.client_cert = (struct mg_client_cert *)
  12675. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  12676. if (conn->request_info.client_cert) {
  12677. conn->request_info.client_cert->peer_cert = (void *)cert;
  12678. conn->request_info.client_cert->subject =
  12679. mg_strdup_ctx(str_subject, conn->phys_ctx);
  12680. conn->request_info.client_cert->issuer =
  12681. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  12682. conn->request_info.client_cert->serial =
  12683. mg_strdup_ctx(str_serial, conn->phys_ctx);
  12684. conn->request_info.client_cert->finger =
  12685. mg_strdup_ctx(str_finger, conn->phys_ctx);
  12686. } else {
  12687. mg_cry_internal(conn,
  12688. "%s",
  12689. "Out of memory: Cannot allocate memory for client "
  12690. "certificate");
  12691. }
  12692. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  12693. * see https://linux.die.net/man/3/bn_bn2hex */
  12694. OPENSSL_free(str_serial);
  12695. }
  12696. }
  12697. #if defined(OPENSSL_API_1_1)
  12698. #else
  12699. static void
  12700. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  12701. {
  12702. (void)line;
  12703. (void)file;
  12704. if (mode & 1) {
  12705. /* 1 is CRYPTO_LOCK */
  12706. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  12707. } else {
  12708. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  12709. }
  12710. }
  12711. #endif /* OPENSSL_API_1_1 */
  12712. #if !defined(NO_SSL_DL)
  12713. static void *
  12714. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  12715. {
  12716. union {
  12717. void *p;
  12718. void (*fp)(void);
  12719. } u;
  12720. void *dll_handle;
  12721. struct ssl_func *fp;
  12722. int ok;
  12723. int truncated = 0;
  12724. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  12725. mg_snprintf(NULL,
  12726. NULL, /* No truncation check for ebuf */
  12727. ebuf,
  12728. ebuf_len,
  12729. "%s: cannot load %s",
  12730. __func__,
  12731. dll_name);
  12732. return NULL;
  12733. }
  12734. ok = 1;
  12735. for (fp = sw; fp->name != NULL; fp++) {
  12736. #if defined(_WIN32)
  12737. /* GetProcAddress() returns pointer to function */
  12738. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  12739. #else
  12740. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  12741. * pointers to function pointers. We need to use a union to make a
  12742. * cast. */
  12743. u.p = dlsym(dll_handle, fp->name);
  12744. #endif /* _WIN32 */
  12745. if (u.fp == NULL) {
  12746. if (ok) {
  12747. mg_snprintf(NULL,
  12748. &truncated,
  12749. ebuf,
  12750. ebuf_len,
  12751. "%s: %s: cannot find %s",
  12752. __func__,
  12753. dll_name,
  12754. fp->name);
  12755. ok = 0;
  12756. } else {
  12757. size_t cur_len = strlen(ebuf);
  12758. if (!truncated) {
  12759. mg_snprintf(NULL,
  12760. &truncated,
  12761. ebuf + cur_len,
  12762. ebuf_len - cur_len - 3,
  12763. ", %s",
  12764. fp->name);
  12765. if (truncated) {
  12766. /* If truncated, add "..." */
  12767. strcat(ebuf, "...");
  12768. }
  12769. }
  12770. }
  12771. /* Debug:
  12772. * printf("Missing function: %s\n", fp->name); */
  12773. } else {
  12774. fp->ptr = u.fp;
  12775. }
  12776. }
  12777. if (!ok) {
  12778. (void)dlclose(dll_handle);
  12779. return NULL;
  12780. }
  12781. return dll_handle;
  12782. }
  12783. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  12784. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  12785. #endif /* NO_SSL_DL */
  12786. #if defined(SSL_ALREADY_INITIALIZED)
  12787. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  12788. #else
  12789. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  12790. #endif
  12791. static int
  12792. initialize_ssl(char *ebuf, size_t ebuf_len)
  12793. {
  12794. #if defined(OPENSSL_API_1_1)
  12795. if (ebuf_len > 0) {
  12796. ebuf[0] = 0;
  12797. }
  12798. #if !defined(NO_SSL_DL)
  12799. if (!cryptolib_dll_handle) {
  12800. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12801. if (!cryptolib_dll_handle) {
  12802. mg_snprintf(NULL,
  12803. NULL, /* No truncation check for ebuf */
  12804. ebuf,
  12805. ebuf_len,
  12806. "%s: error loading library %s",
  12807. __func__,
  12808. CRYPTO_LIB);
  12809. DEBUG_TRACE("%s", ebuf);
  12810. return 0;
  12811. }
  12812. }
  12813. #endif /* NO_SSL_DL */
  12814. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12815. return 1;
  12816. }
  12817. #else /* not OPENSSL_API_1_1 */
  12818. int i;
  12819. size_t size;
  12820. if (ebuf_len > 0) {
  12821. ebuf[0] = 0;
  12822. }
  12823. #if !defined(NO_SSL_DL)
  12824. if (!cryptolib_dll_handle) {
  12825. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12826. if (!cryptolib_dll_handle) {
  12827. mg_snprintf(NULL,
  12828. NULL, /* No truncation check for ebuf */
  12829. ebuf,
  12830. ebuf_len,
  12831. "%s: error loading library %s",
  12832. __func__,
  12833. CRYPTO_LIB);
  12834. DEBUG_TRACE("%s", ebuf);
  12835. return 0;
  12836. }
  12837. }
  12838. #endif /* NO_SSL_DL */
  12839. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12840. return 1;
  12841. }
  12842. /* Initialize locking callbacks, needed for thread safety.
  12843. * http://www.openssl.org/support/faq.html#PROG1
  12844. */
  12845. i = CRYPTO_num_locks();
  12846. if (i < 0) {
  12847. i = 0;
  12848. }
  12849. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  12850. if (size == 0) {
  12851. ssl_mutexes = NULL;
  12852. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  12853. mg_snprintf(NULL,
  12854. NULL, /* No truncation check for ebuf */
  12855. ebuf,
  12856. ebuf_len,
  12857. "%s: cannot allocate mutexes: %s",
  12858. __func__,
  12859. ssl_error());
  12860. DEBUG_TRACE("%s", ebuf);
  12861. return 0;
  12862. }
  12863. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12864. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  12865. }
  12866. CRYPTO_set_locking_callback(&ssl_locking_callback);
  12867. CRYPTO_set_id_callback(&mg_current_thread_id);
  12868. #endif /* OPENSSL_API_1_1 */
  12869. #if !defined(NO_SSL_DL)
  12870. if (!ssllib_dll_handle) {
  12871. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  12872. if (!ssllib_dll_handle) {
  12873. DEBUG_TRACE("%s", ebuf);
  12874. return 0;
  12875. }
  12876. }
  12877. #endif /* NO_SSL_DL */
  12878. #if defined(OPENSSL_API_1_1)
  12879. /* Initialize SSL library */
  12880. OPENSSL_init_ssl(0, NULL);
  12881. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  12882. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  12883. NULL);
  12884. #else
  12885. /* Initialize SSL library */
  12886. SSL_library_init();
  12887. SSL_load_error_strings();
  12888. #endif
  12889. return 1;
  12890. }
  12891. static int
  12892. ssl_use_pem_file(struct mg_context *phys_ctx,
  12893. struct mg_domain_context *dom_ctx,
  12894. const char *pem,
  12895. const char *chain)
  12896. {
  12897. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  12898. mg_cry_internal(fc(phys_ctx),
  12899. "%s: cannot open certificate file %s: %s",
  12900. __func__,
  12901. pem,
  12902. ssl_error());
  12903. return 0;
  12904. }
  12905. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  12906. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  12907. mg_cry_internal(fc(phys_ctx),
  12908. "%s: cannot open private key file %s: %s",
  12909. __func__,
  12910. pem,
  12911. ssl_error());
  12912. return 0;
  12913. }
  12914. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  12915. mg_cry_internal(fc(phys_ctx),
  12916. "%s: certificate and private key do not match: %s",
  12917. __func__,
  12918. pem);
  12919. return 0;
  12920. }
  12921. /* In contrast to OpenSSL, wolfSSL does not support certificate
  12922. * chain files that contain private keys and certificates in
  12923. * SSL_CTX_use_certificate_chain_file.
  12924. * The CivetWeb-Server used pem-Files that contained both information.
  12925. * In order to make wolfSSL work, it is split in two files.
  12926. * One file that contains key and certificate used by the server and
  12927. * an optional chain file for the ssl stack.
  12928. */
  12929. if (chain) {
  12930. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  12931. mg_cry_internal(fc(phys_ctx),
  12932. "%s: cannot use certificate chain file %s: %s",
  12933. __func__,
  12934. pem,
  12935. ssl_error());
  12936. return 0;
  12937. }
  12938. }
  12939. return 1;
  12940. }
  12941. #if defined(OPENSSL_API_1_1)
  12942. static unsigned long
  12943. ssl_get_protocol(int version_id)
  12944. {
  12945. long unsigned ret = SSL_OP_ALL;
  12946. if (version_id > 0)
  12947. ret |= SSL_OP_NO_SSLv2;
  12948. if (version_id > 1)
  12949. ret |= SSL_OP_NO_SSLv3;
  12950. if (version_id > 2)
  12951. ret |= SSL_OP_NO_TLSv1;
  12952. if (version_id > 3)
  12953. ret |= SSL_OP_NO_TLSv1_1;
  12954. return ret;
  12955. }
  12956. #else
  12957. static long
  12958. ssl_get_protocol(int version_id)
  12959. {
  12960. long ret = SSL_OP_ALL;
  12961. if (version_id > 0)
  12962. ret |= SSL_OP_NO_SSLv2;
  12963. if (version_id > 1)
  12964. ret |= SSL_OP_NO_SSLv3;
  12965. if (version_id > 2)
  12966. ret |= SSL_OP_NO_TLSv1;
  12967. if (version_id > 3)
  12968. ret |= SSL_OP_NO_TLSv1_1;
  12969. return ret;
  12970. }
  12971. #endif /* OPENSSL_API_1_1 */
  12972. /* SSL callback documentation:
  12973. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  12974. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  12975. * https://linux.die.net/man/3/ssl_set_info_callback */
  12976. /* Note: There is no "const" for the first argument in the documentation,
  12977. * however some (maybe most, but not all) headers of OpenSSL versions /
  12978. * OpenSSL compatibility layers have it. Having a different definition
  12979. * will cause a warning in C and an error in C++. With inconsitent
  12980. * definitions of this function, having a warning in one version or
  12981. * another is unavoidable. */
  12982. static void
  12983. ssl_info_callback(SSL *ssl, int what, int ret)
  12984. {
  12985. (void)ret;
  12986. if (what & SSL_CB_HANDSHAKE_START) {
  12987. SSL_get_app_data(ssl);
  12988. }
  12989. if (what & SSL_CB_HANDSHAKE_DONE) {
  12990. /* TODO: check for openSSL 1.1 */
  12991. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  12992. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  12993. }
  12994. }
  12995. static int
  12996. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  12997. {
  12998. struct mg_context *ctx = (struct mg_context *)arg;
  12999. struct mg_domain_context *dom =
  13000. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13001. #if defined(__GNUC__) || defined(__MINGW32__)
  13002. #pragma GCC diagnostic push
  13003. #pragma GCC diagnostic ignored "-Wcast-align"
  13004. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13005. /* We used an aligned pointer in SSL_set_app_data */
  13006. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13007. #if defined(__GNUC__) || defined(__MINGW32__)
  13008. #pragma GCC diagnostic pop
  13009. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13010. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13011. (void)ad;
  13012. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13013. DEBUG_TRACE("%s", "internal error - assertion failed");
  13014. return SSL_TLSEXT_ERR_NOACK;
  13015. }
  13016. /* Old clients (Win XP) will not support SNI. Then, there
  13017. * is no server name available in the request - we can
  13018. * only work with the default certificate.
  13019. * Multiple HTTPS hosts on one IP+port are only possible
  13020. * with a certificate containing all alternative names.
  13021. */
  13022. if ((servername == NULL) || (*servername == 0)) {
  13023. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13024. conn->dom_ctx = &(ctx->dd);
  13025. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13026. return SSL_TLSEXT_ERR_NOACK;
  13027. }
  13028. DEBUG_TRACE("TLS connection to host %s", servername);
  13029. while (dom) {
  13030. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13031. /* Found matching domain */
  13032. DEBUG_TRACE("TLS domain %s found",
  13033. dom->config[AUTHENTICATION_DOMAIN]);
  13034. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13035. conn->dom_ctx = dom;
  13036. return SSL_TLSEXT_ERR_OK;
  13037. }
  13038. dom = dom->next;
  13039. }
  13040. /* Default domain */
  13041. DEBUG_TRACE("TLS default domain %s used",
  13042. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13043. conn->dom_ctx = &(ctx->dd);
  13044. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13045. return SSL_TLSEXT_ERR_OK;
  13046. }
  13047. /* Setup SSL CTX as required by CivetWeb */
  13048. static int
  13049. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13050. struct mg_domain_context *dom_ctx,
  13051. const char *pem,
  13052. const char *chain)
  13053. {
  13054. int callback_ret;
  13055. int should_verify_peer;
  13056. int peer_certificate_optional;
  13057. const char *ca_path;
  13058. const char *ca_file;
  13059. int use_default_verify_paths;
  13060. int verify_depth;
  13061. struct timespec now_mt;
  13062. md5_byte_t ssl_context_id[16];
  13063. md5_state_t md5state;
  13064. int protocol_ver;
  13065. #if defined(OPENSSL_API_1_1)
  13066. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13067. mg_cry_internal(fc(phys_ctx),
  13068. "SSL_CTX_new (server) error: %s",
  13069. ssl_error());
  13070. return 0;
  13071. }
  13072. #else
  13073. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13074. mg_cry_internal(fc(phys_ctx),
  13075. "SSL_CTX_new (server) error: %s",
  13076. ssl_error());
  13077. return 0;
  13078. }
  13079. #endif /* OPENSSL_API_1_1 */
  13080. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13081. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13082. | SSL_OP_NO_TLSv1_1);
  13083. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13084. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13085. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13086. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13087. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13088. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13089. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13090. #if !defined(NO_SSL_DL)
  13091. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13092. #endif /* NO_SSL_DL */
  13093. #if defined(__clang__)
  13094. #pragma clang diagnostic push
  13095. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  13096. #endif
  13097. /* Depending on the OpenSSL version, the callback may be
  13098. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  13099. * yielding in an "incompatible-pointer-type" warning for the other
  13100. * version. It seems to be "unclear" what is correct:
  13101. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13102. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13103. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13104. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13105. * Disable this warning here.
  13106. * Alternative would be a version dependent ssl_info_callback and
  13107. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  13108. */
  13109. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13110. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13111. ssl_servername_callback);
  13112. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13113. #if defined(__clang__)
  13114. #pragma clang diagnostic pop
  13115. #endif
  13116. /* If a callback has been specified, call it. */
  13117. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13118. ? 0
  13119. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13120. phys_ctx->user_data));
  13121. /* If callback returns 0, civetweb sets up the SSL certificate.
  13122. * If it returns 1, civetweb assumes the calback already did this.
  13123. * If it returns -1, initializing ssl fails. */
  13124. if (callback_ret < 0) {
  13125. mg_cry_internal(fc(phys_ctx),
  13126. "SSL callback returned error: %i",
  13127. callback_ret);
  13128. return 0;
  13129. }
  13130. if (callback_ret > 0) {
  13131. /* Callback did everything. */
  13132. return 1;
  13133. }
  13134. /* Use some combination of start time, domain and port as a SSL
  13135. * context ID. This should be unique on the current machine. */
  13136. md5_init(&md5state);
  13137. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13138. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13139. md5_append(&md5state,
  13140. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13141. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13142. md5_append(&md5state,
  13143. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13144. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13145. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13146. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13147. md5_finish(&md5state, ssl_context_id);
  13148. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13149. (unsigned char *)ssl_context_id,
  13150. sizeof(ssl_context_id));
  13151. if (pem != NULL) {
  13152. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13153. return 0;
  13154. }
  13155. }
  13156. /* Should we support client certificates? */
  13157. /* Default is "no". */
  13158. should_verify_peer = 0;
  13159. peer_certificate_optional = 0;
  13160. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13161. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13162. /* Yes, they are mandatory */
  13163. should_verify_peer = 1;
  13164. peer_certificate_optional = 0;
  13165. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13166. "optional") == 0) {
  13167. /* Yes, they are optional */
  13168. should_verify_peer = 1;
  13169. peer_certificate_optional = 1;
  13170. }
  13171. }
  13172. use_default_verify_paths =
  13173. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13174. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13175. == 0);
  13176. if (should_verify_peer) {
  13177. ca_path = dom_ctx->config[SSL_CA_PATH];
  13178. ca_file = dom_ctx->config[SSL_CA_FILE];
  13179. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13180. != 1) {
  13181. mg_cry_internal(fc(phys_ctx),
  13182. "SSL_CTX_load_verify_locations error: %s "
  13183. "ssl_verify_peer requires setting "
  13184. "either ssl_ca_path or ssl_ca_file. "
  13185. "Is any of them present in the "
  13186. ".conf file?",
  13187. ssl_error());
  13188. return 0;
  13189. }
  13190. if (peer_certificate_optional) {
  13191. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13192. } else {
  13193. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13194. SSL_VERIFY_PEER
  13195. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13196. NULL);
  13197. }
  13198. if (use_default_verify_paths
  13199. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13200. mg_cry_internal(fc(phys_ctx),
  13201. "SSL_CTX_set_default_verify_paths error: %s",
  13202. ssl_error());
  13203. return 0;
  13204. }
  13205. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13206. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13207. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13208. }
  13209. }
  13210. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13211. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13212. dom_ctx->config[SSL_CIPHER_LIST]) != 1) {
  13213. mg_cry_internal(fc(phys_ctx),
  13214. "SSL_CTX_set_cipher_list error: %s",
  13215. ssl_error());
  13216. }
  13217. }
  13218. return 1;
  13219. }
  13220. /* Check if SSL is required.
  13221. * If so, dynamically load SSL library
  13222. * and set up ctx->ssl_ctx pointer. */
  13223. static int
  13224. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13225. {
  13226. void *ssl_ctx = 0;
  13227. int callback_ret;
  13228. const char *pem;
  13229. const char *chain;
  13230. char ebuf[128];
  13231. if (!phys_ctx) {
  13232. return 0;
  13233. }
  13234. if (!dom_ctx) {
  13235. dom_ctx = &(phys_ctx->dd);
  13236. }
  13237. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13238. /* No SSL port is set. No need to setup SSL. */
  13239. return 1;
  13240. }
  13241. /* Check for external SSL_CTX */
  13242. callback_ret =
  13243. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13244. ? 0
  13245. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13246. phys_ctx->user_data));
  13247. if (callback_ret < 0) {
  13248. mg_cry_internal(fc(phys_ctx),
  13249. "external_ssl_ctx callback returned error: %i",
  13250. callback_ret);
  13251. return 0;
  13252. } else if (callback_ret > 0) {
  13253. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13254. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13255. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13256. return 0;
  13257. }
  13258. return 1;
  13259. }
  13260. /* else: external_ssl_ctx does not exist or returns 0,
  13261. * CivetWeb should continue initializing SSL */
  13262. /* If PEM file is not specified and the init_ssl callback
  13263. * is not specified, setup will fail. */
  13264. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13265. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13266. /* No certificate and no callback:
  13267. * Essential data to set up TLS is missing.
  13268. */
  13269. mg_cry_internal(fc(phys_ctx),
  13270. "Initializing SSL failed: -%s is not set",
  13271. config_options[SSL_CERTIFICATE].name);
  13272. return 0;
  13273. }
  13274. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13275. if (chain == NULL) {
  13276. chain = pem;
  13277. }
  13278. if ((chain != NULL) && (*chain == 0)) {
  13279. chain = NULL;
  13280. }
  13281. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13282. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13283. return 0;
  13284. }
  13285. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13286. }
  13287. static void
  13288. uninitialize_ssl(void)
  13289. {
  13290. #if defined(OPENSSL_API_1_1)
  13291. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13292. /* Shutdown according to
  13293. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13294. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13295. */
  13296. CONF_modules_unload(1);
  13297. #else
  13298. int i;
  13299. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13300. /* Shutdown according to
  13301. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13302. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13303. */
  13304. CRYPTO_set_locking_callback(NULL);
  13305. CRYPTO_set_id_callback(NULL);
  13306. ENGINE_cleanup();
  13307. CONF_modules_unload(1);
  13308. ERR_free_strings();
  13309. EVP_cleanup();
  13310. CRYPTO_cleanup_all_ex_data();
  13311. ERR_remove_state(0);
  13312. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13313. pthread_mutex_destroy(&ssl_mutexes[i]);
  13314. }
  13315. mg_free(ssl_mutexes);
  13316. ssl_mutexes = NULL;
  13317. #endif /* OPENSSL_API_1_1 */
  13318. }
  13319. }
  13320. #endif /* !NO_SSL */
  13321. static int
  13322. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13323. {
  13324. if (phys_ctx) {
  13325. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13326. const char *path;
  13327. if (!dom_ctx) {
  13328. dom_ctx = &(phys_ctx->dd);
  13329. }
  13330. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13331. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  13332. mg_cry_internal(fc(phys_ctx),
  13333. "Cannot open %s: %s",
  13334. path,
  13335. strerror(ERRNO));
  13336. return 0;
  13337. }
  13338. return 1;
  13339. }
  13340. return 0;
  13341. }
  13342. static int
  13343. set_acl_option(struct mg_context *phys_ctx)
  13344. {
  13345. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13346. }
  13347. static void
  13348. reset_per_request_attributes(struct mg_connection *conn)
  13349. {
  13350. if (!conn) {
  13351. return;
  13352. }
  13353. conn->connection_type =
  13354. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13355. conn->num_bytes_sent = conn->consumed_content = 0;
  13356. conn->path_info = NULL;
  13357. conn->status_code = -1;
  13358. conn->content_len = -1;
  13359. conn->is_chunked = 0;
  13360. conn->must_close = 0;
  13361. conn->request_len = 0;
  13362. conn->throttle = 0;
  13363. conn->data_len = 0;
  13364. conn->chunk_remainder = 0;
  13365. conn->accept_gzip = 0;
  13366. conn->response_info.content_length = conn->request_info.content_length = -1;
  13367. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13368. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13369. conn->response_info.status_text = NULL;
  13370. conn->response_info.status_code = 0;
  13371. conn->request_info.remote_user = NULL;
  13372. conn->request_info.request_method = NULL;
  13373. conn->request_info.request_uri = NULL;
  13374. conn->request_info.local_uri = NULL;
  13375. #if defined(MG_LEGACY_INTERFACE)
  13376. /* Legacy before split into local_uri and request_uri */
  13377. conn->request_info.uri = NULL;
  13378. #endif
  13379. }
  13380. #if 0
  13381. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13382. * Leave this function here (commented out) for reference until
  13383. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13384. * no longer required.
  13385. */
  13386. static int
  13387. set_sock_timeout(SOCKET sock, int milliseconds)
  13388. {
  13389. int r0 = 0, r1, r2;
  13390. #if defined(_WIN32)
  13391. /* Windows specific */
  13392. DWORD tv = (DWORD)milliseconds;
  13393. #else
  13394. /* Linux, ... (not Windows) */
  13395. struct timeval tv;
  13396. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13397. * max. time waiting for the acknowledged of TCP data before the connection
  13398. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13399. * If this option is not set, the default timeout of 20-30 minutes is used.
  13400. */
  13401. /* #define TCP_USER_TIMEOUT (18) */
  13402. #if defined(TCP_USER_TIMEOUT)
  13403. unsigned int uto = (unsigned int)milliseconds;
  13404. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13405. #endif
  13406. memset(&tv, 0, sizeof(tv));
  13407. tv.tv_sec = milliseconds / 1000;
  13408. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13409. #endif /* _WIN32 */
  13410. r1 = setsockopt(
  13411. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13412. r2 = setsockopt(
  13413. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13414. return r0 || r1 || r2;
  13415. }
  13416. #endif
  13417. static int
  13418. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13419. {
  13420. if (setsockopt(sock,
  13421. IPPROTO_TCP,
  13422. TCP_NODELAY,
  13423. (SOCK_OPT_TYPE)&nodelay_on,
  13424. sizeof(nodelay_on)) != 0) {
  13425. /* Error */
  13426. return 1;
  13427. }
  13428. /* OK */
  13429. return 0;
  13430. }
  13431. static void
  13432. close_socket_gracefully(struct mg_connection *conn)
  13433. {
  13434. #if defined(_WIN32)
  13435. char buf[MG_BUF_LEN];
  13436. int n;
  13437. #endif
  13438. struct linger linger;
  13439. int error_code = 0;
  13440. int linger_timeout = -2;
  13441. socklen_t opt_len = sizeof(error_code);
  13442. if (!conn) {
  13443. return;
  13444. }
  13445. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13446. * "Note that enabling a nonzero timeout on a nonblocking socket
  13447. * is not recommended.", so set it to blocking now */
  13448. set_blocking_mode(conn->client.sock);
  13449. /* Send FIN to the client */
  13450. shutdown(conn->client.sock, SHUTDOWN_WR);
  13451. #if defined(_WIN32)
  13452. /* Read and discard pending incoming data. If we do not do that and
  13453. * close
  13454. * the socket, the data in the send buffer may be discarded. This
  13455. * behaviour is seen on Windows, when client keeps sending data
  13456. * when server decides to close the connection; then when client
  13457. * does recv() it gets no data back. */
  13458. do {
  13459. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13460. } while (n > 0);
  13461. #endif
  13462. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13463. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13464. }
  13465. /* Set linger option according to configuration */
  13466. if (linger_timeout >= 0) {
  13467. /* Set linger option to avoid socket hanging out after close. This
  13468. * prevent ephemeral port exhaust problem under high QPS. */
  13469. linger.l_onoff = 1;
  13470. #if defined(_MSC_VER)
  13471. #pragma warning(push)
  13472. #pragma warning(disable : 4244)
  13473. #endif
  13474. #if defined(__GNUC__) || defined(__MINGW32__)
  13475. #pragma GCC diagnostic push
  13476. #pragma GCC diagnostic ignored "-Wconversion"
  13477. #endif
  13478. /* Data type of linger structure elements may differ,
  13479. * so we don't know what cast we need here.
  13480. * Disable type conversion warnings. */
  13481. linger.l_linger = (linger_timeout + 999) / 1000;
  13482. #if defined(__GNUC__) || defined(__MINGW32__)
  13483. #pragma GCC diagnostic pop
  13484. #endif
  13485. #if defined(_MSC_VER)
  13486. #pragma warning(pop)
  13487. #endif
  13488. } else {
  13489. linger.l_onoff = 0;
  13490. linger.l_linger = 0;
  13491. }
  13492. if (linger_timeout < -1) {
  13493. /* Default: don't configure any linger */
  13494. } else if (getsockopt(conn->client.sock,
  13495. SOL_SOCKET,
  13496. SO_ERROR,
  13497. #if defined(_WIN32) /* WinSock uses different data type here */
  13498. (char *)&error_code,
  13499. #else
  13500. &error_code,
  13501. #endif
  13502. &opt_len) != 0) {
  13503. /* Cannot determine if socket is already closed. This should
  13504. * not occur and never did in a test. Log an error message
  13505. * and continue. */
  13506. mg_cry_internal(conn,
  13507. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  13508. __func__,
  13509. strerror(ERRNO));
  13510. } else if (error_code == ECONNRESET) {
  13511. /* Socket already closed by client/peer, close socket without linger
  13512. */
  13513. } else {
  13514. /* Set linger timeout */
  13515. if (setsockopt(conn->client.sock,
  13516. SOL_SOCKET,
  13517. SO_LINGER,
  13518. (char *)&linger,
  13519. sizeof(linger)) != 0) {
  13520. mg_cry_internal(
  13521. conn,
  13522. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  13523. __func__,
  13524. linger.l_onoff,
  13525. linger.l_linger,
  13526. strerror(ERRNO));
  13527. }
  13528. }
  13529. /* Now we know that our FIN is ACK-ed, safe to close */
  13530. closesocket(conn->client.sock);
  13531. conn->client.sock = INVALID_SOCKET;
  13532. }
  13533. static void
  13534. close_connection(struct mg_connection *conn)
  13535. {
  13536. #if defined(USE_SERVER_STATS)
  13537. conn->conn_state = 6; /* to close */
  13538. #endif
  13539. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13540. if (conn->lua_websocket_state) {
  13541. lua_websocket_close(conn, conn->lua_websocket_state);
  13542. conn->lua_websocket_state = NULL;
  13543. }
  13544. #endif
  13545. mg_lock_connection(conn);
  13546. /* Set close flag, so keep-alive loops will stop */
  13547. conn->must_close = 1;
  13548. /* call the connection_close callback if assigned */
  13549. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  13550. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13551. conn->phys_ctx->callbacks.connection_close(conn);
  13552. }
  13553. }
  13554. /* Reset user data, after close callback is called.
  13555. * Do not reuse it. If the user needs a destructor,
  13556. * it must be done in the connection_close callback. */
  13557. mg_set_user_connection_data(conn, NULL);
  13558. #if defined(USE_SERVER_STATS)
  13559. conn->conn_state = 7; /* closing */
  13560. #endif
  13561. #if !defined(NO_SSL)
  13562. if (conn->ssl != NULL) {
  13563. /* Run SSL_shutdown twice to ensure completely close SSL connection
  13564. */
  13565. SSL_shutdown(conn->ssl);
  13566. SSL_free(conn->ssl);
  13567. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  13568. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  13569. #if !defined(OPENSSL_API_1_1)
  13570. ERR_remove_state(0);
  13571. #endif
  13572. conn->ssl = NULL;
  13573. }
  13574. #endif
  13575. if (conn->client.sock != INVALID_SOCKET) {
  13576. close_socket_gracefully(conn);
  13577. conn->client.sock = INVALID_SOCKET;
  13578. }
  13579. if (conn->host) {
  13580. mg_free((void *)conn->host);
  13581. conn->host = NULL;
  13582. }
  13583. mg_unlock_connection(conn);
  13584. #if defined(USE_SERVER_STATS)
  13585. conn->conn_state = 8; /* closed */
  13586. #endif
  13587. }
  13588. void
  13589. mg_close_connection(struct mg_connection *conn)
  13590. {
  13591. #if defined(USE_WEBSOCKET)
  13592. struct mg_context *client_ctx = NULL;
  13593. #endif /* defined(USE_WEBSOCKET) */
  13594. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  13595. return;
  13596. }
  13597. #if defined(USE_WEBSOCKET)
  13598. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13599. if (conn->in_websocket_handling) {
  13600. /* Set close flag, so the server thread can exit. */
  13601. conn->must_close = 1;
  13602. return;
  13603. }
  13604. }
  13605. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  13606. unsigned int i;
  13607. /* ws/wss client */
  13608. client_ctx = conn->phys_ctx;
  13609. /* client context: loops must end */
  13610. client_ctx->stop_flag = 1;
  13611. conn->must_close = 1;
  13612. /* We need to get the client thread out of the select/recv call
  13613. * here. */
  13614. /* Since we use a sleep quantum of some seconds to check for recv
  13615. * timeouts, we will just wait a few seconds in mg_join_thread. */
  13616. /* join worker thread */
  13617. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  13618. if (client_ctx->worker_threadids[i] != 0) {
  13619. mg_join_thread(client_ctx->worker_threadids[i]);
  13620. }
  13621. }
  13622. }
  13623. #endif /* defined(USE_WEBSOCKET) */
  13624. close_connection(conn);
  13625. #if !defined(NO_SSL)
  13626. if (conn->client_ssl_ctx != NULL) {
  13627. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  13628. }
  13629. #endif
  13630. #if defined(USE_WEBSOCKET)
  13631. if (client_ctx != NULL) {
  13632. /* free context */
  13633. mg_free(client_ctx->worker_threadids);
  13634. mg_free(client_ctx);
  13635. (void)pthread_mutex_destroy(&conn->mutex);
  13636. mg_free(conn);
  13637. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  13638. mg_free(conn);
  13639. }
  13640. #else
  13641. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  13642. mg_free(conn);
  13643. }
  13644. #endif /* defined(USE_WEBSOCKET) */
  13645. }
  13646. /* Only for memory statistics */
  13647. static struct mg_context common_client_context;
  13648. static struct mg_connection *
  13649. mg_connect_client_impl(const struct mg_client_options *client_options,
  13650. int use_ssl,
  13651. char *ebuf,
  13652. size_t ebuf_len)
  13653. {
  13654. struct mg_connection *conn = NULL;
  13655. SOCKET sock;
  13656. union usa sa;
  13657. struct sockaddr *psa;
  13658. socklen_t len;
  13659. unsigned max_req_size =
  13660. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  13661. /* Size of structures, aligned to 8 bytes */
  13662. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  13663. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  13664. conn = (struct mg_connection *)mg_calloc_ctx(1,
  13665. conn_size + ctx_size
  13666. + max_req_size,
  13667. &common_client_context);
  13668. if (conn == NULL) {
  13669. mg_snprintf(NULL,
  13670. NULL, /* No truncation check for ebuf */
  13671. ebuf,
  13672. ebuf_len,
  13673. "calloc(): %s",
  13674. strerror(ERRNO));
  13675. return NULL;
  13676. }
  13677. #if defined(__GNUC__) || defined(__MINGW32__)
  13678. #pragma GCC diagnostic push
  13679. #pragma GCC diagnostic ignored "-Wcast-align"
  13680. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13681. /* conn_size is aligned to 8 bytes */
  13682. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  13683. #if defined(__GNUC__) || defined(__MINGW32__)
  13684. #pragma GCC diagnostic pop
  13685. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13686. conn->buf = (((char *)conn) + conn_size + ctx_size);
  13687. conn->buf_size = (int)max_req_size;
  13688. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  13689. conn->dom_ctx = &(conn->phys_ctx->dd);
  13690. if (!connect_socket(&common_client_context,
  13691. client_options->host,
  13692. client_options->port,
  13693. use_ssl,
  13694. ebuf,
  13695. ebuf_len,
  13696. &sock,
  13697. &sa)) {
  13698. /* ebuf is set by connect_socket,
  13699. * free all memory and return NULL; */
  13700. mg_free(conn);
  13701. return NULL;
  13702. }
  13703. #if !defined(NO_SSL)
  13704. #if defined(OPENSSL_API_1_1)
  13705. if (use_ssl
  13706. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  13707. mg_snprintf(NULL,
  13708. NULL, /* No truncation check for ebuf */
  13709. ebuf,
  13710. ebuf_len,
  13711. "SSL_CTX_new error");
  13712. closesocket(sock);
  13713. mg_free(conn);
  13714. return NULL;
  13715. }
  13716. #else
  13717. if (use_ssl
  13718. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  13719. == NULL) {
  13720. mg_snprintf(NULL,
  13721. NULL, /* No truncation check for ebuf */
  13722. ebuf,
  13723. ebuf_len,
  13724. "SSL_CTX_new error");
  13725. closesocket(sock);
  13726. mg_free(conn);
  13727. return NULL;
  13728. }
  13729. #endif /* OPENSSL_API_1_1 */
  13730. #endif /* NO_SSL */
  13731. #if defined(USE_IPV6)
  13732. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  13733. : sizeof(conn->client.rsa.sin6);
  13734. psa = (sa.sa.sa_family == AF_INET)
  13735. ? (struct sockaddr *)&(conn->client.rsa.sin)
  13736. : (struct sockaddr *)&(conn->client.rsa.sin6);
  13737. #else
  13738. len = sizeof(conn->client.rsa.sin);
  13739. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  13740. #endif
  13741. conn->client.sock = sock;
  13742. conn->client.lsa = sa;
  13743. if (getsockname(sock, psa, &len) != 0) {
  13744. mg_cry_internal(conn,
  13745. "%s: getsockname() failed: %s",
  13746. __func__,
  13747. strerror(ERRNO));
  13748. }
  13749. conn->client.is_ssl = use_ssl ? 1 : 0;
  13750. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13751. #if !defined(NO_SSL)
  13752. if (use_ssl) {
  13753. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  13754. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  13755. * SSL_CTX_set_verify call is needed to switch off server
  13756. * certificate checking, which is off by default in OpenSSL and
  13757. * on in yaSSL. */
  13758. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  13759. * SSL_VERIFY_PEER, verify_ssl_server); */
  13760. if (client_options->client_cert) {
  13761. if (!ssl_use_pem_file(&common_client_context,
  13762. &(common_client_context.dd),
  13763. client_options->client_cert,
  13764. NULL)) {
  13765. mg_snprintf(NULL,
  13766. NULL, /* No truncation check for ebuf */
  13767. ebuf,
  13768. ebuf_len,
  13769. "Can not use SSL client certificate");
  13770. SSL_CTX_free(conn->client_ssl_ctx);
  13771. closesocket(sock);
  13772. mg_free(conn);
  13773. return NULL;
  13774. }
  13775. }
  13776. if (client_options->server_cert) {
  13777. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  13778. client_options->server_cert,
  13779. NULL);
  13780. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  13781. } else {
  13782. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  13783. }
  13784. if (!sslize(conn,
  13785. conn->client_ssl_ctx,
  13786. SSL_connect,
  13787. &(conn->phys_ctx->stop_flag))) {
  13788. mg_snprintf(NULL,
  13789. NULL, /* No truncation check for ebuf */
  13790. ebuf,
  13791. ebuf_len,
  13792. "SSL connection error");
  13793. SSL_CTX_free(conn->client_ssl_ctx);
  13794. closesocket(sock);
  13795. mg_free(conn);
  13796. return NULL;
  13797. }
  13798. }
  13799. #endif
  13800. if (0 != set_non_blocking_mode(sock)) {
  13801. mg_cry_internal(conn,
  13802. "Cannot set non-blocking mode for client %s:%i",
  13803. client_options->host,
  13804. client_options->port);
  13805. }
  13806. return conn;
  13807. }
  13808. CIVETWEB_API struct mg_connection *
  13809. mg_connect_client_secure(const struct mg_client_options *client_options,
  13810. char *error_buffer,
  13811. size_t error_buffer_size)
  13812. {
  13813. return mg_connect_client_impl(client_options,
  13814. 1,
  13815. error_buffer,
  13816. error_buffer_size);
  13817. }
  13818. struct mg_connection *
  13819. mg_connect_client(const char *host,
  13820. int port,
  13821. int use_ssl,
  13822. char *error_buffer,
  13823. size_t error_buffer_size)
  13824. {
  13825. struct mg_client_options opts;
  13826. memset(&opts, 0, sizeof(opts));
  13827. opts.host = host;
  13828. opts.port = port;
  13829. return mg_connect_client_impl(&opts,
  13830. use_ssl,
  13831. error_buffer,
  13832. error_buffer_size);
  13833. }
  13834. static const struct {
  13835. const char *proto;
  13836. size_t proto_len;
  13837. unsigned default_port;
  13838. } abs_uri_protocols[] = {{"http://", 7, 80},
  13839. {"https://", 8, 443},
  13840. {"ws://", 5, 80},
  13841. {"wss://", 6, 443},
  13842. {NULL, 0, 0}};
  13843. /* Check if the uri is valid.
  13844. * return 0 for invalid uri,
  13845. * return 1 for *,
  13846. * return 2 for relative uri,
  13847. * return 3 for absolute uri without port,
  13848. * return 4 for absolute uri with port */
  13849. static int
  13850. get_uri_type(const char *uri)
  13851. {
  13852. int i;
  13853. const char *hostend, *portbegin;
  13854. char *portend;
  13855. unsigned long port;
  13856. /* According to the HTTP standard
  13857. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  13858. * URI can be an asterisk (*) or should start with slash (relative uri),
  13859. * or it should start with the protocol (absolute uri). */
  13860. if ((uri[0] == '*') && (uri[1] == '\0')) {
  13861. /* asterisk */
  13862. return 1;
  13863. }
  13864. /* Valid URIs according to RFC 3986
  13865. * (https://www.ietf.org/rfc/rfc3986.txt)
  13866. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  13867. * and unreserved characters A-Z a-z 0-9 and -._~
  13868. * and % encoded symbols.
  13869. */
  13870. for (i = 0; uri[i] != 0; i++) {
  13871. if (uri[i] < 33) {
  13872. /* control characters and spaces are invalid */
  13873. return 0;
  13874. }
  13875. if (uri[i] > 126) {
  13876. /* non-ascii characters must be % encoded */
  13877. return 0;
  13878. } else {
  13879. switch (uri[i]) {
  13880. case '"': /* 34 */
  13881. case '<': /* 60 */
  13882. case '>': /* 62 */
  13883. case '\\': /* 92 */
  13884. case '^': /* 94 */
  13885. case '`': /* 96 */
  13886. case '{': /* 123 */
  13887. case '|': /* 124 */
  13888. case '}': /* 125 */
  13889. return 0;
  13890. default:
  13891. /* character is ok */
  13892. break;
  13893. }
  13894. }
  13895. }
  13896. /* A relative uri starts with a / character */
  13897. if (uri[0] == '/') {
  13898. /* relative uri */
  13899. return 2;
  13900. }
  13901. /* It could be an absolute uri: */
  13902. /* This function only checks if the uri is valid, not if it is
  13903. * addressing the current server. So civetweb can also be used
  13904. * as a proxy server. */
  13905. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13906. if (mg_strncasecmp(uri,
  13907. abs_uri_protocols[i].proto,
  13908. abs_uri_protocols[i].proto_len) == 0) {
  13909. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  13910. if (!hostend) {
  13911. return 0;
  13912. }
  13913. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  13914. if (!portbegin) {
  13915. return 3;
  13916. }
  13917. port = strtoul(portbegin + 1, &portend, 10);
  13918. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  13919. return 0;
  13920. }
  13921. return 4;
  13922. }
  13923. }
  13924. return 0;
  13925. }
  13926. /* Return NULL or the relative uri at the current server */
  13927. static const char *
  13928. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  13929. {
  13930. const char *server_domain;
  13931. size_t server_domain_len;
  13932. size_t request_domain_len = 0;
  13933. unsigned long port = 0;
  13934. int i, auth_domain_check_enabled;
  13935. const char *hostbegin = NULL;
  13936. const char *hostend = NULL;
  13937. const char *portbegin;
  13938. char *portend;
  13939. auth_domain_check_enabled =
  13940. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  13941. /* DNS is case insensitive, so use case insensitive string compare here
  13942. */
  13943. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13944. if (mg_strncasecmp(uri,
  13945. abs_uri_protocols[i].proto,
  13946. abs_uri_protocols[i].proto_len) == 0) {
  13947. hostbegin = uri + abs_uri_protocols[i].proto_len;
  13948. hostend = strchr(hostbegin, '/');
  13949. if (!hostend) {
  13950. return 0;
  13951. }
  13952. portbegin = strchr(hostbegin, ':');
  13953. if ((!portbegin) || (portbegin > hostend)) {
  13954. port = abs_uri_protocols[i].default_port;
  13955. request_domain_len = (size_t)(hostend - hostbegin);
  13956. } else {
  13957. port = strtoul(portbegin + 1, &portend, 10);
  13958. if ((portend != hostend) || (port <= 0)
  13959. || !is_valid_port(port)) {
  13960. return 0;
  13961. }
  13962. request_domain_len = (size_t)(portbegin - hostbegin);
  13963. }
  13964. /* protocol found, port set */
  13965. break;
  13966. }
  13967. }
  13968. if (!port) {
  13969. /* port remains 0 if the protocol is not found */
  13970. return 0;
  13971. }
  13972. /* Check if the request is directed to a different server. */
  13973. /* First check if the port is the same (IPv4 and IPv6). */
  13974. #if defined(USE_IPV6)
  13975. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  13976. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  13977. /* Request is directed to a different port */
  13978. return 0;
  13979. }
  13980. } else
  13981. #endif
  13982. {
  13983. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  13984. /* Request is directed to a different port */
  13985. return 0;
  13986. }
  13987. }
  13988. /* Finally check if the server corresponds to the authentication
  13989. * domain of the server (the server domain).
  13990. * Allow full matches (like http://mydomain.com/path/file.ext), and
  13991. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  13992. * but do not allow substrings (like
  13993. * http://notmydomain.com/path/file.ext
  13994. * or http://mydomain.com.fake/path/file.ext).
  13995. */
  13996. if (auth_domain_check_enabled) {
  13997. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  13998. server_domain_len = strlen(server_domain);
  13999. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14000. return 0;
  14001. }
  14002. if ((request_domain_len == server_domain_len)
  14003. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14004. /* Request is directed to this server - full name match. */
  14005. } else {
  14006. if (request_domain_len < (server_domain_len + 2)) {
  14007. /* Request is directed to another server: The server name
  14008. * is longer than the request name.
  14009. * Drop this case here to avoid overflows in the
  14010. * following checks. */
  14011. return 0;
  14012. }
  14013. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14014. /* Request is directed to another server: It could be a
  14015. * substring
  14016. * like notmyserver.com */
  14017. return 0;
  14018. }
  14019. if (0 != memcmp(server_domain,
  14020. hostbegin + request_domain_len - server_domain_len,
  14021. server_domain_len)) {
  14022. /* Request is directed to another server:
  14023. * The server name is different. */
  14024. return 0;
  14025. }
  14026. }
  14027. }
  14028. return hostend;
  14029. }
  14030. static int
  14031. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14032. {
  14033. if (ebuf_len > 0) {
  14034. ebuf[0] = '\0';
  14035. }
  14036. *err = 0;
  14037. reset_per_request_attributes(conn);
  14038. if (!conn) {
  14039. mg_snprintf(conn,
  14040. NULL, /* No truncation check for ebuf */
  14041. ebuf,
  14042. ebuf_len,
  14043. "%s",
  14044. "Internal error");
  14045. *err = 500;
  14046. return 0;
  14047. }
  14048. /* Set the time the request was received. This value should be used for
  14049. * timeouts. */
  14050. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14051. conn->request_len =
  14052. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14053. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14054. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14055. mg_snprintf(conn,
  14056. NULL, /* No truncation check for ebuf */
  14057. ebuf,
  14058. ebuf_len,
  14059. "%s",
  14060. "Invalid message size");
  14061. *err = 500;
  14062. return 0;
  14063. }
  14064. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14065. mg_snprintf(conn,
  14066. NULL, /* No truncation check for ebuf */
  14067. ebuf,
  14068. ebuf_len,
  14069. "%s",
  14070. "Message too large");
  14071. *err = 413;
  14072. return 0;
  14073. }
  14074. if (conn->request_len <= 0) {
  14075. if (conn->data_len > 0) {
  14076. mg_snprintf(conn,
  14077. NULL, /* No truncation check for ebuf */
  14078. ebuf,
  14079. ebuf_len,
  14080. "%s",
  14081. "Malformed message");
  14082. *err = 400;
  14083. } else {
  14084. /* Server did not recv anything -> just close the connection */
  14085. conn->must_close = 1;
  14086. mg_snprintf(conn,
  14087. NULL, /* No truncation check for ebuf */
  14088. ebuf,
  14089. ebuf_len,
  14090. "%s",
  14091. "No data received");
  14092. *err = 0;
  14093. }
  14094. return 0;
  14095. }
  14096. return 1;
  14097. }
  14098. static int
  14099. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14100. {
  14101. const char *cl;
  14102. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14103. return 0;
  14104. }
  14105. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14106. <= 0) {
  14107. mg_snprintf(conn,
  14108. NULL, /* No truncation check for ebuf */
  14109. ebuf,
  14110. ebuf_len,
  14111. "%s",
  14112. "Bad request");
  14113. *err = 400;
  14114. return 0;
  14115. }
  14116. /* Message is a valid request */
  14117. /* Is there a "host" ? */
  14118. conn->host = alloc_get_host(conn);
  14119. if (!conn->host) {
  14120. mg_snprintf(conn,
  14121. NULL, /* No truncation check for ebuf */
  14122. ebuf,
  14123. ebuf_len,
  14124. "%s",
  14125. "Bad request: Host mismatch");
  14126. *err = 400;
  14127. return 0;
  14128. }
  14129. /* Do we know the content length? */
  14130. if ((cl = get_header(conn->request_info.http_headers,
  14131. conn->request_info.num_headers,
  14132. "Content-Length")) != NULL) {
  14133. /* Request/response has content length set */
  14134. char *endptr = NULL;
  14135. conn->content_len = strtoll(cl, &endptr, 10);
  14136. if (endptr == cl) {
  14137. mg_snprintf(conn,
  14138. NULL, /* No truncation check for ebuf */
  14139. ebuf,
  14140. ebuf_len,
  14141. "%s",
  14142. "Bad request");
  14143. *err = 411;
  14144. return 0;
  14145. }
  14146. /* Publish the content length back to the request info. */
  14147. conn->request_info.content_length = conn->content_len;
  14148. } else if ((cl = get_header(conn->request_info.http_headers,
  14149. conn->request_info.num_headers,
  14150. "Transfer-Encoding")) != NULL
  14151. && !mg_strcasecmp(cl, "chunked")) {
  14152. conn->is_chunked = 1;
  14153. conn->content_len = -1; /* unknown content length */
  14154. } else {
  14155. const struct mg_http_method_info *meth =
  14156. get_http_method_info(conn->request_info.request_method);
  14157. if (!meth) {
  14158. /* No valid HTTP method */
  14159. mg_snprintf(conn,
  14160. NULL, /* No truncation check for ebuf */
  14161. ebuf,
  14162. ebuf_len,
  14163. "%s",
  14164. "Bad request");
  14165. *err = 411;
  14166. return 0;
  14167. }
  14168. if (meth->request_has_body) {
  14169. /* POST or PUT request without content length set */
  14170. conn->content_len = -1; /* unknown content length */
  14171. } else {
  14172. /* Other request */
  14173. conn->content_len = 0; /* No content */
  14174. }
  14175. }
  14176. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14177. return 1;
  14178. }
  14179. /* conn is assumed to be valid in this internal function */
  14180. static int
  14181. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14182. {
  14183. const char *cl;
  14184. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14185. return 0;
  14186. }
  14187. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14188. <= 0) {
  14189. mg_snprintf(conn,
  14190. NULL, /* No truncation check for ebuf */
  14191. ebuf,
  14192. ebuf_len,
  14193. "%s",
  14194. "Bad response");
  14195. *err = 400;
  14196. return 0;
  14197. }
  14198. /* Message is a valid response */
  14199. /* Do we know the content length? */
  14200. if ((cl = get_header(conn->response_info.http_headers,
  14201. conn->response_info.num_headers,
  14202. "Content-Length")) != NULL) {
  14203. /* Request/response has content length set */
  14204. char *endptr = NULL;
  14205. conn->content_len = strtoll(cl, &endptr, 10);
  14206. if (endptr == cl) {
  14207. mg_snprintf(conn,
  14208. NULL, /* No truncation check for ebuf */
  14209. ebuf,
  14210. ebuf_len,
  14211. "%s",
  14212. "Bad request");
  14213. *err = 411;
  14214. return 0;
  14215. }
  14216. /* Publish the content length back to the response info. */
  14217. conn->response_info.content_length = conn->content_len;
  14218. /* TODO: check if it is still used in response_info */
  14219. conn->request_info.content_length = conn->content_len;
  14220. } else if ((cl = get_header(conn->response_info.http_headers,
  14221. conn->response_info.num_headers,
  14222. "Transfer-Encoding")) != NULL
  14223. && !mg_strcasecmp(cl, "chunked")) {
  14224. conn->is_chunked = 1;
  14225. conn->content_len = -1; /* unknown content length */
  14226. } else {
  14227. conn->content_len = -1; /* unknown content length */
  14228. }
  14229. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14230. return 1;
  14231. }
  14232. int
  14233. mg_get_response(struct mg_connection *conn,
  14234. char *ebuf,
  14235. size_t ebuf_len,
  14236. int timeout)
  14237. {
  14238. int err, ret;
  14239. char txt[32]; /* will not overflow */
  14240. char *save_timeout;
  14241. char *new_timeout;
  14242. if (ebuf_len > 0) {
  14243. ebuf[0] = '\0';
  14244. }
  14245. if (!conn) {
  14246. mg_snprintf(conn,
  14247. NULL, /* No truncation check for ebuf */
  14248. ebuf,
  14249. ebuf_len,
  14250. "%s",
  14251. "Parameter error");
  14252. return -1;
  14253. }
  14254. /* Implementation of API function for HTTP clients */
  14255. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14256. if (timeout >= 0) {
  14257. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14258. new_timeout = txt;
  14259. /* Not required for non-blocking sockets.
  14260. set_sock_timeout(conn->client.sock, timeout);
  14261. */
  14262. } else {
  14263. new_timeout = NULL;
  14264. }
  14265. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14266. ret = get_response(conn, ebuf, ebuf_len, &err);
  14267. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14268. #if defined(MG_LEGACY_INTERFACE)
  14269. /* TODO: 1) uri is deprecated;
  14270. * 2) here, ri.uri is the http response code */
  14271. conn->request_info.uri = conn->request_info.request_uri;
  14272. #endif
  14273. conn->request_info.local_uri = conn->request_info.request_uri;
  14274. /* TODO (mid): Define proper return values - maybe return length?
  14275. * For the first test use <0 for error and >0 for OK */
  14276. return (ret == 0) ? -1 : +1;
  14277. }
  14278. struct mg_connection *
  14279. mg_download(const char *host,
  14280. int port,
  14281. int use_ssl,
  14282. char *ebuf,
  14283. size_t ebuf_len,
  14284. const char *fmt,
  14285. ...)
  14286. {
  14287. struct mg_connection *conn;
  14288. va_list ap;
  14289. int i;
  14290. int reqerr;
  14291. if (ebuf_len > 0) {
  14292. ebuf[0] = '\0';
  14293. }
  14294. va_start(ap, fmt);
  14295. /* open a connection */
  14296. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14297. if (conn != NULL) {
  14298. i = mg_vprintf(conn, fmt, ap);
  14299. if (i <= 0) {
  14300. mg_snprintf(conn,
  14301. NULL, /* No truncation check for ebuf */
  14302. ebuf,
  14303. ebuf_len,
  14304. "%s",
  14305. "Error sending request");
  14306. } else {
  14307. get_response(conn, ebuf, ebuf_len, &reqerr);
  14308. #if defined(MG_LEGACY_INTERFACE)
  14309. /* TODO: 1) uri is deprecated;
  14310. * 2) here, ri.uri is the http response code */
  14311. conn->request_info.uri = conn->request_info.request_uri;
  14312. #endif
  14313. conn->request_info.local_uri = conn->request_info.request_uri;
  14314. }
  14315. }
  14316. /* if an error occurred, close the connection */
  14317. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14318. mg_close_connection(conn);
  14319. conn = NULL;
  14320. }
  14321. va_end(ap);
  14322. return conn;
  14323. }
  14324. struct websocket_client_thread_data {
  14325. struct mg_connection *conn;
  14326. mg_websocket_data_handler data_handler;
  14327. mg_websocket_close_handler close_handler;
  14328. void *callback_data;
  14329. };
  14330. #if defined(USE_WEBSOCKET)
  14331. #if defined(_WIN32)
  14332. static unsigned __stdcall websocket_client_thread(void *data)
  14333. #else
  14334. static void *
  14335. websocket_client_thread(void *data)
  14336. #endif
  14337. {
  14338. struct websocket_client_thread_data *cdata =
  14339. (struct websocket_client_thread_data *)data;
  14340. #if !defined(_WIN32)
  14341. struct sigaction sa;
  14342. /* Ignore SIGPIPE */
  14343. memset(&sa, 0, sizeof(sa));
  14344. sa.sa_handler = SIG_IGN;
  14345. sigaction(SIGPIPE, &sa, NULL);
  14346. #endif
  14347. mg_set_thread_name("ws-clnt");
  14348. if (cdata->conn->phys_ctx) {
  14349. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14350. /* 3 indicates a websocket client thread */
  14351. /* TODO: check if conn->phys_ctx can be set */
  14352. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  14353. 3);
  14354. }
  14355. }
  14356. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14357. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14358. if (cdata->close_handler != NULL) {
  14359. cdata->close_handler(cdata->conn, cdata->callback_data);
  14360. }
  14361. /* The websocket_client context has only this thread. If it runs out,
  14362. set the stop_flag to 2 (= "stopped"). */
  14363. cdata->conn->phys_ctx->stop_flag = 2;
  14364. mg_free((void *)cdata);
  14365. #if defined(_WIN32)
  14366. return 0;
  14367. #else
  14368. return NULL;
  14369. #endif
  14370. }
  14371. #endif
  14372. struct mg_connection *
  14373. mg_connect_websocket_client(const char *host,
  14374. int port,
  14375. int use_ssl,
  14376. char *error_buffer,
  14377. size_t error_buffer_size,
  14378. const char *path,
  14379. const char *origin,
  14380. mg_websocket_data_handler data_func,
  14381. mg_websocket_close_handler close_func,
  14382. void *user_data)
  14383. {
  14384. struct mg_connection *conn = NULL;
  14385. #if defined(USE_WEBSOCKET)
  14386. struct mg_context *newctx = NULL;
  14387. struct websocket_client_thread_data *thread_data;
  14388. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14389. static const char *handshake_req;
  14390. if (origin != NULL) {
  14391. handshake_req = "GET %s HTTP/1.1\r\n"
  14392. "Host: %s\r\n"
  14393. "Upgrade: websocket\r\n"
  14394. "Connection: Upgrade\r\n"
  14395. "Sec-WebSocket-Key: %s\r\n"
  14396. "Sec-WebSocket-Version: 13\r\n"
  14397. "Origin: %s\r\n"
  14398. "\r\n";
  14399. } else {
  14400. handshake_req = "GET %s HTTP/1.1\r\n"
  14401. "Host: %s\r\n"
  14402. "Upgrade: websocket\r\n"
  14403. "Connection: Upgrade\r\n"
  14404. "Sec-WebSocket-Key: %s\r\n"
  14405. "Sec-WebSocket-Version: 13\r\n"
  14406. "\r\n";
  14407. }
  14408. #if defined(__clang__)
  14409. #pragma clang diagnostic push
  14410. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  14411. #endif
  14412. /* Establish the client connection and request upgrade */
  14413. conn = mg_download(host,
  14414. port,
  14415. use_ssl,
  14416. error_buffer,
  14417. error_buffer_size,
  14418. handshake_req,
  14419. path,
  14420. host,
  14421. magic,
  14422. origin);
  14423. #if defined(__clang__)
  14424. #pragma clang diagnostic pop
  14425. #endif
  14426. /* Connection object will be null if something goes wrong */
  14427. if (conn == NULL) {
  14428. if (!*error_buffer) {
  14429. /* There should be already an error message */
  14430. mg_snprintf(conn,
  14431. NULL, /* No truncation check for ebuf */
  14432. error_buffer,
  14433. error_buffer_size,
  14434. "Unexpected error");
  14435. }
  14436. return NULL;
  14437. }
  14438. if (conn->response_info.status_code != 101) {
  14439. /* We sent an "upgrade" request. For a correct websocket
  14440. * protocol handshake, we expect a "101 Continue" response.
  14441. * Otherwise it is a protocol violation. Maybe the HTTP
  14442. * Server does not know websockets. */
  14443. if (!*error_buffer) {
  14444. /* set an error, if not yet set */
  14445. mg_snprintf(conn,
  14446. NULL, /* No truncation check for ebuf */
  14447. error_buffer,
  14448. error_buffer_size,
  14449. "Unexpected server reply");
  14450. }
  14451. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14452. mg_free(conn);
  14453. return NULL;
  14454. }
  14455. /* For client connections, mg_context is fake. Since we need to set a
  14456. * callback function, we need to create a copy and modify it. */
  14457. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  14458. if (!newctx) {
  14459. DEBUG_TRACE("%s\r\n", "Out of memory");
  14460. mg_free(conn);
  14461. return NULL;
  14462. }
  14463. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  14464. newctx->user_data = user_data;
  14465. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  14466. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  14467. newctx->worker_threadids =
  14468. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  14469. sizeof(pthread_t),
  14470. newctx);
  14471. conn->phys_ctx = newctx;
  14472. conn->dom_ctx = &(newctx->dd);
  14473. thread_data = (struct websocket_client_thread_data *)
  14474. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  14475. if (!thread_data) {
  14476. DEBUG_TRACE("%s\r\n", "Out of memory");
  14477. mg_free(newctx);
  14478. mg_free(conn);
  14479. return NULL;
  14480. }
  14481. thread_data->conn = conn;
  14482. thread_data->data_handler = data_func;
  14483. thread_data->close_handler = close_func;
  14484. thread_data->callback_data = user_data;
  14485. /* Start a thread to read the websocket client connection
  14486. * This thread will automatically stop when mg_disconnect is
  14487. * called on the client connection */
  14488. if (mg_start_thread_with_id(websocket_client_thread,
  14489. (void *)thread_data,
  14490. newctx->worker_threadids) != 0) {
  14491. mg_free((void *)thread_data);
  14492. mg_free((void *)newctx->worker_threadids);
  14493. mg_free((void *)newctx);
  14494. mg_free((void *)conn);
  14495. conn = NULL;
  14496. DEBUG_TRACE("%s",
  14497. "Websocket client connect thread could not be started\r\n");
  14498. }
  14499. #else
  14500. /* Appease "unused parameter" warnings */
  14501. (void)host;
  14502. (void)port;
  14503. (void)use_ssl;
  14504. (void)error_buffer;
  14505. (void)error_buffer_size;
  14506. (void)path;
  14507. (void)origin;
  14508. (void)user_data;
  14509. (void)data_func;
  14510. (void)close_func;
  14511. #endif
  14512. return conn;
  14513. }
  14514. /* Prepare connection data structure */
  14515. static void
  14516. init_connection(struct mg_connection *conn)
  14517. {
  14518. /* Is keep alive allowed by the server */
  14519. int keep_alive_enabled =
  14520. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  14521. if (!keep_alive_enabled) {
  14522. conn->must_close = 1;
  14523. }
  14524. /* Important: on new connection, reset the receiving buffer. Credit
  14525. * goes to crule42. */
  14526. conn->data_len = 0;
  14527. conn->handled_requests = 0;
  14528. mg_set_user_connection_data(conn, NULL);
  14529. #if defined(USE_SERVER_STATS)
  14530. conn->conn_state = 2; /* init */
  14531. #endif
  14532. /* call the init_connection callback if assigned */
  14533. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  14534. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14535. void *conn_data = NULL;
  14536. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  14537. mg_set_user_connection_data(conn, conn_data);
  14538. }
  14539. }
  14540. }
  14541. /* Process a connection - may handle multiple requests
  14542. * using the same connection.
  14543. * Must be called with a valid connection (conn and
  14544. * conn->phys_ctx must be valid).
  14545. */
  14546. static void
  14547. process_new_connection(struct mg_connection *conn)
  14548. {
  14549. struct mg_request_info *ri = &conn->request_info;
  14550. int keep_alive, discard_len;
  14551. char ebuf[100];
  14552. const char *hostend;
  14553. int reqerr, uri_type;
  14554. #if defined(USE_SERVER_STATS)
  14555. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  14556. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  14557. if (mcon > (conn->phys_ctx->max_connections)) {
  14558. /* could use atomic compare exchange, but this
  14559. * seems overkill for statistics data */
  14560. conn->phys_ctx->max_connections = mcon;
  14561. }
  14562. #endif
  14563. init_connection(conn);
  14564. DEBUG_TRACE("Start processing connection from %s",
  14565. conn->request_info.remote_addr);
  14566. /* Loop over multiple requests sent using the same connection
  14567. * (while "keep alive"). */
  14568. do {
  14569. DEBUG_TRACE("calling get_request (%i times for this connection)",
  14570. conn->handled_requests + 1);
  14571. #if defined(USE_SERVER_STATS)
  14572. conn->conn_state = 3; /* ready */
  14573. #endif
  14574. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  14575. /* The request sent by the client could not be understood by
  14576. * the server, or it was incomplete or a timeout. Send an
  14577. * error message and close the connection. */
  14578. if (reqerr > 0) {
  14579. DEBUG_ASSERT(ebuf[0] != '\0');
  14580. mg_send_http_error(conn, reqerr, "%s", ebuf);
  14581. }
  14582. } else if (strcmp(ri->http_version, "1.0")
  14583. && strcmp(ri->http_version, "1.1")) {
  14584. mg_snprintf(conn,
  14585. NULL, /* No truncation check for ebuf */
  14586. ebuf,
  14587. sizeof(ebuf),
  14588. "Bad HTTP version: [%s]",
  14589. ri->http_version);
  14590. mg_send_http_error(conn, 505, "%s", ebuf);
  14591. }
  14592. if (ebuf[0] == '\0') {
  14593. uri_type = get_uri_type(conn->request_info.request_uri);
  14594. switch (uri_type) {
  14595. case 1:
  14596. /* Asterisk */
  14597. conn->request_info.local_uri = NULL;
  14598. break;
  14599. case 2:
  14600. /* relative uri */
  14601. conn->request_info.local_uri = conn->request_info.request_uri;
  14602. break;
  14603. case 3:
  14604. case 4:
  14605. /* absolute uri (with/without port) */
  14606. hostend = get_rel_url_at_current_server(
  14607. conn->request_info.request_uri, conn);
  14608. if (hostend) {
  14609. conn->request_info.local_uri = hostend;
  14610. } else {
  14611. conn->request_info.local_uri = NULL;
  14612. }
  14613. break;
  14614. default:
  14615. mg_snprintf(conn,
  14616. NULL, /* No truncation check for ebuf */
  14617. ebuf,
  14618. sizeof(ebuf),
  14619. "Invalid URI");
  14620. mg_send_http_error(conn, 400, "%s", ebuf);
  14621. conn->request_info.local_uri = NULL;
  14622. break;
  14623. }
  14624. #if defined(MG_LEGACY_INTERFACE)
  14625. /* Legacy before split into local_uri and request_uri */
  14626. conn->request_info.uri = conn->request_info.local_uri;
  14627. #endif
  14628. }
  14629. DEBUG_TRACE("http: %s, error: %s",
  14630. (ri->http_version ? ri->http_version : "none"),
  14631. (ebuf[0] ? ebuf : "none"));
  14632. if (ebuf[0] == '\0') {
  14633. if (conn->request_info.local_uri) {
  14634. /* handle request to local server */
  14635. #if defined(USE_SERVER_STATS)
  14636. conn->conn_state = 4; /* processing */
  14637. #endif
  14638. handle_request(conn);
  14639. #if defined(USE_SERVER_STATS)
  14640. conn->conn_state = 5; /* processed */
  14641. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  14642. conn->consumed_content);
  14643. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  14644. conn->num_bytes_sent);
  14645. #endif
  14646. DEBUG_TRACE("%s", "handle_request done");
  14647. if (conn->phys_ctx->callbacks.end_request != NULL) {
  14648. conn->phys_ctx->callbacks.end_request(conn,
  14649. conn->status_code);
  14650. DEBUG_TRACE("%s", "end_request callback done");
  14651. }
  14652. log_access(conn);
  14653. } else {
  14654. /* TODO: handle non-local request (PROXY) */
  14655. conn->must_close = 1;
  14656. }
  14657. } else {
  14658. conn->must_close = 1;
  14659. }
  14660. if (ri->remote_user != NULL) {
  14661. mg_free((void *)ri->remote_user);
  14662. /* Important! When having connections with and without auth
  14663. * would cause double free and then crash */
  14664. ri->remote_user = NULL;
  14665. }
  14666. /* NOTE(lsm): order is important here. should_keep_alive() call
  14667. * is using parsed request, which will be invalid after
  14668. * memmove's below.
  14669. * Therefore, memorize should_keep_alive() result now for later
  14670. * use in loop exit condition. */
  14671. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  14672. && (conn->content_len >= 0);
  14673. /* Discard all buffered data for this request */
  14674. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  14675. && ((conn->request_len + conn->content_len)
  14676. < (int64_t)conn->data_len))
  14677. ? (int)(conn->request_len + conn->content_len)
  14678. : conn->data_len;
  14679. DEBUG_ASSERT(discard_len >= 0);
  14680. if (discard_len < 0) {
  14681. DEBUG_TRACE("internal error: discard_len = %li",
  14682. (long int)discard_len);
  14683. break;
  14684. }
  14685. conn->data_len -= discard_len;
  14686. if (conn->data_len > 0) {
  14687. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  14688. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  14689. }
  14690. DEBUG_ASSERT(conn->data_len >= 0);
  14691. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  14692. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  14693. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  14694. (long int)conn->data_len,
  14695. (long int)conn->buf_size);
  14696. break;
  14697. }
  14698. conn->handled_requests++;
  14699. } while (keep_alive);
  14700. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  14701. conn->request_info.remote_addr,
  14702. difftime(time(NULL), conn->conn_birth_time));
  14703. close_connection(conn);
  14704. #if defined(USE_SERVER_STATS)
  14705. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  14706. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  14707. #endif
  14708. }
  14709. #if defined(ALTERNATIVE_QUEUE)
  14710. static void
  14711. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14712. {
  14713. unsigned int i;
  14714. while (!ctx->stop_flag) {
  14715. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14716. /* find a free worker slot and signal it */
  14717. if (ctx->client_socks[i].in_use == 0) {
  14718. ctx->client_socks[i] = *sp;
  14719. ctx->client_socks[i].in_use = 1;
  14720. event_signal(ctx->client_wait_events[i]);
  14721. return;
  14722. }
  14723. }
  14724. /* queue is full */
  14725. mg_sleep(1);
  14726. }
  14727. }
  14728. static int
  14729. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14730. {
  14731. DEBUG_TRACE("%s", "going idle");
  14732. ctx->client_socks[thread_index].in_use = 0;
  14733. event_wait(ctx->client_wait_events[thread_index]);
  14734. *sp = ctx->client_socks[thread_index];
  14735. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14736. return !ctx->stop_flag;
  14737. }
  14738. #else /* ALTERNATIVE_QUEUE */
  14739. /* Worker threads take accepted socket from the queue */
  14740. static int
  14741. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14742. {
  14743. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14744. (void)thread_index;
  14745. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14746. DEBUG_TRACE("%s", "going idle");
  14747. /* If the queue is empty, wait. We're idle at this point. */
  14748. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  14749. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  14750. }
  14751. /* If we're stopping, sq_head may be equal to sq_tail. */
  14752. if (ctx->sq_head > ctx->sq_tail) {
  14753. /* Copy socket from the queue and increment tail */
  14754. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  14755. ctx->sq_tail++;
  14756. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14757. /* Wrap pointers if needed */
  14758. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  14759. ctx->sq_tail -= QUEUE_SIZE(ctx);
  14760. ctx->sq_head -= QUEUE_SIZE(ctx);
  14761. }
  14762. }
  14763. (void)pthread_cond_signal(&ctx->sq_empty);
  14764. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14765. return !ctx->stop_flag;
  14766. #undef QUEUE_SIZE
  14767. }
  14768. /* Master thread adds accepted socket to a queue */
  14769. static void
  14770. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14771. {
  14772. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14773. if (!ctx) {
  14774. return;
  14775. }
  14776. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14777. /* If the queue is full, wait */
  14778. while ((ctx->stop_flag == 0)
  14779. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  14780. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  14781. }
  14782. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  14783. /* Copy socket to the queue and increment head */
  14784. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  14785. ctx->sq_head++;
  14786. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  14787. }
  14788. (void)pthread_cond_signal(&ctx->sq_full);
  14789. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14790. #undef QUEUE_SIZE
  14791. }
  14792. #endif /* ALTERNATIVE_QUEUE */
  14793. struct worker_thread_args {
  14794. struct mg_context *ctx;
  14795. int index;
  14796. };
  14797. static void *
  14798. worker_thread_run(struct worker_thread_args *thread_args)
  14799. {
  14800. struct mg_context *ctx = thread_args->ctx;
  14801. struct mg_connection *conn;
  14802. struct mg_workerTLS tls;
  14803. #if defined(MG_LEGACY_INTERFACE)
  14804. uint32_t addr;
  14805. #endif
  14806. mg_set_thread_name("worker");
  14807. tls.is_master = 0;
  14808. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14809. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14810. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14811. #endif
  14812. /* Initialize thread local storage before calling any callback */
  14813. pthread_setspecific(sTlsKey, &tls);
  14814. if (ctx->callbacks.init_thread) {
  14815. /* call init_thread for a worker thread (type 1) */
  14816. ctx->callbacks.init_thread(ctx, 1);
  14817. }
  14818. /* Connection structure has been pre-allocated */
  14819. if (((int)thread_args->index < 0)
  14820. || ((unsigned)thread_args->index
  14821. >= (unsigned)ctx->cfg_worker_threads)) {
  14822. mg_cry_internal(fc(ctx),
  14823. "Internal error: Invalid worker index %i",
  14824. (int)thread_args->index);
  14825. return NULL;
  14826. }
  14827. conn = ctx->worker_connections + thread_args->index;
  14828. /* Request buffers are not pre-allocated. They are private to the
  14829. * request and do not contain any state information that might be
  14830. * of interest to anyone observing a server status. */
  14831. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  14832. if (conn->buf == NULL) {
  14833. mg_cry_internal(fc(ctx),
  14834. "Out of memory: Cannot allocate buffer for worker %i",
  14835. (int)thread_args->index);
  14836. return NULL;
  14837. }
  14838. conn->buf_size = (int)ctx->max_request_size;
  14839. conn->phys_ctx = ctx;
  14840. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  14841. conn->host = NULL; /* until we have more information. */
  14842. conn->thread_index = thread_args->index;
  14843. conn->request_info.user_data = ctx->user_data;
  14844. /* Allocate a mutex for this connection to allow communication both
  14845. * within the request handler and from elsewhere in the application
  14846. */
  14847. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  14848. #if defined(USE_SERVER_STATS)
  14849. conn->conn_state = 1; /* not consumed */
  14850. #endif
  14851. #if defined(ALTERNATIVE_QUEUE)
  14852. while ((ctx->stop_flag == 0)
  14853. && consume_socket(ctx, &conn->client, conn->thread_index)) {
  14854. #else
  14855. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  14856. * signal sq_empty condvar to wake up the master waiting in
  14857. * produce_socket() */
  14858. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  14859. #endif
  14860. conn->conn_birth_time = time(NULL);
  14861. /* Fill in IP, port info early so even if SSL setup below fails,
  14862. * error handler would have the corresponding info.
  14863. * Thanks to Johannes Winkelmann for the patch.
  14864. */
  14865. #if defined(USE_IPV6)
  14866. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  14867. conn->request_info.remote_port =
  14868. ntohs(conn->client.rsa.sin6.sin6_port);
  14869. } else
  14870. #endif
  14871. {
  14872. conn->request_info.remote_port =
  14873. ntohs(conn->client.rsa.sin.sin_port);
  14874. }
  14875. sockaddr_to_string(conn->request_info.remote_addr,
  14876. sizeof(conn->request_info.remote_addr),
  14877. &conn->client.rsa);
  14878. DEBUG_TRACE("Start processing connection from %s",
  14879. conn->request_info.remote_addr);
  14880. conn->request_info.is_ssl = conn->client.is_ssl;
  14881. if (conn->client.is_ssl) {
  14882. #if !defined(NO_SSL)
  14883. /* HTTPS connection */
  14884. if (sslize(conn,
  14885. conn->dom_ctx->ssl_ctx,
  14886. SSL_accept,
  14887. &(conn->phys_ctx->stop_flag))) {
  14888. /* conn->dom_ctx is set in get_request */
  14889. /* Get SSL client certificate information (if set) */
  14890. ssl_get_client_cert_info(conn);
  14891. /* process HTTPS connection */
  14892. process_new_connection(conn);
  14893. /* Free client certificate info */
  14894. if (conn->request_info.client_cert) {
  14895. mg_free((void *)(conn->request_info.client_cert->subject));
  14896. mg_free((void *)(conn->request_info.client_cert->issuer));
  14897. mg_free((void *)(conn->request_info.client_cert->serial));
  14898. mg_free((void *)(conn->request_info.client_cert->finger));
  14899. /* Free certificate memory */
  14900. X509_free(
  14901. (X509 *)conn->request_info.client_cert->peer_cert);
  14902. conn->request_info.client_cert->peer_cert = 0;
  14903. conn->request_info.client_cert->subject = 0;
  14904. conn->request_info.client_cert->issuer = 0;
  14905. conn->request_info.client_cert->serial = 0;
  14906. conn->request_info.client_cert->finger = 0;
  14907. mg_free(conn->request_info.client_cert);
  14908. conn->request_info.client_cert = 0;
  14909. }
  14910. }
  14911. #endif
  14912. } else {
  14913. /* process HTTP connection */
  14914. process_new_connection(conn);
  14915. }
  14916. DEBUG_TRACE("%s", "Connection closed");
  14917. }
  14918. pthread_setspecific(sTlsKey, NULL);
  14919. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14920. CloseHandle(tls.pthread_cond_helper_mutex);
  14921. #endif
  14922. pthread_mutex_destroy(&conn->mutex);
  14923. /* Free the request buffer. */
  14924. conn->buf_size = 0;
  14925. mg_free(conn->buf);
  14926. conn->buf = NULL;
  14927. #if defined(USE_SERVER_STATS)
  14928. conn->conn_state = 9; /* done */
  14929. #endif
  14930. DEBUG_TRACE("%s", "exiting");
  14931. return NULL;
  14932. }
  14933. /* Threads have different return types on Windows and Unix. */
  14934. #if defined(_WIN32)
  14935. static unsigned __stdcall worker_thread(void *thread_func_param)
  14936. {
  14937. struct worker_thread_args *pwta =
  14938. (struct worker_thread_args *)thread_func_param;
  14939. worker_thread_run(pwta);
  14940. mg_free(thread_func_param);
  14941. return 0;
  14942. }
  14943. #else
  14944. static void *
  14945. worker_thread(void *thread_func_param)
  14946. {
  14947. struct worker_thread_args *pwta =
  14948. (struct worker_thread_args *)thread_func_param;
  14949. struct sigaction sa;
  14950. /* Ignore SIGPIPE */
  14951. memset(&sa, 0, sizeof(sa));
  14952. sa.sa_handler = SIG_IGN;
  14953. sigaction(SIGPIPE, &sa, NULL);
  14954. worker_thread_run(pwta);
  14955. mg_free(thread_func_param);
  14956. return NULL;
  14957. }
  14958. #endif /* _WIN32 */
  14959. /* This is an internal function, thus all arguments are expected to be
  14960. * valid - a NULL check is not required. */
  14961. static void
  14962. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  14963. {
  14964. struct socket so;
  14965. char src_addr[IP_ADDR_STR_LEN];
  14966. socklen_t len = sizeof(so.rsa);
  14967. int on = 1;
  14968. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  14969. == INVALID_SOCKET) {
  14970. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  14971. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  14972. mg_cry_internal(fc(ctx),
  14973. "%s: %s is not allowed to connect",
  14974. __func__,
  14975. src_addr);
  14976. closesocket(so.sock);
  14977. } else {
  14978. /* Put so socket structure into the queue */
  14979. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  14980. set_close_on_exec(so.sock, fc(ctx));
  14981. so.is_ssl = listener->is_ssl;
  14982. so.ssl_redir = listener->ssl_redir;
  14983. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  14984. mg_cry_internal(fc(ctx),
  14985. "%s: getsockname() failed: %s",
  14986. __func__,
  14987. strerror(ERRNO));
  14988. }
  14989. /* Set TCP keep-alive. This is needed because if HTTP-level
  14990. * keep-alive
  14991. * is enabled, and client resets the connection, server won't get
  14992. * TCP FIN or RST and will keep the connection open forever. With
  14993. * TCP keep-alive, next keep-alive handshake will figure out that
  14994. * the client is down and will close the server end.
  14995. * Thanks to Igor Klopov who suggested the patch. */
  14996. if (setsockopt(so.sock,
  14997. SOL_SOCKET,
  14998. SO_KEEPALIVE,
  14999. (SOCK_OPT_TYPE)&on,
  15000. sizeof(on)) != 0) {
  15001. mg_cry_internal(
  15002. fc(ctx),
  15003. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15004. __func__,
  15005. strerror(ERRNO));
  15006. }
  15007. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15008. * to effectively fill up the underlying IP packet payload and
  15009. * reduce the overhead of sending lots of small buffers. However
  15010. * this hurts the server's throughput (ie. operations per second)
  15011. * when HTTP 1.1 persistent connections are used and the responses
  15012. * are relatively small (eg. less than 1400 bytes).
  15013. */
  15014. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15015. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15016. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15017. mg_cry_internal(
  15018. fc(ctx),
  15019. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15020. __func__,
  15021. strerror(ERRNO));
  15022. }
  15023. }
  15024. /* We are using non-blocking sockets. Thus, the
  15025. * set_sock_timeout(so.sock, timeout);
  15026. * call is no longer required. */
  15027. /* The "non blocking" property should already be
  15028. * inherited from the parent socket. Set it for
  15029. * non-compliant socket implementations. */
  15030. set_non_blocking_mode(so.sock);
  15031. so.in_use = 0;
  15032. produce_socket(ctx, &so);
  15033. }
  15034. }
  15035. static void
  15036. master_thread_run(void *thread_func_param)
  15037. {
  15038. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  15039. struct mg_workerTLS tls;
  15040. struct pollfd *pfd;
  15041. unsigned int i;
  15042. unsigned int workerthreadcount;
  15043. if (!ctx) {
  15044. return;
  15045. }
  15046. mg_set_thread_name("master");
  15047. /* Increase priority of the master thread */
  15048. #if defined(_WIN32)
  15049. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15050. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15051. int min_prio = sched_get_priority_min(SCHED_RR);
  15052. int max_prio = sched_get_priority_max(SCHED_RR);
  15053. if ((min_prio >= 0) && (max_prio >= 0)
  15054. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15055. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15056. struct sched_param sched_param = {0};
  15057. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15058. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15059. }
  15060. #endif
  15061. /* Initialize thread local storage */
  15062. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15063. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15064. #endif
  15065. tls.is_master = 1;
  15066. pthread_setspecific(sTlsKey, &tls);
  15067. if (ctx->callbacks.init_thread) {
  15068. /* Callback for the master thread (type 0) */
  15069. ctx->callbacks.init_thread(ctx, 0);
  15070. }
  15071. /* Server starts *now* */
  15072. ctx->start_time = time(NULL);
  15073. /* Start the server */
  15074. pfd = ctx->listening_socket_fds;
  15075. while (ctx->stop_flag == 0) {
  15076. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15077. pfd[i].fd = ctx->listening_sockets[i].sock;
  15078. pfd[i].events = POLLIN;
  15079. }
  15080. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15081. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15082. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15083. * successful poll, and POLLIN is defined as
  15084. * (POLLRDNORM | POLLRDBAND)
  15085. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15086. * pfd[i].revents == POLLIN. */
  15087. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15088. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15089. }
  15090. }
  15091. }
  15092. }
  15093. /* Here stop_flag is 1 - Initiate shutdown. */
  15094. DEBUG_TRACE("%s", "stopping workers");
  15095. /* Stop signal received: somebody called mg_stop. Quit. */
  15096. close_all_listening_sockets(ctx);
  15097. /* Wakeup workers that are waiting for connections to handle. */
  15098. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15099. #if defined(ALTERNATIVE_QUEUE)
  15100. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15101. event_signal(ctx->client_wait_events[i]);
  15102. /* Since we know all sockets, we can shutdown the connections. */
  15103. if (ctx->client_socks[i].in_use) {
  15104. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  15105. }
  15106. }
  15107. #else
  15108. pthread_cond_broadcast(&ctx->sq_full);
  15109. #endif
  15110. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15111. /* Join all worker threads to avoid leaking threads. */
  15112. workerthreadcount = ctx->cfg_worker_threads;
  15113. for (i = 0; i < workerthreadcount; i++) {
  15114. if (ctx->worker_threadids[i] != 0) {
  15115. mg_join_thread(ctx->worker_threadids[i]);
  15116. }
  15117. }
  15118. #if defined(USE_LUA)
  15119. /* Free Lua state of lua background task */
  15120. if (ctx->lua_background_state) {
  15121. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15122. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15123. if (lua_istable(lstate, -1)) {
  15124. reg_boolean(lstate, "shutdown", 1);
  15125. lua_pop(lstate, 1);
  15126. mg_sleep(2);
  15127. }
  15128. lua_close(lstate);
  15129. ctx->lua_background_state = 0;
  15130. }
  15131. #endif
  15132. DEBUG_TRACE("%s", "exiting");
  15133. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15134. CloseHandle(tls.pthread_cond_helper_mutex);
  15135. #endif
  15136. pthread_setspecific(sTlsKey, NULL);
  15137. /* Signal mg_stop() that we're done.
  15138. * WARNING: This must be the very last thing this
  15139. * thread does, as ctx becomes invalid after this line. */
  15140. ctx->stop_flag = 2;
  15141. }
  15142. /* Threads have different return types on Windows and Unix. */
  15143. #if defined(_WIN32)
  15144. static unsigned __stdcall master_thread(void *thread_func_param)
  15145. {
  15146. master_thread_run(thread_func_param);
  15147. return 0;
  15148. }
  15149. #else
  15150. static void *
  15151. master_thread(void *thread_func_param)
  15152. {
  15153. struct sigaction sa;
  15154. /* Ignore SIGPIPE */
  15155. memset(&sa, 0, sizeof(sa));
  15156. sa.sa_handler = SIG_IGN;
  15157. sigaction(SIGPIPE, &sa, NULL);
  15158. master_thread_run(thread_func_param);
  15159. return NULL;
  15160. }
  15161. #endif /* _WIN32 */
  15162. static void
  15163. free_context(struct mg_context *ctx)
  15164. {
  15165. int i;
  15166. struct mg_handler_info *tmp_rh;
  15167. if (ctx == NULL) {
  15168. return;
  15169. }
  15170. if (ctx->callbacks.exit_context) {
  15171. ctx->callbacks.exit_context(ctx);
  15172. }
  15173. /* All threads exited, no sync is needed. Destroy thread mutex and
  15174. * condvars
  15175. */
  15176. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15177. #if defined(ALTERNATIVE_QUEUE)
  15178. mg_free(ctx->client_socks);
  15179. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15180. event_destroy(ctx->client_wait_events[i]);
  15181. }
  15182. mg_free(ctx->client_wait_events);
  15183. #else
  15184. (void)pthread_cond_destroy(&ctx->sq_empty);
  15185. (void)pthread_cond_destroy(&ctx->sq_full);
  15186. #endif
  15187. /* Destroy other context global data structures mutex */
  15188. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15189. #if defined(USE_TIMERS)
  15190. timers_exit(ctx);
  15191. #endif
  15192. /* Deallocate config parameters */
  15193. for (i = 0; i < NUM_OPTIONS; i++) {
  15194. if (ctx->dd.config[i] != NULL) {
  15195. #if defined(_MSC_VER)
  15196. #pragma warning(suppress : 6001)
  15197. #endif
  15198. mg_free(ctx->dd.config[i]);
  15199. }
  15200. }
  15201. /* Deallocate request handlers */
  15202. while (ctx->dd.handlers) {
  15203. tmp_rh = ctx->dd.handlers;
  15204. ctx->dd.handlers = tmp_rh->next;
  15205. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15206. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15207. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15208. }
  15209. mg_free(tmp_rh->uri);
  15210. mg_free(tmp_rh);
  15211. }
  15212. #if !defined(NO_SSL)
  15213. /* Deallocate SSL context */
  15214. if (ctx->dd.ssl_ctx != NULL) {
  15215. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15216. int callback_ret =
  15217. (ctx->callbacks.external_ssl_ctx == NULL)
  15218. ? 0
  15219. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15220. if (callback_ret == 0) {
  15221. SSL_CTX_free(ctx->dd.ssl_ctx);
  15222. }
  15223. /* else: ignore error and ommit SSL_CTX_free in case
  15224. * callback_ret is 1 */
  15225. }
  15226. #endif /* !NO_SSL */
  15227. /* Deallocate worker thread ID array */
  15228. if (ctx->worker_threadids != NULL) {
  15229. mg_free(ctx->worker_threadids);
  15230. }
  15231. /* Deallocate worker thread ID array */
  15232. if (ctx->worker_connections != NULL) {
  15233. mg_free(ctx->worker_connections);
  15234. }
  15235. /* deallocate system name string */
  15236. mg_free(ctx->systemName);
  15237. /* Deallocate context itself */
  15238. mg_free(ctx);
  15239. }
  15240. void
  15241. mg_stop(struct mg_context *ctx)
  15242. {
  15243. pthread_t mt;
  15244. if (!ctx) {
  15245. return;
  15246. }
  15247. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15248. * two threads is not allowed. */
  15249. mt = ctx->masterthreadid;
  15250. if (mt == 0) {
  15251. return;
  15252. }
  15253. ctx->masterthreadid = 0;
  15254. /* Set stop flag, so all threads know they have to exit. */
  15255. ctx->stop_flag = 1;
  15256. /* Wait until everything has stopped. */
  15257. while (ctx->stop_flag != 2) {
  15258. (void)mg_sleep(10);
  15259. }
  15260. mg_join_thread(mt);
  15261. free_context(ctx);
  15262. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15263. (void)WSACleanup();
  15264. #endif /* _WIN32 && !__SYMBIAN32__ */
  15265. }
  15266. static void
  15267. get_system_name(char **sysName)
  15268. {
  15269. #if defined(_WIN32)
  15270. #if !defined(__SYMBIAN32__)
  15271. #if defined(_WIN32_WCE)
  15272. *sysName = mg_strdup("WinCE");
  15273. #else
  15274. char name[128];
  15275. DWORD dwVersion = 0;
  15276. DWORD dwMajorVersion = 0;
  15277. DWORD dwMinorVersion = 0;
  15278. DWORD dwBuild = 0;
  15279. BOOL wowRet, isWoW = FALSE;
  15280. #if defined(_MSC_VER)
  15281. #pragma warning(push)
  15282. /* GetVersion was declared deprecated */
  15283. #pragma warning(disable : 4996)
  15284. #endif
  15285. dwVersion = GetVersion();
  15286. #if defined(_MSC_VER)
  15287. #pragma warning(pop)
  15288. #endif
  15289. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15290. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15291. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15292. (void)dwBuild;
  15293. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15294. sprintf(name,
  15295. "Windows %u.%u%s",
  15296. (unsigned)dwMajorVersion,
  15297. (unsigned)dwMinorVersion,
  15298. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15299. *sysName = mg_strdup(name);
  15300. #endif
  15301. #else
  15302. *sysName = mg_strdup("Symbian");
  15303. #endif
  15304. #else
  15305. struct utsname name;
  15306. memset(&name, 0, sizeof(name));
  15307. uname(&name);
  15308. *sysName = mg_strdup(name.sysname);
  15309. #endif
  15310. }
  15311. struct mg_context *
  15312. mg_start(const struct mg_callbacks *callbacks,
  15313. void *user_data,
  15314. const char **options)
  15315. {
  15316. struct mg_context *ctx;
  15317. const char *name, *value, *default_value;
  15318. int idx, ok, workerthreadcount;
  15319. unsigned int i;
  15320. int itmp;
  15321. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15322. struct mg_workerTLS tls;
  15323. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15324. WSADATA data;
  15325. WSAStartup(MAKEWORD(2, 2), &data);
  15326. #endif /* _WIN32 && !__SYMBIAN32__ */
  15327. /* Allocate context and initialize reasonable general case defaults. */
  15328. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15329. return NULL;
  15330. }
  15331. /* Random number generator will initialize at the first call */
  15332. ctx->dd.auth_nonce_mask =
  15333. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15334. if (mg_init_library_called == 0) {
  15335. /* Legacy INIT, if mg_start is called without mg_init_library.
  15336. * Note: This may cause a memory leak */
  15337. const char *ports_option =
  15338. config_options[LISTENING_PORTS].default_value;
  15339. if (options) {
  15340. const char **run_options = options;
  15341. const char *optname = config_options[LISTENING_PORTS].name;
  15342. /* Try to find the "listening_ports" option */
  15343. while (*run_options) {
  15344. if (!strcmp(*run_options, optname)) {
  15345. ports_option = run_options[1];
  15346. }
  15347. run_options += 2;
  15348. }
  15349. }
  15350. if (is_ssl_port_used(ports_option)) {
  15351. /* Initialize with SSL support */
  15352. mg_init_library(MG_FEATURES_TLS);
  15353. } else {
  15354. /* Initialize without SSL support */
  15355. mg_init_library(MG_FEATURES_DEFAULT);
  15356. }
  15357. }
  15358. tls.is_master = -1;
  15359. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15360. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15361. tls.pthread_cond_helper_mutex = NULL;
  15362. #endif
  15363. pthread_setspecific(sTlsKey, &tls);
  15364. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  15365. #if !defined(ALTERNATIVE_QUEUE)
  15366. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  15367. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  15368. #endif
  15369. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  15370. if (!ok) {
  15371. /* Fatal error - abort start. However, this situation should never
  15372. * occur in practice. */
  15373. mg_cry_internal(fc(ctx),
  15374. "%s",
  15375. "Cannot initialize thread synchronization objects");
  15376. mg_free(ctx);
  15377. pthread_setspecific(sTlsKey, NULL);
  15378. return NULL;
  15379. }
  15380. if (callbacks) {
  15381. ctx->callbacks = *callbacks;
  15382. exit_callback = callbacks->exit_context;
  15383. ctx->callbacks.exit_context = 0;
  15384. }
  15385. ctx->user_data = user_data;
  15386. ctx->dd.handlers = NULL;
  15387. ctx->dd.next = NULL;
  15388. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15389. ctx->dd.shared_lua_websockets = NULL;
  15390. #endif
  15391. /* Store options */
  15392. while (options && (name = *options++) != NULL) {
  15393. if ((idx = get_option_index(name)) == -1) {
  15394. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15395. free_context(ctx);
  15396. pthread_setspecific(sTlsKey, NULL);
  15397. return NULL;
  15398. } else if ((value = *options++) == NULL) {
  15399. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15400. free_context(ctx);
  15401. pthread_setspecific(sTlsKey, NULL);
  15402. return NULL;
  15403. }
  15404. if (ctx->dd.config[idx] != NULL) {
  15405. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15406. mg_free(ctx->dd.config[idx]);
  15407. }
  15408. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15409. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15410. }
  15411. /* Set default value if needed */
  15412. for (i = 0; config_options[i].name != NULL; i++) {
  15413. default_value = config_options[i].default_value;
  15414. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15415. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15416. }
  15417. }
  15418. /* Request size option */
  15419. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15420. if (itmp < 1024) {
  15421. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  15422. free_context(ctx);
  15423. pthread_setspecific(sTlsKey, NULL);
  15424. return NULL;
  15425. }
  15426. ctx->max_request_size = (unsigned)itmp;
  15427. /* Worker thread count option */
  15428. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15429. if (workerthreadcount > MAX_WORKER_THREADS) {
  15430. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  15431. free_context(ctx);
  15432. pthread_setspecific(sTlsKey, NULL);
  15433. return NULL;
  15434. }
  15435. if (workerthreadcount <= 0) {
  15436. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  15437. free_context(ctx);
  15438. pthread_setspecific(sTlsKey, NULL);
  15439. return NULL;
  15440. }
  15441. /* Document root */
  15442. #if defined(NO_FILES)
  15443. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  15444. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  15445. free_context(ctx);
  15446. pthread_setspecific(sTlsKey, NULL);
  15447. return NULL;
  15448. }
  15449. #endif
  15450. get_system_name(&ctx->systemName);
  15451. #if defined(USE_LUA)
  15452. /* If a Lua background script has been configured, start it. */
  15453. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  15454. char ebuf[256];
  15455. struct vec opt_vec;
  15456. struct vec eq_vec;
  15457. const char *sparams;
  15458. lua_State *state = mg_prepare_lua_context_script(
  15459. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  15460. if (!state) {
  15461. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  15462. free_context(ctx);
  15463. pthread_setspecific(sTlsKey, NULL);
  15464. return NULL;
  15465. }
  15466. ctx->lua_background_state = (void *)state;
  15467. lua_newtable(state);
  15468. reg_boolean(state, "shutdown", 0);
  15469. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  15470. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  15471. reg_llstring(
  15472. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  15473. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  15474. break;
  15475. }
  15476. lua_setglobal(state, LUABACKGROUNDPARAMS);
  15477. } else {
  15478. ctx->lua_background_state = 0;
  15479. }
  15480. #endif
  15481. /* NOTE(lsm): order is important here. SSL certificates must
  15482. * be initialized before listening ports. UID must be set last. */
  15483. if (!set_gpass_option(ctx, NULL) ||
  15484. #if !defined(NO_SSL)
  15485. !init_ssl_ctx(ctx, NULL) ||
  15486. #endif
  15487. !set_ports_option(ctx) ||
  15488. #if !defined(_WIN32)
  15489. !set_uid_option(ctx) ||
  15490. #endif
  15491. !set_acl_option(ctx)) {
  15492. free_context(ctx);
  15493. pthread_setspecific(sTlsKey, NULL);
  15494. return NULL;
  15495. }
  15496. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  15497. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15498. sizeof(pthread_t),
  15499. ctx);
  15500. if (ctx->worker_threadids == NULL) {
  15501. mg_cry_internal(fc(ctx),
  15502. "%s",
  15503. "Not enough memory for worker thread ID array");
  15504. free_context(ctx);
  15505. pthread_setspecific(sTlsKey, NULL);
  15506. return NULL;
  15507. }
  15508. ctx->worker_connections =
  15509. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15510. sizeof(struct mg_connection),
  15511. ctx);
  15512. if (ctx->worker_connections == NULL) {
  15513. mg_cry_internal(fc(ctx),
  15514. "%s",
  15515. "Not enough memory for worker thread connection array");
  15516. free_context(ctx);
  15517. pthread_setspecific(sTlsKey, NULL);
  15518. return NULL;
  15519. }
  15520. #if defined(ALTERNATIVE_QUEUE)
  15521. ctx->client_wait_events =
  15522. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  15523. ctx->cfg_worker_threads,
  15524. ctx);
  15525. if (ctx->client_wait_events == NULL) {
  15526. mg_cry_internal(fc(ctx),
  15527. "%s",
  15528. "Not enough memory for worker event array");
  15529. mg_free(ctx->worker_threadids);
  15530. free_context(ctx);
  15531. pthread_setspecific(sTlsKey, NULL);
  15532. return NULL;
  15533. }
  15534. ctx->client_socks =
  15535. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  15536. ctx->cfg_worker_threads,
  15537. ctx);
  15538. if (ctx->client_wait_events == NULL) {
  15539. mg_cry_internal(fc(ctx),
  15540. "%s",
  15541. "Not enough memory for worker socket array");
  15542. mg_free(ctx->client_socks);
  15543. mg_free(ctx->worker_threadids);
  15544. free_context(ctx);
  15545. pthread_setspecific(sTlsKey, NULL);
  15546. return NULL;
  15547. }
  15548. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15549. ctx->client_wait_events[i] = event_create();
  15550. if (ctx->client_wait_events[i] == 0) {
  15551. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  15552. while (i > 0) {
  15553. i--;
  15554. event_destroy(ctx->client_wait_events[i]);
  15555. }
  15556. mg_free(ctx->client_socks);
  15557. mg_free(ctx->worker_threadids);
  15558. free_context(ctx);
  15559. pthread_setspecific(sTlsKey, NULL);
  15560. return NULL;
  15561. }
  15562. }
  15563. #endif
  15564. #if defined(USE_TIMERS)
  15565. if (timers_init(ctx) != 0) {
  15566. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  15567. free_context(ctx);
  15568. pthread_setspecific(sTlsKey, NULL);
  15569. return NULL;
  15570. }
  15571. #endif
  15572. /* Context has been created - init user libraries */
  15573. if (ctx->callbacks.init_context) {
  15574. ctx->callbacks.init_context(ctx);
  15575. }
  15576. ctx->callbacks.exit_context = exit_callback;
  15577. ctx->context_type = CONTEXT_SERVER; /* server context */
  15578. /* Start master (listening) thread */
  15579. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  15580. /* Start worker threads */
  15581. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15582. struct worker_thread_args *wta = (struct worker_thread_args *)
  15583. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  15584. if (wta) {
  15585. wta->ctx = ctx;
  15586. wta->index = (int)i;
  15587. }
  15588. if ((wta == NULL)
  15589. || (mg_start_thread_with_id(worker_thread,
  15590. wta,
  15591. &ctx->worker_threadids[i]) != 0)) {
  15592. /* thread was not created */
  15593. if (wta != NULL) {
  15594. mg_free(wta);
  15595. }
  15596. if (i > 0) {
  15597. mg_cry_internal(fc(ctx),
  15598. "Cannot start worker thread %i: error %ld",
  15599. i + 1,
  15600. (long)ERRNO);
  15601. } else {
  15602. mg_cry_internal(fc(ctx),
  15603. "Cannot create threads: error %ld",
  15604. (long)ERRNO);
  15605. free_context(ctx);
  15606. pthread_setspecific(sTlsKey, NULL);
  15607. return NULL;
  15608. }
  15609. break;
  15610. }
  15611. }
  15612. pthread_setspecific(sTlsKey, NULL);
  15613. return ctx;
  15614. }
  15615. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15616. /* Add an additional domain to an already running web server. */
  15617. int
  15618. mg_start_domain(struct mg_context *ctx, const char **options)
  15619. {
  15620. const char *name;
  15621. const char *value;
  15622. const char *default_value;
  15623. struct mg_domain_context *new_dom;
  15624. struct mg_domain_context *dom;
  15625. int idx, i;
  15626. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  15627. return -1;
  15628. }
  15629. new_dom = (struct mg_domain_context *)
  15630. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  15631. if (!new_dom) {
  15632. /* Out of memory */
  15633. return -6;
  15634. }
  15635. /* Store options - TODO: unite duplicate code */
  15636. while (options && (name = *options++) != NULL) {
  15637. if ((idx = get_option_index(name)) == -1) {
  15638. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15639. mg_free(new_dom);
  15640. return -2;
  15641. } else if ((value = *options++) == NULL) {
  15642. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15643. mg_free(new_dom);
  15644. return -2;
  15645. }
  15646. if (new_dom->config[idx] != NULL) {
  15647. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15648. mg_free(new_dom->config[idx]);
  15649. }
  15650. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  15651. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15652. }
  15653. /* Authentication domain is mandatory */
  15654. /* TODO: Maybe use a new option hostname? */
  15655. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  15656. return -4;
  15657. }
  15658. /* Set default value if needed. Take the config value from
  15659. * ctx as a default value. */
  15660. for (i = 0; config_options[i].name != NULL; i++) {
  15661. default_value = ctx->dd.config[i];
  15662. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  15663. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  15664. }
  15665. }
  15666. new_dom->handlers = NULL;
  15667. new_dom->next = NULL;
  15668. new_dom->nonce_count = 0;
  15669. new_dom->auth_nonce_mask =
  15670. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  15671. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15672. new_dom->shared_lua_websockets = NULL;
  15673. #endif
  15674. if (!init_ssl_ctx(ctx, new_dom)) {
  15675. /* Init SSL failed */
  15676. mg_free(new_dom);
  15677. return -3;
  15678. }
  15679. /* Add element to linked list. */
  15680. mg_lock_context(ctx);
  15681. idx = 0;
  15682. dom = &(ctx->dd);
  15683. for (;;) {
  15684. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  15685. dom->config[AUTHENTICATION_DOMAIN])) {
  15686. /* Domain collision */
  15687. mg_cry_internal(fc(ctx),
  15688. "domain %s already in use",
  15689. new_dom->config[AUTHENTICATION_DOMAIN]);
  15690. mg_free(new_dom);
  15691. return -5;
  15692. }
  15693. /* Count number of domains */
  15694. idx++;
  15695. if (dom->next == NULL) {
  15696. dom->next = new_dom;
  15697. break;
  15698. }
  15699. dom = dom->next;
  15700. }
  15701. mg_unlock_context(ctx);
  15702. /* Return domain number */
  15703. return idx;
  15704. }
  15705. #endif
  15706. /* Feature check API function */
  15707. unsigned
  15708. mg_check_feature(unsigned feature)
  15709. {
  15710. static const unsigned feature_set = 0
  15711. /* Set bits for available features according to API documentation.
  15712. * This bit mask is created at compile time, according to the active
  15713. * preprocessor defines. It is a single const value at runtime. */
  15714. #if !defined(NO_FILES)
  15715. | MG_FEATURES_FILES
  15716. #endif
  15717. #if !defined(NO_SSL)
  15718. | MG_FEATURES_SSL
  15719. #endif
  15720. #if !defined(NO_CGI)
  15721. | MG_FEATURES_CGI
  15722. #endif
  15723. #if defined(USE_IPV6)
  15724. | MG_FEATURES_IPV6
  15725. #endif
  15726. #if defined(USE_WEBSOCKET)
  15727. | MG_FEATURES_WEBSOCKET
  15728. #endif
  15729. #if defined(USE_LUA)
  15730. | MG_FEATURES_LUA
  15731. #endif
  15732. #if defined(USE_DUKTAPE)
  15733. | MG_FEATURES_SSJS
  15734. #endif
  15735. #if !defined(NO_CACHING)
  15736. | MG_FEATURES_CACHE
  15737. #endif
  15738. #if defined(USE_SERVER_STATS)
  15739. | MG_FEATURES_STATS
  15740. #endif
  15741. #if defined(USE_ZLIB)
  15742. | MG_FEATURES_COMPRESSION
  15743. #endif
  15744. /* Set some extra bits not defined in the API documentation.
  15745. * These bits may change without further notice. */
  15746. #if defined(MG_LEGACY_INTERFACE)
  15747. | 0x00008000u
  15748. #endif
  15749. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15750. | 0x00004000u
  15751. #endif
  15752. #if defined(MEMORY_DEBUGGING)
  15753. | 0x00001000u
  15754. #endif
  15755. #if defined(USE_TIMERS)
  15756. | 0x00020000u
  15757. #endif
  15758. #if !defined(NO_NONCE_CHECK)
  15759. | 0x00040000u
  15760. #endif
  15761. #if !defined(NO_POPEN)
  15762. | 0x00080000u
  15763. #endif
  15764. ;
  15765. return (feature & feature_set);
  15766. }
  15767. /* strcat with additional NULL check to avoid clang scan-build warning. */
  15768. #define strcat0(a, b) \
  15769. { \
  15770. if ((a != NULL) && (b != NULL)) { \
  15771. strcat(a, b); \
  15772. } \
  15773. }
  15774. /* Get system information. It can be printed or stored by the caller.
  15775. * Return the size of available information. */
  15776. static int
  15777. mg_get_system_info_impl(char *buffer, int buflen)
  15778. {
  15779. char block[256];
  15780. int system_info_length = 0;
  15781. #if defined(_WIN32)
  15782. const char *eol = "\r\n";
  15783. #else
  15784. const char *eol = "\n";
  15785. #endif
  15786. const char *eoobj = "}";
  15787. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15788. if ((buffer == NULL) || (buflen < 1)) {
  15789. buflen = 0;
  15790. } else {
  15791. *buffer = 0;
  15792. }
  15793. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15794. system_info_length += (int)strlen(block);
  15795. if (system_info_length < buflen) {
  15796. strcat0(buffer, block);
  15797. }
  15798. /* Server version */
  15799. {
  15800. const char *version = mg_version();
  15801. mg_snprintf(NULL,
  15802. NULL,
  15803. block,
  15804. sizeof(block),
  15805. "\"version\" : \"%s\",%s",
  15806. version,
  15807. eol);
  15808. system_info_length += (int)strlen(block);
  15809. if (system_info_length < buflen) {
  15810. strcat0(buffer, block);
  15811. }
  15812. }
  15813. /* System info */
  15814. {
  15815. #if defined(_WIN32)
  15816. #if !defined(__SYMBIAN32__)
  15817. DWORD dwVersion = 0;
  15818. DWORD dwMajorVersion = 0;
  15819. DWORD dwMinorVersion = 0;
  15820. SYSTEM_INFO si;
  15821. GetSystemInfo(&si);
  15822. #if defined(_MSC_VER)
  15823. #pragma warning(push)
  15824. /* GetVersion was declared deprecated */
  15825. #pragma warning(disable : 4996)
  15826. #endif
  15827. dwVersion = GetVersion();
  15828. #if defined(_MSC_VER)
  15829. #pragma warning(pop)
  15830. #endif
  15831. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15832. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15833. mg_snprintf(NULL,
  15834. NULL,
  15835. block,
  15836. sizeof(block),
  15837. "\"os\" : \"Windows %u.%u\",%s",
  15838. (unsigned)dwMajorVersion,
  15839. (unsigned)dwMinorVersion,
  15840. eol);
  15841. system_info_length += (int)strlen(block);
  15842. if (system_info_length < buflen) {
  15843. strcat0(buffer, block);
  15844. }
  15845. mg_snprintf(NULL,
  15846. NULL,
  15847. block,
  15848. sizeof(block),
  15849. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  15850. (unsigned)si.wProcessorArchitecture,
  15851. (unsigned)si.dwNumberOfProcessors,
  15852. (unsigned)si.dwActiveProcessorMask,
  15853. eol);
  15854. system_info_length += (int)strlen(block);
  15855. if (system_info_length < buflen) {
  15856. strcat0(buffer, block);
  15857. }
  15858. #else
  15859. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  15860. system_info_length += (int)strlen(block);
  15861. if (system_info_length < buflen) {
  15862. strcat0(buffer, block);
  15863. }
  15864. #endif
  15865. #else
  15866. struct utsname name;
  15867. memset(&name, 0, sizeof(name));
  15868. uname(&name);
  15869. mg_snprintf(NULL,
  15870. NULL,
  15871. block,
  15872. sizeof(block),
  15873. "\"os\" : \"%s %s (%s) - %s\",%s",
  15874. name.sysname,
  15875. name.version,
  15876. name.release,
  15877. name.machine,
  15878. eol);
  15879. system_info_length += (int)strlen(block);
  15880. if (system_info_length < buflen) {
  15881. strcat0(buffer, block);
  15882. }
  15883. #endif
  15884. }
  15885. /* Features */
  15886. {
  15887. mg_snprintf(NULL,
  15888. NULL,
  15889. block,
  15890. sizeof(block),
  15891. "\"features\" : %lu,%s"
  15892. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  15893. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  15894. eol,
  15895. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  15896. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  15897. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  15898. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  15899. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  15900. : "",
  15901. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  15902. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  15903. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  15904. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  15905. eol);
  15906. system_info_length += (int)strlen(block);
  15907. if (system_info_length < buflen) {
  15908. strcat0(buffer, block);
  15909. }
  15910. #if defined(USE_LUA)
  15911. mg_snprintf(NULL,
  15912. NULL,
  15913. block,
  15914. sizeof(block),
  15915. "\"lua_version\" : \"%u (%s)\",%s",
  15916. (unsigned)LUA_VERSION_NUM,
  15917. LUA_RELEASE,
  15918. eol);
  15919. system_info_length += (int)strlen(block);
  15920. if (system_info_length < buflen) {
  15921. strcat0(buffer, block);
  15922. }
  15923. #endif
  15924. #if defined(USE_DUKTAPE)
  15925. mg_snprintf(NULL,
  15926. NULL,
  15927. block,
  15928. sizeof(block),
  15929. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  15930. (unsigned)DUK_VERSION / 10000,
  15931. ((unsigned)DUK_VERSION / 100) % 100,
  15932. (unsigned)DUK_VERSION % 100,
  15933. eol);
  15934. system_info_length += (int)strlen(block);
  15935. if (system_info_length < buflen) {
  15936. strcat0(buffer, block);
  15937. }
  15938. #endif
  15939. }
  15940. /* Build date */
  15941. {
  15942. #if defined(__GNUC__)
  15943. #pragma GCC diagnostic push
  15944. /* Disable bogus compiler warning -Wdate-time */
  15945. #pragma GCC diagnostic ignored "-Wdate-time"
  15946. #endif
  15947. mg_snprintf(NULL,
  15948. NULL,
  15949. block,
  15950. sizeof(block),
  15951. "\"build\" : \"%s\",%s",
  15952. __DATE__,
  15953. eol);
  15954. #if defined(__GNUC__)
  15955. #pragma GCC diagnostic pop
  15956. #endif
  15957. system_info_length += (int)strlen(block);
  15958. if (system_info_length < buflen) {
  15959. strcat0(buffer, block);
  15960. }
  15961. }
  15962. /* Compiler information */
  15963. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  15964. {
  15965. #if defined(_MSC_VER)
  15966. mg_snprintf(NULL,
  15967. NULL,
  15968. block,
  15969. sizeof(block),
  15970. "\"compiler\" : \"MSC: %u (%u)\",%s",
  15971. (unsigned)_MSC_VER,
  15972. (unsigned)_MSC_FULL_VER,
  15973. eol);
  15974. system_info_length += (int)strlen(block);
  15975. if (system_info_length < buflen) {
  15976. strcat0(buffer, block);
  15977. }
  15978. #elif defined(__MINGW64__)
  15979. mg_snprintf(NULL,
  15980. NULL,
  15981. block,
  15982. sizeof(block),
  15983. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  15984. (unsigned)__MINGW64_VERSION_MAJOR,
  15985. (unsigned)__MINGW64_VERSION_MINOR,
  15986. eol);
  15987. system_info_length += (int)strlen(block);
  15988. if (system_info_length < buflen) {
  15989. strcat0(buffer, block);
  15990. }
  15991. mg_snprintf(NULL,
  15992. NULL,
  15993. block,
  15994. sizeof(block),
  15995. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15996. (unsigned)__MINGW32_MAJOR_VERSION,
  15997. (unsigned)__MINGW32_MINOR_VERSION,
  15998. eol);
  15999. system_info_length += (int)strlen(block);
  16000. if (system_info_length < buflen) {
  16001. strcat0(buffer, block);
  16002. }
  16003. #elif defined(__MINGW32__)
  16004. mg_snprintf(NULL,
  16005. NULL,
  16006. block,
  16007. sizeof(block),
  16008. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16009. (unsigned)__MINGW32_MAJOR_VERSION,
  16010. (unsigned)__MINGW32_MINOR_VERSION,
  16011. eol);
  16012. system_info_length += (int)strlen(block);
  16013. if (system_info_length < buflen) {
  16014. strcat0(buffer, block);
  16015. }
  16016. #elif defined(__clang__)
  16017. mg_snprintf(NULL,
  16018. NULL,
  16019. block,
  16020. sizeof(block),
  16021. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  16022. __clang_major__,
  16023. __clang_minor__,
  16024. __clang_patchlevel__,
  16025. __clang_version__,
  16026. eol);
  16027. system_info_length += (int)strlen(block);
  16028. if (system_info_length < buflen) {
  16029. strcat0(buffer, block);
  16030. }
  16031. #elif defined(__GNUC__)
  16032. mg_snprintf(NULL,
  16033. NULL,
  16034. block,
  16035. sizeof(block),
  16036. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  16037. (unsigned)__GNUC__,
  16038. (unsigned)__GNUC_MINOR__,
  16039. (unsigned)__GNUC_PATCHLEVEL__,
  16040. eol);
  16041. system_info_length += (int)strlen(block);
  16042. if (system_info_length < buflen) {
  16043. strcat0(buffer, block);
  16044. }
  16045. #elif defined(__INTEL_COMPILER)
  16046. mg_snprintf(NULL,
  16047. NULL,
  16048. block,
  16049. sizeof(block),
  16050. "\"compiler\" : \"Intel C/C++: %u\",%s",
  16051. (unsigned)__INTEL_COMPILER,
  16052. eol);
  16053. system_info_length += (int)strlen(block);
  16054. if (system_info_length < buflen) {
  16055. strcat0(buffer, block);
  16056. }
  16057. #elif defined(__BORLANDC__)
  16058. mg_snprintf(NULL,
  16059. NULL,
  16060. block,
  16061. sizeof(block),
  16062. "\"compiler\" : \"Borland C: 0x%x\",%s",
  16063. (unsigned)__BORLANDC__,
  16064. eol);
  16065. system_info_length += (int)strlen(block);
  16066. if (system_info_length < buflen) {
  16067. strcat0(buffer, block);
  16068. }
  16069. #elif defined(__SUNPRO_C)
  16070. mg_snprintf(NULL,
  16071. NULL,
  16072. block,
  16073. sizeof(block),
  16074. "\"compiler\" : \"Solaris: 0x%x\",%s",
  16075. (unsigned)__SUNPRO_C,
  16076. eol);
  16077. system_info_length += (int)strlen(block);
  16078. if (system_info_length < buflen) {
  16079. strcat0(buffer, block);
  16080. }
  16081. #else
  16082. mg_snprintf(NULL,
  16083. NULL,
  16084. block,
  16085. sizeof(block),
  16086. "\"compiler\" : \"other\",%s",
  16087. eol);
  16088. system_info_length += (int)strlen(block);
  16089. if (system_info_length < buflen) {
  16090. strcat0(buffer, block);
  16091. }
  16092. #endif
  16093. }
  16094. /* Determine 32/64 bit data mode.
  16095. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16096. {
  16097. mg_snprintf(NULL,
  16098. NULL,
  16099. block,
  16100. sizeof(block),
  16101. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16102. "char:%u/%u, "
  16103. "ptr:%u, size:%u, time:%u\"%s",
  16104. (unsigned)sizeof(short),
  16105. (unsigned)sizeof(int),
  16106. (unsigned)sizeof(long),
  16107. (unsigned)sizeof(long long),
  16108. (unsigned)sizeof(float),
  16109. (unsigned)sizeof(double),
  16110. (unsigned)sizeof(long double),
  16111. (unsigned)sizeof(char),
  16112. (unsigned)sizeof(wchar_t),
  16113. (unsigned)sizeof(void *),
  16114. (unsigned)sizeof(size_t),
  16115. (unsigned)sizeof(time_t),
  16116. eol);
  16117. system_info_length += (int)strlen(block);
  16118. if (system_info_length < buflen) {
  16119. strcat0(buffer, block);
  16120. }
  16121. }
  16122. /* Terminate string */
  16123. if ((buflen > 0) && buffer && buffer[0]) {
  16124. if (system_info_length < buflen) {
  16125. strcat0(buffer, eoobj);
  16126. strcat0(buffer, eol);
  16127. }
  16128. }
  16129. system_info_length += reserved_len;
  16130. return system_info_length;
  16131. }
  16132. #if defined(USE_SERVER_STATS)
  16133. /* Get context information. It can be printed or stored by the caller.
  16134. * Return the size of available information. */
  16135. static int
  16136. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  16137. {
  16138. char block[256];
  16139. int context_info_length = 0;
  16140. #if defined(_WIN32)
  16141. const char *eol = "\r\n";
  16142. #else
  16143. const char *eol = "\n";
  16144. #endif
  16145. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16146. const char *eoobj = "}";
  16147. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16148. if ((buffer == NULL) || (buflen < 1)) {
  16149. buflen = 0;
  16150. } else {
  16151. *buffer = 0;
  16152. }
  16153. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16154. context_info_length += (int)strlen(block);
  16155. if (context_info_length < buflen) {
  16156. strcat0(buffer, block);
  16157. }
  16158. if (ms) { /* <-- should be always true */
  16159. /* Memory information */
  16160. mg_snprintf(NULL,
  16161. NULL,
  16162. block,
  16163. sizeof(block),
  16164. "\"memory\" : {%s"
  16165. "\"blocks\" : %i,%s"
  16166. "\"used\" : %" INT64_FMT ",%s"
  16167. "\"maxUsed\" : %" INT64_FMT "%s"
  16168. "}%s%s",
  16169. eol,
  16170. ms->blockCount,
  16171. eol,
  16172. ms->totalMemUsed,
  16173. eol,
  16174. ms->maxMemUsed,
  16175. eol,
  16176. (ctx ? "," : ""),
  16177. eol);
  16178. context_info_length += (int)strlen(block);
  16179. if (context_info_length + reserved_len < buflen) {
  16180. strcat0(buffer, block);
  16181. }
  16182. }
  16183. if (ctx) {
  16184. /* Connections information */
  16185. mg_snprintf(NULL,
  16186. NULL,
  16187. block,
  16188. sizeof(block),
  16189. "\"connections\" : {%s"
  16190. "\"active\" : %i,%s"
  16191. "\"maxActive\" : %i,%s"
  16192. "\"total\" : %" INT64_FMT "%s"
  16193. "},%s",
  16194. eol,
  16195. ctx->active_connections,
  16196. eol,
  16197. ctx->max_connections,
  16198. eol,
  16199. ctx->total_connections,
  16200. eol,
  16201. eol);
  16202. context_info_length += (int)strlen(block);
  16203. if (context_info_length + reserved_len < buflen) {
  16204. strcat0(buffer, block);
  16205. }
  16206. /* Requests information */
  16207. mg_snprintf(NULL,
  16208. NULL,
  16209. block,
  16210. sizeof(block),
  16211. "\"requests\" : {%s"
  16212. "\"total\" : %" INT64_FMT "%s"
  16213. "},%s",
  16214. eol,
  16215. ctx->total_requests,
  16216. eol,
  16217. eol);
  16218. context_info_length += (int)strlen(block);
  16219. if (context_info_length + reserved_len < buflen) {
  16220. strcat0(buffer, block);
  16221. }
  16222. /* Data information */
  16223. mg_snprintf(NULL,
  16224. NULL,
  16225. block,
  16226. sizeof(block),
  16227. "\"data\" : {%s"
  16228. "\"read\" : %" INT64_FMT "%s,"
  16229. "\"written\" : %" INT64_FMT "%s"
  16230. "},%s",
  16231. eol,
  16232. ctx->total_data_read,
  16233. eol,
  16234. ctx->total_data_written,
  16235. eol,
  16236. eol);
  16237. context_info_length += (int)strlen(block);
  16238. if (context_info_length + reserved_len < buflen) {
  16239. strcat0(buffer, block);
  16240. }
  16241. /* Execution time information */
  16242. char start_time_str[64] = {0};
  16243. char now_str[64] = {0};
  16244. time_t start_time = ctx->start_time;
  16245. time_t now = time(NULL);
  16246. gmt_time_string(start_time_str,
  16247. sizeof(start_time_str) - 1,
  16248. &start_time);
  16249. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16250. mg_snprintf(NULL,
  16251. NULL,
  16252. block,
  16253. sizeof(block),
  16254. "\"time\" : {%s"
  16255. "\"uptime\" : %.0f,%s"
  16256. "\"start\" : \"%s\",%s"
  16257. "\"now\" : \"%s\"%s"
  16258. "}%s",
  16259. eol,
  16260. difftime(now, start_time),
  16261. eol,
  16262. start_time_str,
  16263. eol,
  16264. now_str,
  16265. eol,
  16266. eol);
  16267. context_info_length += (int)strlen(block);
  16268. if (context_info_length + reserved_len < buflen) {
  16269. strcat0(buffer, block);
  16270. }
  16271. }
  16272. /* Terminate string */
  16273. if ((buflen > 0) && buffer && buffer[0]) {
  16274. if (context_info_length < buflen) {
  16275. strcat0(buffer, eoobj);
  16276. strcat0(buffer, eol);
  16277. }
  16278. }
  16279. context_info_length += reserved_len;
  16280. return context_info_length;
  16281. }
  16282. #endif
  16283. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16284. /* Get connection information. It can be printed or stored by the caller.
  16285. * Return the size of available information. */
  16286. static int
  16287. mg_get_connection_info_impl(const struct mg_context *ctx,
  16288. int idx,
  16289. char *buffer,
  16290. int buflen)
  16291. {
  16292. const struct mg_connection *conn;
  16293. const struct mg_request_info *ri;
  16294. char block[256];
  16295. int connection_info_length = 0;
  16296. int state = 0;
  16297. const char *state_str = "unknown";
  16298. #if defined(_WIN32)
  16299. const char *eol = "\r\n";
  16300. #else
  16301. const char *eol = "\n";
  16302. #endif
  16303. const char *eoobj = "}";
  16304. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16305. if ((buffer == NULL) || (buflen < 1)) {
  16306. buflen = 0;
  16307. } else {
  16308. *buffer = 0;
  16309. }
  16310. if ((ctx == NULL) || (idx < 0)) {
  16311. /* Parameter error */
  16312. return 0;
  16313. }
  16314. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16315. /* Out of range */
  16316. return 0;
  16317. }
  16318. /* Take connection [idx]. This connection is not locked in
  16319. * any way, so some other thread might use it. */
  16320. conn = (ctx->worker_connections) + idx;
  16321. /* Initialize output string */
  16322. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16323. connection_info_length += (int)strlen(block);
  16324. if (connection_info_length < buflen) {
  16325. strcat0(buffer, block);
  16326. }
  16327. /* Init variables */
  16328. ri = &(conn->request_info);
  16329. #if defined(USE_SERVER_STATS)
  16330. state = conn->conn_state;
  16331. /* State as string */
  16332. switch (state) {
  16333. case 0:
  16334. state_str = "undefined";
  16335. break;
  16336. case 1:
  16337. state_str = "not used";
  16338. break;
  16339. case 2:
  16340. state_str = "init";
  16341. break;
  16342. case 3:
  16343. state_str = "ready";
  16344. break;
  16345. case 4:
  16346. state_str = "processing";
  16347. break;
  16348. case 5:
  16349. state_str = "processed";
  16350. break;
  16351. case 6:
  16352. state_str = "to close";
  16353. break;
  16354. case 7:
  16355. state_str = "closing";
  16356. break;
  16357. case 8:
  16358. state_str = "closed";
  16359. break;
  16360. case 9:
  16361. state_str = "done";
  16362. break;
  16363. }
  16364. #endif
  16365. /* Connection info */
  16366. if ((state >= 3) && (state < 9)) {
  16367. mg_snprintf(NULL,
  16368. NULL,
  16369. block,
  16370. sizeof(block),
  16371. "\"connection\" : {%s"
  16372. "\"remote\" : {%s"
  16373. "\"protocol\" : \"%s\",%s"
  16374. "\"addr\" : \"%s\",%s"
  16375. "\"port\" : %u%s"
  16376. "},%s"
  16377. "\"handled_requests\" : %u%s"
  16378. "},%s",
  16379. eol,
  16380. eol,
  16381. get_proto_name(conn),
  16382. eol,
  16383. ri->remote_addr,
  16384. eol,
  16385. ri->remote_port,
  16386. eol,
  16387. eol,
  16388. conn->handled_requests,
  16389. eol,
  16390. eol);
  16391. connection_info_length += (int)strlen(block);
  16392. if (connection_info_length + reserved_len < buflen) {
  16393. strcat0(buffer, block);
  16394. }
  16395. }
  16396. /* Request info */
  16397. if ((state >= 4) && (state < 6)) {
  16398. mg_snprintf(NULL,
  16399. NULL,
  16400. block,
  16401. sizeof(block),
  16402. "\"request_info\" : {%s"
  16403. "\"method\" : \"%s\",%s"
  16404. "\"uri\" : \"%s\",%s"
  16405. "\"query\" : %s%s%s%s"
  16406. "},%s",
  16407. eol,
  16408. ri->request_method,
  16409. eol,
  16410. ri->request_uri,
  16411. eol,
  16412. ri->query_string ? "\"" : "",
  16413. ri->query_string ? ri->query_string : "null",
  16414. ri->query_string ? "\"" : "",
  16415. eol,
  16416. eol);
  16417. connection_info_length += (int)strlen(block);
  16418. if (connection_info_length + reserved_len < buflen) {
  16419. strcat0(buffer, block);
  16420. }
  16421. }
  16422. /* Execution time information */
  16423. if ((state >= 2) && (state < 9)) {
  16424. char start_time_str[64] = {0};
  16425. char now_str[64] = {0};
  16426. time_t start_time = conn->conn_birth_time;
  16427. time_t now = time(NULL);
  16428. gmt_time_string(start_time_str,
  16429. sizeof(start_time_str) - 1,
  16430. &start_time);
  16431. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16432. mg_snprintf(NULL,
  16433. NULL,
  16434. block,
  16435. sizeof(block),
  16436. "\"time\" : {%s"
  16437. "\"uptime\" : %.0f,%s"
  16438. "\"start\" : \"%s\",%s"
  16439. "\"now\" : \"%s\"%s"
  16440. "},%s",
  16441. eol,
  16442. difftime(now, start_time),
  16443. eol,
  16444. start_time_str,
  16445. eol,
  16446. now_str,
  16447. eol,
  16448. eol);
  16449. connection_info_length += (int)strlen(block);
  16450. if (connection_info_length + reserved_len < buflen) {
  16451. strcat0(buffer, block);
  16452. }
  16453. }
  16454. /* Remote user name */
  16455. if ((ri->remote_user) && (state < 9)) {
  16456. mg_snprintf(NULL,
  16457. NULL,
  16458. block,
  16459. sizeof(block),
  16460. "\"user\" : {%s"
  16461. "\"name\" : \"%s\",%s"
  16462. "},%s",
  16463. eol,
  16464. ri->remote_user,
  16465. eol,
  16466. eol);
  16467. connection_info_length += (int)strlen(block);
  16468. if (connection_info_length + reserved_len < buflen) {
  16469. strcat0(buffer, block);
  16470. }
  16471. }
  16472. /* Data block */
  16473. if (state >= 3) {
  16474. mg_snprintf(NULL,
  16475. NULL,
  16476. block,
  16477. sizeof(block),
  16478. "\"data\" : {%s"
  16479. "\"read\" : %" INT64_FMT ",%s"
  16480. "\"written\" : %" INT64_FMT "%s"
  16481. "},%s",
  16482. eol,
  16483. conn->consumed_content,
  16484. eol,
  16485. conn->num_bytes_sent,
  16486. eol,
  16487. eol);
  16488. connection_info_length += (int)strlen(block);
  16489. if (connection_info_length + reserved_len < buflen) {
  16490. strcat0(buffer, block);
  16491. }
  16492. }
  16493. /* State */
  16494. mg_snprintf(NULL,
  16495. NULL,
  16496. block,
  16497. sizeof(block),
  16498. "\"state\" : \"%s\"%s",
  16499. state_str,
  16500. eol);
  16501. connection_info_length += (int)strlen(block);
  16502. if (connection_info_length + reserved_len < buflen) {
  16503. strcat0(buffer, block);
  16504. }
  16505. /* Terminate string */
  16506. if ((buflen > 0) && buffer && buffer[0]) {
  16507. if (connection_info_length < buflen) {
  16508. strcat0(buffer, eoobj);
  16509. strcat0(buffer, eol);
  16510. }
  16511. }
  16512. connection_info_length += reserved_len;
  16513. return connection_info_length;
  16514. }
  16515. #endif
  16516. /* Get system information. It can be printed or stored by the caller.
  16517. * Return the size of available information. */
  16518. int
  16519. mg_get_system_info(char *buffer, int buflen)
  16520. {
  16521. if ((buffer == NULL) || (buflen < 1)) {
  16522. return mg_get_system_info_impl(NULL, 0);
  16523. } else {
  16524. /* Reset buffer, so we can always use strcat. */
  16525. buffer[0] = 0;
  16526. return mg_get_system_info_impl(buffer, buflen);
  16527. }
  16528. }
  16529. /* Get context information. It can be printed or stored by the caller.
  16530. * Return the size of available information. */
  16531. int
  16532. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16533. {
  16534. #if defined(USE_SERVER_STATS)
  16535. if ((buffer == NULL) || (buflen < 1)) {
  16536. return mg_get_context_info_impl(ctx, NULL, 0);
  16537. } else {
  16538. /* Reset buffer, so we can always use strcat. */
  16539. buffer[0] = 0;
  16540. return mg_get_context_info_impl(ctx, buffer, buflen);
  16541. }
  16542. #else
  16543. (void)ctx;
  16544. if ((buffer != NULL) && (buflen > 0)) {
  16545. buffer[0] = 0;
  16546. }
  16547. return 0;
  16548. #endif
  16549. }
  16550. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16551. int
  16552. mg_get_connection_info(const struct mg_context *ctx,
  16553. int idx,
  16554. char *buffer,
  16555. int buflen)
  16556. {
  16557. if ((buffer == NULL) || (buflen < 1)) {
  16558. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  16559. } else {
  16560. /* Reset buffer, so we can always use strcat. */
  16561. buffer[0] = 0;
  16562. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  16563. }
  16564. }
  16565. #endif
  16566. /* Initialize this library. This function does not need to be thread safe.
  16567. */
  16568. unsigned
  16569. mg_init_library(unsigned features)
  16570. {
  16571. #if !defined(NO_SSL)
  16572. char ebuf[128];
  16573. #endif
  16574. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  16575. unsigned features_inited = features_to_init;
  16576. if (mg_init_library_called <= 0) {
  16577. /* Not initialized yet */
  16578. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  16579. return 0;
  16580. }
  16581. }
  16582. mg_global_lock();
  16583. if (mg_init_library_called <= 0) {
  16584. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  16585. /* Fatal error - abort start. However, this situation should
  16586. * never occur in practice. */
  16587. mg_global_unlock();
  16588. return 0;
  16589. }
  16590. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16591. InitializeCriticalSection(&global_log_file_lock);
  16592. #endif /* _WIN32 && !__SYMBIAN32__ */
  16593. #if !defined(_WIN32)
  16594. pthread_mutexattr_init(&pthread_mutex_attr);
  16595. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  16596. #endif
  16597. #if defined(USE_LUA)
  16598. lua_init_optional_libraries();
  16599. #endif
  16600. }
  16601. mg_global_unlock();
  16602. #if !defined(NO_SSL)
  16603. if (features_to_init & MG_FEATURES_SSL) {
  16604. if (!mg_ssl_initialized) {
  16605. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  16606. mg_ssl_initialized = 1;
  16607. } else {
  16608. (void)ebuf;
  16609. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  16610. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  16611. }
  16612. } else {
  16613. /* ssl already initialized */
  16614. }
  16615. }
  16616. #endif
  16617. /* Start WinSock for Windows */
  16618. mg_global_lock();
  16619. if (mg_init_library_called <= 0) {
  16620. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16621. WSADATA data;
  16622. WSAStartup(MAKEWORD(2, 2), &data);
  16623. #endif /* _WIN32 && !__SYMBIAN32__ */
  16624. mg_init_library_called = 1;
  16625. } else {
  16626. mg_init_library_called++;
  16627. }
  16628. mg_global_unlock();
  16629. return features_inited;
  16630. }
  16631. /* Un-initialize this library. */
  16632. unsigned
  16633. mg_exit_library(void)
  16634. {
  16635. if (mg_init_library_called <= 0) {
  16636. return 0;
  16637. }
  16638. mg_global_lock();
  16639. mg_init_library_called--;
  16640. if (mg_init_library_called == 0) {
  16641. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16642. (void)WSACleanup();
  16643. #endif /* _WIN32 && !__SYMBIAN32__ */
  16644. #if !defined(NO_SSL)
  16645. if (mg_ssl_initialized) {
  16646. uninitialize_ssl();
  16647. mg_ssl_initialized = 0;
  16648. }
  16649. #endif
  16650. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16651. (void)DeleteCriticalSection(&global_log_file_lock);
  16652. #endif /* _WIN32 && !__SYMBIAN32__ */
  16653. #if !defined(_WIN32)
  16654. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  16655. #endif
  16656. (void)pthread_key_delete(sTlsKey);
  16657. #if defined(USE_LUA)
  16658. lua_exit_optional_libraries();
  16659. #endif
  16660. mg_global_unlock();
  16661. (void)pthread_mutex_destroy(&global_lock_mutex);
  16662. return 1;
  16663. }
  16664. mg_global_unlock();
  16665. return 1;
  16666. }
  16667. /* End of civetweb.c */