civetweb.c 515 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315
  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. #if defined(MG_EXPERIMENTAL_INTERFACES)
  1957. LUA_DEBUG_PARAMS,
  1958. #endif
  1959. #endif
  1960. #if defined(USE_DUKTAPE)
  1961. DUKTAPE_SCRIPT_EXTENSIONS,
  1962. #endif
  1963. #if defined(USE_WEBSOCKET)
  1964. WEBSOCKET_ROOT,
  1965. #endif
  1966. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1967. LUA_WEBSOCKET_EXTENSIONS,
  1968. #endif
  1969. ACCESS_CONTROL_ALLOW_ORIGIN,
  1970. ACCESS_CONTROL_ALLOW_METHODS,
  1971. ACCESS_CONTROL_ALLOW_HEADERS,
  1972. ERROR_PAGES,
  1973. #if !defined(NO_CACHING)
  1974. STATIC_FILE_MAX_AGE,
  1975. #endif
  1976. #if !defined(NO_SSL)
  1977. STRICT_HTTPS_MAX_AGE,
  1978. #endif
  1979. ADDITIONAL_HEADER,
  1980. ALLOW_INDEX_SCRIPT_SUB_RES,
  1981. NUM_OPTIONS
  1982. };
  1983. /* Config option name, config types, default value.
  1984. * Must be in the same order as the enum const above.
  1985. */
  1986. static struct mg_option config_options[] = {
  1987. /* Once for each server */
  1988. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1989. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1990. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1991. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1992. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1993. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1994. #if defined(__linux__)
  1995. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1996. #endif
  1997. #if defined(_WIN32)
  1998. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1999. #endif
  2000. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2001. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2002. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  2003. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2004. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  2005. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  2006. #if defined(USE_WEBSOCKET)
  2007. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  2008. {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2009. #endif
  2010. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2011. #if defined(USE_LUA)
  2012. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  2013. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2014. #endif
  2015. /* Once for each domain */
  2016. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2017. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  2018. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2019. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2020. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  2021. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2022. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  2023. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2024. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  2025. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2026. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  2027. {"index_files",
  2028. MG_CONFIG_TYPE_STRING_LIST,
  2029. #if defined(USE_LUA)
  2030. "index.xhtml,index.html,index.htm,"
  2031. "index.lp,index.lsp,index.lua,index.cgi,"
  2032. "index.shtml,index.php"},
  2033. #else
  2034. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  2035. #endif
  2036. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2037. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2038. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  2039. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  2040. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  2041. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  2042. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  2043. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2044. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  2045. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  2046. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  2047. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  2048. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  2049. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2050. #if defined(USE_LUA)
  2051. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  2052. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2053. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  2054. #if defined(MG_EXPERIMENTAL_INTERFACES)
  2055. {"lua_debug", MG_CONFIG_TYPE_STRING, NULL},
  2056. #endif
  2057. #endif
  2058. #if defined(USE_DUKTAPE)
  2059. /* The support for duktape is still in alpha version state.
  2060. * The name of this config option might change. */
  2061. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  2062. #endif
  2063. #if defined(USE_WEBSOCKET)
  2064. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2065. #endif
  2066. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2067. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  2068. #endif
  2069. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  2070. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  2071. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  2072. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  2073. #if !defined(NO_CACHING)
  2074. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  2075. #endif
  2076. #if !defined(NO_SSL)
  2077. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  2078. #endif
  2079. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  2080. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  2081. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  2082. /* Check if the config_options and the corresponding enum have compatible
  2083. * sizes. */
  2084. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  2085. == (NUM_OPTIONS + 1),
  2086. "config_options and enum not sync");
  2087. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  2088. struct mg_handler_info {
  2089. /* Name/Pattern of the URI. */
  2090. char *uri;
  2091. size_t uri_len;
  2092. /* handler type */
  2093. int handler_type;
  2094. /* Handler for http/https or authorization requests. */
  2095. mg_request_handler handler;
  2096. unsigned int refcount;
  2097. pthread_mutex_t refcount_mutex; /* Protects refcount */
  2098. pthread_cond_t
  2099. refcount_cond; /* Signaled when handler refcount is decremented */
  2100. /* Handler for ws/wss (websocket) requests. */
  2101. mg_websocket_connect_handler connect_handler;
  2102. mg_websocket_ready_handler ready_handler;
  2103. mg_websocket_data_handler data_handler;
  2104. mg_websocket_close_handler close_handler;
  2105. /* accepted subprotocols for ws/wss requests. */
  2106. struct mg_websocket_subprotocols *subprotocols;
  2107. /* Handler for authorization requests */
  2108. mg_authorization_handler auth_handler;
  2109. /* User supplied argument for the handler function. */
  2110. void *cbdata;
  2111. /* next handler in a linked list */
  2112. struct mg_handler_info *next;
  2113. };
  2114. enum {
  2115. CONTEXT_INVALID,
  2116. CONTEXT_SERVER,
  2117. CONTEXT_HTTP_CLIENT,
  2118. CONTEXT_WS_CLIENT
  2119. };
  2120. struct mg_domain_context {
  2121. SSL_CTX *ssl_ctx; /* SSL context */
  2122. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2123. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2124. /* Server nonce */
  2125. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2126. unsigned long nonce_count; /* Used nonces, used for authentication */
  2127. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2128. /* linked list of shared lua websockets */
  2129. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2130. #endif
  2131. /* Linked list of domains */
  2132. struct mg_domain_context *next;
  2133. };
  2134. struct mg_context {
  2135. /* Part 1 - Physical context:
  2136. * This holds threads, ports, timeouts, ...
  2137. * set for the entire server, independent from the
  2138. * addressed hostname.
  2139. */
  2140. /* Connection related */
  2141. int context_type; /* See CONTEXT_* above */
  2142. struct socket *listening_sockets;
  2143. struct pollfd *listening_socket_fds;
  2144. unsigned int num_listening_sockets;
  2145. struct mg_connection *worker_connections; /* The connection struct, pre-
  2146. * allocated for each worker */
  2147. #if defined(USE_SERVER_STATS)
  2148. int active_connections;
  2149. int max_connections;
  2150. int64_t total_connections;
  2151. int64_t total_requests;
  2152. int64_t total_data_read;
  2153. int64_t total_data_written;
  2154. #endif
  2155. /* Thread related */
  2156. volatile int stop_flag; /* Should we stop event loop */
  2157. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2158. pthread_t masterthreadid; /* The master thread ID */
  2159. unsigned int
  2160. cfg_worker_threads; /* The number of configured worker threads. */
  2161. pthread_t *worker_threadids; /* The worker thread IDs */
  2162. /* Connection to thread dispatching */
  2163. #if defined(ALTERNATIVE_QUEUE)
  2164. struct socket *client_socks;
  2165. void **client_wait_events;
  2166. #else
  2167. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2168. volatile int sq_head; /* Head of the socket queue */
  2169. volatile int sq_tail; /* Tail of the socket queue */
  2170. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2171. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2172. #endif
  2173. /* Memory related */
  2174. unsigned int max_request_size; /* The max request size */
  2175. #if defined(USE_SERVER_STATS)
  2176. struct mg_memory_stat ctx_memory;
  2177. #endif
  2178. /* Operating system related */
  2179. char *systemName; /* What operating system is running */
  2180. time_t start_time; /* Server start time, used for authentication
  2181. * and for diagnstics. */
  2182. #if defined(USE_TIMERS)
  2183. struct ttimers *timers;
  2184. #endif
  2185. /* Lua specific: Background operations and shared websockets */
  2186. #if defined(USE_LUA)
  2187. void *lua_background_state;
  2188. #endif
  2189. /* Server nonce */
  2190. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2191. /* Server callbacks */
  2192. struct mg_callbacks callbacks; /* User-defined callback function */
  2193. void *user_data; /* User-defined data */
  2194. /* Part 2 - Logical domain:
  2195. * This holds hostname, TLS certificate, document root, ...
  2196. * set for a domain hosted at the server.
  2197. * There may be multiple domains hosted at one physical server.
  2198. * The default domain "dd" is the first element of a list of
  2199. * domains.
  2200. */
  2201. struct mg_domain_context dd; /* default domain */
  2202. };
  2203. #if defined(USE_SERVER_STATS)
  2204. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2205. static struct mg_memory_stat *
  2206. get_memory_stat(struct mg_context *ctx)
  2207. {
  2208. if (ctx) {
  2209. return &(ctx->ctx_memory);
  2210. }
  2211. return &mg_common_memory;
  2212. }
  2213. #endif
  2214. enum {
  2215. CONNECTION_TYPE_INVALID,
  2216. CONNECTION_TYPE_REQUEST,
  2217. CONNECTION_TYPE_RESPONSE
  2218. };
  2219. struct mg_connection {
  2220. int connection_type; /* see CONNECTION_TYPE_* above */
  2221. struct mg_request_info request_info;
  2222. struct mg_response_info response_info;
  2223. struct mg_context *phys_ctx;
  2224. struct mg_domain_context *dom_ctx;
  2225. #if defined(USE_SERVER_STATS)
  2226. int conn_state; /* 0 = undef, numerical value may change in different
  2227. * versions. For the current definition, see
  2228. * mg_get_connection_info_impl */
  2229. #endif
  2230. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2231. SSL *ssl; /* SSL descriptor */
  2232. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2233. struct socket client; /* Connected client */
  2234. time_t conn_birth_time; /* Time (wall clock) when connection was
  2235. * established */
  2236. struct timespec req_time; /* Time (since system start) when the request
  2237. * was received */
  2238. int64_t num_bytes_sent; /* Total bytes sent to client */
  2239. int64_t content_len; /* Content-Length header value */
  2240. int64_t consumed_content; /* How many bytes of content have been read */
  2241. int is_chunked; /* Transfer-Encoding is chunked:
  2242. * 0 = not chunked,
  2243. * 1 = chunked, do data read yet,
  2244. * 2 = chunked, some data read,
  2245. * 3 = chunked, all data read
  2246. */
  2247. size_t chunk_remainder; /* Unread data from the last chunk */
  2248. char *buf; /* Buffer for received data */
  2249. char *path_info; /* PATH_INFO part of the URL */
  2250. int must_close; /* 1 if connection must be closed */
  2251. int accept_gzip; /* 1 if gzip encoding is accepted */
  2252. int in_error_handler; /* 1 if in handler for user defined error
  2253. * pages */
  2254. #if defined(USE_WEBSOCKET)
  2255. int in_websocket_handling; /* 1 if in read_websocket */
  2256. #endif
  2257. int handled_requests; /* Number of requests handled by this connection
  2258. */
  2259. int buf_size; /* Buffer size */
  2260. int request_len; /* Size of the request + headers in a buffer */
  2261. int data_len; /* Total size of data in a buffer */
  2262. int status_code; /* HTTP reply status code, e.g. 200 */
  2263. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2264. * throttle */
  2265. time_t last_throttle_time; /* Last time throttled data was sent */
  2266. int64_t last_throttle_bytes; /* Bytes sent this second */
  2267. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2268. * atomic transmissions for websockets */
  2269. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2270. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2271. #endif
  2272. int thread_index; /* Thread index within ctx */
  2273. };
  2274. /* Directory entry */
  2275. struct de {
  2276. struct mg_connection *conn;
  2277. char *file_name;
  2278. struct mg_file_stat file;
  2279. };
  2280. #if defined(USE_WEBSOCKET)
  2281. static int is_websocket_protocol(const struct mg_connection *conn);
  2282. #else
  2283. #define is_websocket_protocol(conn) (0)
  2284. #endif
  2285. #define mg_cry_internal(conn, fmt, ...) \
  2286. mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__)
  2287. static void mg_cry_internal_wrap(const struct mg_connection *conn,
  2288. const char *func,
  2289. unsigned line,
  2290. const char *fmt,
  2291. ...) PRINTF_ARGS(4, 5);
  2292. #if !defined(NO_THREAD_NAME)
  2293. #if defined(_WIN32) && defined(_MSC_VER)
  2294. /* Set the thread name for debugging purposes in Visual Studio
  2295. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2296. */
  2297. #pragma pack(push, 8)
  2298. typedef struct tagTHREADNAME_INFO {
  2299. DWORD dwType; /* Must be 0x1000. */
  2300. LPCSTR szName; /* Pointer to name (in user addr space). */
  2301. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2302. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2303. } THREADNAME_INFO;
  2304. #pragma pack(pop)
  2305. #elif defined(__linux__)
  2306. #include <sys/prctl.h>
  2307. #include <sys/sendfile.h>
  2308. #if defined(ALTERNATIVE_QUEUE)
  2309. #include <sys/eventfd.h>
  2310. #endif /* ALTERNATIVE_QUEUE */
  2311. #if defined(ALTERNATIVE_QUEUE)
  2312. static void *
  2313. event_create(void)
  2314. {
  2315. int evhdl = eventfd(0, EFD_CLOEXEC);
  2316. int *ret;
  2317. if (evhdl == -1) {
  2318. /* Linux uses -1 on error, Windows NULL. */
  2319. /* However, Linux does not return 0 on success either. */
  2320. return 0;
  2321. }
  2322. ret = (int *)mg_malloc(sizeof(int));
  2323. if (ret) {
  2324. *ret = evhdl;
  2325. } else {
  2326. (void)close(evhdl);
  2327. }
  2328. return (void *)ret;
  2329. }
  2330. static int
  2331. event_wait(void *eventhdl)
  2332. {
  2333. uint64_t u;
  2334. int evhdl, s;
  2335. if (!eventhdl) {
  2336. /* error */
  2337. return 0;
  2338. }
  2339. evhdl = *(int *)eventhdl;
  2340. s = (int)read(evhdl, &u, sizeof(u));
  2341. if (s != sizeof(u)) {
  2342. /* error */
  2343. return 0;
  2344. }
  2345. (void)u; /* the value is not required */
  2346. return 1;
  2347. }
  2348. static int
  2349. event_signal(void *eventhdl)
  2350. {
  2351. uint64_t u = 1;
  2352. int evhdl, s;
  2353. if (!eventhdl) {
  2354. /* error */
  2355. return 0;
  2356. }
  2357. evhdl = *(int *)eventhdl;
  2358. s = (int)write(evhdl, &u, sizeof(u));
  2359. if (s != sizeof(u)) {
  2360. /* error */
  2361. return 0;
  2362. }
  2363. return 1;
  2364. }
  2365. static void
  2366. event_destroy(void *eventhdl)
  2367. {
  2368. int evhdl;
  2369. if (!eventhdl) {
  2370. /* error */
  2371. return;
  2372. }
  2373. evhdl = *(int *)eventhdl;
  2374. close(evhdl);
  2375. mg_free(eventhdl);
  2376. }
  2377. #endif
  2378. #endif
  2379. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2380. struct posix_event {
  2381. pthread_mutex_t mutex;
  2382. pthread_cond_t cond;
  2383. };
  2384. static void *
  2385. event_create(void)
  2386. {
  2387. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2388. if (ret == 0) {
  2389. /* out of memory */
  2390. return 0;
  2391. }
  2392. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2393. /* pthread mutex not available */
  2394. mg_free(ret);
  2395. return 0;
  2396. }
  2397. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2398. /* pthread cond not available */
  2399. pthread_mutex_destroy(&(ret->mutex));
  2400. mg_free(ret);
  2401. return 0;
  2402. }
  2403. return (void *)ret;
  2404. }
  2405. static int
  2406. event_wait(void *eventhdl)
  2407. {
  2408. struct posix_event *ev = (struct posix_event *)eventhdl;
  2409. pthread_mutex_lock(&(ev->mutex));
  2410. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2411. pthread_mutex_unlock(&(ev->mutex));
  2412. return 1;
  2413. }
  2414. static int
  2415. event_signal(void *eventhdl)
  2416. {
  2417. struct posix_event *ev = (struct posix_event *)eventhdl;
  2418. pthread_mutex_lock(&(ev->mutex));
  2419. pthread_cond_signal(&(ev->cond));
  2420. pthread_mutex_unlock(&(ev->mutex));
  2421. return 1;
  2422. }
  2423. static void
  2424. event_destroy(void *eventhdl)
  2425. {
  2426. struct posix_event *ev = (struct posix_event *)eventhdl;
  2427. pthread_cond_destroy(&(ev->cond));
  2428. pthread_mutex_destroy(&(ev->mutex));
  2429. mg_free(ev);
  2430. }
  2431. #endif
  2432. static void
  2433. mg_set_thread_name(const char *name)
  2434. {
  2435. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2436. mg_snprintf(
  2437. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2438. #if defined(_WIN32)
  2439. #if defined(_MSC_VER)
  2440. /* Windows and Visual Studio Compiler */
  2441. __try
  2442. {
  2443. THREADNAME_INFO info;
  2444. info.dwType = 0x1000;
  2445. info.szName = threadName;
  2446. info.dwThreadID = ~0U;
  2447. info.dwFlags = 0;
  2448. RaiseException(0x406D1388,
  2449. 0,
  2450. sizeof(info) / sizeof(ULONG_PTR),
  2451. (ULONG_PTR *)&info);
  2452. }
  2453. __except(EXCEPTION_EXECUTE_HANDLER)
  2454. {
  2455. }
  2456. #elif defined(__MINGW32__)
  2457. /* No option known to set thread name for MinGW */
  2458. #endif
  2459. #elif defined(__GLIBC__) \
  2460. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2461. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2462. (void)pthread_setname_np(pthread_self(), threadName);
  2463. #elif defined(__linux__)
  2464. /* on linux we can use the old prctl function */
  2465. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2466. #endif
  2467. }
  2468. #else /* !defined(NO_THREAD_NAME) */
  2469. void
  2470. mg_set_thread_name(const char *threadName)
  2471. {
  2472. }
  2473. #endif
  2474. #if defined(MG_LEGACY_INTERFACE)
  2475. const char **
  2476. mg_get_valid_option_names(void)
  2477. {
  2478. /* This function is deprecated. Use mg_get_valid_options instead. */
  2479. static const char *
  2480. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2481. int i;
  2482. for (i = 0; config_options[i].name != NULL; i++) {
  2483. data[i * 2] = config_options[i].name;
  2484. data[i * 2 + 1] = config_options[i].default_value;
  2485. }
  2486. return data;
  2487. }
  2488. #endif
  2489. const struct mg_option *
  2490. mg_get_valid_options(void)
  2491. {
  2492. return config_options;
  2493. }
  2494. /* Do not open file (used in is_file_in_memory) */
  2495. #define MG_FOPEN_MODE_NONE (0)
  2496. /* Open file for read only access */
  2497. #define MG_FOPEN_MODE_READ (1)
  2498. /* Open file for writing, create and overwrite */
  2499. #define MG_FOPEN_MODE_WRITE (2)
  2500. /* Open file for writing, create and append */
  2501. #define MG_FOPEN_MODE_APPEND (4)
  2502. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2503. * output filep and return 1, otherwise return 0 and don't modify anything.
  2504. */
  2505. static int
  2506. open_file_in_memory(const struct mg_connection *conn,
  2507. const char *path,
  2508. struct mg_file *filep,
  2509. int mode)
  2510. {
  2511. #if defined(MG_USE_OPEN_FILE)
  2512. size_t size = 0;
  2513. const char *buf = NULL;
  2514. if (!conn) {
  2515. return 0;
  2516. }
  2517. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2518. return 0;
  2519. }
  2520. if (conn->phys_ctx->callbacks.open_file) {
  2521. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2522. if (buf != NULL) {
  2523. if (filep == NULL) {
  2524. /* This is a file in memory, but we cannot store the
  2525. * properties
  2526. * now.
  2527. * Called from "is_file_in_memory" function. */
  2528. return 1;
  2529. }
  2530. /* NOTE: override filep->size only on success. Otherwise, it
  2531. * might
  2532. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2533. filep->access.membuf = buf;
  2534. filep->access.fp = NULL;
  2535. /* Size was set by the callback */
  2536. filep->stat.size = size;
  2537. /* Assume the data may change during runtime by setting
  2538. * last_modified = now */
  2539. filep->stat.last_modified = time(NULL);
  2540. filep->stat.is_directory = 0;
  2541. filep->stat.is_gzipped = 0;
  2542. }
  2543. }
  2544. return (buf != NULL);
  2545. #else
  2546. (void)conn;
  2547. (void)path;
  2548. (void)filep;
  2549. (void)mode;
  2550. return 0;
  2551. #endif
  2552. }
  2553. static int
  2554. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2555. {
  2556. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2557. }
  2558. static int
  2559. is_file_opened(const struct mg_file_access *fileacc)
  2560. {
  2561. if (!fileacc) {
  2562. return 0;
  2563. }
  2564. #if defined(MG_USE_OPEN_FILE)
  2565. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2566. #else
  2567. return (fileacc->fp != NULL);
  2568. #endif
  2569. }
  2570. static int mg_stat(const struct mg_connection *conn,
  2571. const char *path,
  2572. struct mg_file_stat *filep);
  2573. /* mg_fopen will open a file either in memory or on the disk.
  2574. * The input parameter path is a string in UTF-8 encoding.
  2575. * The input parameter mode is MG_FOPEN_MODE_*
  2576. * On success, either fp or membuf will be set in the output
  2577. * struct file. All status members will also be set.
  2578. * The function returns 1 on success, 0 on error. */
  2579. static int
  2580. mg_fopen(const struct mg_connection *conn,
  2581. const char *path,
  2582. int mode,
  2583. struct mg_file *filep)
  2584. {
  2585. int found;
  2586. if (!filep) {
  2587. return 0;
  2588. }
  2589. filep->access.fp = NULL;
  2590. #if defined(MG_USE_OPEN_FILE)
  2591. filep->access.membuf = NULL;
  2592. #endif
  2593. if (!is_file_in_memory(conn, path)) {
  2594. /* filep is initialized in mg_stat: all fields with memset to,
  2595. * some fields like size and modification date with values */
  2596. found = mg_stat(conn, path, &(filep->stat));
  2597. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2598. /* file does not exist and will not be created */
  2599. return 0;
  2600. }
  2601. #if defined(_WIN32)
  2602. {
  2603. wchar_t wbuf[W_PATH_MAX];
  2604. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2605. switch (mode) {
  2606. case MG_FOPEN_MODE_READ:
  2607. filep->access.fp = _wfopen(wbuf, L"rb");
  2608. break;
  2609. case MG_FOPEN_MODE_WRITE:
  2610. filep->access.fp = _wfopen(wbuf, L"wb");
  2611. break;
  2612. case MG_FOPEN_MODE_APPEND:
  2613. filep->access.fp = _wfopen(wbuf, L"ab");
  2614. break;
  2615. }
  2616. }
  2617. #else
  2618. /* Linux et al already use unicode. No need to convert. */
  2619. switch (mode) {
  2620. case MG_FOPEN_MODE_READ:
  2621. filep->access.fp = fopen(path, "r");
  2622. break;
  2623. case MG_FOPEN_MODE_WRITE:
  2624. filep->access.fp = fopen(path, "w");
  2625. break;
  2626. case MG_FOPEN_MODE_APPEND:
  2627. filep->access.fp = fopen(path, "a");
  2628. break;
  2629. }
  2630. #endif
  2631. if (!found) {
  2632. /* File did not exist before fopen was called.
  2633. * Maybe it has been created now. Get stat info
  2634. * like creation time now. */
  2635. found = mg_stat(conn, path, &(filep->stat));
  2636. (void)found;
  2637. }
  2638. /* file is on disk */
  2639. return (filep->access.fp != NULL);
  2640. } else {
  2641. #if defined(MG_USE_OPEN_FILE)
  2642. /* is_file_in_memory returned true */
  2643. if (open_file_in_memory(conn, path, filep, mode)) {
  2644. /* file is in memory */
  2645. return (filep->access.membuf != NULL);
  2646. }
  2647. #endif
  2648. }
  2649. /* Open failed */
  2650. return 0;
  2651. }
  2652. /* return 0 on success, just like fclose */
  2653. static int
  2654. mg_fclose(struct mg_file_access *fileacc)
  2655. {
  2656. int ret = -1;
  2657. if (fileacc != NULL) {
  2658. if (fileacc->fp != NULL) {
  2659. ret = fclose(fileacc->fp);
  2660. #if defined(MG_USE_OPEN_FILE)
  2661. } else if (fileacc->membuf != NULL) {
  2662. ret = 0;
  2663. #endif
  2664. }
  2665. /* reset all members of fileacc */
  2666. memset(fileacc, 0, sizeof(*fileacc));
  2667. }
  2668. return ret;
  2669. }
  2670. static void
  2671. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2672. {
  2673. for (; *src != '\0' && n > 1; n--) {
  2674. *dst++ = *src++;
  2675. }
  2676. *dst = '\0';
  2677. }
  2678. static int
  2679. lowercase(const char *s)
  2680. {
  2681. return tolower(*(const unsigned char *)s);
  2682. }
  2683. int
  2684. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2685. {
  2686. int diff = 0;
  2687. if (len > 0) {
  2688. do {
  2689. diff = lowercase(s1++) - lowercase(s2++);
  2690. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2691. }
  2692. return diff;
  2693. }
  2694. int
  2695. mg_strcasecmp(const char *s1, const char *s2)
  2696. {
  2697. int diff;
  2698. do {
  2699. diff = lowercase(s1++) - lowercase(s2++);
  2700. } while (diff == 0 && s1[-1] != '\0');
  2701. return diff;
  2702. }
  2703. static char *
  2704. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2705. {
  2706. char *p;
  2707. (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not
  2708. * defined */
  2709. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2710. mg_strlcpy(p, ptr, len + 1);
  2711. }
  2712. return p;
  2713. }
  2714. static char *
  2715. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2716. {
  2717. return mg_strndup_ctx(str, strlen(str), ctx);
  2718. }
  2719. static char *
  2720. mg_strdup(const char *str)
  2721. {
  2722. return mg_strndup_ctx(str, strlen(str), NULL);
  2723. }
  2724. static const char *
  2725. mg_strcasestr(const char *big_str, const char *small_str)
  2726. {
  2727. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2728. if (big_len >= small_len) {
  2729. for (i = 0; i <= (big_len - small_len); i++) {
  2730. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2731. return big_str + i;
  2732. }
  2733. }
  2734. }
  2735. return NULL;
  2736. }
  2737. /* Return null terminated string of given maximum length.
  2738. * Report errors if length is exceeded. */
  2739. static void
  2740. mg_vsnprintf(const struct mg_connection *conn,
  2741. int *truncated,
  2742. char *buf,
  2743. size_t buflen,
  2744. const char *fmt,
  2745. va_list ap)
  2746. {
  2747. int n, ok;
  2748. if (buflen == 0) {
  2749. if (truncated) {
  2750. *truncated = 1;
  2751. }
  2752. return;
  2753. }
  2754. #if defined(__clang__)
  2755. #pragma clang diagnostic push
  2756. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2757. /* Using fmt as a non-literal is intended here, since it is mostly called
  2758. * indirectly by mg_snprintf */
  2759. #endif
  2760. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2761. ok = (n >= 0) && ((size_t)n < buflen);
  2762. #if defined(__clang__)
  2763. #pragma clang diagnostic pop
  2764. #endif
  2765. if (ok) {
  2766. if (truncated) {
  2767. *truncated = 0;
  2768. }
  2769. } else {
  2770. if (truncated) {
  2771. *truncated = 1;
  2772. }
  2773. mg_cry_internal(conn,
  2774. "truncating vsnprintf buffer: [%.*s]",
  2775. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2776. buf);
  2777. n = (int)buflen - 1;
  2778. }
  2779. buf[n] = '\0';
  2780. }
  2781. static void
  2782. mg_snprintf(const struct mg_connection *conn,
  2783. int *truncated,
  2784. char *buf,
  2785. size_t buflen,
  2786. const char *fmt,
  2787. ...)
  2788. {
  2789. va_list ap;
  2790. va_start(ap, fmt);
  2791. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2792. va_end(ap);
  2793. }
  2794. static int
  2795. get_option_index(const char *name)
  2796. {
  2797. int i;
  2798. for (i = 0; config_options[i].name != NULL; i++) {
  2799. if (strcmp(config_options[i].name, name) == 0) {
  2800. return i;
  2801. }
  2802. }
  2803. return -1;
  2804. }
  2805. const char *
  2806. mg_get_option(const struct mg_context *ctx, const char *name)
  2807. {
  2808. int i;
  2809. if ((i = get_option_index(name)) == -1) {
  2810. return NULL;
  2811. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2812. return "";
  2813. } else {
  2814. return ctx->dd.config[i];
  2815. }
  2816. }
  2817. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2818. struct mg_context *
  2819. mg_get_context(const struct mg_connection *conn)
  2820. {
  2821. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2822. }
  2823. void *
  2824. mg_get_user_data(const struct mg_context *ctx)
  2825. {
  2826. return (ctx == NULL) ? NULL : ctx->user_data;
  2827. }
  2828. void
  2829. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2830. {
  2831. if (conn != NULL) {
  2832. conn->request_info.conn_data = data;
  2833. }
  2834. }
  2835. void *
  2836. mg_get_user_connection_data(const struct mg_connection *conn)
  2837. {
  2838. if (conn != NULL) {
  2839. return conn->request_info.conn_data;
  2840. }
  2841. return NULL;
  2842. }
  2843. #if defined(MG_LEGACY_INTERFACE)
  2844. /* Deprecated: Use mg_get_server_ports instead. */
  2845. size_t
  2846. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2847. {
  2848. size_t i;
  2849. if (!ctx) {
  2850. return 0;
  2851. }
  2852. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2853. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2854. ports[i] =
  2855. #if defined(USE_IPV6)
  2856. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2857. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2858. :
  2859. #endif
  2860. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2861. }
  2862. return i;
  2863. }
  2864. #endif
  2865. int
  2866. mg_get_server_ports(const struct mg_context *ctx,
  2867. int size,
  2868. struct mg_server_ports *ports)
  2869. {
  2870. int i, cnt = 0;
  2871. if (size <= 0) {
  2872. return -1;
  2873. }
  2874. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2875. if (!ctx) {
  2876. return -1;
  2877. }
  2878. if (!ctx->listening_sockets) {
  2879. return -1;
  2880. }
  2881. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2882. ports[cnt].port =
  2883. #if defined(USE_IPV6)
  2884. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2885. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2886. :
  2887. #endif
  2888. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2889. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2890. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2891. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2892. /* IPv4 */
  2893. ports[cnt].protocol = 1;
  2894. cnt++;
  2895. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2896. /* IPv6 */
  2897. ports[cnt].protocol = 3;
  2898. cnt++;
  2899. }
  2900. }
  2901. return cnt;
  2902. }
  2903. static void
  2904. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2905. {
  2906. buf[0] = '\0';
  2907. if (!usa) {
  2908. return;
  2909. }
  2910. if (usa->sa.sa_family == AF_INET) {
  2911. getnameinfo(&usa->sa,
  2912. sizeof(usa->sin),
  2913. buf,
  2914. (unsigned)len,
  2915. NULL,
  2916. 0,
  2917. NI_NUMERICHOST);
  2918. }
  2919. #if defined(USE_IPV6)
  2920. else if (usa->sa.sa_family == AF_INET6) {
  2921. getnameinfo(&usa->sa,
  2922. sizeof(usa->sin6),
  2923. buf,
  2924. (unsigned)len,
  2925. NULL,
  2926. 0,
  2927. NI_NUMERICHOST);
  2928. }
  2929. #endif
  2930. }
  2931. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2932. * included in all responses other than 100, 101, 5xx. */
  2933. static void
  2934. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2935. {
  2936. #if !defined(REENTRANT_TIME)
  2937. struct tm *tm;
  2938. tm = ((t != NULL) ? gmtime(t) : NULL);
  2939. if (tm != NULL) {
  2940. #else
  2941. struct tm _tm;
  2942. struct tm *tm = &_tm;
  2943. if (t != NULL) {
  2944. gmtime_r(t, tm);
  2945. #endif
  2946. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2947. } else {
  2948. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2949. buf[buf_len - 1] = '\0';
  2950. }
  2951. }
  2952. /* difftime for struct timespec. Return value is in seconds. */
  2953. static double
  2954. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2955. {
  2956. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2957. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2958. }
  2959. #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl)
  2960. static void mg_cry_internal_impl(const struct mg_connection *conn,
  2961. const char *func,
  2962. unsigned line,
  2963. const char *fmt,
  2964. va_list ap);
  2965. #include "external_mg_cry_internal_impl.inl"
  2966. #else
  2967. /* Print error message to the opened error log stream. */
  2968. static void
  2969. mg_cry_internal_impl(const struct mg_connection *conn,
  2970. const char *func,
  2971. unsigned line,
  2972. const char *fmt,
  2973. va_list ap)
  2974. {
  2975. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2976. struct mg_file fi;
  2977. time_t timestamp;
  2978. /* Unused, in the RELEASE build */
  2979. (void)func;
  2980. (void)line;
  2981. #if defined(__GNUC__) || defined(__MINGW32__)
  2982. #pragma GCC diagnostic push
  2983. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  2984. #endif
  2985. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2986. #if defined(__GNUC__) || defined(__MINGW32__)
  2987. #pragma GCC diagnostic pop
  2988. #endif
  2989. buf[sizeof(buf) - 1] = 0;
  2990. DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf);
  2991. if (!conn) {
  2992. puts(buf);
  2993. return;
  2994. }
  2995. /* Do not lock when getting the callback value, here and below.
  2996. * I suppose this is fine, since function cannot disappear in the
  2997. * same way string option can. */
  2998. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2999. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  3000. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  3001. if (mg_fopen(conn,
  3002. conn->dom_ctx->config[ERROR_LOG_FILE],
  3003. MG_FOPEN_MODE_APPEND,
  3004. &fi) == 0) {
  3005. fi.access.fp = NULL;
  3006. }
  3007. } else {
  3008. fi.access.fp = NULL;
  3009. }
  3010. if (fi.access.fp != NULL) {
  3011. flockfile(fi.access.fp);
  3012. timestamp = time(NULL);
  3013. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3014. fprintf(fi.access.fp,
  3015. "[%010lu] [error] [client %s] ",
  3016. (unsigned long)timestamp,
  3017. src_addr);
  3018. if (conn->request_info.request_method != NULL) {
  3019. fprintf(fi.access.fp,
  3020. "%s %s: ",
  3021. conn->request_info.request_method,
  3022. conn->request_info.request_uri
  3023. ? conn->request_info.request_uri
  3024. : "");
  3025. }
  3026. fprintf(fi.access.fp, "%s", buf);
  3027. fputc('\n', fi.access.fp);
  3028. fflush(fi.access.fp);
  3029. funlockfile(fi.access.fp);
  3030. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  3031. * mg_cry here anyway ;-) */
  3032. }
  3033. }
  3034. }
  3035. #endif /* Externally provided function */
  3036. static void
  3037. mg_cry_internal_wrap(const struct mg_connection *conn,
  3038. const char *func,
  3039. unsigned line,
  3040. const char *fmt,
  3041. ...)
  3042. {
  3043. va_list ap;
  3044. va_start(ap, fmt);
  3045. mg_cry_internal_impl(conn, func, line, fmt, ap);
  3046. va_end(ap);
  3047. }
  3048. void
  3049. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  3050. {
  3051. va_list ap;
  3052. va_start(ap, fmt);
  3053. mg_cry_internal_impl(conn, "user", 0, fmt, ap);
  3054. va_end(ap);
  3055. }
  3056. #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal
  3057. /* Return fake connection structure. Used for logging, if connection
  3058. * is not applicable at the moment of logging. */
  3059. static struct mg_connection *
  3060. fc(struct mg_context *ctx)
  3061. {
  3062. static struct mg_connection fake_connection;
  3063. fake_connection.phys_ctx = ctx;
  3064. fake_connection.dom_ctx = &(ctx->dd);
  3065. return &fake_connection;
  3066. }
  3067. const char *
  3068. mg_version(void)
  3069. {
  3070. return CIVETWEB_VERSION;
  3071. }
  3072. const struct mg_request_info *
  3073. mg_get_request_info(const struct mg_connection *conn)
  3074. {
  3075. if (!conn) {
  3076. return NULL;
  3077. }
  3078. #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE)
  3079. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3080. char txt[16];
  3081. struct mg_workerTLS *tls =
  3082. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3083. sprintf(txt, "%03i", conn->response_info.status_code);
  3084. if (strlen(txt) == 3) {
  3085. memcpy(tls->txtbuf, txt, 4);
  3086. } else {
  3087. strcpy(tls->txtbuf, "ERR");
  3088. }
  3089. ((struct mg_connection *)conn)->request_info.local_uri =
  3090. ((struct mg_connection *)conn)->request_info.request_uri =
  3091. tls->txtbuf; /* use thread safe buffer */
  3092. ((struct mg_connection *)conn)->request_info.num_headers =
  3093. conn->response_info.num_headers;
  3094. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  3095. conn->response_info.http_headers,
  3096. sizeof(conn->response_info.http_headers));
  3097. } else
  3098. #endif
  3099. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  3100. return NULL;
  3101. }
  3102. return &conn->request_info;
  3103. }
  3104. const struct mg_response_info *
  3105. mg_get_response_info(const struct mg_connection *conn)
  3106. {
  3107. if (!conn) {
  3108. return NULL;
  3109. }
  3110. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  3111. return NULL;
  3112. }
  3113. return &conn->response_info;
  3114. }
  3115. static const char *
  3116. get_proto_name(const struct mg_connection *conn)
  3117. {
  3118. #if defined(__clang__)
  3119. #pragma clang diagnostic push
  3120. #pragma clang diagnostic ignored "-Wunreachable-code"
  3121. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  3122. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  3123. * unreachable, but splitting into four different #ifdef clauses here is more
  3124. * complicated.
  3125. */
  3126. #endif
  3127. const struct mg_request_info *ri = &conn->request_info;
  3128. const char *proto =
  3129. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  3130. : (ri->is_ssl ? "https" : "http"));
  3131. return proto;
  3132. #if defined(__clang__)
  3133. #pragma clang diagnostic pop
  3134. #endif
  3135. }
  3136. int
  3137. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  3138. {
  3139. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  3140. return -1;
  3141. } else {
  3142. int truncated = 0;
  3143. const struct mg_request_info *ri = &conn->request_info;
  3144. const char *proto = get_proto_name(conn);
  3145. if (ri->local_uri == NULL) {
  3146. return -1;
  3147. }
  3148. if ((ri->request_uri != NULL)
  3149. && (0 != strcmp(ri->local_uri, ri->request_uri))) {
  3150. /* The request uri is different from the local uri.
  3151. * This is usually if an absolute URI, including server
  3152. * name has been provided. */
  3153. mg_snprintf(conn,
  3154. &truncated,
  3155. buf,
  3156. buflen,
  3157. "%s://%s",
  3158. proto,
  3159. ri->request_uri);
  3160. if (truncated) {
  3161. return -1;
  3162. }
  3163. return 0;
  3164. } else {
  3165. /* The common case is a relative URI, so we have to
  3166. * construct an absolute URI from server name and port */
  3167. #if defined(USE_IPV6)
  3168. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3169. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3170. : htons(conn->client.lsa.sin.sin_port);
  3171. #else
  3172. int port = htons(conn->client.lsa.sin.sin_port);
  3173. #endif
  3174. int def_port = ri->is_ssl ? 443 : 80;
  3175. int auth_domain_check_enabled =
  3176. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3177. && (!mg_strcasecmp(
  3178. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  3179. "yes"));
  3180. const char *server_domain =
  3181. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3182. char portstr[16];
  3183. char server_ip[48];
  3184. if (port != def_port) {
  3185. sprintf(portstr, ":%u", (unsigned)port);
  3186. } else {
  3187. portstr[0] = 0;
  3188. }
  3189. if (!auth_domain_check_enabled || !server_domain) {
  3190. sockaddr_to_string(server_ip,
  3191. sizeof(server_ip),
  3192. &conn->client.lsa);
  3193. server_domain = server_ip;
  3194. }
  3195. mg_snprintf(conn,
  3196. &truncated,
  3197. buf,
  3198. buflen,
  3199. "%s://%s%s%s",
  3200. proto,
  3201. server_domain,
  3202. portstr,
  3203. ri->local_uri);
  3204. if (truncated) {
  3205. return -1;
  3206. }
  3207. return 0;
  3208. }
  3209. }
  3210. }
  3211. /* Skip the characters until one of the delimiters characters found.
  3212. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3213. * Advance pointer to buffer to the next word. Return found 0-terminated
  3214. * word.
  3215. * Delimiters can be quoted with quotechar. */
  3216. static char *
  3217. skip_quoted(char **buf,
  3218. const char *delimiters,
  3219. const char *whitespace,
  3220. char quotechar)
  3221. {
  3222. char *p, *begin_word, *end_word, *end_whitespace;
  3223. begin_word = *buf;
  3224. end_word = begin_word + strcspn(begin_word, delimiters);
  3225. /* Check for quotechar */
  3226. if (end_word > begin_word) {
  3227. p = end_word - 1;
  3228. while (*p == quotechar) {
  3229. /* While the delimiter is quoted, look for the next delimiter.
  3230. */
  3231. /* This happens, e.g., in calls from parse_auth_header,
  3232. * if the user name contains a " character. */
  3233. /* If there is anything beyond end_word, copy it. */
  3234. if (*end_word != '\0') {
  3235. size_t end_off = strcspn(end_word + 1, delimiters);
  3236. memmove(p, end_word, end_off + 1);
  3237. p += end_off; /* p must correspond to end_word - 1 */
  3238. end_word += end_off + 1;
  3239. } else {
  3240. *p = '\0';
  3241. break;
  3242. }
  3243. }
  3244. for (p++; p < end_word; p++) {
  3245. *p = '\0';
  3246. }
  3247. }
  3248. if (*end_word == '\0') {
  3249. *buf = end_word;
  3250. } else {
  3251. #if defined(__GNUC__) || defined(__MINGW32__)
  3252. /* Disable spurious conversion warning for GCC */
  3253. #if GCC_VERSION >= 40500
  3254. #pragma GCC diagnostic push
  3255. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3256. #endif /* GCC_VERSION >= 40500 */
  3257. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3258. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3259. #if defined(__GNUC__) || defined(__MINGW32__)
  3260. #if GCC_VERSION >= 40500
  3261. #pragma GCC diagnostic pop
  3262. #endif /* GCC_VERSION >= 40500 */
  3263. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3264. for (p = end_word; p < end_whitespace; p++) {
  3265. *p = '\0';
  3266. }
  3267. *buf = end_whitespace;
  3268. }
  3269. return begin_word;
  3270. }
  3271. /* Return HTTP header value, or NULL if not found. */
  3272. static const char *
  3273. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3274. {
  3275. int i;
  3276. for (i = 0; i < num_hdr; i++) {
  3277. if (!mg_strcasecmp(name, hdr[i].name)) {
  3278. return hdr[i].value;
  3279. }
  3280. }
  3281. return NULL;
  3282. }
  3283. #if defined(USE_WEBSOCKET)
  3284. /* Retrieve requested HTTP header multiple values, and return the number of
  3285. * found occurrences */
  3286. static int
  3287. get_req_headers(const struct mg_request_info *ri,
  3288. const char *name,
  3289. const char **output,
  3290. int output_max_size)
  3291. {
  3292. int i;
  3293. int cnt = 0;
  3294. if (ri) {
  3295. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3296. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3297. output[cnt++] = ri->http_headers[i].value;
  3298. }
  3299. }
  3300. }
  3301. return cnt;
  3302. }
  3303. #endif
  3304. const char *
  3305. mg_get_header(const struct mg_connection *conn, const char *name)
  3306. {
  3307. if (!conn) {
  3308. return NULL;
  3309. }
  3310. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3311. return get_header(conn->request_info.http_headers,
  3312. conn->request_info.num_headers,
  3313. name);
  3314. }
  3315. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3316. return get_header(conn->response_info.http_headers,
  3317. conn->response_info.num_headers,
  3318. name);
  3319. }
  3320. return NULL;
  3321. }
  3322. static const char *
  3323. get_http_version(const struct mg_connection *conn)
  3324. {
  3325. if (!conn) {
  3326. return NULL;
  3327. }
  3328. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3329. return conn->request_info.http_version;
  3330. }
  3331. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3332. return conn->response_info.http_version;
  3333. }
  3334. return NULL;
  3335. }
  3336. /* A helper function for traversing a comma separated list of values.
  3337. * It returns a list pointer shifted to the next value, or NULL if the end
  3338. * of the list found.
  3339. * Value is stored in val vector. If value has form "x=y", then eq_val
  3340. * vector is initialized to point to the "y" part, and val vector length
  3341. * is adjusted to point only to "x". */
  3342. static const char *
  3343. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3344. {
  3345. int end;
  3346. reparse:
  3347. if (val == NULL || list == NULL || *list == '\0') {
  3348. /* End of the list */
  3349. return NULL;
  3350. }
  3351. /* Skip over leading LWS */
  3352. while (*list == ' ' || *list == '\t')
  3353. list++;
  3354. val->ptr = list;
  3355. if ((list = strchr(val->ptr, ',')) != NULL) {
  3356. /* Comma found. Store length and shift the list ptr */
  3357. val->len = ((size_t)(list - val->ptr));
  3358. list++;
  3359. } else {
  3360. /* This value is the last one */
  3361. list = val->ptr + strlen(val->ptr);
  3362. val->len = ((size_t)(list - val->ptr));
  3363. }
  3364. /* Adjust length for trailing LWS */
  3365. end = (int)val->len - 1;
  3366. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3367. end--;
  3368. val->len = (size_t)(end + 1);
  3369. if (val->len == 0) {
  3370. /* Ignore any empty entries. */
  3371. goto reparse;
  3372. }
  3373. if (eq_val != NULL) {
  3374. /* Value has form "x=y", adjust pointers and lengths
  3375. * so that val points to "x", and eq_val points to "y". */
  3376. eq_val->len = 0;
  3377. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3378. if (eq_val->ptr != NULL) {
  3379. eq_val->ptr++; /* Skip over '=' character */
  3380. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3381. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3382. }
  3383. }
  3384. return list;
  3385. }
  3386. /* A helper function for checking if a comma separated list of values
  3387. * contains
  3388. * the given option (case insensitvely).
  3389. * 'header' can be NULL, in which case false is returned. */
  3390. static int
  3391. header_has_option(const char *header, const char *option)
  3392. {
  3393. struct vec opt_vec;
  3394. struct vec eq_vec;
  3395. DEBUG_ASSERT(option != NULL);
  3396. DEBUG_ASSERT(option[0] != '\0');
  3397. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3398. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3399. return 1;
  3400. }
  3401. return 0;
  3402. }
  3403. /* Perform case-insensitive match of string against pattern */
  3404. static ptrdiff_t
  3405. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3406. {
  3407. const char *or_str;
  3408. ptrdiff_t i, j, len, res;
  3409. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3410. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3411. return (res > 0) ? res : match_prefix(or_str + 1,
  3412. (size_t)((pattern + pattern_len)
  3413. - (or_str + 1)),
  3414. str);
  3415. }
  3416. for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) {
  3417. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3418. continue;
  3419. } else if (pattern[i] == '$') {
  3420. return (str[j] == '\0') ? j : -1;
  3421. } else if (pattern[i] == '*') {
  3422. i++;
  3423. if (pattern[i] == '*') {
  3424. i++;
  3425. len = strlen(str + j);
  3426. } else {
  3427. len = strcspn(str + j, "/");
  3428. }
  3429. if (i == (ptrdiff_t)pattern_len) {
  3430. return j + len;
  3431. }
  3432. do {
  3433. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3434. } while (res == -1 && len-- > 0);
  3435. return (res == -1) ? -1 : j + res + len;
  3436. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3437. return -1;
  3438. }
  3439. }
  3440. return (ptrdiff_t)j;
  3441. }
  3442. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3443. * This function must tolerate situations when connection info is not
  3444. * set up, for example if request parsing failed. */
  3445. static int
  3446. should_keep_alive(const struct mg_connection *conn)
  3447. {
  3448. const char *http_version;
  3449. const char *header;
  3450. /* First satisfy needs of the server */
  3451. if ((conn == NULL) || conn->must_close) {
  3452. /* Close, if civetweb framework needs to close */
  3453. return 0;
  3454. }
  3455. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3456. /* Close, if keep alive is not enabled */
  3457. return 0;
  3458. }
  3459. /* Check explicit wish of the client */
  3460. header = mg_get_header(conn, "Connection");
  3461. if (header) {
  3462. /* If there is a connection header from the client, obey */
  3463. if (header_has_option(header, "keep-alive")) {
  3464. return 1;
  3465. }
  3466. return 0;
  3467. }
  3468. /* Use default of the standard */
  3469. http_version = get_http_version(conn);
  3470. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3471. /* HTTP 1.1 default is keep alive */
  3472. return 1;
  3473. }
  3474. /* HTTP 1.0 (and earlier) default is to close the connection */
  3475. return 0;
  3476. }
  3477. static int
  3478. should_decode_url(const struct mg_connection *conn)
  3479. {
  3480. if (!conn || !conn->dom_ctx) {
  3481. return 0;
  3482. }
  3483. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3484. }
  3485. static const char *
  3486. suggest_connection_header(const struct mg_connection *conn)
  3487. {
  3488. return should_keep_alive(conn) ? "keep-alive" : "close";
  3489. }
  3490. static int
  3491. send_no_cache_header(struct mg_connection *conn)
  3492. {
  3493. /* Send all current and obsolete cache opt-out directives. */
  3494. return mg_printf(conn,
  3495. "Cache-Control: no-cache, no-store, "
  3496. "must-revalidate, private, max-age=0\r\n"
  3497. "Pragma: no-cache\r\n"
  3498. "Expires: 0\r\n");
  3499. }
  3500. static int
  3501. send_static_cache_header(struct mg_connection *conn)
  3502. {
  3503. #if !defined(NO_CACHING)
  3504. /* Read the server config to check how long a file may be cached.
  3505. * The configuration is in seconds. */
  3506. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3507. if (max_age <= 0) {
  3508. /* 0 means "do not cache". All values <0 are reserved
  3509. * and may be used differently in the future. */
  3510. /* If a file should not be cached, do not only send
  3511. * max-age=0, but also pragmas and Expires headers. */
  3512. return send_no_cache_header(conn);
  3513. }
  3514. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3515. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3516. /* See also https://www.mnot.net/cache_docs/ */
  3517. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3518. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3519. * leap
  3520. * year to 31622400 seconds. For the moment, we just send whatever has
  3521. * been configured, still the behavior for >1 year should be considered
  3522. * as undefined. */
  3523. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3524. #else /* NO_CACHING */
  3525. return send_no_cache_header(conn);
  3526. #endif /* !NO_CACHING */
  3527. }
  3528. static int
  3529. send_additional_header(struct mg_connection *conn)
  3530. {
  3531. int i = 0;
  3532. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3533. #if !defined(NO_SSL)
  3534. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3535. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3536. if (max_age >= 0) {
  3537. i += mg_printf(conn,
  3538. "Strict-Transport-Security: max-age=%u\r\n",
  3539. (unsigned)max_age);
  3540. }
  3541. }
  3542. #endif
  3543. if (header && header[0]) {
  3544. i += mg_printf(conn, "%s\r\n", header);
  3545. }
  3546. return i;
  3547. }
  3548. static void handle_file_based_request(struct mg_connection *conn,
  3549. const char *path,
  3550. struct mg_file *filep);
  3551. const char *
  3552. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3553. {
  3554. /* See IANA HTTP status code assignment:
  3555. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3556. */
  3557. switch (response_code) {
  3558. /* RFC2616 Section 10.1 - Informational 1xx */
  3559. case 100:
  3560. return "Continue"; /* RFC2616 Section 10.1.1 */
  3561. case 101:
  3562. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3563. case 102:
  3564. return "Processing"; /* RFC2518 Section 10.1 */
  3565. /* RFC2616 Section 10.2 - Successful 2xx */
  3566. case 200:
  3567. return "OK"; /* RFC2616 Section 10.2.1 */
  3568. case 201:
  3569. return "Created"; /* RFC2616 Section 10.2.2 */
  3570. case 202:
  3571. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3572. case 203:
  3573. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3574. case 204:
  3575. return "No Content"; /* RFC2616 Section 10.2.5 */
  3576. case 205:
  3577. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3578. case 206:
  3579. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3580. case 207:
  3581. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3582. */
  3583. case 208:
  3584. return "Already Reported"; /* RFC5842 Section 7.1 */
  3585. case 226:
  3586. return "IM used"; /* RFC3229 Section 10.4.1 */
  3587. /* RFC2616 Section 10.3 - Redirection 3xx */
  3588. case 300:
  3589. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3590. case 301:
  3591. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3592. case 302:
  3593. return "Found"; /* RFC2616 Section 10.3.3 */
  3594. case 303:
  3595. return "See Other"; /* RFC2616 Section 10.3.4 */
  3596. case 304:
  3597. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3598. case 305:
  3599. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3600. case 307:
  3601. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3602. case 308:
  3603. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3604. /* RFC2616 Section 10.4 - Client Error 4xx */
  3605. case 400:
  3606. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3607. case 401:
  3608. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3609. case 402:
  3610. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3611. case 403:
  3612. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3613. case 404:
  3614. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3615. case 405:
  3616. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3617. case 406:
  3618. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3619. case 407:
  3620. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3621. case 408:
  3622. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3623. case 409:
  3624. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3625. case 410:
  3626. return "Gone"; /* RFC2616 Section 10.4.11 */
  3627. case 411:
  3628. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3629. case 412:
  3630. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3631. case 413:
  3632. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3633. case 414:
  3634. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3635. case 415:
  3636. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3637. case 416:
  3638. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3639. */
  3640. case 417:
  3641. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3642. case 421:
  3643. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3644. case 422:
  3645. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3646. * Section 11.2 */
  3647. case 423:
  3648. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3649. case 424:
  3650. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3651. * Section 11.4 */
  3652. case 426:
  3653. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3654. case 428:
  3655. return "Precondition Required"; /* RFC 6585, Section 3 */
  3656. case 429:
  3657. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3658. case 431:
  3659. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3660. case 451:
  3661. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3662. * Section 3 */
  3663. /* RFC2616 Section 10.5 - Server Error 5xx */
  3664. case 500:
  3665. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3666. case 501:
  3667. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3668. case 502:
  3669. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3670. case 503:
  3671. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3672. case 504:
  3673. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3674. case 505:
  3675. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3676. case 506:
  3677. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3678. case 507:
  3679. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3680. * Section 11.5 */
  3681. case 508:
  3682. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3683. case 510:
  3684. return "Not Extended"; /* RFC 2774, Section 7 */
  3685. case 511:
  3686. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3687. /* Other status codes, not shown in the IANA HTTP status code
  3688. * assignment.
  3689. * E.g., "de facto" standards due to common use, ... */
  3690. case 418:
  3691. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3692. case 419:
  3693. return "Authentication Timeout"; /* common use */
  3694. case 420:
  3695. return "Enhance Your Calm"; /* common use */
  3696. case 440:
  3697. return "Login Timeout"; /* common use */
  3698. case 509:
  3699. return "Bandwidth Limit Exceeded"; /* common use */
  3700. default:
  3701. /* This error code is unknown. This should not happen. */
  3702. if (conn) {
  3703. mg_cry_internal(conn,
  3704. "Unknown HTTP response code: %u",
  3705. response_code);
  3706. }
  3707. /* Return at least a category according to RFC 2616 Section 10. */
  3708. if (response_code >= 100 && response_code < 200) {
  3709. /* Unknown informational status code */
  3710. return "Information";
  3711. }
  3712. if (response_code >= 200 && response_code < 300) {
  3713. /* Unknown success code */
  3714. return "Success";
  3715. }
  3716. if (response_code >= 300 && response_code < 400) {
  3717. /* Unknown redirection code */
  3718. return "Redirection";
  3719. }
  3720. if (response_code >= 400 && response_code < 500) {
  3721. /* Unknown request error code */
  3722. return "Client Error";
  3723. }
  3724. if (response_code >= 500 && response_code < 600) {
  3725. /* Unknown server error code */
  3726. return "Server Error";
  3727. }
  3728. /* Response code not even within reasonable range */
  3729. return "";
  3730. }
  3731. }
  3732. static void
  3733. mg_send_http_error_impl(struct mg_connection *conn,
  3734. int status,
  3735. const char *fmt,
  3736. va_list args)
  3737. {
  3738. char errmsg_buf[MG_BUF_LEN];
  3739. char path_buf[PATH_MAX];
  3740. va_list ap;
  3741. int len, i, page_handler_found, scope, truncated, has_body;
  3742. char date[64];
  3743. time_t curtime = time(NULL);
  3744. const char *error_handler = NULL;
  3745. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3746. const char *error_page_file_ext, *tstr;
  3747. int handled_by_callback = 0;
  3748. const char *status_text = mg_get_response_code_text(conn, status);
  3749. if ((conn == NULL) || (fmt == NULL)) {
  3750. return;
  3751. }
  3752. /* Set status (for log) */
  3753. conn->status_code = status;
  3754. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3755. has_body = ((status > 199) && (status != 204) && (status != 304));
  3756. /* Prepare message in buf, if required */
  3757. if (has_body || (!conn->in_error_handler
  3758. && (conn->phys_ctx->callbacks.http_error != NULL))) {
  3759. /* Store error message in errmsg_buf */
  3760. va_copy(ap, args);
  3761. mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap);
  3762. va_end(ap);
  3763. /* In a debug build, print all html errors */
  3764. DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf);
  3765. }
  3766. /* If there is a http_error callback, call it.
  3767. * But don't do it recursively, if callback calls mg_send_http_error again.
  3768. */
  3769. if (!conn->in_error_handler
  3770. && (conn->phys_ctx->callbacks.http_error != NULL)) {
  3771. /* Mark in_error_handler to avoid recursion and call user callback. */
  3772. conn->in_error_handler = 1;
  3773. handled_by_callback =
  3774. (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf)
  3775. == 0);
  3776. conn->in_error_handler = 0;
  3777. }
  3778. if (!handled_by_callback) {
  3779. /* Check for recursion */
  3780. if (conn->in_error_handler) {
  3781. DEBUG_TRACE(
  3782. "Recursion when handling error %u - fall back to default",
  3783. status);
  3784. } else {
  3785. /* Send user defined error pages, if defined */
  3786. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3787. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3788. page_handler_found = 0;
  3789. if (error_handler != NULL) {
  3790. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3791. switch (scope) {
  3792. case 1: /* Handler for specific error, e.g. 404 error */
  3793. mg_snprintf(conn,
  3794. &truncated,
  3795. path_buf,
  3796. sizeof(path_buf) - 32,
  3797. "%serror%03u.",
  3798. error_handler,
  3799. status);
  3800. break;
  3801. case 2: /* Handler for error group, e.g., 5xx error
  3802. * handler
  3803. * for all server errors (500-599) */
  3804. mg_snprintf(conn,
  3805. &truncated,
  3806. path_buf,
  3807. sizeof(path_buf) - 32,
  3808. "%serror%01uxx.",
  3809. error_handler,
  3810. status / 100);
  3811. break;
  3812. default: /* Handler for all errors */
  3813. mg_snprintf(conn,
  3814. &truncated,
  3815. path_buf,
  3816. sizeof(path_buf) - 32,
  3817. "%serror.",
  3818. error_handler);
  3819. break;
  3820. }
  3821. /* String truncation in buf may only occur if
  3822. * error_handler is too long. This string is
  3823. * from the config, not from a client. */
  3824. (void)truncated;
  3825. len = (int)strlen(path_buf);
  3826. tstr = strchr(error_page_file_ext, '.');
  3827. while (tstr) {
  3828. for (i = 1;
  3829. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3830. i++) {
  3831. /* buffer overrun is not possible here, since
  3832. * (i < 32) && (len < sizeof(path_buf) - 32)
  3833. * ==> (i + len) < sizeof(path_buf) */
  3834. path_buf[len + i - 1] = tstr[i];
  3835. }
  3836. /* buffer overrun is not possible here, since
  3837. * (i <= 32) && (len < sizeof(path_buf) - 32)
  3838. * ==> (i + len) <= sizeof(path_buf) */
  3839. path_buf[len + i - 1] = 0;
  3840. if (mg_stat(conn, path_buf, &error_page_file.stat)) {
  3841. DEBUG_TRACE("Check error page %s - found",
  3842. path_buf);
  3843. page_handler_found = 1;
  3844. break;
  3845. }
  3846. DEBUG_TRACE("Check error page %s - not found",
  3847. path_buf);
  3848. tstr = strchr(tstr + i, '.');
  3849. }
  3850. }
  3851. }
  3852. if (page_handler_found) {
  3853. conn->in_error_handler = 1;
  3854. handle_file_based_request(conn, path_buf, &error_page_file);
  3855. conn->in_error_handler = 0;
  3856. return;
  3857. }
  3858. }
  3859. /* No custom error page. Send default error page. */
  3860. gmt_time_string(date, sizeof(date), &curtime);
  3861. conn->must_close = 1;
  3862. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3863. send_no_cache_header(conn);
  3864. send_additional_header(conn);
  3865. if (has_body) {
  3866. mg_printf(conn,
  3867. "%s",
  3868. "Content-Type: text/plain; charset=utf-8\r\n");
  3869. }
  3870. mg_printf(conn,
  3871. "Date: %s\r\n"
  3872. "Connection: close\r\n\r\n",
  3873. date);
  3874. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3875. if (has_body) {
  3876. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3877. if (fmt != NULL) { /* <-- should be always true */
  3878. mg_write(conn, errmsg_buf, strlen(errmsg_buf));
  3879. }
  3880. } else {
  3881. /* No body allowed. Close the connection. */
  3882. DEBUG_TRACE("Error %i", status);
  3883. }
  3884. }
  3885. }
  3886. void
  3887. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3888. {
  3889. va_list ap;
  3890. va_start(ap, fmt);
  3891. mg_send_http_error_impl(conn, status, fmt, ap);
  3892. va_end(ap);
  3893. }
  3894. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3895. /* Create substitutes for POSIX functions in Win32. */
  3896. #if defined(__MINGW32__)
  3897. /* Show no warning in case system functions are not used. */
  3898. #pragma GCC diagnostic push
  3899. #pragma GCC diagnostic ignored "-Wunused-function"
  3900. #endif
  3901. FUNCTION_MAY_BE_UNUSED
  3902. static int
  3903. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3904. {
  3905. (void)unused;
  3906. *mutex = CreateMutex(NULL, FALSE, NULL);
  3907. return (*mutex == NULL) ? -1 : 0;
  3908. }
  3909. FUNCTION_MAY_BE_UNUSED
  3910. static int
  3911. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3912. {
  3913. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3914. }
  3915. FUNCTION_MAY_BE_UNUSED
  3916. static int
  3917. pthread_mutex_lock(pthread_mutex_t *mutex)
  3918. {
  3919. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  3920. : -1;
  3921. }
  3922. #if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS)
  3923. FUNCTION_MAY_BE_UNUSED
  3924. static int
  3925. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3926. {
  3927. switch (WaitForSingleObject(*mutex, 0)) {
  3928. case WAIT_OBJECT_0:
  3929. return 0;
  3930. case WAIT_TIMEOUT:
  3931. return -2; /* EBUSY */
  3932. }
  3933. return -1;
  3934. }
  3935. #endif
  3936. FUNCTION_MAY_BE_UNUSED
  3937. static int
  3938. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3939. {
  3940. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3941. }
  3942. FUNCTION_MAY_BE_UNUSED
  3943. static int
  3944. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3945. {
  3946. (void)unused;
  3947. InitializeCriticalSection(&cv->threadIdSec);
  3948. cv->waiting_thread = NULL;
  3949. return 0;
  3950. }
  3951. FUNCTION_MAY_BE_UNUSED
  3952. static int
  3953. pthread_cond_timedwait(pthread_cond_t *cv,
  3954. pthread_mutex_t *mutex,
  3955. FUNCTION_MAY_BE_UNUSED const struct timespec *abstime)
  3956. {
  3957. struct mg_workerTLS **ptls,
  3958. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3959. int ok;
  3960. int64_t nsnow, nswaitabs, nswaitrel;
  3961. DWORD mswaitrel;
  3962. EnterCriticalSection(&cv->threadIdSec);
  3963. /* Add this thread to cv's waiting list */
  3964. ptls = &cv->waiting_thread;
  3965. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3966. ;
  3967. tls->next_waiting_thread = NULL;
  3968. *ptls = tls;
  3969. LeaveCriticalSection(&cv->threadIdSec);
  3970. if (abstime) {
  3971. nsnow = mg_get_current_time_ns();
  3972. nswaitabs =
  3973. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3974. nswaitrel = nswaitabs - nsnow;
  3975. if (nswaitrel < 0) {
  3976. nswaitrel = 0;
  3977. }
  3978. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3979. } else {
  3980. mswaitrel = (DWORD)INFINITE;
  3981. }
  3982. pthread_mutex_unlock(mutex);
  3983. ok = (WAIT_OBJECT_0
  3984. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3985. if (!ok) {
  3986. ok = 1;
  3987. EnterCriticalSection(&cv->threadIdSec);
  3988. ptls = &cv->waiting_thread;
  3989. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3990. if (*ptls == tls) {
  3991. *ptls = tls->next_waiting_thread;
  3992. ok = 0;
  3993. break;
  3994. }
  3995. }
  3996. LeaveCriticalSection(&cv->threadIdSec);
  3997. if (ok) {
  3998. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  3999. (DWORD)INFINITE);
  4000. }
  4001. }
  4002. /* This thread has been removed from cv's waiting list */
  4003. pthread_mutex_lock(mutex);
  4004. return ok ? 0 : -1;
  4005. }
  4006. FUNCTION_MAY_BE_UNUSED
  4007. static int
  4008. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  4009. {
  4010. return pthread_cond_timedwait(cv, mutex, NULL);
  4011. }
  4012. FUNCTION_MAY_BE_UNUSED
  4013. static int
  4014. pthread_cond_signal(pthread_cond_t *cv)
  4015. {
  4016. HANDLE wkup = NULL;
  4017. BOOL ok = FALSE;
  4018. EnterCriticalSection(&cv->threadIdSec);
  4019. if (cv->waiting_thread) {
  4020. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  4021. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  4022. ok = SetEvent(wkup);
  4023. DEBUG_ASSERT(ok);
  4024. }
  4025. LeaveCriticalSection(&cv->threadIdSec);
  4026. return ok ? 0 : 1;
  4027. }
  4028. FUNCTION_MAY_BE_UNUSED
  4029. static int
  4030. pthread_cond_broadcast(pthread_cond_t *cv)
  4031. {
  4032. EnterCriticalSection(&cv->threadIdSec);
  4033. while (cv->waiting_thread) {
  4034. pthread_cond_signal(cv);
  4035. }
  4036. LeaveCriticalSection(&cv->threadIdSec);
  4037. return 0;
  4038. }
  4039. FUNCTION_MAY_BE_UNUSED
  4040. static int
  4041. pthread_cond_destroy(pthread_cond_t *cv)
  4042. {
  4043. EnterCriticalSection(&cv->threadIdSec);
  4044. DEBUG_ASSERT(cv->waiting_thread == NULL);
  4045. LeaveCriticalSection(&cv->threadIdSec);
  4046. DeleteCriticalSection(&cv->threadIdSec);
  4047. return 0;
  4048. }
  4049. #if defined(ALTERNATIVE_QUEUE)
  4050. FUNCTION_MAY_BE_UNUSED
  4051. static void *
  4052. event_create(void)
  4053. {
  4054. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  4055. }
  4056. FUNCTION_MAY_BE_UNUSED
  4057. static int
  4058. event_wait(void *eventhdl)
  4059. {
  4060. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  4061. return (res == WAIT_OBJECT_0);
  4062. }
  4063. FUNCTION_MAY_BE_UNUSED
  4064. static int
  4065. event_signal(void *eventhdl)
  4066. {
  4067. return (int)SetEvent((HANDLE)eventhdl);
  4068. }
  4069. FUNCTION_MAY_BE_UNUSED
  4070. static void
  4071. event_destroy(void *eventhdl)
  4072. {
  4073. CloseHandle((HANDLE)eventhdl);
  4074. }
  4075. #endif
  4076. #if defined(__MINGW32__)
  4077. /* Enable unused function warning again */
  4078. #pragma GCC diagnostic pop
  4079. #endif
  4080. /* For Windows, change all slashes to backslashes in path names. */
  4081. static void
  4082. change_slashes_to_backslashes(char *path)
  4083. {
  4084. int i;
  4085. for (i = 0; path[i] != '\0'; i++) {
  4086. if (path[i] == '/') {
  4087. path[i] = '\\';
  4088. }
  4089. /* remove double backslash (check i > 0 to preserve UNC paths,
  4090. * like \\server\file.txt) */
  4091. if ((path[i] == '\\') && (i > 0)) {
  4092. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  4093. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  4094. }
  4095. }
  4096. }
  4097. }
  4098. static int
  4099. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  4100. {
  4101. int diff;
  4102. do {
  4103. diff = tolower(*s1) - tolower(*s2);
  4104. s1++;
  4105. s2++;
  4106. } while ((diff == 0) && (s1[-1] != '\0'));
  4107. return diff;
  4108. }
  4109. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  4110. * wbuf and wbuf_len is a target buffer and its length. */
  4111. static void
  4112. path_to_unicode(const struct mg_connection *conn,
  4113. const char *path,
  4114. wchar_t *wbuf,
  4115. size_t wbuf_len)
  4116. {
  4117. char buf[PATH_MAX], buf2[PATH_MAX];
  4118. wchar_t wbuf2[W_PATH_MAX + 1];
  4119. DWORD long_len, err;
  4120. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  4121. mg_strlcpy(buf, path, sizeof(buf));
  4122. change_slashes_to_backslashes(buf);
  4123. /* Convert to Unicode and back. If doubly-converted string does not
  4124. * match the original, something is fishy, reject. */
  4125. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  4126. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  4127. WideCharToMultiByte(
  4128. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  4129. if (strcmp(buf, buf2) != 0) {
  4130. wbuf[0] = L'\0';
  4131. }
  4132. /* Windows file systems are not case sensitive, but you can still use
  4133. * uppercase and lowercase letters (on all modern file systems).
  4134. * The server can check if the URI uses the same upper/lowercase
  4135. * letters an the file system, effectively making Windows servers
  4136. * case sensitive (like Linux servers are). It is still not possible
  4137. * to use two files with the same name in different cases on Windows
  4138. * (like /a and /A) - this would be possible in Linux.
  4139. * As a default, Windows is not case sensitive, but the case sensitive
  4140. * file name check can be activated by an additional configuration. */
  4141. if (conn) {
  4142. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  4143. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  4144. "yes")) {
  4145. /* Use case sensitive compare function */
  4146. fcompare = wcscmp;
  4147. }
  4148. }
  4149. (void)conn; /* conn is currently unused */
  4150. #if !defined(_WIN32_WCE)
  4151. /* Only accept a full file path, not a Windows short (8.3) path. */
  4152. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  4153. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  4154. if (long_len == 0) {
  4155. err = GetLastError();
  4156. if (err == ERROR_FILE_NOT_FOUND) {
  4157. /* File does not exist. This is not always a problem here. */
  4158. return;
  4159. }
  4160. }
  4161. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  4162. /* Short name is used. */
  4163. wbuf[0] = L'\0';
  4164. }
  4165. #else
  4166. (void)long_len;
  4167. (void)wbuf2;
  4168. (void)err;
  4169. if (strchr(path, '~')) {
  4170. wbuf[0] = L'\0';
  4171. }
  4172. #endif
  4173. }
  4174. /* Windows happily opens files with some garbage at the end of file name.
  4175. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  4176. * "a.cgi", despite one would expect an error back.
  4177. * This function returns non-0 if path ends with some garbage. */
  4178. static int
  4179. path_cannot_disclose_cgi(const char *path)
  4180. {
  4181. static const char *allowed_last_characters = "_-";
  4182. int last = path[strlen(path) - 1];
  4183. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  4184. }
  4185. static int
  4186. mg_stat(const struct mg_connection *conn,
  4187. const char *path,
  4188. struct mg_file_stat *filep)
  4189. {
  4190. wchar_t wbuf[W_PATH_MAX];
  4191. WIN32_FILE_ATTRIBUTE_DATA info;
  4192. time_t creation_time;
  4193. if (!filep) {
  4194. return 0;
  4195. }
  4196. memset(filep, 0, sizeof(*filep));
  4197. if (conn && is_file_in_memory(conn, path)) {
  4198. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4199. * memset */
  4200. /* Quick fix (for 1.9.x): */
  4201. /* mg_stat must fill all fields, also for files in memory */
  4202. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4203. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4204. filep->size = tmp_file.stat.size;
  4205. filep->location = 2;
  4206. /* TODO: for 1.10: restructure how files in memory are handled */
  4207. /* The "file in memory" feature is a candidate for deletion.
  4208. * Please join the discussion at
  4209. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4210. */
  4211. filep->last_modified = time(NULL); /* TODO */
  4212. /* last_modified = now ... assumes the file may change during
  4213. * runtime,
  4214. * so every mg_fopen call may return different data */
  4215. /* last_modified = conn->phys_ctx.start_time;
  4216. * May be used it the data does not change during runtime. This
  4217. * allows
  4218. * browser caching. Since we do not know, we have to assume the file
  4219. * in memory may change. */
  4220. return 1;
  4221. }
  4222. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4223. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  4224. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4225. filep->last_modified =
  4226. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4227. info.ftLastWriteTime.dwHighDateTime);
  4228. /* On Windows, the file creation time can be higher than the
  4229. * modification time, e.g. when a file is copied.
  4230. * Since the Last-Modified timestamp is used for caching
  4231. * it should be based on the most recent timestamp. */
  4232. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4233. info.ftCreationTime.dwHighDateTime);
  4234. if (creation_time > filep->last_modified) {
  4235. filep->last_modified = creation_time;
  4236. }
  4237. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4238. /* If file name is fishy, reset the file structure and return
  4239. * error.
  4240. * Note it is important to reset, not just return the error, cause
  4241. * functions like is_file_opened() check the struct. */
  4242. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  4243. memset(filep, 0, sizeof(*filep));
  4244. return 0;
  4245. }
  4246. return 1;
  4247. }
  4248. return 0;
  4249. }
  4250. static int
  4251. mg_remove(const struct mg_connection *conn, const char *path)
  4252. {
  4253. wchar_t wbuf[W_PATH_MAX];
  4254. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4255. return DeleteFileW(wbuf) ? 0 : -1;
  4256. }
  4257. static int
  4258. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4259. {
  4260. wchar_t wbuf[W_PATH_MAX];
  4261. (void)mode;
  4262. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4263. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4264. }
  4265. /* Create substitutes for POSIX functions in Win32. */
  4266. #if defined(__MINGW32__)
  4267. /* Show no warning in case system functions are not used. */
  4268. #pragma GCC diagnostic push
  4269. #pragma GCC diagnostic ignored "-Wunused-function"
  4270. #endif
  4271. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4272. FUNCTION_MAY_BE_UNUSED
  4273. static DIR *
  4274. mg_opendir(const struct mg_connection *conn, const char *name)
  4275. {
  4276. DIR *dir = NULL;
  4277. wchar_t wpath[W_PATH_MAX];
  4278. DWORD attrs;
  4279. if (name == NULL) {
  4280. SetLastError(ERROR_BAD_ARGUMENTS);
  4281. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4282. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4283. } else {
  4284. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4285. attrs = GetFileAttributesW(wpath);
  4286. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4287. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4288. (void)wcscat(wpath, L"\\*");
  4289. dir->handle = FindFirstFileW(wpath, &dir->info);
  4290. dir->result.d_name[0] = '\0';
  4291. } else {
  4292. mg_free(dir);
  4293. dir = NULL;
  4294. }
  4295. }
  4296. return dir;
  4297. }
  4298. FUNCTION_MAY_BE_UNUSED
  4299. static int
  4300. mg_closedir(DIR *dir)
  4301. {
  4302. int result = 0;
  4303. if (dir != NULL) {
  4304. if (dir->handle != INVALID_HANDLE_VALUE)
  4305. result = FindClose(dir->handle) ? 0 : -1;
  4306. mg_free(dir);
  4307. } else {
  4308. result = -1;
  4309. SetLastError(ERROR_BAD_ARGUMENTS);
  4310. }
  4311. return result;
  4312. }
  4313. FUNCTION_MAY_BE_UNUSED
  4314. static struct dirent *
  4315. mg_readdir(DIR *dir)
  4316. {
  4317. struct dirent *result = 0;
  4318. if (dir) {
  4319. if (dir->handle != INVALID_HANDLE_VALUE) {
  4320. result = &dir->result;
  4321. (void)WideCharToMultiByte(CP_UTF8,
  4322. 0,
  4323. dir->info.cFileName,
  4324. -1,
  4325. result->d_name,
  4326. sizeof(result->d_name),
  4327. NULL,
  4328. NULL);
  4329. if (!FindNextFileW(dir->handle, &dir->info)) {
  4330. (void)FindClose(dir->handle);
  4331. dir->handle = INVALID_HANDLE_VALUE;
  4332. }
  4333. } else {
  4334. SetLastError(ERROR_FILE_NOT_FOUND);
  4335. }
  4336. } else {
  4337. SetLastError(ERROR_BAD_ARGUMENTS);
  4338. }
  4339. return result;
  4340. }
  4341. #if !defined(HAVE_POLL)
  4342. FUNCTION_MAY_BE_UNUSED
  4343. static int
  4344. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4345. {
  4346. struct timeval tv;
  4347. fd_set set;
  4348. unsigned int i;
  4349. int result;
  4350. SOCKET maxfd = 0;
  4351. memset(&tv, 0, sizeof(tv));
  4352. tv.tv_sec = milliseconds / 1000;
  4353. tv.tv_usec = (milliseconds % 1000) * 1000;
  4354. FD_ZERO(&set);
  4355. for (i = 0; i < n; i++) {
  4356. FD_SET((SOCKET)pfd[i].fd, &set);
  4357. pfd[i].revents = 0;
  4358. if (pfd[i].fd > maxfd) {
  4359. maxfd = pfd[i].fd;
  4360. }
  4361. }
  4362. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  4363. for (i = 0; i < n; i++) {
  4364. if (FD_ISSET(pfd[i].fd, &set)) {
  4365. pfd[i].revents = POLLIN;
  4366. }
  4367. }
  4368. }
  4369. /* We should subtract the time used in select from remaining
  4370. * "milliseconds", in particular if called from mg_poll with a
  4371. * timeout quantum.
  4372. * Unfortunately, the remaining time is not stored in "tv" in all
  4373. * implementations, so the result in "tv" must be considered undefined.
  4374. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4375. return result;
  4376. }
  4377. #endif /* HAVE_POLL */
  4378. #if defined(__MINGW32__)
  4379. /* Enable unused function warning again */
  4380. #pragma GCC diagnostic pop
  4381. #endif
  4382. static void
  4383. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4384. {
  4385. (void)conn; /* Unused. */
  4386. #if defined(_WIN32_WCE)
  4387. (void)sock;
  4388. #else
  4389. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4390. #endif
  4391. }
  4392. int
  4393. mg_start_thread(mg_thread_func_t f, void *p)
  4394. {
  4395. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4396. /* Compile-time option to control stack size, e.g.
  4397. * -DUSE_STACK_SIZE=16384
  4398. */
  4399. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4400. == ((uintptr_t)(-1L)))
  4401. ? -1
  4402. : 0);
  4403. #else
  4404. return (
  4405. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4406. ? -1
  4407. : 0);
  4408. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4409. }
  4410. /* Start a thread storing the thread context. */
  4411. static int
  4412. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4413. void *p,
  4414. pthread_t *threadidptr)
  4415. {
  4416. uintptr_t uip;
  4417. HANDLE threadhandle;
  4418. int result = -1;
  4419. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4420. threadhandle = (HANDLE)uip;
  4421. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4422. *threadidptr = threadhandle;
  4423. result = 0;
  4424. }
  4425. return result;
  4426. }
  4427. /* Wait for a thread to finish. */
  4428. static int
  4429. mg_join_thread(pthread_t threadid)
  4430. {
  4431. int result;
  4432. DWORD dwevent;
  4433. result = -1;
  4434. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4435. if (dwevent == WAIT_FAILED) {
  4436. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4437. } else {
  4438. if (dwevent == WAIT_OBJECT_0) {
  4439. CloseHandle(threadid);
  4440. result = 0;
  4441. }
  4442. }
  4443. return result;
  4444. }
  4445. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4446. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4447. /* Create substitutes for POSIX functions in Win32. */
  4448. #if defined(__MINGW32__)
  4449. /* Show no warning in case system functions are not used. */
  4450. #pragma GCC diagnostic push
  4451. #pragma GCC diagnostic ignored "-Wunused-function"
  4452. #endif
  4453. FUNCTION_MAY_BE_UNUSED
  4454. static HANDLE
  4455. dlopen(const char *dll_name, int flags)
  4456. {
  4457. wchar_t wbuf[W_PATH_MAX];
  4458. (void)flags;
  4459. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4460. return LoadLibraryW(wbuf);
  4461. }
  4462. FUNCTION_MAY_BE_UNUSED
  4463. static int
  4464. dlclose(void *handle)
  4465. {
  4466. int result;
  4467. if (FreeLibrary((HMODULE)handle) != 0) {
  4468. result = 0;
  4469. } else {
  4470. result = -1;
  4471. }
  4472. return result;
  4473. }
  4474. #if defined(__MINGW32__)
  4475. /* Enable unused function warning again */
  4476. #pragma GCC diagnostic pop
  4477. #endif
  4478. #endif
  4479. #if !defined(NO_CGI)
  4480. #define SIGKILL (0)
  4481. static int
  4482. kill(pid_t pid, int sig_num)
  4483. {
  4484. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4485. (void)CloseHandle((HANDLE)pid);
  4486. return 0;
  4487. }
  4488. static void
  4489. trim_trailing_whitespaces(char *s)
  4490. {
  4491. char *e = s + strlen(s) - 1;
  4492. while ((e > s) && isspace(*(unsigned char *)e)) {
  4493. *e-- = '\0';
  4494. }
  4495. }
  4496. static pid_t
  4497. spawn_process(struct mg_connection *conn,
  4498. const char *prog,
  4499. char *envblk,
  4500. char *envp[],
  4501. int fdin[2],
  4502. int fdout[2],
  4503. int fderr[2],
  4504. const char *dir)
  4505. {
  4506. HANDLE me;
  4507. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4508. cmdline[PATH_MAX], buf[PATH_MAX];
  4509. int truncated;
  4510. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4511. STARTUPINFOA si;
  4512. PROCESS_INFORMATION pi = {0};
  4513. (void)envp;
  4514. memset(&si, 0, sizeof(si));
  4515. si.cb = sizeof(si);
  4516. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4517. si.wShowWindow = SW_HIDE;
  4518. me = GetCurrentProcess();
  4519. DuplicateHandle(me,
  4520. (HANDLE)_get_osfhandle(fdin[0]),
  4521. me,
  4522. &si.hStdInput,
  4523. 0,
  4524. TRUE,
  4525. DUPLICATE_SAME_ACCESS);
  4526. DuplicateHandle(me,
  4527. (HANDLE)_get_osfhandle(fdout[1]),
  4528. me,
  4529. &si.hStdOutput,
  4530. 0,
  4531. TRUE,
  4532. DUPLICATE_SAME_ACCESS);
  4533. DuplicateHandle(me,
  4534. (HANDLE)_get_osfhandle(fderr[1]),
  4535. me,
  4536. &si.hStdError,
  4537. 0,
  4538. TRUE,
  4539. DUPLICATE_SAME_ACCESS);
  4540. /* Mark handles that should not be inherited. See
  4541. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4542. */
  4543. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4544. HANDLE_FLAG_INHERIT,
  4545. 0);
  4546. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4547. HANDLE_FLAG_INHERIT,
  4548. 0);
  4549. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4550. HANDLE_FLAG_INHERIT,
  4551. 0);
  4552. /* If CGI file is a script, try to read the interpreter line */
  4553. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4554. if (interp == NULL) {
  4555. buf[0] = buf[1] = '\0';
  4556. /* Read the first line of the script into the buffer */
  4557. mg_snprintf(
  4558. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4559. if (truncated) {
  4560. pi.hProcess = (pid_t)-1;
  4561. goto spawn_cleanup;
  4562. }
  4563. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4564. #if defined(MG_USE_OPEN_FILE)
  4565. p = (char *)file.access.membuf;
  4566. #else
  4567. p = (char *)NULL;
  4568. #endif
  4569. mg_fgets(buf, sizeof(buf), &file, &p);
  4570. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4571. buf[sizeof(buf) - 1] = '\0';
  4572. }
  4573. if ((buf[0] == '#') && (buf[1] == '!')) {
  4574. trim_trailing_whitespaces(buf + 2);
  4575. } else {
  4576. buf[2] = '\0';
  4577. }
  4578. interp = buf + 2;
  4579. }
  4580. if (interp[0] != '\0') {
  4581. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4582. interp = full_interp;
  4583. }
  4584. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4585. if (interp[0] != '\0') {
  4586. mg_snprintf(conn,
  4587. &truncated,
  4588. cmdline,
  4589. sizeof(cmdline),
  4590. "\"%s\" \"%s\\%s\"",
  4591. interp,
  4592. full_dir,
  4593. prog);
  4594. } else {
  4595. mg_snprintf(conn,
  4596. &truncated,
  4597. cmdline,
  4598. sizeof(cmdline),
  4599. "\"%s\\%s\"",
  4600. full_dir,
  4601. prog);
  4602. }
  4603. if (truncated) {
  4604. pi.hProcess = (pid_t)-1;
  4605. goto spawn_cleanup;
  4606. }
  4607. DEBUG_TRACE("Running [%s]", cmdline);
  4608. if (CreateProcessA(NULL,
  4609. cmdline,
  4610. NULL,
  4611. NULL,
  4612. TRUE,
  4613. CREATE_NEW_PROCESS_GROUP,
  4614. envblk,
  4615. NULL,
  4616. &si,
  4617. &pi) == 0) {
  4618. mg_cry_internal(
  4619. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4620. pi.hProcess = (pid_t)-1;
  4621. /* goto spawn_cleanup; */
  4622. }
  4623. spawn_cleanup:
  4624. (void)CloseHandle(si.hStdOutput);
  4625. (void)CloseHandle(si.hStdError);
  4626. (void)CloseHandle(si.hStdInput);
  4627. if (pi.hThread != NULL) {
  4628. (void)CloseHandle(pi.hThread);
  4629. }
  4630. return (pid_t)pi.hProcess;
  4631. }
  4632. #endif /* !NO_CGI */
  4633. static int
  4634. set_blocking_mode(SOCKET sock)
  4635. {
  4636. unsigned long non_blocking = 0;
  4637. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4638. }
  4639. static int
  4640. set_non_blocking_mode(SOCKET sock)
  4641. {
  4642. unsigned long non_blocking = 1;
  4643. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4644. }
  4645. #else
  4646. static int
  4647. mg_stat(const struct mg_connection *conn,
  4648. const char *path,
  4649. struct mg_file_stat *filep)
  4650. {
  4651. struct stat st;
  4652. if (!filep) {
  4653. return 0;
  4654. }
  4655. memset(filep, 0, sizeof(*filep));
  4656. if (conn && is_file_in_memory(conn, path)) {
  4657. /* Quick fix (for 1.9.x): */
  4658. /* mg_stat must fill all fields, also for files in memory */
  4659. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4660. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4661. filep->size = tmp_file.stat.size;
  4662. filep->last_modified = time(NULL);
  4663. filep->location = 2;
  4664. /* TODO: remove legacy "files in memory" feature */
  4665. return 1;
  4666. }
  4667. if (0 == stat(path, &st)) {
  4668. filep->size = (uint64_t)(st.st_size);
  4669. filep->last_modified = st.st_mtime;
  4670. filep->is_directory = S_ISDIR(st.st_mode);
  4671. return 1;
  4672. }
  4673. return 0;
  4674. }
  4675. static void
  4676. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4677. {
  4678. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4679. if (conn) {
  4680. mg_cry_internal(conn,
  4681. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4682. __func__,
  4683. strerror(ERRNO));
  4684. }
  4685. }
  4686. }
  4687. int
  4688. mg_start_thread(mg_thread_func_t func, void *param)
  4689. {
  4690. pthread_t thread_id;
  4691. pthread_attr_t attr;
  4692. int result;
  4693. (void)pthread_attr_init(&attr);
  4694. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4695. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4696. /* Compile-time option to control stack size,
  4697. * e.g. -DUSE_STACK_SIZE=16384 */
  4698. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4699. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4700. result = pthread_create(&thread_id, &attr, func, param);
  4701. pthread_attr_destroy(&attr);
  4702. return result;
  4703. }
  4704. /* Start a thread storing the thread context. */
  4705. static int
  4706. mg_start_thread_with_id(mg_thread_func_t func,
  4707. void *param,
  4708. pthread_t *threadidptr)
  4709. {
  4710. pthread_t thread_id;
  4711. pthread_attr_t attr;
  4712. int result;
  4713. (void)pthread_attr_init(&attr);
  4714. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4715. /* Compile-time option to control stack size,
  4716. * e.g. -DUSE_STACK_SIZE=16384 */
  4717. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4718. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4719. result = pthread_create(&thread_id, &attr, func, param);
  4720. pthread_attr_destroy(&attr);
  4721. if ((result == 0) && (threadidptr != NULL)) {
  4722. *threadidptr = thread_id;
  4723. }
  4724. return result;
  4725. }
  4726. /* Wait for a thread to finish. */
  4727. static int
  4728. mg_join_thread(pthread_t threadid)
  4729. {
  4730. int result;
  4731. result = pthread_join(threadid, NULL);
  4732. return result;
  4733. }
  4734. #if !defined(NO_CGI)
  4735. static pid_t
  4736. spawn_process(struct mg_connection *conn,
  4737. const char *prog,
  4738. char *envblk,
  4739. char *envp[],
  4740. int fdin[2],
  4741. int fdout[2],
  4742. int fderr[2],
  4743. const char *dir)
  4744. {
  4745. pid_t pid;
  4746. const char *interp;
  4747. (void)envblk;
  4748. if (conn == NULL) {
  4749. return 0;
  4750. }
  4751. if ((pid = fork()) == -1) {
  4752. /* Parent */
  4753. mg_send_http_error(conn,
  4754. 500,
  4755. "Error: Creating CGI process\nfork(): %s",
  4756. strerror(ERRNO));
  4757. } else if (pid == 0) {
  4758. /* Child */
  4759. if (chdir(dir) != 0) {
  4760. mg_cry_internal(
  4761. conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4762. } else if (dup2(fdin[0], 0) == -1) {
  4763. mg_cry_internal(conn,
  4764. "%s: dup2(%d, 0): %s",
  4765. __func__,
  4766. fdin[0],
  4767. strerror(ERRNO));
  4768. } else if (dup2(fdout[1], 1) == -1) {
  4769. mg_cry_internal(conn,
  4770. "%s: dup2(%d, 1): %s",
  4771. __func__,
  4772. fdout[1],
  4773. strerror(ERRNO));
  4774. } else if (dup2(fderr[1], 2) == -1) {
  4775. mg_cry_internal(conn,
  4776. "%s: dup2(%d, 2): %s",
  4777. __func__,
  4778. fderr[1],
  4779. strerror(ERRNO));
  4780. } else {
  4781. /* Keep stderr and stdout in two different pipes.
  4782. * Stdout will be sent back to the client,
  4783. * stderr should go into a server error log. */
  4784. (void)close(fdin[0]);
  4785. (void)close(fdout[1]);
  4786. (void)close(fderr[1]);
  4787. /* Close write end fdin and read end fdout and fderr */
  4788. (void)close(fdin[1]);
  4789. (void)close(fdout[0]);
  4790. (void)close(fderr[0]);
  4791. /* After exec, all signal handlers are restored to their default
  4792. * values, with one exception of SIGCHLD. According to
  4793. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler
  4794. * will leave unchanged after exec if it was set to be ignored.
  4795. * Restore it to default action. */
  4796. signal(SIGCHLD, SIG_DFL);
  4797. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4798. if (interp == NULL) {
  4799. (void)execle(prog, prog, NULL, envp);
  4800. mg_cry_internal(conn,
  4801. "%s: execle(%s): %s",
  4802. __func__,
  4803. prog,
  4804. strerror(ERRNO));
  4805. } else {
  4806. (void)execle(interp, interp, prog, NULL, envp);
  4807. mg_cry_internal(conn,
  4808. "%s: execle(%s %s): %s",
  4809. __func__,
  4810. interp,
  4811. prog,
  4812. strerror(ERRNO));
  4813. }
  4814. }
  4815. exit(EXIT_FAILURE);
  4816. }
  4817. return pid;
  4818. }
  4819. #endif /* !NO_CGI */
  4820. static int
  4821. set_non_blocking_mode(SOCKET sock)
  4822. {
  4823. int flags = fcntl(sock, F_GETFL, 0);
  4824. if (flags < 0) {
  4825. return -1;
  4826. }
  4827. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4828. return -1;
  4829. }
  4830. return 0;
  4831. }
  4832. static int
  4833. set_blocking_mode(SOCKET sock)
  4834. {
  4835. int flags = fcntl(sock, F_GETFL, 0);
  4836. if (flags < 0) {
  4837. return -1;
  4838. }
  4839. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4840. return -1;
  4841. }
  4842. return 0;
  4843. }
  4844. #endif /* _WIN32 / else */
  4845. /* End of initial operating system specific define block. */
  4846. /* Get a random number (independent of C rand function) */
  4847. static uint64_t
  4848. get_random(void)
  4849. {
  4850. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4851. static uint64_t lcg = 0; /* Linear congruential generator */
  4852. uint64_t now = mg_get_current_time_ns();
  4853. if (lfsr == 0) {
  4854. /* lfsr will be only 0 if has not been initialized,
  4855. * so this code is called only once. */
  4856. lfsr = mg_get_current_time_ns();
  4857. lcg = mg_get_current_time_ns();
  4858. } else {
  4859. /* Get the next step of both random number generators. */
  4860. lfsr = (lfsr >> 1)
  4861. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4862. << 63);
  4863. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4864. }
  4865. /* Combining two pseudo-random number generators and a high resolution
  4866. * part
  4867. * of the current server time will make it hard (impossible?) to guess
  4868. * the
  4869. * next number. */
  4870. return (lfsr ^ lcg ^ now);
  4871. }
  4872. static int
  4873. mg_poll(struct pollfd *pfd,
  4874. unsigned int n,
  4875. int milliseconds,
  4876. volatile int *stop_server)
  4877. {
  4878. /* Call poll, but only for a maximum time of a few seconds.
  4879. * This will allow to stop the server after some seconds, instead
  4880. * of having to wait for a long socket timeout. */
  4881. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4882. do {
  4883. int result;
  4884. if (*stop_server) {
  4885. /* Shut down signal */
  4886. return -2;
  4887. }
  4888. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4889. ms_now = milliseconds;
  4890. }
  4891. result = poll(pfd, n, ms_now);
  4892. if (result != 0) {
  4893. /* Poll returned either success (1) or error (-1).
  4894. * Forward both to the caller. */
  4895. return result;
  4896. }
  4897. /* Poll returned timeout (0). */
  4898. if (milliseconds > 0) {
  4899. milliseconds -= ms_now;
  4900. }
  4901. } while (milliseconds != 0);
  4902. /* timeout: return 0 */
  4903. return 0;
  4904. }
  4905. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4906. * descriptor.
  4907. * Return value:
  4908. * >=0 .. number of bytes successfully written
  4909. * -1 .. timeout
  4910. * -2 .. error
  4911. */
  4912. static int
  4913. push_inner(struct mg_context *ctx,
  4914. FILE *fp,
  4915. SOCKET sock,
  4916. SSL *ssl,
  4917. const char *buf,
  4918. int len,
  4919. double timeout)
  4920. {
  4921. uint64_t start = 0, now = 0, timeout_ns = 0;
  4922. int n, err;
  4923. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4924. #if defined(_WIN32)
  4925. typedef int len_t;
  4926. #else
  4927. typedef size_t len_t;
  4928. #endif
  4929. if (timeout > 0) {
  4930. now = mg_get_current_time_ns();
  4931. start = now;
  4932. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4933. }
  4934. if (ctx == NULL) {
  4935. return -2;
  4936. }
  4937. #if defined(NO_SSL)
  4938. if (ssl) {
  4939. return -2;
  4940. }
  4941. #endif
  4942. /* Try to read until it succeeds, fails, times out, or the server
  4943. * shuts down. */
  4944. for (;;) {
  4945. #if !defined(NO_SSL)
  4946. if (ssl != NULL) {
  4947. n = SSL_write(ssl, buf, len);
  4948. if (n <= 0) {
  4949. err = SSL_get_error(ssl, n);
  4950. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4951. err = ERRNO;
  4952. } else if ((err == SSL_ERROR_WANT_READ)
  4953. || (err == SSL_ERROR_WANT_WRITE)) {
  4954. n = 0;
  4955. } else {
  4956. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4957. return -2;
  4958. }
  4959. } else {
  4960. err = 0;
  4961. }
  4962. } else
  4963. #endif
  4964. if (fp != NULL) {
  4965. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4966. if (ferror(fp)) {
  4967. n = -1;
  4968. err = ERRNO;
  4969. } else {
  4970. err = 0;
  4971. }
  4972. } else {
  4973. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4974. err = (n < 0) ? ERRNO : 0;
  4975. #if defined(_WIN32)
  4976. if (err == WSAEWOULDBLOCK) {
  4977. err = 0;
  4978. n = 0;
  4979. }
  4980. #else
  4981. if (err == EWOULDBLOCK) {
  4982. err = 0;
  4983. n = 0;
  4984. }
  4985. #endif
  4986. if (n < 0) {
  4987. /* shutdown of the socket at client side */
  4988. return -2;
  4989. }
  4990. }
  4991. if (ctx->stop_flag) {
  4992. return -2;
  4993. }
  4994. if ((n > 0) || ((n == 0) && (len == 0))) {
  4995. /* some data has been read, or no data was requested */
  4996. return n;
  4997. }
  4998. if (n < 0) {
  4999. /* socket error - check errno */
  5000. DEBUG_TRACE("send() failed, error %d", err);
  5001. /* TODO (mid): error handling depending on the error code.
  5002. * These codes are different between Windows and Linux.
  5003. * Currently there is no problem with failing send calls,
  5004. * if there is a reproducible situation, it should be
  5005. * investigated in detail.
  5006. */
  5007. return -2;
  5008. }
  5009. /* Only in case n=0 (timeout), repeat calling the write function */
  5010. /* If send failed, wait before retry */
  5011. if (fp != NULL) {
  5012. /* For files, just wait a fixed time.
  5013. * Maybe it helps, maybe not. */
  5014. mg_sleep(5);
  5015. } else {
  5016. /* For sockets, wait for the socket using select */
  5017. fd_set wfds;
  5018. struct timeval tv;
  5019. int sret;
  5020. #if defined(__GNUC__) || defined(__MINGW32__)
  5021. /* GCC seems to have a flaw with it's own socket macros:
  5022. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  5023. */
  5024. #pragma GCC diagnostic push
  5025. #pragma GCC diagnostic ignored "-Wsign-conversion"
  5026. #endif
  5027. FD_ZERO(&wfds);
  5028. FD_SET(sock, &wfds);
  5029. tv.tv_sec = (time_t)(ms_wait / 1000);
  5030. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  5031. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  5032. #if defined(__GNUC__) || defined(__MINGW32__)
  5033. #pragma GCC diagnostic pop
  5034. #endif
  5035. if (sret > 0) {
  5036. /* We got ready to write. Don't check the timeout
  5037. * but directly go back to write again. */
  5038. continue;
  5039. }
  5040. }
  5041. if (timeout > 0) {
  5042. now = mg_get_current_time_ns();
  5043. if ((now - start) > timeout_ns) {
  5044. /* Timeout */
  5045. break;
  5046. }
  5047. }
  5048. }
  5049. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  5050. used */
  5051. return -1;
  5052. }
  5053. static int64_t
  5054. push_all(struct mg_context *ctx,
  5055. FILE *fp,
  5056. SOCKET sock,
  5057. SSL *ssl,
  5058. const char *buf,
  5059. int64_t len)
  5060. {
  5061. double timeout = -1.0;
  5062. int64_t n, nwritten = 0;
  5063. if (ctx == NULL) {
  5064. return -1;
  5065. }
  5066. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  5067. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  5068. }
  5069. while ((len > 0) && (ctx->stop_flag == 0)) {
  5070. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  5071. if (n < 0) {
  5072. if (nwritten == 0) {
  5073. nwritten = n; /* Propagate the error */
  5074. }
  5075. break;
  5076. } else if (n == 0) {
  5077. break; /* No more data to write */
  5078. } else {
  5079. nwritten += n;
  5080. len -= n;
  5081. }
  5082. }
  5083. return nwritten;
  5084. }
  5085. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  5086. * Return value:
  5087. * >=0 .. number of bytes successfully read
  5088. * -1 .. timeout
  5089. * -2 .. error
  5090. */
  5091. static int
  5092. pull_inner(FILE *fp,
  5093. struct mg_connection *conn,
  5094. char *buf,
  5095. int len,
  5096. double timeout)
  5097. {
  5098. int nread, err = 0;
  5099. #if defined(_WIN32)
  5100. typedef int len_t;
  5101. #else
  5102. typedef size_t len_t;
  5103. #endif
  5104. #if !defined(NO_SSL)
  5105. int ssl_pending;
  5106. #endif
  5107. /* We need an additional wait loop around this, because in some cases
  5108. * with TLSwe may get data from the socket but not from SSL_read.
  5109. * In this case we need to repeat at least once.
  5110. */
  5111. if (fp != NULL) {
  5112. #if !defined(_WIN32_WCE)
  5113. /* Use read() instead of fread(), because if we're reading from the
  5114. * CGI pipe, fread() may block until IO buffer is filled up. We
  5115. * cannot afford to block and must pass all read bytes immediately
  5116. * to the client. */
  5117. nread = (int)read(fileno(fp), buf, (size_t)len);
  5118. #else
  5119. /* WinCE does not support CGI pipes */
  5120. nread = (int)fread(buf, 1, (size_t)len, fp);
  5121. #endif
  5122. err = (nread < 0) ? ERRNO : 0;
  5123. if ((nread == 0) && (len > 0)) {
  5124. /* Should get data, but got EOL */
  5125. return -2;
  5126. }
  5127. #if !defined(NO_SSL)
  5128. } else if ((conn->ssl != NULL)
  5129. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  5130. /* We already know there is no more data buffered in conn->buf
  5131. * but there is more available in the SSL layer. So don't poll
  5132. * conn->client.sock yet. */
  5133. if (ssl_pending > len) {
  5134. ssl_pending = len;
  5135. }
  5136. nread = SSL_read(conn->ssl, buf, ssl_pending);
  5137. if (nread <= 0) {
  5138. err = SSL_get_error(conn->ssl, nread);
  5139. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5140. err = ERRNO;
  5141. } else if ((err == SSL_ERROR_WANT_READ)
  5142. || (err == SSL_ERROR_WANT_WRITE)) {
  5143. nread = 0;
  5144. } else {
  5145. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5146. return -1;
  5147. }
  5148. } else {
  5149. err = 0;
  5150. }
  5151. } else if (conn->ssl != NULL) {
  5152. struct pollfd pfd[1];
  5153. int pollres;
  5154. pfd[0].fd = conn->client.sock;
  5155. pfd[0].events = POLLIN;
  5156. pollres = mg_poll(pfd,
  5157. 1,
  5158. (int)(timeout * 1000.0),
  5159. &(conn->phys_ctx->stop_flag));
  5160. if (conn->phys_ctx->stop_flag) {
  5161. return -2;
  5162. }
  5163. if (pollres > 0) {
  5164. nread = SSL_read(conn->ssl, buf, len);
  5165. if (nread <= 0) {
  5166. err = SSL_get_error(conn->ssl, nread);
  5167. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  5168. err = ERRNO;
  5169. } else if ((err == SSL_ERROR_WANT_READ)
  5170. || (err == SSL_ERROR_WANT_WRITE)) {
  5171. nread = 0;
  5172. } else {
  5173. DEBUG_TRACE("SSL_read() failed, error %d", err);
  5174. return -2;
  5175. }
  5176. } else {
  5177. err = 0;
  5178. }
  5179. } else if (pollres < 0) {
  5180. /* Error */
  5181. return -2;
  5182. } else {
  5183. /* pollres = 0 means timeout */
  5184. nread = 0;
  5185. }
  5186. #endif
  5187. } else {
  5188. struct pollfd pfd[1];
  5189. int pollres;
  5190. pfd[0].fd = conn->client.sock;
  5191. pfd[0].events = POLLIN;
  5192. pollres = mg_poll(pfd,
  5193. 1,
  5194. (int)(timeout * 1000.0),
  5195. &(conn->phys_ctx->stop_flag));
  5196. if (conn->phys_ctx->stop_flag) {
  5197. return -2;
  5198. }
  5199. if (pollres > 0) {
  5200. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5201. err = (nread < 0) ? ERRNO : 0;
  5202. if (nread <= 0) {
  5203. /* shutdown of the socket at client side */
  5204. return -2;
  5205. }
  5206. } else if (pollres < 0) {
  5207. /* error callint poll */
  5208. return -2;
  5209. } else {
  5210. /* pollres = 0 means timeout */
  5211. nread = 0;
  5212. }
  5213. }
  5214. if (conn->phys_ctx->stop_flag) {
  5215. return -2;
  5216. }
  5217. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5218. /* some data has been read, or no data was requested */
  5219. return nread;
  5220. }
  5221. if (nread < 0) {
  5222. /* socket error - check errno */
  5223. #if defined(_WIN32)
  5224. if (err == WSAEWOULDBLOCK) {
  5225. /* TODO (low): check if this is still required */
  5226. /* standard case if called from close_socket_gracefully */
  5227. return -2;
  5228. } else if (err == WSAETIMEDOUT) {
  5229. /* TODO (low): check if this is still required */
  5230. /* timeout is handled by the while loop */
  5231. return 0;
  5232. } else if (err == WSAECONNABORTED) {
  5233. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5234. return -2;
  5235. } else {
  5236. DEBUG_TRACE("recv() failed, error %d", err);
  5237. return -2;
  5238. }
  5239. #else
  5240. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5241. * if the timeout is reached and if the socket was set to non-
  5242. * blocking in close_socket_gracefully, so we can not distinguish
  5243. * here. We have to wait for the timeout in both cases for now.
  5244. */
  5245. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5246. /* TODO (low): check if this is still required */
  5247. /* EAGAIN/EWOULDBLOCK:
  5248. * standard case if called from close_socket_gracefully
  5249. * => should return -1 */
  5250. /* or timeout occurred
  5251. * => the code must stay in the while loop */
  5252. /* EINTR can be generated on a socket with a timeout set even
  5253. * when SA_RESTART is effective for all relevant signals
  5254. * (see signal(7)).
  5255. * => stay in the while loop */
  5256. } else {
  5257. DEBUG_TRACE("recv() failed, error %d", err);
  5258. return -2;
  5259. }
  5260. #endif
  5261. }
  5262. /* Timeout occurred, but no data available. */
  5263. return -1;
  5264. }
  5265. static int
  5266. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5267. {
  5268. int n, nread = 0;
  5269. double timeout = -1.0;
  5270. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5271. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5272. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5273. }
  5274. if (timeout >= 0.0) {
  5275. start_time = mg_get_current_time_ns();
  5276. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5277. }
  5278. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5279. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5280. if (n == -2) {
  5281. if (nread == 0) {
  5282. nread = -1; /* Propagate the error */
  5283. }
  5284. break;
  5285. } else if (n == -1) {
  5286. /* timeout */
  5287. if (timeout >= 0.0) {
  5288. now = mg_get_current_time_ns();
  5289. if ((now - start_time) <= timeout_ns) {
  5290. continue;
  5291. }
  5292. }
  5293. break;
  5294. } else if (n == 0) {
  5295. break; /* No more data to read */
  5296. } else {
  5297. conn->consumed_content += n;
  5298. nread += n;
  5299. len -= n;
  5300. }
  5301. }
  5302. return nread;
  5303. }
  5304. static void
  5305. discard_unread_request_data(struct mg_connection *conn)
  5306. {
  5307. char buf[MG_BUF_LEN];
  5308. size_t to_read;
  5309. int nread;
  5310. if (conn == NULL) {
  5311. return;
  5312. }
  5313. to_read = sizeof(buf);
  5314. if (conn->is_chunked) {
  5315. /* Chunked encoding: 3=chunk read completely
  5316. * completely */
  5317. while (conn->is_chunked != 3) {
  5318. nread = mg_read(conn, buf, to_read);
  5319. if (nread <= 0) {
  5320. break;
  5321. }
  5322. }
  5323. } else {
  5324. /* Not chunked: content length is known */
  5325. while (conn->consumed_content < conn->content_len) {
  5326. if (to_read
  5327. > (size_t)(conn->content_len - conn->consumed_content)) {
  5328. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5329. }
  5330. nread = mg_read(conn, buf, to_read);
  5331. if (nread <= 0) {
  5332. break;
  5333. }
  5334. }
  5335. }
  5336. }
  5337. static int
  5338. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5339. {
  5340. int64_t n, buffered_len, nread;
  5341. int64_t len64 =
  5342. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5343. * int, we may not read more
  5344. * bytes */
  5345. const char *body;
  5346. if (conn == NULL) {
  5347. return 0;
  5348. }
  5349. /* If Content-Length is not set for a request with body data
  5350. * (e.g., a PUT or POST request), we do not know in advance
  5351. * how much data should be read. */
  5352. if (conn->consumed_content == 0) {
  5353. if (conn->is_chunked == 1) {
  5354. conn->content_len = len64;
  5355. conn->is_chunked = 2;
  5356. } else if (conn->content_len == -1) {
  5357. /* The body data is completed when the connection
  5358. * is closed. */
  5359. conn->content_len = INT64_MAX;
  5360. conn->must_close = 1;
  5361. }
  5362. }
  5363. nread = 0;
  5364. if (conn->consumed_content < conn->content_len) {
  5365. /* Adjust number of bytes to read. */
  5366. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5367. if (left_to_read < len64) {
  5368. /* Do not read more than the total content length of the
  5369. * request.
  5370. */
  5371. len64 = left_to_read;
  5372. }
  5373. /* Return buffered data */
  5374. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5375. - conn->consumed_content;
  5376. if (buffered_len > 0) {
  5377. if (len64 < buffered_len) {
  5378. buffered_len = len64;
  5379. }
  5380. body = conn->buf + conn->request_len + conn->consumed_content;
  5381. memcpy(buf, body, (size_t)buffered_len);
  5382. len64 -= buffered_len;
  5383. conn->consumed_content += buffered_len;
  5384. nread += buffered_len;
  5385. buf = (char *)buf + buffered_len;
  5386. }
  5387. /* We have returned all buffered data. Read new data from the remote
  5388. * socket.
  5389. */
  5390. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5391. nread += n;
  5392. } else {
  5393. nread = ((nread > 0) ? nread : n);
  5394. }
  5395. }
  5396. return (int)nread;
  5397. }
  5398. static char
  5399. mg_getc(struct mg_connection *conn)
  5400. {
  5401. char c;
  5402. if (conn == NULL) {
  5403. return 0;
  5404. }
  5405. if (mg_read_inner(conn, &c, 1) <= 0) {
  5406. return (char)0;
  5407. }
  5408. return c;
  5409. }
  5410. int
  5411. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5412. {
  5413. if (len > INT_MAX) {
  5414. len = INT_MAX;
  5415. }
  5416. if (conn == NULL) {
  5417. return 0;
  5418. }
  5419. if (conn->is_chunked) {
  5420. size_t all_read = 0;
  5421. while (len > 0) {
  5422. if (conn->is_chunked == 3) {
  5423. /* No more data left to read */
  5424. return 0;
  5425. }
  5426. if (conn->chunk_remainder) {
  5427. /* copy from the remainder of the last received chunk */
  5428. long read_ret;
  5429. size_t read_now =
  5430. ((conn->chunk_remainder > len) ? (len)
  5431. : (conn->chunk_remainder));
  5432. conn->content_len += (int)read_now;
  5433. read_ret =
  5434. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5435. if (read_ret < 1) {
  5436. /* read error */
  5437. return -1;
  5438. }
  5439. all_read += (size_t)read_ret;
  5440. conn->chunk_remainder -= (size_t)read_ret;
  5441. len -= (size_t)read_ret;
  5442. if (conn->chunk_remainder == 0) {
  5443. /* Add data bytes in the current chunk have been read,
  5444. * so we are expecting \r\n now. */
  5445. char x1, x2;
  5446. conn->content_len += 2;
  5447. x1 = mg_getc(conn);
  5448. x2 = mg_getc(conn);
  5449. if ((x1 != '\r') || (x2 != '\n')) {
  5450. /* Protocol violation */
  5451. return -1;
  5452. }
  5453. }
  5454. } else {
  5455. /* fetch a new chunk */
  5456. int i = 0;
  5457. char lenbuf[64];
  5458. char *end = 0;
  5459. unsigned long chunkSize = 0;
  5460. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5461. conn->content_len++;
  5462. lenbuf[i] = mg_getc(conn);
  5463. if ((i > 0) && (lenbuf[i] == '\r')
  5464. && (lenbuf[i - 1] != '\r')) {
  5465. continue;
  5466. }
  5467. if ((i > 1) && (lenbuf[i] == '\n')
  5468. && (lenbuf[i - 1] == '\r')) {
  5469. lenbuf[i + 1] = 0;
  5470. chunkSize = strtoul(lenbuf, &end, 16);
  5471. if (chunkSize == 0) {
  5472. /* regular end of content */
  5473. conn->is_chunked = 3;
  5474. }
  5475. break;
  5476. }
  5477. if (!isxdigit(lenbuf[i])) {
  5478. /* illegal character for chunk length */
  5479. return -1;
  5480. }
  5481. }
  5482. if ((end == NULL) || (*end != '\r')) {
  5483. /* chunksize not set correctly */
  5484. return -1;
  5485. }
  5486. if (chunkSize == 0) {
  5487. break;
  5488. }
  5489. conn->chunk_remainder = chunkSize;
  5490. }
  5491. }
  5492. return (int)all_read;
  5493. }
  5494. return mg_read_inner(conn, buf, len);
  5495. }
  5496. int
  5497. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5498. {
  5499. time_t now;
  5500. int64_t n, total, allowed;
  5501. if (conn == NULL) {
  5502. return 0;
  5503. }
  5504. if (conn->throttle > 0) {
  5505. if ((now = time(NULL)) != conn->last_throttle_time) {
  5506. conn->last_throttle_time = now;
  5507. conn->last_throttle_bytes = 0;
  5508. }
  5509. allowed = conn->throttle - conn->last_throttle_bytes;
  5510. if (allowed > (int64_t)len) {
  5511. allowed = (int64_t)len;
  5512. }
  5513. if ((total = push_all(conn->phys_ctx,
  5514. NULL,
  5515. conn->client.sock,
  5516. conn->ssl,
  5517. (const char *)buf,
  5518. (int64_t)allowed)) == allowed) {
  5519. buf = (const char *)buf + total;
  5520. conn->last_throttle_bytes += total;
  5521. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5522. allowed = (conn->throttle > ((int64_t)len - total))
  5523. ? (int64_t)len - total
  5524. : conn->throttle;
  5525. if ((n = push_all(conn->phys_ctx,
  5526. NULL,
  5527. conn->client.sock,
  5528. conn->ssl,
  5529. (const char *)buf,
  5530. (int64_t)allowed)) != allowed) {
  5531. break;
  5532. }
  5533. sleep(1);
  5534. conn->last_throttle_bytes = allowed;
  5535. conn->last_throttle_time = time(NULL);
  5536. buf = (const char *)buf + n;
  5537. total += n;
  5538. }
  5539. }
  5540. } else {
  5541. total = push_all(conn->phys_ctx,
  5542. NULL,
  5543. conn->client.sock,
  5544. conn->ssl,
  5545. (const char *)buf,
  5546. (int64_t)len);
  5547. }
  5548. if (total > 0) {
  5549. conn->num_bytes_sent += total;
  5550. }
  5551. return (int)total;
  5552. }
  5553. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5554. int
  5555. mg_send_chunk(struct mg_connection *conn,
  5556. const char *chunk,
  5557. unsigned int chunk_len)
  5558. {
  5559. char lenbuf[16];
  5560. size_t lenbuf_len;
  5561. int ret;
  5562. int t;
  5563. /* First store the length information in a text buffer. */
  5564. sprintf(lenbuf, "%x\r\n", chunk_len);
  5565. lenbuf_len = strlen(lenbuf);
  5566. /* Then send length information, chunk and terminating \r\n. */
  5567. ret = mg_write(conn, lenbuf, lenbuf_len);
  5568. if (ret != (int)lenbuf_len) {
  5569. return -1;
  5570. }
  5571. t = ret;
  5572. ret = mg_write(conn, chunk, chunk_len);
  5573. if (ret != (int)chunk_len) {
  5574. return -1;
  5575. }
  5576. t += ret;
  5577. ret = mg_write(conn, "\r\n", 2);
  5578. if (ret != 2) {
  5579. return -1;
  5580. }
  5581. t += ret;
  5582. return t;
  5583. }
  5584. #if defined(__GNUC__) || defined(__MINGW32__)
  5585. /* This block forwards format strings to printf implementations,
  5586. * so we need to disable the format-nonliteral warning. */
  5587. #pragma GCC diagnostic push
  5588. #pragma GCC diagnostic ignored "-Wformat-nonliteral"
  5589. #endif
  5590. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5591. static int
  5592. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5593. {
  5594. va_list ap_copy;
  5595. size_t size = MG_BUF_LEN / 4;
  5596. int len = -1;
  5597. *buf = NULL;
  5598. while (len < 0) {
  5599. if (*buf) {
  5600. mg_free(*buf);
  5601. }
  5602. size *= 4;
  5603. *buf = (char *)mg_malloc(size);
  5604. if (!*buf) {
  5605. break;
  5606. }
  5607. va_copy(ap_copy, ap);
  5608. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5609. va_end(ap_copy);
  5610. (*buf)[size - 1] = 0;
  5611. }
  5612. return len;
  5613. }
  5614. /* Print message to buffer. If buffer is large enough to hold the message,
  5615. * return buffer. If buffer is to small, allocate large enough buffer on
  5616. * heap,
  5617. * and return allocated buffer. */
  5618. static int
  5619. alloc_vprintf(char **out_buf,
  5620. char *prealloc_buf,
  5621. size_t prealloc_size,
  5622. const char *fmt,
  5623. va_list ap)
  5624. {
  5625. va_list ap_copy;
  5626. int len;
  5627. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5628. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5629. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5630. * Therefore, we make two passes: on first pass, get required message
  5631. * length.
  5632. * On second pass, actually print the message. */
  5633. va_copy(ap_copy, ap);
  5634. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5635. va_end(ap_copy);
  5636. if (len < 0) {
  5637. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5638. * Switch to alternative code path that uses incremental
  5639. * allocations.
  5640. */
  5641. va_copy(ap_copy, ap);
  5642. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5643. va_end(ap_copy);
  5644. } else if ((size_t)(len) >= prealloc_size) {
  5645. /* The pre-allocated buffer not large enough. */
  5646. /* Allocate a new buffer. */
  5647. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5648. if (!*out_buf) {
  5649. /* Allocation failed. Return -1 as "out of memory" error. */
  5650. return -1;
  5651. }
  5652. /* Buffer allocation successful. Store the string there. */
  5653. va_copy(ap_copy, ap);
  5654. IGNORE_UNUSED_RESULT(
  5655. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5656. va_end(ap_copy);
  5657. } else {
  5658. /* The pre-allocated buffer is large enough.
  5659. * Use it to store the string and return the address. */
  5660. va_copy(ap_copy, ap);
  5661. IGNORE_UNUSED_RESULT(
  5662. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5663. va_end(ap_copy);
  5664. *out_buf = prealloc_buf;
  5665. }
  5666. return len;
  5667. }
  5668. #if defined(__GNUC__) || defined(__MINGW32__)
  5669. /* Enable format-nonliteral warning again. */
  5670. #pragma GCC diagnostic pop
  5671. #endif
  5672. static int
  5673. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5674. {
  5675. char mem[MG_BUF_LEN];
  5676. char *buf = NULL;
  5677. int len;
  5678. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5679. len = mg_write(conn, buf, (size_t)len);
  5680. }
  5681. if ((buf != mem) && (buf != NULL)) {
  5682. mg_free(buf);
  5683. }
  5684. return len;
  5685. }
  5686. int
  5687. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5688. {
  5689. va_list ap;
  5690. int result;
  5691. va_start(ap, fmt);
  5692. result = mg_vprintf(conn, fmt, ap);
  5693. va_end(ap);
  5694. return result;
  5695. }
  5696. int
  5697. mg_url_decode(const char *src,
  5698. int src_len,
  5699. char *dst,
  5700. int dst_len,
  5701. int is_form_url_encoded)
  5702. {
  5703. int i, j, a, b;
  5704. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5705. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5706. if ((i < src_len - 2) && (src[i] == '%')
  5707. && isxdigit(*(const unsigned char *)(src + i + 1))
  5708. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5709. a = tolower(*(const unsigned char *)(src + i + 1));
  5710. b = tolower(*(const unsigned char *)(src + i + 2));
  5711. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5712. i += 2;
  5713. } else if (is_form_url_encoded && (src[i] == '+')) {
  5714. dst[j] = ' ';
  5715. } else {
  5716. dst[j] = src[i];
  5717. }
  5718. }
  5719. dst[j] = '\0'; /* Null-terminate the destination */
  5720. return (i >= src_len) ? j : -1;
  5721. }
  5722. int
  5723. mg_get_var(const char *data,
  5724. size_t data_len,
  5725. const char *name,
  5726. char *dst,
  5727. size_t dst_len)
  5728. {
  5729. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5730. }
  5731. int
  5732. mg_get_var2(const char *data,
  5733. size_t data_len,
  5734. const char *name,
  5735. char *dst,
  5736. size_t dst_len,
  5737. size_t occurrence)
  5738. {
  5739. const char *p, *e, *s;
  5740. size_t name_len;
  5741. int len;
  5742. if ((dst == NULL) || (dst_len == 0)) {
  5743. len = -2;
  5744. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5745. len = -1;
  5746. dst[0] = '\0';
  5747. } else {
  5748. name_len = strlen(name);
  5749. e = data + data_len;
  5750. len = -1;
  5751. dst[0] = '\0';
  5752. /* data is "var1=val1&var2=val2...". Find variable first */
  5753. for (p = data; p + name_len < e; p++) {
  5754. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5755. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5756. /* Point p to variable value */
  5757. p += name_len + 1;
  5758. /* Point s to the end of the value */
  5759. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5760. if (s == NULL) {
  5761. s = e;
  5762. }
  5763. DEBUG_ASSERT(s >= p);
  5764. if (s < p) {
  5765. return -3;
  5766. }
  5767. /* Decode variable into destination buffer */
  5768. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5769. /* Redirect error code from -1 to -2 (destination buffer too
  5770. * small). */
  5771. if (len == -1) {
  5772. len = -2;
  5773. }
  5774. break;
  5775. }
  5776. }
  5777. }
  5778. return len;
  5779. }
  5780. /* HCP24: some changes to compare hole var_name */
  5781. int
  5782. mg_get_cookie(const char *cookie_header,
  5783. const char *var_name,
  5784. char *dst,
  5785. size_t dst_size)
  5786. {
  5787. const char *s, *p, *end;
  5788. int name_len, len = -1;
  5789. if ((dst == NULL) || (dst_size == 0)) {
  5790. return -2;
  5791. }
  5792. dst[0] = '\0';
  5793. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5794. return -1;
  5795. }
  5796. name_len = (int)strlen(var_name);
  5797. end = s + strlen(s);
  5798. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5799. if (s[name_len] == '=') {
  5800. /* HCP24: now check is it a substring or a full cookie name */
  5801. if ((s == cookie_header) || (s[-1] == ' ')) {
  5802. s += name_len + 1;
  5803. if ((p = strchr(s, ' ')) == NULL) {
  5804. p = end;
  5805. }
  5806. if (p[-1] == ';') {
  5807. p--;
  5808. }
  5809. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5810. s++;
  5811. p--;
  5812. }
  5813. if ((size_t)(p - s) < dst_size) {
  5814. len = (int)(p - s);
  5815. mg_strlcpy(dst, s, (size_t)len + 1);
  5816. } else {
  5817. len = -3;
  5818. }
  5819. break;
  5820. }
  5821. }
  5822. }
  5823. return len;
  5824. }
  5825. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5826. static void
  5827. base64_encode(const unsigned char *src, int src_len, char *dst)
  5828. {
  5829. static const char *b64 =
  5830. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5831. int i, j, a, b, c;
  5832. for (i = j = 0; i < src_len; i += 3) {
  5833. a = src[i];
  5834. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5835. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5836. dst[j++] = b64[a >> 2];
  5837. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5838. if (i + 1 < src_len) {
  5839. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5840. }
  5841. if (i + 2 < src_len) {
  5842. dst[j++] = b64[c & 63];
  5843. }
  5844. }
  5845. while (j % 4 != 0) {
  5846. dst[j++] = '=';
  5847. }
  5848. dst[j++] = '\0';
  5849. }
  5850. #endif
  5851. #if defined(USE_LUA)
  5852. static unsigned char
  5853. b64reverse(char letter)
  5854. {
  5855. if ((letter >= 'A') && (letter <= 'Z')) {
  5856. return letter - 'A';
  5857. }
  5858. if ((letter >= 'a') && (letter <= 'z')) {
  5859. return letter - 'a' + 26;
  5860. }
  5861. if ((letter >= '0') && (letter <= '9')) {
  5862. return letter - '0' + 52;
  5863. }
  5864. if (letter == '+') {
  5865. return 62;
  5866. }
  5867. if (letter == '/') {
  5868. return 63;
  5869. }
  5870. if (letter == '=') {
  5871. return 255; /* normal end */
  5872. }
  5873. return 254; /* error */
  5874. }
  5875. static int
  5876. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5877. {
  5878. int i;
  5879. unsigned char a, b, c, d;
  5880. *dst_len = 0;
  5881. for (i = 0; i < src_len; i += 4) {
  5882. a = b64reverse(src[i]);
  5883. if (a >= 254) {
  5884. return i;
  5885. }
  5886. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5887. if (b >= 254) {
  5888. return i + 1;
  5889. }
  5890. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5891. if (c == 254) {
  5892. return i + 2;
  5893. }
  5894. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5895. if (d == 254) {
  5896. return i + 3;
  5897. }
  5898. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5899. if (c != 255) {
  5900. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5901. if (d != 255) {
  5902. dst[(*dst_len)++] = (c << 6) + d;
  5903. }
  5904. }
  5905. }
  5906. return -1;
  5907. }
  5908. #endif
  5909. static int
  5910. is_put_or_delete_method(const struct mg_connection *conn)
  5911. {
  5912. if (conn) {
  5913. const char *s = conn->request_info.request_method;
  5914. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5915. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5916. }
  5917. return 0;
  5918. }
  5919. #if !defined(NO_FILES)
  5920. static int
  5921. extention_matches_script(
  5922. struct mg_connection *conn, /* in: request (must be valid) */
  5923. const char *filename /* in: filename (must be valid) */
  5924. )
  5925. {
  5926. #if !defined(NO_CGI)
  5927. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  5928. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  5929. filename) > 0) {
  5930. return 1;
  5931. }
  5932. #endif
  5933. #if defined(USE_LUA)
  5934. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  5935. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5936. filename) > 0) {
  5937. return 1;
  5938. }
  5939. #endif
  5940. #if defined(USE_DUKTAPE)
  5941. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5942. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5943. filename) > 0) {
  5944. return 1;
  5945. }
  5946. #endif
  5947. /* filename and conn could be unused, if all preocessor conditions
  5948. * are false (no script language supported). */
  5949. (void)filename;
  5950. (void)conn;
  5951. return 0;
  5952. }
  5953. /* For given directory path, substitute it to valid index file.
  5954. * Return 1 if index file has been found, 0 if not found.
  5955. * If the file is found, it's stats is returned in stp. */
  5956. static int
  5957. substitute_index_file(struct mg_connection *conn,
  5958. char *path,
  5959. size_t path_len,
  5960. struct mg_file_stat *filestat)
  5961. {
  5962. const char *list = conn->dom_ctx->config[INDEX_FILES];
  5963. struct vec filename_vec;
  5964. size_t n = strlen(path);
  5965. int found = 0;
  5966. /* The 'path' given to us points to the directory. Remove all trailing
  5967. * directory separator characters from the end of the path, and
  5968. * then append single directory separator character. */
  5969. while ((n > 0) && (path[n - 1] == '/')) {
  5970. n--;
  5971. }
  5972. path[n] = '/';
  5973. /* Traverse index files list. For each entry, append it to the given
  5974. * path and see if the file exists. If it exists, break the loop */
  5975. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5976. /* Ignore too long entries that may overflow path buffer */
  5977. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  5978. continue;
  5979. }
  5980. /* Prepare full path to the index file */
  5981. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5982. /* Does it exist? */
  5983. if (mg_stat(conn, path, filestat)) {
  5984. /* Yes it does, break the loop */
  5985. found = 1;
  5986. break;
  5987. }
  5988. }
  5989. /* If no index file exists, restore directory path */
  5990. if (!found) {
  5991. path[n] = '\0';
  5992. }
  5993. return found;
  5994. }
  5995. #endif
  5996. static void
  5997. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  5998. char *filename, /* out: filename */
  5999. size_t filename_buf_len, /* in: size of filename buffer */
  6000. struct mg_file_stat *filestat, /* out: file status structure */
  6001. int *is_found, /* out: file found (directly) */
  6002. int *is_script_resource, /* out: handled by a script? */
  6003. int *is_websocket_request, /* out: websocket connetion? */
  6004. int *is_put_or_delete_request /* out: put/delete a file? */
  6005. )
  6006. {
  6007. char const *accept_encoding;
  6008. #if !defined(NO_FILES)
  6009. const char *uri = conn->request_info.local_uri;
  6010. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  6011. const char *rewrite;
  6012. struct vec a, b;
  6013. ptrdiff_t match_len;
  6014. char gz_path[PATH_MAX];
  6015. int truncated;
  6016. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6017. char *tmp_str;
  6018. size_t tmp_str_len, sep_pos;
  6019. int allow_substitute_script_subresources;
  6020. #endif
  6021. #else
  6022. (void)filename_buf_len; /* unused if NO_FILES is defined */
  6023. #endif
  6024. /* Step 1: Set all initially unknown outputs to zero */
  6025. memset(filestat, 0, sizeof(*filestat));
  6026. *filename = 0;
  6027. *is_found = 0;
  6028. *is_script_resource = 0;
  6029. /* Step 2: Check if the request attempts to modify the file system */
  6030. *is_put_or_delete_request = is_put_or_delete_method(conn);
  6031. /* Step 3: Check if it is a websocket request, and modify the document
  6032. * root if required */
  6033. #if defined(USE_WEBSOCKET)
  6034. *is_websocket_request = is_websocket_protocol(conn);
  6035. #if !defined(NO_FILES)
  6036. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  6037. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  6038. }
  6039. #endif /* !NO_FILES */
  6040. #else /* USE_WEBSOCKET */
  6041. *is_websocket_request = 0;
  6042. #endif /* USE_WEBSOCKET */
  6043. /* Step 4: Check if gzip encoded response is allowed */
  6044. conn->accept_gzip = 0;
  6045. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  6046. if (strstr(accept_encoding, "gzip") != NULL) {
  6047. conn->accept_gzip = 1;
  6048. }
  6049. }
  6050. #if !defined(NO_FILES)
  6051. /* Step 5: If there is no root directory, don't look for files. */
  6052. /* Note that root == NULL is a regular use case here. This occurs,
  6053. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  6054. * config is not required. */
  6055. if (root == NULL) {
  6056. /* all file related outputs have already been set to 0, just return
  6057. */
  6058. return;
  6059. }
  6060. /* Step 6: Determine the local file path from the root path and the
  6061. * request uri. */
  6062. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  6063. * part of the path one byte on the right. */
  6064. mg_snprintf(
  6065. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  6066. if (truncated) {
  6067. goto interpret_cleanup;
  6068. }
  6069. /* Step 7: URI rewriting */
  6070. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  6071. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  6072. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  6073. mg_snprintf(conn,
  6074. &truncated,
  6075. filename,
  6076. filename_buf_len - 1,
  6077. "%.*s%s",
  6078. (int)b.len,
  6079. b.ptr,
  6080. uri + match_len);
  6081. break;
  6082. }
  6083. }
  6084. if (truncated) {
  6085. goto interpret_cleanup;
  6086. }
  6087. /* Step 8: Check if the file exists at the server */
  6088. /* Local file path and name, corresponding to requested URI
  6089. * is now stored in "filename" variable. */
  6090. if (mg_stat(conn, filename, filestat)) {
  6091. int uri_len = (int)strlen(uri);
  6092. int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/');
  6093. /* 8.1: File exists. */
  6094. *is_found = 1;
  6095. /* 8.2: Check if it is a script type. */
  6096. if (extention_matches_script(conn, filename)) {
  6097. /* The request addresses a CGI resource, Lua script or
  6098. * server-side javascript.
  6099. * The URI corresponds to the script itself (like
  6100. * /path/script.cgi), and there is no additional resource
  6101. * path (like /path/script.cgi/something).
  6102. * Requests that modify (replace or delete) a resource, like
  6103. * PUT and DELETE requests, should replace/delete the script
  6104. * file.
  6105. * Requests that read or write from/to a resource, like GET and
  6106. * POST requests, should call the script and return the
  6107. * generated response. */
  6108. *is_script_resource = (!*is_put_or_delete_request);
  6109. }
  6110. /* 8.3: If the request target is a directory, there could be
  6111. * a substitute file (index.html, index.cgi, ...). */
  6112. if (filestat->is_directory && is_uri_end_slash) {
  6113. /* Use a local copy here, since substitute_index_file will
  6114. * change the content of the file status */
  6115. struct mg_file_stat tmp_filestat;
  6116. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  6117. if (substitute_index_file(
  6118. conn, filename, filename_buf_len, &tmp_filestat)) {
  6119. /* Substitute file found. Copy stat to the output, then
  6120. * check if the file is a script file */
  6121. *filestat = tmp_filestat;
  6122. if (extention_matches_script(conn, filename)) {
  6123. /* Substitute file is a script file */
  6124. *is_script_resource = 1;
  6125. } else {
  6126. /* Substitute file is a regular file */
  6127. *is_script_resource = 0;
  6128. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  6129. }
  6130. }
  6131. /* If there is no substitute file, the server could return
  6132. * a directory listing in a later step */
  6133. }
  6134. return;
  6135. }
  6136. /* Step 9: Check for zipped files: */
  6137. /* If we can't find the actual file, look for the file
  6138. * with the same name but a .gz extension. If we find it,
  6139. * use that and set the gzipped flag in the file struct
  6140. * to indicate that the response need to have the content-
  6141. * encoding: gzip header.
  6142. * We can only do this if the browser declares support. */
  6143. if (conn->accept_gzip) {
  6144. mg_snprintf(
  6145. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  6146. if (truncated) {
  6147. goto interpret_cleanup;
  6148. }
  6149. if (mg_stat(conn, gz_path, filestat)) {
  6150. if (filestat) {
  6151. filestat->is_gzipped = 1;
  6152. *is_found = 1;
  6153. }
  6154. /* Currently gz files can not be scripts. */
  6155. return;
  6156. }
  6157. }
  6158. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  6159. /* Step 10: Script resources may handle sub-resources */
  6160. /* Support PATH_INFO for CGI scripts. */
  6161. tmp_str_len = strlen(filename);
  6162. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  6163. if (!tmp_str) {
  6164. /* Out of memory */
  6165. goto interpret_cleanup;
  6166. }
  6167. memcpy(tmp_str, filename, tmp_str_len + 1);
  6168. /* Check config, if index scripts may have sub-resources */
  6169. allow_substitute_script_subresources =
  6170. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  6171. "yes");
  6172. sep_pos = tmp_str_len;
  6173. while (sep_pos > 0) {
  6174. sep_pos--;
  6175. if (tmp_str[sep_pos] == '/') {
  6176. int is_script = 0, does_exist = 0;
  6177. tmp_str[sep_pos] = 0;
  6178. if (tmp_str[0]) {
  6179. is_script = extention_matches_script(conn, tmp_str);
  6180. does_exist = mg_stat(conn, tmp_str, filestat);
  6181. }
  6182. if (does_exist && is_script) {
  6183. filename[sep_pos] = 0;
  6184. memmove(filename + sep_pos + 2,
  6185. filename + sep_pos + 1,
  6186. strlen(filename + sep_pos + 1) + 1);
  6187. conn->path_info = filename + sep_pos + 1;
  6188. filename[sep_pos + 1] = '/';
  6189. *is_script_resource = 1;
  6190. *is_found = 1;
  6191. break;
  6192. }
  6193. if (allow_substitute_script_subresources) {
  6194. if (substitute_index_file(
  6195. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  6196. /* some intermediate directory has an index file */
  6197. if (extention_matches_script(conn, tmp_str)) {
  6198. char *tmp_str2;
  6199. DEBUG_TRACE("Substitute script %s serving path %s",
  6200. tmp_str,
  6201. filename);
  6202. /* this index file is a script */
  6203. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  6204. conn->phys_ctx);
  6205. mg_snprintf(conn,
  6206. &truncated,
  6207. filename,
  6208. filename_buf_len,
  6209. "%s//%s",
  6210. tmp_str,
  6211. tmp_str2);
  6212. mg_free(tmp_str2);
  6213. if (truncated) {
  6214. mg_free(tmp_str);
  6215. goto interpret_cleanup;
  6216. }
  6217. sep_pos = strlen(tmp_str);
  6218. filename[sep_pos] = 0;
  6219. conn->path_info = filename + sep_pos + 1;
  6220. *is_script_resource = 1;
  6221. *is_found = 1;
  6222. break;
  6223. } else {
  6224. DEBUG_TRACE("Substitute file %s serving path %s",
  6225. tmp_str,
  6226. filename);
  6227. /* non-script files will not have sub-resources */
  6228. filename[sep_pos] = 0;
  6229. conn->path_info = 0;
  6230. *is_script_resource = 0;
  6231. *is_found = 0;
  6232. break;
  6233. }
  6234. }
  6235. }
  6236. tmp_str[sep_pos] = '/';
  6237. }
  6238. }
  6239. mg_free(tmp_str);
  6240. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6241. #endif /* !defined(NO_FILES) */
  6242. return;
  6243. #if !defined(NO_FILES)
  6244. /* Reset all outputs */
  6245. interpret_cleanup:
  6246. memset(filestat, 0, sizeof(*filestat));
  6247. *filename = 0;
  6248. *is_found = 0;
  6249. *is_script_resource = 0;
  6250. *is_websocket_request = 0;
  6251. *is_put_or_delete_request = 0;
  6252. #endif /* !defined(NO_FILES) */
  6253. }
  6254. /* Check whether full request is buffered. Return:
  6255. * -1 if request or response is malformed
  6256. * 0 if request or response is not yet fully buffered
  6257. * >0 actual request length, including last \r\n\r\n */
  6258. static int
  6259. get_http_header_len(const char *buf, int buflen)
  6260. {
  6261. int i;
  6262. for (i = 0; i < buflen; i++) {
  6263. /* Do an unsigned comparison in some conditions below */
  6264. const unsigned char c = ((const unsigned char *)buf)[i];
  6265. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6266. && !isprint(c)) {
  6267. /* abort scan as soon as one malformed character is found */
  6268. return -1;
  6269. }
  6270. if (i < buflen - 1) {
  6271. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6272. /* Two newline, no carriage return - not standard compliant,
  6273. * but
  6274. * it
  6275. * should be accepted */
  6276. return i + 2;
  6277. }
  6278. }
  6279. if (i < buflen - 3) {
  6280. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6281. && (buf[i + 3] == '\n')) {
  6282. /* Two \r\n - standard compliant */
  6283. return i + 4;
  6284. }
  6285. }
  6286. }
  6287. return 0;
  6288. }
  6289. #if !defined(NO_CACHING)
  6290. /* Convert month to the month number. Return -1 on error, or month number */
  6291. static int
  6292. get_month_index(const char *s)
  6293. {
  6294. size_t i;
  6295. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6296. if (!strcmp(s, month_names[i])) {
  6297. return (int)i;
  6298. }
  6299. }
  6300. return -1;
  6301. }
  6302. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6303. static time_t
  6304. parse_date_string(const char *datetime)
  6305. {
  6306. char month_str[32] = {0};
  6307. int second, minute, hour, day, month, year;
  6308. time_t result = (time_t)0;
  6309. struct tm tm;
  6310. if ((sscanf(datetime,
  6311. "%d/%3s/%d %d:%d:%d",
  6312. &day,
  6313. month_str,
  6314. &year,
  6315. &hour,
  6316. &minute,
  6317. &second) == 6) || (sscanf(datetime,
  6318. "%d %3s %d %d:%d:%d",
  6319. &day,
  6320. month_str,
  6321. &year,
  6322. &hour,
  6323. &minute,
  6324. &second) == 6)
  6325. || (sscanf(datetime,
  6326. "%*3s, %d %3s %d %d:%d:%d",
  6327. &day,
  6328. month_str,
  6329. &year,
  6330. &hour,
  6331. &minute,
  6332. &second) == 6) || (sscanf(datetime,
  6333. "%d-%3s-%d %d:%d:%d",
  6334. &day,
  6335. month_str,
  6336. &year,
  6337. &hour,
  6338. &minute,
  6339. &second) == 6)) {
  6340. month = get_month_index(month_str);
  6341. if ((month >= 0) && (year >= 1970)) {
  6342. memset(&tm, 0, sizeof(tm));
  6343. tm.tm_year = year - 1900;
  6344. tm.tm_mon = month;
  6345. tm.tm_mday = day;
  6346. tm.tm_hour = hour;
  6347. tm.tm_min = minute;
  6348. tm.tm_sec = second;
  6349. result = timegm(&tm);
  6350. }
  6351. }
  6352. return result;
  6353. }
  6354. #endif /* !NO_CACHING */
  6355. /* Protect against directory disclosure attack by removing '..',
  6356. * excessive '/' and '\' characters */
  6357. static void
  6358. remove_double_dots_and_double_slashes(char *s)
  6359. {
  6360. char *p = s;
  6361. while ((s[0] == '.') && (s[1] == '.')) {
  6362. s++;
  6363. }
  6364. while (*s != '\0') {
  6365. *p++ = *s++;
  6366. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6367. /* Skip all following slashes, backslashes and double-dots */
  6368. while (s[0] != '\0') {
  6369. if ((s[0] == '/') || (s[0] == '\\')) {
  6370. s++;
  6371. } else if ((s[0] == '.') && (s[1] == '.')) {
  6372. s += 2;
  6373. } else {
  6374. break;
  6375. }
  6376. }
  6377. }
  6378. }
  6379. *p = '\0';
  6380. }
  6381. static const struct {
  6382. const char *extension;
  6383. size_t ext_len;
  6384. const char *mime_type;
  6385. } builtin_mime_types[] = {
  6386. /* IANA registered MIME types
  6387. * (http://www.iana.org/assignments/media-types)
  6388. * application types */
  6389. {".doc", 4, "application/msword"},
  6390. {".eps", 4, "application/postscript"},
  6391. {".exe", 4, "application/octet-stream"},
  6392. {".js", 3, "application/javascript"},
  6393. {".json", 5, "application/json"},
  6394. {".pdf", 4, "application/pdf"},
  6395. {".ps", 3, "application/postscript"},
  6396. {".rtf", 4, "application/rtf"},
  6397. {".xhtml", 6, "application/xhtml+xml"},
  6398. {".xsl", 4, "application/xml"},
  6399. {".xslt", 5, "application/xml"},
  6400. /* fonts */
  6401. {".ttf", 4, "application/font-sfnt"},
  6402. {".cff", 4, "application/font-sfnt"},
  6403. {".otf", 4, "application/font-sfnt"},
  6404. {".aat", 4, "application/font-sfnt"},
  6405. {".sil", 4, "application/font-sfnt"},
  6406. {".pfr", 4, "application/font-tdpfr"},
  6407. {".woff", 5, "application/font-woff"},
  6408. /* audio */
  6409. {".mp3", 4, "audio/mpeg"},
  6410. {".oga", 4, "audio/ogg"},
  6411. {".ogg", 4, "audio/ogg"},
  6412. /* image */
  6413. {".gif", 4, "image/gif"},
  6414. {".ief", 4, "image/ief"},
  6415. {".jpeg", 5, "image/jpeg"},
  6416. {".jpg", 4, "image/jpeg"},
  6417. {".jpm", 4, "image/jpm"},
  6418. {".jpx", 4, "image/jpx"},
  6419. {".png", 4, "image/png"},
  6420. {".svg", 4, "image/svg+xml"},
  6421. {".tif", 4, "image/tiff"},
  6422. {".tiff", 5, "image/tiff"},
  6423. /* model */
  6424. {".wrl", 4, "model/vrml"},
  6425. /* text */
  6426. {".css", 4, "text/css"},
  6427. {".csv", 4, "text/csv"},
  6428. {".htm", 4, "text/html"},
  6429. {".html", 5, "text/html"},
  6430. {".sgm", 4, "text/sgml"},
  6431. {".shtm", 5, "text/html"},
  6432. {".shtml", 6, "text/html"},
  6433. {".txt", 4, "text/plain"},
  6434. {".xml", 4, "text/xml"},
  6435. /* video */
  6436. {".mov", 4, "video/quicktime"},
  6437. {".mp4", 4, "video/mp4"},
  6438. {".mpeg", 5, "video/mpeg"},
  6439. {".mpg", 4, "video/mpeg"},
  6440. {".ogv", 4, "video/ogg"},
  6441. {".qt", 3, "video/quicktime"},
  6442. /* not registered types
  6443. * (http://reference.sitepoint.com/html/mime-types-full,
  6444. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6445. {".arj", 4, "application/x-arj-compressed"},
  6446. {".gz", 3, "application/x-gunzip"},
  6447. {".rar", 4, "application/x-arj-compressed"},
  6448. {".swf", 4, "application/x-shockwave-flash"},
  6449. {".tar", 4, "application/x-tar"},
  6450. {".tgz", 4, "application/x-tar-gz"},
  6451. {".torrent", 8, "application/x-bittorrent"},
  6452. {".ppt", 4, "application/x-mspowerpoint"},
  6453. {".xls", 4, "application/x-msexcel"},
  6454. {".zip", 4, "application/x-zip-compressed"},
  6455. {".aac",
  6456. 4,
  6457. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6458. {".aif", 4, "audio/x-aif"},
  6459. {".m3u", 4, "audio/x-mpegurl"},
  6460. {".mid", 4, "audio/x-midi"},
  6461. {".ra", 3, "audio/x-pn-realaudio"},
  6462. {".ram", 4, "audio/x-pn-realaudio"},
  6463. {".wav", 4, "audio/x-wav"},
  6464. {".bmp", 4, "image/bmp"},
  6465. {".ico", 4, "image/x-icon"},
  6466. {".pct", 4, "image/x-pct"},
  6467. {".pict", 5, "image/pict"},
  6468. {".rgb", 4, "image/x-rgb"},
  6469. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6470. {".asf", 4, "video/x-ms-asf"},
  6471. {".avi", 4, "video/x-msvideo"},
  6472. {".m4v", 4, "video/x-m4v"},
  6473. {NULL, 0, NULL}};
  6474. const char *
  6475. mg_get_builtin_mime_type(const char *path)
  6476. {
  6477. const char *ext;
  6478. size_t i, path_len;
  6479. path_len = strlen(path);
  6480. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6481. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6482. if ((path_len > builtin_mime_types[i].ext_len)
  6483. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6484. return builtin_mime_types[i].mime_type;
  6485. }
  6486. }
  6487. return "text/plain";
  6488. }
  6489. /* Look at the "path" extension and figure what mime type it has.
  6490. * Store mime type in the vector. */
  6491. static void
  6492. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6493. {
  6494. struct vec ext_vec, mime_vec;
  6495. const char *list, *ext;
  6496. size_t path_len;
  6497. path_len = strlen(path);
  6498. if ((conn == NULL) || (vec == NULL)) {
  6499. if (vec != NULL) {
  6500. memset(vec, '\0', sizeof(struct vec));
  6501. }
  6502. return;
  6503. }
  6504. /* Scan user-defined mime types first, in case user wants to
  6505. * override default mime types. */
  6506. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6507. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6508. /* ext now points to the path suffix */
  6509. ext = path + path_len - ext_vec.len;
  6510. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6511. *vec = mime_vec;
  6512. return;
  6513. }
  6514. }
  6515. vec->ptr = mg_get_builtin_mime_type(path);
  6516. vec->len = strlen(vec->ptr);
  6517. }
  6518. /* Stringify binary data. Output buffer must be twice as big as input,
  6519. * because each byte takes 2 bytes in string representation */
  6520. static void
  6521. bin2str(char *to, const unsigned char *p, size_t len)
  6522. {
  6523. static const char *hex = "0123456789abcdef";
  6524. for (; len--; p++) {
  6525. *to++ = hex[p[0] >> 4];
  6526. *to++ = hex[p[0] & 0x0f];
  6527. }
  6528. *to = '\0';
  6529. }
  6530. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6531. */
  6532. char *
  6533. mg_md5(char buf[33], ...)
  6534. {
  6535. md5_byte_t hash[16];
  6536. const char *p;
  6537. va_list ap;
  6538. md5_state_t ctx;
  6539. md5_init(&ctx);
  6540. va_start(ap, buf);
  6541. while ((p = va_arg(ap, const char *)) != NULL) {
  6542. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6543. }
  6544. va_end(ap);
  6545. md5_finish(&ctx, hash);
  6546. bin2str(buf, hash, sizeof(hash));
  6547. return buf;
  6548. }
  6549. /* Check the user's password, return 1 if OK */
  6550. static int
  6551. check_password(const char *method,
  6552. const char *ha1,
  6553. const char *uri,
  6554. const char *nonce,
  6555. const char *nc,
  6556. const char *cnonce,
  6557. const char *qop,
  6558. const char *response)
  6559. {
  6560. char ha2[32 + 1], expected_response[32 + 1];
  6561. /* Some of the parameters may be NULL */
  6562. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6563. || (qop == NULL) || (response == NULL)) {
  6564. return 0;
  6565. }
  6566. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6567. if (strlen(response) != 32) {
  6568. return 0;
  6569. }
  6570. mg_md5(ha2, method, ":", uri, NULL);
  6571. mg_md5(expected_response,
  6572. ha1,
  6573. ":",
  6574. nonce,
  6575. ":",
  6576. nc,
  6577. ":",
  6578. cnonce,
  6579. ":",
  6580. qop,
  6581. ":",
  6582. ha2,
  6583. NULL);
  6584. return mg_strcasecmp(response, expected_response) == 0;
  6585. }
  6586. /* Use the global passwords file, if specified by auth_gpass option,
  6587. * or search for .htpasswd in the requested directory. */
  6588. static void
  6589. open_auth_file(struct mg_connection *conn,
  6590. const char *path,
  6591. struct mg_file *filep)
  6592. {
  6593. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6594. char name[PATH_MAX];
  6595. const char *p, *e,
  6596. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6597. int truncated;
  6598. if (gpass != NULL) {
  6599. /* Use global passwords file */
  6600. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6601. #if defined(DEBUG)
  6602. /* Use mg_cry_internal here, since gpass has been configured. */
  6603. mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6604. #endif
  6605. }
  6606. /* Important: using local struct mg_file to test path for
  6607. * is_directory flag. If filep is used, mg_stat() makes it
  6608. * appear as if auth file was opened.
  6609. * TODO(mid): Check if this is still required after rewriting
  6610. * mg_stat */
  6611. } else if (mg_stat(conn, path, &filep->stat)
  6612. && filep->stat.is_directory) {
  6613. mg_snprintf(conn,
  6614. &truncated,
  6615. name,
  6616. sizeof(name),
  6617. "%s/%s",
  6618. path,
  6619. PASSWORDS_FILE_NAME);
  6620. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6621. #if defined(DEBUG)
  6622. /* Don't use mg_cry_internal here, but only a trace, since this
  6623. * is
  6624. * a typical case. It will occur for every directory
  6625. * without a password file. */
  6626. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6627. #endif
  6628. }
  6629. } else {
  6630. /* Try to find .htpasswd in requested directory. */
  6631. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6632. if (e[0] == '/') {
  6633. break;
  6634. }
  6635. }
  6636. mg_snprintf(conn,
  6637. &truncated,
  6638. name,
  6639. sizeof(name),
  6640. "%.*s/%s",
  6641. (int)(e - p),
  6642. p,
  6643. PASSWORDS_FILE_NAME);
  6644. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6645. #if defined(DEBUG)
  6646. /* Don't use mg_cry_internal here, but only a trace, since this
  6647. * is
  6648. * a typical case. It will occur for every directory
  6649. * without a password file. */
  6650. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6651. #endif
  6652. }
  6653. }
  6654. }
  6655. }
  6656. /* Parsed Authorization header */
  6657. struct ah {
  6658. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6659. };
  6660. /* Return 1 on success. Always initializes the ah structure. */
  6661. static int
  6662. parse_auth_header(struct mg_connection *conn,
  6663. char *buf,
  6664. size_t buf_size,
  6665. struct ah *ah)
  6666. {
  6667. char *name, *value, *s;
  6668. const char *auth_header;
  6669. uint64_t nonce;
  6670. if (!ah || !conn) {
  6671. return 0;
  6672. }
  6673. (void)memset(ah, 0, sizeof(*ah));
  6674. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6675. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6676. return 0;
  6677. }
  6678. /* Make modifiable copy of the auth header */
  6679. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6680. s = buf;
  6681. /* Parse authorization header */
  6682. for (;;) {
  6683. /* Gobble initial spaces */
  6684. while (isspace(*(unsigned char *)s)) {
  6685. s++;
  6686. }
  6687. name = skip_quoted(&s, "=", " ", 0);
  6688. /* Value is either quote-delimited, or ends at first comma or space.
  6689. */
  6690. if (s[0] == '\"') {
  6691. s++;
  6692. value = skip_quoted(&s, "\"", " ", '\\');
  6693. if (s[0] == ',') {
  6694. s++;
  6695. }
  6696. } else {
  6697. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6698. * spaces */
  6699. }
  6700. if (*name == '\0') {
  6701. break;
  6702. }
  6703. if (!strcmp(name, "username")) {
  6704. ah->user = value;
  6705. } else if (!strcmp(name, "cnonce")) {
  6706. ah->cnonce = value;
  6707. } else if (!strcmp(name, "response")) {
  6708. ah->response = value;
  6709. } else if (!strcmp(name, "uri")) {
  6710. ah->uri = value;
  6711. } else if (!strcmp(name, "qop")) {
  6712. ah->qop = value;
  6713. } else if (!strcmp(name, "nc")) {
  6714. ah->nc = value;
  6715. } else if (!strcmp(name, "nonce")) {
  6716. ah->nonce = value;
  6717. }
  6718. }
  6719. #if !defined(NO_NONCE_CHECK)
  6720. /* Read the nonce from the response. */
  6721. if (ah->nonce == NULL) {
  6722. return 0;
  6723. }
  6724. s = NULL;
  6725. nonce = strtoull(ah->nonce, &s, 10);
  6726. if ((s == NULL) || (*s != 0)) {
  6727. return 0;
  6728. }
  6729. /* Convert the nonce from the client to a number. */
  6730. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6731. /* The converted number corresponds to the time the nounce has been
  6732. * created. This should not be earlier than the server start. */
  6733. /* Server side nonce check is valuable in all situations but one:
  6734. * if the server restarts frequently, but the client should not see
  6735. * that, so the server should accept nonces from previous starts. */
  6736. /* However, the reasonable default is to not accept a nonce from a
  6737. * previous start, so if anyone changed the access rights between
  6738. * two restarts, a new login is required. */
  6739. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6740. /* nonce is from a previous start of the server and no longer valid
  6741. * (replay attack?) */
  6742. return 0;
  6743. }
  6744. /* Check if the nonce is too high, so it has not (yet) been used by the
  6745. * server. */
  6746. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6747. + conn->dom_ctx->nonce_count)) {
  6748. return 0;
  6749. }
  6750. #else
  6751. (void)nonce;
  6752. #endif
  6753. /* CGI needs it as REMOTE_USER */
  6754. if (ah->user != NULL) {
  6755. conn->request_info.remote_user =
  6756. mg_strdup_ctx(ah->user, conn->phys_ctx);
  6757. } else {
  6758. return 0;
  6759. }
  6760. return 1;
  6761. }
  6762. static const char *
  6763. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6764. {
  6765. #if defined(MG_USE_OPEN_FILE)
  6766. const char *eof;
  6767. size_t len;
  6768. const char *memend;
  6769. #else
  6770. (void)p; /* parameter is unused */
  6771. #endif
  6772. if (!filep) {
  6773. return NULL;
  6774. }
  6775. #if defined(MG_USE_OPEN_FILE)
  6776. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6777. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6778. /* Search for \n from p till the end of stream */
  6779. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6780. if (eof != NULL) {
  6781. eof += 1; /* Include \n */
  6782. } else {
  6783. eof = memend; /* Copy remaining data */
  6784. }
  6785. len =
  6786. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6787. memcpy(buf, *p, len);
  6788. buf[len] = '\0';
  6789. *p += len;
  6790. return len ? eof : NULL;
  6791. } else /* filep->access.fp block below */
  6792. #endif
  6793. if (filep->access.fp != NULL) {
  6794. return fgets(buf, (int)size, filep->access.fp);
  6795. } else {
  6796. return NULL;
  6797. }
  6798. }
  6799. /* Define the initial recursion depth for procesesing htpasswd files that
  6800. * include other htpasswd
  6801. * (or even the same) files. It is not difficult to provide a file or files
  6802. * s.t. they force civetweb
  6803. * to infinitely recurse and then crash.
  6804. */
  6805. #define INITIAL_DEPTH 9
  6806. #if INITIAL_DEPTH <= 0
  6807. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6808. #endif
  6809. struct read_auth_file_struct {
  6810. struct mg_connection *conn;
  6811. struct ah ah;
  6812. const char *domain;
  6813. char buf[256 + 256 + 40];
  6814. const char *f_user;
  6815. const char *f_domain;
  6816. const char *f_ha1;
  6817. };
  6818. static int
  6819. read_auth_file(struct mg_file *filep,
  6820. struct read_auth_file_struct *workdata,
  6821. int depth)
  6822. {
  6823. char *p = NULL /* init if MG_USE_OPEN_FILE is not set */;
  6824. int is_authorized = 0;
  6825. struct mg_file fp;
  6826. size_t l;
  6827. if (!filep || !workdata || (0 == depth)) {
  6828. return 0;
  6829. }
  6830. /* Loop over passwords file */
  6831. #if defined(MG_USE_OPEN_FILE)
  6832. p = (char *)filep->access.membuf;
  6833. #endif
  6834. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6835. l = strlen(workdata->buf);
  6836. while (l > 0) {
  6837. if (isspace(workdata->buf[l - 1])
  6838. || iscntrl(workdata->buf[l - 1])) {
  6839. l--;
  6840. workdata->buf[l] = 0;
  6841. } else
  6842. break;
  6843. }
  6844. if (l < 1) {
  6845. continue;
  6846. }
  6847. workdata->f_user = workdata->buf;
  6848. if (workdata->f_user[0] == ':') {
  6849. /* user names may not contain a ':' and may not be empty,
  6850. * so lines starting with ':' may be used for a special purpose
  6851. */
  6852. if (workdata->f_user[1] == '#') {
  6853. /* :# is a comment */
  6854. continue;
  6855. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6856. if (mg_fopen(workdata->conn,
  6857. workdata->f_user + 9,
  6858. MG_FOPEN_MODE_READ,
  6859. &fp)) {
  6860. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6861. (void)mg_fclose(
  6862. &fp.access); /* ignore error on read only file */
  6863. /* No need to continue processing files once we have a
  6864. * match, since nothing will reset it back
  6865. * to 0.
  6866. */
  6867. if (is_authorized) {
  6868. return is_authorized;
  6869. }
  6870. } else {
  6871. mg_cry_internal(workdata->conn,
  6872. "%s: cannot open authorization file: %s",
  6873. __func__,
  6874. workdata->buf);
  6875. }
  6876. continue;
  6877. }
  6878. /* everything is invalid for the moment (might change in the
  6879. * future) */
  6880. mg_cry_internal(workdata->conn,
  6881. "%s: syntax error in authorization file: %s",
  6882. __func__,
  6883. workdata->buf);
  6884. continue;
  6885. }
  6886. workdata->f_domain = strchr(workdata->f_user, ':');
  6887. if (workdata->f_domain == NULL) {
  6888. mg_cry_internal(workdata->conn,
  6889. "%s: syntax error in authorization file: %s",
  6890. __func__,
  6891. workdata->buf);
  6892. continue;
  6893. }
  6894. *(char *)(workdata->f_domain) = 0;
  6895. (workdata->f_domain)++;
  6896. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6897. if (workdata->f_ha1 == NULL) {
  6898. mg_cry_internal(workdata->conn,
  6899. "%s: syntax error in authorization file: %s",
  6900. __func__,
  6901. workdata->buf);
  6902. continue;
  6903. }
  6904. *(char *)(workdata->f_ha1) = 0;
  6905. (workdata->f_ha1)++;
  6906. if (!strcmp(workdata->ah.user, workdata->f_user)
  6907. && !strcmp(workdata->domain, workdata->f_domain)) {
  6908. return check_password(workdata->conn->request_info.request_method,
  6909. workdata->f_ha1,
  6910. workdata->ah.uri,
  6911. workdata->ah.nonce,
  6912. workdata->ah.nc,
  6913. workdata->ah.cnonce,
  6914. workdata->ah.qop,
  6915. workdata->ah.response);
  6916. }
  6917. }
  6918. return is_authorized;
  6919. }
  6920. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6921. static int
  6922. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  6923. {
  6924. struct read_auth_file_struct workdata;
  6925. char buf[MG_BUF_LEN];
  6926. if (!conn || !conn->dom_ctx) {
  6927. return 0;
  6928. }
  6929. memset(&workdata, 0, sizeof(workdata));
  6930. workdata.conn = conn;
  6931. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6932. return 0;
  6933. }
  6934. if (realm) {
  6935. workdata.domain = realm;
  6936. } else {
  6937. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  6938. }
  6939. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6940. }
  6941. /* Public function to check http digest authentication header */
  6942. int
  6943. mg_check_digest_access_authentication(struct mg_connection *conn,
  6944. const char *realm,
  6945. const char *filename)
  6946. {
  6947. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6948. int auth;
  6949. if (!conn || !filename) {
  6950. return -1;
  6951. }
  6952. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  6953. return -2;
  6954. }
  6955. auth = authorize(conn, &file, realm);
  6956. mg_fclose(&file.access);
  6957. return auth;
  6958. }
  6959. /* Return 1 if request is authorised, 0 otherwise. */
  6960. static int
  6961. check_authorization(struct mg_connection *conn, const char *path)
  6962. {
  6963. char fname[PATH_MAX];
  6964. struct vec uri_vec, filename_vec;
  6965. const char *list;
  6966. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6967. int authorized = 1, truncated;
  6968. if (!conn || !conn->dom_ctx) {
  6969. return 0;
  6970. }
  6971. list = conn->dom_ctx->config[PROTECT_URI];
  6972. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6973. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6974. mg_snprintf(conn,
  6975. &truncated,
  6976. fname,
  6977. sizeof(fname),
  6978. "%.*s",
  6979. (int)filename_vec.len,
  6980. filename_vec.ptr);
  6981. if (truncated
  6982. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6983. mg_cry_internal(conn,
  6984. "%s: cannot open %s: %s",
  6985. __func__,
  6986. fname,
  6987. strerror(errno));
  6988. }
  6989. break;
  6990. }
  6991. }
  6992. if (!is_file_opened(&file.access)) {
  6993. open_auth_file(conn, path, &file);
  6994. }
  6995. if (is_file_opened(&file.access)) {
  6996. authorized = authorize(conn, &file, NULL);
  6997. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6998. }
  6999. return authorized;
  7000. }
  7001. /* Internal function. Assumes conn is valid */
  7002. static void
  7003. send_authorization_request(struct mg_connection *conn, const char *realm)
  7004. {
  7005. char date[64];
  7006. time_t curtime = time(NULL);
  7007. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  7008. if (!realm) {
  7009. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  7010. }
  7011. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  7012. nonce += conn->dom_ctx->nonce_count;
  7013. ++conn->dom_ctx->nonce_count;
  7014. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  7015. nonce ^= conn->dom_ctx->auth_nonce_mask;
  7016. conn->status_code = 401;
  7017. conn->must_close = 1;
  7018. gmt_time_string(date, sizeof(date), &curtime);
  7019. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  7020. send_no_cache_header(conn);
  7021. send_additional_header(conn);
  7022. mg_printf(conn,
  7023. "Date: %s\r\n"
  7024. "Connection: %s\r\n"
  7025. "Content-Length: 0\r\n"
  7026. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  7027. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  7028. date,
  7029. suggest_connection_header(conn),
  7030. realm,
  7031. nonce);
  7032. }
  7033. /* Interface function. Parameters are provided by the user, so do
  7034. * at least some basic checks.
  7035. */
  7036. int
  7037. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  7038. const char *realm)
  7039. {
  7040. if (conn && conn->dom_ctx) {
  7041. send_authorization_request(conn, realm);
  7042. return 0;
  7043. }
  7044. return -1;
  7045. }
  7046. #if !defined(NO_FILES)
  7047. static int
  7048. is_authorized_for_put(struct mg_connection *conn)
  7049. {
  7050. if (conn) {
  7051. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7052. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  7053. int ret = 0;
  7054. if (passfile != NULL
  7055. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  7056. ret = authorize(conn, &file, NULL);
  7057. (void)mg_fclose(&file.access); /* ignore error on read only file */
  7058. }
  7059. return ret;
  7060. }
  7061. return 0;
  7062. }
  7063. #endif
  7064. int
  7065. mg_modify_passwords_file(const char *fname,
  7066. const char *domain,
  7067. const char *user,
  7068. const char *pass)
  7069. {
  7070. int found, i;
  7071. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  7072. FILE *fp, *fp2;
  7073. found = 0;
  7074. fp = fp2 = NULL;
  7075. /* Regard empty password as no password - remove user record. */
  7076. if ((pass != NULL) && (pass[0] == '\0')) {
  7077. pass = NULL;
  7078. }
  7079. /* Other arguments must not be empty */
  7080. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  7081. return 0;
  7082. }
  7083. /* Using the given file format, user name and domain must not contain
  7084. * ':'
  7085. */
  7086. if (strchr(user, ':') != NULL) {
  7087. return 0;
  7088. }
  7089. if (strchr(domain, ':') != NULL) {
  7090. return 0;
  7091. }
  7092. /* Do not allow control characters like newline in user name and domain.
  7093. * Do not allow excessively long names either. */
  7094. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  7095. if (iscntrl(user[i])) {
  7096. return 0;
  7097. }
  7098. }
  7099. if (user[i]) {
  7100. return 0;
  7101. }
  7102. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  7103. if (iscntrl(domain[i])) {
  7104. return 0;
  7105. }
  7106. }
  7107. if (domain[i]) {
  7108. return 0;
  7109. }
  7110. /* The maximum length of the path to the password file is limited */
  7111. if ((strlen(fname) + 4) >= PATH_MAX) {
  7112. return 0;
  7113. }
  7114. /* Create a temporary file name. Length has been checked before. */
  7115. strcpy(tmp, fname);
  7116. strcat(tmp, ".tmp");
  7117. /* Create the file if does not exist */
  7118. /* Use of fopen here is OK, since fname is only ASCII */
  7119. if ((fp = fopen(fname, "a+")) != NULL) {
  7120. (void)fclose(fp);
  7121. }
  7122. /* Open the given file and temporary file */
  7123. if ((fp = fopen(fname, "r")) == NULL) {
  7124. return 0;
  7125. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  7126. fclose(fp);
  7127. return 0;
  7128. }
  7129. /* Copy the stuff to temporary file */
  7130. while (fgets(line, sizeof(line), fp) != NULL) {
  7131. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  7132. continue;
  7133. }
  7134. u[255] = 0;
  7135. d[255] = 0;
  7136. if (!strcmp(u, user) && !strcmp(d, domain)) {
  7137. found++;
  7138. if (pass != NULL) {
  7139. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7140. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7141. }
  7142. } else {
  7143. fprintf(fp2, "%s", line);
  7144. }
  7145. }
  7146. /* If new user, just add it */
  7147. if (!found && (pass != NULL)) {
  7148. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  7149. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  7150. }
  7151. /* Close files */
  7152. fclose(fp);
  7153. fclose(fp2);
  7154. /* Put the temp file in place of real file */
  7155. IGNORE_UNUSED_RESULT(remove(fname));
  7156. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  7157. return 1;
  7158. }
  7159. static int
  7160. is_valid_port(unsigned long port)
  7161. {
  7162. return (port <= 0xffff);
  7163. }
  7164. static int
  7165. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  7166. {
  7167. struct addrinfo hints, *res, *ressave;
  7168. int func_ret = 0;
  7169. int gai_ret;
  7170. memset(&hints, 0, sizeof(struct addrinfo));
  7171. hints.ai_family = af;
  7172. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  7173. if (gai_ret != 0) {
  7174. /* gai_strerror could be used to convert gai_ret to a string */
  7175. /* POSIX return values: see
  7176. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  7177. */
  7178. /* Windows return values: see
  7179. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  7180. */
  7181. return 0;
  7182. }
  7183. ressave = res;
  7184. while (res) {
  7185. if (dstlen >= (size_t)res->ai_addrlen) {
  7186. memcpy(dst, res->ai_addr, res->ai_addrlen);
  7187. func_ret = 1;
  7188. }
  7189. res = res->ai_next;
  7190. }
  7191. freeaddrinfo(ressave);
  7192. return func_ret;
  7193. }
  7194. static int
  7195. connect_socket(struct mg_context *ctx /* may be NULL */,
  7196. const char *host,
  7197. int port,
  7198. int use_ssl,
  7199. char *ebuf,
  7200. size_t ebuf_len,
  7201. SOCKET *sock /* output: socket, must not be NULL */,
  7202. union usa *sa /* output: socket address, must not be NULL */
  7203. )
  7204. {
  7205. int ip_ver = 0;
  7206. int conn_ret = -1;
  7207. *sock = INVALID_SOCKET;
  7208. memset(sa, 0, sizeof(*sa));
  7209. if (ebuf_len > 0) {
  7210. *ebuf = 0;
  7211. }
  7212. if (host == NULL) {
  7213. mg_snprintf(NULL,
  7214. NULL, /* No truncation check for ebuf */
  7215. ebuf,
  7216. ebuf_len,
  7217. "%s",
  7218. "NULL host");
  7219. return 0;
  7220. }
  7221. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7222. mg_snprintf(NULL,
  7223. NULL, /* No truncation check for ebuf */
  7224. ebuf,
  7225. ebuf_len,
  7226. "%s",
  7227. "invalid port");
  7228. return 0;
  7229. }
  7230. #if !defined(NO_SSL)
  7231. #if !defined(NO_SSL_DL)
  7232. #if defined(OPENSSL_API_1_1)
  7233. if (use_ssl && (TLS_client_method == NULL)) {
  7234. mg_snprintf(NULL,
  7235. NULL, /* No truncation check for ebuf */
  7236. ebuf,
  7237. ebuf_len,
  7238. "%s",
  7239. "SSL is not initialized");
  7240. return 0;
  7241. }
  7242. #else
  7243. if (use_ssl && (SSLv23_client_method == NULL)) {
  7244. mg_snprintf(NULL,
  7245. NULL, /* No truncation check for ebuf */
  7246. ebuf,
  7247. ebuf_len,
  7248. "%s",
  7249. "SSL is not initialized");
  7250. return 0;
  7251. }
  7252. #endif /* OPENSSL_API_1_1 */
  7253. #else
  7254. (void)use_ssl;
  7255. #endif /* NO_SSL_DL */
  7256. #else
  7257. (void)use_ssl;
  7258. #endif /* !defined(NO_SSL) */
  7259. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7260. sa->sin.sin_family = AF_INET;
  7261. sa->sin.sin_port = htons((uint16_t)port);
  7262. ip_ver = 4;
  7263. #if defined(USE_IPV6)
  7264. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7265. sa->sin6.sin6_family = AF_INET6;
  7266. sa->sin6.sin6_port = htons((uint16_t)port);
  7267. ip_ver = 6;
  7268. } else if (host[0] == '[') {
  7269. /* While getaddrinfo on Windows will work with [::1],
  7270. * getaddrinfo on Linux only works with ::1 (without []). */
  7271. size_t l = strlen(host + 1);
  7272. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7273. if (h) {
  7274. h[l - 1] = 0;
  7275. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7276. sa->sin6.sin6_family = AF_INET6;
  7277. sa->sin6.sin6_port = htons((uint16_t)port);
  7278. ip_ver = 6;
  7279. }
  7280. mg_free(h);
  7281. }
  7282. #endif
  7283. }
  7284. if (ip_ver == 0) {
  7285. mg_snprintf(NULL,
  7286. NULL, /* No truncation check for ebuf */
  7287. ebuf,
  7288. ebuf_len,
  7289. "%s",
  7290. "host not found");
  7291. return 0;
  7292. }
  7293. if (ip_ver == 4) {
  7294. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7295. }
  7296. #if defined(USE_IPV6)
  7297. else if (ip_ver == 6) {
  7298. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7299. }
  7300. #endif
  7301. if (*sock == INVALID_SOCKET) {
  7302. mg_snprintf(NULL,
  7303. NULL, /* No truncation check for ebuf */
  7304. ebuf,
  7305. ebuf_len,
  7306. "socket(): %s",
  7307. strerror(ERRNO));
  7308. return 0;
  7309. }
  7310. if (0 != set_non_blocking_mode(*sock)) {
  7311. mg_snprintf(NULL,
  7312. NULL, /* No truncation check for ebuf */
  7313. ebuf,
  7314. ebuf_len,
  7315. "Cannot set socket to non-blocking: %s",
  7316. strerror(ERRNO));
  7317. closesocket(*sock);
  7318. *sock = INVALID_SOCKET;
  7319. return 0;
  7320. }
  7321. set_close_on_exec(*sock, fc(ctx));
  7322. if (ip_ver == 4) {
  7323. /* connected with IPv4 */
  7324. conn_ret = connect(*sock,
  7325. (struct sockaddr *)((void *)&sa->sin),
  7326. sizeof(sa->sin));
  7327. }
  7328. #if defined(USE_IPV6)
  7329. else if (ip_ver == 6) {
  7330. /* connected with IPv6 */
  7331. conn_ret = connect(*sock,
  7332. (struct sockaddr *)((void *)&sa->sin6),
  7333. sizeof(sa->sin6));
  7334. }
  7335. #endif
  7336. if (conn_ret != 0) {
  7337. fd_set fdset;
  7338. struct timeval timeout;
  7339. int sockerr = -1;
  7340. void *psockerr = &sockerr;
  7341. #if defined(_WIN32)
  7342. int len = (int)sizeof(sockerr);
  7343. #else
  7344. socklen_t len = (socklen_t)sizeof(sockerr);
  7345. #endif
  7346. FD_ZERO(&fdset);
  7347. FD_SET(*sock, &fdset);
  7348. timeout.tv_sec = 10; /* 10 second timeout */
  7349. timeout.tv_usec = 0;
  7350. if (select((int)(*sock) + 1, NULL, &fdset, NULL, &timeout) != 1) {
  7351. /* Not connected */
  7352. mg_snprintf(NULL,
  7353. NULL, /* No truncation check for ebuf */
  7354. ebuf,
  7355. ebuf_len,
  7356. "connect(%s:%d): timeout",
  7357. host,
  7358. port);
  7359. closesocket(*sock);
  7360. *sock = INVALID_SOCKET;
  7361. return 0;
  7362. }
  7363. #if defined(_WIN32)
  7364. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len);
  7365. #else
  7366. getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len);
  7367. #endif
  7368. if (sockerr != 0) {
  7369. /* Not connected */
  7370. mg_snprintf(NULL,
  7371. NULL, /* No truncation check for ebuf */
  7372. ebuf,
  7373. ebuf_len,
  7374. "connect(%s:%d): error %s",
  7375. host,
  7376. port,
  7377. strerror(sockerr));
  7378. closesocket(*sock);
  7379. *sock = INVALID_SOCKET;
  7380. return 0;
  7381. }
  7382. }
  7383. return 1;
  7384. }
  7385. int
  7386. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7387. {
  7388. static const char *dont_escape = "._-$,;~()";
  7389. static const char *hex = "0123456789abcdef";
  7390. char *pos = dst;
  7391. const char *end = dst + dst_len - 1;
  7392. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7393. if (isalnum(*(const unsigned char *)src)
  7394. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7395. *pos = *src;
  7396. } else if (pos + 2 < end) {
  7397. pos[0] = '%';
  7398. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7399. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7400. pos += 2;
  7401. } else {
  7402. break;
  7403. }
  7404. }
  7405. *pos = '\0';
  7406. return (*src == '\0') ? (int)(pos - dst) : -1;
  7407. }
  7408. /* Return 0 on success, non-zero if an error occurs. */
  7409. static int
  7410. print_dir_entry(struct de *de)
  7411. {
  7412. size_t hrefsize;
  7413. char *href;
  7414. char size[64], mod[64];
  7415. #if defined(REENTRANT_TIME)
  7416. struct tm _tm;
  7417. struct tm *tm = &_tm;
  7418. #else
  7419. struct tm *tm;
  7420. #endif
  7421. hrefsize = PATH_MAX * 3; /* worst case */
  7422. href = (char *)mg_malloc(hrefsize);
  7423. if (href == NULL) {
  7424. return -1;
  7425. }
  7426. if (de->file.is_directory) {
  7427. mg_snprintf(de->conn,
  7428. NULL, /* Buffer is big enough */
  7429. size,
  7430. sizeof(size),
  7431. "%s",
  7432. "[DIRECTORY]");
  7433. } else {
  7434. /* We use (signed) cast below because MSVC 6 compiler cannot
  7435. * convert unsigned __int64 to double. Sigh. */
  7436. if (de->file.size < 1024) {
  7437. mg_snprintf(de->conn,
  7438. NULL, /* Buffer is big enough */
  7439. size,
  7440. sizeof(size),
  7441. "%d",
  7442. (int)de->file.size);
  7443. } else if (de->file.size < 0x100000) {
  7444. mg_snprintf(de->conn,
  7445. NULL, /* Buffer is big enough */
  7446. size,
  7447. sizeof(size),
  7448. "%.1fk",
  7449. (double)de->file.size / 1024.0);
  7450. } else if (de->file.size < 0x40000000) {
  7451. mg_snprintf(de->conn,
  7452. NULL, /* Buffer is big enough */
  7453. size,
  7454. sizeof(size),
  7455. "%.1fM",
  7456. (double)de->file.size / 1048576);
  7457. } else {
  7458. mg_snprintf(de->conn,
  7459. NULL, /* Buffer is big enough */
  7460. size,
  7461. sizeof(size),
  7462. "%.1fG",
  7463. (double)de->file.size / 1073741824);
  7464. }
  7465. }
  7466. /* Note: mg_snprintf will not cause a buffer overflow above.
  7467. * So, string truncation checks are not required here. */
  7468. #if defined(REENTRANT_TIME)
  7469. localtime_r(&de->file.last_modified, tm);
  7470. #else
  7471. tm = localtime(&de->file.last_modified);
  7472. #endif
  7473. if (tm != NULL) {
  7474. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7475. } else {
  7476. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7477. mod[sizeof(mod) - 1] = '\0';
  7478. }
  7479. mg_url_encode(de->file_name, href, hrefsize);
  7480. mg_printf(de->conn,
  7481. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7482. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7483. de->conn->request_info.local_uri,
  7484. href,
  7485. de->file.is_directory ? "/" : "",
  7486. de->file_name,
  7487. de->file.is_directory ? "/" : "",
  7488. mod,
  7489. size);
  7490. mg_free(href);
  7491. return 0;
  7492. }
  7493. /* This function is called from send_directory() and used for
  7494. * sorting directory entries by size, or name, or modification time.
  7495. * On windows, __cdecl specification is needed in case if project is built
  7496. * with __stdcall convention. qsort always requires __cdels callback. */
  7497. static int WINCDECL
  7498. compare_dir_entries(const void *p1, const void *p2)
  7499. {
  7500. if (p1 && p2) {
  7501. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7502. const char *query_string = a->conn->request_info.query_string;
  7503. int cmp_result = 0;
  7504. if (query_string == NULL) {
  7505. query_string = "na";
  7506. }
  7507. if (a->file.is_directory && !b->file.is_directory) {
  7508. return -1; /* Always put directories on top */
  7509. } else if (!a->file.is_directory && b->file.is_directory) {
  7510. return 1; /* Always put directories on top */
  7511. } else if (*query_string == 'n') {
  7512. cmp_result = strcmp(a->file_name, b->file_name);
  7513. } else if (*query_string == 's') {
  7514. cmp_result = (a->file.size == b->file.size)
  7515. ? 0
  7516. : ((a->file.size > b->file.size) ? 1 : -1);
  7517. } else if (*query_string == 'd') {
  7518. cmp_result =
  7519. (a->file.last_modified == b->file.last_modified)
  7520. ? 0
  7521. : ((a->file.last_modified > b->file.last_modified) ? 1
  7522. : -1);
  7523. }
  7524. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7525. }
  7526. return 0;
  7527. }
  7528. static int
  7529. must_hide_file(struct mg_connection *conn, const char *path)
  7530. {
  7531. if (conn && conn->dom_ctx) {
  7532. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7533. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7534. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7535. || ((pattern != NULL)
  7536. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7537. }
  7538. return 0;
  7539. }
  7540. static int
  7541. scan_directory(struct mg_connection *conn,
  7542. const char *dir,
  7543. void *data,
  7544. int (*cb)(struct de *, void *))
  7545. {
  7546. char path[PATH_MAX];
  7547. struct dirent *dp;
  7548. DIR *dirp;
  7549. struct de de;
  7550. int truncated;
  7551. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7552. return 0;
  7553. } else {
  7554. de.conn = conn;
  7555. while ((dp = mg_readdir(dirp)) != NULL) {
  7556. /* Do not show current dir and hidden files */
  7557. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7558. || must_hide_file(conn, dp->d_name)) {
  7559. continue;
  7560. }
  7561. mg_snprintf(
  7562. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7563. /* If we don't memset stat structure to zero, mtime will have
  7564. * garbage and strftime() will segfault later on in
  7565. * print_dir_entry(). memset is required only if mg_stat()
  7566. * fails. For more details, see
  7567. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7568. memset(&de.file, 0, sizeof(de.file));
  7569. if (truncated) {
  7570. /* If the path is not complete, skip processing. */
  7571. continue;
  7572. }
  7573. if (!mg_stat(conn, path, &de.file)) {
  7574. mg_cry_internal(conn,
  7575. "%s: mg_stat(%s) failed: %s",
  7576. __func__,
  7577. path,
  7578. strerror(ERRNO));
  7579. }
  7580. de.file_name = dp->d_name;
  7581. cb(&de, data);
  7582. }
  7583. (void)mg_closedir(dirp);
  7584. }
  7585. return 1;
  7586. }
  7587. #if !defined(NO_FILES)
  7588. static int
  7589. remove_directory(struct mg_connection *conn, const char *dir)
  7590. {
  7591. char path[PATH_MAX];
  7592. struct dirent *dp;
  7593. DIR *dirp;
  7594. struct de de;
  7595. int truncated;
  7596. int ok = 1;
  7597. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7598. return 0;
  7599. } else {
  7600. de.conn = conn;
  7601. while ((dp = mg_readdir(dirp)) != NULL) {
  7602. /* Do not show current dir (but show hidden files as they will
  7603. * also be removed) */
  7604. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7605. continue;
  7606. }
  7607. mg_snprintf(
  7608. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7609. /* If we don't memset stat structure to zero, mtime will have
  7610. * garbage and strftime() will segfault later on in
  7611. * print_dir_entry(). memset is required only if mg_stat()
  7612. * fails. For more details, see
  7613. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7614. memset(&de.file, 0, sizeof(de.file));
  7615. if (truncated) {
  7616. /* Do not delete anything shorter */
  7617. ok = 0;
  7618. continue;
  7619. }
  7620. if (!mg_stat(conn, path, &de.file)) {
  7621. mg_cry_internal(conn,
  7622. "%s: mg_stat(%s) failed: %s",
  7623. __func__,
  7624. path,
  7625. strerror(ERRNO));
  7626. ok = 0;
  7627. }
  7628. if (de.file.is_directory) {
  7629. if (remove_directory(conn, path) == 0) {
  7630. ok = 0;
  7631. }
  7632. } else {
  7633. /* This will fail file is the file is in memory */
  7634. if (mg_remove(conn, path) == 0) {
  7635. ok = 0;
  7636. }
  7637. }
  7638. }
  7639. (void)mg_closedir(dirp);
  7640. IGNORE_UNUSED_RESULT(rmdir(dir));
  7641. }
  7642. return ok;
  7643. }
  7644. #endif
  7645. struct dir_scan_data {
  7646. struct de *entries;
  7647. unsigned int num_entries;
  7648. unsigned int arr_size;
  7649. };
  7650. /* Behaves like realloc(), but frees original pointer on failure */
  7651. static void *
  7652. realloc2(void *ptr, size_t size)
  7653. {
  7654. void *new_ptr = mg_realloc(ptr, size);
  7655. if (new_ptr == NULL) {
  7656. mg_free(ptr);
  7657. }
  7658. return new_ptr;
  7659. }
  7660. static int
  7661. dir_scan_callback(struct de *de, void *data)
  7662. {
  7663. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7664. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7665. dsd->arr_size *= 2;
  7666. dsd->entries =
  7667. (struct de *)realloc2(dsd->entries,
  7668. dsd->arr_size * sizeof(dsd->entries[0]));
  7669. }
  7670. if (dsd->entries == NULL) {
  7671. /* TODO(lsm, low): propagate an error to the caller */
  7672. dsd->num_entries = 0;
  7673. } else {
  7674. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7675. dsd->entries[dsd->num_entries].file = de->file;
  7676. dsd->entries[dsd->num_entries].conn = de->conn;
  7677. dsd->num_entries++;
  7678. }
  7679. return 0;
  7680. }
  7681. static void
  7682. handle_directory_request(struct mg_connection *conn, const char *dir)
  7683. {
  7684. unsigned int i;
  7685. int sort_direction;
  7686. struct dir_scan_data data = {NULL, 0, 128};
  7687. char date[64];
  7688. time_t curtime = time(NULL);
  7689. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7690. mg_send_http_error(conn,
  7691. 500,
  7692. "Error: Cannot open directory\nopendir(%s): %s",
  7693. dir,
  7694. strerror(ERRNO));
  7695. return;
  7696. }
  7697. gmt_time_string(date, sizeof(date), &curtime);
  7698. if (!conn) {
  7699. return;
  7700. }
  7701. sort_direction = ((conn->request_info.query_string != NULL)
  7702. && (conn->request_info.query_string[1] == 'd'))
  7703. ? 'a'
  7704. : 'd';
  7705. conn->must_close = 1;
  7706. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7707. send_static_cache_header(conn);
  7708. send_additional_header(conn);
  7709. mg_printf(conn,
  7710. "Date: %s\r\n"
  7711. "Connection: close\r\n"
  7712. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7713. date);
  7714. mg_printf(conn,
  7715. "<html><head><title>Index of %s</title>"
  7716. "<style>th {text-align: left;}</style></head>"
  7717. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7718. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7719. "<th><a href=\"?d%c\">Modified</a></th>"
  7720. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7721. "<tr><td colspan=\"3\"><hr></td></tr>",
  7722. conn->request_info.local_uri,
  7723. conn->request_info.local_uri,
  7724. sort_direction,
  7725. sort_direction,
  7726. sort_direction);
  7727. /* Print first entry - link to a parent directory */
  7728. mg_printf(conn,
  7729. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7730. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7731. conn->request_info.local_uri,
  7732. "..",
  7733. "Parent directory",
  7734. "-",
  7735. "-");
  7736. /* Sort and print directory entries */
  7737. if (data.entries != NULL) {
  7738. qsort(data.entries,
  7739. (size_t)data.num_entries,
  7740. sizeof(data.entries[0]),
  7741. compare_dir_entries);
  7742. for (i = 0; i < data.num_entries; i++) {
  7743. print_dir_entry(&data.entries[i]);
  7744. mg_free(data.entries[i].file_name);
  7745. }
  7746. mg_free(data.entries);
  7747. }
  7748. mg_printf(conn, "%s", "</table></body></html>");
  7749. conn->status_code = 200;
  7750. }
  7751. /* Send len bytes from the opened file to the client. */
  7752. static void
  7753. send_file_data(struct mg_connection *conn,
  7754. struct mg_file *filep,
  7755. int64_t offset,
  7756. int64_t len)
  7757. {
  7758. char buf[MG_BUF_LEN];
  7759. int to_read, num_read, num_written;
  7760. int64_t size;
  7761. if (!filep || !conn) {
  7762. return;
  7763. }
  7764. /* Sanity check the offset */
  7765. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7766. : (int64_t)(filep->stat.size);
  7767. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7768. #if defined(MG_USE_OPEN_FILE)
  7769. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7770. /* file stored in memory */
  7771. if (len > size - offset) {
  7772. len = size - offset;
  7773. }
  7774. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7775. } else /* else block below */
  7776. #endif
  7777. if (len > 0 && filep->access.fp != NULL) {
  7778. /* file stored on disk */
  7779. #if defined(__linux__)
  7780. /* sendfile is only available for Linux */
  7781. if ((conn->ssl == 0) && (conn->throttle == 0)
  7782. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  7783. "yes"))) {
  7784. off_t sf_offs = (off_t)offset;
  7785. ssize_t sf_sent;
  7786. int sf_file = fileno(filep->access.fp);
  7787. int loop_cnt = 0;
  7788. do {
  7789. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7790. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7791. size_t sf_tosend =
  7792. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7793. sf_sent =
  7794. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7795. if (sf_sent > 0) {
  7796. len -= sf_sent;
  7797. offset += sf_sent;
  7798. } else if (loop_cnt == 0) {
  7799. /* This file can not be sent using sendfile.
  7800. * This might be the case for pseudo-files in the
  7801. * /sys/ and /proc/ file system.
  7802. * Use the regular user mode copy code instead. */
  7803. break;
  7804. } else if (sf_sent == 0) {
  7805. /* No error, but 0 bytes sent. May be EOF? */
  7806. return;
  7807. }
  7808. loop_cnt++;
  7809. } while ((len > 0) && (sf_sent >= 0));
  7810. if (sf_sent > 0) {
  7811. return; /* OK */
  7812. }
  7813. /* sf_sent<0 means error, thus fall back to the classic way */
  7814. /* This is always the case, if sf_file is not a "normal" file,
  7815. * e.g., for sending data from the output of a CGI process. */
  7816. offset = (int64_t)sf_offs;
  7817. }
  7818. #endif
  7819. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7820. mg_cry_internal(conn,
  7821. "%s: fseeko() failed: %s",
  7822. __func__,
  7823. strerror(ERRNO));
  7824. mg_send_http_error(
  7825. conn,
  7826. 500,
  7827. "%s",
  7828. "Error: Unable to access file at requested position.");
  7829. } else {
  7830. while (len > 0) {
  7831. /* Calculate how much to read from the file in the buffer */
  7832. to_read = sizeof(buf);
  7833. if ((int64_t)to_read > len) {
  7834. to_read = (int)len;
  7835. }
  7836. /* Read from file, exit the loop on error */
  7837. if ((num_read =
  7838. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7839. <= 0) {
  7840. break;
  7841. }
  7842. /* Send read bytes to the client, exit the loop on error */
  7843. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7844. != num_read) {
  7845. break;
  7846. }
  7847. /* Both read and were successful, adjust counters */
  7848. len -= num_written;
  7849. }
  7850. }
  7851. }
  7852. }
  7853. static int
  7854. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7855. {
  7856. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7857. }
  7858. static void
  7859. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7860. {
  7861. if ((filestat != NULL) && (buf != NULL)) {
  7862. mg_snprintf(NULL,
  7863. NULL, /* All calls to construct_etag use 64 byte buffer */
  7864. buf,
  7865. buf_len,
  7866. "\"%lx.%" INT64_FMT "\"",
  7867. (unsigned long)filestat->last_modified,
  7868. filestat->size);
  7869. }
  7870. }
  7871. static void
  7872. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7873. {
  7874. if (filep != NULL && filep->fp != NULL) {
  7875. #if defined(_WIN32)
  7876. (void)conn; /* Unused. */
  7877. #else
  7878. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7879. mg_cry_internal(conn,
  7880. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7881. __func__,
  7882. strerror(ERRNO));
  7883. }
  7884. #endif
  7885. }
  7886. }
  7887. #if defined(USE_ZLIB)
  7888. #include "mod_zlib.inl"
  7889. #endif
  7890. static void
  7891. handle_static_file_request(struct mg_connection *conn,
  7892. const char *path,
  7893. struct mg_file *filep,
  7894. const char *mime_type,
  7895. const char *additional_headers)
  7896. {
  7897. char date[64], lm[64], etag[64];
  7898. char range[128]; /* large enough, so there will be no overflow */
  7899. const char *msg = "OK", *hdr;
  7900. time_t curtime = time(NULL);
  7901. int64_t cl, r1, r2;
  7902. struct vec mime_vec;
  7903. int n, truncated;
  7904. char gz_path[PATH_MAX];
  7905. const char *encoding = "";
  7906. const char *cors1, *cors2, *cors3;
  7907. int is_head_request;
  7908. #if defined(USE_ZLIB)
  7909. int allow_on_the_fly_compression = 1; /* TODO: get from config */
  7910. #endif
  7911. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  7912. return;
  7913. }
  7914. is_head_request = !strcmp(conn->request_info.request_method, "HEAD");
  7915. if (mime_type == NULL) {
  7916. get_mime_type(conn, path, &mime_vec);
  7917. } else {
  7918. mime_vec.ptr = mime_type;
  7919. mime_vec.len = strlen(mime_type);
  7920. }
  7921. if (filep->stat.size > INT64_MAX) {
  7922. mg_send_http_error(conn,
  7923. 500,
  7924. "Error: File size is too large to send\n%" INT64_FMT,
  7925. filep->stat.size);
  7926. return;
  7927. }
  7928. cl = (int64_t)filep->stat.size;
  7929. conn->status_code = 200;
  7930. range[0] = '\0';
  7931. #if defined(USE_ZLIB)
  7932. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7933. * it's important to rewrite the filename after resolving
  7934. * the mime type from it, to preserve the actual file's type */
  7935. if (!conn->accept_gzip) {
  7936. allow_on_the_fly_compression = 0;
  7937. }
  7938. #endif
  7939. if (filep->stat.is_gzipped) {
  7940. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7941. if (truncated) {
  7942. mg_send_http_error(conn,
  7943. 500,
  7944. "Error: Path of zipped file too long (%s)",
  7945. path);
  7946. return;
  7947. }
  7948. path = gz_path;
  7949. encoding = "Content-Encoding: gzip\r\n";
  7950. #if defined(USE_ZLIB)
  7951. /* File is already compressed. No "on the fly" compression. */
  7952. allow_on_the_fly_compression = 0;
  7953. #endif
  7954. }
  7955. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7956. mg_send_http_error(conn,
  7957. 500,
  7958. "Error: Cannot open file\nfopen(%s): %s",
  7959. path,
  7960. strerror(ERRNO));
  7961. return;
  7962. }
  7963. fclose_on_exec(&filep->access, conn);
  7964. /* If Range: header specified, act accordingly */
  7965. r1 = r2 = 0;
  7966. hdr = mg_get_header(conn, "Range");
  7967. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7968. && (r1 >= 0) && (r2 >= 0)) {
  7969. /* actually, range requests don't play well with a pre-gzipped
  7970. * file (since the range is specified in the uncompressed space) */
  7971. if (filep->stat.is_gzipped) {
  7972. mg_send_http_error(
  7973. conn,
  7974. 416, /* 416 = Range Not Satisfiable */
  7975. "%s",
  7976. "Error: Range requests in gzipped files are not supported");
  7977. (void)mg_fclose(
  7978. &filep->access); /* ignore error on read only file */
  7979. return;
  7980. }
  7981. conn->status_code = 206;
  7982. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7983. mg_snprintf(conn,
  7984. NULL, /* range buffer is big enough */
  7985. range,
  7986. sizeof(range),
  7987. "Content-Range: bytes "
  7988. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7989. r1,
  7990. r1 + cl - 1,
  7991. filep->stat.size);
  7992. msg = "Partial Content";
  7993. #if defined(USE_ZLIB)
  7994. /* Do not compress ranges. */
  7995. allow_on_the_fly_compression = 0;
  7996. #endif
  7997. }
  7998. hdr = mg_get_header(conn, "Origin");
  7999. if (hdr) {
  8000. /* Cross-origin resource sharing (CORS), see
  8001. * http://www.html5rocks.com/en/tutorials/cors/,
  8002. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  8003. * -
  8004. * preflight is not supported for files. */
  8005. cors1 = "Access-Control-Allow-Origin: ";
  8006. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  8007. cors3 = "\r\n";
  8008. } else {
  8009. cors1 = cors2 = cors3 = "";
  8010. }
  8011. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  8012. * according to
  8013. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  8014. gmt_time_string(date, sizeof(date), &curtime);
  8015. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8016. construct_etag(etag, sizeof(etag), &filep->stat);
  8017. /* Send header */
  8018. (void)mg_printf(conn,
  8019. "HTTP/1.1 %d %s\r\n"
  8020. "%s%s%s" /* CORS */
  8021. "Date: %s\r\n"
  8022. "Last-Modified: %s\r\n"
  8023. "Etag: %s\r\n"
  8024. "Content-Type: %.*s\r\n"
  8025. "Connection: %s\r\n",
  8026. conn->status_code,
  8027. msg,
  8028. cors1,
  8029. cors2,
  8030. cors3,
  8031. date,
  8032. lm,
  8033. etag,
  8034. (int)mime_vec.len,
  8035. mime_vec.ptr,
  8036. suggest_connection_header(conn));
  8037. send_static_cache_header(conn);
  8038. send_additional_header(conn);
  8039. #if defined(USE_ZLIB)
  8040. /* On the fly compression allowed */
  8041. if (allow_on_the_fly_compression) {
  8042. /* For on the fly compression, we don't know the content size in
  8043. * advance, so we have to use chunked encoding */
  8044. (void)mg_printf(conn,
  8045. "Content-Encoding: gzip\r\n"
  8046. "Transfer-Encoding: chunked\r\n");
  8047. } else
  8048. #endif
  8049. {
  8050. /* Without on-the-fly compression, we know the content-length
  8051. * and we can use ranges (with on-the-fly compression we cannot).
  8052. * So we send these response headers only in this case. */
  8053. (void)mg_printf(conn,
  8054. "Content-Length: %" INT64_FMT "\r\n"
  8055. "Accept-Ranges: bytes\r\n"
  8056. "%s" /* range */
  8057. "%s" /* encoding */,
  8058. cl,
  8059. range,
  8060. encoding);
  8061. }
  8062. /* The previous code must not add any header starting with X- to make
  8063. * sure no one of the additional_headers is included twice */
  8064. if (additional_headers != NULL) {
  8065. (void)mg_printf(conn,
  8066. "%.*s\r\n\r\n",
  8067. (int)strlen(additional_headers),
  8068. additional_headers);
  8069. } else {
  8070. (void)mg_printf(conn, "\r\n");
  8071. }
  8072. if (!is_head_request) {
  8073. #if defined(USE_ZLIB)
  8074. if (allow_on_the_fly_compression) {
  8075. /* Compress and send */
  8076. send_compressed_data(conn, filep);
  8077. } else
  8078. #endif
  8079. {
  8080. /* Send file directly */
  8081. send_file_data(conn, filep, r1, cl);
  8082. }
  8083. }
  8084. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  8085. }
  8086. #if !defined(NO_CACHING)
  8087. /* Return True if we should reply 304 Not Modified. */
  8088. static int
  8089. is_not_modified(const struct mg_connection *conn,
  8090. const struct mg_file_stat *filestat)
  8091. {
  8092. char etag[64];
  8093. const char *ims = mg_get_header(conn, "If-Modified-Since");
  8094. const char *inm = mg_get_header(conn, "If-None-Match");
  8095. construct_etag(etag, sizeof(etag), filestat);
  8096. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  8097. || ((ims != NULL)
  8098. && (filestat->last_modified <= parse_date_string(ims)));
  8099. }
  8100. static void
  8101. handle_not_modified_static_file_request(struct mg_connection *conn,
  8102. struct mg_file *filep)
  8103. {
  8104. char date[64], lm[64], etag[64];
  8105. time_t curtime = time(NULL);
  8106. if ((conn == NULL) || (filep == NULL)) {
  8107. return;
  8108. }
  8109. conn->status_code = 304;
  8110. gmt_time_string(date, sizeof(date), &curtime);
  8111. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  8112. construct_etag(etag, sizeof(etag), &filep->stat);
  8113. (void)mg_printf(conn,
  8114. "HTTP/1.1 %d %s\r\n"
  8115. "Date: %s\r\n",
  8116. conn->status_code,
  8117. mg_get_response_code_text(conn, conn->status_code),
  8118. date);
  8119. send_static_cache_header(conn);
  8120. send_additional_header(conn);
  8121. (void)mg_printf(conn,
  8122. "Last-Modified: %s\r\n"
  8123. "Etag: %s\r\n"
  8124. "Connection: %s\r\n"
  8125. "\r\n",
  8126. lm,
  8127. etag,
  8128. suggest_connection_header(conn));
  8129. }
  8130. #endif
  8131. void
  8132. mg_send_file(struct mg_connection *conn, const char *path)
  8133. {
  8134. mg_send_mime_file(conn, path, NULL);
  8135. }
  8136. void
  8137. mg_send_mime_file(struct mg_connection *conn,
  8138. const char *path,
  8139. const char *mime_type)
  8140. {
  8141. mg_send_mime_file2(conn, path, mime_type, NULL);
  8142. }
  8143. void
  8144. mg_send_mime_file2(struct mg_connection *conn,
  8145. const char *path,
  8146. const char *mime_type,
  8147. const char *additional_headers)
  8148. {
  8149. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8150. if (!conn) {
  8151. /* No conn */
  8152. return;
  8153. }
  8154. if (mg_stat(conn, path, &file.stat)) {
  8155. #if !defined(NO_CACHING)
  8156. if (is_not_modified(conn, &file.stat)) {
  8157. /* Send 304 "Not Modified" - this must not send any body data */
  8158. handle_not_modified_static_file_request(conn, &file);
  8159. } else
  8160. #endif /* NO_CACHING */
  8161. if (file.stat.is_directory) {
  8162. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  8163. "yes")) {
  8164. handle_directory_request(conn, path);
  8165. } else {
  8166. mg_send_http_error(conn,
  8167. 403,
  8168. "%s",
  8169. "Error: Directory listing denied");
  8170. }
  8171. } else {
  8172. handle_static_file_request(
  8173. conn, path, &file, mime_type, additional_headers);
  8174. }
  8175. } else {
  8176. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  8177. }
  8178. }
  8179. /* For a given PUT path, create all intermediate subdirectories.
  8180. * Return 0 if the path itself is a directory.
  8181. * Return 1 if the path leads to a file.
  8182. * Return -1 for if the path is too long.
  8183. * Return -2 if path can not be created.
  8184. */
  8185. static int
  8186. put_dir(struct mg_connection *conn, const char *path)
  8187. {
  8188. char buf[PATH_MAX];
  8189. const char *s, *p;
  8190. struct mg_file file = STRUCT_FILE_INITIALIZER;
  8191. size_t len;
  8192. int res = 1;
  8193. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  8194. len = (size_t)(p - path);
  8195. if (len >= sizeof(buf)) {
  8196. /* path too long */
  8197. res = -1;
  8198. break;
  8199. }
  8200. memcpy(buf, path, len);
  8201. buf[len] = '\0';
  8202. /* Try to create intermediate directory */
  8203. DEBUG_TRACE("mkdir(%s)", buf);
  8204. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  8205. /* path does not exixt and can not be created */
  8206. res = -2;
  8207. break;
  8208. }
  8209. /* Is path itself a directory? */
  8210. if (p[1] == '\0') {
  8211. res = 0;
  8212. }
  8213. }
  8214. return res;
  8215. }
  8216. static void
  8217. remove_bad_file(const struct mg_connection *conn, const char *path)
  8218. {
  8219. int r = mg_remove(conn, path);
  8220. if (r != 0) {
  8221. mg_cry_internal(conn,
  8222. "%s: Cannot remove invalid file %s",
  8223. __func__,
  8224. path);
  8225. }
  8226. }
  8227. long long
  8228. mg_store_body(struct mg_connection *conn, const char *path)
  8229. {
  8230. char buf[MG_BUF_LEN];
  8231. long long len = 0;
  8232. int ret, n;
  8233. struct mg_file fi;
  8234. if (conn->consumed_content != 0) {
  8235. mg_cry_internal(conn, "%s: Contents already consumed", __func__);
  8236. return -11;
  8237. }
  8238. ret = put_dir(conn, path);
  8239. if (ret < 0) {
  8240. /* -1 for path too long,
  8241. * -2 for path can not be created. */
  8242. return ret;
  8243. }
  8244. if (ret != 1) {
  8245. /* Return 0 means, path itself is a directory. */
  8246. return 0;
  8247. }
  8248. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  8249. return -12;
  8250. }
  8251. ret = mg_read(conn, buf, sizeof(buf));
  8252. while (ret > 0) {
  8253. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  8254. if (n != ret) {
  8255. (void)mg_fclose(
  8256. &fi.access); /* File is bad and will be removed anyway. */
  8257. remove_bad_file(conn, path);
  8258. return -13;
  8259. }
  8260. len += ret;
  8261. ret = mg_read(conn, buf, sizeof(buf));
  8262. }
  8263. /* File is open for writing. If fclose fails, there was probably an
  8264. * error flushing the buffer to disk, so the file on disk might be
  8265. * broken. Delete it and return an error to the caller. */
  8266. if (mg_fclose(&fi.access) != 0) {
  8267. remove_bad_file(conn, path);
  8268. return -14;
  8269. }
  8270. return len;
  8271. }
  8272. /* Parse a buffer:
  8273. * Forward the string pointer till the end of a word, then
  8274. * terminate it and forward till the begin of the next word.
  8275. */
  8276. static int
  8277. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8278. {
  8279. /* Forward until a space is found - use isgraph here */
  8280. /* See http://www.cplusplus.com/reference/cctype/ */
  8281. while (isgraph(**ppw)) {
  8282. (*ppw)++;
  8283. }
  8284. /* Check end of word */
  8285. if (eol) {
  8286. /* must be a end of line */
  8287. if ((**ppw != '\r') && (**ppw != '\n')) {
  8288. return -1;
  8289. }
  8290. } else {
  8291. /* must be a end of a word, but not a line */
  8292. if (**ppw != ' ') {
  8293. return -1;
  8294. }
  8295. }
  8296. /* Terminate and forward to the next word */
  8297. do {
  8298. **ppw = 0;
  8299. (*ppw)++;
  8300. } while ((**ppw) && isspace(**ppw));
  8301. /* Check after term */
  8302. if (!eol) {
  8303. /* if it's not the end of line, there must be a next word */
  8304. if (!isgraph(**ppw)) {
  8305. return -1;
  8306. }
  8307. }
  8308. /* ok */
  8309. return 1;
  8310. }
  8311. /* Parse HTTP headers from the given buffer, advance buf pointer
  8312. * to the point where parsing stopped.
  8313. * All parameters must be valid pointers (not NULL).
  8314. * Return <0 on error. */
  8315. static int
  8316. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8317. {
  8318. int i;
  8319. int num_headers = 0;
  8320. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8321. char *dp = *buf;
  8322. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8323. dp++;
  8324. }
  8325. if (dp == *buf) {
  8326. /* End of headers reached. */
  8327. break;
  8328. }
  8329. if (*dp != ':') {
  8330. /* This is not a valid field. */
  8331. return -1;
  8332. }
  8333. /* End of header key (*dp == ':') */
  8334. /* Truncate here and set the key name */
  8335. *dp = 0;
  8336. hdr[i].name = *buf;
  8337. do {
  8338. dp++;
  8339. } while (*dp == ' ');
  8340. /* The rest of the line is the value */
  8341. hdr[i].value = dp;
  8342. *buf = dp + strcspn(dp, "\r\n");
  8343. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8344. *buf = NULL;
  8345. }
  8346. num_headers = i + 1;
  8347. if (*buf) {
  8348. (*buf)[0] = 0;
  8349. (*buf)[1] = 0;
  8350. *buf += 2;
  8351. } else {
  8352. *buf = dp;
  8353. break;
  8354. }
  8355. if ((*buf)[0] == '\r') {
  8356. /* This is the end of the header */
  8357. break;
  8358. }
  8359. }
  8360. return num_headers;
  8361. }
  8362. struct mg_http_method_info {
  8363. const char *name;
  8364. int request_has_body;
  8365. int response_has_body;
  8366. int is_safe;
  8367. int is_idempotent;
  8368. int is_cacheable;
  8369. };
  8370. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8371. static struct mg_http_method_info http_methods[] = {
  8372. /* HTTP (RFC 2616) */
  8373. {"GET", 0, 1, 1, 1, 1},
  8374. {"POST", 1, 1, 0, 0, 0},
  8375. {"PUT", 1, 0, 0, 1, 0},
  8376. {"DELETE", 0, 0, 0, 1, 0},
  8377. {"HEAD", 0, 0, 1, 1, 1},
  8378. {"OPTIONS", 0, 0, 1, 1, 0},
  8379. {"CONNECT", 1, 1, 0, 0, 0},
  8380. /* TRACE method (RFC 2616) is not supported for security reasons */
  8381. /* PATCH method (RFC 5789) */
  8382. {"PATCH", 1, 0, 0, 0, 0},
  8383. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8384. /* WEBDAV (RFC 2518) */
  8385. {"PROPFIND", 0, 1, 1, 1, 0},
  8386. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8387. * Some PROPFIND results MAY be cached, with care,
  8388. * as there is no cache validation mechanism for
  8389. * most properties. This method is both safe and
  8390. * idempotent (see Section 9.1 of [RFC2616]). */
  8391. {"MKCOL", 0, 0, 0, 1, 0},
  8392. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8393. * When MKCOL is invoked without a request body,
  8394. * the newly created collection SHOULD have no
  8395. * members. A MKCOL request message may contain
  8396. * a message body. The precise behavior of a MKCOL
  8397. * request when the body is present is undefined,
  8398. * ... ==> We do not support MKCOL with body data.
  8399. * This method is idempotent, but not safe (see
  8400. * Section 9.1 of [RFC2616]). Responses to this
  8401. * method MUST NOT be cached. */
  8402. /* Unsupported WEBDAV Methods: */
  8403. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8404. /* + 11 methods from RFC 3253 */
  8405. /* ORDERPATCH (RFC 3648) */
  8406. /* ACL (RFC 3744) */
  8407. /* SEARCH (RFC 5323) */
  8408. /* + MicroSoft extensions
  8409. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8410. /* REPORT method (RFC 3253) */
  8411. {"REPORT", 1, 1, 1, 1, 1},
  8412. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8413. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8414. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8415. * to be useful for REST in case a "GET request with body" is
  8416. * required. */
  8417. {NULL, 0, 0, 0, 0, 0}
  8418. /* end of list */
  8419. };
  8420. static const struct mg_http_method_info *
  8421. get_http_method_info(const char *method)
  8422. {
  8423. /* Check if the method is known to the server. The list of all known
  8424. * HTTP methods can be found here at
  8425. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8426. */
  8427. const struct mg_http_method_info *m = http_methods;
  8428. while (m->name) {
  8429. if (!strcmp(m->name, method)) {
  8430. return m;
  8431. }
  8432. m++;
  8433. }
  8434. return NULL;
  8435. }
  8436. static int
  8437. is_valid_http_method(const char *method)
  8438. {
  8439. return (get_http_method_info(method) != NULL);
  8440. }
  8441. /* Parse HTTP request, fill in mg_request_info structure.
  8442. * This function modifies the buffer by NUL-terminating
  8443. * HTTP request components, header names and header values.
  8444. * Parameters:
  8445. * buf (in/out): pointer to the HTTP header to parse and split
  8446. * len (in): length of HTTP header buffer
  8447. * re (out): parsed header as mg_request_info
  8448. * buf and ri must be valid pointers (not NULL), len>0.
  8449. * Returns <0 on error. */
  8450. static int
  8451. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8452. {
  8453. int request_length;
  8454. int init_skip = 0;
  8455. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8456. * remote_port */
  8457. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8458. NULL;
  8459. ri->num_headers = 0;
  8460. /* RFC says that all initial whitespaces should be ingored */
  8461. /* This included all leading \r and \n (isspace) */
  8462. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8463. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8464. buf++;
  8465. len--;
  8466. init_skip++;
  8467. }
  8468. if (len == 0) {
  8469. /* Incomplete request */
  8470. return 0;
  8471. }
  8472. /* Control characters are not allowed, including zero */
  8473. if (iscntrl(*(unsigned char *)buf)) {
  8474. return -1;
  8475. }
  8476. /* Find end of HTTP header */
  8477. request_length = get_http_header_len(buf, len);
  8478. if (request_length <= 0) {
  8479. return request_length;
  8480. }
  8481. buf[request_length - 1] = '\0';
  8482. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8483. return -1;
  8484. }
  8485. /* The first word has to be the HTTP method */
  8486. ri->request_method = buf;
  8487. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8488. return -1;
  8489. }
  8490. /* Check for a valid http method */
  8491. if (!is_valid_http_method(ri->request_method)) {
  8492. return -1;
  8493. }
  8494. /* The second word is the URI */
  8495. ri->request_uri = buf;
  8496. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8497. return -1;
  8498. }
  8499. /* Next would be the HTTP version */
  8500. ri->http_version = buf;
  8501. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8502. return -1;
  8503. }
  8504. /* Check for a valid HTTP version key */
  8505. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8506. /* Invalid request */
  8507. return -1;
  8508. }
  8509. ri->http_version += 5;
  8510. /* Parse all HTTP headers */
  8511. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8512. if (ri->num_headers < 0) {
  8513. /* Error while parsing headers */
  8514. return -1;
  8515. }
  8516. return request_length + init_skip;
  8517. }
  8518. static int
  8519. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8520. {
  8521. int response_length;
  8522. int init_skip = 0;
  8523. char *tmp, *tmp2;
  8524. long l;
  8525. /* Initialize elements. */
  8526. ri->http_version = ri->status_text = NULL;
  8527. ri->num_headers = ri->status_code = 0;
  8528. /* RFC says that all initial whitespaces should be ingored */
  8529. /* This included all leading \r and \n (isspace) */
  8530. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8531. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8532. buf++;
  8533. len--;
  8534. init_skip++;
  8535. }
  8536. if (len == 0) {
  8537. /* Incomplete request */
  8538. return 0;
  8539. }
  8540. /* Control characters are not allowed, including zero */
  8541. if (iscntrl(*(unsigned char *)buf)) {
  8542. return -1;
  8543. }
  8544. /* Find end of HTTP header */
  8545. response_length = get_http_header_len(buf, len);
  8546. if (response_length <= 0) {
  8547. return response_length;
  8548. }
  8549. buf[response_length - 1] = '\0';
  8550. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8551. return -1;
  8552. }
  8553. /* The first word is the HTTP version */
  8554. /* Check for a valid HTTP version key */
  8555. if (strncmp(buf, "HTTP/", 5) != 0) {
  8556. /* Invalid request */
  8557. return -1;
  8558. }
  8559. buf += 5;
  8560. if (!isgraph(buf[0])) {
  8561. /* Invalid request */
  8562. return -1;
  8563. }
  8564. ri->http_version = buf;
  8565. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8566. return -1;
  8567. }
  8568. /* The second word is the status as a number */
  8569. tmp = buf;
  8570. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8571. return -1;
  8572. }
  8573. l = strtol(tmp, &tmp2, 10);
  8574. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8575. /* Everything else but a 3 digit code is invalid */
  8576. return -1;
  8577. }
  8578. ri->status_code = (int)l;
  8579. /* The rest of the line is the status text */
  8580. ri->status_text = buf;
  8581. /* Find end of status text */
  8582. /* isgraph or isspace = isprint */
  8583. while (isprint(*buf)) {
  8584. buf++;
  8585. }
  8586. if ((*buf != '\r') && (*buf != '\n')) {
  8587. return -1;
  8588. }
  8589. /* Terminate string and forward buf to next line */
  8590. do {
  8591. *buf = 0;
  8592. buf++;
  8593. } while ((*buf) && isspace(*buf));
  8594. /* Parse all HTTP headers */
  8595. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8596. if (ri->num_headers < 0) {
  8597. /* Error while parsing headers */
  8598. return -1;
  8599. }
  8600. return response_length + init_skip;
  8601. }
  8602. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8603. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8604. * buffer (which marks the end of HTTP request). Buffer buf may already
  8605. * have some data. The length of the data is stored in nread.
  8606. * Upon every read operation, increase nread by the number of bytes read. */
  8607. static int
  8608. read_message(FILE *fp,
  8609. struct mg_connection *conn,
  8610. char *buf,
  8611. int bufsiz,
  8612. int *nread)
  8613. {
  8614. int request_len, n = 0;
  8615. struct timespec last_action_time;
  8616. double request_timeout;
  8617. if (!conn) {
  8618. return 0;
  8619. }
  8620. memset(&last_action_time, 0, sizeof(last_action_time));
  8621. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8622. /* value of request_timeout is in seconds, config in milliseconds */
  8623. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8624. } else {
  8625. request_timeout = -1.0;
  8626. }
  8627. if (conn->handled_requests > 0) {
  8628. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8629. request_timeout =
  8630. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8631. }
  8632. }
  8633. request_len = get_http_header_len(buf, *nread);
  8634. /* first time reading from this connection */
  8635. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8636. while (request_len == 0) {
  8637. /* Full request not yet received */
  8638. if (conn->phys_ctx->stop_flag != 0) {
  8639. /* Server is to be stopped. */
  8640. return -1;
  8641. }
  8642. if (*nread >= bufsiz) {
  8643. /* Request too long */
  8644. return -2;
  8645. }
  8646. n = pull_inner(
  8647. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8648. if (n == -2) {
  8649. /* Receive error */
  8650. return -1;
  8651. }
  8652. if (n > 0) {
  8653. *nread += n;
  8654. request_len = get_http_header_len(buf, *nread);
  8655. } else {
  8656. request_len = 0;
  8657. }
  8658. if ((request_len == 0) && (request_timeout >= 0)) {
  8659. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8660. > request_timeout) {
  8661. /* Timeout */
  8662. return -1;
  8663. }
  8664. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8665. }
  8666. }
  8667. return request_len;
  8668. }
  8669. #if !defined(NO_CGI) || !defined(NO_FILES)
  8670. static int
  8671. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8672. {
  8673. const char *expect, *body;
  8674. char buf[MG_BUF_LEN];
  8675. int to_read, nread, success = 0;
  8676. int64_t buffered_len;
  8677. double timeout = -1.0;
  8678. if (!conn) {
  8679. return 0;
  8680. }
  8681. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8682. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8683. }
  8684. expect = mg_get_header(conn, "Expect");
  8685. DEBUG_ASSERT(fp != NULL);
  8686. if (!fp) {
  8687. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8688. return 0;
  8689. }
  8690. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8691. /* Content length is not specified by the client. */
  8692. mg_send_http_error(conn,
  8693. 411,
  8694. "%s",
  8695. "Error: Client did not specify content length");
  8696. } else if ((expect != NULL)
  8697. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8698. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8699. */
  8700. mg_send_http_error(conn,
  8701. 417,
  8702. "Error: Can not fulfill expectation %s",
  8703. expect);
  8704. } else {
  8705. if (expect != NULL) {
  8706. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8707. conn->status_code = 100;
  8708. } else {
  8709. conn->status_code = 200;
  8710. }
  8711. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8712. - conn->consumed_content;
  8713. DEBUG_ASSERT(buffered_len >= 0);
  8714. DEBUG_ASSERT(conn->consumed_content == 0);
  8715. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8716. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8717. return 0;
  8718. }
  8719. if (buffered_len > 0) {
  8720. if ((int64_t)buffered_len > conn->content_len) {
  8721. buffered_len = (int)conn->content_len;
  8722. }
  8723. body = conn->buf + conn->request_len + conn->consumed_content;
  8724. push_all(
  8725. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8726. conn->consumed_content += buffered_len;
  8727. }
  8728. nread = 0;
  8729. while (conn->consumed_content < conn->content_len) {
  8730. to_read = sizeof(buf);
  8731. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8732. to_read = (int)(conn->content_len - conn->consumed_content);
  8733. }
  8734. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8735. if (nread == -2) {
  8736. /* error */
  8737. break;
  8738. }
  8739. if (nread > 0) {
  8740. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  8741. != nread) {
  8742. break;
  8743. }
  8744. }
  8745. conn->consumed_content += nread;
  8746. }
  8747. if (conn->consumed_content == conn->content_len) {
  8748. success = (nread >= 0);
  8749. }
  8750. /* Each error code path in this function must send an error */
  8751. if (!success) {
  8752. /* NOTE: Maybe some data has already been sent. */
  8753. /* TODO (low): If some data has been sent, a correct error
  8754. * reply can no longer be sent, so just close the connection */
  8755. mg_send_http_error(conn, 500, "%s", "");
  8756. }
  8757. }
  8758. return success;
  8759. }
  8760. #endif
  8761. #if !defined(NO_CGI)
  8762. /* This structure helps to create an environment for the spawned CGI
  8763. * program.
  8764. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8765. * last element must be NULL.
  8766. * However, on Windows there is a requirement that all these
  8767. * VARIABLE=VALUE\0
  8768. * strings must reside in a contiguous buffer. The end of the buffer is
  8769. * marked by two '\0' characters.
  8770. * We satisfy both worlds: we create an envp array (which is vars), all
  8771. * entries are actually pointers inside buf. */
  8772. struct cgi_environment {
  8773. struct mg_connection *conn;
  8774. /* Data block */
  8775. char *buf; /* Environment buffer */
  8776. size_t buflen; /* Space available in buf */
  8777. size_t bufused; /* Space taken in buf */
  8778. /* Index block */
  8779. char **var; /* char **envp */
  8780. size_t varlen; /* Number of variables available in var */
  8781. size_t varused; /* Number of variables stored in var */
  8782. };
  8783. static void addenv(struct cgi_environment *env,
  8784. PRINTF_FORMAT_STRING(const char *fmt),
  8785. ...) PRINTF_ARGS(2, 3);
  8786. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8787. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8788. static void
  8789. addenv(struct cgi_environment *env, const char *fmt, ...)
  8790. {
  8791. size_t n, space;
  8792. int truncated = 0;
  8793. char *added;
  8794. va_list ap;
  8795. /* Calculate how much space is left in the buffer */
  8796. space = (env->buflen - env->bufused);
  8797. /* Calculate an estimate for the required space */
  8798. n = strlen(fmt) + 2 + 128;
  8799. do {
  8800. if (space <= n) {
  8801. /* Allocate new buffer */
  8802. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  8803. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  8804. if (!added) {
  8805. /* Out of memory */
  8806. mg_cry_internal(
  8807. env->conn,
  8808. "%s: Cannot allocate memory for CGI variable [%s]",
  8809. __func__,
  8810. fmt);
  8811. return;
  8812. }
  8813. env->buf = added;
  8814. env->buflen = n;
  8815. space = (env->buflen - env->bufused);
  8816. }
  8817. /* Make a pointer to the free space int the buffer */
  8818. added = env->buf + env->bufused;
  8819. /* Copy VARIABLE=VALUE\0 string into the free space */
  8820. va_start(ap, fmt);
  8821. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  8822. va_end(ap);
  8823. /* Do not add truncated strings to the environment */
  8824. if (truncated) {
  8825. /* Reallocate the buffer */
  8826. space = 0;
  8827. n = 1;
  8828. }
  8829. } while (truncated);
  8830. /* Calculate number of bytes added to the environment */
  8831. n = strlen(added) + 1;
  8832. env->bufused += n;
  8833. /* Now update the variable index */
  8834. space = (env->varlen - env->varused);
  8835. if (space < 2) {
  8836. mg_cry_internal(env->conn,
  8837. "%s: Cannot register CGI variable [%s]",
  8838. __func__,
  8839. fmt);
  8840. return;
  8841. }
  8842. /* Append a pointer to the added string into the envp array */
  8843. env->var[env->varused] = added;
  8844. env->varused++;
  8845. }
  8846. /* Return 0 on success, non-zero if an error occurs. */
  8847. static int
  8848. prepare_cgi_environment(struct mg_connection *conn,
  8849. const char *prog,
  8850. struct cgi_environment *env)
  8851. {
  8852. const char *s;
  8853. struct vec var_vec;
  8854. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8855. int i, truncated, uri_len;
  8856. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8857. return -1;
  8858. }
  8859. env->conn = conn;
  8860. env->buflen = CGI_ENVIRONMENT_SIZE;
  8861. env->bufused = 0;
  8862. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  8863. if (env->buf == NULL) {
  8864. mg_cry_internal(conn,
  8865. "%s: Not enough memory for environmental buffer",
  8866. __func__);
  8867. return -1;
  8868. }
  8869. env->varlen = MAX_CGI_ENVIR_VARS;
  8870. env->varused = 0;
  8871. env->var =
  8872. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  8873. if (env->var == NULL) {
  8874. mg_cry_internal(conn,
  8875. "%s: Not enough memory for environmental variables",
  8876. __func__);
  8877. mg_free(env->buf);
  8878. return -1;
  8879. }
  8880. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  8881. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8882. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8883. addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version());
  8884. /* Prepare the environment block */
  8885. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8886. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8887. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8888. #if defined(USE_IPV6)
  8889. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8890. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8891. } else
  8892. #endif
  8893. {
  8894. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8895. }
  8896. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8897. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8898. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8899. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8900. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8901. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8902. /* SCRIPT_NAME */
  8903. uri_len = (int)strlen(conn->request_info.local_uri);
  8904. if (conn->path_info == NULL) {
  8905. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8906. /* URI: /path_to_script/script.cgi */
  8907. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8908. } else {
  8909. /* URI: /path_to_script/ ... using index.cgi */
  8910. const char *index_file = strrchr(prog, '/');
  8911. if (index_file) {
  8912. addenv(env,
  8913. "SCRIPT_NAME=%s%s",
  8914. conn->request_info.local_uri,
  8915. index_file + 1);
  8916. }
  8917. }
  8918. } else {
  8919. /* URI: /path_to_script/script.cgi/path_info */
  8920. addenv(env,
  8921. "SCRIPT_NAME=%.*s",
  8922. uri_len - (int)strlen(conn->path_info),
  8923. conn->request_info.local_uri);
  8924. }
  8925. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8926. if (conn->path_info == NULL) {
  8927. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8928. } else {
  8929. addenv(env,
  8930. "PATH_TRANSLATED=%s%s",
  8931. conn->dom_ctx->config[DOCUMENT_ROOT],
  8932. conn->path_info);
  8933. }
  8934. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8935. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8936. addenv(env, "CONTENT_TYPE=%s", s);
  8937. }
  8938. if (conn->request_info.query_string != NULL) {
  8939. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8940. }
  8941. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8942. addenv(env, "CONTENT_LENGTH=%s", s);
  8943. }
  8944. if ((s = getenv("PATH")) != NULL) {
  8945. addenv(env, "PATH=%s", s);
  8946. }
  8947. if (conn->path_info != NULL) {
  8948. addenv(env, "PATH_INFO=%s", conn->path_info);
  8949. }
  8950. if (conn->status_code > 0) {
  8951. /* CGI error handler should show the status code */
  8952. addenv(env, "STATUS=%d", conn->status_code);
  8953. }
  8954. #if defined(_WIN32)
  8955. if ((s = getenv("COMSPEC")) != NULL) {
  8956. addenv(env, "COMSPEC=%s", s);
  8957. }
  8958. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8959. addenv(env, "SYSTEMROOT=%s", s);
  8960. }
  8961. if ((s = getenv("SystemDrive")) != NULL) {
  8962. addenv(env, "SystemDrive=%s", s);
  8963. }
  8964. if ((s = getenv("ProgramFiles")) != NULL) {
  8965. addenv(env, "ProgramFiles=%s", s);
  8966. }
  8967. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8968. addenv(env, "ProgramFiles(x86)=%s", s);
  8969. }
  8970. #else
  8971. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8972. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8973. }
  8974. #endif /* _WIN32 */
  8975. if ((s = getenv("PERLLIB")) != NULL) {
  8976. addenv(env, "PERLLIB=%s", s);
  8977. }
  8978. if (conn->request_info.remote_user != NULL) {
  8979. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8980. addenv(env, "%s", "AUTH_TYPE=Digest");
  8981. }
  8982. /* Add all headers as HTTP_* variables */
  8983. for (i = 0; i < conn->request_info.num_headers; i++) {
  8984. (void)mg_snprintf(conn,
  8985. &truncated,
  8986. http_var_name,
  8987. sizeof(http_var_name),
  8988. "HTTP_%s",
  8989. conn->request_info.http_headers[i].name);
  8990. if (truncated) {
  8991. mg_cry_internal(conn,
  8992. "%s: HTTP header variable too long [%s]",
  8993. __func__,
  8994. conn->request_info.http_headers[i].name);
  8995. continue;
  8996. }
  8997. /* Convert variable name into uppercase, and change - to _ */
  8998. for (p = http_var_name; *p != '\0'; p++) {
  8999. if (*p == '-') {
  9000. *p = '_';
  9001. }
  9002. *p = (char)toupper(*(unsigned char *)p);
  9003. }
  9004. addenv(env,
  9005. "%s=%s",
  9006. http_var_name,
  9007. conn->request_info.http_headers[i].value);
  9008. }
  9009. /* Add user-specified variables */
  9010. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  9011. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  9012. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  9013. }
  9014. env->var[env->varused] = NULL;
  9015. env->buf[env->bufused] = '\0';
  9016. return 0;
  9017. }
  9018. static void
  9019. handle_cgi_request(struct mg_connection *conn, const char *prog)
  9020. {
  9021. char *buf;
  9022. size_t buflen;
  9023. int headers_len, data_len, i, truncated;
  9024. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  9025. const char *status, *status_text, *connection_state;
  9026. char *pbuf, dir[PATH_MAX], *p;
  9027. struct mg_request_info ri;
  9028. struct cgi_environment blk;
  9029. FILE *in = NULL, *out = NULL, *err = NULL;
  9030. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  9031. pid_t pid = (pid_t)-1;
  9032. if (conn == NULL) {
  9033. return;
  9034. }
  9035. buf = NULL;
  9036. buflen = conn->phys_ctx->max_request_size;
  9037. i = prepare_cgi_environment(conn, prog, &blk);
  9038. if (i != 0) {
  9039. blk.buf = NULL;
  9040. blk.var = NULL;
  9041. goto done;
  9042. }
  9043. /* CGI must be executed in its own directory. 'dir' must point to the
  9044. * directory containing executable program, 'p' must point to the
  9045. * executable program name relative to 'dir'. */
  9046. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  9047. if (truncated) {
  9048. mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog);
  9049. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  9050. goto done;
  9051. }
  9052. if ((p = strrchr(dir, '/')) != NULL) {
  9053. *p++ = '\0';
  9054. } else {
  9055. dir[0] = '.';
  9056. dir[1] = '\0';
  9057. p = (char *)prog;
  9058. }
  9059. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  9060. status = strerror(ERRNO);
  9061. mg_cry_internal(
  9062. conn,
  9063. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  9064. prog,
  9065. status);
  9066. mg_send_http_error(conn,
  9067. 500,
  9068. "Error: Cannot create CGI pipe: %s",
  9069. status);
  9070. goto done;
  9071. }
  9072. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  9073. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  9074. if (pid == (pid_t)-1) {
  9075. status = strerror(ERRNO);
  9076. mg_cry_internal(
  9077. conn,
  9078. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  9079. prog,
  9080. status);
  9081. mg_send_http_error(conn,
  9082. 500,
  9083. "Error: Cannot spawn CGI process [%s]: %s",
  9084. prog,
  9085. status);
  9086. goto done;
  9087. }
  9088. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  9089. */
  9090. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  9091. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  9092. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  9093. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  9094. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  9095. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  9096. /* Parent closes only one side of the pipes.
  9097. * If we don't mark them as closed, close() attempt before
  9098. * return from this function throws an exception on Windows.
  9099. * Windows does not like when closed descriptor is closed again. */
  9100. (void)close(fdin[0]);
  9101. (void)close(fdout[1]);
  9102. (void)close(fderr[1]);
  9103. fdin[0] = fdout[1] = fderr[1] = -1;
  9104. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  9105. status = strerror(ERRNO);
  9106. mg_cry_internal(conn,
  9107. "Error: CGI program \"%s\": Can not open stdin: %s",
  9108. prog,
  9109. status);
  9110. mg_send_http_error(conn,
  9111. 500,
  9112. "Error: CGI can not open fdin\nfopen: %s",
  9113. status);
  9114. goto done;
  9115. }
  9116. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  9117. status = strerror(ERRNO);
  9118. mg_cry_internal(conn,
  9119. "Error: CGI program \"%s\": Can not open stdout: %s",
  9120. prog,
  9121. status);
  9122. mg_send_http_error(conn,
  9123. 500,
  9124. "Error: CGI can not open fdout\nfopen: %s",
  9125. status);
  9126. goto done;
  9127. }
  9128. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  9129. status = strerror(ERRNO);
  9130. mg_cry_internal(conn,
  9131. "Error: CGI program \"%s\": Can not open stderr: %s",
  9132. prog,
  9133. status);
  9134. mg_send_http_error(conn,
  9135. 500,
  9136. "Error: CGI can not open fderr\nfopen: %s",
  9137. status);
  9138. goto done;
  9139. }
  9140. setbuf(in, NULL);
  9141. setbuf(out, NULL);
  9142. setbuf(err, NULL);
  9143. fout.access.fp = out;
  9144. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  9145. DEBUG_TRACE("CGI: send body data (%lli)\n",
  9146. (signed long long)conn->request_info.content_length);
  9147. /* This is a POST/PUT request, or another request with body data. */
  9148. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  9149. /* Error sending the body data */
  9150. mg_cry_internal(
  9151. conn,
  9152. "Error: CGI program \"%s\": Forward body data failed",
  9153. prog);
  9154. goto done;
  9155. }
  9156. }
  9157. /* Close so child gets an EOF. */
  9158. fclose(in);
  9159. in = NULL;
  9160. fdin[1] = -1;
  9161. /* Now read CGI reply into a buffer. We need to set correct
  9162. * status code, thus we need to see all HTTP headers first.
  9163. * Do not send anything back to client, until we buffer in all
  9164. * HTTP headers. */
  9165. data_len = 0;
  9166. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  9167. if (buf == NULL) {
  9168. mg_send_http_error(conn,
  9169. 500,
  9170. "Error: Not enough memory for CGI buffer (%u bytes)",
  9171. (unsigned int)buflen);
  9172. mg_cry_internal(
  9173. conn,
  9174. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  9175. "bytes)",
  9176. prog,
  9177. (unsigned int)buflen);
  9178. goto done;
  9179. }
  9180. DEBUG_TRACE("CGI: %s", "wait for response");
  9181. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  9182. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  9183. if (headers_len <= 0) {
  9184. /* Could not parse the CGI response. Check if some error message on
  9185. * stderr. */
  9186. i = pull_all(err, conn, buf, (int)buflen);
  9187. if (i > 0) {
  9188. /* CGI program explicitly sent an error */
  9189. /* Write the error message to the internal log */
  9190. mg_cry_internal(conn,
  9191. "Error: CGI program \"%s\" sent error "
  9192. "message: [%.*s]",
  9193. prog,
  9194. i,
  9195. buf);
  9196. /* Don't send the error message back to the client */
  9197. mg_send_http_error(conn,
  9198. 500,
  9199. "Error: CGI program \"%s\" failed.",
  9200. prog);
  9201. } else {
  9202. /* CGI program did not explicitly send an error, but a broken
  9203. * respon header */
  9204. mg_cry_internal(conn,
  9205. "Error: CGI program sent malformed or too big "
  9206. "(>%u bytes) HTTP headers: [%.*s]",
  9207. (unsigned)buflen,
  9208. data_len,
  9209. buf);
  9210. mg_send_http_error(conn,
  9211. 500,
  9212. "Error: CGI program sent malformed or too big "
  9213. "(>%u bytes) HTTP headers: [%.*s]",
  9214. (unsigned)buflen,
  9215. data_len,
  9216. buf);
  9217. }
  9218. /* in both cases, abort processing CGI */
  9219. goto done;
  9220. }
  9221. pbuf = buf;
  9222. buf[headers_len - 1] = '\0';
  9223. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  9224. /* Make up and send the status line */
  9225. status_text = "OK";
  9226. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  9227. != NULL) {
  9228. conn->status_code = atoi(status);
  9229. status_text = status;
  9230. while (isdigit(*(const unsigned char *)status_text)
  9231. || *status_text == ' ') {
  9232. status_text++;
  9233. }
  9234. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  9235. != NULL) {
  9236. conn->status_code = 302;
  9237. } else {
  9238. conn->status_code = 200;
  9239. }
  9240. connection_state =
  9241. get_header(ri.http_headers, ri.num_headers, "Connection");
  9242. if (!header_has_option(connection_state, "keep-alive")) {
  9243. conn->must_close = 1;
  9244. }
  9245. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  9246. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  9247. /* Send headers */
  9248. for (i = 0; i < ri.num_headers; i++) {
  9249. mg_printf(conn,
  9250. "%s: %s\r\n",
  9251. ri.http_headers[i].name,
  9252. ri.http_headers[i].value);
  9253. }
  9254. mg_write(conn, "\r\n", 2);
  9255. /* Send chunk of data that may have been read after the headers */
  9256. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  9257. /* Read the rest of CGI output and send to the client */
  9258. DEBUG_TRACE("CGI: %s", "forward all data");
  9259. send_file_data(conn, &fout, 0, INT64_MAX);
  9260. DEBUG_TRACE("CGI: %s", "all data sent");
  9261. done:
  9262. mg_free(blk.var);
  9263. mg_free(blk.buf);
  9264. if (pid != (pid_t)-1) {
  9265. kill(pid, SIGKILL);
  9266. #if !defined(_WIN32)
  9267. {
  9268. int st;
  9269. while (waitpid(pid, &st, 0) != -1)
  9270. ; /* clean zombies */
  9271. }
  9272. #endif
  9273. }
  9274. if (fdin[0] != -1) {
  9275. close(fdin[0]);
  9276. }
  9277. if (fdout[1] != -1) {
  9278. close(fdout[1]);
  9279. }
  9280. if (in != NULL) {
  9281. fclose(in);
  9282. } else if (fdin[1] != -1) {
  9283. close(fdin[1]);
  9284. }
  9285. if (out != NULL) {
  9286. fclose(out);
  9287. } else if (fdout[0] != -1) {
  9288. close(fdout[0]);
  9289. }
  9290. if (err != NULL) {
  9291. fclose(err);
  9292. } else if (fderr[0] != -1) {
  9293. close(fderr[0]);
  9294. }
  9295. if (buf != NULL) {
  9296. mg_free(buf);
  9297. }
  9298. }
  9299. #endif /* !NO_CGI */
  9300. #if !defined(NO_FILES)
  9301. static void
  9302. mkcol(struct mg_connection *conn, const char *path)
  9303. {
  9304. int rc, body_len;
  9305. struct de de;
  9306. char date[64];
  9307. time_t curtime = time(NULL);
  9308. if (conn == NULL) {
  9309. return;
  9310. }
  9311. /* TODO (mid): Check the mg_send_http_error situations in this function
  9312. */
  9313. memset(&de.file, 0, sizeof(de.file));
  9314. if (!mg_stat(conn, path, &de.file)) {
  9315. mg_cry_internal(conn,
  9316. "%s: mg_stat(%s) failed: %s",
  9317. __func__,
  9318. path,
  9319. strerror(ERRNO));
  9320. }
  9321. if (de.file.last_modified) {
  9322. /* TODO (mid): This check does not seem to make any sense ! */
  9323. /* TODO (mid): Add a webdav unit test first, before changing
  9324. * anything here. */
  9325. mg_send_http_error(
  9326. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9327. return;
  9328. }
  9329. body_len = conn->data_len - conn->request_len;
  9330. if (body_len > 0) {
  9331. mg_send_http_error(
  9332. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9333. return;
  9334. }
  9335. rc = mg_mkdir(conn, path, 0755);
  9336. if (rc == 0) {
  9337. conn->status_code = 201;
  9338. gmt_time_string(date, sizeof(date), &curtime);
  9339. mg_printf(conn,
  9340. "HTTP/1.1 %d Created\r\n"
  9341. "Date: %s\r\n",
  9342. conn->status_code,
  9343. date);
  9344. send_static_cache_header(conn);
  9345. send_additional_header(conn);
  9346. mg_printf(conn,
  9347. "Content-Length: 0\r\n"
  9348. "Connection: %s\r\n\r\n",
  9349. suggest_connection_header(conn));
  9350. } else {
  9351. if (errno == EEXIST) {
  9352. mg_send_http_error(
  9353. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9354. } else if (errno == EACCES) {
  9355. mg_send_http_error(
  9356. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9357. } else if (errno == ENOENT) {
  9358. mg_send_http_error(
  9359. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9360. } else {
  9361. mg_send_http_error(
  9362. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9363. }
  9364. }
  9365. }
  9366. static void
  9367. put_file(struct mg_connection *conn, const char *path)
  9368. {
  9369. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9370. const char *range;
  9371. int64_t r1, r2;
  9372. int rc;
  9373. char date[64];
  9374. time_t curtime = time(NULL);
  9375. if (conn == NULL) {
  9376. return;
  9377. }
  9378. if (mg_stat(conn, path, &file.stat)) {
  9379. /* File already exists */
  9380. conn->status_code = 200;
  9381. if (file.stat.is_directory) {
  9382. /* This is an already existing directory,
  9383. * so there is nothing to do for the server. */
  9384. rc = 0;
  9385. } else {
  9386. /* File exists and is not a directory. */
  9387. /* Can it be replaced? */
  9388. #if defined(MG_USE_OPEN_FILE)
  9389. if (file.access.membuf != NULL) {
  9390. /* This is an "in-memory" file, that can not be replaced */
  9391. mg_send_http_error(conn,
  9392. 405,
  9393. "Error: Put not possible\nReplacing %s "
  9394. "is not supported",
  9395. path);
  9396. return;
  9397. }
  9398. #endif
  9399. /* Check if the server may write this file */
  9400. if (access(path, W_OK) == 0) {
  9401. /* Access granted */
  9402. conn->status_code = 200;
  9403. rc = 1;
  9404. } else {
  9405. mg_send_http_error(
  9406. conn,
  9407. 403,
  9408. "Error: Put not possible\nReplacing %s is not allowed",
  9409. path);
  9410. return;
  9411. }
  9412. }
  9413. } else {
  9414. /* File should be created */
  9415. conn->status_code = 201;
  9416. rc = put_dir(conn, path);
  9417. }
  9418. if (rc == 0) {
  9419. /* put_dir returns 0 if path is a directory */
  9420. gmt_time_string(date, sizeof(date), &curtime);
  9421. mg_printf(conn,
  9422. "HTTP/1.1 %d %s\r\n",
  9423. conn->status_code,
  9424. mg_get_response_code_text(NULL, conn->status_code));
  9425. send_no_cache_header(conn);
  9426. send_additional_header(conn);
  9427. mg_printf(conn,
  9428. "Date: %s\r\n"
  9429. "Content-Length: 0\r\n"
  9430. "Connection: %s\r\n\r\n",
  9431. date,
  9432. suggest_connection_header(conn));
  9433. /* Request to create a directory has been fulfilled successfully.
  9434. * No need to put a file. */
  9435. return;
  9436. }
  9437. if (rc == -1) {
  9438. /* put_dir returns -1 if the path is too long */
  9439. mg_send_http_error(conn,
  9440. 414,
  9441. "Error: Path too long\nput_dir(%s): %s",
  9442. path,
  9443. strerror(ERRNO));
  9444. return;
  9445. }
  9446. if (rc == -2) {
  9447. /* put_dir returns -2 if the directory can not be created */
  9448. mg_send_http_error(conn,
  9449. 500,
  9450. "Error: Can not create directory\nput_dir(%s): %s",
  9451. path,
  9452. strerror(ERRNO));
  9453. return;
  9454. }
  9455. /* A file should be created or overwritten. */
  9456. /* Currently CivetWeb does not nead read+write access. */
  9457. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9458. || file.access.fp == NULL) {
  9459. (void)mg_fclose(&file.access);
  9460. mg_send_http_error(conn,
  9461. 500,
  9462. "Error: Can not create file\nfopen(%s): %s",
  9463. path,
  9464. strerror(ERRNO));
  9465. return;
  9466. }
  9467. fclose_on_exec(&file.access, conn);
  9468. range = mg_get_header(conn, "Content-Range");
  9469. r1 = r2 = 0;
  9470. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9471. conn->status_code = 206; /* Partial content */
  9472. fseeko(file.access.fp, r1, SEEK_SET);
  9473. }
  9474. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9475. /* forward_body_data failed.
  9476. * The error code has already been sent to the client,
  9477. * and conn->status_code is already set. */
  9478. (void)mg_fclose(&file.access);
  9479. return;
  9480. }
  9481. if (mg_fclose(&file.access) != 0) {
  9482. /* fclose failed. This might have different reasons, but a likely
  9483. * one is "no space on disk", http 507. */
  9484. conn->status_code = 507;
  9485. }
  9486. gmt_time_string(date, sizeof(date), &curtime);
  9487. mg_printf(conn,
  9488. "HTTP/1.1 %d %s\r\n",
  9489. conn->status_code,
  9490. mg_get_response_code_text(NULL, conn->status_code));
  9491. send_no_cache_header(conn);
  9492. send_additional_header(conn);
  9493. mg_printf(conn,
  9494. "Date: %s\r\n"
  9495. "Content-Length: 0\r\n"
  9496. "Connection: %s\r\n\r\n",
  9497. date,
  9498. suggest_connection_header(conn));
  9499. }
  9500. static void
  9501. delete_file(struct mg_connection *conn, const char *path)
  9502. {
  9503. struct de de;
  9504. memset(&de.file, 0, sizeof(de.file));
  9505. if (!mg_stat(conn, path, &de.file)) {
  9506. /* mg_stat returns 0 if the file does not exist */
  9507. mg_send_http_error(conn,
  9508. 404,
  9509. "Error: Cannot delete file\nFile %s not found",
  9510. path);
  9511. return;
  9512. }
  9513. #if 0 /* Ignore if a file in memory is inside a folder */
  9514. if (de.access.membuf != NULL) {
  9515. /* the file is cached in memory */
  9516. mg_send_http_error(
  9517. conn,
  9518. 405,
  9519. "Error: Delete not possible\nDeleting %s is not supported",
  9520. path);
  9521. return;
  9522. }
  9523. #endif
  9524. if (de.file.is_directory) {
  9525. if (remove_directory(conn, path)) {
  9526. /* Delete is successful: Return 204 without content. */
  9527. mg_send_http_error(conn, 204, "%s", "");
  9528. } else {
  9529. /* Delete is not successful: Return 500 (Server error). */
  9530. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9531. }
  9532. return;
  9533. }
  9534. /* This is an existing file (not a directory).
  9535. * Check if write permission is granted. */
  9536. if (access(path, W_OK) != 0) {
  9537. /* File is read only */
  9538. mg_send_http_error(
  9539. conn,
  9540. 403,
  9541. "Error: Delete not possible\nDeleting %s is not allowed",
  9542. path);
  9543. return;
  9544. }
  9545. /* Try to delete it. */
  9546. if (mg_remove(conn, path) == 0) {
  9547. /* Delete was successful: Return 204 without content. */
  9548. mg_send_http_error(conn, 204, "%s", "");
  9549. } else {
  9550. /* Delete not successful (file locked). */
  9551. mg_send_http_error(conn,
  9552. 423,
  9553. "Error: Cannot delete file\nremove(%s): %s",
  9554. path,
  9555. strerror(ERRNO));
  9556. }
  9557. }
  9558. #endif /* !NO_FILES */
  9559. static void
  9560. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9561. static void
  9562. do_ssi_include(struct mg_connection *conn,
  9563. const char *ssi,
  9564. char *tag,
  9565. int include_level)
  9566. {
  9567. char file_name[MG_BUF_LEN], path[512], *p;
  9568. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9569. size_t len;
  9570. int truncated = 0;
  9571. if (conn == NULL) {
  9572. return;
  9573. }
  9574. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9575. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9576. * always < MG_BUF_LEN. */
  9577. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9578. /* File name is relative to the webserver root */
  9579. file_name[511] = 0;
  9580. (void)mg_snprintf(conn,
  9581. &truncated,
  9582. path,
  9583. sizeof(path),
  9584. "%s/%s",
  9585. conn->dom_ctx->config[DOCUMENT_ROOT],
  9586. file_name);
  9587. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9588. /* File name is relative to the webserver working directory
  9589. * or it is absolute system path */
  9590. file_name[511] = 0;
  9591. (void)
  9592. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9593. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9594. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9595. /* File name is relative to the currect document */
  9596. file_name[511] = 0;
  9597. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9598. if (!truncated) {
  9599. if ((p = strrchr(path, '/')) != NULL) {
  9600. p[1] = '\0';
  9601. }
  9602. len = strlen(path);
  9603. (void)mg_snprintf(conn,
  9604. &truncated,
  9605. path + len,
  9606. sizeof(path) - len,
  9607. "%s",
  9608. file_name);
  9609. }
  9610. } else {
  9611. mg_cry_internal(conn, "Bad SSI #include: [%s]", tag);
  9612. return;
  9613. }
  9614. if (truncated) {
  9615. mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag);
  9616. return;
  9617. }
  9618. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9619. mg_cry_internal(conn,
  9620. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9621. tag,
  9622. path,
  9623. strerror(ERRNO));
  9624. } else {
  9625. fclose_on_exec(&file.access, conn);
  9626. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9627. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9628. path) > 0) {
  9629. send_ssi_file(conn, path, &file, include_level + 1);
  9630. } else {
  9631. send_file_data(conn, &file, 0, INT64_MAX);
  9632. }
  9633. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9634. }
  9635. }
  9636. #if !defined(NO_POPEN)
  9637. static void
  9638. do_ssi_exec(struct mg_connection *conn, char *tag)
  9639. {
  9640. char cmd[1024] = "";
  9641. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9642. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9643. mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag);
  9644. } else {
  9645. cmd[1023] = 0;
  9646. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9647. mg_cry_internal(conn,
  9648. "Cannot SSI #exec: [%s]: %s",
  9649. cmd,
  9650. strerror(ERRNO));
  9651. } else {
  9652. send_file_data(conn, &file, 0, INT64_MAX);
  9653. pclose(file.access.fp);
  9654. }
  9655. }
  9656. }
  9657. #endif /* !NO_POPEN */
  9658. static int
  9659. mg_fgetc(struct mg_file *filep, int offset)
  9660. {
  9661. (void)offset; /* unused in case MG_USE_OPEN_FILE is set */
  9662. if (filep == NULL) {
  9663. return EOF;
  9664. }
  9665. #if defined(MG_USE_OPEN_FILE)
  9666. if ((filep->access.membuf != NULL) && (offset >= 0)
  9667. && (((unsigned int)(offset)) < filep->stat.size)) {
  9668. return ((const unsigned char *)filep->access.membuf)[offset];
  9669. } else /* else block below */
  9670. #endif
  9671. if (filep->access.fp != NULL) {
  9672. return fgetc(filep->access.fp);
  9673. } else {
  9674. return EOF;
  9675. }
  9676. }
  9677. static void
  9678. send_ssi_file(struct mg_connection *conn,
  9679. const char *path,
  9680. struct mg_file *filep,
  9681. int include_level)
  9682. {
  9683. char buf[MG_BUF_LEN];
  9684. int ch, offset, len, in_tag, in_ssi_tag;
  9685. if (include_level > 10) {
  9686. mg_cry_internal(conn, "SSI #include level is too deep (%s)", path);
  9687. return;
  9688. }
  9689. in_tag = in_ssi_tag = len = offset = 0;
  9690. /* Read file, byte by byte, and look for SSI include tags */
  9691. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9692. if (in_tag) {
  9693. /* We are in a tag, either SSI tag or html tag */
  9694. if (ch == '>') {
  9695. /* Tag is closing */
  9696. buf[len++] = '>';
  9697. if (in_ssi_tag) {
  9698. /* Handle SSI tag */
  9699. buf[len] = 0;
  9700. if (!memcmp(buf + 5, "include", 7)) {
  9701. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9702. #if !defined(NO_POPEN)
  9703. } else if (!memcmp(buf + 5, "exec", 4)) {
  9704. do_ssi_exec(conn, buf + 9);
  9705. #endif /* !NO_POPEN */
  9706. } else {
  9707. mg_cry_internal(conn,
  9708. "%s: unknown SSI "
  9709. "command: \"%s\"",
  9710. path,
  9711. buf);
  9712. }
  9713. len = 0;
  9714. in_ssi_tag = in_tag = 0;
  9715. } else {
  9716. /* Not an SSI tag */
  9717. /* Flush buffer */
  9718. (void)mg_write(conn, buf, (size_t)len);
  9719. len = 0;
  9720. in_tag = 0;
  9721. }
  9722. } else {
  9723. /* Tag is still open */
  9724. buf[len++] = (char)(ch & 0xff);
  9725. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9726. /* All SSI tags start with <!--# */
  9727. in_ssi_tag = 1;
  9728. }
  9729. if ((len + 2) > (int)sizeof(buf)) {
  9730. /* Tag to long for buffer */
  9731. mg_cry_internal(conn, "%s: tag is too large", path);
  9732. return;
  9733. }
  9734. }
  9735. } else {
  9736. /* We are not in a tag yet. */
  9737. if (ch == '<') {
  9738. /* Tag is opening */
  9739. in_tag = 1;
  9740. if (len > 0) {
  9741. /* Flush current buffer.
  9742. * Buffer is filled with "len" bytes. */
  9743. (void)mg_write(conn, buf, (size_t)len);
  9744. }
  9745. /* Store the < */
  9746. len = 1;
  9747. buf[0] = '<';
  9748. } else {
  9749. /* No Tag */
  9750. /* Add data to buffer */
  9751. buf[len++] = (char)(ch & 0xff);
  9752. /* Flush if buffer is full */
  9753. if (len == (int)sizeof(buf)) {
  9754. mg_write(conn, buf, (size_t)len);
  9755. len = 0;
  9756. }
  9757. }
  9758. }
  9759. }
  9760. /* Send the rest of buffered data */
  9761. if (len > 0) {
  9762. mg_write(conn, buf, (size_t)len);
  9763. }
  9764. }
  9765. static void
  9766. handle_ssi_file_request(struct mg_connection *conn,
  9767. const char *path,
  9768. struct mg_file *filep)
  9769. {
  9770. char date[64];
  9771. time_t curtime = time(NULL);
  9772. const char *cors1, *cors2, *cors3;
  9773. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  9774. return;
  9775. }
  9776. if (mg_get_header(conn, "Origin")) {
  9777. /* Cross-origin resource sharing (CORS). */
  9778. cors1 = "Access-Control-Allow-Origin: ";
  9779. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9780. cors3 = "\r\n";
  9781. } else {
  9782. cors1 = cors2 = cors3 = "";
  9783. }
  9784. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9785. /* File exists (precondition for calling this function),
  9786. * but can not be opened by the server. */
  9787. mg_send_http_error(conn,
  9788. 500,
  9789. "Error: Cannot read file\nfopen(%s): %s",
  9790. path,
  9791. strerror(ERRNO));
  9792. } else {
  9793. conn->must_close = 1;
  9794. gmt_time_string(date, sizeof(date), &curtime);
  9795. fclose_on_exec(&filep->access, conn);
  9796. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  9797. send_no_cache_header(conn);
  9798. send_additional_header(conn);
  9799. mg_printf(conn,
  9800. "%s%s%s"
  9801. "Date: %s\r\n"
  9802. "Content-Type: text/html\r\n"
  9803. "Connection: %s\r\n\r\n",
  9804. cors1,
  9805. cors2,
  9806. cors3,
  9807. date,
  9808. suggest_connection_header(conn));
  9809. send_ssi_file(conn, path, filep, 0);
  9810. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  9811. }
  9812. }
  9813. #if !defined(NO_FILES)
  9814. static void
  9815. send_options(struct mg_connection *conn)
  9816. {
  9817. char date[64];
  9818. time_t curtime = time(NULL);
  9819. if (!conn) {
  9820. return;
  9821. }
  9822. conn->status_code = 200;
  9823. conn->must_close = 1;
  9824. gmt_time_string(date, sizeof(date), &curtime);
  9825. /* We do not set a "Cache-Control" header here, but leave the default.
  9826. * Since browsers do not send an OPTIONS request, we can not test the
  9827. * effect anyway. */
  9828. mg_printf(conn,
  9829. "HTTP/1.1 200 OK\r\n"
  9830. "Date: %s\r\n"
  9831. "Connection: %s\r\n"
  9832. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  9833. "PROPFIND, MKCOL\r\n"
  9834. "DAV: 1\r\n",
  9835. date,
  9836. suggest_connection_header(conn));
  9837. send_additional_header(conn);
  9838. mg_printf(conn, "\r\n");
  9839. }
  9840. /* Writes PROPFIND properties for a collection element */
  9841. static void
  9842. print_props(struct mg_connection *conn,
  9843. const char *uri,
  9844. struct mg_file_stat *filep)
  9845. {
  9846. char mtime[64];
  9847. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  9848. return;
  9849. }
  9850. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  9851. mg_printf(conn,
  9852. "<d:response>"
  9853. "<d:href>%s</d:href>"
  9854. "<d:propstat>"
  9855. "<d:prop>"
  9856. "<d:resourcetype>%s</d:resourcetype>"
  9857. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  9858. "<d:getlastmodified>%s</d:getlastmodified>"
  9859. "</d:prop>"
  9860. "<d:status>HTTP/1.1 200 OK</d:status>"
  9861. "</d:propstat>"
  9862. "</d:response>\n",
  9863. uri,
  9864. filep->is_directory ? "<d:collection/>" : "",
  9865. filep->size,
  9866. mtime);
  9867. }
  9868. static int
  9869. print_dav_dir_entry(struct de *de, void *data)
  9870. {
  9871. char href[PATH_MAX];
  9872. int truncated;
  9873. struct mg_connection *conn = (struct mg_connection *)data;
  9874. if (!de || !conn) {
  9875. return -1;
  9876. }
  9877. mg_snprintf(conn,
  9878. &truncated,
  9879. href,
  9880. sizeof(href),
  9881. "%s%s",
  9882. conn->request_info.local_uri,
  9883. de->file_name);
  9884. if (!truncated) {
  9885. size_t href_encoded_size;
  9886. char *href_encoded;
  9887. href_encoded_size = PATH_MAX * 3; /* worst case */
  9888. href_encoded = (char *)mg_malloc(href_encoded_size);
  9889. if (href_encoded == NULL) {
  9890. return -1;
  9891. }
  9892. mg_url_encode(href, href_encoded, href_encoded_size);
  9893. print_props(conn, href_encoded, &de->file);
  9894. mg_free(href_encoded);
  9895. }
  9896. return 0;
  9897. }
  9898. static void
  9899. handle_propfind(struct mg_connection *conn,
  9900. const char *path,
  9901. struct mg_file_stat *filep)
  9902. {
  9903. const char *depth = mg_get_header(conn, "Depth");
  9904. char date[64];
  9905. time_t curtime = time(NULL);
  9906. gmt_time_string(date, sizeof(date), &curtime);
  9907. if (!conn || !path || !filep || !conn->dom_ctx) {
  9908. return;
  9909. }
  9910. conn->must_close = 1;
  9911. conn->status_code = 207;
  9912. mg_printf(conn,
  9913. "HTTP/1.1 207 Multi-Status\r\n"
  9914. "Date: %s\r\n",
  9915. date);
  9916. send_static_cache_header(conn);
  9917. send_additional_header(conn);
  9918. mg_printf(conn,
  9919. "Connection: %s\r\n"
  9920. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9921. suggest_connection_header(conn));
  9922. mg_printf(conn,
  9923. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9924. "<d:multistatus xmlns:d='DAV:'>\n");
  9925. /* Print properties for the requested resource itself */
  9926. print_props(conn, conn->request_info.local_uri, filep);
  9927. /* If it is a directory, print directory entries too if Depth is not 0
  9928. */
  9929. if (filep->is_directory
  9930. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9931. "yes")
  9932. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9933. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9934. }
  9935. mg_printf(conn, "%s\n", "</d:multistatus>");
  9936. }
  9937. #endif
  9938. void
  9939. mg_lock_connection(struct mg_connection *conn)
  9940. {
  9941. if (conn) {
  9942. (void)pthread_mutex_lock(&conn->mutex);
  9943. }
  9944. }
  9945. void
  9946. mg_unlock_connection(struct mg_connection *conn)
  9947. {
  9948. if (conn) {
  9949. (void)pthread_mutex_unlock(&conn->mutex);
  9950. }
  9951. }
  9952. void
  9953. mg_lock_context(struct mg_context *ctx)
  9954. {
  9955. if (ctx) {
  9956. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9957. }
  9958. }
  9959. void
  9960. mg_unlock_context(struct mg_context *ctx)
  9961. {
  9962. if (ctx) {
  9963. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9964. }
  9965. }
  9966. #if defined(USE_TIMERS)
  9967. #define TIMER_API static
  9968. #include "timer.inl"
  9969. #endif /* USE_TIMERS */
  9970. #if defined(USE_LUA)
  9971. #include "mod_lua.inl"
  9972. #endif /* USE_LUA */
  9973. #if defined(USE_DUKTAPE)
  9974. #include "mod_duktape.inl"
  9975. #endif /* USE_DUKTAPE */
  9976. #if defined(USE_WEBSOCKET)
  9977. #if !defined(NO_SSL_DL)
  9978. #define SHA_API static
  9979. #include "sha1.inl"
  9980. #endif
  9981. static int
  9982. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9983. {
  9984. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9985. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9986. SHA_CTX sha_ctx;
  9987. int truncated;
  9988. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9989. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9990. if (truncated) {
  9991. conn->must_close = 1;
  9992. return 0;
  9993. }
  9994. DEBUG_TRACE("%s", "Send websocket handshake");
  9995. SHA1_Init(&sha_ctx);
  9996. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9997. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9998. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9999. mg_printf(conn,
  10000. "HTTP/1.1 101 Switching Protocols\r\n"
  10001. "Upgrade: websocket\r\n"
  10002. "Connection: Upgrade\r\n"
  10003. "Sec-WebSocket-Accept: %s\r\n",
  10004. b64_sha);
  10005. if (conn->request_info.acceptedWebSocketSubprotocol) {
  10006. mg_printf(conn,
  10007. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  10008. conn->request_info.acceptedWebSocketSubprotocol);
  10009. } else {
  10010. mg_printf(conn, "%s", "\r\n");
  10011. }
  10012. return 1;
  10013. }
  10014. #if !defined(MG_MAX_UNANSWERED_PING)
  10015. /* Configuration of the maximum number of websocket PINGs that might
  10016. * stay unanswered before the connection is considered broken.
  10017. * Note: The name of this define may still change (until it is
  10018. * defined as a compile parameter in a documentation).
  10019. */
  10020. #define MG_MAX_UNANSWERED_PING (5)
  10021. #endif
  10022. static void
  10023. read_websocket(struct mg_connection *conn,
  10024. mg_websocket_data_handler ws_data_handler,
  10025. void *callback_data)
  10026. {
  10027. /* Pointer to the beginning of the portion of the incoming websocket
  10028. * message queue.
  10029. * The original websocket upgrade request is never removed, so the queue
  10030. * begins after it. */
  10031. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  10032. int n, error, exit_by_callback;
  10033. int ret;
  10034. /* body_len is the length of the entire queue in bytes
  10035. * len is the length of the current message
  10036. * data_len is the length of the current message's data payload
  10037. * header_len is the length of the current message's header */
  10038. size_t i, len, mask_len = 0, header_len, body_len;
  10039. uint64_t data_len = 0;
  10040. /* "The masking key is a 32-bit value chosen at random by the client."
  10041. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  10042. */
  10043. unsigned char mask[4];
  10044. /* data points to the place where the message is stored when passed to
  10045. * the websocket_data callback. This is either mem on the stack, or a
  10046. * dynamically allocated buffer if it is too large. */
  10047. unsigned char mem[4096];
  10048. unsigned char mop; /* mask flag and opcode */
  10049. /* Variables used for connection monitoring */
  10050. double timeout = -1.0;
  10051. int enable_ping_pong = 0;
  10052. int ping_count = 0;
  10053. if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) {
  10054. enable_ping_pong =
  10055. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG],
  10056. "yes");
  10057. }
  10058. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  10059. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  10060. }
  10061. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  10062. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  10063. }
  10064. /* Enter data processing loop */
  10065. DEBUG_TRACE("Websocket connection %s:%u start data processing loop",
  10066. conn->request_info.remote_addr,
  10067. conn->request_info.remote_port);
  10068. conn->in_websocket_handling = 1;
  10069. mg_set_thread_name("wsock");
  10070. /* Loop continuously, reading messages from the socket, invoking the
  10071. * callback, and waiting repeatedly until an error occurs. */
  10072. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10073. header_len = 0;
  10074. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  10075. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  10076. len = buf[1] & 127;
  10077. mask_len = (buf[1] & 128) ? 4 : 0;
  10078. if ((len < 126) && (body_len >= mask_len)) {
  10079. /* inline 7-bit length field */
  10080. data_len = len;
  10081. header_len = 2 + mask_len;
  10082. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  10083. /* 16-bit length field */
  10084. header_len = 4 + mask_len;
  10085. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  10086. } else if (body_len >= (10 + mask_len)) {
  10087. /* 64-bit length field */
  10088. uint32_t l1, l2;
  10089. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  10090. memcpy(&l2, &buf[6], 4);
  10091. header_len = 10 + mask_len;
  10092. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  10093. if (data_len > (uint64_t)0x7FFF0000ul) {
  10094. /* no can do */
  10095. mg_cry_internal(
  10096. conn,
  10097. "%s",
  10098. "websocket out of memory; closing connection");
  10099. break;
  10100. }
  10101. }
  10102. }
  10103. if ((header_len > 0) && (body_len >= header_len)) {
  10104. /* Allocate space to hold websocket payload */
  10105. unsigned char *data = mem;
  10106. if ((size_t)data_len > (size_t)sizeof(mem)) {
  10107. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  10108. conn->phys_ctx);
  10109. if (data == NULL) {
  10110. /* Allocation failed, exit the loop and then close the
  10111. * connection */
  10112. mg_cry_internal(
  10113. conn,
  10114. "%s",
  10115. "websocket out of memory; closing connection");
  10116. break;
  10117. }
  10118. }
  10119. /* Copy the mask before we shift the queue and destroy it */
  10120. if (mask_len > 0) {
  10121. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  10122. } else {
  10123. memset(mask, 0, sizeof(mask));
  10124. }
  10125. /* Read frame payload from the first message in the queue into
  10126. * data and advance the queue by moving the memory in place. */
  10127. DEBUG_ASSERT(body_len >= header_len);
  10128. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  10129. mop = buf[0]; /* current mask and opcode */
  10130. /* Overflow case */
  10131. len = body_len - header_len;
  10132. memcpy(data, buf + header_len, len);
  10133. error = 0;
  10134. while ((uint64_t)len < data_len) {
  10135. n = pull_inner(NULL,
  10136. conn,
  10137. (char *)(data + len),
  10138. (int)(data_len - len),
  10139. timeout);
  10140. if (n <= -2) {
  10141. error = 1;
  10142. break;
  10143. } else if (n > 0) {
  10144. len += (size_t)n;
  10145. } else {
  10146. /* Timeout: should retry */
  10147. /* TODO: retry condition */
  10148. }
  10149. }
  10150. if (error) {
  10151. mg_cry_internal(
  10152. conn,
  10153. "%s",
  10154. "Websocket pull failed; closing connection");
  10155. if (data != mem) {
  10156. mg_free(data);
  10157. }
  10158. break;
  10159. }
  10160. conn->data_len = conn->request_len;
  10161. } else {
  10162. mop = buf[0]; /* current mask and opcode, overwritten by
  10163. * memmove() */
  10164. /* Length of the message being read at the front of the
  10165. * queue. Cast to 31 bit is OK, since we limited
  10166. * data_len before. */
  10167. len = (size_t)data_len + header_len;
  10168. /* Copy the data payload into the data pointer for the
  10169. * callback. Cast to 31 bit is OK, since we
  10170. * limited data_len */
  10171. memcpy(data, buf + header_len, (size_t)data_len);
  10172. /* Move the queue forward len bytes */
  10173. memmove(buf, buf + len, body_len - len);
  10174. /* Mark the queue as advanced */
  10175. conn->data_len -= (int)len;
  10176. }
  10177. /* Apply mask if necessary */
  10178. if (mask_len > 0) {
  10179. for (i = 0; i < (size_t)data_len; i++) {
  10180. data[i] ^= mask[i & 3];
  10181. }
  10182. }
  10183. exit_by_callback = 0;
  10184. if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) {
  10185. /* filter PONG messages */
  10186. DEBUG_TRACE("PONG from %s:%u",
  10187. conn->request_info.remote_addr,
  10188. conn->request_info.remote_port);
  10189. /* No unanwered PINGs left */
  10190. ping_count = 0;
  10191. } else if (enable_ping_pong
  10192. && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) {
  10193. /* reply PING messages */
  10194. DEBUG_TRACE("Reply PING from %s:%u",
  10195. conn->request_info.remote_addr,
  10196. conn->request_info.remote_port);
  10197. ret = mg_websocket_write(conn,
  10198. MG_WEBSOCKET_OPCODE_PONG,
  10199. (char *)data,
  10200. (size_t)data_len);
  10201. if (ret <= 0) {
  10202. /* Error: send failed */
  10203. DEBUG_TRACE("Reply PONG failed (%i)", ret);
  10204. break;
  10205. }
  10206. } else {
  10207. /* Exit the loop if callback signals to exit (server side),
  10208. * or "connection close" opcode received (client side). */
  10209. if ((ws_data_handler != NULL)
  10210. && !ws_data_handler(conn,
  10211. mop,
  10212. (char *)data,
  10213. (size_t)data_len,
  10214. callback_data)) {
  10215. exit_by_callback = 1;
  10216. }
  10217. }
  10218. /* It a buffer has been allocated, free it again */
  10219. if (data != mem) {
  10220. mg_free(data);
  10221. }
  10222. if (exit_by_callback) {
  10223. DEBUG_TRACE("Callback requests to close connection from %s:%u",
  10224. conn->request_info.remote_addr,
  10225. conn->request_info.remote_port);
  10226. break;
  10227. }
  10228. if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  10229. /* Opcode == 8, connection close */
  10230. DEBUG_TRACE("Message requests to close connection from %s:%u",
  10231. conn->request_info.remote_addr,
  10232. conn->request_info.remote_port);
  10233. break;
  10234. }
  10235. /* Not breaking the loop, process next websocket frame. */
  10236. } else {
  10237. /* Read from the socket into the next available location in the
  10238. * message queue. */
  10239. n = pull_inner(NULL,
  10240. conn,
  10241. conn->buf + conn->data_len,
  10242. conn->buf_size - conn->data_len,
  10243. timeout);
  10244. if (n <= -2) {
  10245. /* Error, no bytes read */
  10246. DEBUG_TRACE("PULL from %s:%u failed",
  10247. conn->request_info.remote_addr,
  10248. conn->request_info.remote_port);
  10249. break;
  10250. }
  10251. if (n > 0) {
  10252. conn->data_len += n;
  10253. /* Reset open PING count */
  10254. ping_count = 0;
  10255. } else {
  10256. if (!conn->phys_ctx->stop_flag && !conn->must_close) {
  10257. if (ping_count > MG_MAX_UNANSWERED_PING) {
  10258. /* Stop sending PING */
  10259. DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u "
  10260. "- closing connection",
  10261. ping_count,
  10262. conn->request_info.remote_addr,
  10263. conn->request_info.remote_port);
  10264. break;
  10265. }
  10266. if (enable_ping_pong) {
  10267. /* Send Websocket PING message */
  10268. DEBUG_TRACE("PING to %s:%u",
  10269. conn->request_info.remote_addr,
  10270. conn->request_info.remote_port);
  10271. ret = mg_websocket_write(conn,
  10272. MG_WEBSOCKET_OPCODE_PING,
  10273. NULL,
  10274. 0);
  10275. if (ret <= 0) {
  10276. /* Error: send failed */
  10277. DEBUG_TRACE("Send PING failed (%i)", ret);
  10278. break;
  10279. }
  10280. ping_count++;
  10281. }
  10282. }
  10283. /* Timeout: should retry */
  10284. /* TODO: get timeout def */
  10285. }
  10286. }
  10287. }
  10288. /* Leave data processing loop */
  10289. mg_set_thread_name("worker");
  10290. conn->in_websocket_handling = 0;
  10291. DEBUG_TRACE("Websocket connection %s:%u left data processing loop",
  10292. conn->request_info.remote_addr,
  10293. conn->request_info.remote_port);
  10294. }
  10295. static int
  10296. mg_websocket_write_exec(struct mg_connection *conn,
  10297. int opcode,
  10298. const char *data,
  10299. size_t dataLen,
  10300. uint32_t masking_key)
  10301. {
  10302. unsigned char header[14];
  10303. size_t headerLen;
  10304. int retval;
  10305. #if defined(__GNUC__) || defined(__MINGW32__)
  10306. /* Disable spurious conversion warning for GCC */
  10307. #pragma GCC diagnostic push
  10308. #pragma GCC diagnostic ignored "-Wconversion"
  10309. #endif
  10310. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  10311. #if defined(__GNUC__) || defined(__MINGW32__)
  10312. #pragma GCC diagnostic pop
  10313. #endif
  10314. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  10315. if (dataLen < 126) {
  10316. /* inline 7-bit length field */
  10317. header[1] = (unsigned char)dataLen;
  10318. headerLen = 2;
  10319. } else if (dataLen <= 0xFFFF) {
  10320. /* 16-bit length field */
  10321. uint16_t len = htons((uint16_t)dataLen);
  10322. header[1] = 126;
  10323. memcpy(header + 2, &len, 2);
  10324. headerLen = 4;
  10325. } else {
  10326. /* 64-bit length field */
  10327. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  10328. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  10329. header[1] = 127;
  10330. memcpy(header + 2, &len1, 4);
  10331. memcpy(header + 6, &len2, 4);
  10332. headerLen = 10;
  10333. }
  10334. if (masking_key) {
  10335. /* add mask */
  10336. header[1] |= 0x80;
  10337. memcpy(header + headerLen, &masking_key, 4);
  10338. headerLen += 4;
  10339. }
  10340. /* Note that POSIX/Winsock's send() is threadsafe
  10341. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  10342. * but mongoose's mg_printf/mg_write is not (because of the loop in
  10343. * push(), although that is only a problem if the packet is large or
  10344. * outgoing buffer is full). */
  10345. /* TODO: Check if this lock should be moved to user land.
  10346. * Currently the server sets this lock for websockets, but
  10347. * not for any other connection. It must be set for every
  10348. * conn read/written by more than one thread, no matter if
  10349. * it is a websocket or regular connection. */
  10350. (void)mg_lock_connection(conn);
  10351. retval = mg_write(conn, header, headerLen);
  10352. if (retval != (int)headerLen) {
  10353. /* Did not send complete header */
  10354. retval = -1;
  10355. } else {
  10356. if (dataLen > 0) {
  10357. retval = mg_write(conn, data, dataLen);
  10358. }
  10359. /* if dataLen == 0, the header length (2) is returned */
  10360. }
  10361. /* TODO: Remove this unlock as well, when lock is removed. */
  10362. mg_unlock_connection(conn);
  10363. return retval;
  10364. }
  10365. int
  10366. mg_websocket_write(struct mg_connection *conn,
  10367. int opcode,
  10368. const char *data,
  10369. size_t dataLen)
  10370. {
  10371. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  10372. }
  10373. static void
  10374. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  10375. {
  10376. size_t i = 0;
  10377. i = 0;
  10378. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  10379. /* Convert in 32 bit words, if data is 4 byte aligned */
  10380. while (i < (in_len - 3)) {
  10381. *(uint32_t *)(void *)(out + i) =
  10382. *(uint32_t *)(void *)(in + i) ^ masking_key;
  10383. i += 4;
  10384. }
  10385. }
  10386. if (i != in_len) {
  10387. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  10388. while (i < in_len) {
  10389. *(uint8_t *)(void *)(out + i) =
  10390. *(uint8_t *)(void *)(in + i)
  10391. ^ *(((uint8_t *)&masking_key) + (i % 4));
  10392. i++;
  10393. }
  10394. }
  10395. }
  10396. int
  10397. mg_websocket_client_write(struct mg_connection *conn,
  10398. int opcode,
  10399. const char *data,
  10400. size_t dataLen)
  10401. {
  10402. int retval = -1;
  10403. char *masked_data =
  10404. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10405. uint32_t masking_key = 0;
  10406. if (masked_data == NULL) {
  10407. /* Return -1 in an error case */
  10408. mg_cry_internal(conn,
  10409. "%s",
  10410. "Cannot allocate buffer for masked websocket response: "
  10411. "Out of memory");
  10412. return -1;
  10413. }
  10414. do {
  10415. /* Get a masking key - but not 0 */
  10416. masking_key = (uint32_t)get_random();
  10417. } while (masking_key == 0);
  10418. mask_data(data, dataLen, masking_key, masked_data);
  10419. retval = mg_websocket_write_exec(
  10420. conn, opcode, masked_data, dataLen, masking_key);
  10421. mg_free(masked_data);
  10422. return retval;
  10423. }
  10424. static void
  10425. handle_websocket_request(struct mg_connection *conn,
  10426. const char *path,
  10427. int is_callback_resource,
  10428. struct mg_websocket_subprotocols *subprotocols,
  10429. mg_websocket_connect_handler ws_connect_handler,
  10430. mg_websocket_ready_handler ws_ready_handler,
  10431. mg_websocket_data_handler ws_data_handler,
  10432. mg_websocket_close_handler ws_close_handler,
  10433. void *cbData)
  10434. {
  10435. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10436. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10437. ptrdiff_t lua_websock = 0;
  10438. #if !defined(USE_LUA)
  10439. (void)path;
  10440. #endif
  10441. /* Step 1: Check websocket protocol version. */
  10442. /* Step 1.1: Check Sec-WebSocket-Key. */
  10443. if (!websock_key) {
  10444. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10445. * requires a Sec-WebSocket-Key header.
  10446. */
  10447. /* It could be the hixie draft version
  10448. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10449. */
  10450. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10451. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10452. char key3[8];
  10453. if ((key1 != NULL) && (key2 != NULL)) {
  10454. /* This version uses 8 byte body data in a GET request */
  10455. conn->content_len = 8;
  10456. if (8 == mg_read(conn, key3, 8)) {
  10457. /* This is the hixie version */
  10458. mg_send_http_error(conn,
  10459. 426,
  10460. "%s",
  10461. "Protocol upgrade to RFC 6455 required");
  10462. return;
  10463. }
  10464. }
  10465. /* This is an unknown version */
  10466. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10467. return;
  10468. }
  10469. /* Step 1.2: Check websocket protocol version. */
  10470. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10471. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10472. /* Reject wrong versions */
  10473. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10474. return;
  10475. }
  10476. /* Step 1.3: Could check for "Host", but we do not really nead this
  10477. * value for anything, so just ignore it. */
  10478. /* Step 2: If a callback is responsible, call it. */
  10479. if (is_callback_resource) {
  10480. /* Step 2.1 check and select subprotocol */
  10481. const char *protocols[64]; // max 64 headers
  10482. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10483. "Sec-WebSocket-Protocol",
  10484. protocols,
  10485. 64);
  10486. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10487. int cnt = 0;
  10488. int idx;
  10489. unsigned long len;
  10490. const char *sep, *curSubProtocol,
  10491. *acceptedWebSocketSubprotocol = NULL;
  10492. /* look for matching subprotocol */
  10493. do {
  10494. const char *protocol = protocols[cnt];
  10495. do {
  10496. sep = strchr(protocol, ',');
  10497. curSubProtocol = protocol;
  10498. len = sep ? (unsigned long)(sep - protocol)
  10499. : (unsigned long)strlen(protocol);
  10500. while (sep && isspace(*++sep))
  10501. ; // ignore leading whitespaces
  10502. protocol = sep;
  10503. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10504. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10505. && (strncmp(curSubProtocol,
  10506. subprotocols->subprotocols[idx],
  10507. len) == 0)) {
  10508. acceptedWebSocketSubprotocol =
  10509. subprotocols->subprotocols[idx];
  10510. break;
  10511. }
  10512. }
  10513. } while (sep && !acceptedWebSocketSubprotocol);
  10514. } while (++cnt < nbSubprotocolHeader
  10515. && !acceptedWebSocketSubprotocol);
  10516. conn->request_info.acceptedWebSocketSubprotocol =
  10517. acceptedWebSocketSubprotocol;
  10518. } else if (nbSubprotocolHeader > 0) {
  10519. /* keep legacy behavior */
  10520. const char *protocol = protocols[0];
  10521. /* The protocol is a comma separated list of names. */
  10522. /* The server must only return one value from this list. */
  10523. /* First check if it is a list or just a single value. */
  10524. const char *sep = strrchr(protocol, ',');
  10525. if (sep == NULL) {
  10526. /* Just a single protocol -> accept it. */
  10527. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10528. } else {
  10529. /* Multiple protocols -> accept the last one. */
  10530. /* This is just a quick fix if the client offers multiple
  10531. * protocols. The handler should have a list of accepted
  10532. * protocols on his own
  10533. * and use it to select one protocol among those the client
  10534. * has
  10535. * offered.
  10536. */
  10537. while (isspace(*++sep)) {
  10538. ; /* ignore leading whitespaces */
  10539. }
  10540. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10541. }
  10542. }
  10543. if ((ws_connect_handler != NULL)
  10544. && (ws_connect_handler(conn, cbData) != 0)) {
  10545. /* C callback has returned non-zero, do not proceed with
  10546. * handshake.
  10547. */
  10548. /* Note that C callbacks are no longer called when Lua is
  10549. * responsible, so C can no longer filter callbacks for Lua. */
  10550. return;
  10551. }
  10552. }
  10553. #if defined(USE_LUA)
  10554. /* Step 3: No callback. Check if Lua is responsible. */
  10555. else {
  10556. /* Step 3.1: Check if Lua is responsible. */
  10557. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10558. lua_websock = match_prefix(
  10559. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10560. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10561. path);
  10562. }
  10563. if (lua_websock) {
  10564. /* Step 3.2: Lua is responsible: call it. */
  10565. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10566. if (!conn->lua_websocket_state) {
  10567. /* Lua rejected the new client */
  10568. return;
  10569. }
  10570. }
  10571. }
  10572. #endif
  10573. /* Step 4: Check if there is a responsible websocket handler. */
  10574. if (!is_callback_resource && !lua_websock) {
  10575. /* There is no callback, and Lua is not responsible either. */
  10576. /* Reply with a 404 Not Found. We are still at a standard
  10577. * HTTP request here, before the websocket handshake, so
  10578. * we can still send standard HTTP error replies. */
  10579. mg_send_http_error(conn, 404, "%s", "Not found");
  10580. return;
  10581. }
  10582. /* Step 5: The websocket connection has been accepted */
  10583. if (!send_websocket_handshake(conn, websock_key)) {
  10584. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10585. return;
  10586. }
  10587. /* Step 6: Call the ready handler */
  10588. if (is_callback_resource) {
  10589. if (ws_ready_handler != NULL) {
  10590. ws_ready_handler(conn, cbData);
  10591. }
  10592. #if defined(USE_LUA)
  10593. } else if (lua_websock) {
  10594. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10595. /* the ready handler returned false */
  10596. return;
  10597. }
  10598. #endif
  10599. }
  10600. /* Step 7: Enter the read loop */
  10601. if (is_callback_resource) {
  10602. read_websocket(conn, ws_data_handler, cbData);
  10603. #if defined(USE_LUA)
  10604. } else if (lua_websock) {
  10605. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10606. #endif
  10607. }
  10608. /* Step 8: Call the close handler */
  10609. if (ws_close_handler) {
  10610. ws_close_handler(conn, cbData);
  10611. }
  10612. }
  10613. static int
  10614. is_websocket_protocol(const struct mg_connection *conn)
  10615. {
  10616. const char *upgrade, *connection;
  10617. /* A websocket protocoll has the following HTTP headers:
  10618. *
  10619. * Connection: Upgrade
  10620. * Upgrade: Websocket
  10621. */
  10622. upgrade = mg_get_header(conn, "Upgrade");
  10623. if (upgrade == NULL) {
  10624. return 0; /* fail early, don't waste time checking other header
  10625. * fields
  10626. */
  10627. }
  10628. if (!mg_strcasestr(upgrade, "websocket")) {
  10629. return 0;
  10630. }
  10631. connection = mg_get_header(conn, "Connection");
  10632. if (connection == NULL) {
  10633. return 0;
  10634. }
  10635. if (!mg_strcasestr(connection, "upgrade")) {
  10636. return 0;
  10637. }
  10638. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10639. * "Sec-WebSocket-Version" are also required.
  10640. * Don't check them here, since even an unsupported websocket protocol
  10641. * request still IS a websocket request (in contrast to a standard HTTP
  10642. * request). It will fail later in handle_websocket_request.
  10643. */
  10644. return 1;
  10645. }
  10646. #endif /* !USE_WEBSOCKET */
  10647. static int
  10648. isbyte(int n)
  10649. {
  10650. return (n >= 0) && (n <= 255);
  10651. }
  10652. static int
  10653. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10654. {
  10655. int n, a, b, c, d, slash = 32, len = 0;
  10656. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10657. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10658. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10659. && (slash < 33)) {
  10660. len = n;
  10661. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10662. | (uint32_t)d;
  10663. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10664. }
  10665. return len;
  10666. }
  10667. static int
  10668. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10669. {
  10670. int throttle = 0;
  10671. struct vec vec, val;
  10672. uint32_t net, mask;
  10673. char mult;
  10674. double v;
  10675. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  10676. mult = ',';
  10677. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  10678. || (v < 0) || ((lowercase(&mult) != 'k')
  10679. && (lowercase(&mult) != 'm') && (mult != ','))) {
  10680. continue;
  10681. }
  10682. v *= (lowercase(&mult) == 'k')
  10683. ? 1024
  10684. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  10685. if (vec.len == 1 && vec.ptr[0] == '*') {
  10686. throttle = (int)v;
  10687. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  10688. if ((remote_ip & mask) == net) {
  10689. throttle = (int)v;
  10690. }
  10691. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  10692. throttle = (int)v;
  10693. }
  10694. }
  10695. return throttle;
  10696. }
  10697. static uint32_t
  10698. get_remote_ip(const struct mg_connection *conn)
  10699. {
  10700. if (!conn) {
  10701. return 0;
  10702. }
  10703. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  10704. }
  10705. /* The mg_upload function is superseeded by mg_handle_form_request. */
  10706. #include "handle_form.inl"
  10707. #if defined(MG_LEGACY_INTERFACE)
  10708. /* Implement the deprecated mg_upload function by calling the new
  10709. * mg_handle_form_request function. While mg_upload could only handle
  10710. * HTML forms sent as POST request in multipart/form-data format
  10711. * containing only file input elements, mg_handle_form_request can
  10712. * handle all form input elements and all standard request methods. */
  10713. struct mg_upload_user_data {
  10714. struct mg_connection *conn;
  10715. const char *destination_dir;
  10716. int num_uploaded_files;
  10717. };
  10718. /* Helper function for deprecated mg_upload. */
  10719. static int
  10720. mg_upload_field_found(const char *key,
  10721. const char *filename,
  10722. char *path,
  10723. size_t pathlen,
  10724. void *user_data)
  10725. {
  10726. int truncated = 0;
  10727. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10728. (void)key;
  10729. if (!filename) {
  10730. mg_cry_internal(fud->conn, "%s: No filename set", __func__);
  10731. return FORM_FIELD_STORAGE_ABORT;
  10732. }
  10733. mg_snprintf(fud->conn,
  10734. &truncated,
  10735. path,
  10736. pathlen - 1,
  10737. "%s/%s",
  10738. fud->destination_dir,
  10739. filename);
  10740. if (truncated) {
  10741. mg_cry_internal(fud->conn, "%s: File path too long", __func__);
  10742. return FORM_FIELD_STORAGE_ABORT;
  10743. }
  10744. return FORM_FIELD_STORAGE_STORE;
  10745. }
  10746. /* Helper function for deprecated mg_upload. */
  10747. static int
  10748. mg_upload_field_get(const char *key,
  10749. const char *value,
  10750. size_t value_size,
  10751. void *user_data)
  10752. {
  10753. /* Function should never be called */
  10754. (void)key;
  10755. (void)value;
  10756. (void)value_size;
  10757. (void)user_data;
  10758. return 0;
  10759. }
  10760. /* Helper function for deprecated mg_upload. */
  10761. static int
  10762. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  10763. {
  10764. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10765. (void)file_size;
  10766. fud->num_uploaded_files++;
  10767. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  10768. return 0;
  10769. }
  10770. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  10771. int
  10772. mg_upload(struct mg_connection *conn, const char *destination_dir)
  10773. {
  10774. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  10775. struct mg_form_data_handler fdh = {mg_upload_field_found,
  10776. mg_upload_field_get,
  10777. mg_upload_field_stored,
  10778. 0};
  10779. int ret;
  10780. fdh.user_data = (void *)&fud;
  10781. ret = mg_handle_form_request(conn, &fdh);
  10782. if (ret < 0) {
  10783. mg_cry_internal(conn, "%s: Error while parsing the request", __func__);
  10784. }
  10785. return fud.num_uploaded_files;
  10786. }
  10787. #endif
  10788. static int
  10789. get_first_ssl_listener_index(const struct mg_context *ctx)
  10790. {
  10791. unsigned int i;
  10792. int idx = -1;
  10793. if (ctx) {
  10794. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  10795. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  10796. }
  10797. }
  10798. return idx;
  10799. }
  10800. /* Return host (without port) */
  10801. /* Use mg_free to free the result */
  10802. static const char *
  10803. alloc_get_host(struct mg_connection *conn)
  10804. {
  10805. char host[1025];
  10806. const char *host_header;
  10807. size_t hostlen;
  10808. host_header = get_header(conn->request_info.http_headers,
  10809. conn->request_info.num_headers,
  10810. "Host");
  10811. hostlen = sizeof(host);
  10812. if (host_header != NULL) {
  10813. char *pos;
  10814. mg_strlcpy(host, host_header, hostlen);
  10815. host[hostlen - 1] = '\0';
  10816. pos = strchr(host, ':');
  10817. if (pos != NULL) {
  10818. *pos = '\0';
  10819. }
  10820. if (conn->ssl) {
  10821. /* This is a HTTPS connection, maybe we have a hostname
  10822. * from SNI (set in ssl_servername_callback). */
  10823. const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  10824. if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) {
  10825. /* We are not using the default domain */
  10826. if (mg_strcasecmp(host, sslhost)) {
  10827. /* Mismatch between SNI domain and HTTP domain */
  10828. DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s",
  10829. sslhost,
  10830. host);
  10831. return NULL;
  10832. }
  10833. }
  10834. DEBUG_TRACE("HTTPS Host: %s", host);
  10835. } else {
  10836. struct mg_domain_context *dom = &(conn->phys_ctx->dd);
  10837. while (dom) {
  10838. if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) {
  10839. /* Found matching domain */
  10840. DEBUG_TRACE("HTTP domain %s found",
  10841. dom->config[AUTHENTICATION_DOMAIN]);
  10842. /* TODO: Check if this is a HTTP or HTTPS domain */
  10843. conn->dom_ctx = dom;
  10844. break;
  10845. }
  10846. dom = dom->next;
  10847. }
  10848. DEBUG_TRACE("HTTP Host: %s", host);
  10849. }
  10850. } else {
  10851. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  10852. DEBUG_TRACE("IP: %s", host);
  10853. }
  10854. return mg_strdup_ctx(host, conn->phys_ctx);
  10855. }
  10856. static void
  10857. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  10858. {
  10859. conn->must_close = 1;
  10860. /* Send host, port, uri and (if it exists) ?query_string */
  10861. if (conn->host) {
  10862. mg_printf(conn,
  10863. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  10864. conn->host,
  10865. #if defined(USE_IPV6)
  10866. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  10867. == AF_INET6)
  10868. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  10869. .lsa.sin6.sin6_port)
  10870. :
  10871. #endif
  10872. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  10873. .lsa.sin.sin_port),
  10874. conn->request_info.local_uri,
  10875. (conn->request_info.query_string == NULL) ? "" : "?",
  10876. (conn->request_info.query_string == NULL)
  10877. ? ""
  10878. : conn->request_info.query_string);
  10879. }
  10880. }
  10881. static void
  10882. handler_info_acquire(struct mg_handler_info *handler_info)
  10883. {
  10884. pthread_mutex_lock(&handler_info->refcount_mutex);
  10885. handler_info->refcount++;
  10886. pthread_mutex_unlock(&handler_info->refcount_mutex);
  10887. }
  10888. static void
  10889. handler_info_release(struct mg_handler_info *handler_info)
  10890. {
  10891. pthread_mutex_lock(&handler_info->refcount_mutex);
  10892. handler_info->refcount--;
  10893. pthread_cond_signal(&handler_info->refcount_cond);
  10894. pthread_mutex_unlock(&handler_info->refcount_mutex);
  10895. }
  10896. static void
  10897. handler_info_wait_unused(struct mg_handler_info *handler_info)
  10898. {
  10899. pthread_mutex_lock(&handler_info->refcount_mutex);
  10900. while (handler_info->refcount) {
  10901. pthread_cond_wait(&handler_info->refcount_cond,
  10902. &handler_info->refcount_mutex);
  10903. }
  10904. pthread_mutex_unlock(&handler_info->refcount_mutex);
  10905. }
  10906. static void
  10907. mg_set_handler_type(struct mg_context *phys_ctx,
  10908. struct mg_domain_context *dom_ctx,
  10909. const char *uri,
  10910. int handler_type,
  10911. int is_delete_request,
  10912. mg_request_handler handler,
  10913. struct mg_websocket_subprotocols *subprotocols,
  10914. mg_websocket_connect_handler connect_handler,
  10915. mg_websocket_ready_handler ready_handler,
  10916. mg_websocket_data_handler data_handler,
  10917. mg_websocket_close_handler close_handler,
  10918. mg_authorization_handler auth_handler,
  10919. void *cbdata)
  10920. {
  10921. struct mg_handler_info *tmp_rh, **lastref;
  10922. size_t urilen = strlen(uri);
  10923. if (handler_type == WEBSOCKET_HANDLER) {
  10924. DEBUG_ASSERT(handler == NULL);
  10925. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  10926. || ready_handler != NULL
  10927. || data_handler != NULL
  10928. || close_handler != NULL);
  10929. DEBUG_ASSERT(auth_handler == NULL);
  10930. if (handler != NULL) {
  10931. return;
  10932. }
  10933. if (!is_delete_request && (connect_handler == NULL)
  10934. && (ready_handler == NULL) && (data_handler == NULL)
  10935. && (close_handler == NULL)) {
  10936. return;
  10937. }
  10938. if (auth_handler != NULL) {
  10939. return;
  10940. }
  10941. } else if (handler_type == REQUEST_HANDLER) {
  10942. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  10943. && data_handler == NULL
  10944. && close_handler == NULL);
  10945. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  10946. DEBUG_ASSERT(auth_handler == NULL);
  10947. if ((connect_handler != NULL) || (ready_handler != NULL)
  10948. || (data_handler != NULL) || (close_handler != NULL)) {
  10949. return;
  10950. }
  10951. if (!is_delete_request && (handler == NULL)) {
  10952. return;
  10953. }
  10954. if (auth_handler != NULL) {
  10955. return;
  10956. }
  10957. } else { /* AUTH_HANDLER */
  10958. DEBUG_ASSERT(handler == NULL);
  10959. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  10960. && data_handler == NULL
  10961. && close_handler == NULL);
  10962. DEBUG_ASSERT(auth_handler != NULL);
  10963. if (handler != NULL) {
  10964. return;
  10965. }
  10966. if ((connect_handler != NULL) || (ready_handler != NULL)
  10967. || (data_handler != NULL) || (close_handler != NULL)) {
  10968. return;
  10969. }
  10970. if (!is_delete_request && (auth_handler == NULL)) {
  10971. return;
  10972. }
  10973. }
  10974. if (!phys_ctx || !dom_ctx) {
  10975. return;
  10976. }
  10977. mg_lock_context(phys_ctx);
  10978. /* first try to find an existing handler */
  10979. lastref = &(dom_ctx->handlers);
  10980. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  10981. if (tmp_rh->handler_type == handler_type) {
  10982. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10983. if (!is_delete_request) {
  10984. /* update existing handler */
  10985. if (handler_type == REQUEST_HANDLER) {
  10986. /* Wait for end of use before updating */
  10987. handler_info_wait_unused(tmp_rh);
  10988. /* Ok, the handler is no more use -> Update it */
  10989. tmp_rh->handler = handler;
  10990. } else if (handler_type == WEBSOCKET_HANDLER) {
  10991. tmp_rh->subprotocols = subprotocols;
  10992. tmp_rh->connect_handler = connect_handler;
  10993. tmp_rh->ready_handler = ready_handler;
  10994. tmp_rh->data_handler = data_handler;
  10995. tmp_rh->close_handler = close_handler;
  10996. } else { /* AUTH_HANDLER */
  10997. tmp_rh->auth_handler = auth_handler;
  10998. }
  10999. tmp_rh->cbdata = cbdata;
  11000. } else {
  11001. /* remove existing handler */
  11002. if (handler_type == REQUEST_HANDLER) {
  11003. /* Wait for end of use before removing */
  11004. handler_info_wait_unused(tmp_rh);
  11005. /* Ok, the handler is no more used -> Destroy resources
  11006. */
  11007. pthread_cond_destroy(&tmp_rh->refcount_cond);
  11008. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11009. }
  11010. *lastref = tmp_rh->next;
  11011. mg_free(tmp_rh->uri);
  11012. mg_free(tmp_rh);
  11013. }
  11014. mg_unlock_context(phys_ctx);
  11015. return;
  11016. }
  11017. }
  11018. lastref = &(tmp_rh->next);
  11019. }
  11020. if (is_delete_request) {
  11021. /* no handler to set, this was a remove request to a non-existing
  11022. * handler */
  11023. mg_unlock_context(phys_ctx);
  11024. return;
  11025. }
  11026. tmp_rh =
  11027. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  11028. 1,
  11029. phys_ctx);
  11030. if (tmp_rh == NULL) {
  11031. mg_unlock_context(phys_ctx);
  11032. mg_cry_internal(fc(phys_ctx),
  11033. "%s",
  11034. "Cannot create new request handler struct, OOM");
  11035. return;
  11036. }
  11037. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  11038. if (!tmp_rh->uri) {
  11039. mg_unlock_context(phys_ctx);
  11040. mg_free(tmp_rh);
  11041. mg_cry_internal(fc(phys_ctx),
  11042. "%s",
  11043. "Cannot create new request handler struct, OOM");
  11044. return;
  11045. }
  11046. tmp_rh->uri_len = urilen;
  11047. if (handler_type == REQUEST_HANDLER) {
  11048. /* Init refcount mutex and condition */
  11049. if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) {
  11050. mg_unlock_context(phys_ctx);
  11051. mg_free(tmp_rh);
  11052. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex");
  11053. return;
  11054. }
  11055. if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) {
  11056. mg_unlock_context(phys_ctx);
  11057. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  11058. mg_free(tmp_rh);
  11059. mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond");
  11060. return;
  11061. }
  11062. tmp_rh->refcount = 0;
  11063. tmp_rh->handler = handler;
  11064. } else if (handler_type == WEBSOCKET_HANDLER) {
  11065. tmp_rh->subprotocols = subprotocols;
  11066. tmp_rh->connect_handler = connect_handler;
  11067. tmp_rh->ready_handler = ready_handler;
  11068. tmp_rh->data_handler = data_handler;
  11069. tmp_rh->close_handler = close_handler;
  11070. } else { /* AUTH_HANDLER */
  11071. tmp_rh->auth_handler = auth_handler;
  11072. }
  11073. tmp_rh->cbdata = cbdata;
  11074. tmp_rh->handler_type = handler_type;
  11075. tmp_rh->next = NULL;
  11076. *lastref = tmp_rh;
  11077. mg_unlock_context(phys_ctx);
  11078. }
  11079. void
  11080. mg_set_request_handler(struct mg_context *ctx,
  11081. const char *uri,
  11082. mg_request_handler handler,
  11083. void *cbdata)
  11084. {
  11085. mg_set_handler_type(ctx,
  11086. &(ctx->dd),
  11087. uri,
  11088. REQUEST_HANDLER,
  11089. handler == NULL,
  11090. handler,
  11091. NULL,
  11092. NULL,
  11093. NULL,
  11094. NULL,
  11095. NULL,
  11096. NULL,
  11097. cbdata);
  11098. }
  11099. void
  11100. mg_set_websocket_handler(struct mg_context *ctx,
  11101. const char *uri,
  11102. mg_websocket_connect_handler connect_handler,
  11103. mg_websocket_ready_handler ready_handler,
  11104. mg_websocket_data_handler data_handler,
  11105. mg_websocket_close_handler close_handler,
  11106. void *cbdata)
  11107. {
  11108. mg_set_websocket_handler_with_subprotocols(ctx,
  11109. uri,
  11110. NULL,
  11111. connect_handler,
  11112. ready_handler,
  11113. data_handler,
  11114. close_handler,
  11115. cbdata);
  11116. }
  11117. void
  11118. mg_set_websocket_handler_with_subprotocols(
  11119. struct mg_context *ctx,
  11120. const char *uri,
  11121. struct mg_websocket_subprotocols *subprotocols,
  11122. mg_websocket_connect_handler connect_handler,
  11123. mg_websocket_ready_handler ready_handler,
  11124. mg_websocket_data_handler data_handler,
  11125. mg_websocket_close_handler close_handler,
  11126. void *cbdata)
  11127. {
  11128. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  11129. && (data_handler == NULL)
  11130. && (close_handler == NULL);
  11131. mg_set_handler_type(ctx,
  11132. &(ctx->dd),
  11133. uri,
  11134. WEBSOCKET_HANDLER,
  11135. is_delete_request,
  11136. NULL,
  11137. subprotocols,
  11138. connect_handler,
  11139. ready_handler,
  11140. data_handler,
  11141. close_handler,
  11142. NULL,
  11143. cbdata);
  11144. }
  11145. void
  11146. mg_set_auth_handler(struct mg_context *ctx,
  11147. const char *uri,
  11148. mg_request_handler handler,
  11149. void *cbdata)
  11150. {
  11151. mg_set_handler_type(ctx,
  11152. &(ctx->dd),
  11153. uri,
  11154. AUTH_HANDLER,
  11155. handler == NULL,
  11156. NULL,
  11157. NULL,
  11158. NULL,
  11159. NULL,
  11160. NULL,
  11161. NULL,
  11162. handler,
  11163. cbdata);
  11164. }
  11165. static int
  11166. get_request_handler(struct mg_connection *conn,
  11167. int handler_type,
  11168. mg_request_handler *handler,
  11169. struct mg_websocket_subprotocols **subprotocols,
  11170. mg_websocket_connect_handler *connect_handler,
  11171. mg_websocket_ready_handler *ready_handler,
  11172. mg_websocket_data_handler *data_handler,
  11173. mg_websocket_close_handler *close_handler,
  11174. mg_authorization_handler *auth_handler,
  11175. void **cbdata,
  11176. struct mg_handler_info **handler_info)
  11177. {
  11178. const struct mg_request_info *request_info = mg_get_request_info(conn);
  11179. if (request_info) {
  11180. const char *uri = request_info->local_uri;
  11181. size_t urilen = strlen(uri);
  11182. struct mg_handler_info *tmp_rh;
  11183. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  11184. return 0;
  11185. }
  11186. mg_lock_context(conn->phys_ctx);
  11187. /* first try for an exact match */
  11188. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11189. tmp_rh = tmp_rh->next) {
  11190. if (tmp_rh->handler_type == handler_type) {
  11191. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  11192. if (handler_type == WEBSOCKET_HANDLER) {
  11193. *subprotocols = tmp_rh->subprotocols;
  11194. *connect_handler = tmp_rh->connect_handler;
  11195. *ready_handler = tmp_rh->ready_handler;
  11196. *data_handler = tmp_rh->data_handler;
  11197. *close_handler = tmp_rh->close_handler;
  11198. } else if (handler_type == REQUEST_HANDLER) {
  11199. *handler = tmp_rh->handler;
  11200. /* Acquire handler and give it back */
  11201. handler_info_acquire(tmp_rh);
  11202. *handler_info = tmp_rh;
  11203. } else { /* AUTH_HANDLER */
  11204. *auth_handler = tmp_rh->auth_handler;
  11205. }
  11206. *cbdata = tmp_rh->cbdata;
  11207. mg_unlock_context(conn->phys_ctx);
  11208. return 1;
  11209. }
  11210. }
  11211. }
  11212. /* next try for a partial match, we will accept uri/something */
  11213. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11214. tmp_rh = tmp_rh->next) {
  11215. if (tmp_rh->handler_type == handler_type) {
  11216. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  11217. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  11218. if (handler_type == WEBSOCKET_HANDLER) {
  11219. *subprotocols = tmp_rh->subprotocols;
  11220. *connect_handler = tmp_rh->connect_handler;
  11221. *ready_handler = tmp_rh->ready_handler;
  11222. *data_handler = tmp_rh->data_handler;
  11223. *close_handler = tmp_rh->close_handler;
  11224. } else if (handler_type == REQUEST_HANDLER) {
  11225. *handler = tmp_rh->handler;
  11226. /* Acquire handler and give it back */
  11227. handler_info_acquire(tmp_rh);
  11228. *handler_info = tmp_rh;
  11229. } else { /* AUTH_HANDLER */
  11230. *auth_handler = tmp_rh->auth_handler;
  11231. }
  11232. *cbdata = tmp_rh->cbdata;
  11233. mg_unlock_context(conn->phys_ctx);
  11234. return 1;
  11235. }
  11236. }
  11237. }
  11238. /* finally try for pattern match */
  11239. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  11240. tmp_rh = tmp_rh->next) {
  11241. if (tmp_rh->handler_type == handler_type) {
  11242. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  11243. if (handler_type == WEBSOCKET_HANDLER) {
  11244. *subprotocols = tmp_rh->subprotocols;
  11245. *connect_handler = tmp_rh->connect_handler;
  11246. *ready_handler = tmp_rh->ready_handler;
  11247. *data_handler = tmp_rh->data_handler;
  11248. *close_handler = tmp_rh->close_handler;
  11249. } else if (handler_type == REQUEST_HANDLER) {
  11250. *handler = tmp_rh->handler;
  11251. /* Acquire handler and give it back */
  11252. handler_info_acquire(tmp_rh);
  11253. *handler_info = tmp_rh;
  11254. } else { /* AUTH_HANDLER */
  11255. *auth_handler = tmp_rh->auth_handler;
  11256. }
  11257. *cbdata = tmp_rh->cbdata;
  11258. mg_unlock_context(conn->phys_ctx);
  11259. return 1;
  11260. }
  11261. }
  11262. }
  11263. mg_unlock_context(conn->phys_ctx);
  11264. }
  11265. return 0; /* none found */
  11266. }
  11267. /* Check if the script file is in a path, allowed for script files.
  11268. * This can be used if uploading files is possible not only for the server
  11269. * admin, and the upload mechanism does not check the file extension.
  11270. */
  11271. static int
  11272. is_in_script_path(const struct mg_connection *conn, const char *path)
  11273. {
  11274. /* TODO (Feature): Add config value for allowed script path.
  11275. * Default: All allowed. */
  11276. (void)conn;
  11277. (void)path;
  11278. return 1;
  11279. }
  11280. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  11281. static int
  11282. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  11283. void *cbdata)
  11284. {
  11285. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11286. if (pcallbacks->websocket_connect) {
  11287. return pcallbacks->websocket_connect(conn);
  11288. }
  11289. /* No handler set - assume "OK" */
  11290. return 0;
  11291. }
  11292. static void
  11293. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  11294. {
  11295. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11296. if (pcallbacks->websocket_ready) {
  11297. pcallbacks->websocket_ready(conn);
  11298. }
  11299. }
  11300. static int
  11301. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  11302. int bits,
  11303. char *data,
  11304. size_t len,
  11305. void *cbdata)
  11306. {
  11307. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  11308. if (pcallbacks->websocket_data) {
  11309. return pcallbacks->websocket_data(conn, bits, data, len);
  11310. }
  11311. /* No handler set - assume "OK" */
  11312. return 1;
  11313. }
  11314. #endif
  11315. /* This is the heart of the Civetweb's logic.
  11316. * This function is called when the request is read, parsed and validated,
  11317. * and Civetweb must decide what action to take: serve a file, or
  11318. * a directory, or call embedded function, etcetera. */
  11319. static void
  11320. handle_request(struct mg_connection *conn)
  11321. {
  11322. struct mg_request_info *ri = &conn->request_info;
  11323. char path[PATH_MAX];
  11324. int uri_len, ssl_index;
  11325. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  11326. is_put_or_delete_request = 0, is_callback_resource = 0;
  11327. int i;
  11328. struct mg_file file = STRUCT_FILE_INITIALIZER;
  11329. mg_request_handler callback_handler = NULL;
  11330. struct mg_handler_info *handler_info = NULL;
  11331. struct mg_websocket_subprotocols *subprotocols;
  11332. mg_websocket_connect_handler ws_connect_handler = NULL;
  11333. mg_websocket_ready_handler ws_ready_handler = NULL;
  11334. mg_websocket_data_handler ws_data_handler = NULL;
  11335. mg_websocket_close_handler ws_close_handler = NULL;
  11336. void *callback_data = NULL;
  11337. mg_authorization_handler auth_handler = NULL;
  11338. void *auth_callback_data = NULL;
  11339. int handler_type;
  11340. time_t curtime = time(NULL);
  11341. char date[64];
  11342. path[0] = 0;
  11343. /* 1. get the request url */
  11344. /* 1.1. split into url and query string */
  11345. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  11346. != NULL) {
  11347. *((char *)conn->request_info.query_string++) = '\0';
  11348. }
  11349. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  11350. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  11351. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  11352. if (ssl_index >= 0) {
  11353. redirect_to_https_port(conn, ssl_index);
  11354. } else {
  11355. /* A http to https forward port has been specified,
  11356. * but no https port to forward to. */
  11357. mg_send_http_error(conn,
  11358. 503,
  11359. "%s",
  11360. "Error: SSL forward not configured properly");
  11361. mg_cry_internal(conn,
  11362. "%s",
  11363. "Can not redirect to SSL, no SSL port available");
  11364. }
  11365. return;
  11366. }
  11367. uri_len = (int)strlen(ri->local_uri);
  11368. /* 1.3. decode url (if config says so) */
  11369. if (should_decode_url(conn)) {
  11370. mg_url_decode(
  11371. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  11372. }
  11373. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  11374. * not possible */
  11375. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  11376. /* step 1. completed, the url is known now */
  11377. uri_len = (int)strlen(ri->local_uri);
  11378. DEBUG_TRACE("URL: %s", ri->local_uri);
  11379. /* 2. if this ip has limited speed, set it for this connection */
  11380. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  11381. get_remote_ip(conn),
  11382. ri->local_uri);
  11383. /* 3. call a "handle everything" callback, if registered */
  11384. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  11385. /* Note that since V1.7 the "begin_request" function is called
  11386. * before an authorization check. If an authorization check is
  11387. * required, use a request_handler instead. */
  11388. i = conn->phys_ctx->callbacks.begin_request(conn);
  11389. if (i > 0) {
  11390. /* callback already processed the request. Store the
  11391. return value as a status code for the access log. */
  11392. conn->status_code = i;
  11393. discard_unread_request_data(conn);
  11394. return;
  11395. } else if (i == 0) {
  11396. /* civetweb should process the request */
  11397. } else {
  11398. /* unspecified - may change with the next version */
  11399. return;
  11400. }
  11401. }
  11402. /* request not yet handled by a handler or redirect, so the request
  11403. * is processed here */
  11404. /* 4. Check for CORS preflight requests and handle them (if configured).
  11405. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  11406. */
  11407. if (!strcmp(ri->request_method, "OPTIONS")) {
  11408. /* Send a response to CORS preflights only if
  11409. * access_control_allow_methods is not NULL and not an empty string.
  11410. * In this case, scripts can still handle CORS. */
  11411. const char *cors_meth_cfg =
  11412. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  11413. const char *cors_orig_cfg =
  11414. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  11415. const char *cors_origin =
  11416. get_header(ri->http_headers, ri->num_headers, "Origin");
  11417. const char *cors_acrm = get_header(ri->http_headers,
  11418. ri->num_headers,
  11419. "Access-Control-Request-Method");
  11420. /* Todo: check if cors_origin is in cors_orig_cfg.
  11421. * Or, let the client check this. */
  11422. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  11423. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  11424. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  11425. /* This is a valid CORS preflight, and the server is configured
  11426. * to
  11427. * handle it automatically. */
  11428. const char *cors_acrh =
  11429. get_header(ri->http_headers,
  11430. ri->num_headers,
  11431. "Access-Control-Request-Headers");
  11432. gmt_time_string(date, sizeof(date), &curtime);
  11433. mg_printf(conn,
  11434. "HTTP/1.1 200 OK\r\n"
  11435. "Date: %s\r\n"
  11436. "Access-Control-Allow-Origin: %s\r\n"
  11437. "Access-Control-Allow-Methods: %s\r\n"
  11438. "Content-Length: 0\r\n"
  11439. "Connection: %s\r\n",
  11440. date,
  11441. cors_orig_cfg,
  11442. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  11443. suggest_connection_header(conn));
  11444. if (cors_acrh != NULL) {
  11445. /* CORS request is asking for additional headers */
  11446. const char *cors_hdr_cfg =
  11447. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  11448. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  11449. /* Allow only if access_control_allow_headers is
  11450. * not NULL and not an empty string. If this
  11451. * configuration is set to *, allow everything.
  11452. * Otherwise this configuration must be a list
  11453. * of allowed HTTP header names. */
  11454. mg_printf(conn,
  11455. "Access-Control-Allow-Headers: %s\r\n",
  11456. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  11457. : cors_hdr_cfg));
  11458. }
  11459. }
  11460. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  11461. mg_printf(conn, "\r\n");
  11462. return;
  11463. }
  11464. }
  11465. /* 5. interpret the url to find out how the request must be handled
  11466. */
  11467. /* 5.1. first test, if the request targets the regular http(s)://
  11468. * protocol namespace or the websocket ws(s):// protocol namespace.
  11469. */
  11470. is_websocket_request = is_websocket_protocol(conn);
  11471. #if defined(USE_WEBSOCKET)
  11472. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  11473. #else
  11474. handler_type = REQUEST_HANDLER;
  11475. #endif /* defined(USE_WEBSOCKET) */
  11476. /* 5.2. check if the request will be handled by a callback */
  11477. if (get_request_handler(conn,
  11478. handler_type,
  11479. &callback_handler,
  11480. &subprotocols,
  11481. &ws_connect_handler,
  11482. &ws_ready_handler,
  11483. &ws_data_handler,
  11484. &ws_close_handler,
  11485. NULL,
  11486. &callback_data,
  11487. &handler_info)) {
  11488. /* 5.2.1. A callback will handle this request. All requests
  11489. * handled
  11490. * by a callback have to be considered as requests to a script
  11491. * resource. */
  11492. is_callback_resource = 1;
  11493. is_script_resource = 1;
  11494. is_put_or_delete_request = is_put_or_delete_method(conn);
  11495. } else {
  11496. no_callback_resource:
  11497. /* 5.2.2. No callback is responsible for this request. The URI
  11498. * addresses a file based resource (static content or Lua/cgi
  11499. * scripts in the file system). */
  11500. is_callback_resource = 0;
  11501. interpret_uri(conn,
  11502. path,
  11503. sizeof(path),
  11504. &file.stat,
  11505. &is_found,
  11506. &is_script_resource,
  11507. &is_websocket_request,
  11508. &is_put_or_delete_request);
  11509. }
  11510. /* 6. authorization check */
  11511. /* 6.1. a custom authorization handler is installed */
  11512. if (get_request_handler(conn,
  11513. AUTH_HANDLER,
  11514. NULL,
  11515. NULL,
  11516. NULL,
  11517. NULL,
  11518. NULL,
  11519. NULL,
  11520. &auth_handler,
  11521. &auth_callback_data,
  11522. NULL)) {
  11523. if (!auth_handler(conn, auth_callback_data)) {
  11524. return;
  11525. }
  11526. } else if (is_put_or_delete_request && !is_script_resource
  11527. && !is_callback_resource) {
  11528. /* 6.2. this request is a PUT/DELETE to a real file */
  11529. /* 6.2.1. thus, the server must have real files */
  11530. #if defined(NO_FILES)
  11531. if (1) {
  11532. #else
  11533. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11534. #endif
  11535. /* This server does not have any real files, thus the
  11536. * PUT/DELETE methods are not valid. */
  11537. mg_send_http_error(conn,
  11538. 405,
  11539. "%s method not allowed",
  11540. conn->request_info.request_method);
  11541. return;
  11542. }
  11543. #if !defined(NO_FILES)
  11544. /* 6.2.2. Check if put authorization for static files is
  11545. * available.
  11546. */
  11547. if (!is_authorized_for_put(conn)) {
  11548. send_authorization_request(conn, NULL);
  11549. return;
  11550. }
  11551. #endif
  11552. } else {
  11553. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11554. * or it is a PUT or DELETE request to a resource that does not
  11555. * correspond to a file. Check authorization. */
  11556. if (!check_authorization(conn, path)) {
  11557. send_authorization_request(conn, NULL);
  11558. return;
  11559. }
  11560. }
  11561. /* request is authorized or does not need authorization */
  11562. /* 7. check if there are request handlers for this uri */
  11563. if (is_callback_resource) {
  11564. if (!is_websocket_request) {
  11565. i = callback_handler(conn, callback_data);
  11566. /* Callback handler will not be used anymore. Release it */
  11567. handler_info_release(handler_info);
  11568. if (i > 0) {
  11569. /* Do nothing, callback has served the request. Store
  11570. * then return value as status code for the log and discard
  11571. * all data from the client not used by the callback. */
  11572. conn->status_code = i;
  11573. discard_unread_request_data(conn);
  11574. } else {
  11575. /* The handler did NOT handle the request. */
  11576. /* Some proper reactions would be:
  11577. * a) close the connections without sending anything
  11578. * b) send a 404 not found
  11579. * c) try if there is a file matching the URI
  11580. * It would be possible to do a, b or c in the callback
  11581. * implementation, and return 1 - we cannot do anything
  11582. * here, that is not possible in the callback.
  11583. *
  11584. * TODO: What would be the best reaction here?
  11585. * (Note: The reaction may change, if there is a better
  11586. *idea.)
  11587. */
  11588. /* For the moment, use option c: We look for a proper file,
  11589. * but since a file request is not always a script resource,
  11590. * the authorization check might be different. */
  11591. interpret_uri(conn,
  11592. path,
  11593. sizeof(path),
  11594. &file.stat,
  11595. &is_found,
  11596. &is_script_resource,
  11597. &is_websocket_request,
  11598. &is_put_or_delete_request);
  11599. callback_handler = NULL;
  11600. /* Here we are at a dead end:
  11601. * According to URI matching, a callback should be
  11602. * responsible for handling the request,
  11603. * we called it, but the callback declared itself
  11604. * not responsible.
  11605. * We use a goto here, to get out of this dead end,
  11606. * and continue with the default handling.
  11607. * A goto here is simpler and better to understand
  11608. * than some curious loop. */
  11609. goto no_callback_resource;
  11610. }
  11611. } else {
  11612. #if defined(USE_WEBSOCKET)
  11613. handle_websocket_request(conn,
  11614. path,
  11615. is_callback_resource,
  11616. subprotocols,
  11617. ws_connect_handler,
  11618. ws_ready_handler,
  11619. ws_data_handler,
  11620. ws_close_handler,
  11621. callback_data);
  11622. #endif
  11623. }
  11624. return;
  11625. }
  11626. /* 8. handle websocket requests */
  11627. #if defined(USE_WEBSOCKET)
  11628. if (is_websocket_request) {
  11629. if (is_script_resource) {
  11630. if (is_in_script_path(conn, path)) {
  11631. /* Websocket Lua script */
  11632. handle_websocket_request(conn,
  11633. path,
  11634. 0 /* Lua Script */,
  11635. NULL,
  11636. NULL,
  11637. NULL,
  11638. NULL,
  11639. NULL,
  11640. conn->phys_ctx->user_data);
  11641. } else {
  11642. /* Script was in an illegal path */
  11643. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11644. }
  11645. } else {
  11646. #if defined(MG_LEGACY_INTERFACE)
  11647. handle_websocket_request(
  11648. conn,
  11649. path,
  11650. !is_script_resource /* could be deprecated global callback */,
  11651. NULL,
  11652. deprecated_websocket_connect_wrapper,
  11653. deprecated_websocket_ready_wrapper,
  11654. deprecated_websocket_data_wrapper,
  11655. NULL,
  11656. conn->phys_ctx->user_data);
  11657. #else
  11658. mg_send_http_error(conn, 404, "%s", "Not found");
  11659. #endif
  11660. }
  11661. return;
  11662. } else
  11663. #endif
  11664. #if defined(NO_FILES)
  11665. /* 9a. In case the server uses only callbacks, this uri is
  11666. * unknown.
  11667. * Then, all request handling ends here. */
  11668. mg_send_http_error(conn, 404, "%s", "Not Found");
  11669. #else
  11670. /* 9b. This request is either for a static file or resource handled
  11671. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  11672. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11673. mg_send_http_error(conn, 404, "%s", "Not Found");
  11674. return;
  11675. }
  11676. /* 10. Request is handled by a script */
  11677. if (is_script_resource) {
  11678. handle_file_based_request(conn, path, &file);
  11679. return;
  11680. }
  11681. /* 11. Handle put/delete/mkcol requests */
  11682. if (is_put_or_delete_request) {
  11683. /* 11.1. PUT method */
  11684. if (!strcmp(ri->request_method, "PUT")) {
  11685. put_file(conn, path);
  11686. return;
  11687. }
  11688. /* 11.2. DELETE method */
  11689. if (!strcmp(ri->request_method, "DELETE")) {
  11690. delete_file(conn, path);
  11691. return;
  11692. }
  11693. /* 11.3. MKCOL method */
  11694. if (!strcmp(ri->request_method, "MKCOL")) {
  11695. mkcol(conn, path);
  11696. return;
  11697. }
  11698. /* 11.4. PATCH method
  11699. * This method is not supported for static resources,
  11700. * only for scripts (Lua, CGI) and callbacks. */
  11701. mg_send_http_error(conn,
  11702. 405,
  11703. "%s method not allowed",
  11704. conn->request_info.request_method);
  11705. return;
  11706. }
  11707. /* 11. File does not exist, or it was configured that it should be
  11708. * hidden */
  11709. if (!is_found || (must_hide_file(conn, path))) {
  11710. mg_send_http_error(conn, 404, "%s", "Not found");
  11711. return;
  11712. }
  11713. /* 12. Directory uris should end with a slash */
  11714. if (file.stat.is_directory && (uri_len > 0)
  11715. && (ri->local_uri[uri_len - 1] != '/')) {
  11716. gmt_time_string(date, sizeof(date), &curtime);
  11717. mg_printf(conn,
  11718. "HTTP/1.1 301 Moved Permanently\r\n"
  11719. "Location: %s/\r\n"
  11720. "Date: %s\r\n"
  11721. /* "Cache-Control: private\r\n" (= default) */
  11722. "Content-Length: 0\r\n"
  11723. "Connection: %s\r\n",
  11724. ri->request_uri,
  11725. date,
  11726. suggest_connection_header(conn));
  11727. send_additional_header(conn);
  11728. mg_printf(conn, "\r\n");
  11729. return;
  11730. }
  11731. /* 13. Handle other methods than GET/HEAD */
  11732. /* 13.1. Handle PROPFIND */
  11733. if (!strcmp(ri->request_method, "PROPFIND")) {
  11734. handle_propfind(conn, path, &file.stat);
  11735. return;
  11736. }
  11737. /* 13.2. Handle OPTIONS for files */
  11738. if (!strcmp(ri->request_method, "OPTIONS")) {
  11739. /* This standard handler is only used for real files.
  11740. * Scripts should support the OPTIONS method themselves, to allow a
  11741. * maximum flexibility.
  11742. * Lua and CGI scripts may fully support CORS this way (including
  11743. * preflights). */
  11744. send_options(conn);
  11745. return;
  11746. }
  11747. /* 13.3. everything but GET and HEAD (e.g. POST) */
  11748. if ((0 != strcmp(ri->request_method, "GET"))
  11749. && (0 != strcmp(ri->request_method, "HEAD"))) {
  11750. mg_send_http_error(conn,
  11751. 405,
  11752. "%s method not allowed",
  11753. conn->request_info.request_method);
  11754. return;
  11755. }
  11756. /* 14. directories */
  11757. if (file.stat.is_directory) {
  11758. /* Substitute files have already been handled above. */
  11759. /* Here we can either generate and send a directory listing,
  11760. * or send an "access denied" error. */
  11761. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11762. "yes")) {
  11763. handle_directory_request(conn, path);
  11764. } else {
  11765. mg_send_http_error(conn,
  11766. 403,
  11767. "%s",
  11768. "Error: Directory listing denied");
  11769. }
  11770. return;
  11771. }
  11772. handle_file_based_request(conn, path, &file);
  11773. #endif /* !defined(NO_FILES) */
  11774. #if 0
  11775. /* Perform redirect and auth checks before calling begin_request()
  11776. * handler.
  11777. * Otherwise, begin_request() would need to perform auth checks and
  11778. * redirects. */
  11779. #endif
  11780. }
  11781. static void
  11782. handle_file_based_request(struct mg_connection *conn,
  11783. const char *path,
  11784. struct mg_file *file)
  11785. {
  11786. if (!conn || !conn->dom_ctx) {
  11787. return;
  11788. }
  11789. if (0) {
  11790. #if defined(USE_LUA)
  11791. } else if (match_prefix(
  11792. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  11793. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  11794. path) > 0) {
  11795. if (is_in_script_path(conn, path)) {
  11796. /* Lua server page: an SSI like page containing mostly plain
  11797. * html
  11798. * code
  11799. * plus some tags with server generated contents. */
  11800. handle_lsp_request(conn, path, file, NULL);
  11801. } else {
  11802. /* Script was in an illegal path */
  11803. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11804. }
  11805. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  11806. strlen(
  11807. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  11808. path) > 0) {
  11809. if (is_in_script_path(conn, path)) {
  11810. /* Lua in-server module script: a CGI like script used to
  11811. * generate
  11812. * the
  11813. * entire reply. */
  11814. mg_exec_lua_script(conn, path, NULL);
  11815. } else {
  11816. /* Script was in an illegal path */
  11817. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11818. }
  11819. #endif
  11820. #if defined(USE_DUKTAPE)
  11821. } else if (match_prefix(
  11822. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  11823. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  11824. path) > 0) {
  11825. if (is_in_script_path(conn, path)) {
  11826. /* Call duktape to generate the page */
  11827. mg_exec_duktape_script(conn, path);
  11828. } else {
  11829. /* Script was in an illegal path */
  11830. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11831. }
  11832. #endif
  11833. #if !defined(NO_CGI)
  11834. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  11835. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  11836. path) > 0) {
  11837. if (is_in_script_path(conn, path)) {
  11838. /* CGI scripts may support all HTTP methods */
  11839. handle_cgi_request(conn, path);
  11840. } else {
  11841. /* Script was in an illegal path */
  11842. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11843. }
  11844. #endif /* !NO_CGI */
  11845. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  11846. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  11847. path) > 0) {
  11848. if (is_in_script_path(conn, path)) {
  11849. handle_ssi_file_request(conn, path, file);
  11850. } else {
  11851. /* Script was in an illegal path */
  11852. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11853. }
  11854. #if !defined(NO_CACHING)
  11855. } else if ((!conn->in_error_handler)
  11856. && is_not_modified(conn, &file->stat)) {
  11857. /* Send 304 "Not Modified" - this must not send any body data */
  11858. handle_not_modified_static_file_request(conn, file);
  11859. #endif /* !NO_CACHING */
  11860. } else {
  11861. handle_static_file_request(conn, path, file, NULL, NULL);
  11862. }
  11863. }
  11864. static void
  11865. close_all_listening_sockets(struct mg_context *ctx)
  11866. {
  11867. unsigned int i;
  11868. if (!ctx) {
  11869. return;
  11870. }
  11871. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11872. closesocket(ctx->listening_sockets[i].sock);
  11873. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  11874. }
  11875. mg_free(ctx->listening_sockets);
  11876. ctx->listening_sockets = NULL;
  11877. mg_free(ctx->listening_socket_fds);
  11878. ctx->listening_socket_fds = NULL;
  11879. }
  11880. /* Valid listening port specification is: [ip_address:]port[s]
  11881. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  11882. * Examples for IPv6: [::]:80, [::1]:80,
  11883. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  11884. * see https://tools.ietf.org/html/rfc3513#section-2.2
  11885. * In order to bind to both, IPv4 and IPv6, you can either add
  11886. * both ports using 8080,[::]:8080, or the short form +8080.
  11887. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  11888. * one only accepting IPv4 the other only IPv6. +8080 creates
  11889. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  11890. * environment, they might work differently, or might not work
  11891. * at all - it must be tested what options work best in the
  11892. * relevant network environment.
  11893. */
  11894. static int
  11895. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  11896. {
  11897. unsigned int a, b, c, d, port;
  11898. int ch, len;
  11899. const char *cb;
  11900. #if defined(USE_IPV6)
  11901. char buf[100] = {0};
  11902. #endif
  11903. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  11904. * Also, all-zeroes in the socket address means binding to all addresses
  11905. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  11906. memset(so, 0, sizeof(*so));
  11907. so->lsa.sin.sin_family = AF_INET;
  11908. *ip_version = 0;
  11909. /* Initialize port and len as invalid. */
  11910. port = 0;
  11911. len = 0;
  11912. /* Test for different ways to format this string */
  11913. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  11914. == 5) {
  11915. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  11916. so->lsa.sin.sin_addr.s_addr =
  11917. htonl((a << 24) | (b << 16) | (c << 8) | d);
  11918. so->lsa.sin.sin_port = htons((uint16_t)port);
  11919. *ip_version = 4;
  11920. #if defined(USE_IPV6)
  11921. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  11922. && mg_inet_pton(
  11923. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  11924. /* IPv6 address, examples: see above */
  11925. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  11926. */
  11927. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11928. *ip_version = 6;
  11929. #endif
  11930. } else if ((vec->ptr[0] == '+')
  11931. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  11932. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  11933. /* Add 1 to len for the + character we skipped before */
  11934. len++;
  11935. #if defined(USE_IPV6)
  11936. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  11937. so->lsa.sin6.sin6_family = AF_INET6;
  11938. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11939. *ip_version = 4 + 6;
  11940. #else
  11941. /* Bind to IPv4 only, since IPv6 is not built in. */
  11942. so->lsa.sin.sin_port = htons((uint16_t)port);
  11943. *ip_version = 4;
  11944. #endif
  11945. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  11946. /* If only port is specified, bind to IPv4, INADDR_ANY */
  11947. so->lsa.sin.sin_port = htons((uint16_t)port);
  11948. *ip_version = 4;
  11949. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  11950. /* Could be a hostname */
  11951. /* Will only work for RFC 952 compliant hostnames,
  11952. * starting with a letter, containing only letters,
  11953. * digits and hyphen ('-'). Newer specs may allow
  11954. * more, but this is not guaranteed here, since it
  11955. * may interfere with rules for port option lists. */
  11956. *(char *)cb = 0; /* Use a const cast here and modify the string.
  11957. * We are going to restore the string later. */
  11958. if (mg_inet_pton(
  11959. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  11960. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11961. *ip_version = 4;
  11962. so->lsa.sin.sin_family = AF_INET;
  11963. so->lsa.sin.sin_port = htons((uint16_t)port);
  11964. len += (int)(cb - vec->ptr) + 1;
  11965. } else {
  11966. port = 0;
  11967. len = 0;
  11968. }
  11969. #if defined(USE_IPV6)
  11970. } else if (mg_inet_pton(AF_INET6,
  11971. vec->ptr,
  11972. &so->lsa.sin6,
  11973. sizeof(so->lsa.sin6))) {
  11974. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11975. *ip_version = 6;
  11976. so->lsa.sin6.sin6_family = AF_INET6;
  11977. so->lsa.sin.sin_port = htons((uint16_t)port);
  11978. len += (int)(cb - vec->ptr) + 1;
  11979. } else {
  11980. port = 0;
  11981. len = 0;
  11982. }
  11983. #endif
  11984. }
  11985. *(char *)cb = ':'; /* restore the string */
  11986. } else {
  11987. /* Parsing failure. */
  11988. }
  11989. /* sscanf and the option splitting code ensure the following condition
  11990. */
  11991. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  11992. *ip_version = 0;
  11993. return 0;
  11994. }
  11995. ch = vec->ptr[len]; /* Next character after the port number */
  11996. so->is_ssl = (ch == 's');
  11997. so->ssl_redir = (ch == 'r');
  11998. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  11999. if (is_valid_port(port)
  12000. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  12001. return 1;
  12002. }
  12003. /* Reset ip_version to 0 of there is an error */
  12004. *ip_version = 0;
  12005. return 0;
  12006. }
  12007. /* Is there any SSL port in use? */
  12008. static int
  12009. is_ssl_port_used(const char *ports)
  12010. {
  12011. if (ports) {
  12012. int portslen = (int)strlen(ports);
  12013. char prevIsNumber = 0;
  12014. for (int i = 0; i < portslen; i++) {
  12015. if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) {
  12016. return 1;
  12017. }
  12018. if (ports[i] >= '0' && ports[i] <= '9') {
  12019. prevIsNumber = 1;
  12020. } else {
  12021. prevIsNumber = 0;
  12022. }
  12023. }
  12024. }
  12025. return 0;
  12026. }
  12027. static int
  12028. set_ports_option(struct mg_context *phys_ctx)
  12029. {
  12030. const char *list;
  12031. int on = 1;
  12032. #if defined(USE_IPV6)
  12033. int off = 0;
  12034. #endif
  12035. struct vec vec;
  12036. struct socket so, *ptr;
  12037. struct pollfd *pfd;
  12038. union usa usa;
  12039. socklen_t len;
  12040. int ip_version;
  12041. int portsTotal = 0;
  12042. int portsOk = 0;
  12043. if (!phys_ctx) {
  12044. return 0;
  12045. }
  12046. memset(&so, 0, sizeof(so));
  12047. memset(&usa, 0, sizeof(usa));
  12048. len = sizeof(usa);
  12049. list = phys_ctx->dd.config[LISTENING_PORTS];
  12050. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12051. portsTotal++;
  12052. if (!parse_port_string(&vec, &so, &ip_version)) {
  12053. mg_cry_internal(
  12054. fc(phys_ctx),
  12055. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  12056. (int)vec.len,
  12057. vec.ptr,
  12058. portsTotal,
  12059. "[IP_ADDRESS:]PORT[s|r]");
  12060. continue;
  12061. }
  12062. #if !defined(NO_SSL)
  12063. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  12064. mg_cry_internal(fc(phys_ctx),
  12065. "Cannot add SSL socket (entry %i)",
  12066. portsTotal);
  12067. continue;
  12068. }
  12069. #endif
  12070. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  12071. == INVALID_SOCKET) {
  12072. mg_cry_internal(fc(phys_ctx),
  12073. "cannot create socket (entry %i)",
  12074. portsTotal);
  12075. continue;
  12076. }
  12077. #if defined(_WIN32)
  12078. /* Windows SO_REUSEADDR lets many procs binds to a
  12079. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  12080. * if someone already has the socket -- DTL */
  12081. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  12082. * Windows might need a few seconds before
  12083. * the same port can be used again in the
  12084. * same process, so a short Sleep may be
  12085. * required between mg_stop and mg_start.
  12086. */
  12087. if (setsockopt(so.sock,
  12088. SOL_SOCKET,
  12089. SO_EXCLUSIVEADDRUSE,
  12090. (SOCK_OPT_TYPE)&on,
  12091. sizeof(on)) != 0) {
  12092. /* Set reuse option, but don't abort on errors. */
  12093. mg_cry_internal(
  12094. fc(phys_ctx),
  12095. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  12096. portsTotal);
  12097. }
  12098. #else
  12099. if (setsockopt(so.sock,
  12100. SOL_SOCKET,
  12101. SO_REUSEADDR,
  12102. (SOCK_OPT_TYPE)&on,
  12103. sizeof(on)) != 0) {
  12104. /* Set reuse option, but don't abort on errors. */
  12105. mg_cry_internal(fc(phys_ctx),
  12106. "cannot set socket option SO_REUSEADDR (entry %i)",
  12107. portsTotal);
  12108. }
  12109. #endif
  12110. if (ip_version > 4) {
  12111. /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */
  12112. #if defined(USE_IPV6)
  12113. if (ip_version > 6) {
  12114. if (so.lsa.sa.sa_family == AF_INET6
  12115. && setsockopt(so.sock,
  12116. IPPROTO_IPV6,
  12117. IPV6_V6ONLY,
  12118. (void *)&off,
  12119. sizeof(off)) != 0) {
  12120. /* Set IPv6 only option, but don't abort on errors. */
  12121. mg_cry_internal(
  12122. fc(phys_ctx),
  12123. "cannot set socket option IPV6_V6ONLY=off (entry %i)",
  12124. portsTotal);
  12125. }
  12126. } else {
  12127. if (so.lsa.sa.sa_family == AF_INET6
  12128. && setsockopt(so.sock,
  12129. IPPROTO_IPV6,
  12130. IPV6_V6ONLY,
  12131. (void *)&on,
  12132. sizeof(on)) != 0) {
  12133. /* Set IPv6 only option, but don't abort on errors. */
  12134. mg_cry_internal(
  12135. fc(phys_ctx),
  12136. "cannot set socket option IPV6_V6ONLY=on (entry %i)",
  12137. portsTotal);
  12138. }
  12139. }
  12140. #else
  12141. mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available");
  12142. closesocket(so.sock);
  12143. so.sock = INVALID_SOCKET;
  12144. continue;
  12145. #endif
  12146. }
  12147. if (so.lsa.sa.sa_family == AF_INET) {
  12148. len = sizeof(so.lsa.sin);
  12149. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12150. mg_cry_internal(fc(phys_ctx),
  12151. "cannot bind to %.*s: %d (%s)",
  12152. (int)vec.len,
  12153. vec.ptr,
  12154. (int)ERRNO,
  12155. strerror(errno));
  12156. closesocket(so.sock);
  12157. so.sock = INVALID_SOCKET;
  12158. continue;
  12159. }
  12160. }
  12161. #if defined(USE_IPV6)
  12162. else if (so.lsa.sa.sa_family == AF_INET6) {
  12163. len = sizeof(so.lsa.sin6);
  12164. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  12165. mg_cry_internal(fc(phys_ctx),
  12166. "cannot bind to IPv6 %.*s: %d (%s)",
  12167. (int)vec.len,
  12168. vec.ptr,
  12169. (int)ERRNO,
  12170. strerror(errno));
  12171. closesocket(so.sock);
  12172. so.sock = INVALID_SOCKET;
  12173. continue;
  12174. }
  12175. }
  12176. #endif
  12177. else {
  12178. mg_cry_internal(
  12179. fc(phys_ctx),
  12180. "cannot bind: address family not supported (entry %i)",
  12181. portsTotal);
  12182. closesocket(so.sock);
  12183. so.sock = INVALID_SOCKET;
  12184. continue;
  12185. }
  12186. if (listen(so.sock, SOMAXCONN) != 0) {
  12187. mg_cry_internal(fc(phys_ctx),
  12188. "cannot listen to %.*s: %d (%s)",
  12189. (int)vec.len,
  12190. vec.ptr,
  12191. (int)ERRNO,
  12192. strerror(errno));
  12193. closesocket(so.sock);
  12194. so.sock = INVALID_SOCKET;
  12195. continue;
  12196. }
  12197. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  12198. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  12199. int err = (int)ERRNO;
  12200. mg_cry_internal(fc(phys_ctx),
  12201. "call to getsockname failed %.*s: %d (%s)",
  12202. (int)vec.len,
  12203. vec.ptr,
  12204. err,
  12205. strerror(errno));
  12206. closesocket(so.sock);
  12207. so.sock = INVALID_SOCKET;
  12208. continue;
  12209. }
  12210. /* Update lsa port in case of random free ports */
  12211. #if defined(USE_IPV6)
  12212. if (so.lsa.sa.sa_family == AF_INET6) {
  12213. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  12214. } else
  12215. #endif
  12216. {
  12217. so.lsa.sin.sin_port = usa.sin.sin_port;
  12218. }
  12219. if ((ptr = (struct socket *)
  12220. mg_realloc_ctx(phys_ctx->listening_sockets,
  12221. (phys_ctx->num_listening_sockets + 1)
  12222. * sizeof(phys_ctx->listening_sockets[0]),
  12223. phys_ctx)) == NULL) {
  12224. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12225. closesocket(so.sock);
  12226. so.sock = INVALID_SOCKET;
  12227. continue;
  12228. }
  12229. if ((pfd = (struct pollfd *)
  12230. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  12231. (phys_ctx->num_listening_sockets + 1)
  12232. * sizeof(phys_ctx->listening_socket_fds[0]),
  12233. phys_ctx)) == NULL) {
  12234. mg_cry_internal(fc(phys_ctx), "%s", "Out of memory");
  12235. closesocket(so.sock);
  12236. so.sock = INVALID_SOCKET;
  12237. mg_free(ptr);
  12238. continue;
  12239. }
  12240. set_close_on_exec(so.sock, fc(phys_ctx));
  12241. phys_ctx->listening_sockets = ptr;
  12242. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  12243. phys_ctx->listening_socket_fds = pfd;
  12244. phys_ctx->num_listening_sockets++;
  12245. portsOk++;
  12246. }
  12247. if (portsOk != portsTotal) {
  12248. close_all_listening_sockets(phys_ctx);
  12249. portsOk = 0;
  12250. }
  12251. return portsOk;
  12252. }
  12253. static const char *
  12254. header_val(const struct mg_connection *conn, const char *header)
  12255. {
  12256. const char *header_value;
  12257. if ((header_value = mg_get_header(conn, header)) == NULL) {
  12258. return "-";
  12259. } else {
  12260. return header_value;
  12261. }
  12262. }
  12263. #if defined(MG_EXTERNAL_FUNCTION_log_access)
  12264. static void log_access(const struct mg_connection *conn);
  12265. #include "external_log_access.inl"
  12266. #else
  12267. static void
  12268. log_access(const struct mg_connection *conn)
  12269. {
  12270. const struct mg_request_info *ri;
  12271. struct mg_file fi;
  12272. char date[64], src_addr[IP_ADDR_STR_LEN];
  12273. struct tm *tm;
  12274. const char *referer;
  12275. const char *user_agent;
  12276. char buf[4096];
  12277. if (!conn || !conn->dom_ctx) {
  12278. return;
  12279. }
  12280. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  12281. if (mg_fopen(conn,
  12282. conn->dom_ctx->config[ACCESS_LOG_FILE],
  12283. MG_FOPEN_MODE_APPEND,
  12284. &fi) == 0) {
  12285. fi.access.fp = NULL;
  12286. }
  12287. } else {
  12288. fi.access.fp = NULL;
  12289. }
  12290. /* Log is written to a file and/or a callback. If both are not set,
  12291. * executing the rest of the function is pointless. */
  12292. if ((fi.access.fp == NULL)
  12293. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  12294. return;
  12295. }
  12296. tm = localtime(&conn->conn_birth_time);
  12297. if (tm != NULL) {
  12298. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  12299. } else {
  12300. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  12301. date[sizeof(date) - 1] = '\0';
  12302. }
  12303. ri = &conn->request_info;
  12304. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  12305. referer = header_val(conn, "Referer");
  12306. user_agent = header_val(conn, "User-Agent");
  12307. mg_snprintf(conn,
  12308. NULL, /* Ignore truncation in access log */
  12309. buf,
  12310. sizeof(buf),
  12311. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  12312. src_addr,
  12313. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  12314. date,
  12315. ri->request_method ? ri->request_method : "-",
  12316. ri->request_uri ? ri->request_uri : "-",
  12317. ri->query_string ? "?" : "",
  12318. ri->query_string ? ri->query_string : "",
  12319. ri->http_version,
  12320. conn->status_code,
  12321. conn->num_bytes_sent,
  12322. referer,
  12323. user_agent);
  12324. if (conn->phys_ctx->callbacks.log_access) {
  12325. conn->phys_ctx->callbacks.log_access(conn, buf);
  12326. }
  12327. if (fi.access.fp) {
  12328. int ok = 1;
  12329. flockfile(fi.access.fp);
  12330. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  12331. ok = 0;
  12332. }
  12333. if (fflush(fi.access.fp) != 0) {
  12334. ok = 0;
  12335. }
  12336. funlockfile(fi.access.fp);
  12337. if (mg_fclose(&fi.access) != 0) {
  12338. ok = 0;
  12339. }
  12340. if (!ok) {
  12341. mg_cry_internal(conn,
  12342. "Error writing log file %s",
  12343. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  12344. }
  12345. }
  12346. }
  12347. #endif /* Externally provided function */
  12348. /* Verify given socket address against the ACL.
  12349. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  12350. */
  12351. static int
  12352. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  12353. {
  12354. int allowed, flag;
  12355. uint32_t net, mask;
  12356. struct vec vec;
  12357. if (phys_ctx) {
  12358. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  12359. /* If any ACL is set, deny by default */
  12360. allowed = (list == NULL) ? '+' : '-';
  12361. while ((list = next_option(list, &vec, NULL)) != NULL) {
  12362. flag = vec.ptr[0];
  12363. if ((flag != '+' && flag != '-')
  12364. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  12365. mg_cry_internal(fc(phys_ctx),
  12366. "%s: subnet must be [+|-]x.x.x.x[/x]",
  12367. __func__);
  12368. return -1;
  12369. }
  12370. if (net == (remote_ip & mask)) {
  12371. allowed = flag;
  12372. }
  12373. }
  12374. return allowed == '+';
  12375. }
  12376. return -1;
  12377. }
  12378. #if !defined(_WIN32)
  12379. static int
  12380. set_uid_option(struct mg_context *phys_ctx)
  12381. {
  12382. int success = 0;
  12383. if (phys_ctx) {
  12384. /* We are currently running as curr_uid. */
  12385. const uid_t curr_uid = getuid();
  12386. /* If set, we want to run as run_as_user. */
  12387. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  12388. const struct passwd *to_pw = NULL;
  12389. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  12390. /* run_as_user does not exist on the system. We can't proceed
  12391. * further. */
  12392. mg_cry_internal(fc(phys_ctx),
  12393. "%s: unknown user [%s]",
  12394. __func__,
  12395. run_as_user);
  12396. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  12397. /* There was either no request to change user, or we're already
  12398. * running as run_as_user. Nothing else to do.
  12399. */
  12400. success = 1;
  12401. } else {
  12402. /* Valid change request. */
  12403. if (setgid(to_pw->pw_gid) == -1) {
  12404. mg_cry_internal(fc(phys_ctx),
  12405. "%s: setgid(%s): %s",
  12406. __func__,
  12407. run_as_user,
  12408. strerror(errno));
  12409. } else if (setgroups(0, NULL) == -1) {
  12410. mg_cry_internal(fc(phys_ctx),
  12411. "%s: setgroups(): %s",
  12412. __func__,
  12413. strerror(errno));
  12414. } else if (setuid(to_pw->pw_uid) == -1) {
  12415. mg_cry_internal(fc(phys_ctx),
  12416. "%s: setuid(%s): %s",
  12417. __func__,
  12418. run_as_user,
  12419. strerror(errno));
  12420. } else {
  12421. success = 1;
  12422. }
  12423. }
  12424. }
  12425. return success;
  12426. }
  12427. #endif /* !_WIN32 */
  12428. static void
  12429. tls_dtor(void *key)
  12430. {
  12431. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  12432. /* key == pthread_getspecific(sTlsKey); */
  12433. if (tls) {
  12434. if (tls->is_master == 2) {
  12435. tls->is_master = -3; /* Mark memory as dead */
  12436. mg_free(tls);
  12437. }
  12438. }
  12439. pthread_setspecific(sTlsKey, NULL);
  12440. }
  12441. #if !defined(NO_SSL)
  12442. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  12443. struct mg_domain_context *dom_ctx,
  12444. const char *pem,
  12445. const char *chain);
  12446. static const char *ssl_error(void);
  12447. static int
  12448. refresh_trust(struct mg_connection *conn)
  12449. {
  12450. static int reload_lock = 0;
  12451. static long int data_check = 0;
  12452. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  12453. struct stat cert_buf;
  12454. long int t;
  12455. const char *pem;
  12456. const char *chain;
  12457. int should_verify_peer;
  12458. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  12459. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  12460. * refresh_trust still can not work. */
  12461. return 0;
  12462. }
  12463. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12464. if (chain == NULL) {
  12465. /* pem is not NULL here */
  12466. chain = pem;
  12467. }
  12468. if (*chain == 0) {
  12469. chain = NULL;
  12470. }
  12471. t = data_check;
  12472. if (stat(pem, &cert_buf) != -1) {
  12473. t = (long int)cert_buf.st_mtime;
  12474. }
  12475. if (data_check != t) {
  12476. data_check = t;
  12477. should_verify_peer = 0;
  12478. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12479. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  12480. == 0) {
  12481. should_verify_peer = 1;
  12482. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  12483. "optional") == 0) {
  12484. should_verify_peer = 1;
  12485. }
  12486. }
  12487. if (should_verify_peer) {
  12488. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  12489. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  12490. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  12491. ca_file,
  12492. ca_path) != 1) {
  12493. mg_cry_internal(
  12494. fc(conn->phys_ctx),
  12495. "SSL_CTX_load_verify_locations error: %s "
  12496. "ssl_verify_peer requires setting "
  12497. "either ssl_ca_path or ssl_ca_file. Is any of them "
  12498. "present in "
  12499. "the .conf file?",
  12500. ssl_error());
  12501. return 0;
  12502. }
  12503. }
  12504. if (1 == mg_atomic_inc(p_reload_lock)) {
  12505. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  12506. == 0) {
  12507. return 0;
  12508. }
  12509. *p_reload_lock = 0;
  12510. }
  12511. }
  12512. /* lock while cert is reloading */
  12513. while (*p_reload_lock) {
  12514. sleep(1);
  12515. }
  12516. return 1;
  12517. }
  12518. #if defined(OPENSSL_API_1_1)
  12519. #else
  12520. static pthread_mutex_t *ssl_mutexes;
  12521. #endif /* OPENSSL_API_1_1 */
  12522. static int
  12523. sslize(struct mg_connection *conn,
  12524. SSL_CTX *s,
  12525. int (*func)(SSL *),
  12526. volatile int *stop_server)
  12527. {
  12528. int ret, err;
  12529. int short_trust;
  12530. unsigned i;
  12531. if (!conn) {
  12532. return 0;
  12533. }
  12534. short_trust =
  12535. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  12536. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  12537. if (short_trust) {
  12538. int trust_ret = refresh_trust(conn);
  12539. if (!trust_ret) {
  12540. return trust_ret;
  12541. }
  12542. }
  12543. conn->ssl = SSL_new(s);
  12544. if (conn->ssl == NULL) {
  12545. return 0;
  12546. }
  12547. SSL_set_app_data(conn->ssl, (char *)conn);
  12548. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  12549. if (ret != 1) {
  12550. err = SSL_get_error(conn->ssl, ret);
  12551. mg_cry_internal(conn, "SSL error %i, destroying SSL context", err);
  12552. SSL_free(conn->ssl);
  12553. conn->ssl = NULL;
  12554. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12555. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12556. #if !defined(OPENSSL_API_1_1)
  12557. ERR_remove_state(0);
  12558. #endif
  12559. return 0;
  12560. }
  12561. /* SSL functions may fail and require to be called again:
  12562. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  12563. * Here "func" could be SSL_connect or SSL_accept. */
  12564. for (i = 16; i <= 1024; i *= 2) {
  12565. ret = func(conn->ssl);
  12566. if (ret != 1) {
  12567. err = SSL_get_error(conn->ssl, ret);
  12568. if ((err == SSL_ERROR_WANT_CONNECT)
  12569. || (err == SSL_ERROR_WANT_ACCEPT)
  12570. || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)
  12571. || (err == SSL_ERROR_WANT_X509_LOOKUP)) {
  12572. /* Need to retry the function call "later".
  12573. * See https://linux.die.net/man/3/ssl_get_error
  12574. * This is typical for non-blocking sockets. */
  12575. if (*stop_server) {
  12576. /* Don't wait if the server is going to be stopped. */
  12577. break;
  12578. }
  12579. mg_sleep(i);
  12580. } else if (err == SSL_ERROR_SYSCALL) {
  12581. /* This is an IO error. Look at errno. */
  12582. err = errno;
  12583. mg_cry_internal(conn, "SSL syscall error %i", err);
  12584. break;
  12585. } else {
  12586. /* This is an SSL specific error, e.g. SSL_ERROR_SSL */
  12587. mg_cry_internal(conn, "sslize error: %s", ssl_error());
  12588. break;
  12589. }
  12590. } else {
  12591. /* success */
  12592. break;
  12593. }
  12594. }
  12595. if (ret != 1) {
  12596. SSL_free(conn->ssl);
  12597. conn->ssl = NULL;
  12598. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12599. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12600. #if !defined(OPENSSL_API_1_1)
  12601. ERR_remove_state(0);
  12602. #endif
  12603. return 0;
  12604. }
  12605. return 1;
  12606. }
  12607. /* Return OpenSSL error message (from CRYPTO lib) */
  12608. static const char *
  12609. ssl_error(void)
  12610. {
  12611. unsigned long err;
  12612. err = ERR_get_error();
  12613. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  12614. }
  12615. static int
  12616. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  12617. {
  12618. int i;
  12619. const char hexdigit[] = "0123456789abcdef";
  12620. if ((memlen <= 0) || (buflen <= 0)) {
  12621. return 0;
  12622. }
  12623. if (buflen < (3 * memlen)) {
  12624. return 0;
  12625. }
  12626. for (i = 0; i < memlen; i++) {
  12627. if (i > 0) {
  12628. buf[3 * i - 1] = ' ';
  12629. }
  12630. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  12631. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  12632. }
  12633. buf[3 * memlen - 1] = 0;
  12634. return 1;
  12635. }
  12636. static void
  12637. ssl_get_client_cert_info(struct mg_connection *conn)
  12638. {
  12639. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  12640. if (cert) {
  12641. char str_subject[1024];
  12642. char str_issuer[1024];
  12643. char str_finger[1024];
  12644. unsigned char buf[256];
  12645. char *str_serial = NULL;
  12646. unsigned int ulen;
  12647. int ilen;
  12648. unsigned char *tmp_buf;
  12649. unsigned char *tmp_p;
  12650. /* Handle to algorithm used for fingerprint */
  12651. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  12652. /* Get Subject and issuer */
  12653. X509_NAME *subj = X509_get_subject_name(cert);
  12654. X509_NAME *iss = X509_get_issuer_name(cert);
  12655. /* Get serial number */
  12656. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  12657. /* Translate serial number to a hex string */
  12658. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  12659. str_serial = BN_bn2hex(serial_bn);
  12660. BN_free(serial_bn);
  12661. /* Translate subject and issuer to a string */
  12662. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  12663. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  12664. /* Calculate SHA1 fingerprint and store as a hex string */
  12665. ulen = 0;
  12666. /* ASN1_digest is deprecated. Do the calculation manually,
  12667. * using EVP_Digest. */
  12668. ilen = i2d_X509(cert, NULL);
  12669. tmp_buf = (ilen > 0)
  12670. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  12671. conn->phys_ctx)
  12672. : NULL;
  12673. if (tmp_buf) {
  12674. tmp_p = tmp_buf;
  12675. (void)i2d_X509(cert, &tmp_p);
  12676. if (!EVP_Digest(
  12677. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  12678. ulen = 0;
  12679. }
  12680. mg_free(tmp_buf);
  12681. }
  12682. if (!hexdump2string(
  12683. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  12684. *str_finger = 0;
  12685. }
  12686. conn->request_info.client_cert = (struct mg_client_cert *)
  12687. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  12688. if (conn->request_info.client_cert) {
  12689. conn->request_info.client_cert->peer_cert = (void *)cert;
  12690. conn->request_info.client_cert->subject =
  12691. mg_strdup_ctx(str_subject, conn->phys_ctx);
  12692. conn->request_info.client_cert->issuer =
  12693. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  12694. conn->request_info.client_cert->serial =
  12695. mg_strdup_ctx(str_serial, conn->phys_ctx);
  12696. conn->request_info.client_cert->finger =
  12697. mg_strdup_ctx(str_finger, conn->phys_ctx);
  12698. } else {
  12699. mg_cry_internal(conn,
  12700. "%s",
  12701. "Out of memory: Cannot allocate memory for client "
  12702. "certificate");
  12703. }
  12704. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  12705. * see https://linux.die.net/man/3/bn_bn2hex */
  12706. OPENSSL_free(str_serial);
  12707. }
  12708. }
  12709. #if defined(OPENSSL_API_1_1)
  12710. #else
  12711. static void
  12712. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  12713. {
  12714. (void)line;
  12715. (void)file;
  12716. if (mode & 1) {
  12717. /* 1 is CRYPTO_LOCK */
  12718. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  12719. } else {
  12720. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  12721. }
  12722. }
  12723. #endif /* OPENSSL_API_1_1 */
  12724. #if !defined(NO_SSL_DL)
  12725. static void *
  12726. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  12727. {
  12728. union {
  12729. void *p;
  12730. void (*fp)(void);
  12731. } u;
  12732. void *dll_handle;
  12733. struct ssl_func *fp;
  12734. int ok;
  12735. int truncated = 0;
  12736. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  12737. mg_snprintf(NULL,
  12738. NULL, /* No truncation check for ebuf */
  12739. ebuf,
  12740. ebuf_len,
  12741. "%s: cannot load %s",
  12742. __func__,
  12743. dll_name);
  12744. return NULL;
  12745. }
  12746. ok = 1;
  12747. for (fp = sw; fp->name != NULL; fp++) {
  12748. #if defined(_WIN32)
  12749. /* GetProcAddress() returns pointer to function */
  12750. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  12751. #else
  12752. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  12753. * pointers to function pointers. We need to use a union to make a
  12754. * cast. */
  12755. u.p = dlsym(dll_handle, fp->name);
  12756. #endif /* _WIN32 */
  12757. if (u.fp == NULL) {
  12758. if (ok) {
  12759. mg_snprintf(NULL,
  12760. &truncated,
  12761. ebuf,
  12762. ebuf_len,
  12763. "%s: %s: cannot find %s",
  12764. __func__,
  12765. dll_name,
  12766. fp->name);
  12767. ok = 0;
  12768. } else {
  12769. size_t cur_len = strlen(ebuf);
  12770. if (!truncated) {
  12771. mg_snprintf(NULL,
  12772. &truncated,
  12773. ebuf + cur_len,
  12774. ebuf_len - cur_len - 3,
  12775. ", %s",
  12776. fp->name);
  12777. if (truncated) {
  12778. /* If truncated, add "..." */
  12779. strcat(ebuf, "...");
  12780. }
  12781. }
  12782. }
  12783. /* Debug:
  12784. * printf("Missing function: %s\n", fp->name); */
  12785. } else {
  12786. fp->ptr = u.fp;
  12787. }
  12788. }
  12789. if (!ok) {
  12790. (void)dlclose(dll_handle);
  12791. return NULL;
  12792. }
  12793. return dll_handle;
  12794. }
  12795. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  12796. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  12797. #endif /* NO_SSL_DL */
  12798. #if defined(SSL_ALREADY_INITIALIZED)
  12799. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  12800. #else
  12801. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  12802. #endif
  12803. static int
  12804. initialize_ssl(char *ebuf, size_t ebuf_len)
  12805. {
  12806. #if defined(OPENSSL_API_1_1)
  12807. if (ebuf_len > 0) {
  12808. ebuf[0] = 0;
  12809. }
  12810. #if !defined(NO_SSL_DL)
  12811. if (!cryptolib_dll_handle) {
  12812. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12813. if (!cryptolib_dll_handle) {
  12814. mg_snprintf(NULL,
  12815. NULL, /* No truncation check for ebuf */
  12816. ebuf,
  12817. ebuf_len,
  12818. "%s: error loading library %s",
  12819. __func__,
  12820. CRYPTO_LIB);
  12821. DEBUG_TRACE("%s", ebuf);
  12822. return 0;
  12823. }
  12824. }
  12825. #endif /* NO_SSL_DL */
  12826. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12827. return 1;
  12828. }
  12829. #else /* not OPENSSL_API_1_1 */
  12830. int i;
  12831. size_t size;
  12832. if (ebuf_len > 0) {
  12833. ebuf[0] = 0;
  12834. }
  12835. #if !defined(NO_SSL_DL)
  12836. if (!cryptolib_dll_handle) {
  12837. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12838. if (!cryptolib_dll_handle) {
  12839. mg_snprintf(NULL,
  12840. NULL, /* No truncation check for ebuf */
  12841. ebuf,
  12842. ebuf_len,
  12843. "%s: error loading library %s",
  12844. __func__,
  12845. CRYPTO_LIB);
  12846. DEBUG_TRACE("%s", ebuf);
  12847. return 0;
  12848. }
  12849. }
  12850. #endif /* NO_SSL_DL */
  12851. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12852. return 1;
  12853. }
  12854. /* Initialize locking callbacks, needed for thread safety.
  12855. * http://www.openssl.org/support/faq.html#PROG1
  12856. */
  12857. i = CRYPTO_num_locks();
  12858. if (i < 0) {
  12859. i = 0;
  12860. }
  12861. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  12862. if (size == 0) {
  12863. ssl_mutexes = NULL;
  12864. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  12865. mg_snprintf(NULL,
  12866. NULL, /* No truncation check for ebuf */
  12867. ebuf,
  12868. ebuf_len,
  12869. "%s: cannot allocate mutexes: %s",
  12870. __func__,
  12871. ssl_error());
  12872. DEBUG_TRACE("%s", ebuf);
  12873. return 0;
  12874. }
  12875. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12876. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  12877. }
  12878. CRYPTO_set_locking_callback(&ssl_locking_callback);
  12879. CRYPTO_set_id_callback(&mg_current_thread_id);
  12880. #endif /* OPENSSL_API_1_1 */
  12881. #if !defined(NO_SSL_DL)
  12882. if (!ssllib_dll_handle) {
  12883. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  12884. if (!ssllib_dll_handle) {
  12885. DEBUG_TRACE("%s", ebuf);
  12886. return 0;
  12887. }
  12888. }
  12889. #endif /* NO_SSL_DL */
  12890. #if defined(OPENSSL_API_1_1)
  12891. /* Initialize SSL library */
  12892. OPENSSL_init_ssl(0, NULL);
  12893. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  12894. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  12895. NULL);
  12896. #else
  12897. /* Initialize SSL library */
  12898. SSL_library_init();
  12899. SSL_load_error_strings();
  12900. #endif
  12901. return 1;
  12902. }
  12903. static int
  12904. ssl_use_pem_file(struct mg_context *phys_ctx,
  12905. struct mg_domain_context *dom_ctx,
  12906. const char *pem,
  12907. const char *chain)
  12908. {
  12909. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  12910. mg_cry_internal(fc(phys_ctx),
  12911. "%s: cannot open certificate file %s: %s",
  12912. __func__,
  12913. pem,
  12914. ssl_error());
  12915. return 0;
  12916. }
  12917. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  12918. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  12919. mg_cry_internal(fc(phys_ctx),
  12920. "%s: cannot open private key file %s: %s",
  12921. __func__,
  12922. pem,
  12923. ssl_error());
  12924. return 0;
  12925. }
  12926. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  12927. mg_cry_internal(fc(phys_ctx),
  12928. "%s: certificate and private key do not match: %s",
  12929. __func__,
  12930. pem);
  12931. return 0;
  12932. }
  12933. /* In contrast to OpenSSL, wolfSSL does not support certificate
  12934. * chain files that contain private keys and certificates in
  12935. * SSL_CTX_use_certificate_chain_file.
  12936. * The CivetWeb-Server used pem-Files that contained both information.
  12937. * In order to make wolfSSL work, it is split in two files.
  12938. * One file that contains key and certificate used by the server and
  12939. * an optional chain file for the ssl stack.
  12940. */
  12941. if (chain) {
  12942. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  12943. mg_cry_internal(fc(phys_ctx),
  12944. "%s: cannot use certificate chain file %s: %s",
  12945. __func__,
  12946. pem,
  12947. ssl_error());
  12948. return 0;
  12949. }
  12950. }
  12951. return 1;
  12952. }
  12953. #if defined(OPENSSL_API_1_1)
  12954. static unsigned long
  12955. ssl_get_protocol(int version_id)
  12956. {
  12957. long unsigned ret = SSL_OP_ALL;
  12958. if (version_id > 0)
  12959. ret |= SSL_OP_NO_SSLv2;
  12960. if (version_id > 1)
  12961. ret |= SSL_OP_NO_SSLv3;
  12962. if (version_id > 2)
  12963. ret |= SSL_OP_NO_TLSv1;
  12964. if (version_id > 3)
  12965. ret |= SSL_OP_NO_TLSv1_1;
  12966. return ret;
  12967. }
  12968. #else
  12969. static long
  12970. ssl_get_protocol(int version_id)
  12971. {
  12972. long ret = SSL_OP_ALL;
  12973. if (version_id > 0)
  12974. ret |= SSL_OP_NO_SSLv2;
  12975. if (version_id > 1)
  12976. ret |= SSL_OP_NO_SSLv3;
  12977. if (version_id > 2)
  12978. ret |= SSL_OP_NO_TLSv1;
  12979. if (version_id > 3)
  12980. ret |= SSL_OP_NO_TLSv1_1;
  12981. return ret;
  12982. }
  12983. #endif /* OPENSSL_API_1_1 */
  12984. /* SSL callback documentation:
  12985. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  12986. * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3)
  12987. * https://linux.die.net/man/3/ssl_set_info_callback */
  12988. /* Note: There is no "const" for the first argument in the documentation,
  12989. * however some (maybe most, but not all) headers of OpenSSL versions /
  12990. * OpenSSL compatibility layers have it. Having a different definition
  12991. * will cause a warning in C and an error in C++. With inconsitent
  12992. * definitions of this function, having a warning in one version or
  12993. * another is unavoidable. */
  12994. static void
  12995. ssl_info_callback(SSL *ssl, int what, int ret)
  12996. {
  12997. (void)ret;
  12998. if (what & SSL_CB_HANDSHAKE_START) {
  12999. SSL_get_app_data(ssl);
  13000. }
  13001. if (what & SSL_CB_HANDSHAKE_DONE) {
  13002. /* TODO: check for openSSL 1.1 */
  13003. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  13004. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  13005. }
  13006. }
  13007. static int
  13008. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  13009. {
  13010. struct mg_context *ctx = (struct mg_context *)arg;
  13011. struct mg_domain_context *dom =
  13012. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  13013. #if defined(__GNUC__) || defined(__MINGW32__)
  13014. #pragma GCC diagnostic push
  13015. #pragma GCC diagnostic ignored "-Wcast-align"
  13016. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13017. /* We used an aligned pointer in SSL_set_app_data */
  13018. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  13019. #if defined(__GNUC__) || defined(__MINGW32__)
  13020. #pragma GCC diagnostic pop
  13021. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13022. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  13023. (void)ad;
  13024. if ((ctx == NULL) || (conn->phys_ctx == ctx)) {
  13025. DEBUG_TRACE("%s", "internal error - assertion failed");
  13026. return SSL_TLSEXT_ERR_NOACK;
  13027. }
  13028. /* Old clients (Win XP) will not support SNI. Then, there
  13029. * is no server name available in the request - we can
  13030. * only work with the default certificate.
  13031. * Multiple HTTPS hosts on one IP+port are only possible
  13032. * with a certificate containing all alternative names.
  13033. */
  13034. if ((servername == NULL) || (*servername == 0)) {
  13035. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  13036. conn->dom_ctx = &(ctx->dd);
  13037. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13038. return SSL_TLSEXT_ERR_NOACK;
  13039. }
  13040. DEBUG_TRACE("TLS connection to host %s", servername);
  13041. while (dom) {
  13042. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  13043. /* Found matching domain */
  13044. DEBUG_TRACE("TLS domain %s found",
  13045. dom->config[AUTHENTICATION_DOMAIN]);
  13046. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  13047. conn->dom_ctx = dom;
  13048. return SSL_TLSEXT_ERR_OK;
  13049. }
  13050. dom = dom->next;
  13051. }
  13052. /* Default domain */
  13053. DEBUG_TRACE("TLS default domain %s used",
  13054. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  13055. conn->dom_ctx = &(ctx->dd);
  13056. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  13057. return SSL_TLSEXT_ERR_OK;
  13058. }
  13059. /* Setup SSL CTX as required by CivetWeb */
  13060. static int
  13061. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  13062. struct mg_domain_context *dom_ctx,
  13063. const char *pem,
  13064. const char *chain)
  13065. {
  13066. int callback_ret;
  13067. int should_verify_peer;
  13068. int peer_certificate_optional;
  13069. const char *ca_path;
  13070. const char *ca_file;
  13071. int use_default_verify_paths;
  13072. int verify_depth;
  13073. struct timespec now_mt;
  13074. md5_byte_t ssl_context_id[16];
  13075. md5_state_t md5state;
  13076. int protocol_ver;
  13077. #if defined(OPENSSL_API_1_1)
  13078. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  13079. mg_cry_internal(fc(phys_ctx),
  13080. "SSL_CTX_new (server) error: %s",
  13081. ssl_error());
  13082. return 0;
  13083. }
  13084. #else
  13085. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  13086. mg_cry_internal(fc(phys_ctx),
  13087. "SSL_CTX_new (server) error: %s",
  13088. ssl_error());
  13089. return 0;
  13090. }
  13091. #endif /* OPENSSL_API_1_1 */
  13092. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  13093. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  13094. | SSL_OP_NO_TLSv1_1);
  13095. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  13096. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  13097. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  13098. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  13099. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  13100. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  13101. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  13102. #if !defined(NO_SSL_DL)
  13103. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  13104. #endif /* NO_SSL_DL */
  13105. #if defined(__clang__)
  13106. #pragma clang diagnostic push
  13107. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  13108. #endif
  13109. /* Depending on the OpenSSL version, the callback may be
  13110. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  13111. * yielding in an "incompatible-pointer-type" warning for the other
  13112. * version. It seems to be "unclear" what is correct:
  13113. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  13114. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  13115. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  13116. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  13117. * Disable this warning here.
  13118. * Alternative would be a version dependent ssl_info_callback and
  13119. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  13120. */
  13121. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  13122. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  13123. ssl_servername_callback);
  13124. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  13125. #if defined(__clang__)
  13126. #pragma clang diagnostic pop
  13127. #endif
  13128. /* If a callback has been specified, call it. */
  13129. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  13130. ? 0
  13131. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  13132. phys_ctx->user_data));
  13133. /* If callback returns 0, civetweb sets up the SSL certificate.
  13134. * If it returns 1, civetweb assumes the calback already did this.
  13135. * If it returns -1, initializing ssl fails. */
  13136. if (callback_ret < 0) {
  13137. mg_cry_internal(fc(phys_ctx),
  13138. "SSL callback returned error: %i",
  13139. callback_ret);
  13140. return 0;
  13141. }
  13142. if (callback_ret > 0) {
  13143. /* Callback did everything. */
  13144. return 1;
  13145. }
  13146. /* Use some combination of start time, domain and port as a SSL
  13147. * context ID. This should be unique on the current machine. */
  13148. md5_init(&md5state);
  13149. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  13150. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  13151. md5_append(&md5state,
  13152. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  13153. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  13154. md5_append(&md5state,
  13155. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  13156. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  13157. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  13158. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  13159. md5_finish(&md5state, ssl_context_id);
  13160. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  13161. (unsigned char *)ssl_context_id,
  13162. sizeof(ssl_context_id));
  13163. if (pem != NULL) {
  13164. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  13165. return 0;
  13166. }
  13167. }
  13168. /* Should we support client certificates? */
  13169. /* Default is "no". */
  13170. should_verify_peer = 0;
  13171. peer_certificate_optional = 0;
  13172. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  13173. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  13174. /* Yes, they are mandatory */
  13175. should_verify_peer = 1;
  13176. peer_certificate_optional = 0;
  13177. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  13178. "optional") == 0) {
  13179. /* Yes, they are optional */
  13180. should_verify_peer = 1;
  13181. peer_certificate_optional = 1;
  13182. }
  13183. }
  13184. use_default_verify_paths =
  13185. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  13186. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  13187. == 0);
  13188. if (should_verify_peer) {
  13189. ca_path = dom_ctx->config[SSL_CA_PATH];
  13190. ca_file = dom_ctx->config[SSL_CA_FILE];
  13191. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  13192. != 1) {
  13193. mg_cry_internal(fc(phys_ctx),
  13194. "SSL_CTX_load_verify_locations error: %s "
  13195. "ssl_verify_peer requires setting "
  13196. "either ssl_ca_path or ssl_ca_file. "
  13197. "Is any of them present in the "
  13198. ".conf file?",
  13199. ssl_error());
  13200. return 0;
  13201. }
  13202. if (peer_certificate_optional) {
  13203. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  13204. } else {
  13205. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  13206. SSL_VERIFY_PEER
  13207. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  13208. NULL);
  13209. }
  13210. if (use_default_verify_paths
  13211. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  13212. mg_cry_internal(fc(phys_ctx),
  13213. "SSL_CTX_set_default_verify_paths error: %s",
  13214. ssl_error());
  13215. return 0;
  13216. }
  13217. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  13218. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  13219. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  13220. }
  13221. }
  13222. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  13223. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  13224. dom_ctx->config[SSL_CIPHER_LIST]) != 1) {
  13225. mg_cry_internal(fc(phys_ctx),
  13226. "SSL_CTX_set_cipher_list error: %s",
  13227. ssl_error());
  13228. }
  13229. }
  13230. return 1;
  13231. }
  13232. /* Check if SSL is required.
  13233. * If so, dynamically load SSL library
  13234. * and set up ctx->ssl_ctx pointer. */
  13235. static int
  13236. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13237. {
  13238. void *ssl_ctx = 0;
  13239. int callback_ret;
  13240. const char *pem;
  13241. const char *chain;
  13242. char ebuf[128];
  13243. if (!phys_ctx) {
  13244. return 0;
  13245. }
  13246. if (!dom_ctx) {
  13247. dom_ctx = &(phys_ctx->dd);
  13248. }
  13249. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  13250. /* No SSL port is set. No need to setup SSL. */
  13251. return 1;
  13252. }
  13253. /* Check for external SSL_CTX */
  13254. callback_ret =
  13255. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  13256. ? 0
  13257. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  13258. phys_ctx->user_data));
  13259. if (callback_ret < 0) {
  13260. mg_cry_internal(fc(phys_ctx),
  13261. "external_ssl_ctx callback returned error: %i",
  13262. callback_ret);
  13263. return 0;
  13264. } else if (callback_ret > 0) {
  13265. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  13266. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13267. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13268. return 0;
  13269. }
  13270. return 1;
  13271. }
  13272. /* else: external_ssl_ctx does not exist or returns 0,
  13273. * CivetWeb should continue initializing SSL */
  13274. /* If PEM file is not specified and the init_ssl callback
  13275. * is not specified, setup will fail. */
  13276. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  13277. && (phys_ctx->callbacks.init_ssl == NULL)) {
  13278. /* No certificate and no callback:
  13279. * Essential data to set up TLS is missing.
  13280. */
  13281. mg_cry_internal(fc(phys_ctx),
  13282. "Initializing SSL failed: -%s is not set",
  13283. config_options[SSL_CERTIFICATE].name);
  13284. return 0;
  13285. }
  13286. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  13287. if (chain == NULL) {
  13288. chain = pem;
  13289. }
  13290. if ((chain != NULL) && (*chain == 0)) {
  13291. chain = NULL;
  13292. }
  13293. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  13294. mg_cry_internal(fc(phys_ctx), "%s", ebuf);
  13295. return 0;
  13296. }
  13297. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  13298. }
  13299. static void
  13300. uninitialize_ssl(void)
  13301. {
  13302. #if defined(OPENSSL_API_1_1)
  13303. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13304. /* Shutdown according to
  13305. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13306. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13307. */
  13308. CONF_modules_unload(1);
  13309. #else
  13310. int i;
  13311. if (mg_atomic_dec(&cryptolib_users) == 0) {
  13312. /* Shutdown according to
  13313. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  13314. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  13315. */
  13316. CRYPTO_set_locking_callback(NULL);
  13317. CRYPTO_set_id_callback(NULL);
  13318. ENGINE_cleanup();
  13319. CONF_modules_unload(1);
  13320. ERR_free_strings();
  13321. EVP_cleanup();
  13322. CRYPTO_cleanup_all_ex_data();
  13323. ERR_remove_state(0);
  13324. for (i = 0; i < CRYPTO_num_locks(); i++) {
  13325. pthread_mutex_destroy(&ssl_mutexes[i]);
  13326. }
  13327. mg_free(ssl_mutexes);
  13328. ssl_mutexes = NULL;
  13329. #endif /* OPENSSL_API_1_1 */
  13330. }
  13331. }
  13332. #endif /* !NO_SSL */
  13333. static int
  13334. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  13335. {
  13336. if (phys_ctx) {
  13337. struct mg_file file = STRUCT_FILE_INITIALIZER;
  13338. const char *path;
  13339. if (!dom_ctx) {
  13340. dom_ctx = &(phys_ctx->dd);
  13341. }
  13342. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  13343. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  13344. mg_cry_internal(fc(phys_ctx),
  13345. "Cannot open %s: %s",
  13346. path,
  13347. strerror(ERRNO));
  13348. return 0;
  13349. }
  13350. return 1;
  13351. }
  13352. return 0;
  13353. }
  13354. static int
  13355. set_acl_option(struct mg_context *phys_ctx)
  13356. {
  13357. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  13358. }
  13359. static void
  13360. reset_per_request_attributes(struct mg_connection *conn)
  13361. {
  13362. if (!conn) {
  13363. return;
  13364. }
  13365. conn->connection_type =
  13366. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  13367. conn->num_bytes_sent = conn->consumed_content = 0;
  13368. conn->path_info = NULL;
  13369. conn->status_code = -1;
  13370. conn->content_len = -1;
  13371. conn->is_chunked = 0;
  13372. conn->must_close = 0;
  13373. conn->request_len = 0;
  13374. conn->throttle = 0;
  13375. conn->data_len = 0;
  13376. conn->chunk_remainder = 0;
  13377. conn->accept_gzip = 0;
  13378. conn->response_info.content_length = conn->request_info.content_length = -1;
  13379. conn->response_info.http_version = conn->request_info.http_version = NULL;
  13380. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  13381. conn->response_info.status_text = NULL;
  13382. conn->response_info.status_code = 0;
  13383. conn->request_info.remote_user = NULL;
  13384. conn->request_info.request_method = NULL;
  13385. conn->request_info.request_uri = NULL;
  13386. conn->request_info.local_uri = NULL;
  13387. #if defined(MG_LEGACY_INTERFACE)
  13388. /* Legacy before split into local_uri and request_uri */
  13389. conn->request_info.uri = NULL;
  13390. #endif
  13391. }
  13392. #if 0
  13393. /* Note: set_sock_timeout is not required for non-blocking sockets.
  13394. * Leave this function here (commented out) for reference until
  13395. * CivetWeb 1.9 is tested, and the tests confirme this function is
  13396. * no longer required.
  13397. */
  13398. static int
  13399. set_sock_timeout(SOCKET sock, int milliseconds)
  13400. {
  13401. int r0 = 0, r1, r2;
  13402. #if defined(_WIN32)
  13403. /* Windows specific */
  13404. DWORD tv = (DWORD)milliseconds;
  13405. #else
  13406. /* Linux, ... (not Windows) */
  13407. struct timeval tv;
  13408. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  13409. * max. time waiting for the acknowledged of TCP data before the connection
  13410. * will be forcefully closed and ETIMEDOUT is returned to the application.
  13411. * If this option is not set, the default timeout of 20-30 minutes is used.
  13412. */
  13413. /* #define TCP_USER_TIMEOUT (18) */
  13414. #if defined(TCP_USER_TIMEOUT)
  13415. unsigned int uto = (unsigned int)milliseconds;
  13416. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  13417. #endif
  13418. memset(&tv, 0, sizeof(tv));
  13419. tv.tv_sec = milliseconds / 1000;
  13420. tv.tv_usec = (milliseconds * 1000) % 1000000;
  13421. #endif /* _WIN32 */
  13422. r1 = setsockopt(
  13423. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13424. r2 = setsockopt(
  13425. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  13426. return r0 || r1 || r2;
  13427. }
  13428. #endif
  13429. static int
  13430. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  13431. {
  13432. if (setsockopt(sock,
  13433. IPPROTO_TCP,
  13434. TCP_NODELAY,
  13435. (SOCK_OPT_TYPE)&nodelay_on,
  13436. sizeof(nodelay_on)) != 0) {
  13437. /* Error */
  13438. return 1;
  13439. }
  13440. /* OK */
  13441. return 0;
  13442. }
  13443. static void
  13444. close_socket_gracefully(struct mg_connection *conn)
  13445. {
  13446. #if defined(_WIN32)
  13447. char buf[MG_BUF_LEN];
  13448. int n;
  13449. #endif
  13450. struct linger linger;
  13451. int error_code = 0;
  13452. int linger_timeout = -2;
  13453. socklen_t opt_len = sizeof(error_code);
  13454. if (!conn) {
  13455. return;
  13456. }
  13457. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  13458. * "Note that enabling a nonzero timeout on a nonblocking socket
  13459. * is not recommended.", so set it to blocking now */
  13460. set_blocking_mode(conn->client.sock);
  13461. /* Send FIN to the client */
  13462. shutdown(conn->client.sock, SHUTDOWN_WR);
  13463. #if defined(_WIN32)
  13464. /* Read and discard pending incoming data. If we do not do that and
  13465. * close
  13466. * the socket, the data in the send buffer may be discarded. This
  13467. * behaviour is seen on Windows, when client keeps sending data
  13468. * when server decides to close the connection; then when client
  13469. * does recv() it gets no data back. */
  13470. do {
  13471. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  13472. } while (n > 0);
  13473. #endif
  13474. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  13475. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  13476. }
  13477. /* Set linger option according to configuration */
  13478. if (linger_timeout >= 0) {
  13479. /* Set linger option to avoid socket hanging out after close. This
  13480. * prevent ephemeral port exhaust problem under high QPS. */
  13481. linger.l_onoff = 1;
  13482. #if defined(_MSC_VER)
  13483. #pragma warning(push)
  13484. #pragma warning(disable : 4244)
  13485. #endif
  13486. #if defined(__GNUC__) || defined(__MINGW32__)
  13487. #pragma GCC diagnostic push
  13488. #pragma GCC diagnostic ignored "-Wconversion"
  13489. #endif
  13490. /* Data type of linger structure elements may differ,
  13491. * so we don't know what cast we need here.
  13492. * Disable type conversion warnings. */
  13493. linger.l_linger = (linger_timeout + 999) / 1000;
  13494. #if defined(__GNUC__) || defined(__MINGW32__)
  13495. #pragma GCC diagnostic pop
  13496. #endif
  13497. #if defined(_MSC_VER)
  13498. #pragma warning(pop)
  13499. #endif
  13500. } else {
  13501. linger.l_onoff = 0;
  13502. linger.l_linger = 0;
  13503. }
  13504. if (linger_timeout < -1) {
  13505. /* Default: don't configure any linger */
  13506. } else if (getsockopt(conn->client.sock,
  13507. SOL_SOCKET,
  13508. SO_ERROR,
  13509. #if defined(_WIN32) /* WinSock uses different data type here */
  13510. (char *)&error_code,
  13511. #else
  13512. &error_code,
  13513. #endif
  13514. &opt_len) != 0) {
  13515. /* Cannot determine if socket is already closed. This should
  13516. * not occur and never did in a test. Log an error message
  13517. * and continue. */
  13518. mg_cry_internal(conn,
  13519. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  13520. __func__,
  13521. strerror(ERRNO));
  13522. } else if (error_code == ECONNRESET) {
  13523. /* Socket already closed by client/peer, close socket without linger
  13524. */
  13525. } else {
  13526. /* Set linger timeout */
  13527. if (setsockopt(conn->client.sock,
  13528. SOL_SOCKET,
  13529. SO_LINGER,
  13530. (char *)&linger,
  13531. sizeof(linger)) != 0) {
  13532. mg_cry_internal(
  13533. conn,
  13534. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  13535. __func__,
  13536. linger.l_onoff,
  13537. linger.l_linger,
  13538. strerror(ERRNO));
  13539. }
  13540. }
  13541. /* Now we know that our FIN is ACK-ed, safe to close */
  13542. closesocket(conn->client.sock);
  13543. conn->client.sock = INVALID_SOCKET;
  13544. }
  13545. static void
  13546. close_connection(struct mg_connection *conn)
  13547. {
  13548. #if defined(USE_SERVER_STATS)
  13549. conn->conn_state = 6; /* to close */
  13550. #endif
  13551. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13552. if (conn->lua_websocket_state) {
  13553. lua_websocket_close(conn, conn->lua_websocket_state);
  13554. conn->lua_websocket_state = NULL;
  13555. }
  13556. #endif
  13557. mg_lock_connection(conn);
  13558. /* Set close flag, so keep-alive loops will stop */
  13559. conn->must_close = 1;
  13560. /* call the connection_close callback if assigned */
  13561. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  13562. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13563. conn->phys_ctx->callbacks.connection_close(conn);
  13564. }
  13565. }
  13566. /* Reset user data, after close callback is called.
  13567. * Do not reuse it. If the user needs a destructor,
  13568. * it must be done in the connection_close callback. */
  13569. mg_set_user_connection_data(conn, NULL);
  13570. #if defined(USE_SERVER_STATS)
  13571. conn->conn_state = 7; /* closing */
  13572. #endif
  13573. #if !defined(NO_SSL)
  13574. if (conn->ssl != NULL) {
  13575. /* Run SSL_shutdown twice to ensure completely close SSL connection
  13576. */
  13577. SSL_shutdown(conn->ssl);
  13578. SSL_free(conn->ssl);
  13579. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  13580. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  13581. #if !defined(OPENSSL_API_1_1)
  13582. ERR_remove_state(0);
  13583. #endif
  13584. conn->ssl = NULL;
  13585. }
  13586. #endif
  13587. if (conn->client.sock != INVALID_SOCKET) {
  13588. close_socket_gracefully(conn);
  13589. conn->client.sock = INVALID_SOCKET;
  13590. }
  13591. if (conn->host) {
  13592. mg_free((void *)conn->host);
  13593. conn->host = NULL;
  13594. }
  13595. mg_unlock_connection(conn);
  13596. #if defined(USE_SERVER_STATS)
  13597. conn->conn_state = 8; /* closed */
  13598. #endif
  13599. }
  13600. void
  13601. mg_close_connection(struct mg_connection *conn)
  13602. {
  13603. #if defined(USE_WEBSOCKET)
  13604. struct mg_context *client_ctx = NULL;
  13605. #endif /* defined(USE_WEBSOCKET) */
  13606. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  13607. return;
  13608. }
  13609. #if defined(USE_WEBSOCKET)
  13610. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13611. if (conn->in_websocket_handling) {
  13612. /* Set close flag, so the server thread can exit. */
  13613. conn->must_close = 1;
  13614. return;
  13615. }
  13616. }
  13617. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  13618. unsigned int i;
  13619. /* ws/wss client */
  13620. client_ctx = conn->phys_ctx;
  13621. /* client context: loops must end */
  13622. client_ctx->stop_flag = 1;
  13623. conn->must_close = 1;
  13624. /* We need to get the client thread out of the select/recv call
  13625. * here. */
  13626. /* Since we use a sleep quantum of some seconds to check for recv
  13627. * timeouts, we will just wait a few seconds in mg_join_thread. */
  13628. /* join worker thread */
  13629. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  13630. if (client_ctx->worker_threadids[i] != 0) {
  13631. mg_join_thread(client_ctx->worker_threadids[i]);
  13632. }
  13633. }
  13634. }
  13635. #endif /* defined(USE_WEBSOCKET) */
  13636. close_connection(conn);
  13637. #if !defined(NO_SSL)
  13638. if (conn->client_ssl_ctx != NULL) {
  13639. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  13640. }
  13641. #endif
  13642. #if defined(USE_WEBSOCKET)
  13643. if (client_ctx != NULL) {
  13644. /* free context */
  13645. mg_free(client_ctx->worker_threadids);
  13646. mg_free(client_ctx);
  13647. (void)pthread_mutex_destroy(&conn->mutex);
  13648. mg_free(conn);
  13649. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  13650. mg_free(conn);
  13651. }
  13652. #else
  13653. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  13654. mg_free(conn);
  13655. }
  13656. #endif /* defined(USE_WEBSOCKET) */
  13657. }
  13658. /* Only for memory statistics */
  13659. static struct mg_context common_client_context;
  13660. static struct mg_connection *
  13661. mg_connect_client_impl(const struct mg_client_options *client_options,
  13662. int use_ssl,
  13663. char *ebuf,
  13664. size_t ebuf_len)
  13665. {
  13666. struct mg_connection *conn = NULL;
  13667. SOCKET sock;
  13668. union usa sa;
  13669. struct sockaddr *psa;
  13670. socklen_t len;
  13671. unsigned max_req_size =
  13672. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  13673. /* Size of structures, aligned to 8 bytes */
  13674. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  13675. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  13676. conn = (struct mg_connection *)mg_calloc_ctx(1,
  13677. conn_size + ctx_size
  13678. + max_req_size,
  13679. &common_client_context);
  13680. if (conn == NULL) {
  13681. mg_snprintf(NULL,
  13682. NULL, /* No truncation check for ebuf */
  13683. ebuf,
  13684. ebuf_len,
  13685. "calloc(): %s",
  13686. strerror(ERRNO));
  13687. return NULL;
  13688. }
  13689. #if defined(__GNUC__) || defined(__MINGW32__)
  13690. #pragma GCC diagnostic push
  13691. #pragma GCC diagnostic ignored "-Wcast-align"
  13692. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13693. /* conn_size is aligned to 8 bytes */
  13694. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  13695. #if defined(__GNUC__) || defined(__MINGW32__)
  13696. #pragma GCC diagnostic pop
  13697. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13698. conn->buf = (((char *)conn) + conn_size + ctx_size);
  13699. conn->buf_size = (int)max_req_size;
  13700. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  13701. conn->dom_ctx = &(conn->phys_ctx->dd);
  13702. if (!connect_socket(&common_client_context,
  13703. client_options->host,
  13704. client_options->port,
  13705. use_ssl,
  13706. ebuf,
  13707. ebuf_len,
  13708. &sock,
  13709. &sa)) {
  13710. /* ebuf is set by connect_socket,
  13711. * free all memory and return NULL; */
  13712. mg_free(conn);
  13713. return NULL;
  13714. }
  13715. #if !defined(NO_SSL)
  13716. #if defined(OPENSSL_API_1_1)
  13717. if (use_ssl
  13718. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  13719. mg_snprintf(NULL,
  13720. NULL, /* No truncation check for ebuf */
  13721. ebuf,
  13722. ebuf_len,
  13723. "SSL_CTX_new error");
  13724. closesocket(sock);
  13725. mg_free(conn);
  13726. return NULL;
  13727. }
  13728. #else
  13729. if (use_ssl
  13730. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  13731. == NULL) {
  13732. mg_snprintf(NULL,
  13733. NULL, /* No truncation check for ebuf */
  13734. ebuf,
  13735. ebuf_len,
  13736. "SSL_CTX_new error");
  13737. closesocket(sock);
  13738. mg_free(conn);
  13739. return NULL;
  13740. }
  13741. #endif /* OPENSSL_API_1_1 */
  13742. #endif /* NO_SSL */
  13743. #if defined(USE_IPV6)
  13744. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  13745. : sizeof(conn->client.rsa.sin6);
  13746. psa = (sa.sa.sa_family == AF_INET)
  13747. ? (struct sockaddr *)&(conn->client.rsa.sin)
  13748. : (struct sockaddr *)&(conn->client.rsa.sin6);
  13749. #else
  13750. len = sizeof(conn->client.rsa.sin);
  13751. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  13752. #endif
  13753. conn->client.sock = sock;
  13754. conn->client.lsa = sa;
  13755. if (getsockname(sock, psa, &len) != 0) {
  13756. mg_cry_internal(conn,
  13757. "%s: getsockname() failed: %s",
  13758. __func__,
  13759. strerror(ERRNO));
  13760. }
  13761. conn->client.is_ssl = use_ssl ? 1 : 0;
  13762. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13763. #if !defined(NO_SSL)
  13764. if (use_ssl) {
  13765. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  13766. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  13767. * SSL_CTX_set_verify call is needed to switch off server
  13768. * certificate checking, which is off by default in OpenSSL and
  13769. * on in yaSSL. */
  13770. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  13771. * SSL_VERIFY_PEER, verify_ssl_server); */
  13772. if (client_options->client_cert) {
  13773. if (!ssl_use_pem_file(&common_client_context,
  13774. &(common_client_context.dd),
  13775. client_options->client_cert,
  13776. NULL)) {
  13777. mg_snprintf(NULL,
  13778. NULL, /* No truncation check for ebuf */
  13779. ebuf,
  13780. ebuf_len,
  13781. "Can not use SSL client certificate");
  13782. SSL_CTX_free(conn->client_ssl_ctx);
  13783. closesocket(sock);
  13784. mg_free(conn);
  13785. return NULL;
  13786. }
  13787. }
  13788. if (client_options->server_cert) {
  13789. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  13790. client_options->server_cert,
  13791. NULL);
  13792. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  13793. } else {
  13794. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  13795. }
  13796. if (!sslize(conn,
  13797. conn->client_ssl_ctx,
  13798. SSL_connect,
  13799. &(conn->phys_ctx->stop_flag))) {
  13800. mg_snprintf(NULL,
  13801. NULL, /* No truncation check for ebuf */
  13802. ebuf,
  13803. ebuf_len,
  13804. "SSL connection error");
  13805. SSL_CTX_free(conn->client_ssl_ctx);
  13806. closesocket(sock);
  13807. mg_free(conn);
  13808. return NULL;
  13809. }
  13810. }
  13811. #endif
  13812. if (0 != set_non_blocking_mode(sock)) {
  13813. mg_cry_internal(conn,
  13814. "Cannot set non-blocking mode for client %s:%i",
  13815. client_options->host,
  13816. client_options->port);
  13817. }
  13818. return conn;
  13819. }
  13820. CIVETWEB_API struct mg_connection *
  13821. mg_connect_client_secure(const struct mg_client_options *client_options,
  13822. char *error_buffer,
  13823. size_t error_buffer_size)
  13824. {
  13825. return mg_connect_client_impl(client_options,
  13826. 1,
  13827. error_buffer,
  13828. error_buffer_size);
  13829. }
  13830. struct mg_connection *
  13831. mg_connect_client(const char *host,
  13832. int port,
  13833. int use_ssl,
  13834. char *error_buffer,
  13835. size_t error_buffer_size)
  13836. {
  13837. struct mg_client_options opts;
  13838. memset(&opts, 0, sizeof(opts));
  13839. opts.host = host;
  13840. opts.port = port;
  13841. return mg_connect_client_impl(&opts,
  13842. use_ssl,
  13843. error_buffer,
  13844. error_buffer_size);
  13845. }
  13846. static const struct {
  13847. const char *proto;
  13848. size_t proto_len;
  13849. unsigned default_port;
  13850. } abs_uri_protocols[] = {{"http://", 7, 80},
  13851. {"https://", 8, 443},
  13852. {"ws://", 5, 80},
  13853. {"wss://", 6, 443},
  13854. {NULL, 0, 0}};
  13855. /* Check if the uri is valid.
  13856. * return 0 for invalid uri,
  13857. * return 1 for *,
  13858. * return 2 for relative uri,
  13859. * return 3 for absolute uri without port,
  13860. * return 4 for absolute uri with port */
  13861. static int
  13862. get_uri_type(const char *uri)
  13863. {
  13864. int i;
  13865. const char *hostend, *portbegin;
  13866. char *portend;
  13867. unsigned long port;
  13868. /* According to the HTTP standard
  13869. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  13870. * URI can be an asterisk (*) or should start with slash (relative uri),
  13871. * or it should start with the protocol (absolute uri). */
  13872. if ((uri[0] == '*') && (uri[1] == '\0')) {
  13873. /* asterisk */
  13874. return 1;
  13875. }
  13876. /* Valid URIs according to RFC 3986
  13877. * (https://www.ietf.org/rfc/rfc3986.txt)
  13878. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  13879. * and unreserved characters A-Z a-z 0-9 and -._~
  13880. * and % encoded symbols.
  13881. */
  13882. for (i = 0; uri[i] != 0; i++) {
  13883. if (uri[i] < 33) {
  13884. /* control characters and spaces are invalid */
  13885. return 0;
  13886. }
  13887. if (uri[i] > 126) {
  13888. /* non-ascii characters must be % encoded */
  13889. return 0;
  13890. } else {
  13891. switch (uri[i]) {
  13892. case '"': /* 34 */
  13893. case '<': /* 60 */
  13894. case '>': /* 62 */
  13895. case '\\': /* 92 */
  13896. case '^': /* 94 */
  13897. case '`': /* 96 */
  13898. case '{': /* 123 */
  13899. case '|': /* 124 */
  13900. case '}': /* 125 */
  13901. return 0;
  13902. default:
  13903. /* character is ok */
  13904. break;
  13905. }
  13906. }
  13907. }
  13908. /* A relative uri starts with a / character */
  13909. if (uri[0] == '/') {
  13910. /* relative uri */
  13911. return 2;
  13912. }
  13913. /* It could be an absolute uri: */
  13914. /* This function only checks if the uri is valid, not if it is
  13915. * addressing the current server. So civetweb can also be used
  13916. * as a proxy server. */
  13917. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13918. if (mg_strncasecmp(uri,
  13919. abs_uri_protocols[i].proto,
  13920. abs_uri_protocols[i].proto_len) == 0) {
  13921. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  13922. if (!hostend) {
  13923. return 0;
  13924. }
  13925. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  13926. if (!portbegin) {
  13927. return 3;
  13928. }
  13929. port = strtoul(portbegin + 1, &portend, 10);
  13930. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  13931. return 0;
  13932. }
  13933. return 4;
  13934. }
  13935. }
  13936. return 0;
  13937. }
  13938. /* Return NULL or the relative uri at the current server */
  13939. static const char *
  13940. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  13941. {
  13942. const char *server_domain;
  13943. size_t server_domain_len;
  13944. size_t request_domain_len = 0;
  13945. unsigned long port = 0;
  13946. int i, auth_domain_check_enabled;
  13947. const char *hostbegin = NULL;
  13948. const char *hostend = NULL;
  13949. const char *portbegin;
  13950. char *portend;
  13951. auth_domain_check_enabled =
  13952. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  13953. /* DNS is case insensitive, so use case insensitive string compare here
  13954. */
  13955. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13956. if (mg_strncasecmp(uri,
  13957. abs_uri_protocols[i].proto,
  13958. abs_uri_protocols[i].proto_len) == 0) {
  13959. hostbegin = uri + abs_uri_protocols[i].proto_len;
  13960. hostend = strchr(hostbegin, '/');
  13961. if (!hostend) {
  13962. return 0;
  13963. }
  13964. portbegin = strchr(hostbegin, ':');
  13965. if ((!portbegin) || (portbegin > hostend)) {
  13966. port = abs_uri_protocols[i].default_port;
  13967. request_domain_len = (size_t)(hostend - hostbegin);
  13968. } else {
  13969. port = strtoul(portbegin + 1, &portend, 10);
  13970. if ((portend != hostend) || (port <= 0)
  13971. || !is_valid_port(port)) {
  13972. return 0;
  13973. }
  13974. request_domain_len = (size_t)(portbegin - hostbegin);
  13975. }
  13976. /* protocol found, port set */
  13977. break;
  13978. }
  13979. }
  13980. if (!port) {
  13981. /* port remains 0 if the protocol is not found */
  13982. return 0;
  13983. }
  13984. /* Check if the request is directed to a different server. */
  13985. /* First check if the port is the same (IPv4 and IPv6). */
  13986. #if defined(USE_IPV6)
  13987. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  13988. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  13989. /* Request is directed to a different port */
  13990. return 0;
  13991. }
  13992. } else
  13993. #endif
  13994. {
  13995. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  13996. /* Request is directed to a different port */
  13997. return 0;
  13998. }
  13999. }
  14000. /* Finally check if the server corresponds to the authentication
  14001. * domain of the server (the server domain).
  14002. * Allow full matches (like http://mydomain.com/path/file.ext), and
  14003. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  14004. * but do not allow substrings (like
  14005. * http://notmydomain.com/path/file.ext
  14006. * or http://mydomain.com.fake/path/file.ext).
  14007. */
  14008. if (auth_domain_check_enabled) {
  14009. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  14010. server_domain_len = strlen(server_domain);
  14011. if ((server_domain_len == 0) || (hostbegin == NULL)) {
  14012. return 0;
  14013. }
  14014. if ((request_domain_len == server_domain_len)
  14015. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  14016. /* Request is directed to this server - full name match. */
  14017. } else {
  14018. if (request_domain_len < (server_domain_len + 2)) {
  14019. /* Request is directed to another server: The server name
  14020. * is longer than the request name.
  14021. * Drop this case here to avoid overflows in the
  14022. * following checks. */
  14023. return 0;
  14024. }
  14025. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  14026. /* Request is directed to another server: It could be a
  14027. * substring
  14028. * like notmyserver.com */
  14029. return 0;
  14030. }
  14031. if (0 != memcmp(server_domain,
  14032. hostbegin + request_domain_len - server_domain_len,
  14033. server_domain_len)) {
  14034. /* Request is directed to another server:
  14035. * The server name is different. */
  14036. return 0;
  14037. }
  14038. }
  14039. }
  14040. return hostend;
  14041. }
  14042. static int
  14043. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14044. {
  14045. if (ebuf_len > 0) {
  14046. ebuf[0] = '\0';
  14047. }
  14048. *err = 0;
  14049. reset_per_request_attributes(conn);
  14050. if (!conn) {
  14051. mg_snprintf(conn,
  14052. NULL, /* No truncation check for ebuf */
  14053. ebuf,
  14054. ebuf_len,
  14055. "%s",
  14056. "Internal error");
  14057. *err = 500;
  14058. return 0;
  14059. }
  14060. /* Set the time the request was received. This value should be used for
  14061. * timeouts. */
  14062. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  14063. conn->request_len =
  14064. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  14065. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  14066. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  14067. mg_snprintf(conn,
  14068. NULL, /* No truncation check for ebuf */
  14069. ebuf,
  14070. ebuf_len,
  14071. "%s",
  14072. "Invalid message size");
  14073. *err = 500;
  14074. return 0;
  14075. }
  14076. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  14077. mg_snprintf(conn,
  14078. NULL, /* No truncation check for ebuf */
  14079. ebuf,
  14080. ebuf_len,
  14081. "%s",
  14082. "Message too large");
  14083. *err = 413;
  14084. return 0;
  14085. }
  14086. if (conn->request_len <= 0) {
  14087. if (conn->data_len > 0) {
  14088. mg_snprintf(conn,
  14089. NULL, /* No truncation check for ebuf */
  14090. ebuf,
  14091. ebuf_len,
  14092. "%s",
  14093. "Malformed message");
  14094. *err = 400;
  14095. } else {
  14096. /* Server did not recv anything -> just close the connection */
  14097. conn->must_close = 1;
  14098. mg_snprintf(conn,
  14099. NULL, /* No truncation check for ebuf */
  14100. ebuf,
  14101. ebuf_len,
  14102. "%s",
  14103. "No data received");
  14104. *err = 0;
  14105. }
  14106. return 0;
  14107. }
  14108. return 1;
  14109. }
  14110. static int
  14111. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14112. {
  14113. const char *cl;
  14114. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14115. return 0;
  14116. }
  14117. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  14118. <= 0) {
  14119. mg_snprintf(conn,
  14120. NULL, /* No truncation check for ebuf */
  14121. ebuf,
  14122. ebuf_len,
  14123. "%s",
  14124. "Bad request");
  14125. *err = 400;
  14126. return 0;
  14127. }
  14128. /* Message is a valid request */
  14129. /* Is there a "host" ? */
  14130. conn->host = alloc_get_host(conn);
  14131. if (!conn->host) {
  14132. mg_snprintf(conn,
  14133. NULL, /* No truncation check for ebuf */
  14134. ebuf,
  14135. ebuf_len,
  14136. "%s",
  14137. "Bad request: Host mismatch");
  14138. *err = 400;
  14139. return 0;
  14140. }
  14141. /* Do we know the content length? */
  14142. if ((cl = get_header(conn->request_info.http_headers,
  14143. conn->request_info.num_headers,
  14144. "Content-Length")) != NULL) {
  14145. /* Request/response has content length set */
  14146. char *endptr = NULL;
  14147. conn->content_len = strtoll(cl, &endptr, 10);
  14148. if (endptr == cl) {
  14149. mg_snprintf(conn,
  14150. NULL, /* No truncation check for ebuf */
  14151. ebuf,
  14152. ebuf_len,
  14153. "%s",
  14154. "Bad request");
  14155. *err = 411;
  14156. return 0;
  14157. }
  14158. /* Publish the content length back to the request info. */
  14159. conn->request_info.content_length = conn->content_len;
  14160. } else if ((cl = get_header(conn->request_info.http_headers,
  14161. conn->request_info.num_headers,
  14162. "Transfer-Encoding")) != NULL
  14163. && !mg_strcasecmp(cl, "chunked")) {
  14164. conn->is_chunked = 1;
  14165. conn->content_len = -1; /* unknown content length */
  14166. } else {
  14167. const struct mg_http_method_info *meth =
  14168. get_http_method_info(conn->request_info.request_method);
  14169. if (!meth) {
  14170. /* No valid HTTP method */
  14171. mg_snprintf(conn,
  14172. NULL, /* No truncation check for ebuf */
  14173. ebuf,
  14174. ebuf_len,
  14175. "%s",
  14176. "Bad request");
  14177. *err = 411;
  14178. return 0;
  14179. }
  14180. if (meth->request_has_body) {
  14181. /* POST or PUT request without content length set */
  14182. conn->content_len = -1; /* unknown content length */
  14183. } else {
  14184. /* Other request */
  14185. conn->content_len = 0; /* No content */
  14186. }
  14187. }
  14188. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  14189. return 1;
  14190. }
  14191. /* conn is assumed to be valid in this internal function */
  14192. static int
  14193. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  14194. {
  14195. const char *cl;
  14196. if (!get_message(conn, ebuf, ebuf_len, err)) {
  14197. return 0;
  14198. }
  14199. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  14200. <= 0) {
  14201. mg_snprintf(conn,
  14202. NULL, /* No truncation check for ebuf */
  14203. ebuf,
  14204. ebuf_len,
  14205. "%s",
  14206. "Bad response");
  14207. *err = 400;
  14208. return 0;
  14209. }
  14210. /* Message is a valid response */
  14211. /* Do we know the content length? */
  14212. if ((cl = get_header(conn->response_info.http_headers,
  14213. conn->response_info.num_headers,
  14214. "Content-Length")) != NULL) {
  14215. /* Request/response has content length set */
  14216. char *endptr = NULL;
  14217. conn->content_len = strtoll(cl, &endptr, 10);
  14218. if (endptr == cl) {
  14219. mg_snprintf(conn,
  14220. NULL, /* No truncation check for ebuf */
  14221. ebuf,
  14222. ebuf_len,
  14223. "%s",
  14224. "Bad request");
  14225. *err = 411;
  14226. return 0;
  14227. }
  14228. /* Publish the content length back to the response info. */
  14229. conn->response_info.content_length = conn->content_len;
  14230. /* TODO: check if it is still used in response_info */
  14231. conn->request_info.content_length = conn->content_len;
  14232. } else if ((cl = get_header(conn->response_info.http_headers,
  14233. conn->response_info.num_headers,
  14234. "Transfer-Encoding")) != NULL
  14235. && !mg_strcasecmp(cl, "chunked")) {
  14236. conn->is_chunked = 1;
  14237. conn->content_len = -1; /* unknown content length */
  14238. } else {
  14239. conn->content_len = -1; /* unknown content length */
  14240. }
  14241. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  14242. return 1;
  14243. }
  14244. int
  14245. mg_get_response(struct mg_connection *conn,
  14246. char *ebuf,
  14247. size_t ebuf_len,
  14248. int timeout)
  14249. {
  14250. int err, ret;
  14251. char txt[32]; /* will not overflow */
  14252. char *save_timeout;
  14253. char *new_timeout;
  14254. if (ebuf_len > 0) {
  14255. ebuf[0] = '\0';
  14256. }
  14257. if (!conn) {
  14258. mg_snprintf(conn,
  14259. NULL, /* No truncation check for ebuf */
  14260. ebuf,
  14261. ebuf_len,
  14262. "%s",
  14263. "Parameter error");
  14264. return -1;
  14265. }
  14266. /* Implementation of API function for HTTP clients */
  14267. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  14268. if (timeout >= 0) {
  14269. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  14270. new_timeout = txt;
  14271. /* Not required for non-blocking sockets.
  14272. set_sock_timeout(conn->client.sock, timeout);
  14273. */
  14274. } else {
  14275. new_timeout = NULL;
  14276. }
  14277. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  14278. ret = get_response(conn, ebuf, ebuf_len, &err);
  14279. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  14280. #if defined(MG_LEGACY_INTERFACE)
  14281. /* TODO: 1) uri is deprecated;
  14282. * 2) here, ri.uri is the http response code */
  14283. conn->request_info.uri = conn->request_info.request_uri;
  14284. #endif
  14285. conn->request_info.local_uri = conn->request_info.request_uri;
  14286. /* TODO (mid): Define proper return values - maybe return length?
  14287. * For the first test use <0 for error and >0 for OK */
  14288. return (ret == 0) ? -1 : +1;
  14289. }
  14290. struct mg_connection *
  14291. mg_download(const char *host,
  14292. int port,
  14293. int use_ssl,
  14294. char *ebuf,
  14295. size_t ebuf_len,
  14296. const char *fmt,
  14297. ...)
  14298. {
  14299. struct mg_connection *conn;
  14300. va_list ap;
  14301. int i;
  14302. int reqerr;
  14303. if (ebuf_len > 0) {
  14304. ebuf[0] = '\0';
  14305. }
  14306. va_start(ap, fmt);
  14307. /* open a connection */
  14308. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  14309. if (conn != NULL) {
  14310. i = mg_vprintf(conn, fmt, ap);
  14311. if (i <= 0) {
  14312. mg_snprintf(conn,
  14313. NULL, /* No truncation check for ebuf */
  14314. ebuf,
  14315. ebuf_len,
  14316. "%s",
  14317. "Error sending request");
  14318. } else {
  14319. get_response(conn, ebuf, ebuf_len, &reqerr);
  14320. #if defined(MG_LEGACY_INTERFACE)
  14321. /* TODO: 1) uri is deprecated;
  14322. * 2) here, ri.uri is the http response code */
  14323. conn->request_info.uri = conn->request_info.request_uri;
  14324. #endif
  14325. conn->request_info.local_uri = conn->request_info.request_uri;
  14326. }
  14327. }
  14328. /* if an error occurred, close the connection */
  14329. if ((ebuf[0] != '\0') && (conn != NULL)) {
  14330. mg_close_connection(conn);
  14331. conn = NULL;
  14332. }
  14333. va_end(ap);
  14334. return conn;
  14335. }
  14336. struct websocket_client_thread_data {
  14337. struct mg_connection *conn;
  14338. mg_websocket_data_handler data_handler;
  14339. mg_websocket_close_handler close_handler;
  14340. void *callback_data;
  14341. };
  14342. #if defined(USE_WEBSOCKET)
  14343. #if defined(_WIN32)
  14344. static unsigned __stdcall websocket_client_thread(void *data)
  14345. #else
  14346. static void *
  14347. websocket_client_thread(void *data)
  14348. #endif
  14349. {
  14350. struct websocket_client_thread_data *cdata =
  14351. (struct websocket_client_thread_data *)data;
  14352. #if !defined(_WIN32)
  14353. struct sigaction sa;
  14354. /* Ignore SIGPIPE */
  14355. memset(&sa, 0, sizeof(sa));
  14356. sa.sa_handler = SIG_IGN;
  14357. sigaction(SIGPIPE, &sa, NULL);
  14358. #endif
  14359. mg_set_thread_name("ws-clnt");
  14360. if (cdata->conn->phys_ctx) {
  14361. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  14362. /* 3 indicates a websocket client thread */
  14363. /* TODO: check if conn->phys_ctx can be set */
  14364. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  14365. 3);
  14366. }
  14367. }
  14368. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  14369. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  14370. if (cdata->close_handler != NULL) {
  14371. cdata->close_handler(cdata->conn, cdata->callback_data);
  14372. }
  14373. /* The websocket_client context has only this thread. If it runs out,
  14374. set the stop_flag to 2 (= "stopped"). */
  14375. cdata->conn->phys_ctx->stop_flag = 2;
  14376. mg_free((void *)cdata);
  14377. #if defined(_WIN32)
  14378. return 0;
  14379. #else
  14380. return NULL;
  14381. #endif
  14382. }
  14383. #endif
  14384. struct mg_connection *
  14385. mg_connect_websocket_client(const char *host,
  14386. int port,
  14387. int use_ssl,
  14388. char *error_buffer,
  14389. size_t error_buffer_size,
  14390. const char *path,
  14391. const char *origin,
  14392. mg_websocket_data_handler data_func,
  14393. mg_websocket_close_handler close_func,
  14394. void *user_data)
  14395. {
  14396. struct mg_connection *conn = NULL;
  14397. #if defined(USE_WEBSOCKET)
  14398. struct mg_context *newctx = NULL;
  14399. struct websocket_client_thread_data *thread_data;
  14400. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  14401. static const char *handshake_req;
  14402. if (origin != NULL) {
  14403. handshake_req = "GET %s HTTP/1.1\r\n"
  14404. "Host: %s\r\n"
  14405. "Upgrade: websocket\r\n"
  14406. "Connection: Upgrade\r\n"
  14407. "Sec-WebSocket-Key: %s\r\n"
  14408. "Sec-WebSocket-Version: 13\r\n"
  14409. "Origin: %s\r\n"
  14410. "\r\n";
  14411. } else {
  14412. handshake_req = "GET %s HTTP/1.1\r\n"
  14413. "Host: %s\r\n"
  14414. "Upgrade: websocket\r\n"
  14415. "Connection: Upgrade\r\n"
  14416. "Sec-WebSocket-Key: %s\r\n"
  14417. "Sec-WebSocket-Version: 13\r\n"
  14418. "\r\n";
  14419. }
  14420. #if defined(__clang__)
  14421. #pragma clang diagnostic push
  14422. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  14423. #endif
  14424. /* Establish the client connection and request upgrade */
  14425. conn = mg_download(host,
  14426. port,
  14427. use_ssl,
  14428. error_buffer,
  14429. error_buffer_size,
  14430. handshake_req,
  14431. path,
  14432. host,
  14433. magic,
  14434. origin);
  14435. #if defined(__clang__)
  14436. #pragma clang diagnostic pop
  14437. #endif
  14438. /* Connection object will be null if something goes wrong */
  14439. if (conn == NULL) {
  14440. if (!*error_buffer) {
  14441. /* There should be already an error message */
  14442. mg_snprintf(conn,
  14443. NULL, /* No truncation check for ebuf */
  14444. error_buffer,
  14445. error_buffer_size,
  14446. "Unexpected error");
  14447. }
  14448. return NULL;
  14449. }
  14450. if (conn->response_info.status_code != 101) {
  14451. /* We sent an "upgrade" request. For a correct websocket
  14452. * protocol handshake, we expect a "101 Continue" response.
  14453. * Otherwise it is a protocol violation. Maybe the HTTP
  14454. * Server does not know websockets. */
  14455. if (!*error_buffer) {
  14456. /* set an error, if not yet set */
  14457. mg_snprintf(conn,
  14458. NULL, /* No truncation check for ebuf */
  14459. error_buffer,
  14460. error_buffer_size,
  14461. "Unexpected server reply");
  14462. }
  14463. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  14464. mg_free(conn);
  14465. return NULL;
  14466. }
  14467. /* For client connections, mg_context is fake. Since we need to set a
  14468. * callback function, we need to create a copy and modify it. */
  14469. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  14470. if (!newctx) {
  14471. DEBUG_TRACE("%s\r\n", "Out of memory");
  14472. mg_free(conn);
  14473. return NULL;
  14474. }
  14475. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  14476. newctx->user_data = user_data;
  14477. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  14478. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  14479. newctx->worker_threadids =
  14480. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  14481. sizeof(pthread_t),
  14482. newctx);
  14483. conn->phys_ctx = newctx;
  14484. conn->dom_ctx = &(newctx->dd);
  14485. thread_data = (struct websocket_client_thread_data *)
  14486. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  14487. if (!thread_data) {
  14488. DEBUG_TRACE("%s\r\n", "Out of memory");
  14489. mg_free(newctx);
  14490. mg_free(conn);
  14491. return NULL;
  14492. }
  14493. thread_data->conn = conn;
  14494. thread_data->data_handler = data_func;
  14495. thread_data->close_handler = close_func;
  14496. thread_data->callback_data = user_data;
  14497. /* Start a thread to read the websocket client connection
  14498. * This thread will automatically stop when mg_disconnect is
  14499. * called on the client connection */
  14500. if (mg_start_thread_with_id(websocket_client_thread,
  14501. (void *)thread_data,
  14502. newctx->worker_threadids) != 0) {
  14503. mg_free((void *)thread_data);
  14504. mg_free((void *)newctx->worker_threadids);
  14505. mg_free((void *)newctx);
  14506. mg_free((void *)conn);
  14507. conn = NULL;
  14508. DEBUG_TRACE("%s",
  14509. "Websocket client connect thread could not be started\r\n");
  14510. }
  14511. #else
  14512. /* Appease "unused parameter" warnings */
  14513. (void)host;
  14514. (void)port;
  14515. (void)use_ssl;
  14516. (void)error_buffer;
  14517. (void)error_buffer_size;
  14518. (void)path;
  14519. (void)origin;
  14520. (void)user_data;
  14521. (void)data_func;
  14522. (void)close_func;
  14523. #endif
  14524. return conn;
  14525. }
  14526. /* Prepare connection data structure */
  14527. static void
  14528. init_connection(struct mg_connection *conn)
  14529. {
  14530. /* Is keep alive allowed by the server */
  14531. int keep_alive_enabled =
  14532. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  14533. if (!keep_alive_enabled) {
  14534. conn->must_close = 1;
  14535. }
  14536. /* Important: on new connection, reset the receiving buffer. Credit
  14537. * goes to crule42. */
  14538. conn->data_len = 0;
  14539. conn->handled_requests = 0;
  14540. mg_set_user_connection_data(conn, NULL);
  14541. #if defined(USE_SERVER_STATS)
  14542. conn->conn_state = 2; /* init */
  14543. #endif
  14544. /* call the init_connection callback if assigned */
  14545. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  14546. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  14547. void *conn_data = NULL;
  14548. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  14549. mg_set_user_connection_data(conn, conn_data);
  14550. }
  14551. }
  14552. }
  14553. /* Process a connection - may handle multiple requests
  14554. * using the same connection.
  14555. * Must be called with a valid connection (conn and
  14556. * conn->phys_ctx must be valid).
  14557. */
  14558. static void
  14559. process_new_connection(struct mg_connection *conn)
  14560. {
  14561. struct mg_request_info *ri = &conn->request_info;
  14562. int keep_alive, discard_len;
  14563. char ebuf[100];
  14564. const char *hostend;
  14565. int reqerr, uri_type;
  14566. #if defined(USE_SERVER_STATS)
  14567. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  14568. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  14569. if (mcon > (conn->phys_ctx->max_connections)) {
  14570. /* could use atomic compare exchange, but this
  14571. * seems overkill for statistics data */
  14572. conn->phys_ctx->max_connections = mcon;
  14573. }
  14574. #endif
  14575. init_connection(conn);
  14576. DEBUG_TRACE("Start processing connection from %s",
  14577. conn->request_info.remote_addr);
  14578. /* Loop over multiple requests sent using the same connection
  14579. * (while "keep alive"). */
  14580. do {
  14581. DEBUG_TRACE("calling get_request (%i times for this connection)",
  14582. conn->handled_requests + 1);
  14583. #if defined(USE_SERVER_STATS)
  14584. conn->conn_state = 3; /* ready */
  14585. #endif
  14586. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  14587. /* The request sent by the client could not be understood by
  14588. * the server, or it was incomplete or a timeout. Send an
  14589. * error message and close the connection. */
  14590. if (reqerr > 0) {
  14591. DEBUG_ASSERT(ebuf[0] != '\0');
  14592. mg_send_http_error(conn, reqerr, "%s", ebuf);
  14593. }
  14594. } else if (strcmp(ri->http_version, "1.0")
  14595. && strcmp(ri->http_version, "1.1")) {
  14596. mg_snprintf(conn,
  14597. NULL, /* No truncation check for ebuf */
  14598. ebuf,
  14599. sizeof(ebuf),
  14600. "Bad HTTP version: [%s]",
  14601. ri->http_version);
  14602. mg_send_http_error(conn, 505, "%s", ebuf);
  14603. }
  14604. if (ebuf[0] == '\0') {
  14605. uri_type = get_uri_type(conn->request_info.request_uri);
  14606. switch (uri_type) {
  14607. case 1:
  14608. /* Asterisk */
  14609. conn->request_info.local_uri = NULL;
  14610. break;
  14611. case 2:
  14612. /* relative uri */
  14613. conn->request_info.local_uri = conn->request_info.request_uri;
  14614. break;
  14615. case 3:
  14616. case 4:
  14617. /* absolute uri (with/without port) */
  14618. hostend = get_rel_url_at_current_server(
  14619. conn->request_info.request_uri, conn);
  14620. if (hostend) {
  14621. conn->request_info.local_uri = hostend;
  14622. } else {
  14623. conn->request_info.local_uri = NULL;
  14624. }
  14625. break;
  14626. default:
  14627. mg_snprintf(conn,
  14628. NULL, /* No truncation check for ebuf */
  14629. ebuf,
  14630. sizeof(ebuf),
  14631. "Invalid URI");
  14632. mg_send_http_error(conn, 400, "%s", ebuf);
  14633. conn->request_info.local_uri = NULL;
  14634. break;
  14635. }
  14636. #if defined(MG_LEGACY_INTERFACE)
  14637. /* Legacy before split into local_uri and request_uri */
  14638. conn->request_info.uri = conn->request_info.local_uri;
  14639. #endif
  14640. }
  14641. DEBUG_TRACE("http: %s, error: %s",
  14642. (ri->http_version ? ri->http_version : "none"),
  14643. (ebuf[0] ? ebuf : "none"));
  14644. if (ebuf[0] == '\0') {
  14645. if (conn->request_info.local_uri) {
  14646. /* handle request to local server */
  14647. #if defined(USE_SERVER_STATS)
  14648. conn->conn_state = 4; /* processing */
  14649. #endif
  14650. handle_request(conn);
  14651. #if defined(USE_SERVER_STATS)
  14652. conn->conn_state = 5; /* processed */
  14653. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  14654. conn->consumed_content);
  14655. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  14656. conn->num_bytes_sent);
  14657. #endif
  14658. DEBUG_TRACE("%s", "handle_request done");
  14659. if (conn->phys_ctx->callbacks.end_request != NULL) {
  14660. conn->phys_ctx->callbacks.end_request(conn,
  14661. conn->status_code);
  14662. DEBUG_TRACE("%s", "end_request callback done");
  14663. }
  14664. log_access(conn);
  14665. } else {
  14666. /* TODO: handle non-local request (PROXY) */
  14667. conn->must_close = 1;
  14668. }
  14669. } else {
  14670. conn->must_close = 1;
  14671. }
  14672. if (ri->remote_user != NULL) {
  14673. mg_free((void *)ri->remote_user);
  14674. /* Important! When having connections with and without auth
  14675. * would cause double free and then crash */
  14676. ri->remote_user = NULL;
  14677. }
  14678. /* NOTE(lsm): order is important here. should_keep_alive() call
  14679. * is using parsed request, which will be invalid after
  14680. * memmove's below.
  14681. * Therefore, memorize should_keep_alive() result now for later
  14682. * use in loop exit condition. */
  14683. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  14684. && (conn->content_len >= 0);
  14685. /* Discard all buffered data for this request */
  14686. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  14687. && ((conn->request_len + conn->content_len)
  14688. < (int64_t)conn->data_len))
  14689. ? (int)(conn->request_len + conn->content_len)
  14690. : conn->data_len;
  14691. DEBUG_ASSERT(discard_len >= 0);
  14692. if (discard_len < 0) {
  14693. DEBUG_TRACE("internal error: discard_len = %li",
  14694. (long int)discard_len);
  14695. break;
  14696. }
  14697. conn->data_len -= discard_len;
  14698. if (conn->data_len > 0) {
  14699. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  14700. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  14701. }
  14702. DEBUG_ASSERT(conn->data_len >= 0);
  14703. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  14704. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  14705. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  14706. (long int)conn->data_len,
  14707. (long int)conn->buf_size);
  14708. break;
  14709. }
  14710. conn->handled_requests++;
  14711. } while (keep_alive);
  14712. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  14713. conn->request_info.remote_addr,
  14714. difftime(time(NULL), conn->conn_birth_time));
  14715. close_connection(conn);
  14716. #if defined(USE_SERVER_STATS)
  14717. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  14718. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  14719. #endif
  14720. }
  14721. #if defined(ALTERNATIVE_QUEUE)
  14722. static void
  14723. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14724. {
  14725. unsigned int i;
  14726. while (!ctx->stop_flag) {
  14727. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14728. /* find a free worker slot and signal it */
  14729. if (ctx->client_socks[i].in_use == 0) {
  14730. ctx->client_socks[i] = *sp;
  14731. ctx->client_socks[i].in_use = 1;
  14732. event_signal(ctx->client_wait_events[i]);
  14733. return;
  14734. }
  14735. }
  14736. /* queue is full */
  14737. mg_sleep(1);
  14738. }
  14739. }
  14740. static int
  14741. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14742. {
  14743. DEBUG_TRACE("%s", "going idle");
  14744. ctx->client_socks[thread_index].in_use = 0;
  14745. event_wait(ctx->client_wait_events[thread_index]);
  14746. *sp = ctx->client_socks[thread_index];
  14747. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14748. return !ctx->stop_flag;
  14749. }
  14750. #else /* ALTERNATIVE_QUEUE */
  14751. /* Worker threads take accepted socket from the queue */
  14752. static int
  14753. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14754. {
  14755. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14756. (void)thread_index;
  14757. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14758. DEBUG_TRACE("%s", "going idle");
  14759. /* If the queue is empty, wait. We're idle at this point. */
  14760. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  14761. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  14762. }
  14763. /* If we're stopping, sq_head may be equal to sq_tail. */
  14764. if (ctx->sq_head > ctx->sq_tail) {
  14765. /* Copy socket from the queue and increment tail */
  14766. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  14767. ctx->sq_tail++;
  14768. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14769. /* Wrap pointers if needed */
  14770. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  14771. ctx->sq_tail -= QUEUE_SIZE(ctx);
  14772. ctx->sq_head -= QUEUE_SIZE(ctx);
  14773. }
  14774. }
  14775. (void)pthread_cond_signal(&ctx->sq_empty);
  14776. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14777. return !ctx->stop_flag;
  14778. #undef QUEUE_SIZE
  14779. }
  14780. /* Master thread adds accepted socket to a queue */
  14781. static void
  14782. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14783. {
  14784. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14785. if (!ctx) {
  14786. return;
  14787. }
  14788. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14789. /* If the queue is full, wait */
  14790. while ((ctx->stop_flag == 0)
  14791. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  14792. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  14793. }
  14794. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  14795. /* Copy socket to the queue and increment head */
  14796. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  14797. ctx->sq_head++;
  14798. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  14799. }
  14800. (void)pthread_cond_signal(&ctx->sq_full);
  14801. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14802. #undef QUEUE_SIZE
  14803. }
  14804. #endif /* ALTERNATIVE_QUEUE */
  14805. struct worker_thread_args {
  14806. struct mg_context *ctx;
  14807. int index;
  14808. };
  14809. static void *
  14810. worker_thread_run(struct worker_thread_args *thread_args)
  14811. {
  14812. struct mg_context *ctx = thread_args->ctx;
  14813. struct mg_connection *conn;
  14814. struct mg_workerTLS tls;
  14815. #if defined(MG_LEGACY_INTERFACE)
  14816. uint32_t addr;
  14817. #endif
  14818. mg_set_thread_name("worker");
  14819. tls.is_master = 0;
  14820. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14821. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14822. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14823. #endif
  14824. /* Initialize thread local storage before calling any callback */
  14825. pthread_setspecific(sTlsKey, &tls);
  14826. if (ctx->callbacks.init_thread) {
  14827. /* call init_thread for a worker thread (type 1) */
  14828. ctx->callbacks.init_thread(ctx, 1);
  14829. }
  14830. /* Connection structure has been pre-allocated */
  14831. if (((int)thread_args->index < 0)
  14832. || ((unsigned)thread_args->index
  14833. >= (unsigned)ctx->cfg_worker_threads)) {
  14834. mg_cry_internal(fc(ctx),
  14835. "Internal error: Invalid worker index %i",
  14836. (int)thread_args->index);
  14837. return NULL;
  14838. }
  14839. conn = ctx->worker_connections + thread_args->index;
  14840. /* Request buffers are not pre-allocated. They are private to the
  14841. * request and do not contain any state information that might be
  14842. * of interest to anyone observing a server status. */
  14843. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  14844. if (conn->buf == NULL) {
  14845. mg_cry_internal(fc(ctx),
  14846. "Out of memory: Cannot allocate buffer for worker %i",
  14847. (int)thread_args->index);
  14848. return NULL;
  14849. }
  14850. conn->buf_size = (int)ctx->max_request_size;
  14851. conn->phys_ctx = ctx;
  14852. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  14853. conn->host = NULL; /* until we have more information. */
  14854. conn->thread_index = thread_args->index;
  14855. conn->request_info.user_data = ctx->user_data;
  14856. /* Allocate a mutex for this connection to allow communication both
  14857. * within the request handler and from elsewhere in the application
  14858. */
  14859. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  14860. #if defined(USE_SERVER_STATS)
  14861. conn->conn_state = 1; /* not consumed */
  14862. #endif
  14863. #if defined(ALTERNATIVE_QUEUE)
  14864. while ((ctx->stop_flag == 0)
  14865. && consume_socket(ctx, &conn->client, conn->thread_index)) {
  14866. #else
  14867. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  14868. * signal sq_empty condvar to wake up the master waiting in
  14869. * produce_socket() */
  14870. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  14871. #endif
  14872. conn->conn_birth_time = time(NULL);
  14873. /* Fill in IP, port info early so even if SSL setup below fails,
  14874. * error handler would have the corresponding info.
  14875. * Thanks to Johannes Winkelmann for the patch.
  14876. */
  14877. #if defined(USE_IPV6)
  14878. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  14879. conn->request_info.remote_port =
  14880. ntohs(conn->client.rsa.sin6.sin6_port);
  14881. } else
  14882. #endif
  14883. {
  14884. conn->request_info.remote_port =
  14885. ntohs(conn->client.rsa.sin.sin_port);
  14886. }
  14887. sockaddr_to_string(conn->request_info.remote_addr,
  14888. sizeof(conn->request_info.remote_addr),
  14889. &conn->client.rsa);
  14890. DEBUG_TRACE("Start processing connection from %s",
  14891. conn->request_info.remote_addr);
  14892. conn->request_info.is_ssl = conn->client.is_ssl;
  14893. if (conn->client.is_ssl) {
  14894. #if !defined(NO_SSL)
  14895. /* HTTPS connection */
  14896. if (sslize(conn,
  14897. conn->dom_ctx->ssl_ctx,
  14898. SSL_accept,
  14899. &(conn->phys_ctx->stop_flag))) {
  14900. /* conn->dom_ctx is set in get_request */
  14901. /* Get SSL client certificate information (if set) */
  14902. ssl_get_client_cert_info(conn);
  14903. /* process HTTPS connection */
  14904. process_new_connection(conn);
  14905. /* Free client certificate info */
  14906. if (conn->request_info.client_cert) {
  14907. mg_free((void *)(conn->request_info.client_cert->subject));
  14908. mg_free((void *)(conn->request_info.client_cert->issuer));
  14909. mg_free((void *)(conn->request_info.client_cert->serial));
  14910. mg_free((void *)(conn->request_info.client_cert->finger));
  14911. /* Free certificate memory */
  14912. X509_free(
  14913. (X509 *)conn->request_info.client_cert->peer_cert);
  14914. conn->request_info.client_cert->peer_cert = 0;
  14915. conn->request_info.client_cert->subject = 0;
  14916. conn->request_info.client_cert->issuer = 0;
  14917. conn->request_info.client_cert->serial = 0;
  14918. conn->request_info.client_cert->finger = 0;
  14919. mg_free(conn->request_info.client_cert);
  14920. conn->request_info.client_cert = 0;
  14921. }
  14922. }
  14923. #endif
  14924. } else {
  14925. /* process HTTP connection */
  14926. process_new_connection(conn);
  14927. }
  14928. DEBUG_TRACE("%s", "Connection closed");
  14929. }
  14930. pthread_setspecific(sTlsKey, NULL);
  14931. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14932. CloseHandle(tls.pthread_cond_helper_mutex);
  14933. #endif
  14934. pthread_mutex_destroy(&conn->mutex);
  14935. /* Free the request buffer. */
  14936. conn->buf_size = 0;
  14937. mg_free(conn->buf);
  14938. conn->buf = NULL;
  14939. #if defined(USE_SERVER_STATS)
  14940. conn->conn_state = 9; /* done */
  14941. #endif
  14942. DEBUG_TRACE("%s", "exiting");
  14943. return NULL;
  14944. }
  14945. /* Threads have different return types on Windows and Unix. */
  14946. #if defined(_WIN32)
  14947. static unsigned __stdcall worker_thread(void *thread_func_param)
  14948. {
  14949. struct worker_thread_args *pwta =
  14950. (struct worker_thread_args *)thread_func_param;
  14951. worker_thread_run(pwta);
  14952. mg_free(thread_func_param);
  14953. return 0;
  14954. }
  14955. #else
  14956. static void *
  14957. worker_thread(void *thread_func_param)
  14958. {
  14959. struct worker_thread_args *pwta =
  14960. (struct worker_thread_args *)thread_func_param;
  14961. struct sigaction sa;
  14962. /* Ignore SIGPIPE */
  14963. memset(&sa, 0, sizeof(sa));
  14964. sa.sa_handler = SIG_IGN;
  14965. sigaction(SIGPIPE, &sa, NULL);
  14966. worker_thread_run(pwta);
  14967. mg_free(thread_func_param);
  14968. return NULL;
  14969. }
  14970. #endif /* _WIN32 */
  14971. /* This is an internal function, thus all arguments are expected to be
  14972. * valid - a NULL check is not required. */
  14973. static void
  14974. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  14975. {
  14976. struct socket so;
  14977. char src_addr[IP_ADDR_STR_LEN];
  14978. socklen_t len = sizeof(so.rsa);
  14979. int on = 1;
  14980. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  14981. == INVALID_SOCKET) {
  14982. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  14983. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  14984. mg_cry_internal(fc(ctx),
  14985. "%s: %s is not allowed to connect",
  14986. __func__,
  14987. src_addr);
  14988. closesocket(so.sock);
  14989. } else {
  14990. /* Put so socket structure into the queue */
  14991. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  14992. set_close_on_exec(so.sock, fc(ctx));
  14993. so.is_ssl = listener->is_ssl;
  14994. so.ssl_redir = listener->ssl_redir;
  14995. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  14996. mg_cry_internal(fc(ctx),
  14997. "%s: getsockname() failed: %s",
  14998. __func__,
  14999. strerror(ERRNO));
  15000. }
  15001. /* Set TCP keep-alive. This is needed because if HTTP-level
  15002. * keep-alive
  15003. * is enabled, and client resets the connection, server won't get
  15004. * TCP FIN or RST and will keep the connection open forever. With
  15005. * TCP keep-alive, next keep-alive handshake will figure out that
  15006. * the client is down and will close the server end.
  15007. * Thanks to Igor Klopov who suggested the patch. */
  15008. if (setsockopt(so.sock,
  15009. SOL_SOCKET,
  15010. SO_KEEPALIVE,
  15011. (SOCK_OPT_TYPE)&on,
  15012. sizeof(on)) != 0) {
  15013. mg_cry_internal(
  15014. fc(ctx),
  15015. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  15016. __func__,
  15017. strerror(ERRNO));
  15018. }
  15019. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  15020. * to effectively fill up the underlying IP packet payload and
  15021. * reduce the overhead of sending lots of small buffers. However
  15022. * this hurts the server's throughput (ie. operations per second)
  15023. * when HTTP 1.1 persistent connections are used and the responses
  15024. * are relatively small (eg. less than 1400 bytes).
  15025. */
  15026. if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  15027. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  15028. if (set_tcp_nodelay(so.sock, 1) != 0) {
  15029. mg_cry_internal(
  15030. fc(ctx),
  15031. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  15032. __func__,
  15033. strerror(ERRNO));
  15034. }
  15035. }
  15036. /* We are using non-blocking sockets. Thus, the
  15037. * set_sock_timeout(so.sock, timeout);
  15038. * call is no longer required. */
  15039. /* The "non blocking" property should already be
  15040. * inherited from the parent socket. Set it for
  15041. * non-compliant socket implementations. */
  15042. set_non_blocking_mode(so.sock);
  15043. so.in_use = 0;
  15044. produce_socket(ctx, &so);
  15045. }
  15046. }
  15047. static void
  15048. master_thread_run(void *thread_func_param)
  15049. {
  15050. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  15051. struct mg_workerTLS tls;
  15052. struct pollfd *pfd;
  15053. unsigned int i;
  15054. unsigned int workerthreadcount;
  15055. if (!ctx) {
  15056. return;
  15057. }
  15058. mg_set_thread_name("master");
  15059. /* Increase priority of the master thread */
  15060. #if defined(_WIN32)
  15061. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  15062. #elif defined(USE_MASTER_THREAD_PRIORITY)
  15063. int min_prio = sched_get_priority_min(SCHED_RR);
  15064. int max_prio = sched_get_priority_max(SCHED_RR);
  15065. if ((min_prio >= 0) && (max_prio >= 0)
  15066. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  15067. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  15068. struct sched_param sched_param = {0};
  15069. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  15070. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  15071. }
  15072. #endif
  15073. /* Initialize thread local storage */
  15074. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15075. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  15076. #endif
  15077. tls.is_master = 1;
  15078. pthread_setspecific(sTlsKey, &tls);
  15079. if (ctx->callbacks.init_thread) {
  15080. /* Callback for the master thread (type 0) */
  15081. ctx->callbacks.init_thread(ctx, 0);
  15082. }
  15083. /* Server starts *now* */
  15084. ctx->start_time = time(NULL);
  15085. /* Start the server */
  15086. pfd = ctx->listening_socket_fds;
  15087. while (ctx->stop_flag == 0) {
  15088. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15089. pfd[i].fd = ctx->listening_sockets[i].sock;
  15090. pfd[i].events = POLLIN;
  15091. }
  15092. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  15093. for (i = 0; i < ctx->num_listening_sockets; i++) {
  15094. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  15095. * successful poll, and POLLIN is defined as
  15096. * (POLLRDNORM | POLLRDBAND)
  15097. * Therefore, we're checking pfd[i].revents & POLLIN, not
  15098. * pfd[i].revents == POLLIN. */
  15099. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  15100. accept_new_connection(&ctx->listening_sockets[i], ctx);
  15101. }
  15102. }
  15103. }
  15104. }
  15105. /* Here stop_flag is 1 - Initiate shutdown. */
  15106. DEBUG_TRACE("%s", "stopping workers");
  15107. /* Stop signal received: somebody called mg_stop. Quit. */
  15108. close_all_listening_sockets(ctx);
  15109. /* Wakeup workers that are waiting for connections to handle. */
  15110. (void)pthread_mutex_lock(&ctx->thread_mutex);
  15111. #if defined(ALTERNATIVE_QUEUE)
  15112. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15113. event_signal(ctx->client_wait_events[i]);
  15114. /* Since we know all sockets, we can shutdown the connections. */
  15115. if (ctx->client_socks[i].in_use) {
  15116. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  15117. }
  15118. }
  15119. #else
  15120. pthread_cond_broadcast(&ctx->sq_full);
  15121. #endif
  15122. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  15123. /* Join all worker threads to avoid leaking threads. */
  15124. workerthreadcount = ctx->cfg_worker_threads;
  15125. for (i = 0; i < workerthreadcount; i++) {
  15126. if (ctx->worker_threadids[i] != 0) {
  15127. mg_join_thread(ctx->worker_threadids[i]);
  15128. }
  15129. }
  15130. #if defined(USE_LUA)
  15131. /* Free Lua state of lua background task */
  15132. if (ctx->lua_background_state) {
  15133. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  15134. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  15135. if (lua_istable(lstate, -1)) {
  15136. reg_boolean(lstate, "shutdown", 1);
  15137. lua_pop(lstate, 1);
  15138. mg_sleep(2);
  15139. }
  15140. lua_close(lstate);
  15141. ctx->lua_background_state = 0;
  15142. }
  15143. #endif
  15144. DEBUG_TRACE("%s", "exiting");
  15145. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15146. CloseHandle(tls.pthread_cond_helper_mutex);
  15147. #endif
  15148. pthread_setspecific(sTlsKey, NULL);
  15149. /* Signal mg_stop() that we're done.
  15150. * WARNING: This must be the very last thing this
  15151. * thread does, as ctx becomes invalid after this line. */
  15152. ctx->stop_flag = 2;
  15153. }
  15154. /* Threads have different return types on Windows and Unix. */
  15155. #if defined(_WIN32)
  15156. static unsigned __stdcall master_thread(void *thread_func_param)
  15157. {
  15158. master_thread_run(thread_func_param);
  15159. return 0;
  15160. }
  15161. #else
  15162. static void *
  15163. master_thread(void *thread_func_param)
  15164. {
  15165. struct sigaction sa;
  15166. /* Ignore SIGPIPE */
  15167. memset(&sa, 0, sizeof(sa));
  15168. sa.sa_handler = SIG_IGN;
  15169. sigaction(SIGPIPE, &sa, NULL);
  15170. master_thread_run(thread_func_param);
  15171. return NULL;
  15172. }
  15173. #endif /* _WIN32 */
  15174. static void
  15175. free_context(struct mg_context *ctx)
  15176. {
  15177. int i;
  15178. struct mg_handler_info *tmp_rh;
  15179. if (ctx == NULL) {
  15180. return;
  15181. }
  15182. if (ctx->callbacks.exit_context) {
  15183. ctx->callbacks.exit_context(ctx);
  15184. }
  15185. /* All threads exited, no sync is needed. Destroy thread mutex and
  15186. * condvars
  15187. */
  15188. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  15189. #if defined(ALTERNATIVE_QUEUE)
  15190. mg_free(ctx->client_socks);
  15191. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15192. event_destroy(ctx->client_wait_events[i]);
  15193. }
  15194. mg_free(ctx->client_wait_events);
  15195. #else
  15196. (void)pthread_cond_destroy(&ctx->sq_empty);
  15197. (void)pthread_cond_destroy(&ctx->sq_full);
  15198. #endif
  15199. /* Destroy other context global data structures mutex */
  15200. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  15201. #if defined(USE_TIMERS)
  15202. timers_exit(ctx);
  15203. #endif
  15204. /* Deallocate config parameters */
  15205. for (i = 0; i < NUM_OPTIONS; i++) {
  15206. if (ctx->dd.config[i] != NULL) {
  15207. #if defined(_MSC_VER)
  15208. #pragma warning(suppress : 6001)
  15209. #endif
  15210. mg_free(ctx->dd.config[i]);
  15211. }
  15212. }
  15213. /* Deallocate request handlers */
  15214. while (ctx->dd.handlers) {
  15215. tmp_rh = ctx->dd.handlers;
  15216. ctx->dd.handlers = tmp_rh->next;
  15217. if (tmp_rh->handler_type == REQUEST_HANDLER) {
  15218. pthread_cond_destroy(&tmp_rh->refcount_cond);
  15219. pthread_mutex_destroy(&tmp_rh->refcount_mutex);
  15220. }
  15221. mg_free(tmp_rh->uri);
  15222. mg_free(tmp_rh);
  15223. }
  15224. #if !defined(NO_SSL)
  15225. /* Deallocate SSL context */
  15226. if (ctx->dd.ssl_ctx != NULL) {
  15227. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  15228. int callback_ret =
  15229. (ctx->callbacks.external_ssl_ctx == NULL)
  15230. ? 0
  15231. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  15232. if (callback_ret == 0) {
  15233. SSL_CTX_free(ctx->dd.ssl_ctx);
  15234. }
  15235. /* else: ignore error and ommit SSL_CTX_free in case
  15236. * callback_ret is 1 */
  15237. }
  15238. #endif /* !NO_SSL */
  15239. /* Deallocate worker thread ID array */
  15240. if (ctx->worker_threadids != NULL) {
  15241. mg_free(ctx->worker_threadids);
  15242. }
  15243. /* Deallocate worker thread ID array */
  15244. if (ctx->worker_connections != NULL) {
  15245. mg_free(ctx->worker_connections);
  15246. }
  15247. /* deallocate system name string */
  15248. mg_free(ctx->systemName);
  15249. /* Deallocate context itself */
  15250. mg_free(ctx);
  15251. }
  15252. void
  15253. mg_stop(struct mg_context *ctx)
  15254. {
  15255. pthread_t mt;
  15256. if (!ctx) {
  15257. return;
  15258. }
  15259. /* We don't use a lock here. Calling mg_stop with the same ctx from
  15260. * two threads is not allowed. */
  15261. mt = ctx->masterthreadid;
  15262. if (mt == 0) {
  15263. return;
  15264. }
  15265. ctx->masterthreadid = 0;
  15266. /* Set stop flag, so all threads know they have to exit. */
  15267. ctx->stop_flag = 1;
  15268. /* Wait until everything has stopped. */
  15269. while (ctx->stop_flag != 2) {
  15270. (void)mg_sleep(10);
  15271. }
  15272. mg_join_thread(mt);
  15273. free_context(ctx);
  15274. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15275. (void)WSACleanup();
  15276. #endif /* _WIN32 && !__SYMBIAN32__ */
  15277. }
  15278. static void
  15279. get_system_name(char **sysName)
  15280. {
  15281. #if defined(_WIN32)
  15282. #if !defined(__SYMBIAN32__)
  15283. #if defined(_WIN32_WCE)
  15284. *sysName = mg_strdup("WinCE");
  15285. #else
  15286. char name[128];
  15287. DWORD dwVersion = 0;
  15288. DWORD dwMajorVersion = 0;
  15289. DWORD dwMinorVersion = 0;
  15290. DWORD dwBuild = 0;
  15291. BOOL wowRet, isWoW = FALSE;
  15292. #if defined(_MSC_VER)
  15293. #pragma warning(push)
  15294. /* GetVersion was declared deprecated */
  15295. #pragma warning(disable : 4996)
  15296. #endif
  15297. dwVersion = GetVersion();
  15298. #if defined(_MSC_VER)
  15299. #pragma warning(pop)
  15300. #endif
  15301. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15302. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15303. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  15304. (void)dwBuild;
  15305. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  15306. sprintf(name,
  15307. "Windows %u.%u%s",
  15308. (unsigned)dwMajorVersion,
  15309. (unsigned)dwMinorVersion,
  15310. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  15311. *sysName = mg_strdup(name);
  15312. #endif
  15313. #else
  15314. *sysName = mg_strdup("Symbian");
  15315. #endif
  15316. #else
  15317. struct utsname name;
  15318. memset(&name, 0, sizeof(name));
  15319. uname(&name);
  15320. *sysName = mg_strdup(name.sysname);
  15321. #endif
  15322. }
  15323. struct mg_context *
  15324. mg_start(const struct mg_callbacks *callbacks,
  15325. void *user_data,
  15326. const char **options)
  15327. {
  15328. struct mg_context *ctx;
  15329. const char *name, *value, *default_value;
  15330. int idx, ok, workerthreadcount;
  15331. unsigned int i;
  15332. int itmp;
  15333. void (*exit_callback)(const struct mg_context *ctx) = 0;
  15334. struct mg_workerTLS tls;
  15335. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15336. WSADATA data;
  15337. WSAStartup(MAKEWORD(2, 2), &data);
  15338. #endif /* _WIN32 && !__SYMBIAN32__ */
  15339. /* Allocate context and initialize reasonable general case defaults. */
  15340. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  15341. return NULL;
  15342. }
  15343. /* Random number generator will initialize at the first call */
  15344. ctx->dd.auth_nonce_mask =
  15345. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  15346. if (mg_init_library_called == 0) {
  15347. /* Legacy INIT, if mg_start is called without mg_init_library.
  15348. * Note: This may cause a memory leak */
  15349. const char *ports_option =
  15350. config_options[LISTENING_PORTS].default_value;
  15351. if (options) {
  15352. const char **run_options = options;
  15353. const char *optname = config_options[LISTENING_PORTS].name;
  15354. /* Try to find the "listening_ports" option */
  15355. while (*run_options) {
  15356. if (!strcmp(*run_options, optname)) {
  15357. ports_option = run_options[1];
  15358. }
  15359. run_options += 2;
  15360. }
  15361. }
  15362. if (is_ssl_port_used(ports_option)) {
  15363. /* Initialize with SSL support */
  15364. mg_init_library(MG_FEATURES_TLS);
  15365. } else {
  15366. /* Initialize without SSL support */
  15367. mg_init_library(MG_FEATURES_DEFAULT);
  15368. }
  15369. }
  15370. tls.is_master = -1;
  15371. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  15372. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15373. tls.pthread_cond_helper_mutex = NULL;
  15374. #endif
  15375. pthread_setspecific(sTlsKey, &tls);
  15376. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  15377. #if !defined(ALTERNATIVE_QUEUE)
  15378. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  15379. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  15380. #endif
  15381. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  15382. if (!ok) {
  15383. /* Fatal error - abort start. However, this situation should never
  15384. * occur in practice. */
  15385. mg_cry_internal(fc(ctx),
  15386. "%s",
  15387. "Cannot initialize thread synchronization objects");
  15388. mg_free(ctx);
  15389. pthread_setspecific(sTlsKey, NULL);
  15390. return NULL;
  15391. }
  15392. if (callbacks) {
  15393. ctx->callbacks = *callbacks;
  15394. exit_callback = callbacks->exit_context;
  15395. ctx->callbacks.exit_context = 0;
  15396. }
  15397. ctx->user_data = user_data;
  15398. ctx->dd.handlers = NULL;
  15399. ctx->dd.next = NULL;
  15400. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15401. ctx->dd.shared_lua_websockets = NULL;
  15402. #endif
  15403. /* Store options */
  15404. while (options && (name = *options++) != NULL) {
  15405. if ((idx = get_option_index(name)) == -1) {
  15406. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15407. free_context(ctx);
  15408. pthread_setspecific(sTlsKey, NULL);
  15409. return NULL;
  15410. } else if ((value = *options++) == NULL) {
  15411. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15412. free_context(ctx);
  15413. pthread_setspecific(sTlsKey, NULL);
  15414. return NULL;
  15415. }
  15416. if (ctx->dd.config[idx] != NULL) {
  15417. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15418. mg_free(ctx->dd.config[idx]);
  15419. }
  15420. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  15421. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15422. }
  15423. /* Set default value if needed */
  15424. for (i = 0; config_options[i].name != NULL; i++) {
  15425. default_value = config_options[i].default_value;
  15426. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  15427. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  15428. }
  15429. }
  15430. /* Request size option */
  15431. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  15432. if (itmp < 1024) {
  15433. mg_cry_internal(fc(ctx), "%s", "max_request_size too small");
  15434. free_context(ctx);
  15435. pthread_setspecific(sTlsKey, NULL);
  15436. return NULL;
  15437. }
  15438. ctx->max_request_size = (unsigned)itmp;
  15439. /* Worker thread count option */
  15440. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  15441. if (workerthreadcount > MAX_WORKER_THREADS) {
  15442. mg_cry_internal(fc(ctx), "%s", "Too many worker threads");
  15443. free_context(ctx);
  15444. pthread_setspecific(sTlsKey, NULL);
  15445. return NULL;
  15446. }
  15447. if (workerthreadcount <= 0) {
  15448. mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads");
  15449. free_context(ctx);
  15450. pthread_setspecific(sTlsKey, NULL);
  15451. return NULL;
  15452. }
  15453. /* Document root */
  15454. #if defined(NO_FILES)
  15455. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  15456. mg_cry_internal(fc(ctx), "%s", "Document root must not be set");
  15457. free_context(ctx);
  15458. pthread_setspecific(sTlsKey, NULL);
  15459. return NULL;
  15460. }
  15461. #endif
  15462. get_system_name(&ctx->systemName);
  15463. #if defined(USE_LUA)
  15464. /* If a Lua background script has been configured, start it. */
  15465. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  15466. char ebuf[256];
  15467. struct vec opt_vec;
  15468. struct vec eq_vec;
  15469. const char *sparams;
  15470. lua_State *state = mg_prepare_lua_context_script(
  15471. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  15472. if (!state) {
  15473. mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf);
  15474. free_context(ctx);
  15475. pthread_setspecific(sTlsKey, NULL);
  15476. return NULL;
  15477. }
  15478. ctx->lua_background_state = (void *)state;
  15479. lua_newtable(state);
  15480. reg_boolean(state, "shutdown", 0);
  15481. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  15482. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  15483. reg_llstring(
  15484. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  15485. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  15486. break;
  15487. }
  15488. lua_setglobal(state, LUABACKGROUNDPARAMS);
  15489. } else {
  15490. ctx->lua_background_state = 0;
  15491. }
  15492. #endif
  15493. /* NOTE(lsm): order is important here. SSL certificates must
  15494. * be initialized before listening ports. UID must be set last. */
  15495. if (!set_gpass_option(ctx, NULL) ||
  15496. #if !defined(NO_SSL)
  15497. !init_ssl_ctx(ctx, NULL) ||
  15498. #endif
  15499. !set_ports_option(ctx) ||
  15500. #if !defined(_WIN32)
  15501. !set_uid_option(ctx) ||
  15502. #endif
  15503. !set_acl_option(ctx)) {
  15504. free_context(ctx);
  15505. pthread_setspecific(sTlsKey, NULL);
  15506. return NULL;
  15507. }
  15508. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  15509. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15510. sizeof(pthread_t),
  15511. ctx);
  15512. if (ctx->worker_threadids == NULL) {
  15513. mg_cry_internal(fc(ctx),
  15514. "%s",
  15515. "Not enough memory for worker thread ID array");
  15516. free_context(ctx);
  15517. pthread_setspecific(sTlsKey, NULL);
  15518. return NULL;
  15519. }
  15520. ctx->worker_connections =
  15521. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  15522. sizeof(struct mg_connection),
  15523. ctx);
  15524. if (ctx->worker_connections == NULL) {
  15525. mg_cry_internal(fc(ctx),
  15526. "%s",
  15527. "Not enough memory for worker thread connection array");
  15528. free_context(ctx);
  15529. pthread_setspecific(sTlsKey, NULL);
  15530. return NULL;
  15531. }
  15532. #if defined(ALTERNATIVE_QUEUE)
  15533. ctx->client_wait_events =
  15534. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  15535. ctx->cfg_worker_threads,
  15536. ctx);
  15537. if (ctx->client_wait_events == NULL) {
  15538. mg_cry_internal(fc(ctx),
  15539. "%s",
  15540. "Not enough memory for worker event array");
  15541. mg_free(ctx->worker_threadids);
  15542. free_context(ctx);
  15543. pthread_setspecific(sTlsKey, NULL);
  15544. return NULL;
  15545. }
  15546. ctx->client_socks =
  15547. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  15548. ctx->cfg_worker_threads,
  15549. ctx);
  15550. if (ctx->client_wait_events == NULL) {
  15551. mg_cry_internal(fc(ctx),
  15552. "%s",
  15553. "Not enough memory for worker socket array");
  15554. mg_free(ctx->client_socks);
  15555. mg_free(ctx->worker_threadids);
  15556. free_context(ctx);
  15557. pthread_setspecific(sTlsKey, NULL);
  15558. return NULL;
  15559. }
  15560. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  15561. ctx->client_wait_events[i] = event_create();
  15562. if (ctx->client_wait_events[i] == 0) {
  15563. mg_cry_internal(fc(ctx), "Error creating worker event %i", i);
  15564. while (i > 0) {
  15565. i--;
  15566. event_destroy(ctx->client_wait_events[i]);
  15567. }
  15568. mg_free(ctx->client_socks);
  15569. mg_free(ctx->worker_threadids);
  15570. free_context(ctx);
  15571. pthread_setspecific(sTlsKey, NULL);
  15572. return NULL;
  15573. }
  15574. }
  15575. #endif
  15576. #if defined(USE_TIMERS)
  15577. if (timers_init(ctx) != 0) {
  15578. mg_cry_internal(fc(ctx), "%s", "Error creating timers");
  15579. free_context(ctx);
  15580. pthread_setspecific(sTlsKey, NULL);
  15581. return NULL;
  15582. }
  15583. #endif
  15584. /* Context has been created - init user libraries */
  15585. if (ctx->callbacks.init_context) {
  15586. ctx->callbacks.init_context(ctx);
  15587. }
  15588. ctx->callbacks.exit_context = exit_callback;
  15589. ctx->context_type = CONTEXT_SERVER; /* server context */
  15590. /* Start master (listening) thread */
  15591. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  15592. /* Start worker threads */
  15593. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  15594. struct worker_thread_args *wta = (struct worker_thread_args *)
  15595. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  15596. if (wta) {
  15597. wta->ctx = ctx;
  15598. wta->index = (int)i;
  15599. }
  15600. if ((wta == NULL)
  15601. || (mg_start_thread_with_id(worker_thread,
  15602. wta,
  15603. &ctx->worker_threadids[i]) != 0)) {
  15604. /* thread was not created */
  15605. if (wta != NULL) {
  15606. mg_free(wta);
  15607. }
  15608. if (i > 0) {
  15609. mg_cry_internal(fc(ctx),
  15610. "Cannot start worker thread %i: error %ld",
  15611. i + 1,
  15612. (long)ERRNO);
  15613. } else {
  15614. mg_cry_internal(fc(ctx),
  15615. "Cannot create threads: error %ld",
  15616. (long)ERRNO);
  15617. free_context(ctx);
  15618. pthread_setspecific(sTlsKey, NULL);
  15619. return NULL;
  15620. }
  15621. break;
  15622. }
  15623. }
  15624. pthread_setspecific(sTlsKey, NULL);
  15625. return ctx;
  15626. }
  15627. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15628. /* Add an additional domain to an already running web server. */
  15629. int
  15630. mg_start_domain(struct mg_context *ctx, const char **options)
  15631. {
  15632. const char *name;
  15633. const char *value;
  15634. const char *default_value;
  15635. struct mg_domain_context *new_dom;
  15636. struct mg_domain_context *dom;
  15637. int idx, i;
  15638. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  15639. return -1;
  15640. }
  15641. new_dom = (struct mg_domain_context *)
  15642. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  15643. if (!new_dom) {
  15644. /* Out of memory */
  15645. return -6;
  15646. }
  15647. /* Store options - TODO: unite duplicate code */
  15648. while (options && (name = *options++) != NULL) {
  15649. if ((idx = get_option_index(name)) == -1) {
  15650. mg_cry_internal(fc(ctx), "Invalid option: %s", name);
  15651. mg_free(new_dom);
  15652. return -2;
  15653. } else if ((value = *options++) == NULL) {
  15654. mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name);
  15655. mg_free(new_dom);
  15656. return -2;
  15657. }
  15658. if (new_dom->config[idx] != NULL) {
  15659. mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name);
  15660. mg_free(new_dom->config[idx]);
  15661. }
  15662. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  15663. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15664. }
  15665. /* Authentication domain is mandatory */
  15666. /* TODO: Maybe use a new option hostname? */
  15667. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  15668. return -4;
  15669. }
  15670. /* Set default value if needed. Take the config value from
  15671. * ctx as a default value. */
  15672. for (i = 0; config_options[i].name != NULL; i++) {
  15673. default_value = ctx->dd.config[i];
  15674. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  15675. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  15676. }
  15677. }
  15678. new_dom->handlers = NULL;
  15679. new_dom->next = NULL;
  15680. new_dom->nonce_count = 0;
  15681. new_dom->auth_nonce_mask =
  15682. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  15683. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15684. new_dom->shared_lua_websockets = NULL;
  15685. #endif
  15686. if (!init_ssl_ctx(ctx, new_dom)) {
  15687. /* Init SSL failed */
  15688. mg_free(new_dom);
  15689. return -3;
  15690. }
  15691. /* Add element to linked list. */
  15692. mg_lock_context(ctx);
  15693. idx = 0;
  15694. dom = &(ctx->dd);
  15695. for (;;) {
  15696. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  15697. dom->config[AUTHENTICATION_DOMAIN])) {
  15698. /* Domain collision */
  15699. mg_cry_internal(fc(ctx),
  15700. "domain %s already in use",
  15701. new_dom->config[AUTHENTICATION_DOMAIN]);
  15702. mg_free(new_dom);
  15703. return -5;
  15704. }
  15705. /* Count number of domains */
  15706. idx++;
  15707. if (dom->next == NULL) {
  15708. dom->next = new_dom;
  15709. break;
  15710. }
  15711. dom = dom->next;
  15712. }
  15713. mg_unlock_context(ctx);
  15714. /* Return domain number */
  15715. return idx;
  15716. }
  15717. #endif
  15718. /* Feature check API function */
  15719. unsigned
  15720. mg_check_feature(unsigned feature)
  15721. {
  15722. static const unsigned feature_set = 0
  15723. /* Set bits for available features according to API documentation.
  15724. * This bit mask is created at compile time, according to the active
  15725. * preprocessor defines. It is a single const value at runtime. */
  15726. #if !defined(NO_FILES)
  15727. | MG_FEATURES_FILES
  15728. #endif
  15729. #if !defined(NO_SSL)
  15730. | MG_FEATURES_SSL
  15731. #endif
  15732. #if !defined(NO_CGI)
  15733. | MG_FEATURES_CGI
  15734. #endif
  15735. #if defined(USE_IPV6)
  15736. | MG_FEATURES_IPV6
  15737. #endif
  15738. #if defined(USE_WEBSOCKET)
  15739. | MG_FEATURES_WEBSOCKET
  15740. #endif
  15741. #if defined(USE_LUA)
  15742. | MG_FEATURES_LUA
  15743. #endif
  15744. #if defined(USE_DUKTAPE)
  15745. | MG_FEATURES_SSJS
  15746. #endif
  15747. #if !defined(NO_CACHING)
  15748. | MG_FEATURES_CACHE
  15749. #endif
  15750. #if defined(USE_SERVER_STATS)
  15751. | MG_FEATURES_STATS
  15752. #endif
  15753. #if defined(USE_ZLIB)
  15754. | MG_FEATURES_COMPRESSION
  15755. #endif
  15756. /* Set some extra bits not defined in the API documentation.
  15757. * These bits may change without further notice. */
  15758. #if defined(MG_LEGACY_INTERFACE)
  15759. | 0x00008000u
  15760. #endif
  15761. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15762. | 0x00004000u
  15763. #endif
  15764. #if defined(MEMORY_DEBUGGING)
  15765. | 0x00001000u
  15766. #endif
  15767. #if defined(USE_TIMERS)
  15768. | 0x00020000u
  15769. #endif
  15770. #if !defined(NO_NONCE_CHECK)
  15771. | 0x00040000u
  15772. #endif
  15773. #if !defined(NO_POPEN)
  15774. | 0x00080000u
  15775. #endif
  15776. ;
  15777. return (feature & feature_set);
  15778. }
  15779. /* strcat with additional NULL check to avoid clang scan-build warning. */
  15780. #define strcat0(a, b) \
  15781. { \
  15782. if ((a != NULL) && (b != NULL)) { \
  15783. strcat(a, b); \
  15784. } \
  15785. }
  15786. /* Get system information. It can be printed or stored by the caller.
  15787. * Return the size of available information. */
  15788. static int
  15789. mg_get_system_info_impl(char *buffer, int buflen)
  15790. {
  15791. char block[256];
  15792. int system_info_length = 0;
  15793. #if defined(_WIN32)
  15794. const char *eol = "\r\n";
  15795. #else
  15796. const char *eol = "\n";
  15797. #endif
  15798. const char *eoobj = "}";
  15799. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15800. if ((buffer == NULL) || (buflen < 1)) {
  15801. buflen = 0;
  15802. } else {
  15803. *buffer = 0;
  15804. }
  15805. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15806. system_info_length += (int)strlen(block);
  15807. if (system_info_length < buflen) {
  15808. strcat0(buffer, block);
  15809. }
  15810. /* Server version */
  15811. {
  15812. const char *version = mg_version();
  15813. mg_snprintf(NULL,
  15814. NULL,
  15815. block,
  15816. sizeof(block),
  15817. "\"version\" : \"%s\",%s",
  15818. version,
  15819. eol);
  15820. system_info_length += (int)strlen(block);
  15821. if (system_info_length < buflen) {
  15822. strcat0(buffer, block);
  15823. }
  15824. }
  15825. /* System info */
  15826. {
  15827. #if defined(_WIN32)
  15828. #if !defined(__SYMBIAN32__)
  15829. DWORD dwVersion = 0;
  15830. DWORD dwMajorVersion = 0;
  15831. DWORD dwMinorVersion = 0;
  15832. SYSTEM_INFO si;
  15833. GetSystemInfo(&si);
  15834. #if defined(_MSC_VER)
  15835. #pragma warning(push)
  15836. /* GetVersion was declared deprecated */
  15837. #pragma warning(disable : 4996)
  15838. #endif
  15839. dwVersion = GetVersion();
  15840. #if defined(_MSC_VER)
  15841. #pragma warning(pop)
  15842. #endif
  15843. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15844. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15845. mg_snprintf(NULL,
  15846. NULL,
  15847. block,
  15848. sizeof(block),
  15849. "\"os\" : \"Windows %u.%u\",%s",
  15850. (unsigned)dwMajorVersion,
  15851. (unsigned)dwMinorVersion,
  15852. eol);
  15853. system_info_length += (int)strlen(block);
  15854. if (system_info_length < buflen) {
  15855. strcat0(buffer, block);
  15856. }
  15857. mg_snprintf(NULL,
  15858. NULL,
  15859. block,
  15860. sizeof(block),
  15861. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  15862. (unsigned)si.wProcessorArchitecture,
  15863. (unsigned)si.dwNumberOfProcessors,
  15864. (unsigned)si.dwActiveProcessorMask,
  15865. eol);
  15866. system_info_length += (int)strlen(block);
  15867. if (system_info_length < buflen) {
  15868. strcat0(buffer, block);
  15869. }
  15870. #else
  15871. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  15872. system_info_length += (int)strlen(block);
  15873. if (system_info_length < buflen) {
  15874. strcat0(buffer, block);
  15875. }
  15876. #endif
  15877. #else
  15878. struct utsname name;
  15879. memset(&name, 0, sizeof(name));
  15880. uname(&name);
  15881. mg_snprintf(NULL,
  15882. NULL,
  15883. block,
  15884. sizeof(block),
  15885. "\"os\" : \"%s %s (%s) - %s\",%s",
  15886. name.sysname,
  15887. name.version,
  15888. name.release,
  15889. name.machine,
  15890. eol);
  15891. system_info_length += (int)strlen(block);
  15892. if (system_info_length < buflen) {
  15893. strcat0(buffer, block);
  15894. }
  15895. #endif
  15896. }
  15897. /* Features */
  15898. {
  15899. mg_snprintf(NULL,
  15900. NULL,
  15901. block,
  15902. sizeof(block),
  15903. "\"features\" : %lu,%s"
  15904. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  15905. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  15906. eol,
  15907. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  15908. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  15909. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  15910. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  15911. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  15912. : "",
  15913. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  15914. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  15915. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  15916. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  15917. eol);
  15918. system_info_length += (int)strlen(block);
  15919. if (system_info_length < buflen) {
  15920. strcat0(buffer, block);
  15921. }
  15922. #if defined(USE_LUA)
  15923. mg_snprintf(NULL,
  15924. NULL,
  15925. block,
  15926. sizeof(block),
  15927. "\"lua_version\" : \"%u (%s)\",%s",
  15928. (unsigned)LUA_VERSION_NUM,
  15929. LUA_RELEASE,
  15930. eol);
  15931. system_info_length += (int)strlen(block);
  15932. if (system_info_length < buflen) {
  15933. strcat0(buffer, block);
  15934. }
  15935. #endif
  15936. #if defined(USE_DUKTAPE)
  15937. mg_snprintf(NULL,
  15938. NULL,
  15939. block,
  15940. sizeof(block),
  15941. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  15942. (unsigned)DUK_VERSION / 10000,
  15943. ((unsigned)DUK_VERSION / 100) % 100,
  15944. (unsigned)DUK_VERSION % 100,
  15945. eol);
  15946. system_info_length += (int)strlen(block);
  15947. if (system_info_length < buflen) {
  15948. strcat0(buffer, block);
  15949. }
  15950. #endif
  15951. }
  15952. /* Build date */
  15953. {
  15954. #if defined(__GNUC__)
  15955. #pragma GCC diagnostic push
  15956. /* Disable bogus compiler warning -Wdate-time */
  15957. #pragma GCC diagnostic ignored "-Wdate-time"
  15958. #endif
  15959. mg_snprintf(NULL,
  15960. NULL,
  15961. block,
  15962. sizeof(block),
  15963. "\"build\" : \"%s\",%s",
  15964. __DATE__,
  15965. eol);
  15966. #if defined(__GNUC__)
  15967. #pragma GCC diagnostic pop
  15968. #endif
  15969. system_info_length += (int)strlen(block);
  15970. if (system_info_length < buflen) {
  15971. strcat0(buffer, block);
  15972. }
  15973. }
  15974. /* Compiler information */
  15975. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  15976. {
  15977. #if defined(_MSC_VER)
  15978. mg_snprintf(NULL,
  15979. NULL,
  15980. block,
  15981. sizeof(block),
  15982. "\"compiler\" : \"MSC: %u (%u)\",%s",
  15983. (unsigned)_MSC_VER,
  15984. (unsigned)_MSC_FULL_VER,
  15985. eol);
  15986. system_info_length += (int)strlen(block);
  15987. if (system_info_length < buflen) {
  15988. strcat0(buffer, block);
  15989. }
  15990. #elif defined(__MINGW64__)
  15991. mg_snprintf(NULL,
  15992. NULL,
  15993. block,
  15994. sizeof(block),
  15995. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  15996. (unsigned)__MINGW64_VERSION_MAJOR,
  15997. (unsigned)__MINGW64_VERSION_MINOR,
  15998. eol);
  15999. system_info_length += (int)strlen(block);
  16000. if (system_info_length < buflen) {
  16001. strcat0(buffer, block);
  16002. }
  16003. mg_snprintf(NULL,
  16004. NULL,
  16005. block,
  16006. sizeof(block),
  16007. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16008. (unsigned)__MINGW32_MAJOR_VERSION,
  16009. (unsigned)__MINGW32_MINOR_VERSION,
  16010. eol);
  16011. system_info_length += (int)strlen(block);
  16012. if (system_info_length < buflen) {
  16013. strcat0(buffer, block);
  16014. }
  16015. #elif defined(__MINGW32__)
  16016. mg_snprintf(NULL,
  16017. NULL,
  16018. block,
  16019. sizeof(block),
  16020. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  16021. (unsigned)__MINGW32_MAJOR_VERSION,
  16022. (unsigned)__MINGW32_MINOR_VERSION,
  16023. eol);
  16024. system_info_length += (int)strlen(block);
  16025. if (system_info_length < buflen) {
  16026. strcat0(buffer, block);
  16027. }
  16028. #elif defined(__clang__)
  16029. mg_snprintf(NULL,
  16030. NULL,
  16031. block,
  16032. sizeof(block),
  16033. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  16034. __clang_major__,
  16035. __clang_minor__,
  16036. __clang_patchlevel__,
  16037. __clang_version__,
  16038. eol);
  16039. system_info_length += (int)strlen(block);
  16040. if (system_info_length < buflen) {
  16041. strcat0(buffer, block);
  16042. }
  16043. #elif defined(__GNUC__)
  16044. mg_snprintf(NULL,
  16045. NULL,
  16046. block,
  16047. sizeof(block),
  16048. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  16049. (unsigned)__GNUC__,
  16050. (unsigned)__GNUC_MINOR__,
  16051. (unsigned)__GNUC_PATCHLEVEL__,
  16052. eol);
  16053. system_info_length += (int)strlen(block);
  16054. if (system_info_length < buflen) {
  16055. strcat0(buffer, block);
  16056. }
  16057. #elif defined(__INTEL_COMPILER)
  16058. mg_snprintf(NULL,
  16059. NULL,
  16060. block,
  16061. sizeof(block),
  16062. "\"compiler\" : \"Intel C/C++: %u\",%s",
  16063. (unsigned)__INTEL_COMPILER,
  16064. eol);
  16065. system_info_length += (int)strlen(block);
  16066. if (system_info_length < buflen) {
  16067. strcat0(buffer, block);
  16068. }
  16069. #elif defined(__BORLANDC__)
  16070. mg_snprintf(NULL,
  16071. NULL,
  16072. block,
  16073. sizeof(block),
  16074. "\"compiler\" : \"Borland C: 0x%x\",%s",
  16075. (unsigned)__BORLANDC__,
  16076. eol);
  16077. system_info_length += (int)strlen(block);
  16078. if (system_info_length < buflen) {
  16079. strcat0(buffer, block);
  16080. }
  16081. #elif defined(__SUNPRO_C)
  16082. mg_snprintf(NULL,
  16083. NULL,
  16084. block,
  16085. sizeof(block),
  16086. "\"compiler\" : \"Solaris: 0x%x\",%s",
  16087. (unsigned)__SUNPRO_C,
  16088. eol);
  16089. system_info_length += (int)strlen(block);
  16090. if (system_info_length < buflen) {
  16091. strcat0(buffer, block);
  16092. }
  16093. #else
  16094. mg_snprintf(NULL,
  16095. NULL,
  16096. block,
  16097. sizeof(block),
  16098. "\"compiler\" : \"other\",%s",
  16099. eol);
  16100. system_info_length += (int)strlen(block);
  16101. if (system_info_length < buflen) {
  16102. strcat0(buffer, block);
  16103. }
  16104. #endif
  16105. }
  16106. /* Determine 32/64 bit data mode.
  16107. * see https://en.wikipedia.org/wiki/64-bit_computing */
  16108. {
  16109. mg_snprintf(NULL,
  16110. NULL,
  16111. block,
  16112. sizeof(block),
  16113. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, "
  16114. "char:%u/%u, "
  16115. "ptr:%u, size:%u, time:%u\"%s",
  16116. (unsigned)sizeof(short),
  16117. (unsigned)sizeof(int),
  16118. (unsigned)sizeof(long),
  16119. (unsigned)sizeof(long long),
  16120. (unsigned)sizeof(float),
  16121. (unsigned)sizeof(double),
  16122. (unsigned)sizeof(long double),
  16123. (unsigned)sizeof(char),
  16124. (unsigned)sizeof(wchar_t),
  16125. (unsigned)sizeof(void *),
  16126. (unsigned)sizeof(size_t),
  16127. (unsigned)sizeof(time_t),
  16128. eol);
  16129. system_info_length += (int)strlen(block);
  16130. if (system_info_length < buflen) {
  16131. strcat0(buffer, block);
  16132. }
  16133. }
  16134. /* Terminate string */
  16135. if ((buflen > 0) && buffer && buffer[0]) {
  16136. if (system_info_length < buflen) {
  16137. strcat0(buffer, eoobj);
  16138. strcat0(buffer, eol);
  16139. }
  16140. }
  16141. system_info_length += reserved_len;
  16142. return system_info_length;
  16143. }
  16144. #if defined(USE_SERVER_STATS)
  16145. /* Get context information. It can be printed or stored by the caller.
  16146. * Return the size of available information. */
  16147. static int
  16148. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  16149. {
  16150. char block[256];
  16151. int context_info_length = 0;
  16152. #if defined(_WIN32)
  16153. const char *eol = "\r\n";
  16154. #else
  16155. const char *eol = "\n";
  16156. #endif
  16157. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  16158. const char *eoobj = "}";
  16159. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16160. if ((buffer == NULL) || (buflen < 1)) {
  16161. buflen = 0;
  16162. } else {
  16163. *buffer = 0;
  16164. }
  16165. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16166. context_info_length += (int)strlen(block);
  16167. if (context_info_length < buflen) {
  16168. strcat0(buffer, block);
  16169. }
  16170. if (ms) { /* <-- should be always true */
  16171. /* Memory information */
  16172. mg_snprintf(NULL,
  16173. NULL,
  16174. block,
  16175. sizeof(block),
  16176. "\"memory\" : {%s"
  16177. "\"blocks\" : %i,%s"
  16178. "\"used\" : %" INT64_FMT ",%s"
  16179. "\"maxUsed\" : %" INT64_FMT "%s"
  16180. "}%s%s",
  16181. eol,
  16182. ms->blockCount,
  16183. eol,
  16184. ms->totalMemUsed,
  16185. eol,
  16186. ms->maxMemUsed,
  16187. eol,
  16188. (ctx ? "," : ""),
  16189. eol);
  16190. context_info_length += (int)strlen(block);
  16191. if (context_info_length + reserved_len < buflen) {
  16192. strcat0(buffer, block);
  16193. }
  16194. }
  16195. if (ctx) {
  16196. /* Connections information */
  16197. mg_snprintf(NULL,
  16198. NULL,
  16199. block,
  16200. sizeof(block),
  16201. "\"connections\" : {%s"
  16202. "\"active\" : %i,%s"
  16203. "\"maxActive\" : %i,%s"
  16204. "\"total\" : %" INT64_FMT "%s"
  16205. "},%s",
  16206. eol,
  16207. ctx->active_connections,
  16208. eol,
  16209. ctx->max_connections,
  16210. eol,
  16211. ctx->total_connections,
  16212. eol,
  16213. eol);
  16214. context_info_length += (int)strlen(block);
  16215. if (context_info_length + reserved_len < buflen) {
  16216. strcat0(buffer, block);
  16217. }
  16218. /* Requests information */
  16219. mg_snprintf(NULL,
  16220. NULL,
  16221. block,
  16222. sizeof(block),
  16223. "\"requests\" : {%s"
  16224. "\"total\" : %" INT64_FMT "%s"
  16225. "},%s",
  16226. eol,
  16227. ctx->total_requests,
  16228. eol,
  16229. eol);
  16230. context_info_length += (int)strlen(block);
  16231. if (context_info_length + reserved_len < buflen) {
  16232. strcat0(buffer, block);
  16233. }
  16234. /* Data information */
  16235. mg_snprintf(NULL,
  16236. NULL,
  16237. block,
  16238. sizeof(block),
  16239. "\"data\" : {%s"
  16240. "\"read\" : %" INT64_FMT "%s,"
  16241. "\"written\" : %" INT64_FMT "%s"
  16242. "},%s",
  16243. eol,
  16244. ctx->total_data_read,
  16245. eol,
  16246. ctx->total_data_written,
  16247. eol,
  16248. eol);
  16249. context_info_length += (int)strlen(block);
  16250. if (context_info_length + reserved_len < buflen) {
  16251. strcat0(buffer, block);
  16252. }
  16253. /* Execution time information */
  16254. char start_time_str[64] = {0};
  16255. char now_str[64] = {0};
  16256. time_t start_time = ctx->start_time;
  16257. time_t now = time(NULL);
  16258. gmt_time_string(start_time_str,
  16259. sizeof(start_time_str) - 1,
  16260. &start_time);
  16261. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16262. mg_snprintf(NULL,
  16263. NULL,
  16264. block,
  16265. sizeof(block),
  16266. "\"time\" : {%s"
  16267. "\"uptime\" : %.0f,%s"
  16268. "\"start\" : \"%s\",%s"
  16269. "\"now\" : \"%s\"%s"
  16270. "}%s",
  16271. eol,
  16272. difftime(now, start_time),
  16273. eol,
  16274. start_time_str,
  16275. eol,
  16276. now_str,
  16277. eol,
  16278. eol);
  16279. context_info_length += (int)strlen(block);
  16280. if (context_info_length + reserved_len < buflen) {
  16281. strcat0(buffer, block);
  16282. }
  16283. }
  16284. /* Terminate string */
  16285. if ((buflen > 0) && buffer && buffer[0]) {
  16286. if (context_info_length < buflen) {
  16287. strcat0(buffer, eoobj);
  16288. strcat0(buffer, eol);
  16289. }
  16290. }
  16291. context_info_length += reserved_len;
  16292. return context_info_length;
  16293. }
  16294. #endif
  16295. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16296. /* Get connection information. It can be printed or stored by the caller.
  16297. * Return the size of available information. */
  16298. static int
  16299. mg_get_connection_info_impl(const struct mg_context *ctx,
  16300. int idx,
  16301. char *buffer,
  16302. int buflen)
  16303. {
  16304. const struct mg_connection *conn;
  16305. const struct mg_request_info *ri;
  16306. char block[256];
  16307. int connection_info_length = 0;
  16308. int state = 0;
  16309. const char *state_str = "unknown";
  16310. #if defined(_WIN32)
  16311. const char *eol = "\r\n";
  16312. #else
  16313. const char *eol = "\n";
  16314. #endif
  16315. const char *eoobj = "}";
  16316. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  16317. if ((buffer == NULL) || (buflen < 1)) {
  16318. buflen = 0;
  16319. } else {
  16320. *buffer = 0;
  16321. }
  16322. if ((ctx == NULL) || (idx < 0)) {
  16323. /* Parameter error */
  16324. return 0;
  16325. }
  16326. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  16327. /* Out of range */
  16328. return 0;
  16329. }
  16330. /* Take connection [idx]. This connection is not locked in
  16331. * any way, so some other thread might use it. */
  16332. conn = (ctx->worker_connections) + idx;
  16333. /* Initialize output string */
  16334. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  16335. connection_info_length += (int)strlen(block);
  16336. if (connection_info_length < buflen) {
  16337. strcat0(buffer, block);
  16338. }
  16339. /* Init variables */
  16340. ri = &(conn->request_info);
  16341. #if defined(USE_SERVER_STATS)
  16342. state = conn->conn_state;
  16343. /* State as string */
  16344. switch (state) {
  16345. case 0:
  16346. state_str = "undefined";
  16347. break;
  16348. case 1:
  16349. state_str = "not used";
  16350. break;
  16351. case 2:
  16352. state_str = "init";
  16353. break;
  16354. case 3:
  16355. state_str = "ready";
  16356. break;
  16357. case 4:
  16358. state_str = "processing";
  16359. break;
  16360. case 5:
  16361. state_str = "processed";
  16362. break;
  16363. case 6:
  16364. state_str = "to close";
  16365. break;
  16366. case 7:
  16367. state_str = "closing";
  16368. break;
  16369. case 8:
  16370. state_str = "closed";
  16371. break;
  16372. case 9:
  16373. state_str = "done";
  16374. break;
  16375. }
  16376. #endif
  16377. /* Connection info */
  16378. if ((state >= 3) && (state < 9)) {
  16379. mg_snprintf(NULL,
  16380. NULL,
  16381. block,
  16382. sizeof(block),
  16383. "\"connection\" : {%s"
  16384. "\"remote\" : {%s"
  16385. "\"protocol\" : \"%s\",%s"
  16386. "\"addr\" : \"%s\",%s"
  16387. "\"port\" : %u%s"
  16388. "},%s"
  16389. "\"handled_requests\" : %u%s"
  16390. "},%s",
  16391. eol,
  16392. eol,
  16393. get_proto_name(conn),
  16394. eol,
  16395. ri->remote_addr,
  16396. eol,
  16397. ri->remote_port,
  16398. eol,
  16399. eol,
  16400. conn->handled_requests,
  16401. eol,
  16402. eol);
  16403. connection_info_length += (int)strlen(block);
  16404. if (connection_info_length + reserved_len < buflen) {
  16405. strcat0(buffer, block);
  16406. }
  16407. }
  16408. /* Request info */
  16409. if ((state >= 4) && (state < 6)) {
  16410. mg_snprintf(NULL,
  16411. NULL,
  16412. block,
  16413. sizeof(block),
  16414. "\"request_info\" : {%s"
  16415. "\"method\" : \"%s\",%s"
  16416. "\"uri\" : \"%s\",%s"
  16417. "\"query\" : %s%s%s%s"
  16418. "},%s",
  16419. eol,
  16420. ri->request_method,
  16421. eol,
  16422. ri->request_uri,
  16423. eol,
  16424. ri->query_string ? "\"" : "",
  16425. ri->query_string ? ri->query_string : "null",
  16426. ri->query_string ? "\"" : "",
  16427. eol,
  16428. eol);
  16429. connection_info_length += (int)strlen(block);
  16430. if (connection_info_length + reserved_len < buflen) {
  16431. strcat0(buffer, block);
  16432. }
  16433. }
  16434. /* Execution time information */
  16435. if ((state >= 2) && (state < 9)) {
  16436. char start_time_str[64] = {0};
  16437. char now_str[64] = {0};
  16438. time_t start_time = conn->conn_birth_time;
  16439. time_t now = time(NULL);
  16440. gmt_time_string(start_time_str,
  16441. sizeof(start_time_str) - 1,
  16442. &start_time);
  16443. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  16444. mg_snprintf(NULL,
  16445. NULL,
  16446. block,
  16447. sizeof(block),
  16448. "\"time\" : {%s"
  16449. "\"uptime\" : %.0f,%s"
  16450. "\"start\" : \"%s\",%s"
  16451. "\"now\" : \"%s\"%s"
  16452. "},%s",
  16453. eol,
  16454. difftime(now, start_time),
  16455. eol,
  16456. start_time_str,
  16457. eol,
  16458. now_str,
  16459. eol,
  16460. eol);
  16461. connection_info_length += (int)strlen(block);
  16462. if (connection_info_length + reserved_len < buflen) {
  16463. strcat0(buffer, block);
  16464. }
  16465. }
  16466. /* Remote user name */
  16467. if ((ri->remote_user) && (state < 9)) {
  16468. mg_snprintf(NULL,
  16469. NULL,
  16470. block,
  16471. sizeof(block),
  16472. "\"user\" : {%s"
  16473. "\"name\" : \"%s\",%s"
  16474. "},%s",
  16475. eol,
  16476. ri->remote_user,
  16477. eol,
  16478. eol);
  16479. connection_info_length += (int)strlen(block);
  16480. if (connection_info_length + reserved_len < buflen) {
  16481. strcat0(buffer, block);
  16482. }
  16483. }
  16484. /* Data block */
  16485. if (state >= 3) {
  16486. mg_snprintf(NULL,
  16487. NULL,
  16488. block,
  16489. sizeof(block),
  16490. "\"data\" : {%s"
  16491. "\"read\" : %" INT64_FMT ",%s"
  16492. "\"written\" : %" INT64_FMT "%s"
  16493. "},%s",
  16494. eol,
  16495. conn->consumed_content,
  16496. eol,
  16497. conn->num_bytes_sent,
  16498. eol,
  16499. eol);
  16500. connection_info_length += (int)strlen(block);
  16501. if (connection_info_length + reserved_len < buflen) {
  16502. strcat0(buffer, block);
  16503. }
  16504. }
  16505. /* State */
  16506. mg_snprintf(NULL,
  16507. NULL,
  16508. block,
  16509. sizeof(block),
  16510. "\"state\" : \"%s\"%s",
  16511. state_str,
  16512. eol);
  16513. connection_info_length += (int)strlen(block);
  16514. if (connection_info_length + reserved_len < buflen) {
  16515. strcat0(buffer, block);
  16516. }
  16517. /* Terminate string */
  16518. if ((buflen > 0) && buffer && buffer[0]) {
  16519. if (connection_info_length < buflen) {
  16520. strcat0(buffer, eoobj);
  16521. strcat0(buffer, eol);
  16522. }
  16523. }
  16524. connection_info_length += reserved_len;
  16525. return connection_info_length;
  16526. }
  16527. #endif
  16528. /* Get system information. It can be printed or stored by the caller.
  16529. * Return the size of available information. */
  16530. int
  16531. mg_get_system_info(char *buffer, int buflen)
  16532. {
  16533. if ((buffer == NULL) || (buflen < 1)) {
  16534. return mg_get_system_info_impl(NULL, 0);
  16535. } else {
  16536. /* Reset buffer, so we can always use strcat. */
  16537. buffer[0] = 0;
  16538. return mg_get_system_info_impl(buffer, buflen);
  16539. }
  16540. }
  16541. /* Get context information. It can be printed or stored by the caller.
  16542. * Return the size of available information. */
  16543. int
  16544. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  16545. {
  16546. #if defined(USE_SERVER_STATS)
  16547. if ((buffer == NULL) || (buflen < 1)) {
  16548. return mg_get_context_info_impl(ctx, NULL, 0);
  16549. } else {
  16550. /* Reset buffer, so we can always use strcat. */
  16551. buffer[0] = 0;
  16552. return mg_get_context_info_impl(ctx, buffer, buflen);
  16553. }
  16554. #else
  16555. (void)ctx;
  16556. if ((buffer != NULL) && (buflen > 0)) {
  16557. buffer[0] = 0;
  16558. }
  16559. return 0;
  16560. #endif
  16561. }
  16562. #if defined(MG_EXPERIMENTAL_INTERFACES)
  16563. int
  16564. mg_get_connection_info(const struct mg_context *ctx,
  16565. int idx,
  16566. char *buffer,
  16567. int buflen)
  16568. {
  16569. if ((buffer == NULL) || (buflen < 1)) {
  16570. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  16571. } else {
  16572. /* Reset buffer, so we can always use strcat. */
  16573. buffer[0] = 0;
  16574. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  16575. }
  16576. }
  16577. #endif
  16578. /* Initialize this library. This function does not need to be thread safe.
  16579. */
  16580. unsigned
  16581. mg_init_library(unsigned features)
  16582. {
  16583. #if !defined(NO_SSL)
  16584. char ebuf[128];
  16585. #endif
  16586. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  16587. unsigned features_inited = features_to_init;
  16588. if (mg_init_library_called <= 0) {
  16589. /* Not initialized yet */
  16590. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  16591. return 0;
  16592. }
  16593. }
  16594. mg_global_lock();
  16595. if (mg_init_library_called <= 0) {
  16596. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  16597. /* Fatal error - abort start. However, this situation should
  16598. * never occur in practice. */
  16599. mg_global_unlock();
  16600. return 0;
  16601. }
  16602. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16603. InitializeCriticalSection(&global_log_file_lock);
  16604. #endif /* _WIN32 && !__SYMBIAN32__ */
  16605. #if !defined(_WIN32)
  16606. pthread_mutexattr_init(&pthread_mutex_attr);
  16607. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  16608. #endif
  16609. #if defined(USE_LUA)
  16610. lua_init_optional_libraries();
  16611. #endif
  16612. }
  16613. mg_global_unlock();
  16614. #if !defined(NO_SSL)
  16615. if (features_to_init & MG_FEATURES_SSL) {
  16616. if (!mg_ssl_initialized) {
  16617. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  16618. mg_ssl_initialized = 1;
  16619. } else {
  16620. (void)ebuf;
  16621. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  16622. features_inited &= ~((unsigned)(MG_FEATURES_SSL));
  16623. }
  16624. } else {
  16625. /* ssl already initialized */
  16626. }
  16627. }
  16628. #endif
  16629. /* Start WinSock for Windows */
  16630. mg_global_lock();
  16631. if (mg_init_library_called <= 0) {
  16632. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16633. WSADATA data;
  16634. WSAStartup(MAKEWORD(2, 2), &data);
  16635. #endif /* _WIN32 && !__SYMBIAN32__ */
  16636. mg_init_library_called = 1;
  16637. } else {
  16638. mg_init_library_called++;
  16639. }
  16640. mg_global_unlock();
  16641. return features_inited;
  16642. }
  16643. /* Un-initialize this library. */
  16644. unsigned
  16645. mg_exit_library(void)
  16646. {
  16647. if (mg_init_library_called <= 0) {
  16648. return 0;
  16649. }
  16650. mg_global_lock();
  16651. mg_init_library_called--;
  16652. if (mg_init_library_called == 0) {
  16653. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16654. (void)WSACleanup();
  16655. #endif /* _WIN32 && !__SYMBIAN32__ */
  16656. #if !defined(NO_SSL)
  16657. if (mg_ssl_initialized) {
  16658. uninitialize_ssl();
  16659. mg_ssl_initialized = 0;
  16660. }
  16661. #endif
  16662. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16663. (void)DeleteCriticalSection(&global_log_file_lock);
  16664. #endif /* _WIN32 && !__SYMBIAN32__ */
  16665. #if !defined(_WIN32)
  16666. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  16667. #endif
  16668. (void)pthread_key_delete(sTlsKey);
  16669. #if defined(USE_LUA)
  16670. lua_exit_optional_libraries();
  16671. #endif
  16672. mg_global_unlock();
  16673. (void)pthread_mutex_destroy(&global_lock_mutex);
  16674. return 1;
  16675. }
  16676. mg_global_unlock();
  16677. return 1;
  16678. }
  16679. /* End of civetweb.c */