civetweb.c 492 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618
  1. /* Copyright (c) 2013-2017 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(_WIN32)
  23. #if !defined(_CRT_SECURE_NO_WARNINGS)
  24. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  25. #endif
  26. #ifndef _WIN32_WINNT /* defined for tdm-gcc so we can use getnameinfo */
  27. #define _WIN32_WINNT 0x0501
  28. #endif
  29. #else
  30. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  31. #define _GNU_SOURCE /* for setgroups() */
  32. #endif
  33. #if defined(__linux__) && !defined(_XOPEN_SOURCE)
  34. #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */
  35. #endif
  36. #ifndef _LARGEFILE_SOURCE
  37. #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */
  38. #endif
  39. #ifndef _FILE_OFFSET_BITS
  40. #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */
  41. #endif
  42. #ifndef __STDC_FORMAT_MACROS
  43. #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */
  44. #endif
  45. #ifndef __STDC_LIMIT_MACROS
  46. #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */
  47. #endif
  48. #ifdef __sun
  49. #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */
  50. #define __inline inline /* not recognized on older compiler versions */
  51. #endif
  52. #endif
  53. #if defined(USE_LUA)
  54. #define USE_TIMERS
  55. #endif
  56. #if defined(_MSC_VER)
  57. /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */
  58. #pragma warning(disable : 4306)
  59. /* conditional expression is constant: introduced by FD_SET(..) */
  60. #pragma warning(disable : 4127)
  61. /* non-constant aggregate initializer: issued due to missing C99 support */
  62. #pragma warning(disable : 4204)
  63. /* padding added after data member */
  64. #pragma warning(disable : 4820)
  65. /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */
  66. #pragma warning(disable : 4668)
  67. /* no function prototype given: converting '()' to '(void)' */
  68. #pragma warning(disable : 4255)
  69. /* function has been selected for automatic inline expansion */
  70. #pragma warning(disable : 4711)
  71. #endif
  72. /* This code uses static_assert to check some conditions.
  73. * Unfortunately some compilers still do not support it, so we have a
  74. * replacement function here. */
  75. #if defined(_MSC_VER) && (_MSC_VER >= 1600)
  76. #define mg_static_assert static_assert
  77. #elif defined(__cplusplus) && (__cplusplus >= 201103L)
  78. #define mg_static_assert static_assert
  79. #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  80. #define mg_static_assert _Static_assert
  81. #else
  82. char static_assert_replacement[1];
  83. #define mg_static_assert(cond, txt) \
  84. extern char static_assert_replacement[(cond) ? 1 : -1]
  85. #endif
  86. mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8,
  87. "int data type size check");
  88. mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8,
  89. "pointer data type size check");
  90. mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check");
  91. /* Alternative queue is well tested and should be the new default */
  92. #ifdef NO_ALTERNATIVE_QUEUE
  93. #ifdef ALTERNATIVE_QUEUE
  94. #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both"
  95. #endif
  96. #else
  97. #define ALTERNATIVE_QUEUE
  98. #endif
  99. /* DTL -- including winsock2.h works better if lean and mean */
  100. #ifndef WIN32_LEAN_AND_MEAN
  101. #define WIN32_LEAN_AND_MEAN
  102. #endif
  103. #if defined(__SYMBIAN32__)
  104. /* According to https://en.wikipedia.org/wiki/Symbian#History,
  105. * Symbian is no longer maintained since 2014-01-01.
  106. * Recent versions of CivetWeb are no longer tested for Symbian.
  107. * It makes no sense, to support an abandoned operating system.
  108. * All remaining "#ifdef __SYMBIAN__" cases will be droped from
  109. * the code sooner or later.
  110. */
  111. #pragma message \
  112. "Symbian is no longer maintained. CivetWeb will drop Symbian support."
  113. #define NO_SSL /* SSL is not supported */
  114. #define NO_CGI /* CGI is not supported */
  115. #define PATH_MAX FILENAME_MAX
  116. #endif /* __SYMBIAN32__ */
  117. #ifndef CIVETWEB_HEADER_INCLUDED
  118. /* Include the header file here, so the CivetWeb interface is defined for the
  119. * entire implementation, including the following forward definitions. */
  120. #include "civetweb.h"
  121. #endif
  122. #if !defined(DEBUG_TRACE)
  123. #if defined(DEBUG)
  124. static void DEBUG_TRACE_FUNC(const char *func,
  125. unsigned line,
  126. PRINTF_FORMAT_STRING(const char *fmt),
  127. ...) PRINTF_ARGS(3, 4);
  128. #define DEBUG_TRACE(fmt, ...) \
  129. DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__)
  130. #define NEED_DEBUG_TRACE_FUNC
  131. #else
  132. #define DEBUG_TRACE(fmt, ...) \
  133. do { \
  134. } while (0)
  135. #endif /* DEBUG */
  136. #endif /* DEBUG_TRACE */
  137. #if !defined(DEBUG_ASSERT)
  138. #if defined(DEBUG)
  139. #define DEBUG_ASSERT(cond) \
  140. do { \
  141. if (!(cond)) { \
  142. DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \
  143. exit(2); /* Exit with error */ \
  144. } \
  145. } while (0)
  146. #else
  147. #define DEBUG_ASSERT(cond) \
  148. do { \
  149. } while (0)
  150. #endif /* DEBUG */
  151. #endif
  152. #ifndef IGNORE_UNUSED_RESULT
  153. #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1))
  154. #endif
  155. #if defined(__GNUC__) || defined(__MINGW32__)
  156. /* GCC unused function attribute seems fundamentally broken.
  157. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED
  158. * OR UNUSED" for individual functions failed.
  159. * Either the compiler creates an "unused-function" warning if a
  160. * function is not marked with __attribute__((unused)).
  161. * On the other hand, if the function is marked with this attribute,
  162. * but is used, the compiler raises a completely idiotic
  163. * "used-but-marked-unused" warning - and
  164. * #pragma GCC diagnostic ignored "-Wused-but-marked-unused"
  165. * raises error: unknown option after "#pragma GCC diagnostic".
  166. * Disable this warning completely, until the GCC guys sober up
  167. * again.
  168. */
  169. #pragma GCC diagnostic ignored "-Wunused-function"
  170. #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */
  171. #else
  172. #define FUNCTION_MAY_BE_UNUSED
  173. #endif
  174. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  175. #include <sys/types.h>
  176. #include <sys/stat.h>
  177. #include <errno.h>
  178. #include <signal.h>
  179. #include <fcntl.h>
  180. #endif /* !_WIN32_WCE */
  181. #ifdef __clang__
  182. /* When using -Weverything, clang does not accept it's own headers
  183. * in a release build configuration. Disable what is too much in
  184. * -Weverything. */
  185. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  186. #endif
  187. #if defined(__GNUC__) || defined(__MINGW32__)
  188. /* Who on earth came to the conclusion, using __DATE__ should rise
  189. * an "expansion of date or time macro is not reproducible"
  190. * warning. That's exactly what was intended by using this macro.
  191. * Just disable this nonsense warning. */
  192. /* And disabling them does not work either:
  193. * #pragma clang diagnostic ignored "-Wno-error=date-time"
  194. * #pragma clang diagnostic ignored "-Wdate-time"
  195. * So we just have to disable ALL warnings for some lines
  196. * of code.
  197. * This seems to be a known GCC bug, not resolved since 2012:
  198. * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431
  199. */
  200. #endif
  201. #ifdef __MACH__ /* Apple OSX section */
  202. #ifdef __clang__
  203. #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8))
  204. /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */
  205. #pragma clang diagnostic ignored "-Wno-reserved-id-macro"
  206. #pragma clang diagnostic ignored "-Wno-keyword-macro"
  207. #endif
  208. #endif
  209. #define CLOCK_MONOTONIC (1)
  210. #define CLOCK_REALTIME (2)
  211. #include <sys/errno.h>
  212. #include <sys/time.h>
  213. #include <mach/clock.h>
  214. #include <mach/mach.h>
  215. #include <mach/mach_time.h>
  216. /* clock_gettime is not implemented on OSX prior to 10.12 */
  217. static int
  218. _civet_clock_gettime(int clk_id, struct timespec *t)
  219. {
  220. memset(t, 0, sizeof(*t));
  221. if (clk_id == CLOCK_REALTIME) {
  222. struct timeval now;
  223. int rv = gettimeofday(&now, NULL);
  224. if (rv) {
  225. return rv;
  226. }
  227. t->tv_sec = now.tv_sec;
  228. t->tv_nsec = now.tv_usec * 1000;
  229. return 0;
  230. } else if (clk_id == CLOCK_MONOTONIC) {
  231. static uint64_t clock_start_time = 0;
  232. static mach_timebase_info_data_t timebase_ifo = {0, 0};
  233. uint64_t now = mach_absolute_time();
  234. if (clock_start_time == 0) {
  235. kern_return_t mach_status = mach_timebase_info(&timebase_ifo);
  236. DEBUG_ASSERT(mach_status == KERN_SUCCESS);
  237. /* appease "unused variable" warning for release builds */
  238. (void)mach_status;
  239. clock_start_time = now;
  240. }
  241. now = (uint64_t)((double)(now - clock_start_time)
  242. * (double)timebase_ifo.numer
  243. / (double)timebase_ifo.denom);
  244. t->tv_sec = now / 1000000000;
  245. t->tv_nsec = now % 1000000000;
  246. return 0;
  247. }
  248. return -1; /* EINVAL - Clock ID is unknown */
  249. }
  250. /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */
  251. #ifdef __CLOCK_AVAILABILITY
  252. /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be
  253. * declared but it may be NULL at runtime. So we need to check before using
  254. * it. */
  255. static int
  256. _civet_safe_clock_gettime(int clk_id, struct timespec *t)
  257. {
  258. if (clock_gettime) {
  259. return clock_gettime(clk_id, t);
  260. }
  261. return _civet_clock_gettime(clk_id, t);
  262. }
  263. #define clock_gettime _civet_safe_clock_gettime
  264. #else
  265. #define clock_gettime _civet_clock_gettime
  266. #endif
  267. #endif
  268. #include <time.h>
  269. #include <stdlib.h>
  270. #include <stdarg.h>
  271. #include <string.h>
  272. #include <ctype.h>
  273. #include <limits.h>
  274. #include <stddef.h>
  275. #include <stdio.h>
  276. #include <stdint.h>
  277. #ifndef INT64_MAX
  278. #define INT64_MAX (9223372036854775807)
  279. #endif
  280. #ifndef MAX_WORKER_THREADS
  281. #define MAX_WORKER_THREADS (1024 * 64)
  282. #endif
  283. #ifndef SOCKET_TIMEOUT_QUANTUM /* in ms */
  284. #define SOCKET_TIMEOUT_QUANTUM (2000)
  285. #endif
  286. #define SHUTDOWN_RD (0)
  287. #define SHUTDOWN_WR (1)
  288. #define SHUTDOWN_BOTH (2)
  289. mg_static_assert(MAX_WORKER_THREADS >= 1,
  290. "worker threads must be a positive number");
  291. mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8,
  292. "size_t data type size check");
  293. #if defined(_WIN32) \
  294. && !defined(__SYMBIAN32__) /* WINDOWS / UNIX include block */
  295. #include <windows.h>
  296. #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */
  297. #include <ws2tcpip.h>
  298. typedef const char *SOCK_OPT_TYPE;
  299. #if !defined(PATH_MAX)
  300. #define W_PATH_MAX (MAX_PATH)
  301. /* at most three UTF-8 chars per wchar_t */
  302. #define PATH_MAX (W_PATH_MAX * 3)
  303. #else
  304. #define W_PATH_MAX ((PATH_MAX + 2) / 3)
  305. #endif
  306. mg_static_assert(PATH_MAX >= 1, "path length must be a positive number");
  307. #ifndef _IN_PORT_T
  308. #ifndef in_port_t
  309. #define in_port_t u_short
  310. #endif
  311. #endif
  312. #ifndef _WIN32_WCE
  313. #include <process.h>
  314. #include <direct.h>
  315. #include <io.h>
  316. #else /* _WIN32_WCE */
  317. #define NO_CGI /* WinCE has no pipes */
  318. #define NO_POPEN /* WinCE has no popen */
  319. typedef long off_t;
  320. #define errno ((int)(GetLastError()))
  321. #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10))
  322. #endif /* _WIN32_WCE */
  323. #define MAKEUQUAD(lo, hi) \
  324. ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32))
  325. #define RATE_DIFF (10000000) /* 100 nsecs */
  326. #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de))
  327. #define SYS2UNIX_TIME(lo, hi) \
  328. ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF))
  329. /* Visual Studio 6 does not know __func__ or __FUNCTION__
  330. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  331. * Also use _strtoui64 on modern M$ compilers */
  332. #if defined(_MSC_VER)
  333. #if (_MSC_VER < 1300)
  334. #define STRX(x) #x
  335. #define STR(x) STRX(x)
  336. #define __func__ __FILE__ ":" STR(__LINE__)
  337. #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x))
  338. #define strtoll(x, y, z) (_atoi64(x))
  339. #else
  340. #define __func__ __FUNCTION__
  341. #define strtoull(x, y, z) (_strtoui64(x, y, z))
  342. #define strtoll(x, y, z) (_strtoi64(x, y, z))
  343. #endif
  344. #endif /* _MSC_VER */
  345. #define ERRNO ((int)(GetLastError()))
  346. #define NO_SOCKLEN_T
  347. #if defined(_WIN64) || defined(__MINGW64__)
  348. #define SSL_LIB "ssleay64.dll"
  349. #define CRYPTO_LIB "libeay64.dll"
  350. #else
  351. #define SSL_LIB "ssleay32.dll"
  352. #define CRYPTO_LIB "libeay32.dll"
  353. #endif
  354. #define O_NONBLOCK (0)
  355. #ifndef W_OK
  356. #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */
  357. #endif
  358. #if !defined(EWOULDBLOCK)
  359. #define EWOULDBLOCK WSAEWOULDBLOCK
  360. #endif /* !EWOULDBLOCK */
  361. #define _POSIX_
  362. #define INT64_FMT "I64d"
  363. #define UINT64_FMT "I64u"
  364. #define WINCDECL __cdecl
  365. #define vsnprintf_impl _vsnprintf
  366. #define access _access
  367. #define mg_sleep(x) (Sleep(x))
  368. #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY)
  369. #ifndef popen
  370. #define popen(x, y) (_popen(x, y))
  371. #endif
  372. #ifndef pclose
  373. #define pclose(x) (_pclose(x))
  374. #endif
  375. #define close(x) (_close(x))
  376. #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y)))
  377. #define RTLD_LAZY (0)
  378. #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0)
  379. #define fdopen(x, y) (_fdopen((x), (y)))
  380. #define write(x, y, z) (_write((x), (y), (unsigned)z))
  381. #define read(x, y, z) (_read((x), (y), (unsigned)z))
  382. #define flockfile(x) (EnterCriticalSection(&global_log_file_lock))
  383. #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock))
  384. #define sleep(x) (Sleep((x)*1000))
  385. #define rmdir(x) (_rmdir(x))
  386. #define timegm(x) (_mkgmtime(x))
  387. #if !defined(fileno)
  388. #define fileno(x) (_fileno(x))
  389. #endif /* !fileno MINGW #defines fileno */
  390. typedef HANDLE pthread_mutex_t;
  391. typedef DWORD pthread_key_t;
  392. typedef HANDLE pthread_t;
  393. typedef struct {
  394. CRITICAL_SECTION threadIdSec;
  395. struct mg_workerTLS *waiting_thread; /* The chain of threads */
  396. } pthread_cond_t;
  397. #ifndef __clockid_t_defined
  398. typedef DWORD clockid_t;
  399. #endif
  400. #ifndef CLOCK_MONOTONIC
  401. #define CLOCK_MONOTONIC (1)
  402. #endif
  403. #ifndef CLOCK_REALTIME
  404. #define CLOCK_REALTIME (2)
  405. #endif
  406. #ifndef CLOCK_THREAD
  407. #define CLOCK_THREAD (3)
  408. #endif
  409. #ifndef CLOCK_PROCESS
  410. #define CLOCK_PROCESS (4)
  411. #endif
  412. #if defined(_MSC_VER) && (_MSC_VER >= 1900)
  413. #define _TIMESPEC_DEFINED
  414. #endif
  415. #ifndef _TIMESPEC_DEFINED
  416. struct timespec {
  417. time_t tv_sec; /* seconds */
  418. long tv_nsec; /* nanoseconds */
  419. };
  420. #endif
  421. #if !defined(WIN_PTHREADS_TIME_H)
  422. #define MUST_IMPLEMENT_CLOCK_GETTIME
  423. #endif
  424. #ifdef MUST_IMPLEMENT_CLOCK_GETTIME
  425. #define clock_gettime mg_clock_gettime
  426. static int
  427. clock_gettime(clockid_t clk_id, struct timespec *tp)
  428. {
  429. FILETIME ft;
  430. ULARGE_INTEGER li, li2;
  431. BOOL ok = FALSE;
  432. double d;
  433. static double perfcnt_per_sec = 0.0;
  434. if (tp) {
  435. memset(tp, 0, sizeof(*tp));
  436. if (clk_id == CLOCK_REALTIME) {
  437. /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */
  438. GetSystemTimeAsFileTime(&ft);
  439. li.LowPart = ft.dwLowDateTime;
  440. li.HighPart = ft.dwHighDateTime;
  441. li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */
  442. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  443. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  444. ok = TRUE;
  445. /* END: CLOCK_REALTIME */
  446. } else if (clk_id == CLOCK_MONOTONIC) {
  447. /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */
  448. if (perfcnt_per_sec == 0.0) {
  449. QueryPerformanceFrequency((LARGE_INTEGER *)&li);
  450. perfcnt_per_sec = 1.0 / li.QuadPart;
  451. }
  452. if (perfcnt_per_sec != 0.0) {
  453. QueryPerformanceCounter((LARGE_INTEGER *)&li);
  454. d = li.QuadPart * perfcnt_per_sec;
  455. tp->tv_sec = (time_t)d;
  456. d -= tp->tv_sec;
  457. tp->tv_nsec = (long)(d * 1.0E9);
  458. ok = TRUE;
  459. }
  460. /* END: CLOCK_MONOTONIC */
  461. } else if (clk_id == CLOCK_THREAD) {
  462. /* BEGIN: CLOCK_THREAD = CPU usage of thread */
  463. FILETIME t_create, t_exit, t_kernel, t_user;
  464. if (GetThreadTimes(GetCurrentThread(),
  465. &t_create,
  466. &t_exit,
  467. &t_kernel,
  468. &t_user)) {
  469. li.LowPart = t_user.dwLowDateTime;
  470. li.HighPart = t_user.dwHighDateTime;
  471. li2.LowPart = t_kernel.dwLowDateTime;
  472. li2.HighPart = t_kernel.dwHighDateTime;
  473. li.QuadPart += li2.QuadPart;
  474. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  475. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  476. ok = TRUE;
  477. }
  478. /* END: CLOCK_THREAD */
  479. } else if (clk_id == CLOCK_PROCESS) {
  480. /* BEGIN: CLOCK_PROCESS = CPU usage of process */
  481. FILETIME t_create, t_exit, t_kernel, t_user;
  482. if (GetProcessTimes(GetCurrentProcess(),
  483. &t_create,
  484. &t_exit,
  485. &t_kernel,
  486. &t_user)) {
  487. li.LowPart = t_user.dwLowDateTime;
  488. li.HighPart = t_user.dwHighDateTime;
  489. li2.LowPart = t_kernel.dwLowDateTime;
  490. li2.HighPart = t_kernel.dwHighDateTime;
  491. li.QuadPart += li2.QuadPart;
  492. tp->tv_sec = (time_t)(li.QuadPart / 10000000);
  493. tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100;
  494. ok = TRUE;
  495. }
  496. /* END: CLOCK_PROCESS */
  497. } else {
  498. /* BEGIN: unknown clock */
  499. /* ok = FALSE; already set by init */
  500. /* END: unknown clock */
  501. }
  502. }
  503. return ok ? 0 : -1;
  504. }
  505. #endif
  506. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  507. static int pthread_mutex_lock(pthread_mutex_t *);
  508. static int pthread_mutex_unlock(pthread_mutex_t *);
  509. static void path_to_unicode(const struct mg_connection *conn,
  510. const char *path,
  511. wchar_t *wbuf,
  512. size_t wbuf_len);
  513. /* All file operations need to be rewritten to solve #246. */
  514. #include "file_ops.inl"
  515. struct mg_file;
  516. static const char *
  517. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p);
  518. /* POSIX dirent interface */
  519. struct dirent {
  520. char d_name[PATH_MAX];
  521. };
  522. typedef struct DIR {
  523. HANDLE handle;
  524. WIN32_FIND_DATAW info;
  525. struct dirent result;
  526. } DIR;
  527. #if defined(_WIN32) && !defined(POLLIN)
  528. #ifndef HAVE_POLL
  529. struct pollfd {
  530. SOCKET fd;
  531. short events;
  532. short revents;
  533. };
  534. #define POLLIN (0x0300)
  535. #endif
  536. #endif
  537. /* Mark required libraries */
  538. #if defined(_MSC_VER)
  539. #pragma comment(lib, "Ws2_32.lib")
  540. #endif
  541. #else /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  542. WINDOWS / UNIX include block */
  543. #include <sys/wait.h>
  544. #include <sys/socket.h>
  545. #include <sys/poll.h>
  546. #include <netinet/in.h>
  547. #include <arpa/inet.h>
  548. #include <sys/time.h>
  549. #include <sys/utsname.h>
  550. #include <stdint.h>
  551. #include <inttypes.h>
  552. #include <netdb.h>
  553. #include <netinet/tcp.h>
  554. typedef const void *SOCK_OPT_TYPE;
  555. #if defined(ANDROID)
  556. typedef unsigned short int in_port_t;
  557. #endif
  558. #include <pwd.h>
  559. #include <unistd.h>
  560. #include <grp.h>
  561. #include <dirent.h>
  562. #define vsnprintf_impl vsnprintf
  563. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  564. #include <dlfcn.h>
  565. #endif
  566. #include <pthread.h>
  567. #if defined(__MACH__)
  568. #define SSL_LIB "libssl.dylib"
  569. #define CRYPTO_LIB "libcrypto.dylib"
  570. #else
  571. #if !defined(SSL_LIB)
  572. #define SSL_LIB "libssl.so"
  573. #endif
  574. #if !defined(CRYPTO_LIB)
  575. #define CRYPTO_LIB "libcrypto.so"
  576. #endif
  577. #endif
  578. #ifndef O_BINARY
  579. #define O_BINARY (0)
  580. #endif /* O_BINARY */
  581. #define closesocket(a) (close(a))
  582. #define mg_mkdir(conn, path, mode) (mkdir(path, mode))
  583. #define mg_remove(conn, x) (remove(x))
  584. #define mg_sleep(x) (usleep((x)*1000))
  585. #define mg_opendir(conn, x) (opendir(x))
  586. #define mg_closedir(x) (closedir(x))
  587. #define mg_readdir(x) (readdir(x))
  588. #define ERRNO (errno)
  589. #define INVALID_SOCKET (-1)
  590. #define INT64_FMT PRId64
  591. #define UINT64_FMT PRIu64
  592. typedef int SOCKET;
  593. #define WINCDECL
  594. #if defined(__hpux)
  595. /* HPUX 11 does not have monotonic, fall back to realtime */
  596. #ifndef CLOCK_MONOTONIC
  597. #define CLOCK_MONOTONIC CLOCK_REALTIME
  598. #endif
  599. /* HPUX defines socklen_t incorrectly as size_t which is 64bit on
  600. * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED
  601. * the prototypes use int* rather than socklen_t* which matches the
  602. * actual library expectation. When called with the wrong size arg
  603. * accept() returns a zero client inet addr and check_acl() always
  604. * fails. Since socklen_t is widely used below, just force replace
  605. * their typedef with int. - DTL
  606. */
  607. #define socklen_t int
  608. #endif /* hpux */
  609. #endif /* defined(_WIN32) && !defined(__SYMBIAN32__) - \
  610. WINDOWS / UNIX include block */
  611. /* va_copy should always be a macro, C99 and C++11 - DTL */
  612. #ifndef va_copy
  613. #define va_copy(x, y) ((x) = (y))
  614. #endif
  615. #ifdef _WIN32
  616. /* Create substitutes for POSIX functions in Win32. */
  617. #if defined(__MINGW32__)
  618. /* Show no warning in case system functions are not used. */
  619. #pragma GCC diagnostic push
  620. #pragma GCC diagnostic ignored "-Wunused-function"
  621. #endif
  622. static CRITICAL_SECTION global_log_file_lock;
  623. FUNCTION_MAY_BE_UNUSED
  624. static DWORD
  625. pthread_self(void)
  626. {
  627. return GetCurrentThreadId();
  628. }
  629. FUNCTION_MAY_BE_UNUSED
  630. static int
  631. pthread_key_create(
  632. pthread_key_t *key,
  633. void (*_ignored)(void *) /* destructor not supported for Windows */
  634. )
  635. {
  636. (void)_ignored;
  637. if ((key != 0)) {
  638. *key = TlsAlloc();
  639. return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1;
  640. }
  641. return -2;
  642. }
  643. FUNCTION_MAY_BE_UNUSED
  644. static int
  645. pthread_key_delete(pthread_key_t key)
  646. {
  647. return TlsFree(key) ? 0 : 1;
  648. }
  649. FUNCTION_MAY_BE_UNUSED
  650. static int
  651. pthread_setspecific(pthread_key_t key, void *value)
  652. {
  653. return TlsSetValue(key, value) ? 0 : 1;
  654. }
  655. FUNCTION_MAY_BE_UNUSED
  656. static void *
  657. pthread_getspecific(pthread_key_t key)
  658. {
  659. return TlsGetValue(key);
  660. }
  661. #if defined(__MINGW32__)
  662. /* Enable unused function warning again */
  663. #pragma GCC diagnostic pop
  664. #endif
  665. static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL;
  666. #else
  667. static pthread_mutexattr_t pthread_mutex_attr;
  668. #endif /* _WIN32 */
  669. #define PASSWORDS_FILE_NAME ".htpasswd"
  670. #define CGI_ENVIRONMENT_SIZE (4096)
  671. #define MAX_CGI_ENVIR_VARS (256)
  672. #define MG_BUF_LEN (8192)
  673. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  674. #if defined(_WIN32_WCE)
  675. /* Create substitutes for POSIX functions in Win32. */
  676. #if defined(__MINGW32__)
  677. /* Show no warning in case system functions are not used. */
  678. #pragma GCC diagnostic push
  679. #pragma GCC diagnostic ignored "-Wunused-function"
  680. #endif
  681. FUNCTION_MAY_BE_UNUSED
  682. static time_t
  683. time(time_t *ptime)
  684. {
  685. time_t t;
  686. SYSTEMTIME st;
  687. FILETIME ft;
  688. GetSystemTime(&st);
  689. SystemTimeToFileTime(&st, &ft);
  690. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  691. if (ptime != NULL) {
  692. *ptime = t;
  693. }
  694. return t;
  695. }
  696. FUNCTION_MAY_BE_UNUSED
  697. static struct tm *
  698. localtime_s(const time_t *ptime, struct tm *ptm)
  699. {
  700. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  701. FILETIME ft, lft;
  702. SYSTEMTIME st;
  703. TIME_ZONE_INFORMATION tzinfo;
  704. if (ptm == NULL) {
  705. return NULL;
  706. }
  707. *(int64_t *)&ft = t;
  708. FileTimeToLocalFileTime(&ft, &lft);
  709. FileTimeToSystemTime(&lft, &st);
  710. ptm->tm_year = st.wYear - 1900;
  711. ptm->tm_mon = st.wMonth - 1;
  712. ptm->tm_wday = st.wDayOfWeek;
  713. ptm->tm_mday = st.wDay;
  714. ptm->tm_hour = st.wHour;
  715. ptm->tm_min = st.wMinute;
  716. ptm->tm_sec = st.wSecond;
  717. ptm->tm_yday = 0; /* hope nobody uses this */
  718. ptm->tm_isdst =
  719. (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0;
  720. return ptm;
  721. }
  722. FUNCTION_MAY_BE_UNUSED
  723. static struct tm *
  724. gmtime_s(const time_t *ptime, struct tm *ptm)
  725. {
  726. /* FIXME(lsm): fix this. */
  727. return localtime_s(ptime, ptm);
  728. }
  729. static int mg_atomic_inc(volatile int *addr);
  730. static struct tm tm_array[MAX_WORKER_THREADS];
  731. static int tm_index = 0;
  732. FUNCTION_MAY_BE_UNUSED
  733. static struct tm *
  734. localtime(const time_t *ptime)
  735. {
  736. int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0]));
  737. return localtime_s(ptime, tm_array + i);
  738. }
  739. FUNCTION_MAY_BE_UNUSED
  740. static struct tm *
  741. gmtime(const time_t *ptime)
  742. {
  743. int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array);
  744. return gmtime_s(ptime, tm_array + i);
  745. }
  746. FUNCTION_MAY_BE_UNUSED
  747. static size_t
  748. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  749. {
  750. /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime()
  751. * for WinCE"); */
  752. return 0;
  753. }
  754. #define _beginthreadex(psec, stack, func, prm, flags, ptid) \
  755. (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid)
  756. #define remove(f) mg_remove(NULL, f)
  757. FUNCTION_MAY_BE_UNUSED
  758. static int
  759. rename(const char *a, const char *b)
  760. {
  761. wchar_t wa[W_PATH_MAX];
  762. wchar_t wb[W_PATH_MAX];
  763. path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa));
  764. path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb));
  765. return MoveFileW(wa, wb) ? 0 : -1;
  766. }
  767. struct stat {
  768. int64_t st_size;
  769. time_t st_mtime;
  770. };
  771. FUNCTION_MAY_BE_UNUSED
  772. static int
  773. stat(const char *name, struct stat *st)
  774. {
  775. wchar_t wbuf[W_PATH_MAX];
  776. WIN32_FILE_ATTRIBUTE_DATA attr;
  777. time_t creation_time, write_time;
  778. path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf));
  779. memset(&attr, 0, sizeof(attr));
  780. GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr);
  781. st->st_size =
  782. (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow;
  783. write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime,
  784. attr.ftLastWriteTime.dwHighDateTime);
  785. creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime,
  786. attr.ftCreationTime.dwHighDateTime);
  787. if (creation_time > write_time) {
  788. st->st_mtime = creation_time;
  789. } else {
  790. st->st_mtime = write_time;
  791. }
  792. return 0;
  793. }
  794. #define access(x, a) 1 /* not required anyway */
  795. /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */
  796. /* Values from errno.h in Windows SDK (Visual Studio). */
  797. #define EEXIST 17
  798. #define EACCES 13
  799. #define ENOENT 2
  800. #if defined(__MINGW32__)
  801. /* Enable unused function warning again */
  802. #pragma GCC diagnostic pop
  803. #endif
  804. #endif /* defined(_WIN32_WCE) */
  805. #if defined(__GNUC__) || defined(__MINGW32__)
  806. /* Show no warning in case system functions are not used. */
  807. #define GCC_VERSION \
  808. (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
  809. #if GCC_VERSION >= 40500
  810. #pragma GCC diagnostic push
  811. #pragma GCC diagnostic ignored "-Wunused-function"
  812. #endif /* GCC_VERSION >= 40500 */
  813. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  814. #if defined(__clang__)
  815. /* Show no warning in case system functions are not used. */
  816. #pragma clang diagnostic push
  817. #pragma clang diagnostic ignored "-Wunused-function"
  818. #endif
  819. static pthread_mutex_t global_lock_mutex;
  820. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  821. /* Forward declaration for Windows */
  822. FUNCTION_MAY_BE_UNUSED
  823. static int pthread_mutex_lock(pthread_mutex_t *mutex);
  824. FUNCTION_MAY_BE_UNUSED
  825. static int pthread_mutex_unlock(pthread_mutex_t *mutex);
  826. #endif
  827. FUNCTION_MAY_BE_UNUSED
  828. static void
  829. mg_global_lock(void)
  830. {
  831. (void)pthread_mutex_lock(&global_lock_mutex);
  832. }
  833. FUNCTION_MAY_BE_UNUSED
  834. static void
  835. mg_global_unlock(void)
  836. {
  837. (void)pthread_mutex_unlock(&global_lock_mutex);
  838. }
  839. FUNCTION_MAY_BE_UNUSED
  840. static int
  841. mg_atomic_inc(volatile int *addr)
  842. {
  843. int ret;
  844. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  845. /* Depending on the SDK, this function uses either
  846. * (volatile unsigned int *) or (volatile LONG *),
  847. * so whatever you use, the other SDK is likely to raise a warning. */
  848. ret = InterlockedIncrement((volatile long *)addr);
  849. #elif defined(__GNUC__) \
  850. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  851. && !defined(NO_ATOMICS)
  852. ret = __sync_add_and_fetch(addr, 1);
  853. #else
  854. mg_global_lock();
  855. ret = (++(*addr));
  856. mg_global_unlock();
  857. #endif
  858. return ret;
  859. }
  860. FUNCTION_MAY_BE_UNUSED
  861. static int
  862. mg_atomic_dec(volatile int *addr)
  863. {
  864. int ret;
  865. #if defined(_WIN32) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  866. /* Depending on the SDK, this function uses either
  867. * (volatile unsigned int *) or (volatile LONG *),
  868. * so whatever you use, the other SDK is likely to raise a warning. */
  869. ret = InterlockedDecrement((volatile long *)addr);
  870. #elif defined(__GNUC__) \
  871. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  872. && !defined(NO_ATOMICS)
  873. ret = __sync_sub_and_fetch(addr, 1);
  874. #else
  875. mg_global_lock();
  876. ret = (--(*addr));
  877. mg_global_unlock();
  878. #endif
  879. return ret;
  880. }
  881. #if defined(USE_SERVER_STATS)
  882. static int64_t
  883. mg_atomic_add(volatile int64_t *addr, int64_t value)
  884. {
  885. int64_t ret;
  886. #if defined(_WIN64) && !defined(__SYMBIAN32__) && !defined(NO_ATOMICS)
  887. ret = InterlockedAdd64(addr, value);
  888. #elif defined(__GNUC__) \
  889. && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \
  890. && !defined(NO_ATOMICS)
  891. ret = __sync_add_and_fetch(addr, value);
  892. #else
  893. mg_global_lock();
  894. *addr += value;
  895. ret = (*addr);
  896. mg_global_unlock();
  897. #endif
  898. return ret;
  899. }
  900. #endif
  901. #if defined(__GNUC__)
  902. /* Show no warning in case system functions are not used. */
  903. #if GCC_VERSION >= 40500
  904. #pragma GCC diagnostic pop
  905. #endif /* GCC_VERSION >= 40500 */
  906. #endif /* defined(__GNUC__) */
  907. #if defined(__clang__)
  908. /* Show no warning in case system functions are not used. */
  909. #pragma clang diagnostic pop
  910. #endif
  911. #if defined(USE_SERVER_STATS)
  912. struct mg_memory_stat {
  913. volatile int64_t totalMemUsed;
  914. volatile int64_t maxMemUsed;
  915. volatile int blockCount;
  916. };
  917. static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx);
  918. static void *
  919. mg_malloc_ex(size_t size,
  920. struct mg_context *ctx,
  921. const char *file,
  922. unsigned line)
  923. {
  924. void *data = malloc(size + 2 * sizeof(uintptr_t));
  925. void *memory = 0;
  926. struct mg_memory_stat *mstat = get_memory_stat(ctx);
  927. #if defined(MEMORY_DEBUGGING)
  928. char mallocStr[256];
  929. #else
  930. (void)file;
  931. (void)line;
  932. #endif
  933. if (data) {
  934. int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size);
  935. if (mmem > mstat->maxMemUsed) {
  936. /* could use atomic compare exchange, but this
  937. * seems overkill for statistics data */
  938. mstat->maxMemUsed = mmem;
  939. }
  940. mg_atomic_inc(&mstat->blockCount);
  941. ((uintptr_t *)data)[0] = size;
  942. ((uintptr_t *)data)[1] = (uintptr_t)mstat;
  943. memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  944. }
  945. #if defined(MEMORY_DEBUGGING)
  946. sprintf(mallocStr,
  947. "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n",
  948. memory,
  949. (unsigned long)size,
  950. (unsigned long)mstat->totalMemUsed,
  951. (unsigned long)mstat->blockCount,
  952. file,
  953. line);
  954. #if defined(_WIN32)
  955. OutputDebugStringA(mallocStr);
  956. #else
  957. DEBUG_TRACE("%s", mallocStr);
  958. #endif
  959. #endif
  960. return memory;
  961. }
  962. static void *
  963. mg_calloc_ex(size_t count,
  964. size_t size,
  965. struct mg_context *ctx,
  966. const char *file,
  967. unsigned line)
  968. {
  969. void *data = mg_malloc_ex(size * count, ctx, file, line);
  970. if (data) {
  971. memset(data, 0, size * count);
  972. }
  973. return data;
  974. }
  975. static void
  976. mg_free_ex(void *memory, const char *file, unsigned line)
  977. {
  978. void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  979. #if defined(MEMORY_DEBUGGING)
  980. char mallocStr[256];
  981. #else
  982. (void)file;
  983. (void)line;
  984. #endif
  985. if (memory) {
  986. uintptr_t size = ((uintptr_t *)data)[0];
  987. struct mg_memory_stat *mstat =
  988. (struct mg_memory_stat *)(((uintptr_t *)data)[1]);
  989. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size);
  990. mg_atomic_dec(&mstat->blockCount);
  991. #if defined(MEMORY_DEBUGGING)
  992. sprintf(mallocStr,
  993. "MEM: %p %5lu free %7lu %4lu --- %s:%u\n",
  994. memory,
  995. (unsigned long)size,
  996. (unsigned long)mstat->totalMemUsed,
  997. (unsigned long)mstat->blockCount,
  998. file,
  999. line);
  1000. #if defined(_WIN32)
  1001. OutputDebugStringA(mallocStr);
  1002. #else
  1003. DEBUG_TRACE("%s", mallocStr);
  1004. #endif
  1005. #endif
  1006. free(data);
  1007. }
  1008. }
  1009. static void *
  1010. mg_realloc_ex(void *memory,
  1011. size_t newsize,
  1012. struct mg_context *ctx,
  1013. const char *file,
  1014. unsigned line)
  1015. {
  1016. void *data;
  1017. void *_realloc;
  1018. uintptr_t oldsize;
  1019. #if defined(MEMORY_DEBUGGING)
  1020. char mallocStr[256];
  1021. #else
  1022. (void)file;
  1023. (void)line;
  1024. #endif
  1025. if (newsize) {
  1026. if (memory) {
  1027. /* Reallocate existing block */
  1028. struct mg_memory_stat *mstat;
  1029. data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t));
  1030. oldsize = ((uintptr_t *)data)[0];
  1031. mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1];
  1032. _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t));
  1033. if (_realloc) {
  1034. data = _realloc;
  1035. mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize);
  1036. #if defined(MEMORY_DEBUGGING)
  1037. sprintf(mallocStr,
  1038. "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n",
  1039. memory,
  1040. (unsigned long)oldsize,
  1041. (unsigned long)mstat->totalMemUsed,
  1042. (unsigned long)mstat->blockCount,
  1043. file,
  1044. line);
  1045. #if defined(_WIN32)
  1046. OutputDebugStringA(mallocStr);
  1047. #else
  1048. DEBUG_TRACE("%s", mallocStr);
  1049. #endif
  1050. #endif
  1051. mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize);
  1052. #if defined(MEMORY_DEBUGGING)
  1053. sprintf(mallocStr,
  1054. "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n",
  1055. memory,
  1056. (unsigned long)newsize,
  1057. (unsigned long)mstat->totalMemUsed,
  1058. (unsigned long)mstat->blockCount,
  1059. file,
  1060. line);
  1061. #if defined(_WIN32)
  1062. OutputDebugStringA(mallocStr);
  1063. #else
  1064. DEBUG_TRACE("%s", mallocStr);
  1065. #endif
  1066. #endif
  1067. *(uintptr_t *)data = newsize;
  1068. data = (void *)(((char *)data) + 2 * sizeof(uintptr_t));
  1069. } else {
  1070. #if defined(MEMORY_DEBUGGING)
  1071. #if defined(_WIN32)
  1072. OutputDebugStringA("MEM: realloc failed\n");
  1073. #else
  1074. DEBUG_TRACE("%s", "MEM: realloc failed\n");
  1075. #endif
  1076. #endif
  1077. return _realloc;
  1078. }
  1079. } else {
  1080. /* Allocate new block */
  1081. data = mg_malloc_ex(newsize, ctx, file, line);
  1082. }
  1083. } else {
  1084. /* Free existing block */
  1085. data = 0;
  1086. mg_free_ex(memory, file, line);
  1087. }
  1088. return data;
  1089. }
  1090. #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__)
  1091. #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__)
  1092. #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__)
  1093. #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__)
  1094. #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__)
  1095. #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__)
  1096. #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__)
  1097. #else /* USE_SERVER_STATS */
  1098. static __inline void *
  1099. mg_malloc(size_t a)
  1100. {
  1101. return malloc(a);
  1102. }
  1103. static __inline void *
  1104. mg_calloc(size_t a, size_t b)
  1105. {
  1106. return calloc(a, b);
  1107. }
  1108. static __inline void *
  1109. mg_realloc(void *a, size_t b)
  1110. {
  1111. return realloc(a, b);
  1112. }
  1113. static __inline void
  1114. mg_free(void *a)
  1115. {
  1116. free(a);
  1117. }
  1118. #define mg_malloc_ctx(a, c) mg_malloc(a)
  1119. #define mg_calloc_ctx(a, b, c) mg_calloc(a, b)
  1120. #define mg_realloc_ctx(a, b, c) mg_realloc(a, b)
  1121. #define mg_free_ctx(a, c) mg_free(a)
  1122. #endif /* USE_SERVER_STATS */
  1123. static void mg_vsnprintf(const struct mg_connection *conn,
  1124. int *truncated,
  1125. char *buf,
  1126. size_t buflen,
  1127. const char *fmt,
  1128. va_list ap);
  1129. static void mg_snprintf(const struct mg_connection *conn,
  1130. int *truncated,
  1131. char *buf,
  1132. size_t buflen,
  1133. PRINTF_FORMAT_STRING(const char *fmt),
  1134. ...) PRINTF_ARGS(5, 6);
  1135. /* This following lines are just meant as a reminder to use the mg-functions
  1136. * for memory management */
  1137. #ifdef malloc
  1138. #undef malloc
  1139. #endif
  1140. #ifdef calloc
  1141. #undef calloc
  1142. #endif
  1143. #ifdef realloc
  1144. #undef realloc
  1145. #endif
  1146. #ifdef free
  1147. #undef free
  1148. #endif
  1149. #ifdef snprintf
  1150. #undef snprintf
  1151. #endif
  1152. #ifdef vsnprintf
  1153. #undef vsnprintf
  1154. #endif
  1155. #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc
  1156. #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc
  1157. #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc
  1158. #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free
  1159. #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf
  1160. #ifdef _WIN32 /* vsnprintf must not be used in any system, * \ \ \ \
  1161. * but this define only works well for Windows. */
  1162. #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf
  1163. #endif
  1164. /* mg_init_library counter */
  1165. static int mg_init_library_called = 0;
  1166. #if !defined(NO_SSL)
  1167. static int mg_ssl_initialized = 0;
  1168. #endif
  1169. static pthread_key_t sTlsKey; /* Thread local storage index */
  1170. static int thread_idx_max = 0;
  1171. struct mg_workerTLS {
  1172. int is_master;
  1173. unsigned long thread_idx;
  1174. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1175. HANDLE pthread_cond_helper_mutex;
  1176. struct mg_workerTLS *next_waiting_thread;
  1177. #endif
  1178. };
  1179. #if defined(__GNUC__) || defined(__MINGW32__)
  1180. /* Show no warning in case system functions are not used. */
  1181. #if GCC_VERSION >= 40500
  1182. #pragma GCC diagnostic push
  1183. #pragma GCC diagnostic ignored "-Wunused-function"
  1184. #endif /* GCC_VERSION >= 40500 */
  1185. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  1186. #if defined(__clang__)
  1187. /* Show no warning in case system functions are not used. */
  1188. #pragma clang diagnostic push
  1189. #pragma clang diagnostic ignored "-Wunused-function"
  1190. #endif
  1191. /* Get a unique thread ID as unsigned long, independent from the data type
  1192. * of thread IDs defined by the operating system API.
  1193. * If two calls to mg_current_thread_id return the same value, they calls
  1194. * are done from the same thread. If they return different values, they are
  1195. * done from different threads. (Provided this function is used in the same
  1196. * process context and threads are not repeatedly created and deleted, but
  1197. * CivetWeb does not do that).
  1198. * This function must match the signature required for SSL id callbacks:
  1199. * CRYPTO_set_id_callback
  1200. */
  1201. FUNCTION_MAY_BE_UNUSED
  1202. static unsigned long
  1203. mg_current_thread_id(void)
  1204. {
  1205. #ifdef _WIN32
  1206. return GetCurrentThreadId();
  1207. #else
  1208. #ifdef __clang__
  1209. #pragma clang diagnostic push
  1210. #pragma clang diagnostic ignored "-Wunreachable-code"
  1211. /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)"
  1212. * or not, so one of the two conditions will be unreachable by construction.
  1213. * Unfortunately the C standard does not define a way to check this at
  1214. * compile time, since the #if preprocessor conditions can not use the sizeof
  1215. * operator as an argument. */
  1216. #endif
  1217. if (sizeof(pthread_t) > sizeof(unsigned long)) {
  1218. /* This is the problematic case for CRYPTO_set_id_callback:
  1219. * The OS pthread_t can not be cast to unsigned long. */
  1220. struct mg_workerTLS *tls =
  1221. (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  1222. if (tls == NULL) {
  1223. /* SSL called from an unknown thread: Create some thread index.
  1224. */
  1225. tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS));
  1226. tls->is_master = -2; /* -2 means "3rd party thread" */
  1227. tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  1228. pthread_setspecific(sTlsKey, tls);
  1229. }
  1230. return tls->thread_idx;
  1231. } else {
  1232. /* pthread_t may be any data type, so a simple cast to unsigned long
  1233. * can rise a warning/error, depending on the platform.
  1234. * Here memcpy is used as an anything-to-anything cast. */
  1235. unsigned long ret = 0;
  1236. pthread_t t = pthread_self();
  1237. memcpy(&ret, &t, sizeof(pthread_t));
  1238. return ret;
  1239. }
  1240. #ifdef __clang__
  1241. #pragma clang diagnostic pop
  1242. #endif
  1243. #endif
  1244. }
  1245. FUNCTION_MAY_BE_UNUSED
  1246. static uint64_t
  1247. mg_get_current_time_ns(void)
  1248. {
  1249. struct timespec tsnow;
  1250. clock_gettime(CLOCK_REALTIME, &tsnow);
  1251. return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec;
  1252. }
  1253. #if defined(__GNUC__)
  1254. /* Show no warning in case system functions are not used. */
  1255. #if GCC_VERSION >= 40500
  1256. #pragma GCC diagnostic pop
  1257. #endif /* GCC_VERSION >= 40500 */
  1258. #endif /* defined(__GNUC__) */
  1259. #if defined(__clang__)
  1260. /* Show no warning in case system functions are not used. */
  1261. #pragma clang diagnostic pop
  1262. #endif
  1263. #if defined(NEED_DEBUG_TRACE_FUNC)
  1264. static void
  1265. DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...)
  1266. {
  1267. va_list args;
  1268. uint64_t nsnow;
  1269. static uint64_t nslast;
  1270. struct timespec tsnow;
  1271. /* Get some operating system independent thread id */
  1272. unsigned long thread_id = mg_current_thread_id();
  1273. clock_gettime(CLOCK_REALTIME, &tsnow);
  1274. nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000)
  1275. + ((uint64_t)tsnow.tv_nsec);
  1276. if (!nslast) {
  1277. nslast = nsnow;
  1278. }
  1279. flockfile(stdout);
  1280. printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ",
  1281. (unsigned long)tsnow.tv_sec,
  1282. (unsigned long)tsnow.tv_nsec,
  1283. nsnow - nslast,
  1284. thread_id,
  1285. func,
  1286. line);
  1287. va_start(args, fmt);
  1288. vprintf(fmt, args);
  1289. va_end(args);
  1290. putchar('\n');
  1291. fflush(stdout);
  1292. funlockfile(stdout);
  1293. nslast = nsnow;
  1294. }
  1295. #endif /* NEED_DEBUG_TRACE_FUNC */
  1296. #define MD5_STATIC static
  1297. #include "md5.inl"
  1298. /* Darwin prior to 7.0 and Win32 do not have socklen_t */
  1299. #ifdef NO_SOCKLEN_T
  1300. typedef int socklen_t;
  1301. #endif /* NO_SOCKLEN_T */
  1302. #define _DARWIN_UNLIMITED_SELECT
  1303. #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */
  1304. #if !defined(MSG_NOSIGNAL)
  1305. #define MSG_NOSIGNAL (0)
  1306. #endif
  1307. #if !defined(SOMAXCONN)
  1308. #define SOMAXCONN (100)
  1309. #endif
  1310. /* Size of the accepted socket queue */
  1311. #if !defined(MGSQLEN)
  1312. #define MGSQLEN (20)
  1313. #endif
  1314. #if defined(NO_SSL)
  1315. typedef struct SSL SSL; /* dummy for SSL argument to push/pull */
  1316. typedef struct SSL_CTX SSL_CTX;
  1317. #else
  1318. #if defined(NO_SSL_DL)
  1319. #include <openssl/ssl.h>
  1320. #include <openssl/err.h>
  1321. #include <openssl/crypto.h>
  1322. #include <openssl/x509.h>
  1323. #include <openssl/pem.h>
  1324. #include <openssl/engine.h>
  1325. #include <openssl/conf.h>
  1326. #include <openssl/dh.h>
  1327. #include <openssl/bn.h>
  1328. #include <openssl/opensslv.h>
  1329. #else
  1330. /* SSL loaded dynamically from DLL.
  1331. * I put the prototypes here to be independent from OpenSSL source
  1332. * installation. */
  1333. typedef struct ssl_st SSL;
  1334. typedef struct ssl_method_st SSL_METHOD;
  1335. typedef struct ssl_ctx_st SSL_CTX;
  1336. typedef struct x509_store_ctx_st X509_STORE_CTX;
  1337. typedef struct x509_name X509_NAME;
  1338. typedef struct asn1_integer ASN1_INTEGER;
  1339. typedef struct bignum BIGNUM;
  1340. typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
  1341. typedef struct evp_md EVP_MD;
  1342. typedef struct x509 X509;
  1343. #define SSL_CTRL_OPTIONS (32)
  1344. #define SSL_CTRL_CLEAR_OPTIONS (77)
  1345. #define SSL_CTRL_SET_ECDH_AUTO (94)
  1346. #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
  1347. #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
  1348. #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
  1349. #define SSL_VERIFY_NONE (0)
  1350. #define SSL_VERIFY_PEER (1)
  1351. #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2)
  1352. #define SSL_VERIFY_CLIENT_ONCE (4)
  1353. #define SSL_OP_ALL ((long)(0x80000BFFUL))
  1354. #define SSL_OP_NO_SSLv2 (0x01000000L)
  1355. #define SSL_OP_NO_SSLv3 (0x02000000L)
  1356. #define SSL_OP_NO_TLSv1 (0x04000000L)
  1357. #define SSL_OP_NO_TLSv1_2 (0x08000000L)
  1358. #define SSL_OP_NO_TLSv1_1 (0x10000000L)
  1359. #define SSL_OP_SINGLE_DH_USE (0x00100000L)
  1360. #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L)
  1361. #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L)
  1362. #define SSL_OP_NO_COMPRESSION (0x00020000L)
  1363. #define SSL_CB_HANDSHAKE_START (0x10)
  1364. #define SSL_CB_HANDSHAKE_DONE (0x20)
  1365. #define SSL_ERROR_NONE (0)
  1366. #define SSL_ERROR_SSL (1)
  1367. #define SSL_ERROR_WANT_READ (2)
  1368. #define SSL_ERROR_WANT_WRITE (3)
  1369. #define SSL_ERROR_WANT_X509_LOOKUP (4)
  1370. #define SSL_ERROR_SYSCALL (5) /* see errno */
  1371. #define SSL_ERROR_ZERO_RETURN (6)
  1372. #define SSL_ERROR_WANT_CONNECT (7)
  1373. #define SSL_ERROR_WANT_ACCEPT (8)
  1374. #define TLSEXT_TYPE_server_name (0)
  1375. #define TLSEXT_NAMETYPE_host_name (0)
  1376. #define SSL_TLSEXT_ERR_OK (0)
  1377. #define SSL_TLSEXT_ERR_ALERT_WARNING (1)
  1378. #define SSL_TLSEXT_ERR_ALERT_FATAL (2)
  1379. #define SSL_TLSEXT_ERR_NOACK (3)
  1380. struct ssl_func {
  1381. const char *name; /* SSL function name */
  1382. void (*ptr)(void); /* Function pointer */
  1383. };
  1384. #ifdef OPENSSL_API_1_1
  1385. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1386. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1387. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1388. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1389. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1390. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1391. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1392. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1393. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1394. #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1395. #define OPENSSL_init_ssl \
  1396. (*(int (*)(uint64_t opts, \
  1397. const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr)
  1398. #define SSL_CTX_use_PrivateKey_file \
  1399. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1400. #define SSL_CTX_use_certificate_file \
  1401. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1402. #define SSL_CTX_set_default_passwd_cb \
  1403. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1404. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1405. #define SSL_CTX_use_certificate_chain_file \
  1406. (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr)
  1407. #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr)
  1408. #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr)
  1409. #define SSL_CTX_set_verify \
  1410. (*(void (*)(SSL_CTX *, \
  1411. int, \
  1412. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr)
  1413. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr)
  1414. #define SSL_CTX_load_verify_locations \
  1415. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr)
  1416. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr)
  1417. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr)
  1418. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr)
  1419. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr)
  1420. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr)
  1421. #define SSL_CIPHER_get_name \
  1422. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr)
  1423. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr)
  1424. #define SSL_CTX_set_session_id_context \
  1425. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr)
  1426. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr)
  1427. #define SSL_CTX_set_cipher_list \
  1428. (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr)
  1429. #define SSL_CTX_set_options \
  1430. (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr)
  1431. #define SSL_CTX_set_info_callback \
  1432. (*(void (*)(SSL_CTX * ctx, \
  1433. void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1434. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1435. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1436. #define SSL_CTX_callback_ctrl \
  1437. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1438. #define SSL_get_servername \
  1439. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1440. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1441. #define SSL_CTX_clear_options(ctx, op) \
  1442. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1443. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1444. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1445. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1446. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1447. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1448. SSL_CTX_callback_ctrl(ctx, \
  1449. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1450. (void (*)(void))cb)
  1451. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1452. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1453. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1454. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1455. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1456. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1457. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr)
  1458. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr)
  1459. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr)
  1460. #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr)
  1461. #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr)
  1462. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr)
  1463. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr)
  1464. #define X509_NAME_oneline \
  1465. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr)
  1466. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr)
  1467. #define EVP_get_digestbyname \
  1468. (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr)
  1469. #define EVP_Digest \
  1470. (*(int (*)( \
  1471. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1472. crypto_sw[10].ptr)
  1473. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr)
  1474. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr)
  1475. #define ASN1_INTEGER_to_BN \
  1476. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr)
  1477. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr)
  1478. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr)
  1479. #define OPENSSL_free(a) CRYPTO_free(a)
  1480. /* init_ssl_ctx() function updates this array.
  1481. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1482. * of respective functions. The macros above (like SSL_connect()) are really
  1483. * just calling these functions indirectly via the pointer. */
  1484. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1485. {"SSL_accept", NULL},
  1486. {"SSL_connect", NULL},
  1487. {"SSL_read", NULL},
  1488. {"SSL_write", NULL},
  1489. {"SSL_get_error", NULL},
  1490. {"SSL_set_fd", NULL},
  1491. {"SSL_new", NULL},
  1492. {"SSL_CTX_new", NULL},
  1493. {"TLS_server_method", NULL},
  1494. {"OPENSSL_init_ssl", NULL},
  1495. {"SSL_CTX_use_PrivateKey_file", NULL},
  1496. {"SSL_CTX_use_certificate_file", NULL},
  1497. {"SSL_CTX_set_default_passwd_cb", NULL},
  1498. {"SSL_CTX_free", NULL},
  1499. {"SSL_CTX_use_certificate_chain_file", NULL},
  1500. {"TLS_client_method", NULL},
  1501. {"SSL_pending", NULL},
  1502. {"SSL_CTX_set_verify", NULL},
  1503. {"SSL_shutdown", NULL},
  1504. {"SSL_CTX_load_verify_locations", NULL},
  1505. {"SSL_CTX_set_default_verify_paths", NULL},
  1506. {"SSL_CTX_set_verify_depth", NULL},
  1507. {"SSL_get_peer_certificate", NULL},
  1508. {"SSL_get_version", NULL},
  1509. {"SSL_get_current_cipher", NULL},
  1510. {"SSL_CIPHER_get_name", NULL},
  1511. {"SSL_CTX_check_private_key", NULL},
  1512. {"SSL_CTX_set_session_id_context", NULL},
  1513. {"SSL_CTX_ctrl", NULL},
  1514. {"SSL_CTX_set_cipher_list", NULL},
  1515. {"SSL_CTX_set_options", NULL},
  1516. {"SSL_CTX_set_info_callback", NULL},
  1517. {"SSL_get_ex_data", NULL},
  1518. {"SSL_set_ex_data", NULL},
  1519. {"SSL_CTX_callback_ctrl", NULL},
  1520. {"SSL_get_servername", NULL},
  1521. {"SSL_set_SSL_CTX", NULL},
  1522. {NULL, NULL}};
  1523. /* Similar array as ssl_sw. These functions could be located in different
  1524. * lib. */
  1525. static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL},
  1526. {"ERR_error_string", NULL},
  1527. {"ERR_remove_state", NULL},
  1528. {"CONF_modules_unload", NULL},
  1529. {"X509_free", NULL},
  1530. {"X509_get_subject_name", NULL},
  1531. {"X509_get_issuer_name", NULL},
  1532. {"X509_NAME_oneline", NULL},
  1533. {"X509_get_serialNumber", NULL},
  1534. {"EVP_get_digestbyname", NULL},
  1535. {"EVP_Digest", NULL},
  1536. {"i2d_X509", NULL},
  1537. {"BN_bn2hex", NULL},
  1538. {"ASN1_INTEGER_to_BN", NULL},
  1539. {"BN_free", NULL},
  1540. {"CRYPTO_free", NULL},
  1541. {NULL, NULL}};
  1542. #else
  1543. #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr)
  1544. #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr)
  1545. #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr)
  1546. #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr)
  1547. #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr)
  1548. #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr)
  1549. #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr)
  1550. #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr)
  1551. #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr)
  1552. #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr)
  1553. #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr)
  1554. #define SSL_CTX_use_PrivateKey_file \
  1555. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr)
  1556. #define SSL_CTX_use_certificate_file \
  1557. (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr)
  1558. #define SSL_CTX_set_default_passwd_cb \
  1559. (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr)
  1560. #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr)
  1561. #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr)
  1562. #define SSL_CTX_use_certificate_chain_file \
  1563. (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr)
  1564. #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr)
  1565. #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr)
  1566. #define SSL_CTX_set_verify \
  1567. (*(void (*)(SSL_CTX *, \
  1568. int, \
  1569. int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr)
  1570. #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr)
  1571. #define SSL_CTX_load_verify_locations \
  1572. (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr)
  1573. #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr)
  1574. #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr)
  1575. #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr)
  1576. #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr)
  1577. #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr)
  1578. #define SSL_CIPHER_get_name \
  1579. (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr)
  1580. #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr)
  1581. #define SSL_CTX_set_session_id_context \
  1582. (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr)
  1583. #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr)
  1584. #define SSL_CTX_set_cipher_list \
  1585. (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr)
  1586. #define SSL_CTX_set_info_callback \
  1587. (*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr)
  1588. #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr)
  1589. #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr)
  1590. #define SSL_CTX_callback_ctrl \
  1591. (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr)
  1592. #define SSL_get_servername \
  1593. (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr)
  1594. #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr)
  1595. #define SSL_CTX_set_options(ctx, op) \
  1596. SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL)
  1597. #define SSL_CTX_clear_options(ctx, op) \
  1598. SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL)
  1599. #define SSL_CTX_set_ecdh_auto(ctx, onoff) \
  1600. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL)
  1601. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
  1602. #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
  1603. #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
  1604. SSL_CTX_callback_ctrl(ctx, \
  1605. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \
  1606. (void (*)(void))cb)
  1607. #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
  1608. SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg)
  1609. #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore)
  1610. #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter)
  1611. #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg))
  1612. #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0))
  1613. #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr)
  1614. #define CRYPTO_set_locking_callback \
  1615. (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr)
  1616. #define CRYPTO_set_id_callback \
  1617. (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr)
  1618. #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr)
  1619. #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr)
  1620. #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr)
  1621. #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr)
  1622. #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr)
  1623. #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr)
  1624. #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr)
  1625. #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr)
  1626. #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr)
  1627. #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr)
  1628. #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr)
  1629. #define X509_NAME_oneline \
  1630. (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr)
  1631. #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr)
  1632. #define i2c_ASN1_INTEGER \
  1633. (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr)
  1634. #define EVP_get_digestbyname \
  1635. (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr)
  1636. #define EVP_Digest \
  1637. (*(int (*)( \
  1638. const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \
  1639. crypto_sw[18].ptr)
  1640. #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr)
  1641. #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr)
  1642. #define ASN1_INTEGER_to_BN \
  1643. (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr)
  1644. #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr)
  1645. #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr)
  1646. #define OPENSSL_free(a) CRYPTO_free(a)
  1647. /* init_ssl_ctx() function updates this array.
  1648. * It loads SSL library dynamically and changes NULLs to the actual addresses
  1649. * of respective functions. The macros above (like SSL_connect()) are really
  1650. * just calling these functions indirectly via the pointer. */
  1651. static struct ssl_func ssl_sw[] = {{"SSL_free", NULL},
  1652. {"SSL_accept", NULL},
  1653. {"SSL_connect", NULL},
  1654. {"SSL_read", NULL},
  1655. {"SSL_write", NULL},
  1656. {"SSL_get_error", NULL},
  1657. {"SSL_set_fd", NULL},
  1658. {"SSL_new", NULL},
  1659. {"SSL_CTX_new", NULL},
  1660. {"SSLv23_server_method", NULL},
  1661. {"SSL_library_init", NULL},
  1662. {"SSL_CTX_use_PrivateKey_file", NULL},
  1663. {"SSL_CTX_use_certificate_file", NULL},
  1664. {"SSL_CTX_set_default_passwd_cb", NULL},
  1665. {"SSL_CTX_free", NULL},
  1666. {"SSL_load_error_strings", NULL},
  1667. {"SSL_CTX_use_certificate_chain_file", NULL},
  1668. {"SSLv23_client_method", NULL},
  1669. {"SSL_pending", NULL},
  1670. {"SSL_CTX_set_verify", NULL},
  1671. {"SSL_shutdown", NULL},
  1672. {"SSL_CTX_load_verify_locations", NULL},
  1673. {"SSL_CTX_set_default_verify_paths", NULL},
  1674. {"SSL_CTX_set_verify_depth", NULL},
  1675. {"SSL_get_peer_certificate", NULL},
  1676. {"SSL_get_version", NULL},
  1677. {"SSL_get_current_cipher", NULL},
  1678. {"SSL_CIPHER_get_name", NULL},
  1679. {"SSL_CTX_check_private_key", NULL},
  1680. {"SSL_CTX_set_session_id_context", NULL},
  1681. {"SSL_CTX_ctrl", NULL},
  1682. {"SSL_CTX_set_cipher_list", NULL},
  1683. {"SSL_CTX_set_info_callback", NULL},
  1684. {"SSL_get_ex_data", NULL},
  1685. {"SSL_set_ex_data", NULL},
  1686. {"SSL_CTX_callback_ctrl", NULL},
  1687. {"SSL_get_servername", NULL},
  1688. {"SSL_set_SSL_CTX", NULL},
  1689. {NULL, NULL}};
  1690. /* Similar array as ssl_sw. These functions could be located in different
  1691. * lib. */
  1692. static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL},
  1693. {"CRYPTO_set_locking_callback", NULL},
  1694. {"CRYPTO_set_id_callback", NULL},
  1695. {"ERR_get_error", NULL},
  1696. {"ERR_error_string", NULL},
  1697. {"ERR_remove_state", NULL},
  1698. {"ERR_free_strings", NULL},
  1699. {"ENGINE_cleanup", NULL},
  1700. {"CONF_modules_unload", NULL},
  1701. {"CRYPTO_cleanup_all_ex_data", NULL},
  1702. {"EVP_cleanup", NULL},
  1703. {"X509_free", NULL},
  1704. {"X509_get_subject_name", NULL},
  1705. {"X509_get_issuer_name", NULL},
  1706. {"X509_NAME_oneline", NULL},
  1707. {"X509_get_serialNumber", NULL},
  1708. {"i2c_ASN1_INTEGER", NULL},
  1709. {"EVP_get_digestbyname", NULL},
  1710. {"EVP_Digest", NULL},
  1711. {"i2d_X509", NULL},
  1712. {"BN_bn2hex", NULL},
  1713. {"ASN1_INTEGER_to_BN", NULL},
  1714. {"BN_free", NULL},
  1715. {"CRYPTO_free", NULL},
  1716. {NULL, NULL}};
  1717. #endif /* OPENSSL_API_1_1 */
  1718. #endif /* NO_SSL_DL */
  1719. #endif /* NO_SSL */
  1720. #if !defined(NO_CACHING)
  1721. static const char *month_names[] = {"Jan",
  1722. "Feb",
  1723. "Mar",
  1724. "Apr",
  1725. "May",
  1726. "Jun",
  1727. "Jul",
  1728. "Aug",
  1729. "Sep",
  1730. "Oct",
  1731. "Nov",
  1732. "Dec"};
  1733. #endif /* !NO_CACHING */
  1734. /* Unified socket address. For IPv6 support, add IPv6 address structure in
  1735. * the
  1736. * union u. */
  1737. union usa {
  1738. struct sockaddr sa;
  1739. struct sockaddr_in sin;
  1740. #if defined(USE_IPV6)
  1741. struct sockaddr_in6 sin6;
  1742. #endif
  1743. };
  1744. /* Describes a string (chunk of memory). */
  1745. struct vec {
  1746. const char *ptr;
  1747. size_t len;
  1748. };
  1749. struct mg_file_stat {
  1750. /* File properties filled by mg_stat: */
  1751. uint64_t size;
  1752. time_t last_modified;
  1753. int is_directory; /* Set to 1 if mg_stat is called for a directory */
  1754. int is_gzipped; /* Set to 1 if the content is gzipped, in which
  1755. * case we need a "Content-Eencoding: gzip" header */
  1756. int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */
  1757. };
  1758. struct mg_file_in_memory {
  1759. char *p;
  1760. uint32_t pos;
  1761. char mode;
  1762. };
  1763. struct mg_file_access {
  1764. /* File properties filled by mg_fopen: */
  1765. FILE *fp;
  1766. /* TODO (low): Replace "membuf" implementation by a "file in memory"
  1767. * support library. Use some struct mg_file_in_memory *mf; instead of
  1768. * membuf char pointer. */
  1769. const char *membuf;
  1770. };
  1771. struct mg_file {
  1772. struct mg_file_stat stat;
  1773. struct mg_file_access access;
  1774. };
  1775. #define STRUCT_FILE_INITIALIZER \
  1776. { \
  1777. { \
  1778. (uint64_t)0, (time_t)0, 0, 0, 0 \
  1779. } \
  1780. , \
  1781. { \
  1782. (FILE *) NULL, (const char *)NULL \
  1783. } \
  1784. }
  1785. /* Describes listening socket, or socket which was accept()-ed by the master
  1786. * thread and queued for future handling by the worker thread. */
  1787. struct socket {
  1788. SOCKET sock; /* Listening socket */
  1789. union usa lsa; /* Local socket address */
  1790. union usa rsa; /* Remote socket address */
  1791. unsigned char is_ssl; /* Is port SSL-ed */
  1792. unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL
  1793. * port */
  1794. unsigned char in_use; /* Is valid */
  1795. };
  1796. /* Enum const for all options must be in sync with
  1797. * static struct mg_option config_options[]
  1798. * This is tested in the unit test (test/private.c)
  1799. * "Private Config Options"
  1800. */
  1801. enum {
  1802. LISTENING_PORTS,
  1803. NUM_THREADS,
  1804. RUN_AS_USER,
  1805. CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the
  1806. * socket option typedef TCP_NODELAY. */
  1807. MAX_REQUEST_SIZE,
  1808. LINGER_TIMEOUT,
  1809. #if defined(__linux__)
  1810. ALLOW_SENDFILE_CALL,
  1811. #endif
  1812. #if defined(_WIN32)
  1813. CASE_SENSITIVE_FILES,
  1814. #endif
  1815. THROTTLE,
  1816. ACCESS_LOG_FILE,
  1817. ERROR_LOG_FILE,
  1818. ENABLE_KEEP_ALIVE,
  1819. REQUEST_TIMEOUT,
  1820. KEEP_ALIVE_TIMEOUT,
  1821. #if defined(USE_WEBSOCKET)
  1822. WEBSOCKET_TIMEOUT,
  1823. #endif
  1824. DECODE_URL,
  1825. #if defined(USE_LUA)
  1826. LUA_BACKGROUND_SCRIPT,
  1827. LUA_BACKGROUND_SCRIPT_PARAMS,
  1828. #endif
  1829. DOCUMENT_ROOT,
  1830. CGI_EXTENSIONS,
  1831. CGI_ENVIRONMENT,
  1832. PUT_DELETE_PASSWORDS_FILE,
  1833. CGI_INTERPRETER,
  1834. PROTECT_URI,
  1835. AUTHENTICATION_DOMAIN,
  1836. ENABLE_AUTH_DOMAIN_CHECK,
  1837. SSI_EXTENSIONS,
  1838. ENABLE_DIRECTORY_LISTING,
  1839. GLOBAL_PASSWORDS_FILE,
  1840. INDEX_FILES,
  1841. ACCESS_CONTROL_LIST,
  1842. EXTRA_MIME_TYPES,
  1843. SSL_CERTIFICATE,
  1844. SSL_CERTIFICATE_CHAIN,
  1845. URL_REWRITE_PATTERN,
  1846. HIDE_FILES,
  1847. SSL_DO_VERIFY_PEER,
  1848. SSL_CA_PATH,
  1849. SSL_CA_FILE,
  1850. SSL_VERIFY_DEPTH,
  1851. SSL_DEFAULT_VERIFY_PATHS,
  1852. SSL_CIPHER_LIST,
  1853. SSL_PROTOCOL_VERSION,
  1854. SSL_SHORT_TRUST,
  1855. #if defined(USE_LUA)
  1856. LUA_PRELOAD_FILE,
  1857. LUA_SCRIPT_EXTENSIONS,
  1858. LUA_SERVER_PAGE_EXTENSIONS,
  1859. #endif
  1860. #if defined(USE_DUKTAPE)
  1861. DUKTAPE_SCRIPT_EXTENSIONS,
  1862. #endif
  1863. #if defined(USE_WEBSOCKET)
  1864. WEBSOCKET_ROOT,
  1865. #endif
  1866. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1867. LUA_WEBSOCKET_EXTENSIONS,
  1868. #endif
  1869. ACCESS_CONTROL_ALLOW_ORIGIN,
  1870. ACCESS_CONTROL_ALLOW_METHODS,
  1871. ACCESS_CONTROL_ALLOW_HEADERS,
  1872. ERROR_PAGES,
  1873. #if !defined(NO_CACHING)
  1874. STATIC_FILE_MAX_AGE,
  1875. #endif
  1876. #if !defined(NO_SSL)
  1877. STRICT_HTTPS_MAX_AGE,
  1878. #endif
  1879. ADDITIONAL_HEADER,
  1880. ALLOW_INDEX_SCRIPT_SUB_RES,
  1881. NUM_OPTIONS
  1882. };
  1883. /* Config option name, config types, default value.
  1884. * Must be in the same order as the enum const above.
  1885. */
  1886. static struct mg_option config_options[] = {
  1887. /* Once for each server */
  1888. {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"},
  1889. {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"},
  1890. {"run_as_user", MG_CONFIG_TYPE_STRING, NULL},
  1891. {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"},
  1892. {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"},
  1893. {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL},
  1894. #if defined(__linux__)
  1895. {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1896. #endif
  1897. #if defined(_WIN32)
  1898. {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1899. #endif
  1900. {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1901. {"access_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1902. {"error_log_file", MG_CONFIG_TYPE_FILE, NULL},
  1903. {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1904. {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1905. {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"},
  1906. #if defined(USE_WEBSOCKET)
  1907. {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"},
  1908. #endif
  1909. {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1910. #if defined(USE_LUA)
  1911. {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL},
  1912. {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1913. #endif
  1914. /* Once for each domain */
  1915. {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1916. {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"},
  1917. {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1918. {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1919. {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL},
  1920. {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1921. {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"},
  1922. {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1923. {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"},
  1924. {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1925. {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL},
  1926. {"index_files",
  1927. MG_CONFIG_TYPE_STRING_LIST,
  1928. #ifdef USE_LUA
  1929. "index.xhtml,index.html,index.htm,"
  1930. "index.lp,index.lsp,index.lua,index.cgi,"
  1931. "index.shtml,index.php"},
  1932. #else
  1933. "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"},
  1934. #endif
  1935. {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1936. {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1937. {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL},
  1938. {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL},
  1939. {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL},
  1940. {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL},
  1941. {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"},
  1942. {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1943. {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL},
  1944. {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"},
  1945. {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"},
  1946. {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL},
  1947. {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"},
  1948. {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1949. #if defined(USE_LUA)
  1950. {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL},
  1951. {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1952. {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"},
  1953. #endif
  1954. #if defined(USE_DUKTAPE)
  1955. /* The support for duktape is still in alpha version state.
  1956. * The name of this config option might change. */
  1957. {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"},
  1958. #endif
  1959. #if defined(USE_WEBSOCKET)
  1960. {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1961. #endif
  1962. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  1963. {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"},
  1964. #endif
  1965. {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"},
  1966. {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"},
  1967. {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"},
  1968. {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL},
  1969. #if !defined(NO_CACHING)
  1970. {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"},
  1971. #endif
  1972. #if !defined(NO_SSL)
  1973. {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL},
  1974. #endif
  1975. {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL},
  1976. {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"},
  1977. {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}};
  1978. /* Check if the config_options and the corresponding enum have compatible
  1979. * sizes. */
  1980. mg_static_assert((sizeof(config_options) / sizeof(config_options[0]))
  1981. == (NUM_OPTIONS + 1),
  1982. "config_options and enum not sync");
  1983. enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER };
  1984. struct mg_handler_info {
  1985. /* Name/Pattern of the URI. */
  1986. char *uri;
  1987. size_t uri_len;
  1988. /* handler type */
  1989. int handler_type;
  1990. /* Handler for http/https or authorization requests. */
  1991. mg_request_handler handler;
  1992. /* Handler for ws/wss (websocket) requests. */
  1993. mg_websocket_connect_handler connect_handler;
  1994. mg_websocket_ready_handler ready_handler;
  1995. mg_websocket_data_handler data_handler;
  1996. mg_websocket_close_handler close_handler;
  1997. /* accepted subprotocols for ws/wss requests. */
  1998. struct mg_websocket_subprotocols *subprotocols;
  1999. /* Handler for authorization requests */
  2000. mg_authorization_handler auth_handler;
  2001. /* User supplied argument for the handler function. */
  2002. void *cbdata;
  2003. /* next handler in a linked list */
  2004. struct mg_handler_info *next;
  2005. };
  2006. enum {
  2007. CONTEXT_INVALID,
  2008. CONTEXT_SERVER,
  2009. CONTEXT_HTTP_CLIENT,
  2010. CONTEXT_WS_CLIENT
  2011. };
  2012. struct mg_domain_context {
  2013. SSL_CTX *ssl_ctx; /* SSL context */
  2014. char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */
  2015. struct mg_handler_info *handlers; /* linked list of uri handlers */
  2016. /* Server nonce */
  2017. uint64_t auth_nonce_mask; /* Mask for all nonce values */
  2018. unsigned long nonce_count; /* Used nonces, used for authentication */
  2019. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2020. /* linked list of shared lua websockets */
  2021. struct mg_shared_lua_websocket_list *shared_lua_websockets;
  2022. #endif
  2023. /* Linked list of domains */
  2024. struct mg_domain_context *next;
  2025. };
  2026. struct mg_context {
  2027. /* Part 1 - Physical context:
  2028. * This holds threads, ports, timeouts, ...
  2029. * set for the entire server, independent from the
  2030. * addressed hostname.
  2031. */
  2032. /* Connection related */
  2033. int context_type; /* See CONTEXT_* above */
  2034. struct socket *listening_sockets;
  2035. struct pollfd *listening_socket_fds;
  2036. unsigned int num_listening_sockets;
  2037. struct mg_connection *worker_connections; /* The connection struct, pre-
  2038. * allocated for each worker */
  2039. #if defined(USE_SERVER_STATS)
  2040. int active_connections;
  2041. int max_connections;
  2042. int64_t total_connections;
  2043. int64_t total_requests;
  2044. int64_t total_data_read;
  2045. int64_t total_data_written;
  2046. #endif
  2047. /* Thread related */
  2048. volatile int stop_flag; /* Should we stop event loop */
  2049. pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */
  2050. pthread_t masterthreadid; /* The master thread ID */
  2051. unsigned int
  2052. cfg_worker_threads; /* The number of configured worker threads. */
  2053. pthread_t *worker_threadids; /* The worker thread IDs */
  2054. /* Connection to thread dispatching */
  2055. #ifdef ALTERNATIVE_QUEUE
  2056. struct socket *client_socks;
  2057. void **client_wait_events;
  2058. #else
  2059. struct socket queue[MGSQLEN]; /* Accepted sockets */
  2060. volatile int sq_head; /* Head of the socket queue */
  2061. volatile int sq_tail; /* Tail of the socket queue */
  2062. pthread_cond_t sq_full; /* Signaled when socket is produced */
  2063. pthread_cond_t sq_empty; /* Signaled when socket is consumed */
  2064. #endif
  2065. /* Memory related */
  2066. unsigned int max_request_size; /* The max request size */
  2067. #if defined(USE_SERVER_STATS)
  2068. struct mg_memory_stat ctx_memory;
  2069. #endif
  2070. /* Operating system related */
  2071. char *systemName; /* What operating system is running */
  2072. time_t start_time; /* Server start time, used for authentication
  2073. * and for diagnstics. */
  2074. #if defined(USE_TIMERS)
  2075. struct ttimers *timers;
  2076. #endif
  2077. /* Lua specific: Background operations and shared websockets */
  2078. #if defined(USE_LUA)
  2079. void *lua_background_state;
  2080. #endif
  2081. /* Server nonce */
  2082. pthread_mutex_t nonce_mutex; /* Protects nonce_count */
  2083. /* Server callbacks */
  2084. struct mg_callbacks callbacks; /* User-defined callback function */
  2085. void *user_data; /* User-defined data */
  2086. /* Part 2 - Logical domain:
  2087. * This holds hostname, TLS certificate, document root, ...
  2088. * set for a domain hosted at the server.
  2089. * There may be multiple domains hosted at one physical server.
  2090. * The default domain "dd" is the first element of a list of
  2091. * domains.
  2092. */
  2093. struct mg_domain_context dd; /* default domain */
  2094. };
  2095. #if defined(USE_SERVER_STATS)
  2096. static struct mg_memory_stat mg_common_memory = {0, 0, 0};
  2097. static struct mg_memory_stat *
  2098. get_memory_stat(struct mg_context *ctx)
  2099. {
  2100. if (ctx) {
  2101. return &(ctx->ctx_memory);
  2102. }
  2103. return &mg_common_memory;
  2104. }
  2105. #endif
  2106. enum {
  2107. CONNECTION_TYPE_INVALID,
  2108. CONNECTION_TYPE_REQUEST,
  2109. CONNECTION_TYPE_RESPONSE
  2110. };
  2111. struct mg_connection {
  2112. int connection_type; /* see CONNECTION_TYPE_* above */
  2113. struct mg_request_info request_info;
  2114. struct mg_response_info response_info;
  2115. struct mg_context *phys_ctx;
  2116. struct mg_domain_context *dom_ctx;
  2117. #if defined(USE_SERVER_STATS)
  2118. int conn_state; /* 0 = undef, numerical value may change in different
  2119. * versions. For the current definition, see
  2120. * mg_get_connection_info_impl */
  2121. #endif
  2122. const char *host; /* Host (HTTP/1.1 header or SNI) */
  2123. SSL *ssl; /* SSL descriptor */
  2124. SSL_CTX *client_ssl_ctx; /* SSL context for client connections */
  2125. struct socket client; /* Connected client */
  2126. time_t conn_birth_time; /* Time (wall clock) when connection was
  2127. * established */
  2128. struct timespec req_time; /* Time (since system start) when the request
  2129. * was received */
  2130. int64_t num_bytes_sent; /* Total bytes sent to client */
  2131. int64_t content_len; /* Content-Length header value */
  2132. int64_t consumed_content; /* How many bytes of content have been read */
  2133. int is_chunked; /* Transfer-Encoding is chunked:
  2134. * 0 = not chunked,
  2135. * 1 = chunked, do data read yet,
  2136. * 2 = chunked, some data read,
  2137. * 3 = chunked, all data read
  2138. */
  2139. size_t chunk_remainder; /* Unread data from the last chunk */
  2140. char *buf; /* Buffer for received data */
  2141. char *path_info; /* PATH_INFO part of the URL */
  2142. int must_close; /* 1 if connection must be closed */
  2143. int accept_gzip; /* 1 if gzip encoding is accepted */
  2144. int in_error_handler; /* 1 if in handler for user defined error
  2145. * pages */
  2146. #if defined(USE_WEBSOCKET)
  2147. int in_websocket_handling; /* 1 if in read_websocket */
  2148. #endif
  2149. int handled_requests; /* Number of requests handled by this connection
  2150. */
  2151. int buf_size; /* Buffer size */
  2152. int request_len; /* Size of the request + headers in a buffer */
  2153. int data_len; /* Total size of data in a buffer */
  2154. int status_code; /* HTTP reply status code, e.g. 200 */
  2155. int throttle; /* Throttling, bytes/sec. <= 0 means no
  2156. * throttle */
  2157. time_t last_throttle_time; /* Last time throttled data was sent */
  2158. int64_t last_throttle_bytes; /* Bytes sent this second */
  2159. pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure
  2160. * atomic transmissions for websockets */
  2161. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  2162. void *lua_websocket_state; /* Lua_State for a websocket connection */
  2163. #endif
  2164. int thread_index; /* Thread index within ctx */
  2165. };
  2166. /* Directory entry */
  2167. struct de {
  2168. struct mg_connection *conn;
  2169. char *file_name;
  2170. struct mg_file_stat file;
  2171. };
  2172. #if defined(USE_WEBSOCKET)
  2173. static int is_websocket_protocol(const struct mg_connection *conn);
  2174. #else
  2175. #define is_websocket_protocol(conn) (0)
  2176. #endif
  2177. #if !defined(NO_THREAD_NAME)
  2178. #if defined(_WIN32) && defined(_MSC_VER)
  2179. /* Set the thread name for debugging purposes in Visual Studio
  2180. * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
  2181. */
  2182. #pragma pack(push, 8)
  2183. typedef struct tagTHREADNAME_INFO {
  2184. DWORD dwType; /* Must be 0x1000. */
  2185. LPCSTR szName; /* Pointer to name (in user addr space). */
  2186. DWORD dwThreadID; /* Thread ID (-1=caller thread). */
  2187. DWORD dwFlags; /* Reserved for future use, must be zero. */
  2188. } THREADNAME_INFO;
  2189. #pragma pack(pop)
  2190. #elif defined(__linux__)
  2191. #include <sys/prctl.h>
  2192. #include <sys/sendfile.h>
  2193. #ifdef ALTERNATIVE_QUEUE
  2194. #include <sys/eventfd.h>
  2195. #endif /* ALTERNATIVE_QUEUE */
  2196. #if defined(ALTERNATIVE_QUEUE)
  2197. #ifdef __clang__
  2198. #pragma clang diagnostic push
  2199. #pragma clang diagnostic ignored "-Wunreachable-code"
  2200. /* For every system, "(sizeof(int) == sizeof(void *))" is either always
  2201. * true or always false. One of the two branches is unreachable in any case.
  2202. * Unfortunately the C standard does not define a way to check this at
  2203. * compile time, since the #if preprocessor conditions can not use the sizeof
  2204. * operator as an argument. */
  2205. #endif
  2206. #if defined(__GNUC__) || defined(__MINGW32__)
  2207. /* GCC does not realize one branch is unreachable, so it raises some
  2208. * pointer cast warning within the unreachable branch.
  2209. */
  2210. #pragma GCC diagnostic push
  2211. #pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
  2212. #pragma GCC diagnostic ignored "-Wpointer-to-int-cast"
  2213. #endif
  2214. static void *
  2215. event_create(void)
  2216. {
  2217. int evhdl = eventfd(0, EFD_CLOEXEC);
  2218. int *ret;
  2219. if (evhdl == -1) {
  2220. /* Linux uses -1 on error, Windows NULL. */
  2221. /* However, Linux does not return 0 on success either. */
  2222. return 0;
  2223. }
  2224. if (sizeof(int) == sizeof(void *)) {
  2225. ret = (void *)evhdl;
  2226. } else {
  2227. ret = (int *)mg_malloc(sizeof(int));
  2228. if (ret) {
  2229. *ret = evhdl;
  2230. } else {
  2231. (void)close(evhdl);
  2232. }
  2233. }
  2234. return (void *)ret;
  2235. }
  2236. static int
  2237. event_wait(void *eventhdl)
  2238. {
  2239. uint64_t u;
  2240. int evhdl, s;
  2241. if (sizeof(int) == sizeof(void *)) {
  2242. evhdl = (int)eventhdl;
  2243. } else {
  2244. if (!eventhdl) {
  2245. /* error */
  2246. return 0;
  2247. }
  2248. evhdl = *(int *)eventhdl;
  2249. }
  2250. s = (int)read(evhdl, &u, sizeof(u));
  2251. if (s != sizeof(uint64_t)) {
  2252. /* error */
  2253. return 0;
  2254. }
  2255. (void)u; /* the value is not required */
  2256. return 1;
  2257. }
  2258. static int
  2259. event_signal(void *eventhdl)
  2260. {
  2261. uint64_t u = 1;
  2262. int evhdl, s;
  2263. if (sizeof(int) == sizeof(void *)) {
  2264. evhdl = (int)eventhdl;
  2265. } else {
  2266. if (!eventhdl) {
  2267. /* error */
  2268. return 0;
  2269. }
  2270. evhdl = *(int *)eventhdl;
  2271. }
  2272. s = (int)write(evhdl, &u, sizeof(u));
  2273. if (s != sizeof(uint64_t)) {
  2274. /* error */
  2275. return 0;
  2276. }
  2277. return 1;
  2278. }
  2279. static void
  2280. event_destroy(void *eventhdl)
  2281. {
  2282. int evhdl;
  2283. if (sizeof(int) == sizeof(void *)) {
  2284. evhdl = (int)eventhdl;
  2285. close(evhdl);
  2286. } else {
  2287. if (!eventhdl) {
  2288. /* error */
  2289. return;
  2290. }
  2291. evhdl = *(int *)eventhdl;
  2292. close(evhdl);
  2293. mg_free(eventhdl);
  2294. }
  2295. }
  2296. #if defined(__GNUC__) || defined(__MINGW32__)
  2297. #pragma GCC diagnostic pop
  2298. #endif
  2299. #ifdef __clang__
  2300. #pragma clang diagnostic pop
  2301. #endif
  2302. #endif
  2303. #endif
  2304. #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE)
  2305. struct posix_event {
  2306. pthread_mutex_t mutex;
  2307. pthread_cond_t cond;
  2308. };
  2309. static void *
  2310. event_create(void)
  2311. {
  2312. struct posix_event *ret = mg_malloc(sizeof(struct posix_event));
  2313. if (ret == 0) {
  2314. /* out of memory */
  2315. return 0;
  2316. }
  2317. if (0 != pthread_mutex_init(&(ret->mutex), NULL)) {
  2318. /* pthread mutex not available */
  2319. mg_free(ret);
  2320. return 0;
  2321. }
  2322. if (0 != pthread_cond_init(&(ret->cond), NULL)) {
  2323. /* pthread cond not available */
  2324. pthread_mutex_destroy(&(ret->mutex));
  2325. mg_free(ret);
  2326. return 0;
  2327. }
  2328. return (void *)ret;
  2329. }
  2330. static int
  2331. event_wait(void *eventhdl)
  2332. {
  2333. struct posix_event *ev = (struct posix_event *)eventhdl;
  2334. pthread_mutex_lock(&(ev->mutex));
  2335. pthread_cond_wait(&(ev->cond), &(ev->mutex));
  2336. pthread_mutex_unlock(&(ev->mutex));
  2337. return 1;
  2338. }
  2339. static int
  2340. event_signal(void *eventhdl)
  2341. {
  2342. struct posix_event *ev = (struct posix_event *)eventhdl;
  2343. pthread_mutex_lock(&(ev->mutex));
  2344. pthread_cond_signal(&(ev->cond));
  2345. pthread_mutex_unlock(&(ev->mutex));
  2346. return 1;
  2347. }
  2348. static void
  2349. event_destroy(void *eventhdl)
  2350. {
  2351. struct posix_event *ev = (struct posix_event *)eventhdl;
  2352. pthread_cond_destroy(&(ev->cond));
  2353. pthread_mutex_destroy(&(ev->mutex));
  2354. mg_free(ev);
  2355. }
  2356. #endif
  2357. static void
  2358. mg_set_thread_name(const char *name)
  2359. {
  2360. char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */
  2361. mg_snprintf(
  2362. NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name);
  2363. #if defined(_WIN32)
  2364. #if defined(_MSC_VER)
  2365. /* Windows and Visual Studio Compiler */
  2366. __try
  2367. {
  2368. THREADNAME_INFO info;
  2369. info.dwType = 0x1000;
  2370. info.szName = threadName;
  2371. info.dwThreadID = ~0U;
  2372. info.dwFlags = 0;
  2373. RaiseException(0x406D1388,
  2374. 0,
  2375. sizeof(info) / sizeof(ULONG_PTR),
  2376. (ULONG_PTR *)&info);
  2377. }
  2378. __except(EXCEPTION_EXECUTE_HANDLER)
  2379. {
  2380. }
  2381. #elif defined(__MINGW32__)
  2382. /* No option known to set thread name for MinGW */
  2383. #endif
  2384. #elif defined(__GLIBC__) \
  2385. && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12)))
  2386. /* pthread_setname_np first appeared in glibc in version 2.12*/
  2387. (void)pthread_setname_np(pthread_self(), threadName);
  2388. #elif defined(__linux__)
  2389. /* on linux we can use the old prctl function */
  2390. (void)prctl(PR_SET_NAME, threadName, 0, 0, 0);
  2391. #endif
  2392. }
  2393. #else /* !defined(NO_THREAD_NAME) */
  2394. void
  2395. mg_set_thread_name(const char *threadName)
  2396. {
  2397. }
  2398. #endif
  2399. #if defined(MG_LEGACY_INTERFACE)
  2400. const char **
  2401. mg_get_valid_option_names(void)
  2402. {
  2403. /* This function is deprecated. Use mg_get_valid_options instead. */
  2404. static const char *
  2405. data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0};
  2406. int i;
  2407. for (i = 0; config_options[i].name != NULL; i++) {
  2408. data[i * 2] = config_options[i].name;
  2409. data[i * 2 + 1] = config_options[i].default_value;
  2410. }
  2411. return data;
  2412. }
  2413. #endif
  2414. const struct mg_option *
  2415. mg_get_valid_options(void)
  2416. {
  2417. return config_options;
  2418. }
  2419. /* Do not open file (used in is_file_in_memory) */
  2420. #define MG_FOPEN_MODE_NONE (0)
  2421. /* Open file for read only access */
  2422. #define MG_FOPEN_MODE_READ (1)
  2423. /* Open file for writing, create and overwrite */
  2424. #define MG_FOPEN_MODE_WRITE (2)
  2425. /* Open file for writing, create and append */
  2426. #define MG_FOPEN_MODE_APPEND (4)
  2427. /* If a file is in memory, set all "stat" members and the membuf pointer of
  2428. * output filep and return 1, otherwise return 0 and don't modify anything.
  2429. */
  2430. static int
  2431. open_file_in_memory(const struct mg_connection *conn,
  2432. const char *path,
  2433. struct mg_file *filep,
  2434. int mode)
  2435. {
  2436. #if defined(MG_USE_OPEN_FILE)
  2437. size_t size = 0;
  2438. const char *buf = NULL;
  2439. if (!conn) {
  2440. return 0;
  2441. }
  2442. if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) {
  2443. return 0;
  2444. }
  2445. if (conn->phys_ctx->callbacks.open_file) {
  2446. buf = conn->phys_ctx->callbacks.open_file(conn, path, &size);
  2447. if (buf != NULL) {
  2448. if (filep == NULL) {
  2449. /* This is a file in memory, but we cannot store the
  2450. * properties
  2451. * now.
  2452. * Called from "is_file_in_memory" function. */
  2453. return 1;
  2454. }
  2455. /* NOTE: override filep->size only on success. Otherwise, it
  2456. * might
  2457. * break constructs like if (!mg_stat() || !mg_fopen()) ... */
  2458. filep->access.membuf = buf;
  2459. filep->access.fp = NULL;
  2460. /* Size was set by the callback */
  2461. filep->stat.size = size;
  2462. /* Assume the data may change during runtime by setting
  2463. * last_modified = now */
  2464. filep->stat.last_modified = time(NULL);
  2465. filep->stat.is_directory = 0;
  2466. filep->stat.is_gzipped = 0;
  2467. }
  2468. }
  2469. return (buf != NULL);
  2470. #else
  2471. (void)conn;
  2472. (void)path;
  2473. (void)filep;
  2474. (void)mode;
  2475. return 0;
  2476. #endif
  2477. }
  2478. static int
  2479. is_file_in_memory(const struct mg_connection *conn, const char *path)
  2480. {
  2481. return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE);
  2482. }
  2483. static int
  2484. is_file_opened(const struct mg_file_access *fileacc)
  2485. {
  2486. if (!fileacc) {
  2487. return 0;
  2488. }
  2489. return (fileacc->membuf != NULL) || (fileacc->fp != NULL);
  2490. }
  2491. static int mg_stat(const struct mg_connection *conn,
  2492. const char *path,
  2493. struct mg_file_stat *filep);
  2494. /* mg_fopen will open a file either in memory or on the disk.
  2495. * The input parameter path is a string in UTF-8 encoding.
  2496. * The input parameter mode is MG_FOPEN_MODE_*
  2497. * On success, either fp or membuf will be set in the output
  2498. * struct file. All status members will also be set.
  2499. * The function returns 1 on success, 0 on error. */
  2500. static int
  2501. mg_fopen(const struct mg_connection *conn,
  2502. const char *path,
  2503. int mode,
  2504. struct mg_file *filep)
  2505. {
  2506. int found;
  2507. if (!filep) {
  2508. return 0;
  2509. }
  2510. filep->access.fp = NULL;
  2511. filep->access.membuf = NULL;
  2512. if (!is_file_in_memory(conn, path)) {
  2513. /* filep is initialized in mg_stat: all fields with memset to,
  2514. * some fields like size and modification date with values */
  2515. found = mg_stat(conn, path, &(filep->stat));
  2516. if ((mode == MG_FOPEN_MODE_READ) && (!found)) {
  2517. /* file does not exist and will not be created */
  2518. return 0;
  2519. }
  2520. #ifdef _WIN32
  2521. {
  2522. wchar_t wbuf[W_PATH_MAX];
  2523. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  2524. switch (mode) {
  2525. case MG_FOPEN_MODE_READ:
  2526. filep->access.fp = _wfopen(wbuf, L"rb");
  2527. break;
  2528. case MG_FOPEN_MODE_WRITE:
  2529. filep->access.fp = _wfopen(wbuf, L"wb");
  2530. break;
  2531. case MG_FOPEN_MODE_APPEND:
  2532. filep->access.fp = _wfopen(wbuf, L"ab");
  2533. break;
  2534. }
  2535. }
  2536. #else
  2537. /* Linux et al already use unicode. No need to convert. */
  2538. switch (mode) {
  2539. case MG_FOPEN_MODE_READ:
  2540. filep->access.fp = fopen(path, "r");
  2541. break;
  2542. case MG_FOPEN_MODE_WRITE:
  2543. filep->access.fp = fopen(path, "w");
  2544. break;
  2545. case MG_FOPEN_MODE_APPEND:
  2546. filep->access.fp = fopen(path, "a");
  2547. break;
  2548. }
  2549. #endif
  2550. if (!found) {
  2551. /* File did not exist before fopen was called.
  2552. * Maybe it has been created now. Get stat info
  2553. * like creation time now. */
  2554. found = mg_stat(conn, path, &(filep->stat));
  2555. (void)found;
  2556. }
  2557. /* file is on disk */
  2558. return (filep->access.fp != NULL);
  2559. } else {
  2560. /* is_file_in_memory returned true */
  2561. if (open_file_in_memory(conn, path, filep, mode)) {
  2562. /* file is in memory */
  2563. return (filep->access.membuf != NULL);
  2564. }
  2565. }
  2566. /* Open failed */
  2567. return 0;
  2568. }
  2569. /* return 0 on success, just like fclose */
  2570. static int
  2571. mg_fclose(struct mg_file_access *fileacc)
  2572. {
  2573. int ret = -1;
  2574. if (fileacc != NULL) {
  2575. if (fileacc->fp != NULL) {
  2576. ret = fclose(fileacc->fp);
  2577. } else if (fileacc->membuf != NULL) {
  2578. ret = 0;
  2579. }
  2580. /* reset all members of fileacc */
  2581. memset(fileacc, 0, sizeof(*fileacc));
  2582. }
  2583. return ret;
  2584. }
  2585. static void
  2586. mg_strlcpy(register char *dst, register const char *src, size_t n)
  2587. {
  2588. for (; *src != '\0' && n > 1; n--) {
  2589. *dst++ = *src++;
  2590. }
  2591. *dst = '\0';
  2592. }
  2593. static int
  2594. lowercase(const char *s)
  2595. {
  2596. return tolower(*(const unsigned char *)s);
  2597. }
  2598. int
  2599. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  2600. {
  2601. int diff = 0;
  2602. if (len > 0) {
  2603. do {
  2604. diff = lowercase(s1++) - lowercase(s2++);
  2605. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2606. }
  2607. return diff;
  2608. }
  2609. int
  2610. mg_strcasecmp(const char *s1, const char *s2)
  2611. {
  2612. int diff;
  2613. do {
  2614. diff = lowercase(s1++) - lowercase(s2++);
  2615. } while (diff == 0 && s1[-1] != '\0');
  2616. return diff;
  2617. }
  2618. static char *
  2619. mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx)
  2620. {
  2621. char *p;
  2622. if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) {
  2623. mg_strlcpy(p, ptr, len + 1);
  2624. }
  2625. return p;
  2626. }
  2627. static char *
  2628. mg_strdup_ctx(const char *str, struct mg_context *ctx)
  2629. {
  2630. return mg_strndup_ctx(str, strlen(str), ctx);
  2631. }
  2632. static char *
  2633. mg_strdup(const char *str)
  2634. {
  2635. return mg_strndup_ctx(str, strlen(str), NULL);
  2636. }
  2637. static const char *
  2638. mg_strcasestr(const char *big_str, const char *small_str)
  2639. {
  2640. size_t i, big_len = strlen(big_str), small_len = strlen(small_str);
  2641. if (big_len >= small_len) {
  2642. for (i = 0; i <= (big_len - small_len); i++) {
  2643. if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) {
  2644. return big_str + i;
  2645. }
  2646. }
  2647. }
  2648. return NULL;
  2649. }
  2650. /* Return null terminated string of given maximum length.
  2651. * Report errors if length is exceeded. */
  2652. static void
  2653. mg_vsnprintf(const struct mg_connection *conn,
  2654. int *truncated,
  2655. char *buf,
  2656. size_t buflen,
  2657. const char *fmt,
  2658. va_list ap)
  2659. {
  2660. int n, ok;
  2661. if (buflen == 0) {
  2662. if (truncated) {
  2663. *truncated = 1;
  2664. }
  2665. return;
  2666. }
  2667. #ifdef __clang__
  2668. #pragma clang diagnostic push
  2669. #pragma clang diagnostic ignored "-Wformat-nonliteral"
  2670. /* Using fmt as a non-literal is intended here, since it is mostly called
  2671. * indirectly by mg_snprintf */
  2672. #endif
  2673. n = (int)vsnprintf_impl(buf, buflen, fmt, ap);
  2674. ok = (n >= 0) && ((size_t)n < buflen);
  2675. #ifdef __clang__
  2676. #pragma clang diagnostic pop
  2677. #endif
  2678. if (ok) {
  2679. if (truncated) {
  2680. *truncated = 0;
  2681. }
  2682. } else {
  2683. if (truncated) {
  2684. *truncated = 1;
  2685. }
  2686. mg_cry(conn,
  2687. "truncating vsnprintf buffer: [%.*s]",
  2688. (int)((buflen > 200) ? 200 : (buflen - 1)),
  2689. buf);
  2690. n = (int)buflen - 1;
  2691. }
  2692. buf[n] = '\0';
  2693. }
  2694. static void
  2695. mg_snprintf(const struct mg_connection *conn,
  2696. int *truncated,
  2697. char *buf,
  2698. size_t buflen,
  2699. const char *fmt,
  2700. ...)
  2701. {
  2702. va_list ap;
  2703. va_start(ap, fmt);
  2704. mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap);
  2705. va_end(ap);
  2706. }
  2707. static int
  2708. get_option_index(const char *name)
  2709. {
  2710. int i;
  2711. for (i = 0; config_options[i].name != NULL; i++) {
  2712. if (strcmp(config_options[i].name, name) == 0) {
  2713. return i;
  2714. }
  2715. }
  2716. return -1;
  2717. }
  2718. const char *
  2719. mg_get_option(const struct mg_context *ctx, const char *name)
  2720. {
  2721. int i;
  2722. if ((i = get_option_index(name)) == -1) {
  2723. return NULL;
  2724. } else if (!ctx || ctx->dd.config[i] == NULL) {
  2725. return "";
  2726. } else {
  2727. return ctx->dd.config[i];
  2728. }
  2729. }
  2730. #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly
  2731. struct mg_context *
  2732. mg_get_context(const struct mg_connection *conn)
  2733. {
  2734. return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx);
  2735. }
  2736. void *
  2737. mg_get_user_data(const struct mg_context *ctx)
  2738. {
  2739. return (ctx == NULL) ? NULL : ctx->user_data;
  2740. }
  2741. void
  2742. mg_set_user_connection_data(struct mg_connection *conn, void *data)
  2743. {
  2744. if (conn != NULL) {
  2745. conn->request_info.conn_data = data;
  2746. }
  2747. }
  2748. void *
  2749. mg_get_user_connection_data(const struct mg_connection *conn)
  2750. {
  2751. if (conn != NULL) {
  2752. return conn->request_info.conn_data;
  2753. }
  2754. return NULL;
  2755. }
  2756. #if defined(MG_LEGACY_INTERFACE)
  2757. /* Deprecated: Use mg_get_server_ports instead. */
  2758. size_t
  2759. mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl)
  2760. {
  2761. size_t i;
  2762. if (!ctx) {
  2763. return 0;
  2764. }
  2765. for (i = 0; i < size && i < ctx->num_listening_sockets; i++) {
  2766. ssl[i] = ctx->listening_sockets[i].is_ssl;
  2767. ports[i] =
  2768. #if defined(USE_IPV6)
  2769. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2770. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2771. :
  2772. #endif
  2773. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2774. }
  2775. return i;
  2776. }
  2777. #endif
  2778. int
  2779. mg_get_server_ports(const struct mg_context *ctx,
  2780. int size,
  2781. struct mg_server_ports *ports)
  2782. {
  2783. int i, cnt = 0;
  2784. if (size <= 0) {
  2785. return -1;
  2786. }
  2787. memset(ports, 0, sizeof(*ports) * (size_t)size);
  2788. if (!ctx) {
  2789. return -1;
  2790. }
  2791. if (!ctx->listening_sockets) {
  2792. return -1;
  2793. }
  2794. for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) {
  2795. ports[cnt].port =
  2796. #if defined(USE_IPV6)
  2797. (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6)
  2798. ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port)
  2799. :
  2800. #endif
  2801. ntohs(ctx->listening_sockets[i].lsa.sin.sin_port);
  2802. ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl;
  2803. ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir;
  2804. if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) {
  2805. /* IPv4 */
  2806. ports[cnt].protocol = 1;
  2807. cnt++;
  2808. } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) {
  2809. /* IPv6 */
  2810. ports[cnt].protocol = 3;
  2811. cnt++;
  2812. }
  2813. }
  2814. return cnt;
  2815. }
  2816. static void
  2817. sockaddr_to_string(char *buf, size_t len, const union usa *usa)
  2818. {
  2819. buf[0] = '\0';
  2820. if (!usa) {
  2821. return;
  2822. }
  2823. if (usa->sa.sa_family == AF_INET) {
  2824. getnameinfo(&usa->sa,
  2825. sizeof(usa->sin),
  2826. buf,
  2827. (unsigned)len,
  2828. NULL,
  2829. 0,
  2830. NI_NUMERICHOST);
  2831. }
  2832. #if defined(USE_IPV6)
  2833. else if (usa->sa.sa_family == AF_INET6) {
  2834. getnameinfo(&usa->sa,
  2835. sizeof(usa->sin6),
  2836. buf,
  2837. (unsigned)len,
  2838. NULL,
  2839. 0,
  2840. NI_NUMERICHOST);
  2841. }
  2842. #endif
  2843. }
  2844. /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be
  2845. * included in all responses other than 100, 101, 5xx. */
  2846. static void
  2847. gmt_time_string(char *buf, size_t buf_len, time_t *t)
  2848. {
  2849. struct tm *tm;
  2850. tm = ((t != NULL) ? gmtime(t) : NULL);
  2851. if (tm != NULL) {
  2852. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm);
  2853. } else {
  2854. mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len);
  2855. buf[buf_len - 1] = '\0';
  2856. }
  2857. }
  2858. /* difftime for struct timespec. Return value is in seconds. */
  2859. static double
  2860. mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before)
  2861. {
  2862. return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9
  2863. + (double)(ts_now->tv_sec - ts_before->tv_sec);
  2864. }
  2865. /* Print error message to the opened error log stream. */
  2866. void
  2867. mg_cry(const struct mg_connection *conn, const char *fmt, ...)
  2868. {
  2869. char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN];
  2870. va_list ap;
  2871. struct mg_file fi;
  2872. time_t timestamp;
  2873. va_start(ap, fmt);
  2874. IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap));
  2875. va_end(ap);
  2876. buf[sizeof(buf) - 1] = 0;
  2877. DEBUG_TRACE("mg_cry: %s", buf);
  2878. if (!conn) {
  2879. puts(buf);
  2880. return;
  2881. }
  2882. /* Do not lock when getting the callback value, here and below.
  2883. * I suppose this is fine, since function cannot disappear in the
  2884. * same way string option can. */
  2885. if ((conn->phys_ctx->callbacks.log_message == NULL)
  2886. || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) {
  2887. if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) {
  2888. if (mg_fopen(conn,
  2889. conn->dom_ctx->config[ERROR_LOG_FILE],
  2890. MG_FOPEN_MODE_APPEND,
  2891. &fi) == 0) {
  2892. fi.access.fp = NULL;
  2893. }
  2894. } else {
  2895. fi.access.fp = NULL;
  2896. }
  2897. if (fi.access.fp != NULL) {
  2898. flockfile(fi.access.fp);
  2899. timestamp = time(NULL);
  2900. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2901. fprintf(fi.access.fp,
  2902. "[%010lu] [error] [client %s] ",
  2903. (unsigned long)timestamp,
  2904. src_addr);
  2905. if (conn->request_info.request_method != NULL) {
  2906. fprintf(fi.access.fp,
  2907. "%s %s: ",
  2908. conn->request_info.request_method,
  2909. conn->request_info.request_uri
  2910. ? conn->request_info.request_uri
  2911. : "");
  2912. }
  2913. fprintf(fi.access.fp, "%s", buf);
  2914. fputc('\n', fi.access.fp);
  2915. fflush(fi.access.fp);
  2916. funlockfile(fi.access.fp);
  2917. (void)mg_fclose(&fi.access); /* Ignore errors. We can't call
  2918. * mg_cry here anyway ;-) */
  2919. }
  2920. }
  2921. }
  2922. /* Return fake connection structure. Used for logging, if connection
  2923. * is not applicable at the moment of logging. */
  2924. static struct mg_connection *
  2925. fc(struct mg_context *ctx)
  2926. {
  2927. static struct mg_connection fake_connection;
  2928. fake_connection.phys_ctx = ctx;
  2929. fake_connection.dom_ctx = &(ctx->dd);
  2930. return &fake_connection;
  2931. }
  2932. const char *
  2933. mg_version(void)
  2934. {
  2935. return CIVETWEB_VERSION;
  2936. }
  2937. const struct mg_request_info *
  2938. mg_get_request_info(const struct mg_connection *conn)
  2939. {
  2940. if (!conn) {
  2941. return NULL;
  2942. }
  2943. #if 1 /* TODO: deal with legacy */
  2944. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  2945. static char txt[16];
  2946. sprintf(txt, "%03i", conn->response_info.status_code);
  2947. ((struct mg_connection *)conn)->request_info.local_uri =
  2948. ((struct mg_connection *)conn)->request_info.request_uri =
  2949. txt; /* TODO: not thread safe */
  2950. ((struct mg_connection *)conn)->request_info.num_headers =
  2951. conn->response_info.num_headers;
  2952. memcpy(((struct mg_connection *)conn)->request_info.http_headers,
  2953. conn->response_info.http_headers,
  2954. sizeof(conn->response_info.http_headers));
  2955. } else
  2956. #endif
  2957. if (conn->connection_type != CONNECTION_TYPE_REQUEST) {
  2958. return NULL;
  2959. }
  2960. return &conn->request_info;
  2961. }
  2962. const struct mg_response_info *
  2963. mg_get_response_info(const struct mg_connection *conn)
  2964. {
  2965. if (!conn) {
  2966. return NULL;
  2967. }
  2968. if (conn->connection_type != CONNECTION_TYPE_RESPONSE) {
  2969. return NULL;
  2970. }
  2971. return &conn->response_info;
  2972. }
  2973. static const char *
  2974. get_proto_name(const struct mg_connection *conn)
  2975. {
  2976. #ifdef __clang__
  2977. #pragma clang diagnostic push
  2978. #pragma clang diagnostic ignored "-Wunreachable-code"
  2979. /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be
  2980. * not supported. Clang raises an "unreachable code" warning for parts of ?:
  2981. * unreachable, but splitting into four different #ifdef clauses here is more
  2982. * complicated.
  2983. */
  2984. #endif
  2985. const struct mg_request_info *ri = &conn->request_info;
  2986. const char *proto =
  2987. (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws")
  2988. : (ri->is_ssl ? "https" : "http"));
  2989. return proto;
  2990. #ifdef __clang__
  2991. #pragma clang diagnostic pop
  2992. #endif
  2993. }
  2994. int
  2995. mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen)
  2996. {
  2997. if ((buflen < 1) || (buf == 0) || (conn == 0)) {
  2998. return -1;
  2999. } else {
  3000. int truncated = 0;
  3001. const struct mg_request_info *ri = &conn->request_info;
  3002. const char *proto = get_proto_name(conn);
  3003. if (ri->local_uri == NULL) {
  3004. return -1;
  3005. }
  3006. if ((ri->request_uri != NULL)
  3007. && strcmp(ri->local_uri, ri->request_uri)) {
  3008. mg_snprintf(conn,
  3009. &truncated,
  3010. buf,
  3011. buflen,
  3012. "%s://%s",
  3013. proto,
  3014. ri->request_uri);
  3015. if (truncated) {
  3016. return -1;
  3017. }
  3018. return 0;
  3019. } else {
  3020. #if defined(USE_IPV6)
  3021. int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6);
  3022. int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port)
  3023. : htons(conn->client.lsa.sin.sin_port);
  3024. #else
  3025. int port = htons(conn->client.lsa.sin.sin_port);
  3026. #endif
  3027. int def_port = ri->is_ssl ? 443 : 80;
  3028. int auth_domain_check_enabled =
  3029. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK]
  3030. && (!mg_strcasecmp(
  3031. conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK],
  3032. "yes"));
  3033. const char *server_domain =
  3034. conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  3035. char portstr[16];
  3036. char server_ip[48];
  3037. if (port != def_port) {
  3038. sprintf(portstr, ":%u", (unsigned)port);
  3039. } else {
  3040. portstr[0] = 0;
  3041. }
  3042. if (!auth_domain_check_enabled || !server_domain) {
  3043. sockaddr_to_string(server_ip,
  3044. sizeof(server_ip),
  3045. &conn->client.lsa);
  3046. server_domain = server_ip;
  3047. }
  3048. mg_snprintf(conn,
  3049. &truncated,
  3050. buf,
  3051. buflen,
  3052. "%s://%s%s%s",
  3053. proto,
  3054. server_domain,
  3055. portstr,
  3056. ri->local_uri);
  3057. if (truncated) {
  3058. return -1;
  3059. }
  3060. return 0;
  3061. }
  3062. }
  3063. }
  3064. /* Skip the characters until one of the delimiters characters found.
  3065. * 0-terminate resulting word. Skip the delimiter and following whitespaces.
  3066. * Advance pointer to buffer to the next word. Return found 0-terminated
  3067. * word.
  3068. * Delimiters can be quoted with quotechar. */
  3069. static char *
  3070. skip_quoted(char **buf,
  3071. const char *delimiters,
  3072. const char *whitespace,
  3073. char quotechar)
  3074. {
  3075. char *p, *begin_word, *end_word, *end_whitespace;
  3076. begin_word = *buf;
  3077. end_word = begin_word + strcspn(begin_word, delimiters);
  3078. /* Check for quotechar */
  3079. if (end_word > begin_word) {
  3080. p = end_word - 1;
  3081. while (*p == quotechar) {
  3082. /* While the delimiter is quoted, look for the next delimiter.
  3083. */
  3084. /* This happens, e.g., in calls from parse_auth_header,
  3085. * if the user name contains a " character. */
  3086. /* If there is anything beyond end_word, copy it. */
  3087. if (*end_word != '\0') {
  3088. size_t end_off = strcspn(end_word + 1, delimiters);
  3089. memmove(p, end_word, end_off + 1);
  3090. p += end_off; /* p must correspond to end_word - 1 */
  3091. end_word += end_off + 1;
  3092. } else {
  3093. *p = '\0';
  3094. break;
  3095. }
  3096. }
  3097. for (p++; p < end_word; p++) {
  3098. *p = '\0';
  3099. }
  3100. }
  3101. if (*end_word == '\0') {
  3102. *buf = end_word;
  3103. } else {
  3104. #if defined(__GNUC__) || defined(__MINGW32__)
  3105. /* Disable spurious conversion warning for GCC */
  3106. #if GCC_VERSION >= 40500
  3107. #pragma GCC diagnostic push
  3108. #pragma GCC diagnostic ignored "-Wsign-conversion"
  3109. #endif /* GCC_VERSION >= 40500 */
  3110. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3111. end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1;
  3112. #if defined(__GNUC__) || defined(__MINGW32__)
  3113. #if GCC_VERSION >= 40500
  3114. #pragma GCC diagnostic pop
  3115. #endif /* GCC_VERSION >= 40500 */
  3116. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  3117. for (p = end_word; p < end_whitespace; p++) {
  3118. *p = '\0';
  3119. }
  3120. *buf = end_whitespace;
  3121. }
  3122. return begin_word;
  3123. }
  3124. /* Return HTTP header value, or NULL if not found. */
  3125. static const char *
  3126. get_header(const struct mg_header *hdr, int num_hdr, const char *name)
  3127. {
  3128. int i;
  3129. for (i = 0; i < num_hdr; i++) {
  3130. if (!mg_strcasecmp(name, hdr[i].name)) {
  3131. return hdr[i].value;
  3132. }
  3133. }
  3134. return NULL;
  3135. }
  3136. #if defined(USE_WEBSOCKET)
  3137. /* Retrieve requested HTTP header multiple values, and return the number of
  3138. * found occurences */
  3139. static int
  3140. get_req_headers(const struct mg_request_info *ri,
  3141. const char *name,
  3142. const char **output,
  3143. int output_max_size)
  3144. {
  3145. int i;
  3146. int cnt = 0;
  3147. if (ri) {
  3148. for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) {
  3149. if (!mg_strcasecmp(name, ri->http_headers[i].name)) {
  3150. output[cnt++] = ri->http_headers[i].value;
  3151. }
  3152. }
  3153. }
  3154. return cnt;
  3155. }
  3156. #endif
  3157. const char *
  3158. mg_get_header(const struct mg_connection *conn, const char *name)
  3159. {
  3160. if (!conn) {
  3161. return NULL;
  3162. }
  3163. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3164. return get_header(conn->request_info.http_headers,
  3165. conn->request_info.num_headers,
  3166. name);
  3167. }
  3168. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3169. return get_header(conn->response_info.http_headers,
  3170. conn->response_info.num_headers,
  3171. name);
  3172. }
  3173. return NULL;
  3174. }
  3175. static const char *
  3176. get_http_version(const struct mg_connection *conn)
  3177. {
  3178. if (!conn) {
  3179. return NULL;
  3180. }
  3181. if (conn->connection_type == CONNECTION_TYPE_REQUEST) {
  3182. return conn->request_info.http_version;
  3183. }
  3184. if (conn->connection_type == CONNECTION_TYPE_RESPONSE) {
  3185. return conn->response_info.http_version;
  3186. }
  3187. return NULL;
  3188. }
  3189. /* A helper function for traversing a comma separated list of values.
  3190. * It returns a list pointer shifted to the next value, or NULL if the end
  3191. * of the list found.
  3192. * Value is stored in val vector. If value has form "x=y", then eq_val
  3193. * vector is initialized to point to the "y" part, and val vector length
  3194. * is adjusted to point only to "x". */
  3195. static const char *
  3196. next_option(const char *list, struct vec *val, struct vec *eq_val)
  3197. {
  3198. int end;
  3199. reparse:
  3200. if (val == NULL || list == NULL || *list == '\0') {
  3201. /* End of the list */
  3202. return NULL;
  3203. }
  3204. /* Skip over leading LWS */
  3205. while (*list == ' ' || *list == '\t')
  3206. list++;
  3207. val->ptr = list;
  3208. if ((list = strchr(val->ptr, ',')) != NULL) {
  3209. /* Comma found. Store length and shift the list ptr */
  3210. val->len = ((size_t)(list - val->ptr));
  3211. list++;
  3212. } else {
  3213. /* This value is the last one */
  3214. list = val->ptr + strlen(val->ptr);
  3215. val->len = ((size_t)(list - val->ptr));
  3216. }
  3217. /* Adjust length for trailing LWS */
  3218. end = (int)val->len - 1;
  3219. while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t')))
  3220. end--;
  3221. val->len = (size_t)(end + 1);
  3222. if (val->len == 0) {
  3223. /* Ignore any empty entries. */
  3224. goto reparse;
  3225. }
  3226. if (eq_val != NULL) {
  3227. /* Value has form "x=y", adjust pointers and lengths
  3228. * so that val points to "x", and eq_val points to "y". */
  3229. eq_val->len = 0;
  3230. eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len);
  3231. if (eq_val->ptr != NULL) {
  3232. eq_val->ptr++; /* Skip over '=' character */
  3233. eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len;
  3234. val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1;
  3235. }
  3236. }
  3237. return list;
  3238. }
  3239. /* A helper function for checking if a comma separated list of values
  3240. * contains
  3241. * the given option (case insensitvely).
  3242. * 'header' can be NULL, in which case false is returned. */
  3243. static int
  3244. header_has_option(const char *header, const char *option)
  3245. {
  3246. struct vec opt_vec;
  3247. struct vec eq_vec;
  3248. DEBUG_ASSERT(option != NULL);
  3249. DEBUG_ASSERT(option[0] != '\0');
  3250. while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) {
  3251. if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0)
  3252. return 1;
  3253. }
  3254. return 0;
  3255. }
  3256. /* Perform case-insensitive match of string against pattern */
  3257. static int
  3258. match_prefix(const char *pattern, size_t pattern_len, const char *str)
  3259. {
  3260. const char *or_str;
  3261. size_t i;
  3262. int j, len, res;
  3263. if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) {
  3264. res = match_prefix(pattern, (size_t)(or_str - pattern), str);
  3265. return (res > 0) ? res : match_prefix(or_str + 1,
  3266. (size_t)((pattern + pattern_len)
  3267. - (or_str + 1)),
  3268. str);
  3269. }
  3270. for (i = 0, j = 0; (i < pattern_len); i++, j++) {
  3271. if ((pattern[i] == '?') && (str[j] != '\0')) {
  3272. continue;
  3273. } else if (pattern[i] == '$') {
  3274. return (str[j] == '\0') ? j : -1;
  3275. } else if (pattern[i] == '*') {
  3276. i++;
  3277. if (pattern[i] == '*') {
  3278. i++;
  3279. len = (int)strlen(str + j);
  3280. } else {
  3281. len = (int)strcspn(str + j, "/");
  3282. }
  3283. if (i == pattern_len) {
  3284. return j + len;
  3285. }
  3286. do {
  3287. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  3288. } while (res == -1 && len-- > 0);
  3289. return (res == -1) ? -1 : j + res + len;
  3290. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  3291. return -1;
  3292. }
  3293. }
  3294. return j;
  3295. }
  3296. /* HTTP 1.1 assumes keep alive if "Connection:" header is not set
  3297. * This function must tolerate situations when connection info is not
  3298. * set up, for example if request parsing failed. */
  3299. static int
  3300. should_keep_alive(const struct mg_connection *conn)
  3301. {
  3302. const char *http_version;
  3303. const char *header;
  3304. /* First satisfy needs of the server */
  3305. if ((conn == NULL) || conn->must_close) {
  3306. /* Close, if civetweb framework needs to close */
  3307. return 0;
  3308. }
  3309. if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) {
  3310. /* Close, if keep alive is not enabled */
  3311. return 0;
  3312. }
  3313. /* Check explicit wish of the client */
  3314. header = mg_get_header(conn, "Connection");
  3315. if (header) {
  3316. /* If there is a connection header from the client, obey */
  3317. if (header_has_option(header, "keep-alive")) {
  3318. return 1;
  3319. }
  3320. return 0;
  3321. }
  3322. /* Use default of the standard */
  3323. http_version = get_http_version(conn);
  3324. if (http_version && (0 == strcmp(http_version, "1.1"))) {
  3325. /* HTTP 1.1 default is keep alive */
  3326. return 1;
  3327. }
  3328. /* HTTP 1.0 (and earlier) default is to close the connection */
  3329. return 0;
  3330. }
  3331. static int
  3332. should_decode_url(const struct mg_connection *conn)
  3333. {
  3334. if (!conn || !conn->dom_ctx) {
  3335. return 0;
  3336. }
  3337. return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0);
  3338. }
  3339. static const char *
  3340. suggest_connection_header(const struct mg_connection *conn)
  3341. {
  3342. return should_keep_alive(conn) ? "keep-alive" : "close";
  3343. }
  3344. static int
  3345. send_no_cache_header(struct mg_connection *conn)
  3346. {
  3347. /* Send all current and obsolete cache opt-out directives. */
  3348. return mg_printf(conn,
  3349. "Cache-Control: no-cache, no-store, "
  3350. "must-revalidate, private, max-age=0\r\n"
  3351. "Pragma: no-cache\r\n"
  3352. "Expires: 0\r\n");
  3353. }
  3354. static int
  3355. send_static_cache_header(struct mg_connection *conn)
  3356. {
  3357. #if !defined(NO_CACHING)
  3358. /* Read the server config to check how long a file may be cached.
  3359. * The configuration is in seconds. */
  3360. int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]);
  3361. if (max_age <= 0) {
  3362. /* 0 means "do not cache". All values <0 are reserved
  3363. * and may be used differently in the future. */
  3364. /* If a file should not be cached, do not only send
  3365. * max-age=0, but also pragmas and Expires headers. */
  3366. return send_no_cache_header(conn);
  3367. }
  3368. /* Use "Cache-Control: max-age" instead of "Expires" header.
  3369. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */
  3370. /* See also https://www.mnot.net/cache_docs/ */
  3371. /* According to RFC 2616, Section 14.21, caching times should not exceed
  3372. * one year. A year with 365 days corresponds to 31536000 seconds, a
  3373. * leap
  3374. * year to 31622400 seconds. For the moment, we just send whatever has
  3375. * been configured, still the behavior for >1 year should be considered
  3376. * as undefined. */
  3377. return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age);
  3378. #else /* NO_CACHING */
  3379. return send_no_cache_header(conn);
  3380. #endif /* !NO_CACHING */
  3381. }
  3382. static int
  3383. send_additional_header(struct mg_connection *conn)
  3384. {
  3385. int i = 0;
  3386. const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER];
  3387. #if !defined(NO_SSL)
  3388. if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) {
  3389. int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]);
  3390. if (max_age >= 0) {
  3391. i += mg_printf(conn,
  3392. "Strict-Transport-Security: max-age=%u\r\n",
  3393. (unsigned)max_age);
  3394. }
  3395. }
  3396. #endif
  3397. if (header && header[0]) {
  3398. i += mg_printf(conn, "%s\r\n", header);
  3399. }
  3400. return i;
  3401. }
  3402. static void handle_file_based_request(struct mg_connection *conn,
  3403. const char *path,
  3404. struct mg_file *filep);
  3405. const char *
  3406. mg_get_response_code_text(const struct mg_connection *conn, int response_code)
  3407. {
  3408. /* See IANA HTTP status code assignment:
  3409. * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
  3410. */
  3411. switch (response_code) {
  3412. /* RFC2616 Section 10.1 - Informational 1xx */
  3413. case 100:
  3414. return "Continue"; /* RFC2616 Section 10.1.1 */
  3415. case 101:
  3416. return "Switching Protocols"; /* RFC2616 Section 10.1.2 */
  3417. case 102:
  3418. return "Processing"; /* RFC2518 Section 10.1 */
  3419. /* RFC2616 Section 10.2 - Successful 2xx */
  3420. case 200:
  3421. return "OK"; /* RFC2616 Section 10.2.1 */
  3422. case 201:
  3423. return "Created"; /* RFC2616 Section 10.2.2 */
  3424. case 202:
  3425. return "Accepted"; /* RFC2616 Section 10.2.3 */
  3426. case 203:
  3427. return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */
  3428. case 204:
  3429. return "No Content"; /* RFC2616 Section 10.2.5 */
  3430. case 205:
  3431. return "Reset Content"; /* RFC2616 Section 10.2.6 */
  3432. case 206:
  3433. return "Partial Content"; /* RFC2616 Section 10.2.7 */
  3434. case 207:
  3435. return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1
  3436. */
  3437. case 208:
  3438. return "Already Reported"; /* RFC5842 Section 7.1 */
  3439. case 226:
  3440. return "IM used"; /* RFC3229 Section 10.4.1 */
  3441. /* RFC2616 Section 10.3 - Redirection 3xx */
  3442. case 300:
  3443. return "Multiple Choices"; /* RFC2616 Section 10.3.1 */
  3444. case 301:
  3445. return "Moved Permanently"; /* RFC2616 Section 10.3.2 */
  3446. case 302:
  3447. return "Found"; /* RFC2616 Section 10.3.3 */
  3448. case 303:
  3449. return "See Other"; /* RFC2616 Section 10.3.4 */
  3450. case 304:
  3451. return "Not Modified"; /* RFC2616 Section 10.3.5 */
  3452. case 305:
  3453. return "Use Proxy"; /* RFC2616 Section 10.3.6 */
  3454. case 307:
  3455. return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */
  3456. case 308:
  3457. return "Permanent Redirect"; /* RFC7238 Section 3 */
  3458. /* RFC2616 Section 10.4 - Client Error 4xx */
  3459. case 400:
  3460. return "Bad Request"; /* RFC2616 Section 10.4.1 */
  3461. case 401:
  3462. return "Unauthorized"; /* RFC2616 Section 10.4.2 */
  3463. case 402:
  3464. return "Payment Required"; /* RFC2616 Section 10.4.3 */
  3465. case 403:
  3466. return "Forbidden"; /* RFC2616 Section 10.4.4 */
  3467. case 404:
  3468. return "Not Found"; /* RFC2616 Section 10.4.5 */
  3469. case 405:
  3470. return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */
  3471. case 406:
  3472. return "Not Acceptable"; /* RFC2616 Section 10.4.7 */
  3473. case 407:
  3474. return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */
  3475. case 408:
  3476. return "Request Time-out"; /* RFC2616 Section 10.4.9 */
  3477. case 409:
  3478. return "Conflict"; /* RFC2616 Section 10.4.10 */
  3479. case 410:
  3480. return "Gone"; /* RFC2616 Section 10.4.11 */
  3481. case 411:
  3482. return "Length Required"; /* RFC2616 Section 10.4.12 */
  3483. case 412:
  3484. return "Precondition Failed"; /* RFC2616 Section 10.4.13 */
  3485. case 413:
  3486. return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */
  3487. case 414:
  3488. return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */
  3489. case 415:
  3490. return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */
  3491. case 416:
  3492. return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17
  3493. */
  3494. case 417:
  3495. return "Expectation Failed"; /* RFC2616 Section 10.4.18 */
  3496. case 421:
  3497. return "Misdirected Request"; /* RFC7540 Section 9.1.2 */
  3498. case 422:
  3499. return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918
  3500. * Section 11.2 */
  3501. case 423:
  3502. return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */
  3503. case 424:
  3504. return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918
  3505. * Section 11.4 */
  3506. case 426:
  3507. return "Upgrade Required"; /* RFC 2817 Section 4 */
  3508. case 428:
  3509. return "Precondition Required"; /* RFC 6585, Section 3 */
  3510. case 429:
  3511. return "Too Many Requests"; /* RFC 6585, Section 4 */
  3512. case 431:
  3513. return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */
  3514. case 451:
  3515. return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05,
  3516. * Section 3 */
  3517. /* RFC2616 Section 10.5 - Server Error 5xx */
  3518. case 500:
  3519. return "Internal Server Error"; /* RFC2616 Section 10.5.1 */
  3520. case 501:
  3521. return "Not Implemented"; /* RFC2616 Section 10.5.2 */
  3522. case 502:
  3523. return "Bad Gateway"; /* RFC2616 Section 10.5.3 */
  3524. case 503:
  3525. return "Service Unavailable"; /* RFC2616 Section 10.5.4 */
  3526. case 504:
  3527. return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */
  3528. case 505:
  3529. return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */
  3530. case 506:
  3531. return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */
  3532. case 507:
  3533. return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918
  3534. * Section 11.5 */
  3535. case 508:
  3536. return "Loop Detected"; /* RFC5842 Section 7.1 */
  3537. case 510:
  3538. return "Not Extended"; /* RFC 2774, Section 7 */
  3539. case 511:
  3540. return "Network Authentication Required"; /* RFC 6585, Section 6 */
  3541. /* Other status codes, not shown in the IANA HTTP status code
  3542. * assignment.
  3543. * E.g., "de facto" standards due to common use, ... */
  3544. case 418:
  3545. return "I am a teapot"; /* RFC2324 Section 2.3.2 */
  3546. case 419:
  3547. return "Authentication Timeout"; /* common use */
  3548. case 420:
  3549. return "Enhance Your Calm"; /* common use */
  3550. case 440:
  3551. return "Login Timeout"; /* common use */
  3552. case 509:
  3553. return "Bandwidth Limit Exceeded"; /* common use */
  3554. default:
  3555. /* This error code is unknown. This should not happen. */
  3556. if (conn) {
  3557. mg_cry(conn, "Unknown HTTP response code: %u", response_code);
  3558. }
  3559. /* Return at least a category according to RFC 2616 Section 10. */
  3560. if (response_code >= 100 && response_code < 200) {
  3561. /* Unknown informational status code */
  3562. return "Information";
  3563. }
  3564. if (response_code >= 200 && response_code < 300) {
  3565. /* Unknown success code */
  3566. return "Success";
  3567. }
  3568. if (response_code >= 300 && response_code < 400) {
  3569. /* Unknown redirection code */
  3570. return "Redirection";
  3571. }
  3572. if (response_code >= 400 && response_code < 500) {
  3573. /* Unknown request error code */
  3574. return "Client Error";
  3575. }
  3576. if (response_code >= 500 && response_code < 600) {
  3577. /* Unknown server error code */
  3578. return "Server Error";
  3579. }
  3580. /* Response code not even within reasonable range */
  3581. return "";
  3582. }
  3583. }
  3584. void
  3585. mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...)
  3586. {
  3587. char buf[MG_BUF_LEN];
  3588. va_list ap;
  3589. int len, i, page_handler_found, scope, truncated, has_body;
  3590. char date[64];
  3591. time_t curtime = time(NULL);
  3592. const char *error_handler = NULL;
  3593. struct mg_file error_page_file = STRUCT_FILE_INITIALIZER;
  3594. const char *error_page_file_ext, *tstr;
  3595. const char *status_text = mg_get_response_code_text(conn, status);
  3596. if (conn == NULL) {
  3597. return;
  3598. }
  3599. conn->status_code = status;
  3600. if (conn->in_error_handler || (conn->phys_ctx->callbacks.http_error == NULL)
  3601. || conn->phys_ctx->callbacks.http_error(conn, status)) {
  3602. /* Check for recursion */
  3603. if (conn->in_error_handler) {
  3604. DEBUG_TRACE(
  3605. "Recursion when handling error %u - fall back to default",
  3606. status);
  3607. } else {
  3608. /* Send user defined error pages, if defined */
  3609. error_handler = conn->dom_ctx->config[ERROR_PAGES];
  3610. error_page_file_ext = conn->dom_ctx->config[INDEX_FILES];
  3611. page_handler_found = 0;
  3612. if (error_handler != NULL) {
  3613. for (scope = 1; (scope <= 3) && !page_handler_found; scope++) {
  3614. switch (scope) {
  3615. case 1: /* Handler for specific error, e.g. 404 error */
  3616. mg_snprintf(conn,
  3617. &truncated,
  3618. buf,
  3619. sizeof(buf) - 32,
  3620. "%serror%03u.",
  3621. error_handler,
  3622. status);
  3623. break;
  3624. case 2: /* Handler for error group, e.g., 5xx error
  3625. * handler
  3626. * for all server errors (500-599) */
  3627. mg_snprintf(conn,
  3628. &truncated,
  3629. buf,
  3630. sizeof(buf) - 32,
  3631. "%serror%01uxx.",
  3632. error_handler,
  3633. status / 100);
  3634. break;
  3635. default: /* Handler for all errors */
  3636. mg_snprintf(conn,
  3637. &truncated,
  3638. buf,
  3639. sizeof(buf) - 32,
  3640. "%serror.",
  3641. error_handler);
  3642. break;
  3643. }
  3644. /* String truncation in buf may only occur if
  3645. * error_handler is too long. This string is
  3646. * from the config, not from a client. */
  3647. (void)truncated;
  3648. len = (int)strlen(buf);
  3649. tstr = strchr(error_page_file_ext, '.');
  3650. while (tstr) {
  3651. for (i = 1;
  3652. (i < 32) && (tstr[i] != 0) && (tstr[i] != ',');
  3653. i++)
  3654. buf[len + i - 1] = tstr[i];
  3655. buf[len + i - 1] = 0;
  3656. if (mg_stat(conn, buf, &error_page_file.stat)) {
  3657. DEBUG_TRACE("Check error page %s - found", buf);
  3658. page_handler_found = 1;
  3659. break;
  3660. }
  3661. DEBUG_TRACE("Check error page %s - not found", buf);
  3662. tstr = strchr(tstr + i, '.');
  3663. }
  3664. }
  3665. }
  3666. if (page_handler_found) {
  3667. conn->in_error_handler = 1;
  3668. handle_file_based_request(conn, buf, &error_page_file);
  3669. conn->in_error_handler = 0;
  3670. return;
  3671. }
  3672. }
  3673. /* No custom error page. Send default error page. */
  3674. gmt_time_string(date, sizeof(date), &curtime);
  3675. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3676. has_body = ((status > 199) && (status != 204) && (status != 304));
  3677. conn->must_close = 1;
  3678. mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text);
  3679. send_no_cache_header(conn);
  3680. send_additional_header(conn);
  3681. if (has_body) {
  3682. mg_printf(conn,
  3683. "%s",
  3684. "Content-Type: text/plain; charset=utf-8\r\n");
  3685. }
  3686. mg_printf(conn,
  3687. "Date: %s\r\n"
  3688. "Connection: close\r\n\r\n",
  3689. date);
  3690. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  3691. if (has_body) {
  3692. mg_printf(conn, "Error %d: %s\n", status, status_text);
  3693. if (fmt != NULL) {
  3694. va_start(ap, fmt);
  3695. mg_vsnprintf(conn, NULL, buf, sizeof(buf), fmt, ap);
  3696. va_end(ap);
  3697. mg_write(conn, buf, strlen(buf));
  3698. DEBUG_TRACE("Error %i - [%s]", status, buf);
  3699. }
  3700. } else {
  3701. /* No body allowed. Close the connection. */
  3702. DEBUG_TRACE("Error %i", status);
  3703. }
  3704. }
  3705. }
  3706. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  3707. /* Create substitutes for POSIX functions in Win32. */
  3708. #if defined(__MINGW32__)
  3709. /* Show no warning in case system functions are not used. */
  3710. #pragma GCC diagnostic push
  3711. #pragma GCC diagnostic ignored "-Wunused-function"
  3712. #endif
  3713. FUNCTION_MAY_BE_UNUSED
  3714. static int
  3715. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  3716. {
  3717. (void)unused;
  3718. *mutex = CreateMutex(NULL, FALSE, NULL);
  3719. return (*mutex == NULL) ? -1 : 0;
  3720. }
  3721. FUNCTION_MAY_BE_UNUSED
  3722. static int
  3723. pthread_mutex_destroy(pthread_mutex_t *mutex)
  3724. {
  3725. return (CloseHandle(*mutex) == 0) ? -1 : 0;
  3726. }
  3727. FUNCTION_MAY_BE_UNUSED
  3728. static int
  3729. pthread_mutex_lock(pthread_mutex_t *mutex)
  3730. {
  3731. return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0
  3732. : -1;
  3733. }
  3734. #ifdef ENABLE_UNUSED_PTHREAD_FUNCTIONS
  3735. FUNCTION_MAY_BE_UNUSED
  3736. static int
  3737. pthread_mutex_trylock(pthread_mutex_t *mutex)
  3738. {
  3739. switch (WaitForSingleObject(*mutex, 0)) {
  3740. case WAIT_OBJECT_0:
  3741. return 0;
  3742. case WAIT_TIMEOUT:
  3743. return -2; /* EBUSY */
  3744. }
  3745. return -1;
  3746. }
  3747. #endif
  3748. FUNCTION_MAY_BE_UNUSED
  3749. static int
  3750. pthread_mutex_unlock(pthread_mutex_t *mutex)
  3751. {
  3752. return (ReleaseMutex(*mutex) == 0) ? -1 : 0;
  3753. }
  3754. FUNCTION_MAY_BE_UNUSED
  3755. static int
  3756. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  3757. {
  3758. (void)unused;
  3759. InitializeCriticalSection(&cv->threadIdSec);
  3760. cv->waiting_thread = NULL;
  3761. return 0;
  3762. }
  3763. FUNCTION_MAY_BE_UNUSED
  3764. static int
  3765. pthread_cond_timedwait(pthread_cond_t *cv,
  3766. pthread_mutex_t *mutex,
  3767. const struct timespec *abstime)
  3768. {
  3769. struct mg_workerTLS **ptls,
  3770. *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey);
  3771. int ok;
  3772. int64_t nsnow, nswaitabs, nswaitrel;
  3773. DWORD mswaitrel;
  3774. EnterCriticalSection(&cv->threadIdSec);
  3775. /* Add this thread to cv's waiting list */
  3776. ptls = &cv->waiting_thread;
  3777. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread)
  3778. ;
  3779. tls->next_waiting_thread = NULL;
  3780. *ptls = tls;
  3781. LeaveCriticalSection(&cv->threadIdSec);
  3782. if (abstime) {
  3783. nsnow = mg_get_current_time_ns();
  3784. nswaitabs =
  3785. (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec;
  3786. nswaitrel = nswaitabs - nsnow;
  3787. if (nswaitrel < 0) {
  3788. nswaitrel = 0;
  3789. }
  3790. mswaitrel = (DWORD)(nswaitrel / 1000000);
  3791. } else {
  3792. mswaitrel = (DWORD)INFINITE;
  3793. }
  3794. pthread_mutex_unlock(mutex);
  3795. ok = (WAIT_OBJECT_0
  3796. == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel));
  3797. if (!ok) {
  3798. ok = 1;
  3799. EnterCriticalSection(&cv->threadIdSec);
  3800. ptls = &cv->waiting_thread;
  3801. for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) {
  3802. if (*ptls == tls) {
  3803. *ptls = tls->next_waiting_thread;
  3804. ok = 0;
  3805. break;
  3806. }
  3807. }
  3808. LeaveCriticalSection(&cv->threadIdSec);
  3809. if (ok) {
  3810. WaitForSingleObject(tls->pthread_cond_helper_mutex,
  3811. (DWORD)INFINITE);
  3812. }
  3813. }
  3814. /* This thread has been removed from cv's waiting list */
  3815. pthread_mutex_lock(mutex);
  3816. return ok ? 0 : -1;
  3817. }
  3818. FUNCTION_MAY_BE_UNUSED
  3819. static int
  3820. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  3821. {
  3822. return pthread_cond_timedwait(cv, mutex, NULL);
  3823. }
  3824. FUNCTION_MAY_BE_UNUSED
  3825. static int
  3826. pthread_cond_signal(pthread_cond_t *cv)
  3827. {
  3828. HANDLE wkup = NULL;
  3829. BOOL ok = FALSE;
  3830. EnterCriticalSection(&cv->threadIdSec);
  3831. if (cv->waiting_thread) {
  3832. wkup = cv->waiting_thread->pthread_cond_helper_mutex;
  3833. cv->waiting_thread = cv->waiting_thread->next_waiting_thread;
  3834. ok = SetEvent(wkup);
  3835. DEBUG_ASSERT(ok);
  3836. }
  3837. LeaveCriticalSection(&cv->threadIdSec);
  3838. return ok ? 0 : 1;
  3839. }
  3840. FUNCTION_MAY_BE_UNUSED
  3841. static int
  3842. pthread_cond_broadcast(pthread_cond_t *cv)
  3843. {
  3844. EnterCriticalSection(&cv->threadIdSec);
  3845. while (cv->waiting_thread) {
  3846. pthread_cond_signal(cv);
  3847. }
  3848. LeaveCriticalSection(&cv->threadIdSec);
  3849. return 0;
  3850. }
  3851. FUNCTION_MAY_BE_UNUSED
  3852. static int
  3853. pthread_cond_destroy(pthread_cond_t *cv)
  3854. {
  3855. EnterCriticalSection(&cv->threadIdSec);
  3856. DEBUG_ASSERT(cv->waiting_thread == NULL);
  3857. LeaveCriticalSection(&cv->threadIdSec);
  3858. DeleteCriticalSection(&cv->threadIdSec);
  3859. return 0;
  3860. }
  3861. #ifdef ALTERNATIVE_QUEUE
  3862. FUNCTION_MAY_BE_UNUSED
  3863. static void *
  3864. event_create(void)
  3865. {
  3866. return (void *)CreateEvent(NULL, FALSE, FALSE, NULL);
  3867. }
  3868. FUNCTION_MAY_BE_UNUSED
  3869. static int
  3870. event_wait(void *eventhdl)
  3871. {
  3872. int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE);
  3873. return (res == WAIT_OBJECT_0);
  3874. }
  3875. FUNCTION_MAY_BE_UNUSED
  3876. static int
  3877. event_signal(void *eventhdl)
  3878. {
  3879. return (int)SetEvent((HANDLE)eventhdl);
  3880. }
  3881. FUNCTION_MAY_BE_UNUSED
  3882. static void
  3883. event_destroy(void *eventhdl)
  3884. {
  3885. CloseHandle((HANDLE)eventhdl);
  3886. }
  3887. #endif
  3888. #if defined(__MINGW32__)
  3889. /* Enable unused function warning again */
  3890. #pragma GCC diagnostic pop
  3891. #endif
  3892. /* For Windows, change all slashes to backslashes in path names. */
  3893. static void
  3894. change_slashes_to_backslashes(char *path)
  3895. {
  3896. int i;
  3897. for (i = 0; path[i] != '\0'; i++) {
  3898. if (path[i] == '/') {
  3899. path[i] = '\\';
  3900. }
  3901. /* remove double backslash (check i > 0 to preserve UNC paths,
  3902. * like \\server\file.txt) */
  3903. if ((path[i] == '\\') && (i > 0)) {
  3904. while ((path[i + 1] == '\\') || (path[i + 1] == '/')) {
  3905. (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1));
  3906. }
  3907. }
  3908. }
  3909. }
  3910. static int
  3911. mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2)
  3912. {
  3913. int diff;
  3914. do {
  3915. diff = tolower(*s1) - tolower(*s2);
  3916. s1++;
  3917. s2++;
  3918. } while ((diff == 0) && (s1[-1] != '\0'));
  3919. return diff;
  3920. }
  3921. /* Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  3922. * wbuf and wbuf_len is a target buffer and its length. */
  3923. static void
  3924. path_to_unicode(const struct mg_connection *conn,
  3925. const char *path,
  3926. wchar_t *wbuf,
  3927. size_t wbuf_len)
  3928. {
  3929. char buf[PATH_MAX], buf2[PATH_MAX];
  3930. wchar_t wbuf2[W_PATH_MAX + 1];
  3931. DWORD long_len, err;
  3932. int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp;
  3933. mg_strlcpy(buf, path, sizeof(buf));
  3934. change_slashes_to_backslashes(buf);
  3935. /* Convert to Unicode and back. If doubly-converted string does not
  3936. * match the original, something is fishy, reject. */
  3937. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  3938. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len);
  3939. WideCharToMultiByte(
  3940. CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL);
  3941. if (strcmp(buf, buf2) != 0) {
  3942. wbuf[0] = L'\0';
  3943. }
  3944. /* Windows file systems are not case sensitive, but you can still use
  3945. * uppercase and lowercase letters (on all modern file systems).
  3946. * The server can check if the URI uses the same upper/lowercase
  3947. * letters an the file system, effectively making Windows servers
  3948. * case sensitive (like Linux servers are). It is still not possible
  3949. * to use two files with the same name in different cases on Windows
  3950. * (like /a and /A) - this would be possible in Linux.
  3951. * As a default, Windows is not case sensitive, but the case sensitive
  3952. * file name check can be activated by an additional configuration. */
  3953. if (conn) {
  3954. if (conn->dom_ctx->config[CASE_SENSITIVE_FILES]
  3955. && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES],
  3956. "yes")) {
  3957. /* Use case sensitive compare function */
  3958. fcompare = wcscmp;
  3959. }
  3960. }
  3961. (void)conn; /* conn is currently unused */
  3962. #if !defined(_WIN32_WCE)
  3963. /* Only accept a full file path, not a Windows short (8.3) path. */
  3964. memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t));
  3965. long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1);
  3966. if (long_len == 0) {
  3967. err = GetLastError();
  3968. if (err == ERROR_FILE_NOT_FOUND) {
  3969. /* File does not exist. This is not always a problem here. */
  3970. return;
  3971. }
  3972. }
  3973. if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) {
  3974. /* Short name is used. */
  3975. wbuf[0] = L'\0';
  3976. }
  3977. #else
  3978. (void)long_len;
  3979. (void)wbuf2;
  3980. (void)err;
  3981. if (strchr(path, '~')) {
  3982. wbuf[0] = L'\0';
  3983. }
  3984. #endif
  3985. }
  3986. /* Windows happily opens files with some garbage at the end of file name.
  3987. * For example, fopen("a.cgi ", "r") on Windows successfully opens
  3988. * "a.cgi", despite one would expect an error back.
  3989. * This function returns non-0 if path ends with some garbage. */
  3990. static int
  3991. path_cannot_disclose_cgi(const char *path)
  3992. {
  3993. static const char *allowed_last_characters = "_-";
  3994. int last = path[strlen(path) - 1];
  3995. return isalnum(last) || strchr(allowed_last_characters, last) != NULL;
  3996. }
  3997. static int
  3998. mg_stat(const struct mg_connection *conn,
  3999. const char *path,
  4000. struct mg_file_stat *filep)
  4001. {
  4002. wchar_t wbuf[W_PATH_MAX];
  4003. WIN32_FILE_ATTRIBUTE_DATA info;
  4004. time_t creation_time;
  4005. if (!filep) {
  4006. return 0;
  4007. }
  4008. memset(filep, 0, sizeof(*filep));
  4009. if (conn && is_file_in_memory(conn, path)) {
  4010. /* filep->is_directory = 0; filep->gzipped = 0; .. already done by
  4011. * memset */
  4012. /* Quick fix (for 1.9.x): */
  4013. /* mg_stat must fill all fields, also for files in memory */
  4014. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4015. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4016. filep->size = tmp_file.stat.size;
  4017. filep->location = 2;
  4018. /* TODO: for 1.10: restructure how files in memory are handled */
  4019. /* The "file in memory" feature is a candidate for deletion.
  4020. * Please join the discussion at
  4021. * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI
  4022. */
  4023. filep->last_modified = time(NULL); /* TODO */
  4024. /* last_modified = now ... assumes the file may change during
  4025. * runtime,
  4026. * so every mg_fopen call may return different data */
  4027. /* last_modified = conn->phys_ctx.start_time;
  4028. * May be used it the data does not change during runtime. This
  4029. * allows
  4030. * browser caching. Since we do not know, we have to assume the file
  4031. * in memory may change. */
  4032. return 1;
  4033. }
  4034. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4035. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  4036. filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  4037. filep->last_modified =
  4038. SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  4039. info.ftLastWriteTime.dwHighDateTime);
  4040. /* On Windows, the file creation time can be higher than the
  4041. * modification time, e.g. when a file is copied.
  4042. * Since the Last-Modified timestamp is used for caching
  4043. * it should be based on the most recent timestamp. */
  4044. creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime,
  4045. info.ftCreationTime.dwHighDateTime);
  4046. if (creation_time > filep->last_modified) {
  4047. filep->last_modified = creation_time;
  4048. }
  4049. filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  4050. /* If file name is fishy, reset the file structure and return
  4051. * error.
  4052. * Note it is important to reset, not just return the error, cause
  4053. * functions like is_file_opened() check the struct. */
  4054. if (!filep->is_directory && !path_cannot_disclose_cgi(path)) {
  4055. memset(filep, 0, sizeof(*filep));
  4056. return 0;
  4057. }
  4058. return 1;
  4059. }
  4060. return 0;
  4061. }
  4062. static int
  4063. mg_remove(const struct mg_connection *conn, const char *path)
  4064. {
  4065. wchar_t wbuf[W_PATH_MAX];
  4066. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4067. return DeleteFileW(wbuf) ? 0 : -1;
  4068. }
  4069. static int
  4070. mg_mkdir(const struct mg_connection *conn, const char *path, int mode)
  4071. {
  4072. wchar_t wbuf[W_PATH_MAX];
  4073. (void)mode;
  4074. path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf));
  4075. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  4076. }
  4077. /* Create substitutes for POSIX functions in Win32. */
  4078. #if defined(__MINGW32__)
  4079. /* Show no warning in case system functions are not used. */
  4080. #pragma GCC diagnostic push
  4081. #pragma GCC diagnostic ignored "-Wunused-function"
  4082. #endif
  4083. /* Implementation of POSIX opendir/closedir/readdir for Windows. */
  4084. FUNCTION_MAY_BE_UNUSED
  4085. static DIR *
  4086. mg_opendir(const struct mg_connection *conn, const char *name)
  4087. {
  4088. DIR *dir = NULL;
  4089. wchar_t wpath[W_PATH_MAX];
  4090. DWORD attrs;
  4091. if (name == NULL) {
  4092. SetLastError(ERROR_BAD_ARGUMENTS);
  4093. } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) {
  4094. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  4095. } else {
  4096. path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath));
  4097. attrs = GetFileAttributesW(wpath);
  4098. if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF)
  4099. && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) {
  4100. (void)wcscat(wpath, L"\\*");
  4101. dir->handle = FindFirstFileW(wpath, &dir->info);
  4102. dir->result.d_name[0] = '\0';
  4103. } else {
  4104. mg_free(dir);
  4105. dir = NULL;
  4106. }
  4107. }
  4108. return dir;
  4109. }
  4110. FUNCTION_MAY_BE_UNUSED
  4111. static int
  4112. mg_closedir(DIR *dir)
  4113. {
  4114. int result = 0;
  4115. if (dir != NULL) {
  4116. if (dir->handle != INVALID_HANDLE_VALUE)
  4117. result = FindClose(dir->handle) ? 0 : -1;
  4118. mg_free(dir);
  4119. } else {
  4120. result = -1;
  4121. SetLastError(ERROR_BAD_ARGUMENTS);
  4122. }
  4123. return result;
  4124. }
  4125. FUNCTION_MAY_BE_UNUSED
  4126. static struct dirent *
  4127. mg_readdir(DIR *dir)
  4128. {
  4129. struct dirent *result = 0;
  4130. if (dir) {
  4131. if (dir->handle != INVALID_HANDLE_VALUE) {
  4132. result = &dir->result;
  4133. (void)WideCharToMultiByte(CP_UTF8,
  4134. 0,
  4135. dir->info.cFileName,
  4136. -1,
  4137. result->d_name,
  4138. sizeof(result->d_name),
  4139. NULL,
  4140. NULL);
  4141. if (!FindNextFileW(dir->handle, &dir->info)) {
  4142. (void)FindClose(dir->handle);
  4143. dir->handle = INVALID_HANDLE_VALUE;
  4144. }
  4145. } else {
  4146. SetLastError(ERROR_FILE_NOT_FOUND);
  4147. }
  4148. } else {
  4149. SetLastError(ERROR_BAD_ARGUMENTS);
  4150. }
  4151. return result;
  4152. }
  4153. #ifndef HAVE_POLL
  4154. FUNCTION_MAY_BE_UNUSED
  4155. static int
  4156. poll(struct pollfd *pfd, unsigned int n, int milliseconds)
  4157. {
  4158. struct timeval tv;
  4159. fd_set set;
  4160. unsigned int i;
  4161. int result;
  4162. SOCKET maxfd = 0;
  4163. memset(&tv, 0, sizeof(tv));
  4164. tv.tv_sec = milliseconds / 1000;
  4165. tv.tv_usec = (milliseconds % 1000) * 1000;
  4166. FD_ZERO(&set);
  4167. for (i = 0; i < n; i++) {
  4168. FD_SET((SOCKET)pfd[i].fd, &set);
  4169. pfd[i].revents = 0;
  4170. if (pfd[i].fd > maxfd) {
  4171. maxfd = pfd[i].fd;
  4172. }
  4173. }
  4174. if ((result = select((int)maxfd + 1, &set, NULL, NULL, &tv)) > 0) {
  4175. for (i = 0; i < n; i++) {
  4176. if (FD_ISSET(pfd[i].fd, &set)) {
  4177. pfd[i].revents = POLLIN;
  4178. }
  4179. }
  4180. }
  4181. /* We should subtract the time used in select from remaining
  4182. * "milliseconds", in particular if called from mg_poll with a
  4183. * timeout quantum.
  4184. * Unfortunately, the remaining time is not stored in "tv" in all
  4185. * implementations, so the result in "tv" must be considered undefined.
  4186. * See http://man7.org/linux/man-pages/man2/select.2.html */
  4187. return result;
  4188. }
  4189. #endif /* HAVE_POLL */
  4190. #if defined(__MINGW32__)
  4191. /* Enable unused function warning again */
  4192. #pragma GCC diagnostic pop
  4193. #endif
  4194. static void
  4195. set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */)
  4196. {
  4197. (void)conn; /* Unused. */
  4198. #if defined(_WIN32_WCE)
  4199. (void)sock;
  4200. #else
  4201. (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0);
  4202. #endif
  4203. }
  4204. int
  4205. mg_start_thread(mg_thread_func_t f, void *p)
  4206. {
  4207. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4208. /* Compile-time option to control stack size, e.g.
  4209. * -DUSE_STACK_SIZE=16384
  4210. */
  4211. return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p)
  4212. == ((uintptr_t)(-1L)))
  4213. ? -1
  4214. : 0);
  4215. #else
  4216. return (
  4217. (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L)))
  4218. ? -1
  4219. : 0);
  4220. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4221. }
  4222. /* Start a thread storing the thread context. */
  4223. static int
  4224. mg_start_thread_with_id(unsigned(__stdcall *f)(void *),
  4225. void *p,
  4226. pthread_t *threadidptr)
  4227. {
  4228. uintptr_t uip;
  4229. HANDLE threadhandle;
  4230. int result = -1;
  4231. uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL);
  4232. threadhandle = (HANDLE)uip;
  4233. if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) {
  4234. *threadidptr = threadhandle;
  4235. result = 0;
  4236. }
  4237. return result;
  4238. }
  4239. /* Wait for a thread to finish. */
  4240. static int
  4241. mg_join_thread(pthread_t threadid)
  4242. {
  4243. int result;
  4244. DWORD dwevent;
  4245. result = -1;
  4246. dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE);
  4247. if (dwevent == WAIT_FAILED) {
  4248. DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO);
  4249. } else {
  4250. if (dwevent == WAIT_OBJECT_0) {
  4251. CloseHandle(threadid);
  4252. result = 0;
  4253. }
  4254. }
  4255. return result;
  4256. }
  4257. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  4258. /* If SSL is loaded dynamically, dlopen/dlclose is required. */
  4259. /* Create substitutes for POSIX functions in Win32. */
  4260. #if defined(__MINGW32__)
  4261. /* Show no warning in case system functions are not used. */
  4262. #pragma GCC diagnostic push
  4263. #pragma GCC diagnostic ignored "-Wunused-function"
  4264. #endif
  4265. FUNCTION_MAY_BE_UNUSED
  4266. static HANDLE
  4267. dlopen(const char *dll_name, int flags)
  4268. {
  4269. wchar_t wbuf[W_PATH_MAX];
  4270. (void)flags;
  4271. path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf));
  4272. return LoadLibraryW(wbuf);
  4273. }
  4274. FUNCTION_MAY_BE_UNUSED
  4275. static int
  4276. dlclose(void *handle)
  4277. {
  4278. int result;
  4279. if (FreeLibrary((HMODULE)handle) != 0) {
  4280. result = 0;
  4281. } else {
  4282. result = -1;
  4283. }
  4284. return result;
  4285. }
  4286. #if defined(__MINGW32__)
  4287. /* Enable unused function warning again */
  4288. #pragma GCC diagnostic pop
  4289. #endif
  4290. #endif
  4291. #if !defined(NO_CGI)
  4292. #define SIGKILL (0)
  4293. static int
  4294. kill(pid_t pid, int sig_num)
  4295. {
  4296. (void)TerminateProcess((HANDLE)pid, (UINT)sig_num);
  4297. (void)CloseHandle((HANDLE)pid);
  4298. return 0;
  4299. }
  4300. static void
  4301. trim_trailing_whitespaces(char *s)
  4302. {
  4303. char *e = s + strlen(s) - 1;
  4304. while ((e > s) && isspace(*(unsigned char *)e)) {
  4305. *e-- = '\0';
  4306. }
  4307. }
  4308. static pid_t
  4309. spawn_process(struct mg_connection *conn,
  4310. const char *prog,
  4311. char *envblk,
  4312. char *envp[],
  4313. int fdin[2],
  4314. int fdout[2],
  4315. int fderr[2],
  4316. const char *dir)
  4317. {
  4318. HANDLE me;
  4319. char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX],
  4320. cmdline[PATH_MAX], buf[PATH_MAX];
  4321. int truncated;
  4322. struct mg_file file = STRUCT_FILE_INITIALIZER;
  4323. STARTUPINFOA si;
  4324. PROCESS_INFORMATION pi = {0};
  4325. (void)envp;
  4326. memset(&si, 0, sizeof(si));
  4327. si.cb = sizeof(si);
  4328. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  4329. si.wShowWindow = SW_HIDE;
  4330. me = GetCurrentProcess();
  4331. DuplicateHandle(me,
  4332. (HANDLE)_get_osfhandle(fdin[0]),
  4333. me,
  4334. &si.hStdInput,
  4335. 0,
  4336. TRUE,
  4337. DUPLICATE_SAME_ACCESS);
  4338. DuplicateHandle(me,
  4339. (HANDLE)_get_osfhandle(fdout[1]),
  4340. me,
  4341. &si.hStdOutput,
  4342. 0,
  4343. TRUE,
  4344. DUPLICATE_SAME_ACCESS);
  4345. DuplicateHandle(me,
  4346. (HANDLE)_get_osfhandle(fderr[1]),
  4347. me,
  4348. &si.hStdError,
  4349. 0,
  4350. TRUE,
  4351. DUPLICATE_SAME_ACCESS);
  4352. /* Mark handles that should not be inherited. See
  4353. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx
  4354. */
  4355. SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]),
  4356. HANDLE_FLAG_INHERIT,
  4357. 0);
  4358. SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]),
  4359. HANDLE_FLAG_INHERIT,
  4360. 0);
  4361. SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]),
  4362. HANDLE_FLAG_INHERIT,
  4363. 0);
  4364. /* If CGI file is a script, try to read the interpreter line */
  4365. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4366. if (interp == NULL) {
  4367. buf[0] = buf[1] = '\0';
  4368. /* Read the first line of the script into the buffer */
  4369. mg_snprintf(
  4370. conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog);
  4371. if (truncated) {
  4372. pi.hProcess = (pid_t)-1;
  4373. goto spawn_cleanup;
  4374. }
  4375. if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) {
  4376. p = (char *)file.access.membuf;
  4377. mg_fgets(buf, sizeof(buf), &file, &p);
  4378. (void)mg_fclose(&file.access); /* ignore error on read only file */
  4379. buf[sizeof(buf) - 1] = '\0';
  4380. }
  4381. if ((buf[0] == '#') && (buf[1] == '!')) {
  4382. trim_trailing_whitespaces(buf + 2);
  4383. } else {
  4384. buf[2] = '\0';
  4385. }
  4386. interp = buf + 2;
  4387. }
  4388. if (interp[0] != '\0') {
  4389. GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL);
  4390. interp = full_interp;
  4391. }
  4392. GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL);
  4393. if (interp[0] != '\0') {
  4394. mg_snprintf(conn,
  4395. &truncated,
  4396. cmdline,
  4397. sizeof(cmdline),
  4398. "\"%s\" \"%s\\%s\"",
  4399. interp,
  4400. full_dir,
  4401. prog);
  4402. } else {
  4403. mg_snprintf(conn,
  4404. &truncated,
  4405. cmdline,
  4406. sizeof(cmdline),
  4407. "\"%s\\%s\"",
  4408. full_dir,
  4409. prog);
  4410. }
  4411. if (truncated) {
  4412. pi.hProcess = (pid_t)-1;
  4413. goto spawn_cleanup;
  4414. }
  4415. DEBUG_TRACE("Running [%s]", cmdline);
  4416. if (CreateProcessA(NULL,
  4417. cmdline,
  4418. NULL,
  4419. NULL,
  4420. TRUE,
  4421. CREATE_NEW_PROCESS_GROUP,
  4422. envblk,
  4423. NULL,
  4424. &si,
  4425. &pi) == 0) {
  4426. mg_cry(
  4427. conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO);
  4428. pi.hProcess = (pid_t)-1;
  4429. /* goto spawn_cleanup; */
  4430. }
  4431. spawn_cleanup:
  4432. (void)CloseHandle(si.hStdOutput);
  4433. (void)CloseHandle(si.hStdError);
  4434. (void)CloseHandle(si.hStdInput);
  4435. if (pi.hThread != NULL) {
  4436. (void)CloseHandle(pi.hThread);
  4437. }
  4438. return (pid_t)pi.hProcess;
  4439. }
  4440. #endif /* !NO_CGI */
  4441. static int
  4442. set_blocking_mode(SOCKET sock)
  4443. {
  4444. unsigned long non_blocking = 0;
  4445. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4446. }
  4447. static int
  4448. set_non_blocking_mode(SOCKET sock)
  4449. {
  4450. unsigned long non_blocking = 1;
  4451. return ioctlsocket(sock, (long)FIONBIO, &non_blocking);
  4452. }
  4453. #else
  4454. static int
  4455. mg_stat(const struct mg_connection *conn,
  4456. const char *path,
  4457. struct mg_file_stat *filep)
  4458. {
  4459. struct stat st;
  4460. if (!filep) {
  4461. return 0;
  4462. }
  4463. memset(filep, 0, sizeof(*filep));
  4464. if (conn && is_file_in_memory(conn, path)) {
  4465. /* Quick fix (for 1.9.x): */
  4466. /* mg_stat must fill all fields, also for files in memory */
  4467. struct mg_file tmp_file = STRUCT_FILE_INITIALIZER;
  4468. open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE);
  4469. filep->size = tmp_file.stat.size;
  4470. filep->last_modified = time(NULL);
  4471. filep->location = 2;
  4472. /* TODO: for 1.10: restructure how files in memory are handled */
  4473. return 1;
  4474. }
  4475. if (0 == stat(path, &st)) {
  4476. filep->size = (uint64_t)(st.st_size);
  4477. filep->last_modified = st.st_mtime;
  4478. filep->is_directory = S_ISDIR(st.st_mode);
  4479. return 1;
  4480. }
  4481. return 0;
  4482. }
  4483. static void
  4484. set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */)
  4485. {
  4486. if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) {
  4487. if (conn) {
  4488. mg_cry(conn,
  4489. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  4490. __func__,
  4491. strerror(ERRNO));
  4492. }
  4493. }
  4494. }
  4495. int
  4496. mg_start_thread(mg_thread_func_t func, void *param)
  4497. {
  4498. pthread_t thread_id;
  4499. pthread_attr_t attr;
  4500. int result;
  4501. (void)pthread_attr_init(&attr);
  4502. (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  4503. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4504. /* Compile-time option to control stack size,
  4505. * e.g. -DUSE_STACK_SIZE=16384 */
  4506. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4507. #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
  4508. result = pthread_create(&thread_id, &attr, func, param);
  4509. pthread_attr_destroy(&attr);
  4510. return result;
  4511. }
  4512. /* Start a thread storing the thread context. */
  4513. static int
  4514. mg_start_thread_with_id(mg_thread_func_t func,
  4515. void *param,
  4516. pthread_t *threadidptr)
  4517. {
  4518. pthread_t thread_id;
  4519. pthread_attr_t attr;
  4520. int result;
  4521. (void)pthread_attr_init(&attr);
  4522. #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
  4523. /* Compile-time option to control stack size,
  4524. * e.g. -DUSE_STACK_SIZE=16384 */
  4525. (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
  4526. #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */
  4527. result = pthread_create(&thread_id, &attr, func, param);
  4528. pthread_attr_destroy(&attr);
  4529. if ((result == 0) && (threadidptr != NULL)) {
  4530. *threadidptr = thread_id;
  4531. }
  4532. return result;
  4533. }
  4534. /* Wait for a thread to finish. */
  4535. static int
  4536. mg_join_thread(pthread_t threadid)
  4537. {
  4538. int result;
  4539. result = pthread_join(threadid, NULL);
  4540. return result;
  4541. }
  4542. #ifndef NO_CGI
  4543. static pid_t
  4544. spawn_process(struct mg_connection *conn,
  4545. const char *prog,
  4546. char *envblk,
  4547. char *envp[],
  4548. int fdin[2],
  4549. int fdout[2],
  4550. int fderr[2],
  4551. const char *dir)
  4552. {
  4553. pid_t pid;
  4554. const char *interp;
  4555. (void)envblk;
  4556. if (conn == NULL) {
  4557. return 0;
  4558. }
  4559. if ((pid = fork()) == -1) {
  4560. /* Parent */
  4561. mg_send_http_error(conn,
  4562. 500,
  4563. "Error: Creating CGI process\nfork(): %s",
  4564. strerror(ERRNO));
  4565. } else if (pid == 0) {
  4566. /* Child */
  4567. if (chdir(dir) != 0) {
  4568. mg_cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  4569. } else if (dup2(fdin[0], 0) == -1) {
  4570. mg_cry(conn,
  4571. "%s: dup2(%d, 0): %s",
  4572. __func__,
  4573. fdin[0],
  4574. strerror(ERRNO));
  4575. } else if (dup2(fdout[1], 1) == -1) {
  4576. mg_cry(conn,
  4577. "%s: dup2(%d, 1): %s",
  4578. __func__,
  4579. fdout[1],
  4580. strerror(ERRNO));
  4581. } else if (dup2(fderr[1], 2) == -1) {
  4582. mg_cry(conn,
  4583. "%s: dup2(%d, 2): %s",
  4584. __func__,
  4585. fderr[1],
  4586. strerror(ERRNO));
  4587. } else {
  4588. /* Keep stderr and stdout in two different pipes.
  4589. * Stdout will be sent back to the client,
  4590. * stderr should go into a server error log. */
  4591. (void)close(fdin[0]);
  4592. (void)close(fdout[1]);
  4593. (void)close(fderr[1]);
  4594. /* Close write end fdin and read end fdout and fderr */
  4595. (void)close(fdin[1]);
  4596. (void)close(fdout[0]);
  4597. (void)close(fderr[0]);
  4598. /* After exec, all signal handlers are restored to their default
  4599. * values, with one exception of SIGCHLD. According to
  4600. * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler will
  4601. * leave unchanged after exec if it was set to be ignored. Restore
  4602. * it to default action. */
  4603. signal(SIGCHLD, SIG_DFL);
  4604. interp = conn->dom_ctx->config[CGI_INTERPRETER];
  4605. if (interp == NULL) {
  4606. (void)execle(prog, prog, NULL, envp);
  4607. mg_cry(conn,
  4608. "%s: execle(%s): %s",
  4609. __func__,
  4610. prog,
  4611. strerror(ERRNO));
  4612. } else {
  4613. (void)execle(interp, interp, prog, NULL, envp);
  4614. mg_cry(conn,
  4615. "%s: execle(%s %s): %s",
  4616. __func__,
  4617. interp,
  4618. prog,
  4619. strerror(ERRNO));
  4620. }
  4621. }
  4622. exit(EXIT_FAILURE);
  4623. }
  4624. return pid;
  4625. }
  4626. #endif /* !NO_CGI */
  4627. static int
  4628. set_non_blocking_mode(SOCKET sock)
  4629. {
  4630. int flags = fcntl(sock, F_GETFL, 0);
  4631. if (flags < 0) {
  4632. return -1;
  4633. }
  4634. if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) {
  4635. return -1;
  4636. }
  4637. return 0;
  4638. }
  4639. static int
  4640. set_blocking_mode(SOCKET sock)
  4641. {
  4642. int flags = fcntl(sock, F_GETFL, 0);
  4643. if (flags < 0) {
  4644. return -1;
  4645. }
  4646. if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) {
  4647. return -1;
  4648. }
  4649. return 0;
  4650. }
  4651. #endif /* _WIN32 / else */
  4652. /* End of initial operating system specific define block. */
  4653. /* Get a random number (independent of C rand function) */
  4654. static uint64_t
  4655. get_random(void)
  4656. {
  4657. static uint64_t lfsr = 0; /* Linear feedback shift register */
  4658. static uint64_t lcg = 0; /* Linear congruential generator */
  4659. uint64_t now = mg_get_current_time_ns();
  4660. if (lfsr == 0) {
  4661. /* lfsr will be only 0 if has not been initialized,
  4662. * so this code is called only once. */
  4663. lfsr = mg_get_current_time_ns();
  4664. lcg = mg_get_current_time_ns();
  4665. } else {
  4666. /* Get the next step of both random number generators. */
  4667. lfsr = (lfsr >> 1)
  4668. | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1)
  4669. << 63);
  4670. lcg = lcg * 6364136223846793005LL + 1442695040888963407LL;
  4671. }
  4672. /* Combining two pseudo-random number generators and a high resolution
  4673. * part
  4674. * of the current server time will make it hard (impossible?) to guess
  4675. * the
  4676. * next number. */
  4677. return (lfsr ^ lcg ^ now);
  4678. }
  4679. static int
  4680. mg_poll(struct pollfd *pfd,
  4681. unsigned int n,
  4682. int milliseconds,
  4683. volatile int *stop_server)
  4684. {
  4685. /* Call poll, but only for a maximum time of a few seconds.
  4686. * This will allow to stop the server after some seconds, instead
  4687. * of having to wait for a long socket timeout. */
  4688. int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4689. do {
  4690. int result;
  4691. if (*stop_server) {
  4692. /* Shut down signal */
  4693. return -2;
  4694. }
  4695. if ((milliseconds >= 0) && (milliseconds < ms_now)) {
  4696. ms_now = milliseconds;
  4697. }
  4698. result = poll(pfd, n, ms_now);
  4699. if (result != 0) {
  4700. /* Poll returned either success (1) or error (-1).
  4701. * Forward both to the caller. */
  4702. return result;
  4703. }
  4704. /* Poll returned timeout (0). */
  4705. if (milliseconds > 0) {
  4706. milliseconds -= ms_now;
  4707. }
  4708. } while (milliseconds != 0);
  4709. /* timeout: return 0 */
  4710. return 0;
  4711. }
  4712. /* Write data to the IO channel - opened file descriptor, socket or SSL
  4713. * descriptor.
  4714. * Return value:
  4715. * >=0 .. number of bytes successfully written
  4716. * -1 .. timeout
  4717. * -2 .. error
  4718. */
  4719. static int
  4720. push_inner(struct mg_context *ctx,
  4721. FILE *fp,
  4722. SOCKET sock,
  4723. SSL *ssl,
  4724. const char *buf,
  4725. int len,
  4726. double timeout)
  4727. {
  4728. uint64_t start = 0, now = 0, timeout_ns = 0;
  4729. int n, err;
  4730. unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */
  4731. #ifdef _WIN32
  4732. typedef int len_t;
  4733. #else
  4734. typedef size_t len_t;
  4735. #endif
  4736. if (timeout > 0) {
  4737. now = mg_get_current_time_ns();
  4738. start = now;
  4739. timeout_ns = (uint64_t)(timeout * 1.0E9);
  4740. }
  4741. if (ctx == NULL) {
  4742. return -2;
  4743. }
  4744. #ifdef NO_SSL
  4745. if (ssl) {
  4746. return -2;
  4747. }
  4748. #endif
  4749. /* Try to read until it succeeds, fails, times out, or the server
  4750. * shuts down. */
  4751. for (;;) {
  4752. #ifndef NO_SSL
  4753. if (ssl != NULL) {
  4754. n = SSL_write(ssl, buf, len);
  4755. if (n <= 0) {
  4756. err = SSL_get_error(ssl, n);
  4757. if ((err == SSL_ERROR_SYSCALL) && (n == -1)) {
  4758. err = ERRNO;
  4759. } else if ((err == SSL_ERROR_WANT_READ)
  4760. || (err == SSL_ERROR_WANT_WRITE)) {
  4761. n = 0;
  4762. } else {
  4763. DEBUG_TRACE("SSL_write() failed, error %d", err);
  4764. return -2;
  4765. }
  4766. } else {
  4767. err = 0;
  4768. }
  4769. } else
  4770. #endif
  4771. if (fp != NULL) {
  4772. n = (int)fwrite(buf, 1, (size_t)len, fp);
  4773. if (ferror(fp)) {
  4774. n = -1;
  4775. err = ERRNO;
  4776. } else {
  4777. err = 0;
  4778. }
  4779. } else {
  4780. n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL);
  4781. err = (n < 0) ? ERRNO : 0;
  4782. #ifdef _WIN32
  4783. if (err == WSAEWOULDBLOCK) {
  4784. err = 0;
  4785. n = 0;
  4786. }
  4787. #else
  4788. if (err == EWOULDBLOCK) {
  4789. err = 0;
  4790. n = 0;
  4791. }
  4792. #endif
  4793. if (n < 0) {
  4794. /* shutdown of the socket at client side */
  4795. return -2;
  4796. }
  4797. }
  4798. if (ctx->stop_flag) {
  4799. return -2;
  4800. }
  4801. if ((n > 0) || ((n == 0) && (len == 0))) {
  4802. /* some data has been read, or no data was requested */
  4803. return n;
  4804. }
  4805. if (n < 0) {
  4806. /* socket error - check errno */
  4807. DEBUG_TRACE("send() failed, error %d", err);
  4808. /* TODO (mid): error handling depending on the error code.
  4809. * These codes are different between Windows and Linux.
  4810. * Currently there is no problem with failing send calls,
  4811. * if there is a reproducible situation, it should be
  4812. * investigated in detail.
  4813. */
  4814. return -2;
  4815. }
  4816. /* Only in case n=0 (timeout), repeat calling the write function */
  4817. /* If send failed, wait before retry */
  4818. if (fp != NULL) {
  4819. /* For files, just wait a fixed time,
  4820. * maybe an average disk seek time. */
  4821. mg_sleep(ms_wait > 10 ? 10 : ms_wait);
  4822. } else {
  4823. /* For sockets, wait for the socket using select */
  4824. fd_set wfds;
  4825. struct timeval tv;
  4826. int sret;
  4827. #if defined(__GNUC__) || defined(__MINGW32__)
  4828. /* GCC seems to have a flaw with it's own socket macros:
  4829. * http://www.linuxquestions.org/questions/programming-9/impossible-to-use-gcc-with-wconversion-and-standard-socket-macros-841935/
  4830. */
  4831. #pragma GCC diagnostic push
  4832. #pragma GCC diagnostic ignored "-Wsign-conversion"
  4833. #endif
  4834. FD_ZERO(&wfds);
  4835. FD_SET(sock, &wfds);
  4836. tv.tv_sec = (time_t)(ms_wait / 1000);
  4837. tv.tv_usec = (long)((ms_wait % 1000) * 1000);
  4838. sret = select((int)sock + 1, NULL, &wfds, NULL, &tv);
  4839. #if defined(__GNUC__) || defined(__MINGW32__)
  4840. #pragma GCC diagnostic pop
  4841. #endif
  4842. if (sret > 0) {
  4843. /* We got ready to write. Don't check the timeout
  4844. * but directly go back to write again. */
  4845. continue;
  4846. }
  4847. }
  4848. if (timeout > 0) {
  4849. now = mg_get_current_time_ns();
  4850. if ((now - start) > timeout_ns) {
  4851. /* Timeout */
  4852. break;
  4853. }
  4854. }
  4855. }
  4856. (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not
  4857. used */
  4858. return -1;
  4859. }
  4860. static int64_t
  4861. push_all(struct mg_context *ctx,
  4862. FILE *fp,
  4863. SOCKET sock,
  4864. SSL *ssl,
  4865. const char *buf,
  4866. int64_t len)
  4867. {
  4868. double timeout = -1.0;
  4869. int64_t n, nwritten = 0;
  4870. if (ctx == NULL) {
  4871. return -1;
  4872. }
  4873. if (ctx->dd.config[REQUEST_TIMEOUT]) {
  4874. timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0;
  4875. }
  4876. while ((len > 0) && (ctx->stop_flag == 0)) {
  4877. n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout);
  4878. if (n < 0) {
  4879. if (nwritten == 0) {
  4880. nwritten = n; /* Propagate the error */
  4881. }
  4882. break;
  4883. } else if (n == 0) {
  4884. break; /* No more data to write */
  4885. } else {
  4886. nwritten += n;
  4887. len -= n;
  4888. }
  4889. }
  4890. return nwritten;
  4891. }
  4892. /* Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  4893. * Return value:
  4894. * >=0 .. number of bytes successfully read
  4895. * -1 .. timeout
  4896. * -2 .. error
  4897. */
  4898. static int
  4899. pull_inner(FILE *fp,
  4900. struct mg_connection *conn,
  4901. char *buf,
  4902. int len,
  4903. double timeout)
  4904. {
  4905. int nread, err = 0;
  4906. #ifdef _WIN32
  4907. typedef int len_t;
  4908. #else
  4909. typedef size_t len_t;
  4910. #endif
  4911. #ifndef NO_SSL
  4912. int ssl_pending;
  4913. #endif
  4914. /* We need an additional wait loop around this, because in some cases
  4915. * with TLSwe may get data from the socket but not from SSL_read.
  4916. * In this case we need to repeat at least once.
  4917. */
  4918. if (fp != NULL) {
  4919. #if !defined(_WIN32_WCE)
  4920. /* Use read() instead of fread(), because if we're reading from the
  4921. * CGI pipe, fread() may block until IO buffer is filled up. We
  4922. * cannot afford to block and must pass all read bytes immediately
  4923. * to the client. */
  4924. nread = (int)read(fileno(fp), buf, (size_t)len);
  4925. #else
  4926. /* WinCE does not support CGI pipes */
  4927. nread = (int)fread(buf, 1, (size_t)len, fp);
  4928. #endif
  4929. err = (nread < 0) ? ERRNO : 0;
  4930. if ((nread == 0) && (len > 0)) {
  4931. /* Should get data, but got EOL */
  4932. return -2;
  4933. }
  4934. #ifndef NO_SSL
  4935. } else if ((conn->ssl != NULL)
  4936. && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) {
  4937. /* We already know there is no more data buffered in conn->buf
  4938. * but there is more available in the SSL layer. So don't poll
  4939. * conn->client.sock yet. */
  4940. if (ssl_pending > len) {
  4941. ssl_pending = len;
  4942. }
  4943. nread = SSL_read(conn->ssl, buf, ssl_pending);
  4944. if (nread <= 0) {
  4945. err = SSL_get_error(conn->ssl, nread);
  4946. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4947. err = ERRNO;
  4948. } else if ((err == SSL_ERROR_WANT_READ)
  4949. || (err == SSL_ERROR_WANT_WRITE)) {
  4950. nread = 0;
  4951. } else {
  4952. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4953. return -1;
  4954. }
  4955. } else {
  4956. err = 0;
  4957. }
  4958. } else if (conn->ssl != NULL) {
  4959. struct pollfd pfd[1];
  4960. int pollres;
  4961. pfd[0].fd = conn->client.sock;
  4962. pfd[0].events = POLLIN;
  4963. pollres = mg_poll(pfd,
  4964. 1,
  4965. (int)(timeout * 1000.0),
  4966. &(conn->phys_ctx->stop_flag));
  4967. if (conn->phys_ctx->stop_flag) {
  4968. return -2;
  4969. }
  4970. if (pollres > 0) {
  4971. nread = SSL_read(conn->ssl, buf, len);
  4972. if (nread <= 0) {
  4973. err = SSL_get_error(conn->ssl, nread);
  4974. if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) {
  4975. err = ERRNO;
  4976. } else if ((err == SSL_ERROR_WANT_READ)
  4977. || (err == SSL_ERROR_WANT_WRITE)) {
  4978. nread = 0;
  4979. } else {
  4980. DEBUG_TRACE("SSL_read() failed, error %d", err);
  4981. return -2;
  4982. }
  4983. } else {
  4984. err = 0;
  4985. }
  4986. } else if (pollres < 0) {
  4987. /* Error */
  4988. return -2;
  4989. } else {
  4990. /* pollres = 0 means timeout */
  4991. nread = 0;
  4992. }
  4993. #endif
  4994. } else {
  4995. struct pollfd pfd[1];
  4996. int pollres;
  4997. pfd[0].fd = conn->client.sock;
  4998. pfd[0].events = POLLIN;
  4999. pollres = mg_poll(pfd,
  5000. 1,
  5001. (int)(timeout * 1000.0),
  5002. &(conn->phys_ctx->stop_flag));
  5003. if (conn->phys_ctx->stop_flag) {
  5004. return -2;
  5005. }
  5006. if (pollres > 0) {
  5007. nread = (int)recv(conn->client.sock, buf, (len_t)len, 0);
  5008. err = (nread < 0) ? ERRNO : 0;
  5009. if (nread <= 0) {
  5010. /* shutdown of the socket at client side */
  5011. return -2;
  5012. }
  5013. } else if (pollres < 0) {
  5014. /* error callint poll */
  5015. return -2;
  5016. } else {
  5017. /* pollres = 0 means timeout */
  5018. nread = 0;
  5019. }
  5020. }
  5021. if (conn->phys_ctx->stop_flag) {
  5022. return -2;
  5023. }
  5024. if ((nread > 0) || ((nread == 0) && (len == 0))) {
  5025. /* some data has been read, or no data was requested */
  5026. return nread;
  5027. }
  5028. if (nread < 0) {
  5029. /* socket error - check errno */
  5030. #ifdef _WIN32
  5031. if (err == WSAEWOULDBLOCK) {
  5032. /* TODO (low): check if this is still required */
  5033. /* standard case if called from close_socket_gracefully */
  5034. return -2;
  5035. } else if (err == WSAETIMEDOUT) {
  5036. /* TODO (low): check if this is still required */
  5037. /* timeout is handled by the while loop */
  5038. return 0;
  5039. } else if (err == WSAECONNABORTED) {
  5040. /* See https://www.chilkatsoft.com/p/p_299.asp */
  5041. return -2;
  5042. } else {
  5043. DEBUG_TRACE("recv() failed, error %d", err);
  5044. return -2;
  5045. }
  5046. #else
  5047. /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases,
  5048. * if the timeout is reached and if the socket was set to non-
  5049. * blocking in close_socket_gracefully, so we can not distinguish
  5050. * here. We have to wait for the timeout in both cases for now.
  5051. */
  5052. if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) {
  5053. /* TODO (low): check if this is still required */
  5054. /* EAGAIN/EWOULDBLOCK:
  5055. * standard case if called from close_socket_gracefully
  5056. * => should return -1 */
  5057. /* or timeout occured
  5058. * => the code must stay in the while loop */
  5059. /* EINTR can be generated on a socket with a timeout set even
  5060. * when SA_RESTART is effective for all relevant signals
  5061. * (see signal(7)).
  5062. * => stay in the while loop */
  5063. } else {
  5064. DEBUG_TRACE("recv() failed, error %d", err);
  5065. return -2;
  5066. }
  5067. #endif
  5068. }
  5069. /* Timeout occured, but no data available. */
  5070. return -1;
  5071. }
  5072. static int
  5073. pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len)
  5074. {
  5075. int n, nread = 0;
  5076. double timeout = -1.0;
  5077. uint64_t start_time = 0, now = 0, timeout_ns = 0;
  5078. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  5079. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  5080. }
  5081. if (timeout >= 0.0) {
  5082. start_time = mg_get_current_time_ns();
  5083. timeout_ns = (uint64_t)(timeout * 1.0E9);
  5084. }
  5085. while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) {
  5086. n = pull_inner(fp, conn, buf + nread, len, timeout);
  5087. if (n == -2) {
  5088. if (nread == 0) {
  5089. nread = -1; /* Propagate the error */
  5090. }
  5091. break;
  5092. } else if (n == -1) {
  5093. /* timeout */
  5094. if (timeout >= 0.0) {
  5095. now = mg_get_current_time_ns();
  5096. if ((now - start_time) <= timeout_ns) {
  5097. continue;
  5098. }
  5099. }
  5100. break;
  5101. } else if (n == 0) {
  5102. break; /* No more data to read */
  5103. } else {
  5104. conn->consumed_content += n;
  5105. nread += n;
  5106. len -= n;
  5107. }
  5108. }
  5109. return nread;
  5110. }
  5111. static void
  5112. discard_unread_request_data(struct mg_connection *conn)
  5113. {
  5114. char buf[MG_BUF_LEN];
  5115. size_t to_read;
  5116. int nread;
  5117. if (conn == NULL) {
  5118. return;
  5119. }
  5120. to_read = sizeof(buf);
  5121. if (conn->is_chunked) {
  5122. /* Chunked encoding: 3=chunk read completely
  5123. * completely */
  5124. while (conn->is_chunked != 3) {
  5125. nread = mg_read(conn, buf, to_read);
  5126. if (nread <= 0) {
  5127. break;
  5128. }
  5129. }
  5130. } else {
  5131. /* Not chunked: content length is known */
  5132. while (conn->consumed_content < conn->content_len) {
  5133. if (to_read
  5134. > (size_t)(conn->content_len - conn->consumed_content)) {
  5135. to_read = (size_t)(conn->content_len - conn->consumed_content);
  5136. }
  5137. nread = mg_read(conn, buf, to_read);
  5138. if (nread <= 0) {
  5139. break;
  5140. }
  5141. }
  5142. }
  5143. }
  5144. static int
  5145. mg_read_inner(struct mg_connection *conn, void *buf, size_t len)
  5146. {
  5147. int64_t n, buffered_len, nread;
  5148. int64_t len64 =
  5149. (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is
  5150. * int, we may not read more
  5151. * bytes */
  5152. const char *body;
  5153. if (conn == NULL) {
  5154. return 0;
  5155. }
  5156. /* If Content-Length is not set for a request with body data
  5157. * (e.g., a PUT or POST request), we do not know in advance
  5158. * how much data should be read. */
  5159. if (conn->consumed_content == 0) {
  5160. if (conn->is_chunked == 1) {
  5161. conn->content_len = len64;
  5162. conn->is_chunked = 2;
  5163. } else if (conn->content_len == -1) {
  5164. /* The body data is completed when the connection
  5165. * is closed. */
  5166. conn->content_len = INT64_MAX;
  5167. conn->must_close = 1;
  5168. }
  5169. }
  5170. nread = 0;
  5171. if (conn->consumed_content < conn->content_len) {
  5172. /* Adjust number of bytes to read. */
  5173. int64_t left_to_read = conn->content_len - conn->consumed_content;
  5174. if (left_to_read < len64) {
  5175. /* Do not read more than the total content length of the
  5176. * request.
  5177. */
  5178. len64 = left_to_read;
  5179. }
  5180. /* Return buffered data */
  5181. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  5182. - conn->consumed_content;
  5183. if (buffered_len > 0) {
  5184. if (len64 < buffered_len) {
  5185. buffered_len = len64;
  5186. }
  5187. body = conn->buf + conn->request_len + conn->consumed_content;
  5188. memcpy(buf, body, (size_t)buffered_len);
  5189. len64 -= buffered_len;
  5190. conn->consumed_content += buffered_len;
  5191. nread += buffered_len;
  5192. buf = (char *)buf + buffered_len;
  5193. }
  5194. /* We have returned all buffered data. Read new data from the remote
  5195. * socket.
  5196. */
  5197. if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) {
  5198. nread += n;
  5199. } else {
  5200. nread = ((nread > 0) ? nread : n);
  5201. }
  5202. }
  5203. return (int)nread;
  5204. }
  5205. static char
  5206. mg_getc(struct mg_connection *conn)
  5207. {
  5208. char c;
  5209. if (conn == NULL) {
  5210. return 0;
  5211. }
  5212. if (mg_read_inner(conn, &c, 1) <= 0) {
  5213. return (char)0;
  5214. }
  5215. return c;
  5216. }
  5217. int
  5218. mg_read(struct mg_connection *conn, void *buf, size_t len)
  5219. {
  5220. if (len > INT_MAX) {
  5221. len = INT_MAX;
  5222. }
  5223. if (conn == NULL) {
  5224. return 0;
  5225. }
  5226. if (conn->is_chunked) {
  5227. size_t all_read = 0;
  5228. while (len > 0) {
  5229. if (conn->is_chunked == 3) {
  5230. /* No more data left to read */
  5231. return 0;
  5232. }
  5233. if (conn->chunk_remainder) {
  5234. /* copy from the remainder of the last received chunk */
  5235. long read_ret;
  5236. size_t read_now =
  5237. ((conn->chunk_remainder > len) ? (len)
  5238. : (conn->chunk_remainder));
  5239. conn->content_len += (int)read_now;
  5240. read_ret =
  5241. mg_read_inner(conn, (char *)buf + all_read, read_now);
  5242. if (read_ret < 1) {
  5243. /* read error */
  5244. return -1;
  5245. }
  5246. all_read += (size_t)read_ret;
  5247. conn->chunk_remainder -= (size_t)read_ret;
  5248. len -= (size_t)read_ret;
  5249. if (conn->chunk_remainder == 0) {
  5250. /* Add data bytes in the current chunk have been read,
  5251. * so we are expecting \r\n now. */
  5252. char x1, x2;
  5253. conn->content_len += 2;
  5254. x1 = mg_getc(conn);
  5255. x2 = mg_getc(conn);
  5256. if ((x1 != '\r') || (x2 != '\n')) {
  5257. /* Protocol violation */
  5258. return -1;
  5259. }
  5260. }
  5261. } else {
  5262. /* fetch a new chunk */
  5263. int i = 0;
  5264. char lenbuf[64];
  5265. char *end = 0;
  5266. unsigned long chunkSize = 0;
  5267. for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) {
  5268. conn->content_len++;
  5269. lenbuf[i] = mg_getc(conn);
  5270. if ((i > 0) && (lenbuf[i] == '\r')
  5271. && (lenbuf[i - 1] != '\r')) {
  5272. continue;
  5273. }
  5274. if ((i > 1) && (lenbuf[i] == '\n')
  5275. && (lenbuf[i - 1] == '\r')) {
  5276. lenbuf[i + 1] = 0;
  5277. chunkSize = strtoul(lenbuf, &end, 16);
  5278. if (chunkSize == 0) {
  5279. /* regular end of content */
  5280. conn->is_chunked = 3;
  5281. }
  5282. break;
  5283. }
  5284. if (!isxdigit(lenbuf[i])) {
  5285. /* illegal character for chunk length */
  5286. return -1;
  5287. }
  5288. }
  5289. if ((end == NULL) || (*end != '\r')) {
  5290. /* chunksize not set correctly */
  5291. return -1;
  5292. }
  5293. if (chunkSize == 0) {
  5294. break;
  5295. }
  5296. conn->chunk_remainder = chunkSize;
  5297. }
  5298. }
  5299. return (int)all_read;
  5300. }
  5301. return mg_read_inner(conn, buf, len);
  5302. }
  5303. int
  5304. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  5305. {
  5306. time_t now;
  5307. int64_t n, total, allowed;
  5308. if (conn == NULL) {
  5309. return 0;
  5310. }
  5311. if (conn->throttle > 0) {
  5312. if ((now = time(NULL)) != conn->last_throttle_time) {
  5313. conn->last_throttle_time = now;
  5314. conn->last_throttle_bytes = 0;
  5315. }
  5316. allowed = conn->throttle - conn->last_throttle_bytes;
  5317. if (allowed > (int64_t)len) {
  5318. allowed = (int64_t)len;
  5319. }
  5320. if ((total = push_all(conn->phys_ctx,
  5321. NULL,
  5322. conn->client.sock,
  5323. conn->ssl,
  5324. (const char *)buf,
  5325. (int64_t)allowed)) == allowed) {
  5326. buf = (const char *)buf + total;
  5327. conn->last_throttle_bytes += total;
  5328. while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) {
  5329. allowed = (conn->throttle > ((int64_t)len - total))
  5330. ? (int64_t)len - total
  5331. : conn->throttle;
  5332. if ((n = push_all(conn->phys_ctx,
  5333. NULL,
  5334. conn->client.sock,
  5335. conn->ssl,
  5336. (const char *)buf,
  5337. (int64_t)allowed)) != allowed) {
  5338. break;
  5339. }
  5340. sleep(1);
  5341. conn->last_throttle_bytes = allowed;
  5342. conn->last_throttle_time = time(NULL);
  5343. buf = (const char *)buf + n;
  5344. total += n;
  5345. }
  5346. }
  5347. } else {
  5348. total = push_all(conn->phys_ctx,
  5349. NULL,
  5350. conn->client.sock,
  5351. conn->ssl,
  5352. (const char *)buf,
  5353. (int64_t)len);
  5354. }
  5355. if (total > 0) {
  5356. conn->num_bytes_sent += total;
  5357. }
  5358. return (int)total;
  5359. }
  5360. /* Send a chunk, if "Transfer-Encoding: chunked" is used */
  5361. int
  5362. mg_send_chunk(struct mg_connection *conn,
  5363. const char *chunk,
  5364. unsigned int chunk_len)
  5365. {
  5366. char lenbuf[16];
  5367. size_t lenbuf_len;
  5368. int ret;
  5369. int t;
  5370. /* First store the length information in a text buffer. */
  5371. sprintf(lenbuf, "%x\r\n", chunk_len);
  5372. lenbuf_len = strlen(lenbuf);
  5373. /* Then send length information, chunk and terminating \r\n. */
  5374. ret = mg_write(conn, lenbuf, lenbuf_len);
  5375. if (ret != (int)lenbuf_len) {
  5376. return -1;
  5377. }
  5378. t = ret;
  5379. ret = mg_write(conn, chunk, chunk_len);
  5380. if (ret != (int)chunk_len) {
  5381. return -1;
  5382. }
  5383. t += ret;
  5384. ret = mg_write(conn, "\r\n", 2);
  5385. if (ret != 2) {
  5386. return -1;
  5387. }
  5388. t += ret;
  5389. return t;
  5390. }
  5391. /* Alternative alloc_vprintf() for non-compliant C runtimes */
  5392. static int
  5393. alloc_vprintf2(char **buf, const char *fmt, va_list ap)
  5394. {
  5395. va_list ap_copy;
  5396. size_t size = MG_BUF_LEN / 4;
  5397. int len = -1;
  5398. *buf = NULL;
  5399. while (len < 0) {
  5400. if (*buf) {
  5401. mg_free(*buf);
  5402. }
  5403. size *= 4;
  5404. *buf = (char *)mg_malloc(size);
  5405. if (!*buf) {
  5406. break;
  5407. }
  5408. va_copy(ap_copy, ap);
  5409. len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy);
  5410. va_end(ap_copy);
  5411. (*buf)[size - 1] = 0;
  5412. }
  5413. return len;
  5414. }
  5415. /* Print message to buffer. If buffer is large enough to hold the message,
  5416. * return buffer. If buffer is to small, allocate large enough buffer on
  5417. * heap,
  5418. * and return allocated buffer. */
  5419. static int
  5420. alloc_vprintf(char **out_buf,
  5421. char *prealloc_buf,
  5422. size_t prealloc_size,
  5423. const char *fmt,
  5424. va_list ap)
  5425. {
  5426. va_list ap_copy;
  5427. int len;
  5428. /* Windows is not standard-compliant, and vsnprintf() returns -1 if
  5429. * buffer is too small. Also, older versions of msvcrt.dll do not have
  5430. * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly.
  5431. * Therefore, we make two passes: on first pass, get required message
  5432. * length.
  5433. * On second pass, actually print the message. */
  5434. va_copy(ap_copy, ap);
  5435. len = vsnprintf_impl(NULL, 0, fmt, ap_copy);
  5436. va_end(ap_copy);
  5437. if (len < 0) {
  5438. /* C runtime is not standard compliant, vsnprintf() returned -1.
  5439. * Switch to alternative code path that uses incremental
  5440. * allocations.
  5441. */
  5442. va_copy(ap_copy, ap);
  5443. len = alloc_vprintf2(out_buf, fmt, ap_copy);
  5444. va_end(ap_copy);
  5445. } else if ((size_t)(len) >= prealloc_size) {
  5446. /* The pre-allocated buffer not large enough. */
  5447. /* Allocate a new buffer. */
  5448. *out_buf = (char *)mg_malloc((size_t)(len) + 1);
  5449. if (!*out_buf) {
  5450. /* Allocation failed. Return -1 as "out of memory" error. */
  5451. return -1;
  5452. }
  5453. /* Buffer allocation successful. Store the string there. */
  5454. va_copy(ap_copy, ap);
  5455. IGNORE_UNUSED_RESULT(
  5456. vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy));
  5457. va_end(ap_copy);
  5458. } else {
  5459. /* The pre-allocated buffer is large enough.
  5460. * Use it to store the string and return the address. */
  5461. va_copy(ap_copy, ap);
  5462. IGNORE_UNUSED_RESULT(
  5463. vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy));
  5464. va_end(ap_copy);
  5465. *out_buf = prealloc_buf;
  5466. }
  5467. return len;
  5468. }
  5469. static int
  5470. mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap)
  5471. {
  5472. char mem[MG_BUF_LEN];
  5473. char *buf = NULL;
  5474. int len;
  5475. if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) {
  5476. len = mg_write(conn, buf, (size_t)len);
  5477. }
  5478. if ((buf != mem) && (buf != NULL)) {
  5479. mg_free(buf);
  5480. }
  5481. return len;
  5482. }
  5483. int
  5484. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  5485. {
  5486. va_list ap;
  5487. int result;
  5488. va_start(ap, fmt);
  5489. result = mg_vprintf(conn, fmt, ap);
  5490. va_end(ap);
  5491. return result;
  5492. }
  5493. int
  5494. mg_url_decode(const char *src,
  5495. int src_len,
  5496. char *dst,
  5497. int dst_len,
  5498. int is_form_url_encoded)
  5499. {
  5500. int i, j, a, b;
  5501. #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W'))
  5502. for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) {
  5503. if ((i < src_len - 2) && (src[i] == '%')
  5504. && isxdigit(*(const unsigned char *)(src + i + 1))
  5505. && isxdigit(*(const unsigned char *)(src + i + 2))) {
  5506. a = tolower(*(const unsigned char *)(src + i + 1));
  5507. b = tolower(*(const unsigned char *)(src + i + 2));
  5508. dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b));
  5509. i += 2;
  5510. } else if (is_form_url_encoded && (src[i] == '+')) {
  5511. dst[j] = ' ';
  5512. } else {
  5513. dst[j] = src[i];
  5514. }
  5515. }
  5516. dst[j] = '\0'; /* Null-terminate the destination */
  5517. return (i >= src_len) ? j : -1;
  5518. }
  5519. int
  5520. mg_get_var(const char *data,
  5521. size_t data_len,
  5522. const char *name,
  5523. char *dst,
  5524. size_t dst_len)
  5525. {
  5526. return mg_get_var2(data, data_len, name, dst, dst_len, 0);
  5527. }
  5528. int
  5529. mg_get_var2(const char *data,
  5530. size_t data_len,
  5531. const char *name,
  5532. char *dst,
  5533. size_t dst_len,
  5534. size_t occurrence)
  5535. {
  5536. const char *p, *e, *s;
  5537. size_t name_len;
  5538. int len;
  5539. if ((dst == NULL) || (dst_len == 0)) {
  5540. len = -2;
  5541. } else if ((data == NULL) || (name == NULL) || (data_len == 0)) {
  5542. len = -1;
  5543. dst[0] = '\0';
  5544. } else {
  5545. name_len = strlen(name);
  5546. e = data + data_len;
  5547. len = -1;
  5548. dst[0] = '\0';
  5549. /* data is "var1=val1&var2=val2...". Find variable first */
  5550. for (p = data; p + name_len < e; p++) {
  5551. if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=')
  5552. && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) {
  5553. /* Point p to variable value */
  5554. p += name_len + 1;
  5555. /* Point s to the end of the value */
  5556. s = (const char *)memchr(p, '&', (size_t)(e - p));
  5557. if (s == NULL) {
  5558. s = e;
  5559. }
  5560. DEBUG_ASSERT(s >= p);
  5561. if (s < p) {
  5562. return -3;
  5563. }
  5564. /* Decode variable into destination buffer */
  5565. len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1);
  5566. /* Redirect error code from -1 to -2 (destination buffer too
  5567. * small). */
  5568. if (len == -1) {
  5569. len = -2;
  5570. }
  5571. break;
  5572. }
  5573. }
  5574. }
  5575. return len;
  5576. }
  5577. /* HCP24: some changes to compare hole var_name */
  5578. int
  5579. mg_get_cookie(const char *cookie_header,
  5580. const char *var_name,
  5581. char *dst,
  5582. size_t dst_size)
  5583. {
  5584. const char *s, *p, *end;
  5585. int name_len, len = -1;
  5586. if ((dst == NULL) || (dst_size == 0)) {
  5587. return -2;
  5588. }
  5589. dst[0] = '\0';
  5590. if ((var_name == NULL) || ((s = cookie_header) == NULL)) {
  5591. return -1;
  5592. }
  5593. name_len = (int)strlen(var_name);
  5594. end = s + strlen(s);
  5595. for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) {
  5596. if (s[name_len] == '=') {
  5597. /* HCP24: now check is it a substring or a full cookie name */
  5598. if ((s == cookie_header) || (s[-1] == ' ')) {
  5599. s += name_len + 1;
  5600. if ((p = strchr(s, ' ')) == NULL) {
  5601. p = end;
  5602. }
  5603. if (p[-1] == ';') {
  5604. p--;
  5605. }
  5606. if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) {
  5607. s++;
  5608. p--;
  5609. }
  5610. if ((size_t)(p - s) < dst_size) {
  5611. len = (int)(p - s);
  5612. mg_strlcpy(dst, s, (size_t)len + 1);
  5613. } else {
  5614. len = -3;
  5615. }
  5616. break;
  5617. }
  5618. }
  5619. }
  5620. return len;
  5621. }
  5622. #if defined(USE_WEBSOCKET) || defined(USE_LUA)
  5623. static void
  5624. base64_encode(const unsigned char *src, int src_len, char *dst)
  5625. {
  5626. static const char *b64 =
  5627. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  5628. int i, j, a, b, c;
  5629. for (i = j = 0; i < src_len; i += 3) {
  5630. a = src[i];
  5631. b = ((i + 1) >= src_len) ? 0 : src[i + 1];
  5632. c = ((i + 2) >= src_len) ? 0 : src[i + 2];
  5633. dst[j++] = b64[a >> 2];
  5634. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  5635. if (i + 1 < src_len) {
  5636. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  5637. }
  5638. if (i + 2 < src_len) {
  5639. dst[j++] = b64[c & 63];
  5640. }
  5641. }
  5642. while (j % 4 != 0) {
  5643. dst[j++] = '=';
  5644. }
  5645. dst[j++] = '\0';
  5646. }
  5647. #endif
  5648. #if defined(USE_LUA)
  5649. static unsigned char
  5650. b64reverse(char letter)
  5651. {
  5652. if ((letter >= 'A') && (letter <= 'Z')) {
  5653. return letter - 'A';
  5654. }
  5655. if ((letter >= 'a') && (letter <= 'z')) {
  5656. return letter - 'a' + 26;
  5657. }
  5658. if ((letter >= '0') && (letter <= '9')) {
  5659. return letter - '0' + 52;
  5660. }
  5661. if (letter == '+') {
  5662. return 62;
  5663. }
  5664. if (letter == '/') {
  5665. return 63;
  5666. }
  5667. if (letter == '=') {
  5668. return 255; /* normal end */
  5669. }
  5670. return 254; /* error */
  5671. }
  5672. static int
  5673. base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len)
  5674. {
  5675. int i;
  5676. unsigned char a, b, c, d;
  5677. *dst_len = 0;
  5678. for (i = 0; i < src_len; i += 4) {
  5679. a = b64reverse(src[i]);
  5680. if (a >= 254) {
  5681. return i;
  5682. }
  5683. b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]);
  5684. if (b >= 254) {
  5685. return i + 1;
  5686. }
  5687. c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]);
  5688. if (c == 254) {
  5689. return i + 2;
  5690. }
  5691. d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]);
  5692. if (d == 254) {
  5693. return i + 3;
  5694. }
  5695. dst[(*dst_len)++] = (a << 2) + (b >> 4);
  5696. if (c != 255) {
  5697. dst[(*dst_len)++] = (b << 4) + (c >> 2);
  5698. if (d != 255) {
  5699. dst[(*dst_len)++] = (c << 6) + d;
  5700. }
  5701. }
  5702. }
  5703. return -1;
  5704. }
  5705. #endif
  5706. static int
  5707. is_put_or_delete_method(const struct mg_connection *conn)
  5708. {
  5709. if (conn) {
  5710. const char *s = conn->request_info.request_method;
  5711. return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE")
  5712. || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH"));
  5713. }
  5714. return 0;
  5715. }
  5716. #if !defined(NO_FILES)
  5717. static int
  5718. extention_matches_script(
  5719. struct mg_connection *conn, /* in: request (must be valid) */
  5720. const char *filename /* in: filename (must be valid) */
  5721. )
  5722. {
  5723. #if !defined(NO_CGI)
  5724. if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  5725. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  5726. filename) > 0) {
  5727. return 1;
  5728. }
  5729. #endif
  5730. #if defined(USE_LUA)
  5731. if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  5732. strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  5733. filename) > 0) {
  5734. return 1;
  5735. }
  5736. #endif
  5737. #if defined(USE_DUKTAPE)
  5738. if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  5739. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  5740. filename) > 0) {
  5741. return 1;
  5742. }
  5743. #endif
  5744. /* filename and conn could be unused, if all preocessor conditions
  5745. * are false (no script language supported). */
  5746. (void)filename;
  5747. (void)conn;
  5748. return 0;
  5749. }
  5750. /* For given directory path, substitute it to valid index file.
  5751. * Return 1 if index file has been found, 0 if not found.
  5752. * If the file is found, it's stats is returned in stp. */
  5753. static int
  5754. substitute_index_file(struct mg_connection *conn,
  5755. char *path,
  5756. size_t path_len,
  5757. struct mg_file_stat *filestat)
  5758. {
  5759. const char *list = conn->dom_ctx->config[INDEX_FILES];
  5760. struct vec filename_vec;
  5761. size_t n = strlen(path);
  5762. int found = 0;
  5763. /* The 'path' given to us points to the directory. Remove all trailing
  5764. * directory separator characters from the end of the path, and
  5765. * then append single directory separator character. */
  5766. while ((n > 0) && (path[n - 1] == '/')) {
  5767. n--;
  5768. }
  5769. path[n] = '/';
  5770. /* Traverse index files list. For each entry, append it to the given
  5771. * path and see if the file exists. If it exists, break the loop */
  5772. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  5773. /* Ignore too long entries that may overflow path buffer */
  5774. if ((filename_vec.len + 1) > (path_len - (n + 1))) {
  5775. continue;
  5776. }
  5777. /* Prepare full path to the index file */
  5778. mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  5779. /* Does it exist? */
  5780. if (mg_stat(conn, path, filestat)) {
  5781. /* Yes it does, break the loop */
  5782. found = 1;
  5783. break;
  5784. }
  5785. }
  5786. /* If no index file exists, restore directory path */
  5787. if (!found) {
  5788. path[n] = '\0';
  5789. }
  5790. return found;
  5791. }
  5792. #endif
  5793. static void
  5794. interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */
  5795. char *filename, /* out: filename */
  5796. size_t filename_buf_len, /* in: size of filename buffer */
  5797. struct mg_file_stat *filestat, /* out: file status structure */
  5798. int *is_found, /* out: file found (directly) */
  5799. int *is_script_resource, /* out: handled by a script? */
  5800. int *is_websocket_request, /* out: websocket connetion? */
  5801. int *is_put_or_delete_request /* out: put/delete a file? */
  5802. )
  5803. {
  5804. char const *accept_encoding;
  5805. #if !defined(NO_FILES)
  5806. const char *uri = conn->request_info.local_uri;
  5807. const char *root = conn->dom_ctx->config[DOCUMENT_ROOT];
  5808. const char *rewrite;
  5809. struct vec a, b;
  5810. int match_len;
  5811. char gz_path[PATH_MAX];
  5812. int truncated;
  5813. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5814. char *tmp_str;
  5815. size_t tmp_str_len, sep_pos;
  5816. int allow_substitute_script_subresources;
  5817. #endif
  5818. #else
  5819. (void)filename_buf_len; /* unused if NO_FILES is defined */
  5820. #endif
  5821. /* Step 1: Set all initially unknown outputs to zero */
  5822. memset(filestat, 0, sizeof(*filestat));
  5823. *filename = 0;
  5824. *is_found = 0;
  5825. *is_script_resource = 0;
  5826. /* Step 2: Check if the request attempts to modify the file system */
  5827. *is_put_or_delete_request = is_put_or_delete_method(conn);
  5828. /* Step 3: Check if it is a websocket request, and modify the document
  5829. * root if required */
  5830. #if defined(USE_WEBSOCKET)
  5831. *is_websocket_request = is_websocket_protocol(conn);
  5832. #if !defined(NO_FILES)
  5833. if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) {
  5834. root = conn->dom_ctx->config[WEBSOCKET_ROOT];
  5835. }
  5836. #endif /* !NO_FILES */
  5837. #else /* USE_WEBSOCKET */
  5838. *is_websocket_request = 0;
  5839. #endif /* USE_WEBSOCKET */
  5840. /* Step 4: Check if gzip encoded response is allowed */
  5841. conn->accept_gzip = 0;
  5842. if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) {
  5843. if (strstr(accept_encoding, "gzip") != NULL) {
  5844. conn->accept_gzip = 1;
  5845. }
  5846. }
  5847. #if !defined(NO_FILES)
  5848. /* Step 5: If there is no root directory, don't look for files. */
  5849. /* Note that root == NULL is a regular use case here. This occurs,
  5850. * if all requests are handled by callbacks, so the WEBSOCKET_ROOT
  5851. * config is not required. */
  5852. if (root == NULL) {
  5853. /* all file related outputs have already been set to 0, just return
  5854. */
  5855. return;
  5856. }
  5857. /* Step 6: Determine the local file path from the root path and the
  5858. * request uri. */
  5859. /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift
  5860. * part of the path one byte on the right. */
  5861. mg_snprintf(
  5862. conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri);
  5863. if (truncated) {
  5864. goto interpret_cleanup;
  5865. }
  5866. /* Step 7: URI rewriting */
  5867. rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN];
  5868. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  5869. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  5870. mg_snprintf(conn,
  5871. &truncated,
  5872. filename,
  5873. filename_buf_len - 1,
  5874. "%.*s%s",
  5875. (int)b.len,
  5876. b.ptr,
  5877. uri + match_len);
  5878. break;
  5879. }
  5880. }
  5881. if (truncated) {
  5882. goto interpret_cleanup;
  5883. }
  5884. /* Step 8: Check if the file exists at the server */
  5885. /* Local file path and name, corresponding to requested URI
  5886. * is now stored in "filename" variable. */
  5887. if (mg_stat(conn, filename, filestat)) {
  5888. /* 8.1: File exists. */
  5889. *is_found = 1;
  5890. /* 8.2: Check if it is a script type. */
  5891. if (extention_matches_script(conn, filename)) {
  5892. /* The request addresses a CGI resource, Lua script or
  5893. * server-side javascript.
  5894. * The URI corresponds to the script itself (like
  5895. * /path/script.cgi), and there is no additional resource
  5896. * path (like /path/script.cgi/something).
  5897. * Requests that modify (replace or delete) a resource, like
  5898. * PUT and DELETE requests, should replace/delete the script
  5899. * file.
  5900. * Requests that read or write from/to a resource, like GET and
  5901. * POST requests, should call the script and return the
  5902. * generated response. */
  5903. *is_script_resource = (!*is_put_or_delete_request);
  5904. }
  5905. /* 8.3: If the request target is a directory, there could be
  5906. * a substitute file (index.html, index.cgi, ...). */
  5907. if (filestat->is_directory) {
  5908. /* Use a local copy here, since substitute_index_file will
  5909. * change the content of the file status */
  5910. struct mg_file_stat tmp_filestat;
  5911. memset(&tmp_filestat, 0, sizeof(tmp_filestat));
  5912. if (substitute_index_file(
  5913. conn, filename, filename_buf_len, &tmp_filestat)) {
  5914. /* Substitute file found. Copy stat to the output, then
  5915. * check if the file is a script file */
  5916. *filestat = tmp_filestat;
  5917. if (extention_matches_script(conn, filename)) {
  5918. /* Substitute file is a script file */
  5919. *is_script_resource = 1;
  5920. } else {
  5921. /* Substitute file is a regular file */
  5922. *is_script_resource = 0;
  5923. *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0);
  5924. }
  5925. }
  5926. /* If there is no substitute file, the server could return
  5927. * a directory listing in a later step */
  5928. }
  5929. return;
  5930. }
  5931. /* Step 9: Check for zipped files: */
  5932. /* If we can't find the actual file, look for the file
  5933. * with the same name but a .gz extension. If we find it,
  5934. * use that and set the gzipped flag in the file struct
  5935. * to indicate that the response need to have the content-
  5936. * encoding: gzip header.
  5937. * We can only do this if the browser declares support. */
  5938. if (conn->accept_gzip) {
  5939. mg_snprintf(
  5940. conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename);
  5941. if (truncated) {
  5942. goto interpret_cleanup;
  5943. }
  5944. if (mg_stat(conn, gz_path, filestat)) {
  5945. if (filestat) {
  5946. filestat->is_gzipped = 1;
  5947. *is_found = 1;
  5948. }
  5949. /* Currently gz files can not be scripts. */
  5950. return;
  5951. }
  5952. }
  5953. #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE)
  5954. /* Step 10: Script resources may handle sub-resources */
  5955. /* Support PATH_INFO for CGI scripts. */
  5956. tmp_str_len = strlen(filename);
  5957. tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx);
  5958. if (!tmp_str) {
  5959. /* Out of memory */
  5960. goto interpret_cleanup;
  5961. }
  5962. memcpy(tmp_str, filename, tmp_str_len + 1);
  5963. /* Check config, if index scripts may have sub-resources */
  5964. allow_substitute_script_subresources =
  5965. !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES],
  5966. "yes");
  5967. sep_pos = tmp_str_len;
  5968. while (sep_pos > 0) {
  5969. sep_pos--;
  5970. if (tmp_str[sep_pos] == '/') {
  5971. int is_script = 0, does_exist = 0;
  5972. tmp_str[sep_pos] = 0;
  5973. if (tmp_str[0]) {
  5974. is_script = extention_matches_script(conn, tmp_str);
  5975. does_exist = mg_stat(conn, tmp_str, filestat);
  5976. }
  5977. if (does_exist && is_script) {
  5978. filename[sep_pos] = 0;
  5979. memmove(filename + sep_pos + 2,
  5980. filename + sep_pos + 1,
  5981. strlen(filename + sep_pos + 1) + 1);
  5982. conn->path_info = filename + sep_pos + 1;
  5983. filename[sep_pos + 1] = '/';
  5984. *is_script_resource = 1;
  5985. *is_found = 1;
  5986. break;
  5987. }
  5988. if (allow_substitute_script_subresources) {
  5989. if (substitute_index_file(
  5990. conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) {
  5991. /* some intermediate directory has an index file */
  5992. if (extention_matches_script(conn, tmp_str)) {
  5993. char *tmp_str2;
  5994. DEBUG_TRACE("Substitute script %s serving path %s",
  5995. tmp_str,
  5996. filename);
  5997. /* this index file is a script */
  5998. tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1,
  5999. conn->phys_ctx);
  6000. mg_snprintf(conn,
  6001. &truncated,
  6002. filename,
  6003. filename_buf_len,
  6004. "%s//%s",
  6005. tmp_str,
  6006. tmp_str2);
  6007. mg_free(tmp_str2);
  6008. if (truncated) {
  6009. mg_free(tmp_str);
  6010. goto interpret_cleanup;
  6011. }
  6012. sep_pos = strlen(tmp_str);
  6013. filename[sep_pos] = 0;
  6014. conn->path_info = filename + sep_pos + 1;
  6015. *is_script_resource = 1;
  6016. *is_found = 1;
  6017. break;
  6018. } else {
  6019. DEBUG_TRACE("Substitute file %s serving path %s",
  6020. tmp_str,
  6021. filename);
  6022. /* non-script files will not have sub-resources */
  6023. filename[sep_pos] = 0;
  6024. conn->path_info = 0;
  6025. *is_script_resource = 0;
  6026. *is_found = 0;
  6027. break;
  6028. }
  6029. }
  6030. }
  6031. tmp_str[sep_pos] = '/';
  6032. }
  6033. }
  6034. mg_free(tmp_str);
  6035. #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */
  6036. #endif /* !defined(NO_FILES) */
  6037. return;
  6038. #if !defined(NO_FILES)
  6039. /* Reset all outputs */
  6040. interpret_cleanup:
  6041. memset(filestat, 0, sizeof(*filestat));
  6042. *filename = 0;
  6043. *is_found = 0;
  6044. *is_script_resource = 0;
  6045. *is_websocket_request = 0;
  6046. *is_put_or_delete_request = 0;
  6047. #endif /* !defined(NO_FILES) */
  6048. }
  6049. /* Check whether full request is buffered. Return:
  6050. * -1 if request or response is malformed
  6051. * 0 if request or response is not yet fully buffered
  6052. * >0 actual request length, including last \r\n\r\n */
  6053. static int
  6054. get_http_header_len(const char *buf, int buflen)
  6055. {
  6056. int i;
  6057. for (i = 0; i < buflen; i++) {
  6058. /* Do an unsigned comparison in some conditions below */
  6059. const unsigned char c = ((const unsigned char *)buf)[i];
  6060. if ((c < 128) && ((char)c != '\r') && ((char)c != '\n')
  6061. && !isprint(c)) {
  6062. /* abort scan as soon as one malformed character is found */
  6063. return -1;
  6064. }
  6065. if (i < buflen - 1) {
  6066. if ((buf[i] == '\n') && (buf[i + 1] == '\n')) {
  6067. /* Two newline, no carriage return - not standard compliant,
  6068. * but
  6069. * it
  6070. * should be accepted */
  6071. return i + 2;
  6072. }
  6073. }
  6074. if (i < buflen - 3) {
  6075. if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r')
  6076. && (buf[i + 3] == '\n')) {
  6077. /* Two \r\n - standard compliant */
  6078. return i + 4;
  6079. }
  6080. }
  6081. }
  6082. return 0;
  6083. }
  6084. #if !defined(NO_CACHING)
  6085. /* Convert month to the month number. Return -1 on error, or month number */
  6086. static int
  6087. get_month_index(const char *s)
  6088. {
  6089. size_t i;
  6090. for (i = 0; i < ARRAY_SIZE(month_names); i++) {
  6091. if (!strcmp(s, month_names[i])) {
  6092. return (int)i;
  6093. }
  6094. }
  6095. return -1;
  6096. }
  6097. /* Parse UTC date-time string, and return the corresponding time_t value. */
  6098. static time_t
  6099. parse_date_string(const char *datetime)
  6100. {
  6101. char month_str[32] = {0};
  6102. int second, minute, hour, day, month, year;
  6103. time_t result = (time_t)0;
  6104. struct tm tm;
  6105. if ((sscanf(datetime,
  6106. "%d/%3s/%d %d:%d:%d",
  6107. &day,
  6108. month_str,
  6109. &year,
  6110. &hour,
  6111. &minute,
  6112. &second) == 6) || (sscanf(datetime,
  6113. "%d %3s %d %d:%d:%d",
  6114. &day,
  6115. month_str,
  6116. &year,
  6117. &hour,
  6118. &minute,
  6119. &second) == 6)
  6120. || (sscanf(datetime,
  6121. "%*3s, %d %3s %d %d:%d:%d",
  6122. &day,
  6123. month_str,
  6124. &year,
  6125. &hour,
  6126. &minute,
  6127. &second) == 6) || (sscanf(datetime,
  6128. "%d-%3s-%d %d:%d:%d",
  6129. &day,
  6130. month_str,
  6131. &year,
  6132. &hour,
  6133. &minute,
  6134. &second) == 6)) {
  6135. month = get_month_index(month_str);
  6136. if ((month >= 0) && (year >= 1970)) {
  6137. memset(&tm, 0, sizeof(tm));
  6138. tm.tm_year = year - 1900;
  6139. tm.tm_mon = month;
  6140. tm.tm_mday = day;
  6141. tm.tm_hour = hour;
  6142. tm.tm_min = minute;
  6143. tm.tm_sec = second;
  6144. result = timegm(&tm);
  6145. }
  6146. }
  6147. return result;
  6148. }
  6149. #endif /* !NO_CACHING */
  6150. /* Protect against directory disclosure attack by removing '..',
  6151. * excessive '/' and '\' characters */
  6152. static void
  6153. remove_double_dots_and_double_slashes(char *s)
  6154. {
  6155. char *p = s;
  6156. while ((s[0] == '.') && (s[1] == '.')) {
  6157. s++;
  6158. }
  6159. while (*s != '\0') {
  6160. *p++ = *s++;
  6161. if ((s[-1] == '/') || (s[-1] == '\\')) {
  6162. /* Skip all following slashes, backslashes and double-dots */
  6163. while (s[0] != '\0') {
  6164. if ((s[0] == '/') || (s[0] == '\\')) {
  6165. s++;
  6166. } else if ((s[0] == '.') && (s[1] == '.')) {
  6167. s += 2;
  6168. } else {
  6169. break;
  6170. }
  6171. }
  6172. }
  6173. }
  6174. *p = '\0';
  6175. }
  6176. static const struct {
  6177. const char *extension;
  6178. size_t ext_len;
  6179. const char *mime_type;
  6180. } builtin_mime_types[] = {
  6181. /* IANA registered MIME types
  6182. * (http://www.iana.org/assignments/media-types)
  6183. * application types */
  6184. {".doc", 4, "application/msword"},
  6185. {".eps", 4, "application/postscript"},
  6186. {".exe", 4, "application/octet-stream"},
  6187. {".js", 3, "application/javascript"},
  6188. {".json", 5, "application/json"},
  6189. {".pdf", 4, "application/pdf"},
  6190. {".ps", 3, "application/postscript"},
  6191. {".rtf", 4, "application/rtf"},
  6192. {".xhtml", 6, "application/xhtml+xml"},
  6193. {".xsl", 4, "application/xml"},
  6194. {".xslt", 5, "application/xml"},
  6195. /* fonts */
  6196. {".ttf", 4, "application/font-sfnt"},
  6197. {".cff", 4, "application/font-sfnt"},
  6198. {".otf", 4, "application/font-sfnt"},
  6199. {".aat", 4, "application/font-sfnt"},
  6200. {".sil", 4, "application/font-sfnt"},
  6201. {".pfr", 4, "application/font-tdpfr"},
  6202. {".woff", 5, "application/font-woff"},
  6203. /* audio */
  6204. {".mp3", 4, "audio/mpeg"},
  6205. {".oga", 4, "audio/ogg"},
  6206. {".ogg", 4, "audio/ogg"},
  6207. /* image */
  6208. {".gif", 4, "image/gif"},
  6209. {".ief", 4, "image/ief"},
  6210. {".jpeg", 5, "image/jpeg"},
  6211. {".jpg", 4, "image/jpeg"},
  6212. {".jpm", 4, "image/jpm"},
  6213. {".jpx", 4, "image/jpx"},
  6214. {".png", 4, "image/png"},
  6215. {".svg", 4, "image/svg+xml"},
  6216. {".tif", 4, "image/tiff"},
  6217. {".tiff", 5, "image/tiff"},
  6218. /* model */
  6219. {".wrl", 4, "model/vrml"},
  6220. /* text */
  6221. {".css", 4, "text/css"},
  6222. {".csv", 4, "text/csv"},
  6223. {".htm", 4, "text/html"},
  6224. {".html", 5, "text/html"},
  6225. {".sgm", 4, "text/sgml"},
  6226. {".shtm", 5, "text/html"},
  6227. {".shtml", 6, "text/html"},
  6228. {".txt", 4, "text/plain"},
  6229. {".xml", 4, "text/xml"},
  6230. /* video */
  6231. {".mov", 4, "video/quicktime"},
  6232. {".mp4", 4, "video/mp4"},
  6233. {".mpeg", 5, "video/mpeg"},
  6234. {".mpg", 4, "video/mpeg"},
  6235. {".ogv", 4, "video/ogg"},
  6236. {".qt", 3, "video/quicktime"},
  6237. /* not registered types
  6238. * (http://reference.sitepoint.com/html/mime-types-full,
  6239. * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */
  6240. {".arj", 4, "application/x-arj-compressed"},
  6241. {".gz", 3, "application/x-gunzip"},
  6242. {".rar", 4, "application/x-arj-compressed"},
  6243. {".swf", 4, "application/x-shockwave-flash"},
  6244. {".tar", 4, "application/x-tar"},
  6245. {".tgz", 4, "application/x-tar-gz"},
  6246. {".torrent", 8, "application/x-bittorrent"},
  6247. {".ppt", 4, "application/x-mspowerpoint"},
  6248. {".xls", 4, "application/x-msexcel"},
  6249. {".zip", 4, "application/x-zip-compressed"},
  6250. {".aac",
  6251. 4,
  6252. "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */
  6253. {".aif", 4, "audio/x-aif"},
  6254. {".m3u", 4, "audio/x-mpegurl"},
  6255. {".mid", 4, "audio/x-midi"},
  6256. {".ra", 3, "audio/x-pn-realaudio"},
  6257. {".ram", 4, "audio/x-pn-realaudio"},
  6258. {".wav", 4, "audio/x-wav"},
  6259. {".bmp", 4, "image/bmp"},
  6260. {".ico", 4, "image/x-icon"},
  6261. {".pct", 4, "image/x-pct"},
  6262. {".pict", 5, "image/pict"},
  6263. {".rgb", 4, "image/x-rgb"},
  6264. {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */
  6265. {".asf", 4, "video/x-ms-asf"},
  6266. {".avi", 4, "video/x-msvideo"},
  6267. {".m4v", 4, "video/x-m4v"},
  6268. {NULL, 0, NULL}};
  6269. const char *
  6270. mg_get_builtin_mime_type(const char *path)
  6271. {
  6272. const char *ext;
  6273. size_t i, path_len;
  6274. path_len = strlen(path);
  6275. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  6276. ext = path + (path_len - builtin_mime_types[i].ext_len);
  6277. if ((path_len > builtin_mime_types[i].ext_len)
  6278. && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) {
  6279. return builtin_mime_types[i].mime_type;
  6280. }
  6281. }
  6282. return "text/plain";
  6283. }
  6284. /* Look at the "path" extension and figure what mime type it has.
  6285. * Store mime type in the vector. */
  6286. static void
  6287. get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec)
  6288. {
  6289. struct vec ext_vec, mime_vec;
  6290. const char *list, *ext;
  6291. size_t path_len;
  6292. path_len = strlen(path);
  6293. if ((conn == NULL) || (vec == NULL)) {
  6294. if (vec != NULL) {
  6295. memset(vec, '\0', sizeof(struct vec));
  6296. }
  6297. return;
  6298. }
  6299. /* Scan user-defined mime types first, in case user wants to
  6300. * override default mime types. */
  6301. list = conn->dom_ctx->config[EXTRA_MIME_TYPES];
  6302. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  6303. /* ext now points to the path suffix */
  6304. ext = path + path_len - ext_vec.len;
  6305. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  6306. *vec = mime_vec;
  6307. return;
  6308. }
  6309. }
  6310. vec->ptr = mg_get_builtin_mime_type(path);
  6311. vec->len = strlen(vec->ptr);
  6312. }
  6313. /* Stringify binary data. Output buffer must be twice as big as input,
  6314. * because each byte takes 2 bytes in string representation */
  6315. static void
  6316. bin2str(char *to, const unsigned char *p, size_t len)
  6317. {
  6318. static const char *hex = "0123456789abcdef";
  6319. for (; len--; p++) {
  6320. *to++ = hex[p[0] >> 4];
  6321. *to++ = hex[p[0] & 0x0f];
  6322. }
  6323. *to = '\0';
  6324. }
  6325. /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  6326. */
  6327. char *
  6328. mg_md5(char buf[33], ...)
  6329. {
  6330. md5_byte_t hash[16];
  6331. const char *p;
  6332. va_list ap;
  6333. md5_state_t ctx;
  6334. md5_init(&ctx);
  6335. va_start(ap, buf);
  6336. while ((p = va_arg(ap, const char *)) != NULL) {
  6337. md5_append(&ctx, (const md5_byte_t *)p, strlen(p));
  6338. }
  6339. va_end(ap);
  6340. md5_finish(&ctx, hash);
  6341. bin2str(buf, hash, sizeof(hash));
  6342. return buf;
  6343. }
  6344. /* Check the user's password, return 1 if OK */
  6345. static int
  6346. check_password(const char *method,
  6347. const char *ha1,
  6348. const char *uri,
  6349. const char *nonce,
  6350. const char *nc,
  6351. const char *cnonce,
  6352. const char *qop,
  6353. const char *response)
  6354. {
  6355. char ha2[32 + 1], expected_response[32 + 1];
  6356. /* Some of the parameters may be NULL */
  6357. if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL)
  6358. || (qop == NULL) || (response == NULL)) {
  6359. return 0;
  6360. }
  6361. /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */
  6362. if (strlen(response) != 32) {
  6363. return 0;
  6364. }
  6365. mg_md5(ha2, method, ":", uri, NULL);
  6366. mg_md5(expected_response,
  6367. ha1,
  6368. ":",
  6369. nonce,
  6370. ":",
  6371. nc,
  6372. ":",
  6373. cnonce,
  6374. ":",
  6375. qop,
  6376. ":",
  6377. ha2,
  6378. NULL);
  6379. return mg_strcasecmp(response, expected_response) == 0;
  6380. }
  6381. /* Use the global passwords file, if specified by auth_gpass option,
  6382. * or search for .htpasswd in the requested directory. */
  6383. static void
  6384. open_auth_file(struct mg_connection *conn,
  6385. const char *path,
  6386. struct mg_file *filep)
  6387. {
  6388. if ((conn != NULL) && (conn->dom_ctx != NULL)) {
  6389. char name[PATH_MAX];
  6390. const char *p, *e,
  6391. *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  6392. int truncated;
  6393. if (gpass != NULL) {
  6394. /* Use global passwords file */
  6395. if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) {
  6396. #ifdef DEBUG
  6397. /* Use mg_cry here, since gpass has been configured. */
  6398. mg_cry(conn, "fopen(%s): %s", gpass, strerror(ERRNO));
  6399. #endif
  6400. }
  6401. /* Important: using local struct mg_file to test path for
  6402. * is_directory flag. If filep is used, mg_stat() makes it
  6403. * appear as if auth file was opened.
  6404. * TODO(mid): Check if this is still required after rewriting
  6405. * mg_stat */
  6406. } else if (mg_stat(conn, path, &filep->stat)
  6407. && filep->stat.is_directory) {
  6408. mg_snprintf(conn,
  6409. &truncated,
  6410. name,
  6411. sizeof(name),
  6412. "%s/%s",
  6413. path,
  6414. PASSWORDS_FILE_NAME);
  6415. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6416. #ifdef DEBUG
  6417. /* Don't use mg_cry here, but only a trace, since this is
  6418. * a typical case. It will occur for every directory
  6419. * without a password file. */
  6420. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6421. #endif
  6422. }
  6423. } else {
  6424. /* Try to find .htpasswd in requested directory. */
  6425. for (p = path, e = p + strlen(p) - 1; e > p; e--) {
  6426. if (e[0] == '/') {
  6427. break;
  6428. }
  6429. }
  6430. mg_snprintf(conn,
  6431. &truncated,
  6432. name,
  6433. sizeof(name),
  6434. "%.*s/%s",
  6435. (int)(e - p),
  6436. p,
  6437. PASSWORDS_FILE_NAME);
  6438. if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) {
  6439. #ifdef DEBUG
  6440. /* Don't use mg_cry here, but only a trace, since this is
  6441. * a typical case. It will occur for every directory
  6442. * without a password file. */
  6443. DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO));
  6444. #endif
  6445. }
  6446. }
  6447. }
  6448. }
  6449. /* Parsed Authorization header */
  6450. struct ah {
  6451. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  6452. };
  6453. /* Return 1 on success. Always initializes the ah structure. */
  6454. static int
  6455. parse_auth_header(struct mg_connection *conn,
  6456. char *buf,
  6457. size_t buf_size,
  6458. struct ah *ah)
  6459. {
  6460. char *name, *value, *s;
  6461. const char *auth_header;
  6462. uint64_t nonce;
  6463. if (!ah || !conn) {
  6464. return 0;
  6465. }
  6466. (void)memset(ah, 0, sizeof(*ah));
  6467. if (((auth_header = mg_get_header(conn, "Authorization")) == NULL)
  6468. || mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  6469. return 0;
  6470. }
  6471. /* Make modifiable copy of the auth header */
  6472. (void)mg_strlcpy(buf, auth_header + 7, buf_size);
  6473. s = buf;
  6474. /* Parse authorization header */
  6475. for (;;) {
  6476. /* Gobble initial spaces */
  6477. while (isspace(*(unsigned char *)s)) {
  6478. s++;
  6479. }
  6480. name = skip_quoted(&s, "=", " ", 0);
  6481. /* Value is either quote-delimited, or ends at first comma or space.
  6482. */
  6483. if (s[0] == '\"') {
  6484. s++;
  6485. value = skip_quoted(&s, "\"", " ", '\\');
  6486. if (s[0] == ',') {
  6487. s++;
  6488. }
  6489. } else {
  6490. value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses
  6491. * spaces */
  6492. }
  6493. if (*name == '\0') {
  6494. break;
  6495. }
  6496. if (!strcmp(name, "username")) {
  6497. ah->user = value;
  6498. } else if (!strcmp(name, "cnonce")) {
  6499. ah->cnonce = value;
  6500. } else if (!strcmp(name, "response")) {
  6501. ah->response = value;
  6502. } else if (!strcmp(name, "uri")) {
  6503. ah->uri = value;
  6504. } else if (!strcmp(name, "qop")) {
  6505. ah->qop = value;
  6506. } else if (!strcmp(name, "nc")) {
  6507. ah->nc = value;
  6508. } else if (!strcmp(name, "nonce")) {
  6509. ah->nonce = value;
  6510. }
  6511. }
  6512. #ifndef NO_NONCE_CHECK
  6513. /* Read the nonce from the response. */
  6514. if (ah->nonce == NULL) {
  6515. return 0;
  6516. }
  6517. s = NULL;
  6518. nonce = strtoull(ah->nonce, &s, 10);
  6519. if ((s == NULL) || (*s != 0)) {
  6520. return 0;
  6521. }
  6522. /* Convert the nonce from the client to a number. */
  6523. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6524. /* The converted number corresponds to the time the nounce has been
  6525. * created. This should not be earlier than the server start. */
  6526. /* Server side nonce check is valuable in all situations but one:
  6527. * if the server restarts frequently, but the client should not see
  6528. * that, so the server should accept nonces from previous starts. */
  6529. /* However, the reasonable default is to not accept a nonce from a
  6530. * previous start, so if anyone changed the access rights between
  6531. * two restarts, a new login is required. */
  6532. if (nonce < (uint64_t)conn->phys_ctx->start_time) {
  6533. /* nonce is from a previous start of the server and no longer valid
  6534. * (replay attack?) */
  6535. return 0;
  6536. }
  6537. /* Check if the nonce is too high, so it has not (yet) been used by the
  6538. * server. */
  6539. if (nonce >= ((uint64_t)conn->phys_ctx->start_time
  6540. + conn->dom_ctx->nonce_count)) {
  6541. return 0;
  6542. }
  6543. #else
  6544. (void)nonce;
  6545. #endif
  6546. /* CGI needs it as REMOTE_USER */
  6547. if (ah->user != NULL) {
  6548. conn->request_info.remote_user =
  6549. mg_strdup_ctx(ah->user, conn->phys_ctx);
  6550. } else {
  6551. return 0;
  6552. }
  6553. return 1;
  6554. }
  6555. static const char *
  6556. mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p)
  6557. {
  6558. const char *eof;
  6559. size_t len;
  6560. const char *memend;
  6561. if (!filep) {
  6562. return NULL;
  6563. }
  6564. if ((filep->access.membuf != NULL) && (*p != NULL)) {
  6565. memend = (const char *)&filep->access.membuf[filep->stat.size];
  6566. /* Search for \n from p till the end of stream */
  6567. eof = (char *)memchr(*p, '\n', (size_t)(memend - *p));
  6568. if (eof != NULL) {
  6569. eof += 1; /* Include \n */
  6570. } else {
  6571. eof = memend; /* Copy remaining data */
  6572. }
  6573. len =
  6574. ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p);
  6575. memcpy(buf, *p, len);
  6576. buf[len] = '\0';
  6577. *p += len;
  6578. return len ? eof : NULL;
  6579. } else if (filep->access.fp != NULL) {
  6580. return fgets(buf, (int)size, filep->access.fp);
  6581. } else {
  6582. return NULL;
  6583. }
  6584. }
  6585. /* Define the initial recursion depth for procesesing htpasswd files that
  6586. * include other htpasswd
  6587. * (or even the same) files. It is not difficult to provide a file or files
  6588. * s.t. they force civetweb
  6589. * to infinitely recurse and then crash.
  6590. */
  6591. #define INITIAL_DEPTH 9
  6592. #if INITIAL_DEPTH <= 0
  6593. #error Bad INITIAL_DEPTH for recursion, set to at least 1
  6594. #endif
  6595. struct read_auth_file_struct {
  6596. struct mg_connection *conn;
  6597. struct ah ah;
  6598. const char *domain;
  6599. char buf[256 + 256 + 40];
  6600. const char *f_user;
  6601. const char *f_domain;
  6602. const char *f_ha1;
  6603. };
  6604. static int
  6605. read_auth_file(struct mg_file *filep,
  6606. struct read_auth_file_struct *workdata,
  6607. int depth)
  6608. {
  6609. char *p;
  6610. int is_authorized = 0;
  6611. struct mg_file fp;
  6612. size_t l;
  6613. if (!filep || !workdata || (0 == depth)) {
  6614. return 0;
  6615. }
  6616. /* Loop over passwords file */
  6617. p = (char *)filep->access.membuf;
  6618. while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) {
  6619. l = strlen(workdata->buf);
  6620. while (l > 0) {
  6621. if (isspace(workdata->buf[l - 1])
  6622. || iscntrl(workdata->buf[l - 1])) {
  6623. l--;
  6624. workdata->buf[l] = 0;
  6625. } else
  6626. break;
  6627. }
  6628. if (l < 1) {
  6629. continue;
  6630. }
  6631. workdata->f_user = workdata->buf;
  6632. if (workdata->f_user[0] == ':') {
  6633. /* user names may not contain a ':' and may not be empty,
  6634. * so lines starting with ':' may be used for a special purpose
  6635. */
  6636. if (workdata->f_user[1] == '#') {
  6637. /* :# is a comment */
  6638. continue;
  6639. } else if (!strncmp(workdata->f_user + 1, "include=", 8)) {
  6640. if (mg_fopen(workdata->conn,
  6641. workdata->f_user + 9,
  6642. MG_FOPEN_MODE_READ,
  6643. &fp)) {
  6644. is_authorized = read_auth_file(&fp, workdata, depth - 1);
  6645. (void)mg_fclose(
  6646. &fp.access); /* ignore error on read only file */
  6647. /* No need to continue processing files once we have a
  6648. * match, since nothing will reset it back
  6649. * to 0.
  6650. */
  6651. if (is_authorized) {
  6652. return is_authorized;
  6653. }
  6654. } else {
  6655. mg_cry(workdata->conn,
  6656. "%s: cannot open authorization file: %s",
  6657. __func__,
  6658. workdata->buf);
  6659. }
  6660. continue;
  6661. }
  6662. /* everything is invalid for the moment (might change in the
  6663. * future) */
  6664. mg_cry(workdata->conn,
  6665. "%s: syntax error in authorization file: %s",
  6666. __func__,
  6667. workdata->buf);
  6668. continue;
  6669. }
  6670. workdata->f_domain = strchr(workdata->f_user, ':');
  6671. if (workdata->f_domain == NULL) {
  6672. mg_cry(workdata->conn,
  6673. "%s: syntax error in authorization file: %s",
  6674. __func__,
  6675. workdata->buf);
  6676. continue;
  6677. }
  6678. *(char *)(workdata->f_domain) = 0;
  6679. (workdata->f_domain)++;
  6680. workdata->f_ha1 = strchr(workdata->f_domain, ':');
  6681. if (workdata->f_ha1 == NULL) {
  6682. mg_cry(workdata->conn,
  6683. "%s: syntax error in authorization file: %s",
  6684. __func__,
  6685. workdata->buf);
  6686. continue;
  6687. }
  6688. *(char *)(workdata->f_ha1) = 0;
  6689. (workdata->f_ha1)++;
  6690. if (!strcmp(workdata->ah.user, workdata->f_user)
  6691. && !strcmp(workdata->domain, workdata->f_domain)) {
  6692. return check_password(workdata->conn->request_info.request_method,
  6693. workdata->f_ha1,
  6694. workdata->ah.uri,
  6695. workdata->ah.nonce,
  6696. workdata->ah.nc,
  6697. workdata->ah.cnonce,
  6698. workdata->ah.qop,
  6699. workdata->ah.response);
  6700. }
  6701. }
  6702. return is_authorized;
  6703. }
  6704. /* Authorize against the opened passwords file. Return 1 if authorized. */
  6705. static int
  6706. authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm)
  6707. {
  6708. struct read_auth_file_struct workdata;
  6709. char buf[MG_BUF_LEN];
  6710. if (!conn || !conn->dom_ctx) {
  6711. return 0;
  6712. }
  6713. memset(&workdata, 0, sizeof(workdata));
  6714. workdata.conn = conn;
  6715. if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) {
  6716. return 0;
  6717. }
  6718. if (realm) {
  6719. workdata.domain = realm;
  6720. } else {
  6721. workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  6722. }
  6723. return read_auth_file(filep, &workdata, INITIAL_DEPTH);
  6724. }
  6725. /* Public function to check http digest authentication header */
  6726. int
  6727. mg_check_digest_access_authentication(struct mg_connection *conn,
  6728. const char *realm,
  6729. const char *filename)
  6730. {
  6731. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6732. int auth;
  6733. if (!conn || !filename) {
  6734. return -1;
  6735. }
  6736. if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) {
  6737. return -2;
  6738. }
  6739. auth = authorize(conn, &file, realm);
  6740. mg_fclose(&file.access);
  6741. return auth;
  6742. }
  6743. /* Return 1 if request is authorised, 0 otherwise. */
  6744. static int
  6745. check_authorization(struct mg_connection *conn, const char *path)
  6746. {
  6747. char fname[PATH_MAX];
  6748. struct vec uri_vec, filename_vec;
  6749. const char *list;
  6750. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6751. int authorized = 1, truncated;
  6752. if (!conn || !conn->dom_ctx) {
  6753. return 0;
  6754. }
  6755. list = conn->dom_ctx->config[PROTECT_URI];
  6756. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  6757. if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) {
  6758. mg_snprintf(conn,
  6759. &truncated,
  6760. fname,
  6761. sizeof(fname),
  6762. "%.*s",
  6763. (int)filename_vec.len,
  6764. filename_vec.ptr);
  6765. if (truncated
  6766. || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) {
  6767. mg_cry(conn,
  6768. "%s: cannot open %s: %s",
  6769. __func__,
  6770. fname,
  6771. strerror(errno));
  6772. }
  6773. break;
  6774. }
  6775. }
  6776. if (!is_file_opened(&file.access)) {
  6777. open_auth_file(conn, path, &file);
  6778. }
  6779. if (is_file_opened(&file.access)) {
  6780. authorized = authorize(conn, &file, NULL);
  6781. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6782. }
  6783. return authorized;
  6784. }
  6785. /* Internal function. Assumes conn is valid */
  6786. static void
  6787. send_authorization_request(struct mg_connection *conn, const char *realm)
  6788. {
  6789. char date[64];
  6790. time_t curtime = time(NULL);
  6791. uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time);
  6792. if (!realm) {
  6793. realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  6794. }
  6795. (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex);
  6796. nonce += conn->dom_ctx->nonce_count;
  6797. ++conn->dom_ctx->nonce_count;
  6798. (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex);
  6799. nonce ^= conn->dom_ctx->auth_nonce_mask;
  6800. conn->status_code = 401;
  6801. conn->must_close = 1;
  6802. gmt_time_string(date, sizeof(date), &curtime);
  6803. mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n");
  6804. send_no_cache_header(conn);
  6805. send_additional_header(conn);
  6806. mg_printf(conn,
  6807. "Date: %s\r\n"
  6808. "Connection: %s\r\n"
  6809. "Content-Length: 0\r\n"
  6810. "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", "
  6811. "nonce=\"%" UINT64_FMT "\"\r\n\r\n",
  6812. date,
  6813. suggest_connection_header(conn),
  6814. realm,
  6815. nonce);
  6816. }
  6817. /* Interface function. Parameters are provided by the user, so do
  6818. * at least some basic checks.
  6819. */
  6820. int
  6821. mg_send_digest_access_authentication_request(struct mg_connection *conn,
  6822. const char *realm)
  6823. {
  6824. if (conn && conn->dom_ctx) {
  6825. send_authorization_request(conn, realm);
  6826. return 0;
  6827. }
  6828. return -1;
  6829. }
  6830. #if !defined(NO_FILES)
  6831. static int
  6832. is_authorized_for_put(struct mg_connection *conn)
  6833. {
  6834. if (conn) {
  6835. struct mg_file file = STRUCT_FILE_INITIALIZER;
  6836. const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE];
  6837. int ret = 0;
  6838. if (passfile != NULL
  6839. && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) {
  6840. ret = authorize(conn, &file, NULL);
  6841. (void)mg_fclose(&file.access); /* ignore error on read only file */
  6842. }
  6843. return ret;
  6844. }
  6845. return 0;
  6846. }
  6847. #endif
  6848. int
  6849. mg_modify_passwords_file(const char *fname,
  6850. const char *domain,
  6851. const char *user,
  6852. const char *pass)
  6853. {
  6854. int found, i;
  6855. char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8];
  6856. FILE *fp, *fp2;
  6857. found = 0;
  6858. fp = fp2 = NULL;
  6859. /* Regard empty password as no password - remove user record. */
  6860. if ((pass != NULL) && (pass[0] == '\0')) {
  6861. pass = NULL;
  6862. }
  6863. /* Other arguments must not be empty */
  6864. if ((fname == NULL) || (domain == NULL) || (user == NULL)) {
  6865. return 0;
  6866. }
  6867. /* Using the given file format, user name and domain must not contain
  6868. * ':'
  6869. */
  6870. if (strchr(user, ':') != NULL) {
  6871. return 0;
  6872. }
  6873. if (strchr(domain, ':') != NULL) {
  6874. return 0;
  6875. }
  6876. /* Do not allow control characters like newline in user name and domain.
  6877. * Do not allow excessively long names either. */
  6878. for (i = 0; ((i < 255) && (user[i] != 0)); i++) {
  6879. if (iscntrl(user[i])) {
  6880. return 0;
  6881. }
  6882. }
  6883. if (user[i]) {
  6884. return 0;
  6885. }
  6886. for (i = 0; ((i < 255) && (domain[i] != 0)); i++) {
  6887. if (iscntrl(domain[i])) {
  6888. return 0;
  6889. }
  6890. }
  6891. if (domain[i]) {
  6892. return 0;
  6893. }
  6894. /* The maximum length of the path to the password file is limited */
  6895. if ((strlen(fname) + 4) >= PATH_MAX) {
  6896. return 0;
  6897. }
  6898. /* Create a temporary file name. Length has been checked before. */
  6899. strcpy(tmp, fname);
  6900. strcat(tmp, ".tmp");
  6901. /* Create the file if does not exist */
  6902. /* Use of fopen here is OK, since fname is only ASCII */
  6903. if ((fp = fopen(fname, "a+")) != NULL) {
  6904. (void)fclose(fp);
  6905. }
  6906. /* Open the given file and temporary file */
  6907. if ((fp = fopen(fname, "r")) == NULL) {
  6908. return 0;
  6909. } else if ((fp2 = fopen(tmp, "w+")) == NULL) {
  6910. fclose(fp);
  6911. return 0;
  6912. }
  6913. /* Copy the stuff to temporary file */
  6914. while (fgets(line, sizeof(line), fp) != NULL) {
  6915. if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) {
  6916. continue;
  6917. }
  6918. u[255] = 0;
  6919. d[255] = 0;
  6920. if (!strcmp(u, user) && !strcmp(d, domain)) {
  6921. found++;
  6922. if (pass != NULL) {
  6923. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6924. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6925. }
  6926. } else {
  6927. fprintf(fp2, "%s", line);
  6928. }
  6929. }
  6930. /* If new user, just add it */
  6931. if (!found && (pass != NULL)) {
  6932. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  6933. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  6934. }
  6935. /* Close files */
  6936. fclose(fp);
  6937. fclose(fp2);
  6938. /* Put the temp file in place of real file */
  6939. IGNORE_UNUSED_RESULT(remove(fname));
  6940. IGNORE_UNUSED_RESULT(rename(tmp, fname));
  6941. return 1;
  6942. }
  6943. static int
  6944. is_valid_port(unsigned long port)
  6945. {
  6946. return (port <= 0xffff);
  6947. }
  6948. static int
  6949. mg_inet_pton(int af, const char *src, void *dst, size_t dstlen)
  6950. {
  6951. struct addrinfo hints, *res, *ressave;
  6952. int func_ret = 0;
  6953. int gai_ret;
  6954. memset(&hints, 0, sizeof(struct addrinfo));
  6955. hints.ai_family = af;
  6956. gai_ret = getaddrinfo(src, NULL, &hints, &res);
  6957. if (gai_ret != 0) {
  6958. /* gai_strerror could be used to convert gai_ret to a string */
  6959. /* POSIX return values: see
  6960. * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html
  6961. */
  6962. /* Windows return values: see
  6963. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx
  6964. */
  6965. return 0;
  6966. }
  6967. ressave = res;
  6968. while (res) {
  6969. if (dstlen >= (size_t)res->ai_addrlen) {
  6970. memcpy(dst, res->ai_addr, res->ai_addrlen);
  6971. func_ret = 1;
  6972. }
  6973. res = res->ai_next;
  6974. }
  6975. freeaddrinfo(ressave);
  6976. return func_ret;
  6977. }
  6978. static int
  6979. connect_socket(struct mg_context *ctx /* may be NULL */,
  6980. const char *host,
  6981. int port,
  6982. int use_ssl,
  6983. char *ebuf,
  6984. size_t ebuf_len,
  6985. SOCKET *sock /* output: socket, must not be NULL */,
  6986. union usa *sa /* output: socket address, must not be NULL */
  6987. )
  6988. {
  6989. int ip_ver = 0;
  6990. int conn_ret = -1;
  6991. *sock = INVALID_SOCKET;
  6992. memset(sa, 0, sizeof(*sa));
  6993. if (ebuf_len > 0) {
  6994. *ebuf = 0;
  6995. }
  6996. if (host == NULL) {
  6997. mg_snprintf(NULL,
  6998. NULL, /* No truncation check for ebuf */
  6999. ebuf,
  7000. ebuf_len,
  7001. "%s",
  7002. "NULL host");
  7003. return 0;
  7004. }
  7005. if ((port <= 0) || !is_valid_port((unsigned)port)) {
  7006. mg_snprintf(NULL,
  7007. NULL, /* No truncation check for ebuf */
  7008. ebuf,
  7009. ebuf_len,
  7010. "%s",
  7011. "invalid port");
  7012. return 0;
  7013. }
  7014. #if !defined(NO_SSL)
  7015. #if !defined(NO_SSL_DL)
  7016. #ifdef OPENSSL_API_1_1
  7017. if (use_ssl && (TLS_client_method == NULL)) {
  7018. mg_snprintf(NULL,
  7019. NULL, /* No truncation check for ebuf */
  7020. ebuf,
  7021. ebuf_len,
  7022. "%s",
  7023. "SSL is not initialized");
  7024. return 0;
  7025. }
  7026. #else
  7027. if (use_ssl && (SSLv23_client_method == NULL)) {
  7028. mg_snprintf(NULL,
  7029. NULL, /* No truncation check for ebuf */
  7030. ebuf,
  7031. ebuf_len,
  7032. "%s",
  7033. "SSL is not initialized");
  7034. return 0;
  7035. }
  7036. #endif /* OPENSSL_API_1_1 */
  7037. #else
  7038. (void)use_ssl;
  7039. #endif /* NO_SSL_DL */
  7040. #else
  7041. (void)use_ssl;
  7042. #endif /* !defined(NO_SSL) */
  7043. if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) {
  7044. sa->sin.sin_family = AF_INET;
  7045. sa->sin.sin_port = htons((uint16_t)port);
  7046. ip_ver = 4;
  7047. #ifdef USE_IPV6
  7048. } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) {
  7049. sa->sin6.sin6_family = AF_INET6;
  7050. sa->sin6.sin6_port = htons((uint16_t)port);
  7051. ip_ver = 6;
  7052. } else if (host[0] == '[') {
  7053. /* While getaddrinfo on Windows will work with [::1],
  7054. * getaddrinfo on Linux only works with ::1 (without []). */
  7055. size_t l = strlen(host + 1);
  7056. char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL;
  7057. if (h) {
  7058. h[l - 1] = 0;
  7059. if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) {
  7060. sa->sin6.sin6_family = AF_INET6;
  7061. sa->sin6.sin6_port = htons((uint16_t)port);
  7062. ip_ver = 6;
  7063. }
  7064. mg_free(h);
  7065. }
  7066. #endif
  7067. }
  7068. if (ip_ver == 0) {
  7069. mg_snprintf(NULL,
  7070. NULL, /* No truncation check for ebuf */
  7071. ebuf,
  7072. ebuf_len,
  7073. "%s",
  7074. "host not found");
  7075. return 0;
  7076. }
  7077. if (ip_ver == 4) {
  7078. *sock = socket(PF_INET, SOCK_STREAM, 0);
  7079. }
  7080. #ifdef USE_IPV6
  7081. else if (ip_ver == 6) {
  7082. *sock = socket(PF_INET6, SOCK_STREAM, 0);
  7083. }
  7084. #endif
  7085. if (*sock == INVALID_SOCKET) {
  7086. mg_snprintf(NULL,
  7087. NULL, /* No truncation check for ebuf */
  7088. ebuf,
  7089. ebuf_len,
  7090. "socket(): %s",
  7091. strerror(ERRNO));
  7092. return 0;
  7093. }
  7094. if (0 != set_non_blocking_mode(*sock)) {
  7095. mg_snprintf(NULL,
  7096. NULL, /* No truncation check for ebuf */
  7097. ebuf,
  7098. ebuf_len,
  7099. "Cannot set socket to non-blocking: %s",
  7100. strerror(ERRNO));
  7101. closesocket(*sock);
  7102. *sock = INVALID_SOCKET;
  7103. return 0;
  7104. }
  7105. set_close_on_exec(*sock, fc(ctx));
  7106. if (ip_ver == 4) {
  7107. /* connected with IPv4 */
  7108. conn_ret = connect(*sock, (struct sockaddr *)&sa->sin, sizeof(sa->sin));
  7109. }
  7110. #ifdef USE_IPV6
  7111. else if (ip_ver == 6) {
  7112. /* connected with IPv6 */
  7113. conn_ret =
  7114. connect(*sock, (struct sockaddr *)&sa->sin6, sizeof(sa->sin6));
  7115. }
  7116. #endif
  7117. if (conn_ret != 0) {
  7118. fd_set fdset;
  7119. struct timeval timeout;
  7120. int sockerr = -1;
  7121. #if defined(_WIN32)
  7122. int len = (int)sizeof(sockerr);
  7123. #else
  7124. socklen_t len = (socklen_t)sizeof(sockerr);
  7125. #endif
  7126. FD_ZERO(&fdset);
  7127. FD_SET(*sock, &fdset);
  7128. timeout.tv_sec = 10; /* 10 second timeout */
  7129. timeout.tv_usec = 0;
  7130. if (select((int)(*sock) + 1, NULL, &fdset, NULL, &timeout) != 1) {
  7131. /* Not connected */
  7132. mg_snprintf(NULL,
  7133. NULL, /* No truncation check for ebuf */
  7134. ebuf,
  7135. ebuf_len,
  7136. "connect(%s:%d): timeout",
  7137. host,
  7138. port);
  7139. closesocket(*sock);
  7140. *sock = INVALID_SOCKET;
  7141. return 0;
  7142. }
  7143. #if defined(_WIN32)
  7144. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)&sockerr, &len);
  7145. #else
  7146. getsockopt(*sock, SOL_SOCKET, SO_ERROR, (void *)&sockerr, &len);
  7147. #endif
  7148. if (sockerr != 0) {
  7149. /* Not connected */
  7150. mg_snprintf(NULL,
  7151. NULL, /* No truncation check for ebuf */
  7152. ebuf,
  7153. ebuf_len,
  7154. "connect(%s:%d): error %s",
  7155. host,
  7156. port,
  7157. strerror(sockerr));
  7158. closesocket(*sock);
  7159. *sock = INVALID_SOCKET;
  7160. return 0;
  7161. }
  7162. }
  7163. return 1;
  7164. }
  7165. int
  7166. mg_url_encode(const char *src, char *dst, size_t dst_len)
  7167. {
  7168. static const char *dont_escape = "._-$,;~()";
  7169. static const char *hex = "0123456789abcdef";
  7170. char *pos = dst;
  7171. const char *end = dst + dst_len - 1;
  7172. for (; ((*src != '\0') && (pos < end)); src++, pos++) {
  7173. if (isalnum(*(const unsigned char *)src)
  7174. || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) {
  7175. *pos = *src;
  7176. } else if (pos + 2 < end) {
  7177. pos[0] = '%';
  7178. pos[1] = hex[(*(const unsigned char *)src) >> 4];
  7179. pos[2] = hex[(*(const unsigned char *)src) & 0xf];
  7180. pos += 2;
  7181. } else {
  7182. break;
  7183. }
  7184. }
  7185. *pos = '\0';
  7186. return (*src == '\0') ? (int)(pos - dst) : -1;
  7187. }
  7188. /* Return 0 on success, non-zero if an error occurs. */
  7189. static int
  7190. print_dir_entry(struct de *de)
  7191. {
  7192. size_t hrefsize;
  7193. char *href;
  7194. char size[64], mod[64];
  7195. struct tm *tm;
  7196. hrefsize = PATH_MAX * 3; /* worst case */
  7197. href = (char *)mg_malloc(hrefsize);
  7198. if (href == NULL) {
  7199. return -1;
  7200. }
  7201. if (de->file.is_directory) {
  7202. mg_snprintf(de->conn,
  7203. NULL, /* Buffer is big enough */
  7204. size,
  7205. sizeof(size),
  7206. "%s",
  7207. "[DIRECTORY]");
  7208. } else {
  7209. /* We use (signed) cast below because MSVC 6 compiler cannot
  7210. * convert unsigned __int64 to double. Sigh. */
  7211. if (de->file.size < 1024) {
  7212. mg_snprintf(de->conn,
  7213. NULL, /* Buffer is big enough */
  7214. size,
  7215. sizeof(size),
  7216. "%d",
  7217. (int)de->file.size);
  7218. } else if (de->file.size < 0x100000) {
  7219. mg_snprintf(de->conn,
  7220. NULL, /* Buffer is big enough */
  7221. size,
  7222. sizeof(size),
  7223. "%.1fk",
  7224. (double)de->file.size / 1024.0);
  7225. } else if (de->file.size < 0x40000000) {
  7226. mg_snprintf(de->conn,
  7227. NULL, /* Buffer is big enough */
  7228. size,
  7229. sizeof(size),
  7230. "%.1fM",
  7231. (double)de->file.size / 1048576);
  7232. } else {
  7233. mg_snprintf(de->conn,
  7234. NULL, /* Buffer is big enough */
  7235. size,
  7236. sizeof(size),
  7237. "%.1fG",
  7238. (double)de->file.size / 1073741824);
  7239. }
  7240. }
  7241. /* Note: mg_snprintf will not cause a buffer overflow above.
  7242. * So, string truncation checks are not required here. */
  7243. tm = localtime(&de->file.last_modified);
  7244. if (tm != NULL) {
  7245. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm);
  7246. } else {
  7247. mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod));
  7248. mod[sizeof(mod) - 1] = '\0';
  7249. }
  7250. mg_url_encode(de->file_name, href, hrefsize);
  7251. mg_printf(de->conn,
  7252. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  7253. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7254. de->conn->request_info.local_uri,
  7255. href,
  7256. de->file.is_directory ? "/" : "",
  7257. de->file_name,
  7258. de->file.is_directory ? "/" : "",
  7259. mod,
  7260. size);
  7261. mg_free(href);
  7262. return 0;
  7263. }
  7264. /* This function is called from send_directory() and used for
  7265. * sorting directory entries by size, or name, or modification time.
  7266. * On windows, __cdecl specification is needed in case if project is built
  7267. * with __stdcall convention. qsort always requires __cdels callback. */
  7268. static int WINCDECL
  7269. compare_dir_entries(const void *p1, const void *p2)
  7270. {
  7271. if (p1 && p2) {
  7272. const struct de *a = (const struct de *)p1, *b = (const struct de *)p2;
  7273. const char *query_string = a->conn->request_info.query_string;
  7274. int cmp_result = 0;
  7275. if (query_string == NULL) {
  7276. query_string = "na";
  7277. }
  7278. if (a->file.is_directory && !b->file.is_directory) {
  7279. return -1; /* Always put directories on top */
  7280. } else if (!a->file.is_directory && b->file.is_directory) {
  7281. return 1; /* Always put directories on top */
  7282. } else if (*query_string == 'n') {
  7283. cmp_result = strcmp(a->file_name, b->file_name);
  7284. } else if (*query_string == 's') {
  7285. cmp_result = (a->file.size == b->file.size)
  7286. ? 0
  7287. : ((a->file.size > b->file.size) ? 1 : -1);
  7288. } else if (*query_string == 'd') {
  7289. cmp_result =
  7290. (a->file.last_modified == b->file.last_modified)
  7291. ? 0
  7292. : ((a->file.last_modified > b->file.last_modified) ? 1
  7293. : -1);
  7294. }
  7295. return (query_string[1] == 'd') ? -cmp_result : cmp_result;
  7296. }
  7297. return 0;
  7298. }
  7299. static int
  7300. must_hide_file(struct mg_connection *conn, const char *path)
  7301. {
  7302. if (conn && conn->dom_ctx) {
  7303. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  7304. const char *pattern = conn->dom_ctx->config[HIDE_FILES];
  7305. return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0)
  7306. || ((pattern != NULL)
  7307. && (match_prefix(pattern, strlen(pattern), path) > 0));
  7308. }
  7309. return 0;
  7310. }
  7311. static int
  7312. scan_directory(struct mg_connection *conn,
  7313. const char *dir,
  7314. void *data,
  7315. int (*cb)(struct de *, void *))
  7316. {
  7317. char path[PATH_MAX];
  7318. struct dirent *dp;
  7319. DIR *dirp;
  7320. struct de de;
  7321. int truncated;
  7322. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7323. return 0;
  7324. } else {
  7325. de.conn = conn;
  7326. while ((dp = mg_readdir(dirp)) != NULL) {
  7327. /* Do not show current dir and hidden files */
  7328. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")
  7329. || must_hide_file(conn, dp->d_name)) {
  7330. continue;
  7331. }
  7332. mg_snprintf(
  7333. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7334. /* If we don't memset stat structure to zero, mtime will have
  7335. * garbage and strftime() will segfault later on in
  7336. * print_dir_entry(). memset is required only if mg_stat()
  7337. * fails. For more details, see
  7338. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7339. memset(&de.file, 0, sizeof(de.file));
  7340. if (truncated) {
  7341. /* If the path is not complete, skip processing. */
  7342. continue;
  7343. }
  7344. if (!mg_stat(conn, path, &de.file)) {
  7345. mg_cry(conn,
  7346. "%s: mg_stat(%s) failed: %s",
  7347. __func__,
  7348. path,
  7349. strerror(ERRNO));
  7350. }
  7351. de.file_name = dp->d_name;
  7352. cb(&de, data);
  7353. }
  7354. (void)mg_closedir(dirp);
  7355. }
  7356. return 1;
  7357. }
  7358. #if !defined(NO_FILES)
  7359. static int
  7360. remove_directory(struct mg_connection *conn, const char *dir)
  7361. {
  7362. char path[PATH_MAX];
  7363. struct dirent *dp;
  7364. DIR *dirp;
  7365. struct de de;
  7366. int truncated;
  7367. int ok = 1;
  7368. if ((dirp = mg_opendir(conn, dir)) == NULL) {
  7369. return 0;
  7370. } else {
  7371. de.conn = conn;
  7372. while ((dp = mg_readdir(dirp)) != NULL) {
  7373. /* Do not show current dir (but show hidden files as they will
  7374. * also be removed) */
  7375. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) {
  7376. continue;
  7377. }
  7378. mg_snprintf(
  7379. conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name);
  7380. /* If we don't memset stat structure to zero, mtime will have
  7381. * garbage and strftime() will segfault later on in
  7382. * print_dir_entry(). memset is required only if mg_stat()
  7383. * fails. For more details, see
  7384. * http://code.google.com/p/mongoose/issues/detail?id=79 */
  7385. memset(&de.file, 0, sizeof(de.file));
  7386. if (truncated) {
  7387. /* Do not delete anything shorter */
  7388. ok = 0;
  7389. continue;
  7390. }
  7391. if (!mg_stat(conn, path, &de.file)) {
  7392. mg_cry(conn,
  7393. "%s: mg_stat(%s) failed: %s",
  7394. __func__,
  7395. path,
  7396. strerror(ERRNO));
  7397. ok = 0;
  7398. }
  7399. if (de.file.is_directory) {
  7400. if (remove_directory(conn, path) == 0) {
  7401. ok = 0;
  7402. }
  7403. } else {
  7404. /* This will fail file is the file is in memory */
  7405. if (mg_remove(conn, path) == 0) {
  7406. ok = 0;
  7407. }
  7408. }
  7409. }
  7410. (void)mg_closedir(dirp);
  7411. IGNORE_UNUSED_RESULT(rmdir(dir));
  7412. }
  7413. return ok;
  7414. }
  7415. #endif
  7416. struct dir_scan_data {
  7417. struct de *entries;
  7418. unsigned int num_entries;
  7419. unsigned int arr_size;
  7420. };
  7421. /* Behaves like realloc(), but frees original pointer on failure */
  7422. static void *
  7423. realloc2(void *ptr, size_t size)
  7424. {
  7425. void *new_ptr = mg_realloc(ptr, size);
  7426. if (new_ptr == NULL) {
  7427. mg_free(ptr);
  7428. }
  7429. return new_ptr;
  7430. }
  7431. static int
  7432. dir_scan_callback(struct de *de, void *data)
  7433. {
  7434. struct dir_scan_data *dsd = (struct dir_scan_data *)data;
  7435. if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) {
  7436. dsd->arr_size *= 2;
  7437. dsd->entries =
  7438. (struct de *)realloc2(dsd->entries,
  7439. dsd->arr_size * sizeof(dsd->entries[0]));
  7440. }
  7441. if (dsd->entries == NULL) {
  7442. /* TODO(lsm, low): propagate an error to the caller */
  7443. dsd->num_entries = 0;
  7444. } else {
  7445. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  7446. dsd->entries[dsd->num_entries].file = de->file;
  7447. dsd->entries[dsd->num_entries].conn = de->conn;
  7448. dsd->num_entries++;
  7449. }
  7450. return 0;
  7451. }
  7452. static void
  7453. handle_directory_request(struct mg_connection *conn, const char *dir)
  7454. {
  7455. unsigned int i;
  7456. int sort_direction;
  7457. struct dir_scan_data data = {NULL, 0, 128};
  7458. char date[64];
  7459. time_t curtime = time(NULL);
  7460. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  7461. mg_send_http_error(conn,
  7462. 500,
  7463. "Error: Cannot open directory\nopendir(%s): %s",
  7464. dir,
  7465. strerror(ERRNO));
  7466. return;
  7467. }
  7468. gmt_time_string(date, sizeof(date), &curtime);
  7469. if (!conn) {
  7470. return;
  7471. }
  7472. sort_direction = ((conn->request_info.query_string != NULL)
  7473. && (conn->request_info.query_string[1] == 'd'))
  7474. ? 'a'
  7475. : 'd';
  7476. conn->must_close = 1;
  7477. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  7478. send_static_cache_header(conn);
  7479. send_additional_header(conn);
  7480. mg_printf(conn,
  7481. "Date: %s\r\n"
  7482. "Connection: close\r\n"
  7483. "Content-Type: text/html; charset=utf-8\r\n\r\n",
  7484. date);
  7485. mg_printf(conn,
  7486. "<html><head><title>Index of %s</title>"
  7487. "<style>th {text-align: left;}</style></head>"
  7488. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  7489. "<tr><th><a href=\"?n%c\">Name</a></th>"
  7490. "<th><a href=\"?d%c\">Modified</a></th>"
  7491. "<th><a href=\"?s%c\">Size</a></th></tr>"
  7492. "<tr><td colspan=\"3\"><hr></td></tr>",
  7493. conn->request_info.local_uri,
  7494. conn->request_info.local_uri,
  7495. sort_direction,
  7496. sort_direction,
  7497. sort_direction);
  7498. /* Print first entry - link to a parent directory */
  7499. mg_printf(conn,
  7500. "<tr><td><a href=\"%s%s\">%s</a></td>"
  7501. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  7502. conn->request_info.local_uri,
  7503. "..",
  7504. "Parent directory",
  7505. "-",
  7506. "-");
  7507. /* Sort and print directory entries */
  7508. if (data.entries != NULL) {
  7509. qsort(data.entries,
  7510. (size_t)data.num_entries,
  7511. sizeof(data.entries[0]),
  7512. compare_dir_entries);
  7513. for (i = 0; i < data.num_entries; i++) {
  7514. print_dir_entry(&data.entries[i]);
  7515. mg_free(data.entries[i].file_name);
  7516. }
  7517. mg_free(data.entries);
  7518. }
  7519. mg_printf(conn, "%s", "</table></body></html>");
  7520. conn->status_code = 200;
  7521. }
  7522. /* Send len bytes from the opened file to the client. */
  7523. static void
  7524. send_file_data(struct mg_connection *conn,
  7525. struct mg_file *filep,
  7526. int64_t offset,
  7527. int64_t len)
  7528. {
  7529. char buf[MG_BUF_LEN];
  7530. int to_read, num_read, num_written;
  7531. int64_t size;
  7532. if (!filep || !conn) {
  7533. return;
  7534. }
  7535. /* Sanity check the offset */
  7536. size = (filep->stat.size > INT64_MAX) ? INT64_MAX
  7537. : (int64_t)(filep->stat.size);
  7538. offset = (offset < 0) ? 0 : ((offset > size) ? size : offset);
  7539. if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) {
  7540. /* file stored in memory */
  7541. if (len > size - offset) {
  7542. len = size - offset;
  7543. }
  7544. mg_write(conn, filep->access.membuf + offset, (size_t)len);
  7545. } else if (len > 0 && filep->access.fp != NULL) {
  7546. /* file stored on disk */
  7547. #if defined(__linux__)
  7548. /* sendfile is only available for Linux */
  7549. if ((conn->ssl == 0) && (conn->throttle == 0)
  7550. && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL],
  7551. "yes"))) {
  7552. off_t sf_offs = (off_t)offset;
  7553. ssize_t sf_sent;
  7554. int sf_file = fileno(filep->access.fp);
  7555. int loop_cnt = 0;
  7556. do {
  7557. /* 2147479552 (0x7FFFF000) is a limit found by experiment on
  7558. * 64 bit Linux (2^31 minus one memory page of 4k?). */
  7559. size_t sf_tosend =
  7560. (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000);
  7561. sf_sent =
  7562. sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend);
  7563. if (sf_sent > 0) {
  7564. len -= sf_sent;
  7565. offset += sf_sent;
  7566. } else if (loop_cnt == 0) {
  7567. /* This file can not be sent using sendfile.
  7568. * This might be the case for pseudo-files in the
  7569. * /sys/ and /proc/ file system.
  7570. * Use the regular user mode copy code instead. */
  7571. break;
  7572. } else if (sf_sent == 0) {
  7573. /* No error, but 0 bytes sent. May be EOF? */
  7574. return;
  7575. }
  7576. loop_cnt++;
  7577. } while ((len > 0) && (sf_sent >= 0));
  7578. if (sf_sent > 0) {
  7579. return; /* OK */
  7580. }
  7581. /* sf_sent<0 means error, thus fall back to the classic way */
  7582. /* This is always the case, if sf_file is not a "normal" file,
  7583. * e.g., for sending data from the output of a CGI process. */
  7584. offset = (int64_t)sf_offs;
  7585. }
  7586. #endif
  7587. if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) {
  7588. mg_cry(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO));
  7589. mg_send_http_error(
  7590. conn,
  7591. 500,
  7592. "%s",
  7593. "Error: Unable to access file at requested position.");
  7594. } else {
  7595. while (len > 0) {
  7596. /* Calculate how much to read from the file in the buffer */
  7597. to_read = sizeof(buf);
  7598. if ((int64_t)to_read > len) {
  7599. to_read = (int)len;
  7600. }
  7601. /* Read from file, exit the loop on error */
  7602. if ((num_read =
  7603. (int)fread(buf, 1, (size_t)to_read, filep->access.fp))
  7604. <= 0) {
  7605. break;
  7606. }
  7607. /* Send read bytes to the client, exit the loop on error */
  7608. if ((num_written = mg_write(conn, buf, (size_t)num_read))
  7609. != num_read) {
  7610. break;
  7611. }
  7612. /* Both read and were successful, adjust counters */
  7613. len -= num_written;
  7614. }
  7615. }
  7616. }
  7617. }
  7618. static int
  7619. parse_range_header(const char *header, int64_t *a, int64_t *b)
  7620. {
  7621. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  7622. }
  7623. static void
  7624. construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat)
  7625. {
  7626. if ((filestat != NULL) && (buf != NULL)) {
  7627. mg_snprintf(NULL,
  7628. NULL, /* All calls to construct_etag use 64 byte buffer */
  7629. buf,
  7630. buf_len,
  7631. "\"%lx.%" INT64_FMT "\"",
  7632. (unsigned long)filestat->last_modified,
  7633. filestat->size);
  7634. }
  7635. }
  7636. static void
  7637. fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn)
  7638. {
  7639. if (filep != NULL && filep->fp != NULL) {
  7640. #ifdef _WIN32
  7641. (void)conn; /* Unused. */
  7642. #else
  7643. if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) {
  7644. mg_cry(conn,
  7645. "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s",
  7646. __func__,
  7647. strerror(ERRNO));
  7648. }
  7649. #endif
  7650. }
  7651. }
  7652. static void
  7653. handle_static_file_request(struct mg_connection *conn,
  7654. const char *path,
  7655. struct mg_file *filep,
  7656. const char *mime_type,
  7657. const char *additional_headers)
  7658. {
  7659. char date[64], lm[64], etag[64];
  7660. char range[128]; /* large enough, so there will be no overflow */
  7661. const char *msg = "OK", *hdr;
  7662. time_t curtime = time(NULL);
  7663. int64_t cl, r1, r2;
  7664. struct vec mime_vec;
  7665. int n, truncated;
  7666. char gz_path[PATH_MAX];
  7667. const char *encoding = "";
  7668. const char *cors1, *cors2, *cors3;
  7669. int allow_on_the_fly_compression;
  7670. if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) {
  7671. return;
  7672. }
  7673. if (mime_type == NULL) {
  7674. get_mime_type(conn, path, &mime_vec);
  7675. } else {
  7676. mime_vec.ptr = mime_type;
  7677. mime_vec.len = strlen(mime_type);
  7678. }
  7679. if (filep->stat.size > INT64_MAX) {
  7680. mg_send_http_error(conn,
  7681. 500,
  7682. "Error: File size is too large to send\n%" INT64_FMT,
  7683. filep->stat.size);
  7684. return;
  7685. }
  7686. cl = (int64_t)filep->stat.size;
  7687. conn->status_code = 200;
  7688. range[0] = '\0';
  7689. /* if this file is in fact a pre-gzipped file, rewrite its filename
  7690. * it's important to rewrite the filename after resolving
  7691. * the mime type from it, to preserve the actual file's type */
  7692. allow_on_the_fly_compression = conn->accept_gzip;
  7693. if (filep->stat.is_gzipped) {
  7694. mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path);
  7695. if (truncated) {
  7696. mg_send_http_error(conn,
  7697. 500,
  7698. "Error: Path of zipped file too long (%s)",
  7699. path);
  7700. return;
  7701. }
  7702. path = gz_path;
  7703. encoding = "Content-Encoding: gzip\r\n";
  7704. /* File is already compressed. No "on the fly" compression. */
  7705. allow_on_the_fly_compression = 0;
  7706. }
  7707. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  7708. mg_send_http_error(conn,
  7709. 500,
  7710. "Error: Cannot open file\nfopen(%s): %s",
  7711. path,
  7712. strerror(ERRNO));
  7713. return;
  7714. }
  7715. fclose_on_exec(&filep->access, conn);
  7716. /* If Range: header specified, act accordingly */
  7717. r1 = r2 = 0;
  7718. hdr = mg_get_header(conn, "Range");
  7719. if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0)
  7720. && (r1 >= 0) && (r2 >= 0)) {
  7721. /* actually, range requests don't play well with a pre-gzipped
  7722. * file (since the range is specified in the uncompressed space) */
  7723. if (filep->stat.is_gzipped) {
  7724. mg_send_http_error(
  7725. conn,
  7726. 416, /* 416 = Range Not Satisfiable */
  7727. "%s",
  7728. "Error: Range requests in gzipped files are not supported");
  7729. (void)mg_fclose(
  7730. &filep->access); /* ignore error on read only file */
  7731. return;
  7732. }
  7733. conn->status_code = 206;
  7734. cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1);
  7735. mg_snprintf(conn,
  7736. NULL, /* range buffer is big enough */
  7737. range,
  7738. sizeof(range),
  7739. "Content-Range: bytes "
  7740. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  7741. r1,
  7742. r1 + cl - 1,
  7743. filep->stat.size);
  7744. msg = "Partial Content";
  7745. /* Do not compress ranges. */
  7746. allow_on_the_fly_compression = 0;
  7747. }
  7748. hdr = mg_get_header(conn, "Origin");
  7749. if (hdr) {
  7750. /* Cross-origin resource sharing (CORS), see
  7751. * http://www.html5rocks.com/en/tutorials/cors/,
  7752. * http://www.html5rocks.com/static/images/cors_server_flowchart.png
  7753. * -
  7754. * preflight is not supported for files. */
  7755. cors1 = "Access-Control-Allow-Origin: ";
  7756. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  7757. cors3 = "\r\n";
  7758. } else {
  7759. cors1 = cors2 = cors3 = "";
  7760. }
  7761. /* Prepare Etag, Date, Last-Modified headers. Must be in UTC,
  7762. * according to
  7763. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */
  7764. gmt_time_string(date, sizeof(date), &curtime);
  7765. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7766. construct_etag(etag, sizeof(etag), &filep->stat);
  7767. /* On the fly compression allowed */
  7768. if (allow_on_the_fly_compression) {
  7769. ;
  7770. /* TODO: add interface to compression module */
  7771. /* e.g., def from https://zlib.net/zlib_how.html */
  7772. /* Check license (zlib has a permissive license, but */
  7773. /* is still not MIT) and use dynamic binding like */
  7774. /* done with OpenSSL */
  7775. /* See #199 (https://github.com/civetweb/civetweb/issues/199) */
  7776. }
  7777. /* Send header */
  7778. (void)mg_printf(conn,
  7779. "HTTP/1.1 %d %s\r\n"
  7780. "%s%s%s"
  7781. "Date: %s\r\n",
  7782. conn->status_code,
  7783. msg,
  7784. cors1,
  7785. cors2,
  7786. cors3,
  7787. date);
  7788. send_static_cache_header(conn);
  7789. send_additional_header(conn);
  7790. (void)mg_printf(conn,
  7791. "Last-Modified: %s\r\n"
  7792. "Etag: %s\r\n"
  7793. "Content-Type: %.*s\r\n"
  7794. "Content-Length: %" INT64_FMT "\r\n"
  7795. "Connection: %s\r\n"
  7796. "Accept-Ranges: bytes\r\n"
  7797. "%s%s",
  7798. lm,
  7799. etag,
  7800. (int)mime_vec.len,
  7801. mime_vec.ptr,
  7802. cl,
  7803. suggest_connection_header(conn),
  7804. range,
  7805. encoding);
  7806. /* The previous code must not add any header starting with X- to make
  7807. * sure no one of the additional_headers is included twice */
  7808. if (additional_headers != NULL) {
  7809. (void)mg_printf(conn,
  7810. "%.*s\r\n\r\n",
  7811. (int)strlen(additional_headers),
  7812. additional_headers);
  7813. } else {
  7814. (void)mg_printf(conn, "\r\n");
  7815. }
  7816. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  7817. send_file_data(conn, filep, r1, cl);
  7818. }
  7819. (void)mg_fclose(&filep->access); /* ignore error on read only file */
  7820. }
  7821. #if !defined(NO_CACHING)
  7822. /* Return True if we should reply 304 Not Modified. */
  7823. static int
  7824. is_not_modified(const struct mg_connection *conn,
  7825. const struct mg_file_stat *filestat)
  7826. {
  7827. char etag[64];
  7828. const char *ims = mg_get_header(conn, "If-Modified-Since");
  7829. const char *inm = mg_get_header(conn, "If-None-Match");
  7830. construct_etag(etag, sizeof(etag), filestat);
  7831. return ((inm != NULL) && !mg_strcasecmp(etag, inm))
  7832. || ((ims != NULL)
  7833. && (filestat->last_modified <= parse_date_string(ims)));
  7834. }
  7835. static void
  7836. handle_not_modified_static_file_request(struct mg_connection *conn,
  7837. struct mg_file *filep)
  7838. {
  7839. char date[64], lm[64], etag[64];
  7840. time_t curtime = time(NULL);
  7841. if ((conn == NULL) || (filep == NULL)) {
  7842. return;
  7843. }
  7844. conn->status_code = 304;
  7845. gmt_time_string(date, sizeof(date), &curtime);
  7846. gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified);
  7847. construct_etag(etag, sizeof(etag), &filep->stat);
  7848. (void)mg_printf(conn,
  7849. "HTTP/1.1 %d %s\r\n"
  7850. "Date: %s\r\n",
  7851. conn->status_code,
  7852. mg_get_response_code_text(conn, conn->status_code),
  7853. date);
  7854. send_static_cache_header(conn);
  7855. send_additional_header(conn);
  7856. (void)mg_printf(conn,
  7857. "Last-Modified: %s\r\n"
  7858. "Etag: %s\r\n"
  7859. "Connection: %s\r\n"
  7860. "\r\n",
  7861. lm,
  7862. etag,
  7863. suggest_connection_header(conn));
  7864. }
  7865. #endif
  7866. void
  7867. mg_send_file(struct mg_connection *conn, const char *path)
  7868. {
  7869. mg_send_mime_file(conn, path, NULL);
  7870. }
  7871. void
  7872. mg_send_mime_file(struct mg_connection *conn,
  7873. const char *path,
  7874. const char *mime_type)
  7875. {
  7876. mg_send_mime_file2(conn, path, mime_type, NULL);
  7877. }
  7878. void
  7879. mg_send_mime_file2(struct mg_connection *conn,
  7880. const char *path,
  7881. const char *mime_type,
  7882. const char *additional_headers)
  7883. {
  7884. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7885. if (!conn) {
  7886. /* No conn */
  7887. return;
  7888. }
  7889. if (mg_stat(conn, path, &file.stat)) {
  7890. #if !defined(NO_CACHING)
  7891. if (is_not_modified(conn, &file.stat)) {
  7892. /* Send 304 "Not Modified" - this must not send any body data */
  7893. handle_not_modified_static_file_request(conn, &file);
  7894. } else
  7895. #endif /* NO_CACHING */
  7896. if (file.stat.is_directory) {
  7897. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  7898. "yes")) {
  7899. handle_directory_request(conn, path);
  7900. } else {
  7901. mg_send_http_error(conn,
  7902. 403,
  7903. "%s",
  7904. "Error: Directory listing denied");
  7905. }
  7906. } else {
  7907. handle_static_file_request(
  7908. conn, path, &file, mime_type, additional_headers);
  7909. }
  7910. } else {
  7911. mg_send_http_error(conn, 404, "%s", "Error: File not found");
  7912. }
  7913. }
  7914. /* For a given PUT path, create all intermediate subdirectories.
  7915. * Return 0 if the path itself is a directory.
  7916. * Return 1 if the path leads to a file.
  7917. * Return -1 for if the path is too long.
  7918. * Return -2 if path can not be created.
  7919. */
  7920. static int
  7921. put_dir(struct mg_connection *conn, const char *path)
  7922. {
  7923. char buf[PATH_MAX];
  7924. const char *s, *p;
  7925. struct mg_file file = STRUCT_FILE_INITIALIZER;
  7926. size_t len;
  7927. int res = 1;
  7928. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  7929. len = (size_t)(p - path);
  7930. if (len >= sizeof(buf)) {
  7931. /* path too long */
  7932. res = -1;
  7933. break;
  7934. }
  7935. memcpy(buf, path, len);
  7936. buf[len] = '\0';
  7937. /* Try to create intermediate directory */
  7938. DEBUG_TRACE("mkdir(%s)", buf);
  7939. if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) {
  7940. /* path does not exixt and can not be created */
  7941. res = -2;
  7942. break;
  7943. }
  7944. /* Is path itself a directory? */
  7945. if (p[1] == '\0') {
  7946. res = 0;
  7947. }
  7948. }
  7949. return res;
  7950. }
  7951. static void
  7952. remove_bad_file(const struct mg_connection *conn, const char *path)
  7953. {
  7954. int r = mg_remove(conn, path);
  7955. if (r != 0) {
  7956. mg_cry(conn, "%s: Cannot remove invalid file %s", __func__, path);
  7957. }
  7958. }
  7959. long long
  7960. mg_store_body(struct mg_connection *conn, const char *path)
  7961. {
  7962. char buf[MG_BUF_LEN];
  7963. long long len = 0;
  7964. int ret, n;
  7965. struct mg_file fi;
  7966. if (conn->consumed_content != 0) {
  7967. mg_cry(conn, "%s: Contents already consumed", __func__);
  7968. return -11;
  7969. }
  7970. ret = put_dir(conn, path);
  7971. if (ret < 0) {
  7972. /* -1 for path too long,
  7973. * -2 for path can not be created. */
  7974. return ret;
  7975. }
  7976. if (ret != 1) {
  7977. /* Return 0 means, path itself is a directory. */
  7978. return 0;
  7979. }
  7980. if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) {
  7981. return -12;
  7982. }
  7983. ret = mg_read(conn, buf, sizeof(buf));
  7984. while (ret > 0) {
  7985. n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp);
  7986. if (n != ret) {
  7987. (void)mg_fclose(
  7988. &fi.access); /* File is bad and will be removed anyway. */
  7989. remove_bad_file(conn, path);
  7990. return -13;
  7991. }
  7992. len += ret;
  7993. ret = mg_read(conn, buf, sizeof(buf));
  7994. }
  7995. /* File is open for writing. If fclose fails, there was probably an
  7996. * error flushing the buffer to disk, so the file on disk might be
  7997. * broken. Delete it and return an error to the caller. */
  7998. if (mg_fclose(&fi.access) != 0) {
  7999. remove_bad_file(conn, path);
  8000. return -14;
  8001. }
  8002. return len;
  8003. }
  8004. /* Parse a buffer:
  8005. * Forward the string pointer till the end of a word, then
  8006. * terminate it and forward till the begin of the next word.
  8007. */
  8008. static int
  8009. skip_to_end_of_word_and_terminate(char **ppw, int eol)
  8010. {
  8011. /* Forward until a space is found - use isgraph here */
  8012. /* See http://www.cplusplus.com/reference/cctype/ */
  8013. while (isgraph(**ppw)) {
  8014. (*ppw)++;
  8015. }
  8016. /* Check end of word */
  8017. if (eol) {
  8018. /* must be a end of line */
  8019. if ((**ppw != '\r') && (**ppw != '\n')) {
  8020. return -1;
  8021. }
  8022. } else {
  8023. /* must be a end of a word, but not a line */
  8024. if (**ppw != ' ') {
  8025. return -1;
  8026. }
  8027. }
  8028. /* Terminate and forward to the next word */
  8029. do {
  8030. **ppw = 0;
  8031. (*ppw)++;
  8032. } while ((**ppw) && isspace(**ppw));
  8033. /* Check after term */
  8034. if (!eol) {
  8035. /* if it's not the end of line, there must be a next word */
  8036. if (!isgraph(**ppw)) {
  8037. return -1;
  8038. }
  8039. }
  8040. /* ok */
  8041. return 1;
  8042. }
  8043. /* Parse HTTP headers from the given buffer, advance buf pointer
  8044. * to the point where parsing stopped.
  8045. * All parameters must be valid pointers (not NULL).
  8046. * Return <0 on error. */
  8047. static int
  8048. parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS])
  8049. {
  8050. int i;
  8051. int num_headers = 0;
  8052. for (i = 0; i < (int)MG_MAX_HEADERS; i++) {
  8053. char *dp = *buf;
  8054. while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) {
  8055. dp++;
  8056. }
  8057. if (dp == *buf) {
  8058. /* End of headers reached. */
  8059. break;
  8060. }
  8061. if (*dp != ':') {
  8062. /* This is not a valid field. */
  8063. return -1;
  8064. }
  8065. /* End of header key (*dp == ':') */
  8066. /* Truncate here and set the key name */
  8067. *dp = 0;
  8068. hdr[i].name = *buf;
  8069. do {
  8070. dp++;
  8071. } while (*dp == ' ');
  8072. /* The rest of the line is the value */
  8073. hdr[i].value = dp;
  8074. *buf = dp + strcspn(dp, "\r\n");
  8075. if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) {
  8076. *buf = NULL;
  8077. }
  8078. num_headers = i + 1;
  8079. if (*buf) {
  8080. (*buf)[0] = 0;
  8081. (*buf)[1] = 0;
  8082. *buf += 2;
  8083. } else {
  8084. *buf = dp;
  8085. break;
  8086. }
  8087. if ((*buf)[0] == '\r') {
  8088. /* This is the end of the header */
  8089. break;
  8090. }
  8091. }
  8092. return num_headers;
  8093. }
  8094. struct mg_http_method_info {
  8095. const char *name;
  8096. int request_has_body;
  8097. int response_has_body;
  8098. int is_safe;
  8099. int is_idempotent;
  8100. int is_cacheable;
  8101. };
  8102. /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */
  8103. static struct mg_http_method_info http_methods[] = {
  8104. /* HTTP (RFC 2616) */
  8105. {"GET", 0, 1, 1, 1, 1},
  8106. {"POST", 1, 1, 0, 0, 0},
  8107. {"PUT", 1, 0, 0, 1, 0},
  8108. {"DELETE", 0, 0, 0, 1, 0},
  8109. {"HEAD", 0, 0, 1, 1, 1},
  8110. {"OPTIONS", 0, 0, 1, 1, 0},
  8111. {"CONNECT", 1, 1, 0, 0, 0},
  8112. /* TRACE method (RFC 2616) is not supported for security reasons */
  8113. /* PATCH method (RFC 5789) */
  8114. {"PATCH", 1, 0, 0, 0, 0},
  8115. /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */
  8116. /* WEBDAV (RFC 2518) */
  8117. {"PROPFIND", 0, 1, 1, 1, 0},
  8118. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8119. * Some PROPFIND results MAY be cached, with care,
  8120. * as there is no cache validation mechanism for
  8121. * most properties. This method is both safe and
  8122. * idempotent (see Section 9.1 of [RFC2616]). */
  8123. {"MKCOL", 0, 0, 0, 1, 0},
  8124. /* http://www.webdav.org/specs/rfc4918.html, 9.1:
  8125. * When MKCOL is invoked without a request body,
  8126. * the newly created collection SHOULD have no
  8127. * members. A MKCOL request message may contain
  8128. * a message body. The precise behavior of a MKCOL
  8129. * request when the body is present is undefined,
  8130. * ... ==> We do not support MKCOL with body data.
  8131. * This method is idempotent, but not safe (see
  8132. * Section 9.1 of [RFC2616]). Responses to this
  8133. * method MUST NOT be cached. */
  8134. /* Unsupported WEBDAV Methods: */
  8135. /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */
  8136. /* + 11 methods from RFC 3253 */
  8137. /* ORDERPATCH (RFC 3648) */
  8138. /* ACL (RFC 3744) */
  8139. /* SEARCH (RFC 5323) */
  8140. /* + MicroSoft extensions
  8141. * https://msdn.microsoft.com/en-us/library/aa142917.aspx */
  8142. /* REPORT method (RFC 3253) */
  8143. {"REPORT", 1, 1, 1, 1, 1},
  8144. /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */
  8145. /* It was defined for WEBDAV in RFC 3253, Sec. 3.6
  8146. * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems
  8147. * to be useful for REST in case a "GET request with body" is
  8148. * required. */
  8149. {NULL, 0, 0, 0, 0, 0}
  8150. /* end of list */
  8151. };
  8152. static const struct mg_http_method_info *
  8153. get_http_method_info(const char *method)
  8154. {
  8155. /* Check if the method is known to the server. The list of all known
  8156. * HTTP methods can be found here at
  8157. * http://www.iana.org/assignments/http-methods/http-methods.xhtml
  8158. */
  8159. const struct mg_http_method_info *m = http_methods;
  8160. while (m->name) {
  8161. if (!strcmp(m->name, method)) {
  8162. return m;
  8163. }
  8164. m++;
  8165. }
  8166. return NULL;
  8167. }
  8168. static int
  8169. is_valid_http_method(const char *method)
  8170. {
  8171. return (get_http_method_info(method) != NULL);
  8172. }
  8173. /* Parse HTTP request, fill in mg_request_info structure.
  8174. * This function modifies the buffer by NUL-terminating
  8175. * HTTP request components, header names and header values.
  8176. * Parameters:
  8177. * buf (in/out): pointer to the HTTP header to parse and split
  8178. * len (in): length of HTTP header buffer
  8179. * re (out): parsed header as mg_request_info
  8180. * buf and ri must be valid pointers (not NULL), len>0.
  8181. * Returns <0 on error. */
  8182. static int
  8183. parse_http_request(char *buf, int len, struct mg_request_info *ri)
  8184. {
  8185. int request_length;
  8186. int init_skip = 0;
  8187. /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr,
  8188. * remote_port */
  8189. ri->remote_user = ri->request_method = ri->request_uri = ri->http_version =
  8190. NULL;
  8191. ri->num_headers = 0;
  8192. /* RFC says that all initial whitespaces should be ingored */
  8193. /* This included all leading \r and \n (isspace) */
  8194. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8195. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8196. buf++;
  8197. len--;
  8198. init_skip++;
  8199. }
  8200. if (len == 0) {
  8201. /* Incomplete request */
  8202. return 0;
  8203. }
  8204. /* Control characters are not allowed, including zero */
  8205. if (iscntrl(*(unsigned char *)buf)) {
  8206. return -1;
  8207. }
  8208. /* Find end of HTTP header */
  8209. request_length = get_http_header_len(buf, len);
  8210. if (request_length <= 0) {
  8211. return request_length;
  8212. }
  8213. buf[request_length - 1] = '\0';
  8214. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8215. return -1;
  8216. }
  8217. /* The first word has to be the HTTP method */
  8218. ri->request_method = buf;
  8219. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8220. return -1;
  8221. }
  8222. /* Check for a valid http method */
  8223. if (!is_valid_http_method(ri->request_method)) {
  8224. return -1;
  8225. }
  8226. /* The second word is the URI */
  8227. ri->request_uri = buf;
  8228. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8229. return -1;
  8230. }
  8231. /* Next would be the HTTP version */
  8232. ri->http_version = buf;
  8233. if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) {
  8234. return -1;
  8235. }
  8236. /* Check for a valid HTTP version key */
  8237. if (strncmp(ri->http_version, "HTTP/", 5) != 0) {
  8238. /* Invalid request */
  8239. return -1;
  8240. }
  8241. ri->http_version += 5;
  8242. /* Parse all HTTP headers */
  8243. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8244. if (ri->num_headers < 0) {
  8245. /* Error while parsing headers */
  8246. return -1;
  8247. }
  8248. return request_length + init_skip;
  8249. }
  8250. static int
  8251. parse_http_response(char *buf, int len, struct mg_response_info *ri)
  8252. {
  8253. int response_length;
  8254. int init_skip = 0;
  8255. char *tmp, *tmp2;
  8256. long l;
  8257. /* Initialize elements. */
  8258. ri->http_version = ri->status_text = NULL;
  8259. ri->num_headers = ri->status_code = 0;
  8260. /* RFC says that all initial whitespaces should be ingored */
  8261. /* This included all leading \r and \n (isspace) */
  8262. /* See table: http://www.cplusplus.com/reference/cctype/ */
  8263. while ((len > 0) && isspace(*(unsigned char *)buf)) {
  8264. buf++;
  8265. len--;
  8266. init_skip++;
  8267. }
  8268. if (len == 0) {
  8269. /* Incomplete request */
  8270. return 0;
  8271. }
  8272. /* Control characters are not allowed, including zero */
  8273. if (iscntrl(*(unsigned char *)buf)) {
  8274. return -1;
  8275. }
  8276. /* Find end of HTTP header */
  8277. response_length = get_http_header_len(buf, len);
  8278. if (response_length <= 0) {
  8279. return response_length;
  8280. }
  8281. buf[response_length - 1] = '\0';
  8282. if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) {
  8283. return -1;
  8284. }
  8285. /* The first word is the HTTP version */
  8286. /* Check for a valid HTTP version key */
  8287. if (strncmp(buf, "HTTP/", 5) != 0) {
  8288. /* Invalid request */
  8289. return -1;
  8290. }
  8291. buf += 5;
  8292. if (!isgraph(buf[0])) {
  8293. /* Invalid request */
  8294. return -1;
  8295. }
  8296. ri->http_version = buf;
  8297. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8298. return -1;
  8299. }
  8300. /* The second word is the status as a number */
  8301. tmp = buf;
  8302. if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) {
  8303. return -1;
  8304. }
  8305. l = strtol(tmp, &tmp2, 10);
  8306. if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) {
  8307. /* Everything else but a 3 digit code is invalid */
  8308. return -1;
  8309. }
  8310. ri->status_code = (int)l;
  8311. /* The rest of the line is the status text */
  8312. ri->status_text = buf;
  8313. /* Find end of status text */
  8314. /* isgraph or isspace = isprint */
  8315. while (isprint(*buf)) {
  8316. buf++;
  8317. }
  8318. if ((*buf != '\r') && (*buf != '\n')) {
  8319. return -1;
  8320. }
  8321. /* Terminate string and forward buf to next line */
  8322. do {
  8323. *buf = 0;
  8324. buf++;
  8325. } while ((*buf) && isspace(*buf));
  8326. /* Parse all HTTP headers */
  8327. ri->num_headers = parse_http_headers(&buf, ri->http_headers);
  8328. if (ri->num_headers < 0) {
  8329. /* Error while parsing headers */
  8330. return -1;
  8331. }
  8332. return response_length + init_skip;
  8333. }
  8334. /* Keep reading the input (either opened file descriptor fd, or socket sock,
  8335. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  8336. * buffer (which marks the end of HTTP request). Buffer buf may already
  8337. * have some data. The length of the data is stored in nread.
  8338. * Upon every read operation, increase nread by the number of bytes read. */
  8339. static int
  8340. read_message(FILE *fp,
  8341. struct mg_connection *conn,
  8342. char *buf,
  8343. int bufsiz,
  8344. int *nread)
  8345. {
  8346. int request_len, n = 0;
  8347. struct timespec last_action_time;
  8348. double request_timeout;
  8349. if (!conn) {
  8350. return 0;
  8351. }
  8352. memset(&last_action_time, 0, sizeof(last_action_time));
  8353. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8354. /* value of request_timeout is in seconds, config in milliseconds */
  8355. request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8356. } else {
  8357. request_timeout = -1.0;
  8358. }
  8359. if (conn->handled_requests > 0) {
  8360. if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) {
  8361. request_timeout =
  8362. atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0;
  8363. }
  8364. }
  8365. request_len = get_http_header_len(buf, *nread);
  8366. /* first time reading from this connection */
  8367. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8368. while (request_len == 0) {
  8369. /* Full request not yet received */
  8370. if (conn->phys_ctx->stop_flag != 0) {
  8371. /* Server is to be stopped. */
  8372. return -1;
  8373. }
  8374. if (*nread >= bufsiz) {
  8375. /* Request too long */
  8376. return -2;
  8377. }
  8378. n = pull_inner(
  8379. fp, conn, buf + *nread, bufsiz - *nread, request_timeout);
  8380. if (n == -2) {
  8381. /* Receive error */
  8382. return -1;
  8383. }
  8384. if (n > 0) {
  8385. *nread += n;
  8386. request_len = get_http_header_len(buf, *nread);
  8387. } else {
  8388. request_len = 0;
  8389. }
  8390. if ((request_len == 0) && (request_timeout >= 0)) {
  8391. if (mg_difftimespec(&last_action_time, &(conn->req_time))
  8392. > request_timeout) {
  8393. /* Timeout */
  8394. return -1;
  8395. }
  8396. clock_gettime(CLOCK_MONOTONIC, &last_action_time);
  8397. }
  8398. }
  8399. return request_len;
  8400. }
  8401. #if !defined(NO_CGI) || !defined(NO_FILES)
  8402. static int
  8403. forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl)
  8404. {
  8405. const char *expect, *body;
  8406. char buf[MG_BUF_LEN];
  8407. int to_read, nread, success = 0;
  8408. int64_t buffered_len;
  8409. double timeout = -1.0;
  8410. if (!conn) {
  8411. return 0;
  8412. }
  8413. if (conn->dom_ctx->config[REQUEST_TIMEOUT]) {
  8414. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  8415. }
  8416. expect = mg_get_header(conn, "Expect");
  8417. DEBUG_ASSERT(fp != NULL);
  8418. if (!fp) {
  8419. mg_send_http_error(conn, 500, "%s", "Error: NULL File");
  8420. return 0;
  8421. }
  8422. if ((conn->content_len == -1) && (!conn->is_chunked)) {
  8423. /* Content length is not specified by the client. */
  8424. mg_send_http_error(conn,
  8425. 411,
  8426. "%s",
  8427. "Error: Client did not specify content length");
  8428. } else if ((expect != NULL)
  8429. && (mg_strcasecmp(expect, "100-continue") != 0)) {
  8430. /* Client sent an "Expect: xyz" header and xyz is not 100-continue.
  8431. */
  8432. mg_send_http_error(conn,
  8433. 417,
  8434. "Error: Can not fulfill expectation %s",
  8435. expect);
  8436. } else {
  8437. if (expect != NULL) {
  8438. (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  8439. conn->status_code = 100;
  8440. } else {
  8441. conn->status_code = 200;
  8442. }
  8443. buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len
  8444. - conn->consumed_content;
  8445. DEBUG_ASSERT(buffered_len >= 0);
  8446. DEBUG_ASSERT(conn->consumed_content == 0);
  8447. if ((buffered_len < 0) || (conn->consumed_content != 0)) {
  8448. mg_send_http_error(conn, 500, "%s", "Error: Size mismatch");
  8449. return 0;
  8450. }
  8451. if (buffered_len > 0) {
  8452. if ((int64_t)buffered_len > conn->content_len) {
  8453. buffered_len = (int)conn->content_len;
  8454. }
  8455. body = conn->buf + conn->request_len + conn->consumed_content;
  8456. push_all(
  8457. conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len);
  8458. conn->consumed_content += buffered_len;
  8459. }
  8460. nread = 0;
  8461. while (conn->consumed_content < conn->content_len) {
  8462. to_read = sizeof(buf);
  8463. if ((int64_t)to_read > conn->content_len - conn->consumed_content) {
  8464. to_read = (int)(conn->content_len - conn->consumed_content);
  8465. }
  8466. nread = pull_inner(NULL, conn, buf, to_read, timeout);
  8467. if (nread == -2) {
  8468. /* error */
  8469. break;
  8470. }
  8471. if (nread > 0) {
  8472. if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread)
  8473. != nread) {
  8474. break;
  8475. }
  8476. }
  8477. conn->consumed_content += nread;
  8478. }
  8479. if (conn->consumed_content == conn->content_len) {
  8480. success = (nread >= 0);
  8481. }
  8482. /* Each error code path in this function must send an error */
  8483. if (!success) {
  8484. /* NOTE: Maybe some data has already been sent. */
  8485. /* TODO (low): If some data has been sent, a correct error
  8486. * reply can no longer be sent, so just close the connection */
  8487. mg_send_http_error(conn, 500, "%s", "");
  8488. }
  8489. }
  8490. return success;
  8491. }
  8492. #endif
  8493. #if !defined(NO_CGI)
  8494. /* This structure helps to create an environment for the spawned CGI
  8495. * program.
  8496. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  8497. * last element must be NULL.
  8498. * However, on Windows there is a requirement that all these
  8499. * VARIABLE=VALUE\0
  8500. * strings must reside in a contiguous buffer. The end of the buffer is
  8501. * marked by two '\0' characters.
  8502. * We satisfy both worlds: we create an envp array (which is vars), all
  8503. * entries are actually pointers inside buf. */
  8504. struct cgi_environment {
  8505. struct mg_connection *conn;
  8506. /* Data block */
  8507. char *buf; /* Environment buffer */
  8508. size_t buflen; /* Space available in buf */
  8509. size_t bufused; /* Space taken in buf */
  8510. /* Index block */
  8511. char **var; /* char **envp */
  8512. size_t varlen; /* Number of variables available in var */
  8513. size_t varused; /* Number of variables stored in var */
  8514. };
  8515. static void addenv(struct cgi_environment *env,
  8516. PRINTF_FORMAT_STRING(const char *fmt),
  8517. ...) PRINTF_ARGS(2, 3);
  8518. /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  8519. * pointer into the vars array. Assumes env != NULL and fmt != NULL. */
  8520. static void
  8521. addenv(struct cgi_environment *env, const char *fmt, ...)
  8522. {
  8523. size_t n, space;
  8524. int truncated = 0;
  8525. char *added;
  8526. va_list ap;
  8527. /* Calculate how much space is left in the buffer */
  8528. space = (env->buflen - env->bufused);
  8529. /* Calculate an estimate for the required space */
  8530. n = strlen(fmt) + 2 + 128;
  8531. do {
  8532. if (space <= n) {
  8533. /* Allocate new buffer */
  8534. n = env->buflen + CGI_ENVIRONMENT_SIZE;
  8535. added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx);
  8536. if (!added) {
  8537. /* Out of memory */
  8538. mg_cry(env->conn,
  8539. "%s: Cannot allocate memory for CGI variable [%s]",
  8540. __func__,
  8541. fmt);
  8542. return;
  8543. }
  8544. env->buf = added;
  8545. env->buflen = n;
  8546. space = (env->buflen - env->bufused);
  8547. }
  8548. /* Make a pointer to the free space int the buffer */
  8549. added = env->buf + env->bufused;
  8550. /* Copy VARIABLE=VALUE\0 string into the free space */
  8551. va_start(ap, fmt);
  8552. mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap);
  8553. va_end(ap);
  8554. /* Do not add truncated strings to the environment */
  8555. if (truncated) {
  8556. /* Reallocate the buffer */
  8557. space = 0;
  8558. n = 1;
  8559. }
  8560. } while (truncated);
  8561. /* Calculate number of bytes added to the environment */
  8562. n = strlen(added) + 1;
  8563. env->bufused += n;
  8564. /* Now update the variable index */
  8565. space = (env->varlen - env->varused);
  8566. if (space < 2) {
  8567. mg_cry(env->conn,
  8568. "%s: Cannot register CGI variable [%s]",
  8569. __func__,
  8570. fmt);
  8571. return;
  8572. }
  8573. /* Append a pointer to the added string into the envp array */
  8574. env->var[env->varused] = added;
  8575. env->varused++;
  8576. }
  8577. /* Return 0 on success, non-zero if an error occurs. */
  8578. static int
  8579. prepare_cgi_environment(struct mg_connection *conn,
  8580. const char *prog,
  8581. struct cgi_environment *env)
  8582. {
  8583. const char *s;
  8584. struct vec var_vec;
  8585. char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128];
  8586. int i, truncated, uri_len;
  8587. if ((conn == NULL) || (prog == NULL) || (env == NULL)) {
  8588. return -1;
  8589. }
  8590. env->conn = conn;
  8591. env->buflen = CGI_ENVIRONMENT_SIZE;
  8592. env->bufused = 0;
  8593. env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx);
  8594. if (env->buf == NULL) {
  8595. mg_cry(conn,
  8596. "%s: Not enough memory for environmental buffer",
  8597. __func__);
  8598. return -1;
  8599. }
  8600. env->varlen = MAX_CGI_ENVIR_VARS;
  8601. env->varused = 0;
  8602. env->var =
  8603. (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx);
  8604. if (env->var == NULL) {
  8605. mg_cry(conn,
  8606. "%s: Not enough memory for environmental variables",
  8607. __func__);
  8608. mg_free(env->buf);
  8609. return -1;
  8610. }
  8611. addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]);
  8612. addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8613. addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8614. addenv(env, "SERVER_SOFTWARE=%s/%s", "Civetweb", mg_version());
  8615. /* Prepare the environment block */
  8616. addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  8617. addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  8618. addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */
  8619. #if defined(USE_IPV6)
  8620. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  8621. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port));
  8622. } else
  8623. #endif
  8624. {
  8625. addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  8626. }
  8627. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  8628. addenv(env, "REMOTE_ADDR=%s", src_addr);
  8629. addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method);
  8630. addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port);
  8631. addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri);
  8632. addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri);
  8633. /* SCRIPT_NAME */
  8634. uri_len = (int)strlen(conn->request_info.local_uri);
  8635. if (conn->path_info == NULL) {
  8636. if (conn->request_info.local_uri[uri_len - 1] != '/') {
  8637. /* URI: /path_to_script/script.cgi */
  8638. addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri);
  8639. } else {
  8640. /* URI: /path_to_script/ ... using index.cgi */
  8641. const char *index_file = strrchr(prog, '/');
  8642. if (index_file) {
  8643. addenv(env,
  8644. "SCRIPT_NAME=%s%s",
  8645. conn->request_info.local_uri,
  8646. index_file + 1);
  8647. }
  8648. }
  8649. } else {
  8650. /* URI: /path_to_script/script.cgi/path_info */
  8651. addenv(env,
  8652. "SCRIPT_NAME=%.*s",
  8653. uri_len - (int)strlen(conn->path_info),
  8654. conn->request_info.local_uri);
  8655. }
  8656. addenv(env, "SCRIPT_FILENAME=%s", prog);
  8657. if (conn->path_info == NULL) {
  8658. addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]);
  8659. } else {
  8660. addenv(env,
  8661. "PATH_TRANSLATED=%s%s",
  8662. conn->dom_ctx->config[DOCUMENT_ROOT],
  8663. conn->path_info);
  8664. }
  8665. addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on");
  8666. if ((s = mg_get_header(conn, "Content-Type")) != NULL) {
  8667. addenv(env, "CONTENT_TYPE=%s", s);
  8668. }
  8669. if (conn->request_info.query_string != NULL) {
  8670. addenv(env, "QUERY_STRING=%s", conn->request_info.query_string);
  8671. }
  8672. if ((s = mg_get_header(conn, "Content-Length")) != NULL) {
  8673. addenv(env, "CONTENT_LENGTH=%s", s);
  8674. }
  8675. if ((s = getenv("PATH")) != NULL) {
  8676. addenv(env, "PATH=%s", s);
  8677. }
  8678. if (conn->path_info != NULL) {
  8679. addenv(env, "PATH_INFO=%s", conn->path_info);
  8680. }
  8681. if (conn->status_code > 0) {
  8682. /* CGI error handler should show the status code */
  8683. addenv(env, "STATUS=%d", conn->status_code);
  8684. }
  8685. #if defined(_WIN32)
  8686. if ((s = getenv("COMSPEC")) != NULL) {
  8687. addenv(env, "COMSPEC=%s", s);
  8688. }
  8689. if ((s = getenv("SYSTEMROOT")) != NULL) {
  8690. addenv(env, "SYSTEMROOT=%s", s);
  8691. }
  8692. if ((s = getenv("SystemDrive")) != NULL) {
  8693. addenv(env, "SystemDrive=%s", s);
  8694. }
  8695. if ((s = getenv("ProgramFiles")) != NULL) {
  8696. addenv(env, "ProgramFiles=%s", s);
  8697. }
  8698. if ((s = getenv("ProgramFiles(x86)")) != NULL) {
  8699. addenv(env, "ProgramFiles(x86)=%s", s);
  8700. }
  8701. #else
  8702. if ((s = getenv("LD_LIBRARY_PATH")) != NULL) {
  8703. addenv(env, "LD_LIBRARY_PATH=%s", s);
  8704. }
  8705. #endif /* _WIN32 */
  8706. if ((s = getenv("PERLLIB")) != NULL) {
  8707. addenv(env, "PERLLIB=%s", s);
  8708. }
  8709. if (conn->request_info.remote_user != NULL) {
  8710. addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user);
  8711. addenv(env, "%s", "AUTH_TYPE=Digest");
  8712. }
  8713. /* Add all headers as HTTP_* variables */
  8714. for (i = 0; i < conn->request_info.num_headers; i++) {
  8715. (void)mg_snprintf(conn,
  8716. &truncated,
  8717. http_var_name,
  8718. sizeof(http_var_name),
  8719. "HTTP_%s",
  8720. conn->request_info.http_headers[i].name);
  8721. if (truncated) {
  8722. mg_cry(conn,
  8723. "%s: HTTP header variable too long [%s]",
  8724. __func__,
  8725. conn->request_info.http_headers[i].name);
  8726. continue;
  8727. }
  8728. /* Convert variable name into uppercase, and change - to _ */
  8729. for (p = http_var_name; *p != '\0'; p++) {
  8730. if (*p == '-') {
  8731. *p = '_';
  8732. }
  8733. *p = (char)toupper(*(unsigned char *)p);
  8734. }
  8735. addenv(env,
  8736. "%s=%s",
  8737. http_var_name,
  8738. conn->request_info.http_headers[i].value);
  8739. }
  8740. /* Add user-specified variables */
  8741. s = conn->dom_ctx->config[CGI_ENVIRONMENT];
  8742. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  8743. addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr);
  8744. }
  8745. env->var[env->varused] = NULL;
  8746. env->buf[env->bufused] = '\0';
  8747. return 0;
  8748. }
  8749. static void
  8750. handle_cgi_request(struct mg_connection *conn, const char *prog)
  8751. {
  8752. char *buf;
  8753. size_t buflen;
  8754. int headers_len, data_len, i, truncated;
  8755. int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1};
  8756. const char *status, *status_text, *connection_state;
  8757. char *pbuf, dir[PATH_MAX], *p;
  8758. struct mg_request_info ri;
  8759. struct cgi_environment blk;
  8760. FILE *in = NULL, *out = NULL, *err = NULL;
  8761. struct mg_file fout = STRUCT_FILE_INITIALIZER;
  8762. pid_t pid = (pid_t)-1;
  8763. if (conn == NULL) {
  8764. return;
  8765. }
  8766. buf = NULL;
  8767. buflen = 16384;
  8768. i = prepare_cgi_environment(conn, prog, &blk);
  8769. if (i != 0) {
  8770. blk.buf = NULL;
  8771. blk.var = NULL;
  8772. goto done;
  8773. }
  8774. /* CGI must be executed in its own directory. 'dir' must point to the
  8775. * directory containing executable program, 'p' must point to the
  8776. * executable program name relative to 'dir'. */
  8777. (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog);
  8778. if (truncated) {
  8779. mg_cry(conn, "Error: CGI program \"%s\": Path too long", prog);
  8780. mg_send_http_error(conn, 500, "Error: %s", "CGI path too long");
  8781. goto done;
  8782. }
  8783. if ((p = strrchr(dir, '/')) != NULL) {
  8784. *p++ = '\0';
  8785. } else {
  8786. dir[0] = '.';
  8787. dir[1] = '\0';
  8788. p = (char *)prog;
  8789. }
  8790. if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) {
  8791. status = strerror(ERRNO);
  8792. mg_cry(conn,
  8793. "Error: CGI program \"%s\": Can not create CGI pipes: %s",
  8794. prog,
  8795. status);
  8796. mg_send_http_error(conn,
  8797. 500,
  8798. "Error: Cannot create CGI pipe: %s",
  8799. status);
  8800. goto done;
  8801. }
  8802. DEBUG_TRACE("CGI: spawn %s %s\n", dir, p);
  8803. pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir);
  8804. if (pid == (pid_t)-1) {
  8805. status = strerror(ERRNO);
  8806. mg_cry(conn,
  8807. "Error: CGI program \"%s\": Can not spawn CGI process: %s",
  8808. prog,
  8809. status);
  8810. mg_send_http_error(conn,
  8811. 500,
  8812. "Error: Cannot spawn CGI process [%s]: %s",
  8813. prog,
  8814. status);
  8815. goto done;
  8816. }
  8817. /* Make sure child closes all pipe descriptors. It must dup them to 0,1
  8818. */
  8819. set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */
  8820. set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */
  8821. set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */
  8822. set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */
  8823. set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */
  8824. set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */
  8825. /* Parent closes only one side of the pipes.
  8826. * If we don't mark them as closed, close() attempt before
  8827. * return from this function throws an exception on Windows.
  8828. * Windows does not like when closed descriptor is closed again. */
  8829. (void)close(fdin[0]);
  8830. (void)close(fdout[1]);
  8831. (void)close(fderr[1]);
  8832. fdin[0] = fdout[1] = fderr[1] = -1;
  8833. if ((in = fdopen(fdin[1], "wb")) == NULL) {
  8834. status = strerror(ERRNO);
  8835. mg_cry(conn,
  8836. "Error: CGI program \"%s\": Can not open stdin: %s",
  8837. prog,
  8838. status);
  8839. mg_send_http_error(conn,
  8840. 500,
  8841. "Error: CGI can not open fdin\nfopen: %s",
  8842. status);
  8843. goto done;
  8844. }
  8845. if ((out = fdopen(fdout[0], "rb")) == NULL) {
  8846. status = strerror(ERRNO);
  8847. mg_cry(conn,
  8848. "Error: CGI program \"%s\": Can not open stdout: %s",
  8849. prog,
  8850. status);
  8851. mg_send_http_error(conn,
  8852. 500,
  8853. "Error: CGI can not open fdout\nfopen: %s",
  8854. status);
  8855. goto done;
  8856. }
  8857. if ((err = fdopen(fderr[0], "rb")) == NULL) {
  8858. status = strerror(ERRNO);
  8859. mg_cry(conn,
  8860. "Error: CGI program \"%s\": Can not open stderr: %s",
  8861. prog,
  8862. status);
  8863. mg_send_http_error(conn,
  8864. 500,
  8865. "Error: CGI can not open fdout\nfopen: %s",
  8866. status);
  8867. goto done;
  8868. }
  8869. setbuf(in, NULL);
  8870. setbuf(out, NULL);
  8871. setbuf(err, NULL);
  8872. fout.access.fp = out;
  8873. if ((conn->request_info.content_length != 0) || (conn->is_chunked)) {
  8874. DEBUG_TRACE("CGI: send body data (%lli)\n",
  8875. (signed long long)conn->request_info.content_length);
  8876. /* This is a POST/PUT request, or another request with body data. */
  8877. if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  8878. /* Error sending the body data */
  8879. mg_cry(conn,
  8880. "Error: CGI program \"%s\": Forward body data failed",
  8881. prog);
  8882. goto done;
  8883. }
  8884. }
  8885. /* Close so child gets an EOF. */
  8886. fclose(in);
  8887. in = NULL;
  8888. fdin[1] = -1;
  8889. /* Now read CGI reply into a buffer. We need to set correct
  8890. * status code, thus we need to see all HTTP headers first.
  8891. * Do not send anything back to client, until we buffer in all
  8892. * HTTP headers. */
  8893. data_len = 0;
  8894. buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx);
  8895. if (buf == NULL) {
  8896. mg_send_http_error(conn,
  8897. 500,
  8898. "Error: Not enough memory for CGI buffer (%u bytes)",
  8899. (unsigned int)buflen);
  8900. mg_cry(conn,
  8901. "Error: CGI program \"%s\": Not enough memory for buffer (%u "
  8902. "bytes)",
  8903. prog,
  8904. (unsigned int)buflen);
  8905. goto done;
  8906. }
  8907. DEBUG_TRACE("CGI: %s", "wait for response");
  8908. headers_len = read_message(out, conn, buf, (int)buflen, &data_len);
  8909. DEBUG_TRACE("CGI: response: %li", (signed long)headers_len);
  8910. if (headers_len <= 0) {
  8911. /* Could not parse the CGI response. Check if some error message on
  8912. * stderr. */
  8913. i = pull_all(err, conn, buf, (int)buflen);
  8914. if (i > 0) {
  8915. mg_cry(conn,
  8916. "Error: CGI program \"%s\" sent error "
  8917. "message: [%.*s]",
  8918. prog,
  8919. i,
  8920. buf);
  8921. mg_send_http_error(conn,
  8922. 500,
  8923. "Error: CGI program \"%s\" sent error "
  8924. "message: [%.*s]",
  8925. prog,
  8926. i,
  8927. buf);
  8928. } else {
  8929. mg_cry(conn,
  8930. "Error: CGI program sent malformed or too big "
  8931. "(>%u bytes) HTTP headers: [%.*s]",
  8932. (unsigned)buflen,
  8933. data_len,
  8934. buf);
  8935. mg_send_http_error(conn,
  8936. 500,
  8937. "Error: CGI program sent malformed or too big "
  8938. "(>%u bytes) HTTP headers: [%.*s]",
  8939. (unsigned)buflen,
  8940. data_len,
  8941. buf);
  8942. }
  8943. goto done;
  8944. }
  8945. pbuf = buf;
  8946. buf[headers_len - 1] = '\0';
  8947. ri.num_headers = parse_http_headers(&pbuf, ri.http_headers);
  8948. /* Make up and send the status line */
  8949. status_text = "OK";
  8950. if ((status = get_header(ri.http_headers, ri.num_headers, "Status"))
  8951. != NULL) {
  8952. conn->status_code = atoi(status);
  8953. status_text = status;
  8954. while (isdigit(*(const unsigned char *)status_text)
  8955. || *status_text == ' ') {
  8956. status_text++;
  8957. }
  8958. } else if (get_header(ri.http_headers, ri.num_headers, "Location")
  8959. != NULL) {
  8960. conn->status_code = 302;
  8961. } else {
  8962. conn->status_code = 200;
  8963. }
  8964. connection_state =
  8965. get_header(ri.http_headers, ri.num_headers, "Connection");
  8966. if (!header_has_option(connection_state, "keep-alive")) {
  8967. conn->must_close = 1;
  8968. }
  8969. DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text);
  8970. (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text);
  8971. /* Send headers */
  8972. for (i = 0; i < ri.num_headers; i++) {
  8973. mg_printf(conn,
  8974. "%s: %s\r\n",
  8975. ri.http_headers[i].name,
  8976. ri.http_headers[i].value);
  8977. }
  8978. mg_write(conn, "\r\n", 2);
  8979. /* Send chunk of data that may have been read after the headers */
  8980. mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len));
  8981. /* Read the rest of CGI output and send to the client */
  8982. send_file_data(conn, &fout, 0, INT64_MAX);
  8983. DEBUG_TRACE("CGI: %s", "all data sent");
  8984. done:
  8985. mg_free(blk.var);
  8986. mg_free(blk.buf);
  8987. if (pid != (pid_t)-1) {
  8988. kill(pid, SIGKILL);
  8989. #if !defined(_WIN32)
  8990. {
  8991. int st;
  8992. while (waitpid(pid, &st, 0) != -1)
  8993. ; /* clean zombies */
  8994. }
  8995. #endif
  8996. }
  8997. if (fdin[0] != -1) {
  8998. close(fdin[0]);
  8999. }
  9000. if (fdout[1] != -1) {
  9001. close(fdout[1]);
  9002. }
  9003. if (in != NULL) {
  9004. fclose(in);
  9005. } else if (fdin[1] != -1) {
  9006. close(fdin[1]);
  9007. }
  9008. if (out != NULL) {
  9009. fclose(out);
  9010. } else if (fdout[0] != -1) {
  9011. close(fdout[0]);
  9012. }
  9013. if (err != NULL) {
  9014. fclose(err);
  9015. } else if (fderr[0] != -1) {
  9016. close(fderr[0]);
  9017. }
  9018. if (buf != NULL) {
  9019. mg_free(buf);
  9020. }
  9021. }
  9022. #endif /* !NO_CGI */
  9023. #if !defined(NO_FILES)
  9024. static void
  9025. mkcol(struct mg_connection *conn, const char *path)
  9026. {
  9027. int rc, body_len;
  9028. struct de de;
  9029. char date[64];
  9030. time_t curtime = time(NULL);
  9031. if (conn == NULL) {
  9032. return;
  9033. }
  9034. /* TODO (mid): Check the mg_send_http_error situations in this function
  9035. */
  9036. memset(&de.file, 0, sizeof(de.file));
  9037. if (!mg_stat(conn, path, &de.file)) {
  9038. mg_cry(conn,
  9039. "%s: mg_stat(%s) failed: %s",
  9040. __func__,
  9041. path,
  9042. strerror(ERRNO));
  9043. }
  9044. if (de.file.last_modified) {
  9045. /* TODO (mid): This check does not seem to make any sense ! */
  9046. /* TODO (mid): Add a webdav unit test first, before changing
  9047. * anything here. */
  9048. mg_send_http_error(
  9049. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9050. return;
  9051. }
  9052. body_len = conn->data_len - conn->request_len;
  9053. if (body_len > 0) {
  9054. mg_send_http_error(
  9055. conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9056. return;
  9057. }
  9058. rc = mg_mkdir(conn, path, 0755);
  9059. if (rc == 0) {
  9060. conn->status_code = 201;
  9061. gmt_time_string(date, sizeof(date), &curtime);
  9062. mg_printf(conn,
  9063. "HTTP/1.1 %d Created\r\n"
  9064. "Date: %s\r\n",
  9065. conn->status_code,
  9066. date);
  9067. send_static_cache_header(conn);
  9068. send_additional_header(conn);
  9069. mg_printf(conn,
  9070. "Content-Length: 0\r\n"
  9071. "Connection: %s\r\n\r\n",
  9072. suggest_connection_header(conn));
  9073. } else if (rc == -1) {
  9074. if (errno == EEXIST) {
  9075. mg_send_http_error(
  9076. conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9077. } else if (errno == EACCES) {
  9078. mg_send_http_error(
  9079. conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9080. } else if (errno == ENOENT) {
  9081. mg_send_http_error(
  9082. conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO));
  9083. } else {
  9084. mg_send_http_error(
  9085. conn, 500, "fopen(%s): %s", path, strerror(ERRNO));
  9086. }
  9087. }
  9088. }
  9089. static void
  9090. put_file(struct mg_connection *conn, const char *path)
  9091. {
  9092. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9093. const char *range;
  9094. int64_t r1, r2;
  9095. int rc;
  9096. char date[64];
  9097. time_t curtime = time(NULL);
  9098. if (conn == NULL) {
  9099. return;
  9100. }
  9101. if (mg_stat(conn, path, &file.stat)) {
  9102. /* File already exists */
  9103. conn->status_code = 200;
  9104. if (file.stat.is_directory) {
  9105. /* This is an already existing directory,
  9106. * so there is nothing to do for the server. */
  9107. rc = 0;
  9108. } else {
  9109. /* File exists and is not a directory. */
  9110. /* Can it be replaced? */
  9111. if (file.access.membuf != NULL) {
  9112. /* This is an "in-memory" file, that can not be replaced */
  9113. mg_send_http_error(conn,
  9114. 405,
  9115. "Error: Put not possible\nReplacing %s "
  9116. "is not supported",
  9117. path);
  9118. return;
  9119. }
  9120. /* Check if the server may write this file */
  9121. if (access(path, W_OK) == 0) {
  9122. /* Access granted */
  9123. conn->status_code = 200;
  9124. rc = 1;
  9125. } else {
  9126. mg_send_http_error(
  9127. conn,
  9128. 403,
  9129. "Error: Put not possible\nReplacing %s is not allowed",
  9130. path);
  9131. return;
  9132. }
  9133. }
  9134. } else {
  9135. /* File should be created */
  9136. conn->status_code = 201;
  9137. rc = put_dir(conn, path);
  9138. }
  9139. if (rc == 0) {
  9140. /* put_dir returns 0 if path is a directory */
  9141. gmt_time_string(date, sizeof(date), &curtime);
  9142. mg_printf(conn,
  9143. "HTTP/1.1 %d %s\r\n",
  9144. conn->status_code,
  9145. mg_get_response_code_text(NULL, conn->status_code));
  9146. send_no_cache_header(conn);
  9147. send_additional_header(conn);
  9148. mg_printf(conn,
  9149. "Date: %s\r\n"
  9150. "Content-Length: 0\r\n"
  9151. "Connection: %s\r\n\r\n",
  9152. date,
  9153. suggest_connection_header(conn));
  9154. /* Request to create a directory has been fulfilled successfully.
  9155. * No need to put a file. */
  9156. return;
  9157. }
  9158. if (rc == -1) {
  9159. /* put_dir returns -1 if the path is too long */
  9160. mg_send_http_error(conn,
  9161. 414,
  9162. "Error: Path too long\nput_dir(%s): %s",
  9163. path,
  9164. strerror(ERRNO));
  9165. return;
  9166. }
  9167. if (rc == -2) {
  9168. /* put_dir returns -2 if the directory can not be created */
  9169. mg_send_http_error(conn,
  9170. 500,
  9171. "Error: Can not create directory\nput_dir(%s): %s",
  9172. path,
  9173. strerror(ERRNO));
  9174. return;
  9175. }
  9176. /* A file should be created or overwritten. */
  9177. /* Currently CivetWeb does not nead read+write access. */
  9178. if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file)
  9179. || file.access.fp == NULL) {
  9180. (void)mg_fclose(&file.access);
  9181. mg_send_http_error(conn,
  9182. 500,
  9183. "Error: Can not create file\nfopen(%s): %s",
  9184. path,
  9185. strerror(ERRNO));
  9186. return;
  9187. }
  9188. fclose_on_exec(&file.access, conn);
  9189. range = mg_get_header(conn, "Content-Range");
  9190. r1 = r2 = 0;
  9191. if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) {
  9192. conn->status_code = 206; /* Partial content */
  9193. fseeko(file.access.fp, r1, SEEK_SET);
  9194. }
  9195. if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) {
  9196. /* forward_body_data failed.
  9197. * The error code has already been sent to the client,
  9198. * and conn->status_code is already set. */
  9199. (void)mg_fclose(&file.access);
  9200. return;
  9201. }
  9202. if (mg_fclose(&file.access) != 0) {
  9203. /* fclose failed. This might have different reasons, but a likely
  9204. * one is "no space on disk", http 507. */
  9205. conn->status_code = 507;
  9206. }
  9207. gmt_time_string(date, sizeof(date), &curtime);
  9208. mg_printf(conn,
  9209. "HTTP/1.1 %d %s\r\n",
  9210. conn->status_code,
  9211. mg_get_response_code_text(NULL, conn->status_code));
  9212. send_no_cache_header(conn);
  9213. send_additional_header(conn);
  9214. mg_printf(conn,
  9215. "Date: %s\r\n"
  9216. "Content-Length: 0\r\n"
  9217. "Connection: %s\r\n\r\n",
  9218. date,
  9219. suggest_connection_header(conn));
  9220. }
  9221. static void
  9222. delete_file(struct mg_connection *conn, const char *path)
  9223. {
  9224. struct de de;
  9225. memset(&de.file, 0, sizeof(de.file));
  9226. if (!mg_stat(conn, path, &de.file)) {
  9227. /* mg_stat returns 0 if the file does not exist */
  9228. mg_send_http_error(conn,
  9229. 404,
  9230. "Error: Cannot delete file\nFile %s not found",
  9231. path);
  9232. return;
  9233. }
  9234. #if 0 /* Ignore if a file in memory is inside a folder */
  9235. if (de.access.membuf != NULL) {
  9236. /* the file is cached in memory */
  9237. mg_send_http_error(
  9238. conn,
  9239. 405,
  9240. "Error: Delete not possible\nDeleting %s is not supported",
  9241. path);
  9242. return;
  9243. }
  9244. #endif
  9245. if (de.file.is_directory) {
  9246. if (remove_directory(conn, path)) {
  9247. /* Delete is successful: Return 204 without content. */
  9248. mg_send_http_error(conn, 204, "%s", "");
  9249. } else {
  9250. /* Delete is not successful: Return 500 (Server error). */
  9251. mg_send_http_error(conn, 500, "Error: Could not delete %s", path);
  9252. }
  9253. return;
  9254. }
  9255. /* This is an existing file (not a directory).
  9256. * Check if write permission is granted. */
  9257. if (access(path, W_OK) != 0) {
  9258. /* File is read only */
  9259. mg_send_http_error(
  9260. conn,
  9261. 403,
  9262. "Error: Delete not possible\nDeleting %s is not allowed",
  9263. path);
  9264. return;
  9265. }
  9266. /* Try to delete it. */
  9267. if (mg_remove(conn, path) == 0) {
  9268. /* Delete was successful: Return 204 without content. */
  9269. mg_send_http_error(conn, 204, "%s", "");
  9270. } else {
  9271. /* Delete not successful (file locked). */
  9272. mg_send_http_error(conn,
  9273. 423,
  9274. "Error: Cannot delete file\nremove(%s): %s",
  9275. path,
  9276. strerror(ERRNO));
  9277. }
  9278. }
  9279. #endif /* !NO_FILES */
  9280. static void
  9281. send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int);
  9282. static void
  9283. do_ssi_include(struct mg_connection *conn,
  9284. const char *ssi,
  9285. char *tag,
  9286. int include_level)
  9287. {
  9288. char file_name[MG_BUF_LEN], path[512], *p;
  9289. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9290. size_t len;
  9291. int truncated = 0;
  9292. if (conn == NULL) {
  9293. return;
  9294. }
  9295. /* sscanf() is safe here, since send_ssi_file() also uses buffer
  9296. * of size MG_BUF_LEN to get the tag. So strlen(tag) is
  9297. * always < MG_BUF_LEN. */
  9298. if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) {
  9299. /* File name is relative to the webserver root */
  9300. file_name[511] = 0;
  9301. (void)mg_snprintf(conn,
  9302. &truncated,
  9303. path,
  9304. sizeof(path),
  9305. "%s/%s",
  9306. conn->dom_ctx->config[DOCUMENT_ROOT],
  9307. file_name);
  9308. } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) {
  9309. /* File name is relative to the webserver working directory
  9310. * or it is absolute system path */
  9311. file_name[511] = 0;
  9312. (void)
  9313. mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name);
  9314. } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1)
  9315. || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) {
  9316. /* File name is relative to the currect document */
  9317. file_name[511] = 0;
  9318. (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi);
  9319. if (!truncated) {
  9320. if ((p = strrchr(path, '/')) != NULL) {
  9321. p[1] = '\0';
  9322. }
  9323. len = strlen(path);
  9324. (void)mg_snprintf(conn,
  9325. &truncated,
  9326. path + len,
  9327. sizeof(path) - len,
  9328. "%s",
  9329. file_name);
  9330. }
  9331. } else {
  9332. mg_cry(conn, "Bad SSI #include: [%s]", tag);
  9333. return;
  9334. }
  9335. if (truncated) {
  9336. mg_cry(conn, "SSI #include path length overflow: [%s]", tag);
  9337. return;
  9338. }
  9339. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) {
  9340. mg_cry(conn,
  9341. "Cannot open SSI #include: [%s]: fopen(%s): %s",
  9342. tag,
  9343. path,
  9344. strerror(ERRNO));
  9345. } else {
  9346. fclose_on_exec(&file.access, conn);
  9347. if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  9348. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  9349. path) > 0) {
  9350. send_ssi_file(conn, path, &file, include_level + 1);
  9351. } else {
  9352. send_file_data(conn, &file, 0, INT64_MAX);
  9353. }
  9354. (void)mg_fclose(&file.access); /* Ignore errors for readonly files */
  9355. }
  9356. }
  9357. #if !defined(NO_POPEN)
  9358. static void
  9359. do_ssi_exec(struct mg_connection *conn, char *tag)
  9360. {
  9361. char cmd[1024] = "";
  9362. struct mg_file file = STRUCT_FILE_INITIALIZER;
  9363. if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) {
  9364. mg_cry(conn, "Bad SSI #exec: [%s]", tag);
  9365. } else {
  9366. cmd[1023] = 0;
  9367. if ((file.access.fp = popen(cmd, "r")) == NULL) {
  9368. mg_cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  9369. } else {
  9370. send_file_data(conn, &file, 0, INT64_MAX);
  9371. pclose(file.access.fp);
  9372. }
  9373. }
  9374. }
  9375. #endif /* !NO_POPEN */
  9376. static int
  9377. mg_fgetc(struct mg_file *filep, int offset)
  9378. {
  9379. if (filep == NULL) {
  9380. return EOF;
  9381. }
  9382. if ((filep->access.membuf != NULL) && (offset >= 0)
  9383. && (((unsigned int)(offset)) < filep->stat.size)) {
  9384. return ((const unsigned char *)filep->access.membuf)[offset];
  9385. } else if (filep->access.fp != NULL) {
  9386. return fgetc(filep->access.fp);
  9387. } else {
  9388. return EOF;
  9389. }
  9390. }
  9391. static void
  9392. send_ssi_file(struct mg_connection *conn,
  9393. const char *path,
  9394. struct mg_file *filep,
  9395. int include_level)
  9396. {
  9397. char buf[MG_BUF_LEN];
  9398. int ch, offset, len, in_tag, in_ssi_tag;
  9399. if (include_level > 10) {
  9400. mg_cry(conn, "SSI #include level is too deep (%s)", path);
  9401. return;
  9402. }
  9403. in_tag = in_ssi_tag = len = offset = 0;
  9404. /* Read file, byte by byte, and look for SSI include tags */
  9405. while ((ch = mg_fgetc(filep, offset++)) != EOF) {
  9406. if (in_tag) {
  9407. /* We are in a tag, either SSI tag or html tag */
  9408. if (ch == '>') {
  9409. /* Tag is closing */
  9410. buf[len++] = '>';
  9411. if (in_ssi_tag) {
  9412. /* Handle SSI tag */
  9413. buf[len] = 0;
  9414. if (!memcmp(buf + 5, "include", 7)) {
  9415. do_ssi_include(conn, path, buf + 12, include_level + 1);
  9416. #if !defined(NO_POPEN)
  9417. } else if (!memcmp(buf + 5, "exec", 4)) {
  9418. do_ssi_exec(conn, buf + 9);
  9419. #endif /* !NO_POPEN */
  9420. } else {
  9421. mg_cry(conn,
  9422. "%s: unknown SSI "
  9423. "command: \"%s\"",
  9424. path,
  9425. buf);
  9426. }
  9427. len = 0;
  9428. in_ssi_tag = in_tag = 0;
  9429. } else {
  9430. /* Not an SSI tag */
  9431. /* Flush buffer */
  9432. (void)mg_write(conn, buf, (size_t)len);
  9433. len = 0;
  9434. in_tag = 0;
  9435. }
  9436. } else {
  9437. /* Tag is still open */
  9438. buf[len++] = (char)(ch & 0xff);
  9439. if ((len == 5) && !memcmp(buf, "<!--#", 5)) {
  9440. /* All SSI tags start with <!--# */
  9441. in_ssi_tag = 1;
  9442. }
  9443. if ((len + 2) > (int)sizeof(buf)) {
  9444. /* Tag to long for buffer */
  9445. mg_cry(conn, "%s: tag is too large", path);
  9446. return;
  9447. }
  9448. }
  9449. } else {
  9450. /* We are not in a tag yet. */
  9451. if (ch == '<') {
  9452. /* Tag is opening */
  9453. in_tag = 1;
  9454. /* Flush current buffer */
  9455. (void)mg_write(conn, buf, (size_t)len);
  9456. /* Store the < */
  9457. len = 1;
  9458. buf[0] = '<';
  9459. } else {
  9460. /* No Tag */
  9461. /* Add data to buffer */
  9462. buf[len++] = (char)(ch & 0xff);
  9463. /* Flush if buffer is full */
  9464. if (len == (int)sizeof(buf)) {
  9465. mg_write(conn, buf, (size_t)len);
  9466. len = 0;
  9467. }
  9468. }
  9469. }
  9470. }
  9471. /* Send the rest of buffered data */
  9472. if (len > 0) {
  9473. mg_write(conn, buf, (size_t)len);
  9474. }
  9475. }
  9476. static void
  9477. handle_ssi_file_request(struct mg_connection *conn,
  9478. const char *path,
  9479. struct mg_file *filep)
  9480. {
  9481. char date[64];
  9482. time_t curtime = time(NULL);
  9483. const char *cors1, *cors2, *cors3;
  9484. if ((conn == NULL) || (path == NULL) || (filep == NULL)) {
  9485. return;
  9486. }
  9487. if (mg_get_header(conn, "Origin")) {
  9488. /* Cross-origin resource sharing (CORS). */
  9489. cors1 = "Access-Control-Allow-Origin: ";
  9490. cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  9491. cors3 = "\r\n";
  9492. } else {
  9493. cors1 = cors2 = cors3 = "";
  9494. }
  9495. if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) {
  9496. /* File exists (precondition for calling this function),
  9497. * but can not be opened by the server. */
  9498. mg_send_http_error(conn,
  9499. 500,
  9500. "Error: Cannot read file\nfopen(%s): %s",
  9501. path,
  9502. strerror(ERRNO));
  9503. } else {
  9504. conn->must_close = 1;
  9505. gmt_time_string(date, sizeof(date), &curtime);
  9506. fclose_on_exec(&filep->access, conn);
  9507. mg_printf(conn, "HTTP/1.1 200 OK\r\n");
  9508. send_no_cache_header(conn);
  9509. send_additional_header(conn);
  9510. mg_printf(conn,
  9511. "%s%s%s"
  9512. "Date: %s\r\n"
  9513. "Content-Type: text/html\r\n"
  9514. "Connection: %s\r\n\r\n",
  9515. cors1,
  9516. cors2,
  9517. cors3,
  9518. date,
  9519. suggest_connection_header(conn));
  9520. send_ssi_file(conn, path, filep, 0);
  9521. (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */
  9522. }
  9523. }
  9524. #if !defined(NO_FILES)
  9525. static void
  9526. send_options(struct mg_connection *conn)
  9527. {
  9528. char date[64];
  9529. time_t curtime = time(NULL);
  9530. if (!conn) {
  9531. return;
  9532. }
  9533. conn->status_code = 200;
  9534. conn->must_close = 1;
  9535. gmt_time_string(date, sizeof(date), &curtime);
  9536. /* We do not set a "Cache-Control" header here, but leave the default.
  9537. * Since browsers do not send an OPTIONS request, we can not test the
  9538. * effect anyway. */
  9539. mg_printf(conn,
  9540. "HTTP/1.1 200 OK\r\n"
  9541. "Date: %s\r\n"
  9542. "Connection: %s\r\n"
  9543. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, "
  9544. "PROPFIND, MKCOL\r\n"
  9545. "DAV: 1\r\n",
  9546. date,
  9547. suggest_connection_header(conn));
  9548. send_additional_header(conn);
  9549. mg_printf(conn, "\r\n");
  9550. }
  9551. /* Writes PROPFIND properties for a collection element */
  9552. static void
  9553. print_props(struct mg_connection *conn,
  9554. const char *uri,
  9555. struct mg_file_stat *filep)
  9556. {
  9557. char mtime[64];
  9558. if ((conn == NULL) || (uri == NULL) || (filep == NULL)) {
  9559. return;
  9560. }
  9561. gmt_time_string(mtime, sizeof(mtime), &filep->last_modified);
  9562. mg_printf(conn,
  9563. "<d:response>"
  9564. "<d:href>%s</d:href>"
  9565. "<d:propstat>"
  9566. "<d:prop>"
  9567. "<d:resourcetype>%s</d:resourcetype>"
  9568. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  9569. "<d:getlastmodified>%s</d:getlastmodified>"
  9570. "</d:prop>"
  9571. "<d:status>HTTP/1.1 200 OK</d:status>"
  9572. "</d:propstat>"
  9573. "</d:response>\n",
  9574. uri,
  9575. filep->is_directory ? "<d:collection/>" : "",
  9576. filep->size,
  9577. mtime);
  9578. }
  9579. static int
  9580. print_dav_dir_entry(struct de *de, void *data)
  9581. {
  9582. char href[PATH_MAX];
  9583. int truncated;
  9584. struct mg_connection *conn = (struct mg_connection *)data;
  9585. if (!de || !conn) {
  9586. return -1;
  9587. }
  9588. mg_snprintf(conn,
  9589. &truncated,
  9590. href,
  9591. sizeof(href),
  9592. "%s%s",
  9593. conn->request_info.local_uri,
  9594. de->file_name);
  9595. if (!truncated) {
  9596. size_t href_encoded_size;
  9597. char *href_encoded;
  9598. href_encoded_size = PATH_MAX * 3; /* worst case */
  9599. href_encoded = (char *)mg_malloc(href_encoded_size);
  9600. if (href_encoded == NULL) {
  9601. return -1;
  9602. }
  9603. mg_url_encode(href, href_encoded, href_encoded_size);
  9604. print_props(conn, href_encoded, &de->file);
  9605. mg_free(href_encoded);
  9606. }
  9607. return 0;
  9608. }
  9609. static void
  9610. handle_propfind(struct mg_connection *conn,
  9611. const char *path,
  9612. struct mg_file_stat *filep)
  9613. {
  9614. const char *depth = mg_get_header(conn, "Depth");
  9615. char date[64];
  9616. time_t curtime = time(NULL);
  9617. gmt_time_string(date, sizeof(date), &curtime);
  9618. if (!conn || !path || !filep || !conn->dom_ctx) {
  9619. return;
  9620. }
  9621. conn->must_close = 1;
  9622. conn->status_code = 207;
  9623. mg_printf(conn,
  9624. "HTTP/1.1 207 Multi-Status\r\n"
  9625. "Date: %s\r\n",
  9626. date);
  9627. send_static_cache_header(conn);
  9628. send_additional_header(conn);
  9629. mg_printf(conn,
  9630. "Connection: %s\r\n"
  9631. "Content-Type: text/xml; charset=utf-8\r\n\r\n",
  9632. suggest_connection_header(conn));
  9633. mg_printf(conn,
  9634. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  9635. "<d:multistatus xmlns:d='DAV:'>\n");
  9636. /* Print properties for the requested resource itself */
  9637. print_props(conn, conn->request_info.local_uri, filep);
  9638. /* If it is a directory, print directory entries too if Depth is not 0
  9639. */
  9640. if (filep && filep->is_directory
  9641. && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  9642. "yes")
  9643. && ((depth == NULL) || (strcmp(depth, "0") != 0))) {
  9644. scan_directory(conn, path, conn, &print_dav_dir_entry);
  9645. }
  9646. mg_printf(conn, "%s\n", "</d:multistatus>");
  9647. }
  9648. #endif
  9649. void
  9650. mg_lock_connection(struct mg_connection *conn)
  9651. {
  9652. if (conn) {
  9653. (void)pthread_mutex_lock(&conn->mutex);
  9654. }
  9655. }
  9656. void
  9657. mg_unlock_connection(struct mg_connection *conn)
  9658. {
  9659. if (conn) {
  9660. (void)pthread_mutex_unlock(&conn->mutex);
  9661. }
  9662. }
  9663. void
  9664. mg_lock_context(struct mg_context *ctx)
  9665. {
  9666. if (ctx) {
  9667. (void)pthread_mutex_lock(&ctx->nonce_mutex);
  9668. }
  9669. }
  9670. void
  9671. mg_unlock_context(struct mg_context *ctx)
  9672. {
  9673. if (ctx) {
  9674. (void)pthread_mutex_unlock(&ctx->nonce_mutex);
  9675. }
  9676. }
  9677. #if defined(USE_TIMERS)
  9678. #define TIMER_API static
  9679. #include "timer.inl"
  9680. #endif /* USE_TIMERS */
  9681. #ifdef USE_LUA
  9682. #include "mod_lua.inl"
  9683. #endif /* USE_LUA */
  9684. #ifdef USE_DUKTAPE
  9685. #include "mod_duktape.inl"
  9686. #endif /* USE_DUKTAPE */
  9687. #if defined(USE_WEBSOCKET)
  9688. #if !defined(NO_SSL_DL)
  9689. #define SHA_API static
  9690. #include "sha1.inl"
  9691. #endif
  9692. static int
  9693. send_websocket_handshake(struct mg_connection *conn, const char *websock_key)
  9694. {
  9695. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  9696. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  9697. SHA_CTX sha_ctx;
  9698. int truncated;
  9699. /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */
  9700. mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic);
  9701. if (truncated) {
  9702. conn->must_close = 1;
  9703. return 0;
  9704. }
  9705. DEBUG_TRACE("%s", "Send websocket handshake");
  9706. SHA1_Init(&sha_ctx);
  9707. SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf));
  9708. SHA1_Final((unsigned char *)sha, &sha_ctx);
  9709. base64_encode((unsigned char *)sha, sizeof(sha), b64_sha);
  9710. mg_printf(conn,
  9711. "HTTP/1.1 101 Switching Protocols\r\n"
  9712. "Upgrade: websocket\r\n"
  9713. "Connection: Upgrade\r\n"
  9714. "Sec-WebSocket-Accept: %s\r\n",
  9715. b64_sha);
  9716. if (conn->request_info.acceptedWebSocketSubprotocol) {
  9717. mg_printf(conn,
  9718. "Sec-WebSocket-Protocol: %s\r\n\r\n",
  9719. conn->request_info.acceptedWebSocketSubprotocol);
  9720. } else {
  9721. mg_printf(conn, "%s", "\r\n");
  9722. }
  9723. return 1;
  9724. }
  9725. static void
  9726. read_websocket(struct mg_connection *conn,
  9727. mg_websocket_data_handler ws_data_handler,
  9728. void *callback_data)
  9729. {
  9730. /* Pointer to the beginning of the portion of the incoming websocket
  9731. * message queue.
  9732. * The original websocket upgrade request is never removed, so the queue
  9733. * begins after it. */
  9734. unsigned char *buf = (unsigned char *)conn->buf + conn->request_len;
  9735. int n, error, exit_by_callback;
  9736. /* body_len is the length of the entire queue in bytes
  9737. * len is the length of the current message
  9738. * data_len is the length of the current message's data payload
  9739. * header_len is the length of the current message's header */
  9740. size_t i, len, mask_len = 0, header_len, body_len;
  9741. uint64_t data_len = 0;
  9742. /* "The masking key is a 32-bit value chosen at random by the client."
  9743. * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5
  9744. */
  9745. unsigned char mask[4];
  9746. /* data points to the place where the message is stored when passed to
  9747. * the
  9748. * websocket_data callback. This is either mem on the stack, or a
  9749. * dynamically allocated buffer if it is too large. */
  9750. unsigned char mem[4096];
  9751. unsigned char mop; /* mask flag and opcode */
  9752. double timeout = -1.0;
  9753. if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) {
  9754. timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0;
  9755. }
  9756. if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) {
  9757. timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0;
  9758. }
  9759. conn->in_websocket_handling = 1;
  9760. mg_set_thread_name("wsock");
  9761. /* Loop continuously, reading messages from the socket, invoking the
  9762. * callback, and waiting repeatedly until an error occurs. */
  9763. while (!conn->phys_ctx->stop_flag && !conn->must_close) {
  9764. header_len = 0;
  9765. DEBUG_ASSERT(conn->data_len >= conn->request_len);
  9766. if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) {
  9767. len = buf[1] & 127;
  9768. mask_len = (buf[1] & 128) ? 4 : 0;
  9769. if ((len < 126) && (body_len >= mask_len)) {
  9770. /* inline 7-bit length field */
  9771. data_len = len;
  9772. header_len = 2 + mask_len;
  9773. } else if ((len == 126) && (body_len >= (4 + mask_len))) {
  9774. /* 16-bit length field */
  9775. header_len = 4 + mask_len;
  9776. data_len = ((((size_t)buf[2]) << 8) + buf[3]);
  9777. } else if (body_len >= (10 + mask_len)) {
  9778. /* 64-bit length field */
  9779. uint32_t l1, l2;
  9780. memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */
  9781. memcpy(&l2, &buf[6], 4);
  9782. header_len = 10 + mask_len;
  9783. data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2);
  9784. if (data_len > (uint64_t)0x7FFF0000ul) {
  9785. /* no can do */
  9786. mg_cry(conn, "websocket out of memory; closing connection");
  9787. break;
  9788. }
  9789. }
  9790. }
  9791. if ((header_len > 0) && (body_len >= header_len)) {
  9792. /* Allocate space to hold websocket payload */
  9793. unsigned char *data = mem;
  9794. if ((size_t)data_len > (size_t)sizeof(mem)) {
  9795. data = (unsigned char *)mg_malloc_ctx((size_t)data_len,
  9796. conn->phys_ctx);
  9797. if (data == NULL) {
  9798. /* Allocation failed, exit the loop and then close the
  9799. * connection */
  9800. mg_cry(conn, "websocket out of memory; closing connection");
  9801. break;
  9802. }
  9803. }
  9804. /* Copy the mask before we shift the queue and destroy it */
  9805. if (mask_len > 0) {
  9806. memcpy(mask, buf + header_len - mask_len, sizeof(mask));
  9807. } else {
  9808. memset(mask, 0, sizeof(mask));
  9809. }
  9810. /* Read frame payload from the first message in the queue into
  9811. * data and advance the queue by moving the memory in place. */
  9812. DEBUG_ASSERT(body_len >= header_len);
  9813. if (data_len + (uint64_t)header_len > (uint64_t)body_len) {
  9814. mop = buf[0]; /* current mask and opcode */
  9815. /* Overflow case */
  9816. len = body_len - header_len;
  9817. memcpy(data, buf + header_len, len);
  9818. error = 0;
  9819. while ((uint64_t)len < data_len) {
  9820. n = pull_inner(NULL,
  9821. conn,
  9822. (char *)(data + len),
  9823. (int)(data_len - len),
  9824. timeout);
  9825. if (n <= -2) {
  9826. error = 1;
  9827. break;
  9828. } else if (n > 0) {
  9829. len += (size_t)n;
  9830. } else {
  9831. /* Timeout: should retry */
  9832. /* TODO: retry condition */
  9833. }
  9834. }
  9835. if (error) {
  9836. mg_cry(conn, "Websocket pull failed; closing connection");
  9837. if (data != mem) {
  9838. mg_free(data);
  9839. }
  9840. break;
  9841. }
  9842. conn->data_len = conn->request_len;
  9843. } else {
  9844. mop = buf[0]; /* current mask and opcode, overwritten by
  9845. * memmove() */
  9846. /* Length of the message being read at the front of the
  9847. * queue. Cast to 31 bit is OK, since we limited
  9848. * data_len before. */
  9849. len = (size_t)data_len + header_len;
  9850. /* Copy the data payload into the data pointer for the
  9851. * callback. Cast to 31 bit is OK, since we
  9852. * limited data_len */
  9853. memcpy(data, buf + header_len, (size_t)data_len);
  9854. /* Move the queue forward len bytes */
  9855. memmove(buf, buf + len, body_len - len);
  9856. /* Mark the queue as advanced */
  9857. conn->data_len -= (int)len;
  9858. }
  9859. /* Apply mask if necessary */
  9860. if (mask_len > 0) {
  9861. for (i = 0; i < (size_t)data_len; i++) {
  9862. data[i] ^= mask[i & 3];
  9863. }
  9864. }
  9865. /* Exit the loop if callback signals to exit (server side),
  9866. * or "connection close" opcode received (client side). */
  9867. exit_by_callback = 0;
  9868. if ((ws_data_handler != NULL)
  9869. && !ws_data_handler(conn,
  9870. mop,
  9871. (char *)data,
  9872. (size_t)data_len,
  9873. callback_data)) {
  9874. exit_by_callback = 1;
  9875. }
  9876. if (data != mem) {
  9877. mg_free(data);
  9878. }
  9879. if (exit_by_callback
  9880. || ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE)) {
  9881. /* Opcode == 8, connection close */
  9882. break;
  9883. }
  9884. /* Not breaking the loop, process next websocket frame. */
  9885. } else {
  9886. /* Read from the socket into the next available location in the
  9887. * message queue. */
  9888. n = pull_inner(NULL,
  9889. conn,
  9890. conn->buf + conn->data_len,
  9891. conn->buf_size - conn->data_len,
  9892. timeout);
  9893. if (n <= -2) {
  9894. /* Error, no bytes read */
  9895. break;
  9896. }
  9897. if (n > 0) {
  9898. conn->data_len += n;
  9899. } else {
  9900. /* Timeout: should retry */
  9901. /* TODO: get timeout def */
  9902. }
  9903. }
  9904. }
  9905. mg_set_thread_name("worker");
  9906. conn->in_websocket_handling = 0;
  9907. }
  9908. static int
  9909. mg_websocket_write_exec(struct mg_connection *conn,
  9910. int opcode,
  9911. const char *data,
  9912. size_t dataLen,
  9913. uint32_t masking_key)
  9914. {
  9915. unsigned char header[14];
  9916. size_t headerLen = 1;
  9917. int retval = -1;
  9918. #if defined(__GNUC__) || defined(__MINGW32__)
  9919. /* Disable spurious conversion warning for GCC */
  9920. #pragma GCC diagnostic push
  9921. #pragma GCC diagnostic ignored "-Wconversion"
  9922. #endif
  9923. header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf);
  9924. #if defined(__GNUC__) || defined(__MINGW32__)
  9925. #pragma GCC diagnostic pop
  9926. #endif
  9927. /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */
  9928. if (dataLen < 126) {
  9929. /* inline 7-bit length field */
  9930. header[1] = (unsigned char)dataLen;
  9931. headerLen = 2;
  9932. } else if (dataLen <= 0xFFFF) {
  9933. /* 16-bit length field */
  9934. uint16_t len = htons((uint16_t)dataLen);
  9935. header[1] = 126;
  9936. memcpy(header + 2, &len, 2);
  9937. headerLen = 4;
  9938. } else {
  9939. /* 64-bit length field */
  9940. uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32));
  9941. uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu));
  9942. header[1] = 127;
  9943. memcpy(header + 2, &len1, 4);
  9944. memcpy(header + 6, &len2, 4);
  9945. headerLen = 10;
  9946. }
  9947. if (masking_key) {
  9948. /* add mask */
  9949. header[1] |= 0x80;
  9950. memcpy(header + headerLen, &masking_key, 4);
  9951. headerLen += 4;
  9952. }
  9953. /* Note that POSIX/Winsock's send() is threadsafe
  9954. * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid
  9955. * but mongoose's mg_printf/mg_write is not (because of the loop in
  9956. * push(), although that is only a problem if the packet is large or
  9957. * outgoing buffer is full). */
  9958. /* TODO: Check if this lock should be moved to user land.
  9959. * Currently the server sets this lock for websockets, but
  9960. * not for any other connection. It must be set for every
  9961. * conn read/written by more than one thread, no matter if
  9962. * it is a websocket or regular connection. */
  9963. (void)mg_lock_connection(conn);
  9964. retval = mg_write(conn, header, headerLen);
  9965. if (dataLen > 0) {
  9966. retval = mg_write(conn, data, dataLen);
  9967. }
  9968. /* TODO: Remove this unlock as well, when lock is moved. */
  9969. mg_unlock_connection(conn);
  9970. return retval;
  9971. }
  9972. int
  9973. mg_websocket_write(struct mg_connection *conn,
  9974. int opcode,
  9975. const char *data,
  9976. size_t dataLen)
  9977. {
  9978. return mg_websocket_write_exec(conn, opcode, data, dataLen, 0);
  9979. }
  9980. static void
  9981. mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out)
  9982. {
  9983. size_t i = 0;
  9984. i = 0;
  9985. if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) {
  9986. /* Convert in 32 bit words, if data is 4 byte aligned */
  9987. while (i < (in_len - 3)) {
  9988. *(uint32_t *)(void *)(out + i) =
  9989. *(uint32_t *)(void *)(in + i) ^ masking_key;
  9990. i += 4;
  9991. }
  9992. }
  9993. if (i != in_len) {
  9994. /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/
  9995. while (i < in_len) {
  9996. *(uint8_t *)(void *)(out + i) =
  9997. *(uint8_t *)(void *)(in + i)
  9998. ^ *(((uint8_t *)&masking_key) + (i % 4));
  9999. i++;
  10000. }
  10001. }
  10002. }
  10003. int
  10004. mg_websocket_client_write(struct mg_connection *conn,
  10005. int opcode,
  10006. const char *data,
  10007. size_t dataLen)
  10008. {
  10009. int retval = -1;
  10010. char *masked_data =
  10011. (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx);
  10012. uint32_t masking_key = (uint32_t)get_random();
  10013. if (masked_data == NULL) {
  10014. /* Return -1 in an error case */
  10015. mg_cry(conn,
  10016. "Cannot allocate buffer for masked websocket response: "
  10017. "Out of memory");
  10018. return -1;
  10019. }
  10020. mask_data(data, dataLen, masking_key, masked_data);
  10021. retval = mg_websocket_write_exec(
  10022. conn, opcode, masked_data, dataLen, masking_key);
  10023. mg_free(masked_data);
  10024. return retval;
  10025. }
  10026. static void
  10027. handle_websocket_request(struct mg_connection *conn,
  10028. const char *path,
  10029. int is_callback_resource,
  10030. struct mg_websocket_subprotocols *subprotocols,
  10031. mg_websocket_connect_handler ws_connect_handler,
  10032. mg_websocket_ready_handler ws_ready_handler,
  10033. mg_websocket_data_handler ws_data_handler,
  10034. mg_websocket_close_handler ws_close_handler,
  10035. void *cbData)
  10036. {
  10037. const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key");
  10038. const char *version = mg_get_header(conn, "Sec-WebSocket-Version");
  10039. int lua_websock = 0;
  10040. #if !defined(USE_LUA)
  10041. (void)path;
  10042. #endif
  10043. /* Step 1: Check websocket protocol version. */
  10044. /* Step 1.1: Check Sec-WebSocket-Key. */
  10045. if (!websock_key) {
  10046. /* The RFC standard version (https://tools.ietf.org/html/rfc6455)
  10047. * requires a Sec-WebSocket-Key header.
  10048. */
  10049. /* It could be the hixie draft version
  10050. * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76).
  10051. */
  10052. const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1");
  10053. const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2");
  10054. char key3[8];
  10055. if ((key1 != NULL) && (key2 != NULL)) {
  10056. /* This version uses 8 byte body data in a GET request */
  10057. conn->content_len = 8;
  10058. if (8 == mg_read(conn, key3, 8)) {
  10059. /* This is the hixie version */
  10060. mg_send_http_error(conn,
  10061. 426,
  10062. "%s",
  10063. "Protocol upgrade to RFC 6455 required");
  10064. return;
  10065. }
  10066. }
  10067. /* This is an unknown version */
  10068. mg_send_http_error(conn, 400, "%s", "Malformed websocket request");
  10069. return;
  10070. }
  10071. /* Step 1.2: Check websocket protocol version. */
  10072. /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */
  10073. if ((version == NULL) || (strcmp(version, "13") != 0)) {
  10074. /* Reject wrong versions */
  10075. mg_send_http_error(conn, 426, "%s", "Protocol upgrade required");
  10076. return;
  10077. }
  10078. /* Step 1.3: Could check for "Host", but we do not really nead this
  10079. * value for anything, so just ignore it. */
  10080. /* Step 2: If a callback is responsible, call it. */
  10081. if (is_callback_resource) {
  10082. /* Step 2.1 check and select subprotocol */
  10083. const char *protocols[64]; // max 64 headers
  10084. int nbSubprotocolHeader = get_req_headers(&conn->request_info,
  10085. "Sec-WebSocket-Protocol",
  10086. protocols,
  10087. 64);
  10088. if ((nbSubprotocolHeader > 0) && subprotocols) {
  10089. int cnt = 0;
  10090. int idx;
  10091. unsigned long len;
  10092. const char *sep, *curSubProtocol,
  10093. *acceptedWebSocketSubprotocol = NULL;
  10094. /* look for matching subprotocol */
  10095. do {
  10096. const char *protocol = protocols[cnt];
  10097. do {
  10098. sep = strchr(protocol, ',');
  10099. curSubProtocol = protocol;
  10100. len = sep ? (unsigned long)(sep - protocol)
  10101. : (unsigned long)strlen(protocol);
  10102. while (sep && isspace(*++sep))
  10103. ; // ignore leading whitespaces
  10104. protocol = sep;
  10105. for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) {
  10106. if ((strlen(subprotocols->subprotocols[idx]) == len)
  10107. && (strncmp(curSubProtocol,
  10108. subprotocols->subprotocols[idx],
  10109. len) == 0)) {
  10110. acceptedWebSocketSubprotocol =
  10111. subprotocols->subprotocols[idx];
  10112. break;
  10113. }
  10114. }
  10115. } while (sep && !acceptedWebSocketSubprotocol);
  10116. } while (++cnt < nbSubprotocolHeader
  10117. && !acceptedWebSocketSubprotocol);
  10118. conn->request_info.acceptedWebSocketSubprotocol =
  10119. acceptedWebSocketSubprotocol;
  10120. } else if (nbSubprotocolHeader > 0) {
  10121. /* keep legacy behavior */
  10122. const char *protocol = protocols[0];
  10123. /* The protocol is a comma separated list of names. */
  10124. /* The server must only return one value from this list. */
  10125. /* First check if it is a list or just a single value. */
  10126. const char *sep = strrchr(protocol, ',');
  10127. if (sep == NULL) {
  10128. /* Just a single protocol -> accept it. */
  10129. conn->request_info.acceptedWebSocketSubprotocol = protocol;
  10130. } else {
  10131. /* Multiple protocols -> accept the last one. */
  10132. /* This is just a quick fix if the client offers multiple
  10133. * protocols. The handler should have a list of accepted
  10134. * protocols on his own
  10135. * and use it to select one protocol among those the client
  10136. * has
  10137. * offered.
  10138. */
  10139. while (isspace(*++sep)) {
  10140. ; /* ignore leading whitespaces */
  10141. }
  10142. conn->request_info.acceptedWebSocketSubprotocol = sep;
  10143. }
  10144. }
  10145. if ((ws_connect_handler != NULL)
  10146. && (ws_connect_handler(conn, cbData) != 0)) {
  10147. /* C callback has returned non-zero, do not proceed with
  10148. * handshake.
  10149. */
  10150. /* Note that C callbacks are no longer called when Lua is
  10151. * responsible, so C can no longer filter callbacks for Lua. */
  10152. return;
  10153. }
  10154. }
  10155. #if defined(USE_LUA)
  10156. /* Step 3: No callback. Check if Lua is responsible. */
  10157. else {
  10158. /* Step 3.1: Check if Lua is responsible. */
  10159. if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) {
  10160. lua_websock = match_prefix(
  10161. conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS],
  10162. strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]),
  10163. path);
  10164. }
  10165. if (lua_websock) {
  10166. /* Step 3.2: Lua is responsible: call it. */
  10167. conn->lua_websocket_state = lua_websocket_new(path, conn);
  10168. if (!conn->lua_websocket_state) {
  10169. /* Lua rejected the new client */
  10170. return;
  10171. }
  10172. }
  10173. }
  10174. #endif
  10175. /* Step 4: Check if there is a responsible websocket handler. */
  10176. if (!is_callback_resource && !lua_websock) {
  10177. /* There is no callback, and Lua is not responsible either. */
  10178. /* Reply with a 404 Not Found. We are still at a standard
  10179. * HTTP request here, before the websocket handshake, so
  10180. * we can still send standard HTTP error replies. */
  10181. mg_send_http_error(conn, 404, "%s", "Not found");
  10182. return;
  10183. }
  10184. /* Step 5: The websocket connection has been accepted */
  10185. if (!send_websocket_handshake(conn, websock_key)) {
  10186. mg_send_http_error(conn, 500, "%s", "Websocket handshake failed");
  10187. return;
  10188. }
  10189. /* Step 6: Call the ready handler */
  10190. if (is_callback_resource) {
  10191. if (ws_ready_handler != NULL) {
  10192. ws_ready_handler(conn, cbData);
  10193. }
  10194. #if defined(USE_LUA)
  10195. } else if (lua_websock) {
  10196. if (!lua_websocket_ready(conn, conn->lua_websocket_state)) {
  10197. /* the ready handler returned false */
  10198. return;
  10199. }
  10200. #endif
  10201. }
  10202. /* Step 7: Enter the read loop */
  10203. if (is_callback_resource) {
  10204. read_websocket(conn, ws_data_handler, cbData);
  10205. #if defined(USE_LUA)
  10206. } else if (lua_websock) {
  10207. read_websocket(conn, lua_websocket_data, conn->lua_websocket_state);
  10208. #endif
  10209. }
  10210. /* Step 8: Call the close handler */
  10211. if (ws_close_handler) {
  10212. ws_close_handler(conn, cbData);
  10213. }
  10214. }
  10215. static int
  10216. is_websocket_protocol(const struct mg_connection *conn)
  10217. {
  10218. const char *upgrade, *connection;
  10219. /* A websocket protocoll has the following HTTP headers:
  10220. *
  10221. * Connection: Upgrade
  10222. * Upgrade: Websocket
  10223. */
  10224. upgrade = mg_get_header(conn, "Upgrade");
  10225. if (upgrade == NULL) {
  10226. return 0; /* fail early, don't waste time checking other header
  10227. * fields
  10228. */
  10229. }
  10230. if (!mg_strcasestr(upgrade, "websocket")) {
  10231. return 0;
  10232. }
  10233. connection = mg_get_header(conn, "Connection");
  10234. if (connection == NULL) {
  10235. return 0;
  10236. }
  10237. if (!mg_strcasestr(connection, "upgrade")) {
  10238. return 0;
  10239. }
  10240. /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and
  10241. * "Sec-WebSocket-Version" are also required.
  10242. * Don't check them here, since even an unsupported websocket protocol
  10243. * request still IS a websocket request (in contrast to a standard HTTP
  10244. * request). It will fail later in handle_websocket_request.
  10245. */
  10246. return 1;
  10247. }
  10248. #endif /* !USE_WEBSOCKET */
  10249. static int
  10250. isbyte(int n)
  10251. {
  10252. return (n >= 0) && (n <= 255);
  10253. }
  10254. static int
  10255. parse_net(const char *spec, uint32_t *net, uint32_t *mask)
  10256. {
  10257. int n, a, b, c, d, slash = 32, len = 0;
  10258. if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5)
  10259. || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4))
  10260. && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0)
  10261. && (slash < 33)) {
  10262. len = n;
  10263. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8)
  10264. | (uint32_t)d;
  10265. *mask = slash ? (0xffffffffU << (32 - slash)) : 0;
  10266. }
  10267. return len;
  10268. }
  10269. static int
  10270. set_throttle(const char *spec, uint32_t remote_ip, const char *uri)
  10271. {
  10272. int throttle = 0;
  10273. struct vec vec, val;
  10274. uint32_t net, mask;
  10275. char mult;
  10276. double v;
  10277. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  10278. mult = ',';
  10279. if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1)
  10280. || (v < 0) || ((lowercase(&mult) != 'k')
  10281. && (lowercase(&mult) != 'm') && (mult != ','))) {
  10282. continue;
  10283. }
  10284. v *= (lowercase(&mult) == 'k')
  10285. ? 1024
  10286. : ((lowercase(&mult) == 'm') ? 1048576 : 1);
  10287. if (vec.len == 1 && vec.ptr[0] == '*') {
  10288. throttle = (int)v;
  10289. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  10290. if ((remote_ip & mask) == net) {
  10291. throttle = (int)v;
  10292. }
  10293. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  10294. throttle = (int)v;
  10295. }
  10296. }
  10297. return throttle;
  10298. }
  10299. static uint32_t
  10300. get_remote_ip(const struct mg_connection *conn)
  10301. {
  10302. if (!conn) {
  10303. return 0;
  10304. }
  10305. return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr);
  10306. }
  10307. /* The mg_upload function is superseeded by mg_handle_form_request. */
  10308. #include "handle_form.inl"
  10309. #if defined(MG_LEGACY_INTERFACE)
  10310. /* Implement the deprecated mg_upload function by calling the new
  10311. * mg_handle_form_request function. While mg_upload could only handle
  10312. * HTML forms sent as POST request in multipart/form-data format
  10313. * containing only file input elements, mg_handle_form_request can
  10314. * handle all form input elements and all standard request methods. */
  10315. struct mg_upload_user_data {
  10316. struct mg_connection *conn;
  10317. const char *destination_dir;
  10318. int num_uploaded_files;
  10319. };
  10320. /* Helper function for deprecated mg_upload. */
  10321. static int
  10322. mg_upload_field_found(const char *key,
  10323. const char *filename,
  10324. char *path,
  10325. size_t pathlen,
  10326. void *user_data)
  10327. {
  10328. int truncated = 0;
  10329. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10330. (void)key;
  10331. if (!filename) {
  10332. mg_cry(fud->conn, "%s: No filename set", __func__);
  10333. return FORM_FIELD_STORAGE_ABORT;
  10334. }
  10335. mg_snprintf(fud->conn,
  10336. &truncated,
  10337. path,
  10338. pathlen - 1,
  10339. "%s/%s",
  10340. fud->destination_dir,
  10341. filename);
  10342. if (!truncated) {
  10343. mg_cry(fud->conn, "%s: File path too long", __func__);
  10344. return FORM_FIELD_STORAGE_ABORT;
  10345. }
  10346. return FORM_FIELD_STORAGE_STORE;
  10347. }
  10348. /* Helper function for deprecated mg_upload. */
  10349. static int
  10350. mg_upload_field_get(const char *key,
  10351. const char *value,
  10352. size_t value_size,
  10353. void *user_data)
  10354. {
  10355. /* Function should never be called */
  10356. (void)key;
  10357. (void)value;
  10358. (void)value_size;
  10359. (void)user_data;
  10360. return 0;
  10361. }
  10362. /* Helper function for deprecated mg_upload. */
  10363. static int
  10364. mg_upload_field_stored(const char *path, long long file_size, void *user_data)
  10365. {
  10366. struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data;
  10367. (void)file_size;
  10368. fud->num_uploaded_files++;
  10369. fud->conn->phys_ctx->callbacks.upload(fud->conn, path);
  10370. return 0;
  10371. }
  10372. /* Deprecated function mg_upload - use mg_handle_form_request instead. */
  10373. int
  10374. mg_upload(struct mg_connection *conn, const char *destination_dir)
  10375. {
  10376. struct mg_upload_user_data fud = {conn, destination_dir, 0};
  10377. struct mg_form_data_handler fdh = {mg_upload_field_found,
  10378. mg_upload_field_get,
  10379. mg_upload_field_stored,
  10380. 0};
  10381. int ret;
  10382. fdh.user_data = (void *)&fud;
  10383. ret = mg_handle_form_request(conn, &fdh);
  10384. if (ret < 0) {
  10385. mg_cry(conn, "%s: Error while parsing the request", __func__);
  10386. }
  10387. return fud.num_uploaded_files;
  10388. }
  10389. #endif
  10390. static int
  10391. get_first_ssl_listener_index(const struct mg_context *ctx)
  10392. {
  10393. unsigned int i;
  10394. int idx = -1;
  10395. if (ctx) {
  10396. for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) {
  10397. idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1;
  10398. }
  10399. }
  10400. return idx;
  10401. }
  10402. /* Return host (without port) */
  10403. /* Use mg_free to free the result */
  10404. static const char *
  10405. alloc_get_host(struct mg_connection *conn)
  10406. {
  10407. char host[1025];
  10408. const char *host_header;
  10409. size_t hostlen;
  10410. host_header = get_header(conn->request_info.http_headers,
  10411. conn->request_info.num_headers,
  10412. "Host");
  10413. hostlen = sizeof(host);
  10414. if (host_header != NULL) {
  10415. char *pos;
  10416. mg_strlcpy(host, host_header, hostlen);
  10417. host[hostlen - 1] = '\0';
  10418. pos = strchr(host, ':');
  10419. if (pos != NULL) {
  10420. *pos = '\0';
  10421. }
  10422. DEBUG_TRACE("Host: %s", host);
  10423. } else {
  10424. sockaddr_to_string(host, hostlen, &conn->client.lsa);
  10425. DEBUG_TRACE("IP: %s", host);
  10426. }
  10427. return mg_strdup_ctx(host, conn->phys_ctx);
  10428. }
  10429. static void
  10430. redirect_to_https_port(struct mg_connection *conn, int ssl_index)
  10431. {
  10432. conn->must_close = 1;
  10433. /* Send host, port, uri and (if it exists) ?query_string */
  10434. if (conn->host) {
  10435. mg_printf(conn,
  10436. "HTTP/1.1 302 Found\r\nLocation: https://%s:%d%s%s%s\r\n\r\n",
  10437. conn->host,
  10438. #if defined(USE_IPV6)
  10439. (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family
  10440. == AF_INET6)
  10441. ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  10442. .lsa.sin6.sin6_port)
  10443. :
  10444. #endif
  10445. (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index]
  10446. .lsa.sin.sin_port),
  10447. conn->request_info.local_uri,
  10448. (conn->request_info.query_string == NULL) ? "" : "?",
  10449. (conn->request_info.query_string == NULL)
  10450. ? ""
  10451. : conn->request_info.query_string);
  10452. }
  10453. }
  10454. static void
  10455. mg_set_handler_type(struct mg_context *phys_ctx,
  10456. struct mg_domain_context *dom_ctx,
  10457. const char *uri,
  10458. int handler_type,
  10459. int is_delete_request,
  10460. mg_request_handler handler,
  10461. struct mg_websocket_subprotocols *subprotocols,
  10462. mg_websocket_connect_handler connect_handler,
  10463. mg_websocket_ready_handler ready_handler,
  10464. mg_websocket_data_handler data_handler,
  10465. mg_websocket_close_handler close_handler,
  10466. mg_authorization_handler auth_handler,
  10467. void *cbdata)
  10468. {
  10469. struct mg_handler_info *tmp_rh, **lastref;
  10470. size_t urilen = strlen(uri);
  10471. if (handler_type == WEBSOCKET_HANDLER) {
  10472. DEBUG_ASSERT(handler == NULL);
  10473. DEBUG_ASSERT(is_delete_request || connect_handler != NULL
  10474. || ready_handler != NULL
  10475. || data_handler != NULL
  10476. || close_handler != NULL);
  10477. DEBUG_ASSERT(auth_handler == NULL);
  10478. if (handler != NULL) {
  10479. return;
  10480. }
  10481. if (!is_delete_request && (connect_handler == NULL)
  10482. && (ready_handler == NULL) && (data_handler == NULL)
  10483. && (close_handler == NULL)) {
  10484. return;
  10485. }
  10486. if (auth_handler != NULL) {
  10487. return;
  10488. }
  10489. } else if (handler_type == REQUEST_HANDLER) {
  10490. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  10491. && data_handler == NULL
  10492. && close_handler == NULL);
  10493. DEBUG_ASSERT(is_delete_request || (handler != NULL));
  10494. DEBUG_ASSERT(auth_handler == NULL);
  10495. if ((connect_handler != NULL) || (ready_handler != NULL)
  10496. || (data_handler != NULL) || (close_handler != NULL)) {
  10497. return;
  10498. }
  10499. if (!is_delete_request && (handler == NULL)) {
  10500. return;
  10501. }
  10502. if (auth_handler != NULL) {
  10503. return;
  10504. }
  10505. } else { /* AUTH_HANDLER */
  10506. DEBUG_ASSERT(handler == NULL);
  10507. DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL
  10508. && data_handler == NULL
  10509. && close_handler == NULL);
  10510. DEBUG_ASSERT(auth_handler != NULL);
  10511. if (handler != NULL) {
  10512. return;
  10513. }
  10514. if ((connect_handler != NULL) || (ready_handler != NULL)
  10515. || (data_handler != NULL) || (close_handler != NULL)) {
  10516. return;
  10517. }
  10518. if (!is_delete_request && (auth_handler == NULL)) {
  10519. return;
  10520. }
  10521. }
  10522. if (!phys_ctx || !dom_ctx) {
  10523. return;
  10524. }
  10525. mg_lock_context(phys_ctx);
  10526. /* first try to find an existing handler */
  10527. lastref = &(dom_ctx->handlers);
  10528. for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) {
  10529. if (tmp_rh->handler_type == handler_type) {
  10530. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10531. if (!is_delete_request) {
  10532. /* update existing handler */
  10533. if (handler_type == REQUEST_HANDLER) {
  10534. tmp_rh->handler = handler;
  10535. } else if (handler_type == WEBSOCKET_HANDLER) {
  10536. tmp_rh->subprotocols = subprotocols;
  10537. tmp_rh->connect_handler = connect_handler;
  10538. tmp_rh->ready_handler = ready_handler;
  10539. tmp_rh->data_handler = data_handler;
  10540. tmp_rh->close_handler = close_handler;
  10541. } else { /* AUTH_HANDLER */
  10542. tmp_rh->auth_handler = auth_handler;
  10543. }
  10544. tmp_rh->cbdata = cbdata;
  10545. } else {
  10546. /* remove existing handler */
  10547. *lastref = tmp_rh->next;
  10548. mg_free(tmp_rh->uri);
  10549. mg_free(tmp_rh);
  10550. }
  10551. mg_unlock_context(phys_ctx);
  10552. return;
  10553. }
  10554. }
  10555. lastref = &(tmp_rh->next);
  10556. }
  10557. if (is_delete_request) {
  10558. /* no handler to set, this was a remove request to a non-existing
  10559. * handler */
  10560. mg_unlock_context(phys_ctx);
  10561. return;
  10562. }
  10563. tmp_rh =
  10564. (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info),
  10565. 1,
  10566. phys_ctx);
  10567. if (tmp_rh == NULL) {
  10568. mg_unlock_context(phys_ctx);
  10569. mg_cry(fc(phys_ctx),
  10570. "%s",
  10571. "Cannot create new request handler struct, OOM");
  10572. return;
  10573. }
  10574. tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx);
  10575. if (!tmp_rh->uri) {
  10576. mg_unlock_context(phys_ctx);
  10577. mg_free(tmp_rh);
  10578. mg_cry(fc(phys_ctx),
  10579. "%s",
  10580. "Cannot create new request handler struct, OOM");
  10581. return;
  10582. }
  10583. tmp_rh->uri_len = urilen;
  10584. if (handler_type == REQUEST_HANDLER) {
  10585. tmp_rh->handler = handler;
  10586. } else if (handler_type == WEBSOCKET_HANDLER) {
  10587. tmp_rh->subprotocols = subprotocols;
  10588. tmp_rh->connect_handler = connect_handler;
  10589. tmp_rh->ready_handler = ready_handler;
  10590. tmp_rh->data_handler = data_handler;
  10591. tmp_rh->close_handler = close_handler;
  10592. } else { /* AUTH_HANDLER */
  10593. tmp_rh->auth_handler = auth_handler;
  10594. }
  10595. tmp_rh->cbdata = cbdata;
  10596. tmp_rh->handler_type = handler_type;
  10597. tmp_rh->next = NULL;
  10598. *lastref = tmp_rh;
  10599. mg_unlock_context(phys_ctx);
  10600. }
  10601. void
  10602. mg_set_request_handler(struct mg_context *ctx,
  10603. const char *uri,
  10604. mg_request_handler handler,
  10605. void *cbdata)
  10606. {
  10607. mg_set_handler_type(ctx,
  10608. &(ctx->dd),
  10609. uri,
  10610. REQUEST_HANDLER,
  10611. handler == NULL,
  10612. handler,
  10613. NULL,
  10614. NULL,
  10615. NULL,
  10616. NULL,
  10617. NULL,
  10618. NULL,
  10619. cbdata);
  10620. }
  10621. void
  10622. mg_set_websocket_handler(struct mg_context *ctx,
  10623. const char *uri,
  10624. mg_websocket_connect_handler connect_handler,
  10625. mg_websocket_ready_handler ready_handler,
  10626. mg_websocket_data_handler data_handler,
  10627. mg_websocket_close_handler close_handler,
  10628. void *cbdata)
  10629. {
  10630. mg_set_websocket_handler_with_subprotocols(ctx,
  10631. uri,
  10632. NULL,
  10633. connect_handler,
  10634. ready_handler,
  10635. data_handler,
  10636. close_handler,
  10637. cbdata);
  10638. }
  10639. void
  10640. mg_set_websocket_handler_with_subprotocols(
  10641. struct mg_context *ctx,
  10642. const char *uri,
  10643. struct mg_websocket_subprotocols *subprotocols,
  10644. mg_websocket_connect_handler connect_handler,
  10645. mg_websocket_ready_handler ready_handler,
  10646. mg_websocket_data_handler data_handler,
  10647. mg_websocket_close_handler close_handler,
  10648. void *cbdata)
  10649. {
  10650. int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL)
  10651. && (data_handler == NULL)
  10652. && (close_handler == NULL);
  10653. mg_set_handler_type(ctx,
  10654. &(ctx->dd),
  10655. uri,
  10656. WEBSOCKET_HANDLER,
  10657. is_delete_request,
  10658. NULL,
  10659. subprotocols,
  10660. connect_handler,
  10661. ready_handler,
  10662. data_handler,
  10663. close_handler,
  10664. NULL,
  10665. cbdata);
  10666. }
  10667. void
  10668. mg_set_auth_handler(struct mg_context *ctx,
  10669. const char *uri,
  10670. mg_request_handler handler,
  10671. void *cbdata)
  10672. {
  10673. mg_set_handler_type(ctx,
  10674. &(ctx->dd),
  10675. uri,
  10676. AUTH_HANDLER,
  10677. handler == NULL,
  10678. NULL,
  10679. NULL,
  10680. NULL,
  10681. NULL,
  10682. NULL,
  10683. NULL,
  10684. handler,
  10685. cbdata);
  10686. }
  10687. static int
  10688. get_request_handler(struct mg_connection *conn,
  10689. int handler_type,
  10690. mg_request_handler *handler,
  10691. struct mg_websocket_subprotocols **subprotocols,
  10692. mg_websocket_connect_handler *connect_handler,
  10693. mg_websocket_ready_handler *ready_handler,
  10694. mg_websocket_data_handler *data_handler,
  10695. mg_websocket_close_handler *close_handler,
  10696. mg_authorization_handler *auth_handler,
  10697. void **cbdata)
  10698. {
  10699. const struct mg_request_info *request_info = mg_get_request_info(conn);
  10700. if (request_info) {
  10701. const char *uri = request_info->local_uri;
  10702. size_t urilen = strlen(uri);
  10703. struct mg_handler_info *tmp_rh;
  10704. if (!conn || !conn->phys_ctx || !conn->dom_ctx) {
  10705. return 0;
  10706. }
  10707. mg_lock_context(conn->phys_ctx);
  10708. /* first try for an exact match */
  10709. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  10710. tmp_rh = tmp_rh->next) {
  10711. if (tmp_rh->handler_type == handler_type) {
  10712. if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) {
  10713. if (handler_type == WEBSOCKET_HANDLER) {
  10714. *subprotocols = tmp_rh->subprotocols;
  10715. *connect_handler = tmp_rh->connect_handler;
  10716. *ready_handler = tmp_rh->ready_handler;
  10717. *data_handler = tmp_rh->data_handler;
  10718. *close_handler = tmp_rh->close_handler;
  10719. } else if (handler_type == REQUEST_HANDLER) {
  10720. *handler = tmp_rh->handler;
  10721. } else { /* AUTH_HANDLER */
  10722. *auth_handler = tmp_rh->auth_handler;
  10723. }
  10724. *cbdata = tmp_rh->cbdata;
  10725. mg_unlock_context(conn->phys_ctx);
  10726. return 1;
  10727. }
  10728. }
  10729. }
  10730. /* next try for a partial match, we will accept uri/something */
  10731. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  10732. tmp_rh = tmp_rh->next) {
  10733. if (tmp_rh->handler_type == handler_type) {
  10734. if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/')
  10735. && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) {
  10736. if (handler_type == WEBSOCKET_HANDLER) {
  10737. *subprotocols = tmp_rh->subprotocols;
  10738. *connect_handler = tmp_rh->connect_handler;
  10739. *ready_handler = tmp_rh->ready_handler;
  10740. *data_handler = tmp_rh->data_handler;
  10741. *close_handler = tmp_rh->close_handler;
  10742. } else if (handler_type == REQUEST_HANDLER) {
  10743. *handler = tmp_rh->handler;
  10744. } else { /* AUTH_HANDLER */
  10745. *auth_handler = tmp_rh->auth_handler;
  10746. }
  10747. *cbdata = tmp_rh->cbdata;
  10748. mg_unlock_context(conn->phys_ctx);
  10749. return 1;
  10750. }
  10751. }
  10752. }
  10753. /* finally try for pattern match */
  10754. for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL;
  10755. tmp_rh = tmp_rh->next) {
  10756. if (tmp_rh->handler_type == handler_type) {
  10757. if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) {
  10758. if (handler_type == WEBSOCKET_HANDLER) {
  10759. *subprotocols = tmp_rh->subprotocols;
  10760. *connect_handler = tmp_rh->connect_handler;
  10761. *ready_handler = tmp_rh->ready_handler;
  10762. *data_handler = tmp_rh->data_handler;
  10763. *close_handler = tmp_rh->close_handler;
  10764. } else if (handler_type == REQUEST_HANDLER) {
  10765. *handler = tmp_rh->handler;
  10766. } else { /* AUTH_HANDLER */
  10767. *auth_handler = tmp_rh->auth_handler;
  10768. }
  10769. *cbdata = tmp_rh->cbdata;
  10770. mg_unlock_context(conn->phys_ctx);
  10771. return 1;
  10772. }
  10773. }
  10774. }
  10775. mg_unlock_context(conn->phys_ctx);
  10776. }
  10777. return 0; /* none found */
  10778. }
  10779. /* Check if the script file is in a path, allowed for script files.
  10780. * This can be used if uploading files is possible not only for the server
  10781. * admin, and the upload mechanism does not check the file extension.
  10782. */
  10783. static int
  10784. is_in_script_path(const struct mg_connection *conn, const char *path)
  10785. {
  10786. /* TODO (Feature): Add config value for allowed script path.
  10787. * Default: All allowed. */
  10788. (void)conn;
  10789. (void)path;
  10790. return 1;
  10791. }
  10792. #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE)
  10793. static int
  10794. deprecated_websocket_connect_wrapper(const struct mg_connection *conn,
  10795. void *cbdata)
  10796. {
  10797. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10798. if (pcallbacks->websocket_connect) {
  10799. return pcallbacks->websocket_connect(conn);
  10800. }
  10801. /* No handler set - assume "OK" */
  10802. return 0;
  10803. }
  10804. static void
  10805. deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata)
  10806. {
  10807. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10808. if (pcallbacks->websocket_ready) {
  10809. pcallbacks->websocket_ready(conn);
  10810. }
  10811. }
  10812. static int
  10813. deprecated_websocket_data_wrapper(struct mg_connection *conn,
  10814. int bits,
  10815. char *data,
  10816. size_t len,
  10817. void *cbdata)
  10818. {
  10819. struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata;
  10820. if (pcallbacks->websocket_data) {
  10821. return pcallbacks->websocket_data(conn, bits, data, len);
  10822. }
  10823. /* No handler set - assume "OK" */
  10824. return 1;
  10825. }
  10826. #endif
  10827. /* This is the heart of the Civetweb's logic.
  10828. * This function is called when the request is read, parsed and validated,
  10829. * and Civetweb must decide what action to take: serve a file, or
  10830. * a directory, or call embedded function, etcetera. */
  10831. static void
  10832. handle_request(struct mg_connection *conn)
  10833. {
  10834. struct mg_request_info *ri = &conn->request_info;
  10835. char path[PATH_MAX];
  10836. int uri_len, ssl_index;
  10837. int is_found = 0, is_script_resource = 0, is_websocket_request = 0,
  10838. is_put_or_delete_request = 0, is_callback_resource = 0;
  10839. int i;
  10840. struct mg_file file = STRUCT_FILE_INITIALIZER;
  10841. mg_request_handler callback_handler = NULL;
  10842. struct mg_websocket_subprotocols *subprotocols;
  10843. mg_websocket_connect_handler ws_connect_handler = NULL;
  10844. mg_websocket_ready_handler ws_ready_handler = NULL;
  10845. mg_websocket_data_handler ws_data_handler = NULL;
  10846. mg_websocket_close_handler ws_close_handler = NULL;
  10847. void *callback_data = NULL;
  10848. mg_authorization_handler auth_handler = NULL;
  10849. void *auth_callback_data = NULL;
  10850. int handler_type;
  10851. time_t curtime = time(NULL);
  10852. char date[64];
  10853. path[0] = 0;
  10854. /* 1. get the request url */
  10855. /* 1.1. split into url and query string */
  10856. if ((conn->request_info.query_string = strchr(ri->request_uri, '?'))
  10857. != NULL) {
  10858. *((char *)conn->request_info.query_string++) = '\0';
  10859. }
  10860. /* 1.2. do a https redirect, if required. Do not decode URIs yet. */
  10861. if (!conn->client.is_ssl && conn->client.ssl_redir) {
  10862. ssl_index = get_first_ssl_listener_index(conn->phys_ctx);
  10863. if (ssl_index >= 0) {
  10864. redirect_to_https_port(conn, ssl_index);
  10865. } else {
  10866. /* A http to https forward port has been specified,
  10867. * but no https port to forward to. */
  10868. mg_send_http_error(conn,
  10869. 503,
  10870. "%s",
  10871. "Error: SSL forward not configured properly");
  10872. mg_cry(conn, "Can not redirect to SSL, no SSL port available");
  10873. }
  10874. return;
  10875. }
  10876. uri_len = (int)strlen(ri->local_uri);
  10877. /* 1.3. decode url (if config says so) */
  10878. if (should_decode_url(conn)) {
  10879. mg_url_decode(
  10880. ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0);
  10881. }
  10882. /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is
  10883. * not possible */
  10884. remove_double_dots_and_double_slashes((char *)ri->local_uri);
  10885. /* step 1. completed, the url is known now */
  10886. uri_len = (int)strlen(ri->local_uri);
  10887. DEBUG_TRACE("URL: %s", ri->local_uri);
  10888. /* 2. if this ip has limited speed, set it for this connection */
  10889. conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE],
  10890. get_remote_ip(conn),
  10891. ri->local_uri);
  10892. /* 3. call a "handle everything" callback, if registered */
  10893. if (conn->phys_ctx->callbacks.begin_request != NULL) {
  10894. /* Note that since V1.7 the "begin_request" function is called
  10895. * before an authorization check. If an authorization check is
  10896. * required, use a request_handler instead. */
  10897. i = conn->phys_ctx->callbacks.begin_request(conn);
  10898. if (i > 0) {
  10899. /* callback already processed the request. Store the
  10900. return value as a status code for the access log. */
  10901. conn->status_code = i;
  10902. discard_unread_request_data(conn);
  10903. return;
  10904. } else if (i == 0) {
  10905. /* civetweb should process the request */
  10906. } else {
  10907. /* unspecified - may change with the next version */
  10908. return;
  10909. }
  10910. }
  10911. /* request not yet handled by a handler or redirect, so the request
  10912. * is processed here */
  10913. /* 4. Check for CORS preflight requests and handle them (if configured).
  10914. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  10915. */
  10916. if (!strcmp(ri->request_method, "OPTIONS")) {
  10917. /* Send a response to CORS preflights only if
  10918. * access_control_allow_methods is not NULL and not an empty string.
  10919. * In this case, scripts can still handle CORS. */
  10920. const char *cors_meth_cfg =
  10921. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS];
  10922. const char *cors_orig_cfg =
  10923. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN];
  10924. const char *cors_origin =
  10925. get_header(ri->http_headers, ri->num_headers, "Origin");
  10926. const char *cors_acrm = get_header(ri->http_headers,
  10927. ri->num_headers,
  10928. "Access-Control-Request-Method");
  10929. /* Todo: check if cors_origin is in cors_orig_cfg.
  10930. * Or, let the client check this. */
  10931. if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0)
  10932. && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0)
  10933. && (cors_origin != NULL) && (cors_acrm != NULL)) {
  10934. /* This is a valid CORS preflight, and the server is configured
  10935. * to
  10936. * handle it automatically. */
  10937. const char *cors_acrh =
  10938. get_header(ri->http_headers,
  10939. ri->num_headers,
  10940. "Access-Control-Request-Headers");
  10941. gmt_time_string(date, sizeof(date), &curtime);
  10942. mg_printf(conn,
  10943. "HTTP/1.1 200 OK\r\n"
  10944. "Date: %s\r\n"
  10945. "Access-Control-Allow-Origin: %s\r\n"
  10946. "Access-Control-Allow-Methods: %s\r\n"
  10947. "Content-Length: 0\r\n"
  10948. "Connection: %s\r\n",
  10949. date,
  10950. cors_orig_cfg,
  10951. ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg),
  10952. suggest_connection_header(conn));
  10953. if (cors_acrh != NULL) {
  10954. /* CORS request is asking for additional headers */
  10955. const char *cors_hdr_cfg =
  10956. conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS];
  10957. if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) {
  10958. /* Allow only if access_control_allow_headers is
  10959. * not NULL and not an empty string. If this
  10960. * configuration is set to *, allow everything.
  10961. * Otherwise this configuration must be a list
  10962. * of allowed HTTP header names. */
  10963. mg_printf(conn,
  10964. "Access-Control-Allow-Headers: %s\r\n",
  10965. ((cors_hdr_cfg[0] == '*') ? cors_acrh
  10966. : cors_hdr_cfg));
  10967. }
  10968. }
  10969. mg_printf(conn, "Access-Control-Max-Age: 60\r\n");
  10970. mg_printf(conn, "\r\n");
  10971. return;
  10972. }
  10973. }
  10974. /* 5. interpret the url to find out how the request must be handled
  10975. */
  10976. /* 5.1. first test, if the request targets the regular http(s)://
  10977. * protocol namespace or the websocket ws(s):// protocol namespace.
  10978. */
  10979. is_websocket_request = is_websocket_protocol(conn);
  10980. #if defined(USE_WEBSOCKET)
  10981. handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER;
  10982. #else
  10983. handler_type = REQUEST_HANDLER;
  10984. #endif /* defined(USE_WEBSOCKET) */
  10985. /* 5.2. check if the request will be handled by a callback */
  10986. if (get_request_handler(conn,
  10987. handler_type,
  10988. &callback_handler,
  10989. &subprotocols,
  10990. &ws_connect_handler,
  10991. &ws_ready_handler,
  10992. &ws_data_handler,
  10993. &ws_close_handler,
  10994. NULL,
  10995. &callback_data)) {
  10996. /* 5.2.1. A callback will handle this request. All requests
  10997. * handled
  10998. * by a callback have to be considered as requests to a script
  10999. * resource. */
  11000. is_callback_resource = 1;
  11001. is_script_resource = 1;
  11002. is_put_or_delete_request = is_put_or_delete_method(conn);
  11003. } else {
  11004. no_callback_resource:
  11005. /* 5.2.2. No callback is responsible for this request. The URI
  11006. * addresses a file based resource (static content or Lua/cgi
  11007. * scripts in the file system). */
  11008. is_callback_resource = 0;
  11009. interpret_uri(conn,
  11010. path,
  11011. sizeof(path),
  11012. &file.stat,
  11013. &is_found,
  11014. &is_script_resource,
  11015. &is_websocket_request,
  11016. &is_put_or_delete_request);
  11017. }
  11018. /* 6. authorization check */
  11019. /* 6.1. a custom authorization handler is installed */
  11020. if (get_request_handler(conn,
  11021. AUTH_HANDLER,
  11022. NULL,
  11023. NULL,
  11024. NULL,
  11025. NULL,
  11026. NULL,
  11027. NULL,
  11028. &auth_handler,
  11029. &auth_callback_data)) {
  11030. if (!auth_handler(conn, auth_callback_data)) {
  11031. return;
  11032. }
  11033. } else if (is_put_or_delete_request && !is_script_resource
  11034. && !is_callback_resource) {
  11035. /* 6.2. this request is a PUT/DELETE to a real file */
  11036. /* 6.2.1. thus, the server must have real files */
  11037. #if defined(NO_FILES)
  11038. if (1) {
  11039. #else
  11040. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11041. #endif
  11042. /* This server does not have any real files, thus the
  11043. * PUT/DELETE methods are not valid. */
  11044. mg_send_http_error(conn,
  11045. 405,
  11046. "%s method not allowed",
  11047. conn->request_info.request_method);
  11048. return;
  11049. }
  11050. #if !defined(NO_FILES)
  11051. /* 6.2.2. Check if put authorization for static files is
  11052. * available.
  11053. */
  11054. if (!is_authorized_for_put(conn)) {
  11055. send_authorization_request(conn, NULL);
  11056. return;
  11057. }
  11058. #endif
  11059. } else {
  11060. /* 6.3. This is either a OPTIONS, GET, HEAD or POST request,
  11061. * or it is a PUT or DELETE request to a resource that does not
  11062. * correspond to a file. Check authorization. */
  11063. if (!check_authorization(conn, path)) {
  11064. send_authorization_request(conn, NULL);
  11065. return;
  11066. }
  11067. }
  11068. /* request is authorized or does not need authorization */
  11069. /* 7. check if there are request handlers for this uri */
  11070. if (is_callback_resource) {
  11071. if (!is_websocket_request) {
  11072. i = callback_handler(conn, callback_data);
  11073. if (i > 0) {
  11074. /* Do nothing, callback has served the request. Store
  11075. * then return value as status code for the log and discard
  11076. * all data from the client not used by the callback. */
  11077. conn->status_code = i;
  11078. discard_unread_request_data(conn);
  11079. } else {
  11080. /* The handler did NOT handle the request. */
  11081. /* Some proper reactions would be:
  11082. * a) close the connections without sending anything
  11083. * b) send a 404 not found
  11084. * c) try if there is a file matching the URI
  11085. * It would be possible to do a, b or c in the callback
  11086. * implementation, and return 1 - we cannot do anything
  11087. * here, that is not possible in the callback.
  11088. *
  11089. * TODO: What would be the best reaction here?
  11090. * (Note: The reaction may change, if there is a better
  11091. *idea.)
  11092. */
  11093. /* For the moment, use option c: We look for a proper file,
  11094. * but since a file request is not always a script resource,
  11095. * the authorization check might be different. */
  11096. interpret_uri(conn,
  11097. path,
  11098. sizeof(path),
  11099. &file.stat,
  11100. &is_found,
  11101. &is_script_resource,
  11102. &is_websocket_request,
  11103. &is_put_or_delete_request);
  11104. callback_handler = NULL;
  11105. /* Here we are at a dead end:
  11106. * According to URI matching, a callback should be
  11107. * responsible for handling the request,
  11108. * we called it, but the callback declared itself
  11109. * not responsible.
  11110. * We use a goto here, to get out of this dead end,
  11111. * and continue with the default handling.
  11112. * A goto here is simpler and better to understand
  11113. * than some curious loop. */
  11114. goto no_callback_resource;
  11115. }
  11116. } else {
  11117. #if defined(USE_WEBSOCKET)
  11118. handle_websocket_request(conn,
  11119. path,
  11120. is_callback_resource,
  11121. subprotocols,
  11122. ws_connect_handler,
  11123. ws_ready_handler,
  11124. ws_data_handler,
  11125. ws_close_handler,
  11126. callback_data);
  11127. #endif
  11128. }
  11129. return;
  11130. }
  11131. /* 8. handle websocket requests */
  11132. #if defined(USE_WEBSOCKET)
  11133. if (is_websocket_request) {
  11134. if (is_script_resource) {
  11135. if (is_in_script_path(conn, path)) {
  11136. /* Websocket Lua script */
  11137. handle_websocket_request(conn,
  11138. path,
  11139. 0 /* Lua Script */,
  11140. NULL,
  11141. NULL,
  11142. NULL,
  11143. NULL,
  11144. NULL,
  11145. conn->phys_ctx->user_data);
  11146. } else {
  11147. /* Script was in an illegal path */
  11148. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11149. }
  11150. } else {
  11151. #if defined(MG_LEGACY_INTERFACE)
  11152. handle_websocket_request(
  11153. conn,
  11154. path,
  11155. !is_script_resource /* could be deprecated global callback */,
  11156. NULL,
  11157. deprecated_websocket_connect_wrapper,
  11158. deprecated_websocket_ready_wrapper,
  11159. deprecated_websocket_data_wrapper,
  11160. NULL,
  11161. conn->phys_ctx->user_data);
  11162. #else
  11163. mg_send_http_error(conn, 404, "%s", "Not found");
  11164. #endif
  11165. }
  11166. return;
  11167. } else
  11168. #endif
  11169. #if defined(NO_FILES)
  11170. /* 9a. In case the server uses only callbacks, this uri is
  11171. * unknown.
  11172. * Then, all request handling ends here. */
  11173. mg_send_http_error(conn, 404, "%s", "Not Found");
  11174. #else
  11175. /* 9b. This request is either for a static file or resource handled
  11176. * by a script file. Thus, a DOCUMENT_ROOT must exist. */
  11177. if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) {
  11178. mg_send_http_error(conn, 404, "%s", "Not Found");
  11179. return;
  11180. }
  11181. /* 10. Request is handled by a script */
  11182. if (is_script_resource) {
  11183. handle_file_based_request(conn, path, &file);
  11184. return;
  11185. }
  11186. /* 11. Handle put/delete/mkcol requests */
  11187. if (is_put_or_delete_request) {
  11188. /* 11.1. PUT method */
  11189. if (!strcmp(ri->request_method, "PUT")) {
  11190. put_file(conn, path);
  11191. return;
  11192. }
  11193. /* 11.2. DELETE method */
  11194. if (!strcmp(ri->request_method, "DELETE")) {
  11195. delete_file(conn, path);
  11196. return;
  11197. }
  11198. /* 11.3. MKCOL method */
  11199. if (!strcmp(ri->request_method, "MKCOL")) {
  11200. mkcol(conn, path);
  11201. return;
  11202. }
  11203. /* 11.4. PATCH method
  11204. * This method is not supported for static resources,
  11205. * only for scripts (Lua, CGI) and callbacks. */
  11206. mg_send_http_error(conn,
  11207. 405,
  11208. "%s method not allowed",
  11209. conn->request_info.request_method);
  11210. return;
  11211. }
  11212. /* 11. File does not exist, or it was configured that it should be
  11213. * hidden */
  11214. if (!is_found || (must_hide_file(conn, path))) {
  11215. mg_send_http_error(conn, 404, "%s", "Not found");
  11216. return;
  11217. }
  11218. /* 12. Directory uris should end with a slash */
  11219. if (file.stat.is_directory && (uri_len > 0)
  11220. && (ri->local_uri[uri_len - 1] != '/')) {
  11221. gmt_time_string(date, sizeof(date), &curtime);
  11222. mg_printf(conn,
  11223. "HTTP/1.1 301 Moved Permanently\r\n"
  11224. "Location: %s/\r\n"
  11225. "Date: %s\r\n"
  11226. /* "Cache-Control: private\r\n" (= default) */
  11227. "Content-Length: 0\r\n"
  11228. "Connection: %s\r\n",
  11229. ri->request_uri,
  11230. date,
  11231. suggest_connection_header(conn));
  11232. send_additional_header(conn);
  11233. mg_printf(conn, "\r\n");
  11234. return;
  11235. }
  11236. /* 13. Handle other methods than GET/HEAD */
  11237. /* 13.1. Handle PROPFIND */
  11238. if (!strcmp(ri->request_method, "PROPFIND")) {
  11239. handle_propfind(conn, path, &file.stat);
  11240. return;
  11241. }
  11242. /* 13.2. Handle OPTIONS for files */
  11243. if (!strcmp(ri->request_method, "OPTIONS")) {
  11244. /* This standard handler is only used for real files.
  11245. * Scripts should support the OPTIONS method themselves, to allow a
  11246. * maximum flexibility.
  11247. * Lua and CGI scripts may fully support CORS this way (including
  11248. * preflights). */
  11249. send_options(conn);
  11250. return;
  11251. }
  11252. /* 13.3. everything but GET and HEAD (e.g. POST) */
  11253. if ((0 != strcmp(ri->request_method, "GET"))
  11254. && (0 != strcmp(ri->request_method, "HEAD"))) {
  11255. mg_send_http_error(conn,
  11256. 405,
  11257. "%s method not allowed",
  11258. conn->request_info.request_method);
  11259. return;
  11260. }
  11261. /* 14. directories */
  11262. if (file.stat.is_directory) {
  11263. /* Substitute files have already been handled above. */
  11264. /* Here we can either generate and send a directory listing,
  11265. * or send an "access denied" error. */
  11266. if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING],
  11267. "yes")) {
  11268. handle_directory_request(conn, path);
  11269. } else {
  11270. mg_send_http_error(conn,
  11271. 403,
  11272. "%s",
  11273. "Error: Directory listing denied");
  11274. }
  11275. return;
  11276. }
  11277. handle_file_based_request(conn, path, &file);
  11278. #endif /* !defined(NO_FILES) */
  11279. #if 0
  11280. /* Perform redirect and auth checks before calling begin_request()
  11281. * handler.
  11282. * Otherwise, begin_request() would need to perform auth checks and
  11283. * redirects. */
  11284. #endif
  11285. }
  11286. static void
  11287. handle_file_based_request(struct mg_connection *conn,
  11288. const char *path,
  11289. struct mg_file *file)
  11290. {
  11291. if (!conn || !conn->dom_ctx) {
  11292. return;
  11293. }
  11294. if (0) {
  11295. #ifdef USE_LUA
  11296. } else if (match_prefix(
  11297. conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS],
  11298. strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]),
  11299. path) > 0) {
  11300. if (is_in_script_path(conn, path)) {
  11301. /* Lua server page: an SSI like page containing mostly plain
  11302. * html
  11303. * code
  11304. * plus some tags with server generated contents. */
  11305. handle_lsp_request(conn, path, file, NULL);
  11306. } else {
  11307. /* Script was in an illegal path */
  11308. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11309. }
  11310. } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS],
  11311. strlen(
  11312. conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]),
  11313. path) > 0) {
  11314. if (is_in_script_path(conn, path)) {
  11315. /* Lua in-server module script: a CGI like script used to
  11316. * generate
  11317. * the
  11318. * entire reply. */
  11319. mg_exec_lua_script(conn, path, NULL);
  11320. } else {
  11321. /* Script was in an illegal path */
  11322. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11323. }
  11324. #endif
  11325. #if defined(USE_DUKTAPE)
  11326. } else if (match_prefix(
  11327. conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS],
  11328. strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]),
  11329. path) > 0) {
  11330. if (is_in_script_path(conn, path)) {
  11331. /* Call duktape to generate the page */
  11332. mg_exec_duktape_script(conn, path);
  11333. } else {
  11334. /* Script was in an illegal path */
  11335. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11336. }
  11337. #endif
  11338. #if !defined(NO_CGI)
  11339. } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS],
  11340. strlen(conn->dom_ctx->config[CGI_EXTENSIONS]),
  11341. path) > 0) {
  11342. if (is_in_script_path(conn, path)) {
  11343. /* CGI scripts may support all HTTP methods */
  11344. handle_cgi_request(conn, path);
  11345. } else {
  11346. /* Script was in an illegal path */
  11347. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11348. }
  11349. #endif /* !NO_CGI */
  11350. } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS],
  11351. strlen(conn->dom_ctx->config[SSI_EXTENSIONS]),
  11352. path) > 0) {
  11353. if (is_in_script_path(conn, path)) {
  11354. handle_ssi_file_request(conn, path, file);
  11355. } else {
  11356. /* Script was in an illegal path */
  11357. mg_send_http_error(conn, 403, "%s", "Forbidden");
  11358. }
  11359. #if !defined(NO_CACHING)
  11360. } else if ((!conn->in_error_handler)
  11361. && is_not_modified(conn, &file->stat)) {
  11362. /* Send 304 "Not Modified" - this must not send any body data */
  11363. handle_not_modified_static_file_request(conn, file);
  11364. #endif /* !NO_CACHING */
  11365. } else {
  11366. handle_static_file_request(conn, path, file, NULL, NULL);
  11367. }
  11368. }
  11369. static void
  11370. close_all_listening_sockets(struct mg_context *ctx)
  11371. {
  11372. unsigned int i;
  11373. if (!ctx) {
  11374. return;
  11375. }
  11376. for (i = 0; i < ctx->num_listening_sockets; i++) {
  11377. closesocket(ctx->listening_sockets[i].sock);
  11378. ctx->listening_sockets[i].sock = INVALID_SOCKET;
  11379. }
  11380. mg_free(ctx->listening_sockets);
  11381. ctx->listening_sockets = NULL;
  11382. mg_free(ctx->listening_socket_fds);
  11383. ctx->listening_socket_fds = NULL;
  11384. }
  11385. /* Valid listening port specification is: [ip_address:]port[s]
  11386. * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s
  11387. * Examples for IPv6: [::]:80, [::1]:80,
  11388. * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s
  11389. * see https://tools.ietf.org/html/rfc3513#section-2.2
  11390. * In order to bind to both, IPv4 and IPv6, you can either add
  11391. * both ports using 8080,[::]:8080, or the short form +8080.
  11392. * Both forms differ in detail: 8080,[::]:8080 create two sockets,
  11393. * one only accepting IPv4 the other only IPv6. +8080 creates
  11394. * one socket accepting IPv4 and IPv6. Depending on the IPv6
  11395. * environment, they might work differently, or might not work
  11396. * at all - it must be tested what options work best in the
  11397. * relevant network environment.
  11398. */
  11399. static int
  11400. parse_port_string(const struct vec *vec, struct socket *so, int *ip_version)
  11401. {
  11402. unsigned int a, b, c, d, port;
  11403. int ch, len;
  11404. const char *cb;
  11405. #if defined(USE_IPV6)
  11406. char buf[100] = {0};
  11407. #endif
  11408. /* MacOS needs that. If we do not zero it, subsequent bind() will fail.
  11409. * Also, all-zeroes in the socket address means binding to all addresses
  11410. * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */
  11411. memset(so, 0, sizeof(*so));
  11412. so->lsa.sin.sin_family = AF_INET;
  11413. *ip_version = 0;
  11414. /* Initialize port and len as invalid. */
  11415. port = 0;
  11416. len = 0;
  11417. /* Test for different ways to format this string */
  11418. if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len)
  11419. == 5) {
  11420. /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
  11421. so->lsa.sin.sin_addr.s_addr =
  11422. htonl((a << 24) | (b << 16) | (c << 8) | d);
  11423. so->lsa.sin.sin_port = htons((uint16_t)port);
  11424. *ip_version = 4;
  11425. #if defined(USE_IPV6)
  11426. } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2
  11427. && mg_inet_pton(
  11428. AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) {
  11429. /* IPv6 address, examples: see above */
  11430. /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton
  11431. */
  11432. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11433. *ip_version = 6;
  11434. #endif
  11435. } else if ((vec->ptr[0] == '+')
  11436. && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) {
  11437. /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */
  11438. /* Add 1 to len for the + character we skipped before */
  11439. len++;
  11440. #if defined(USE_IPV6)
  11441. /* Set socket family to IPv6, do not use IPV6_V6ONLY */
  11442. so->lsa.sin6.sin6_family = AF_INET6;
  11443. so->lsa.sin6.sin6_port = htons((uint16_t)port);
  11444. *ip_version = 4 + 6;
  11445. #else
  11446. /* Bind to IPv4 only, since IPv6 is not built in. */
  11447. so->lsa.sin.sin_port = htons((uint16_t)port);
  11448. *ip_version = 4;
  11449. #endif
  11450. } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) {
  11451. /* If only port is specified, bind to IPv4, INADDR_ANY */
  11452. so->lsa.sin.sin_port = htons((uint16_t)port);
  11453. *ip_version = 4;
  11454. } else if ((cb = strchr(vec->ptr, ':')) != NULL) {
  11455. /* Could be a hostname */
  11456. /* Will only work for RFC 952 compliant hostnames,
  11457. * starting with a letter, containing only letters,
  11458. * digits and hyphen ('-'). Newer specs may allow
  11459. * more, but this is not guaranteed here, since it
  11460. * may interfere with rules for port option lists. */
  11461. *(char *)cb = 0; /* Use a const cast here and modify the string.
  11462. * We are going to restore the string later. */
  11463. if (mg_inet_pton(
  11464. AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) {
  11465. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11466. *ip_version = 4;
  11467. so->lsa.sin.sin_family = AF_INET;
  11468. so->lsa.sin.sin_port = htons((uint16_t)port);
  11469. len += (int)(cb - vec->ptr) + 1;
  11470. } else {
  11471. port = 0;
  11472. len = 0;
  11473. }
  11474. #if defined(USE_IPV6)
  11475. } else if (mg_inet_pton(AF_INET6,
  11476. vec->ptr,
  11477. &so->lsa.sin6,
  11478. sizeof(so->lsa.sin6))) {
  11479. if (sscanf(cb + 1, "%u%n", &port, &len) == 1) {
  11480. *ip_version = 6;
  11481. so->lsa.sin6.sin6_family = AF_INET6;
  11482. so->lsa.sin.sin_port = htons((uint16_t)port);
  11483. len += (int)(cb - vec->ptr) + 1;
  11484. } else {
  11485. port = 0;
  11486. len = 0;
  11487. }
  11488. #endif
  11489. }
  11490. *(char *)cb = ':'; /* restore the string */
  11491. } else {
  11492. /* Parsing failure. */
  11493. }
  11494. /* sscanf and the option splitting code ensure the following condition
  11495. */
  11496. if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) {
  11497. *ip_version = 0;
  11498. return 0;
  11499. }
  11500. ch = vec->ptr[len]; /* Next character after the port number */
  11501. so->is_ssl = (ch == 's');
  11502. so->ssl_redir = (ch == 'r');
  11503. /* Make sure the port is valid and vector ends with 's', 'r' or ',' */
  11504. if (is_valid_port(port)
  11505. && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) {
  11506. return 1;
  11507. }
  11508. /* Reset ip_version to 0 of there is an error */
  11509. *ip_version = 0;
  11510. return 0;
  11511. }
  11512. /* Is there any SSL port in use? */
  11513. static int
  11514. is_ssl_port_used(const char *ports)
  11515. {
  11516. if (ports) {
  11517. if (strchr(ports, 's')) {
  11518. return 1;
  11519. }
  11520. if (strchr(ports, 'r')) {
  11521. return 1;
  11522. }
  11523. }
  11524. return 0;
  11525. }
  11526. static int
  11527. set_ports_option(struct mg_context *phys_ctx)
  11528. {
  11529. const char *list;
  11530. int on = 1;
  11531. #if defined(USE_IPV6)
  11532. int off = 0;
  11533. #endif
  11534. struct vec vec;
  11535. struct socket so, *ptr;
  11536. struct pollfd *pfd;
  11537. union usa usa;
  11538. socklen_t len;
  11539. int ip_version;
  11540. int portsTotal = 0;
  11541. int portsOk = 0;
  11542. if (!phys_ctx) {
  11543. return 0;
  11544. }
  11545. memset(&so, 0, sizeof(so));
  11546. memset(&usa, 0, sizeof(usa));
  11547. len = sizeof(usa);
  11548. list = phys_ctx->dd.config[LISTENING_PORTS];
  11549. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11550. portsTotal++;
  11551. if (!parse_port_string(&vec, &so, &ip_version)) {
  11552. mg_cry(fc(phys_ctx),
  11553. "%.*s: invalid port spec (entry %i). Expecting list of: %s",
  11554. (int)vec.len,
  11555. vec.ptr,
  11556. portsTotal,
  11557. "[IP_ADDRESS:]PORT[s|r]");
  11558. continue;
  11559. }
  11560. #if !defined(NO_SSL)
  11561. if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) {
  11562. mg_cry(fc(phys_ctx),
  11563. "Cannot add SSL socket (entry %i)",
  11564. portsTotal);
  11565. continue;
  11566. }
  11567. #endif
  11568. if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6))
  11569. == INVALID_SOCKET) {
  11570. mg_cry(fc(phys_ctx), "cannot create socket (entry %i)", portsTotal);
  11571. continue;
  11572. }
  11573. #ifdef _WIN32
  11574. /* Windows SO_REUSEADDR lets many procs binds to a
  11575. * socket, SO_EXCLUSIVEADDRUSE makes the bind fail
  11576. * if someone already has the socket -- DTL */
  11577. /* NOTE: If SO_EXCLUSIVEADDRUSE is used,
  11578. * Windows might need a few seconds before
  11579. * the same port can be used again in the
  11580. * same process, so a short Sleep may be
  11581. * required between mg_stop and mg_start.
  11582. */
  11583. if (setsockopt(so.sock,
  11584. SOL_SOCKET,
  11585. SO_EXCLUSIVEADDRUSE,
  11586. (SOCK_OPT_TYPE)&on,
  11587. sizeof(on)) != 0) {
  11588. /* Set reuse option, but don't abort on errors. */
  11589. mg_cry(fc(phys_ctx),
  11590. "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)",
  11591. portsTotal);
  11592. }
  11593. #else
  11594. if (setsockopt(so.sock,
  11595. SOL_SOCKET,
  11596. SO_REUSEADDR,
  11597. (SOCK_OPT_TYPE)&on,
  11598. sizeof(on)) != 0) {
  11599. /* Set reuse option, but don't abort on errors. */
  11600. mg_cry(fc(phys_ctx),
  11601. "cannot set socket option SO_REUSEADDR (entry %i)",
  11602. portsTotal);
  11603. }
  11604. #endif
  11605. if (ip_version > 4) {
  11606. #if defined(USE_IPV6)
  11607. if (ip_version == 6) {
  11608. if (so.lsa.sa.sa_family == AF_INET6
  11609. && setsockopt(so.sock,
  11610. IPPROTO_IPV6,
  11611. IPV6_V6ONLY,
  11612. (void *)&off,
  11613. sizeof(off)) != 0) {
  11614. /* Set IPv6 only option, but don't abort on errors. */
  11615. mg_cry(fc(phys_ctx),
  11616. "cannot set socket option IPV6_V6ONLY (entry %i)",
  11617. portsTotal);
  11618. }
  11619. }
  11620. #else
  11621. mg_cry(fc(phys_ctx), "IPv6 not available");
  11622. closesocket(so.sock);
  11623. so.sock = INVALID_SOCKET;
  11624. continue;
  11625. #endif
  11626. }
  11627. if (so.lsa.sa.sa_family == AF_INET) {
  11628. len = sizeof(so.lsa.sin);
  11629. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11630. mg_cry(fc(phys_ctx),
  11631. "cannot bind to %.*s: %d (%s)",
  11632. (int)vec.len,
  11633. vec.ptr,
  11634. (int)ERRNO,
  11635. strerror(errno));
  11636. closesocket(so.sock);
  11637. so.sock = INVALID_SOCKET;
  11638. continue;
  11639. }
  11640. }
  11641. #if defined(USE_IPV6)
  11642. else if (so.lsa.sa.sa_family == AF_INET6) {
  11643. len = sizeof(so.lsa.sin6);
  11644. if (bind(so.sock, &so.lsa.sa, len) != 0) {
  11645. mg_cry(fc(phys_ctx),
  11646. "cannot bind to IPv6 %.*s: %d (%s)",
  11647. (int)vec.len,
  11648. vec.ptr,
  11649. (int)ERRNO,
  11650. strerror(errno));
  11651. closesocket(so.sock);
  11652. so.sock = INVALID_SOCKET;
  11653. continue;
  11654. }
  11655. }
  11656. #endif
  11657. else {
  11658. mg_cry(fc(phys_ctx),
  11659. "cannot bind: address family not supported (entry %i)",
  11660. portsTotal);
  11661. closesocket(so.sock);
  11662. so.sock = INVALID_SOCKET;
  11663. continue;
  11664. }
  11665. if (listen(so.sock, SOMAXCONN) != 0) {
  11666. mg_cry(fc(phys_ctx),
  11667. "cannot listen to %.*s: %d (%s)",
  11668. (int)vec.len,
  11669. vec.ptr,
  11670. (int)ERRNO,
  11671. strerror(errno));
  11672. closesocket(so.sock);
  11673. so.sock = INVALID_SOCKET;
  11674. continue;
  11675. }
  11676. if ((getsockname(so.sock, &(usa.sa), &len) != 0)
  11677. || (usa.sa.sa_family != so.lsa.sa.sa_family)) {
  11678. int err = (int)ERRNO;
  11679. mg_cry(fc(phys_ctx),
  11680. "call to getsockname failed %.*s: %d (%s)",
  11681. (int)vec.len,
  11682. vec.ptr,
  11683. err,
  11684. strerror(errno));
  11685. closesocket(so.sock);
  11686. so.sock = INVALID_SOCKET;
  11687. continue;
  11688. }
  11689. /* Update lsa port in case of random free ports */
  11690. #if defined(USE_IPV6)
  11691. if (so.lsa.sa.sa_family == AF_INET6) {
  11692. so.lsa.sin6.sin6_port = usa.sin6.sin6_port;
  11693. } else
  11694. #endif
  11695. {
  11696. so.lsa.sin.sin_port = usa.sin.sin_port;
  11697. }
  11698. if ((ptr = (struct socket *)
  11699. mg_realloc_ctx(phys_ctx->listening_sockets,
  11700. (phys_ctx->num_listening_sockets + 1)
  11701. * sizeof(phys_ctx->listening_sockets[0]),
  11702. phys_ctx)) == NULL) {
  11703. mg_cry(fc(phys_ctx), "%s", "Out of memory");
  11704. closesocket(so.sock);
  11705. so.sock = INVALID_SOCKET;
  11706. continue;
  11707. }
  11708. if ((pfd = (struct pollfd *)
  11709. mg_realloc_ctx(phys_ctx->listening_socket_fds,
  11710. (phys_ctx->num_listening_sockets + 1)
  11711. * sizeof(phys_ctx->listening_socket_fds[0]),
  11712. phys_ctx)) == NULL) {
  11713. mg_cry(fc(phys_ctx), "%s", "Out of memory");
  11714. closesocket(so.sock);
  11715. so.sock = INVALID_SOCKET;
  11716. mg_free(ptr);
  11717. continue;
  11718. }
  11719. set_close_on_exec(so.sock, fc(phys_ctx));
  11720. phys_ctx->listening_sockets = ptr;
  11721. phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so;
  11722. phys_ctx->listening_socket_fds = pfd;
  11723. phys_ctx->num_listening_sockets++;
  11724. portsOk++;
  11725. }
  11726. if (portsOk != portsTotal) {
  11727. close_all_listening_sockets(phys_ctx);
  11728. portsOk = 0;
  11729. }
  11730. return portsOk;
  11731. }
  11732. static const char *
  11733. header_val(const struct mg_connection *conn, const char *header)
  11734. {
  11735. const char *header_value;
  11736. if ((header_value = mg_get_header(conn, header)) == NULL) {
  11737. return "-";
  11738. } else {
  11739. return header_value;
  11740. }
  11741. }
  11742. static void
  11743. log_access(const struct mg_connection *conn)
  11744. {
  11745. const struct mg_request_info *ri;
  11746. struct mg_file fi;
  11747. char date[64], src_addr[IP_ADDR_STR_LEN];
  11748. struct tm *tm;
  11749. const char *referer;
  11750. const char *user_agent;
  11751. char buf[4096];
  11752. if (!conn || !conn->dom_ctx) {
  11753. return;
  11754. }
  11755. if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) {
  11756. if (mg_fopen(conn,
  11757. conn->dom_ctx->config[ACCESS_LOG_FILE],
  11758. MG_FOPEN_MODE_APPEND,
  11759. &fi) == 0) {
  11760. fi.access.fp = NULL;
  11761. }
  11762. } else {
  11763. fi.access.fp = NULL;
  11764. }
  11765. /* Log is written to a file and/or a callback. If both are not set,
  11766. * executing the rest of the function is pointless. */
  11767. if ((fi.access.fp == NULL)
  11768. && (conn->phys_ctx->callbacks.log_access == NULL)) {
  11769. return;
  11770. }
  11771. tm = localtime(&conn->conn_birth_time);
  11772. if (tm != NULL) {
  11773. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm);
  11774. } else {
  11775. mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date));
  11776. date[sizeof(date) - 1] = '\0';
  11777. }
  11778. ri = &conn->request_info;
  11779. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  11780. referer = header_val(conn, "Referer");
  11781. user_agent = header_val(conn, "User-Agent");
  11782. mg_snprintf(conn,
  11783. NULL, /* Ignore truncation in access log */
  11784. buf,
  11785. sizeof(buf),
  11786. "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s",
  11787. src_addr,
  11788. (ri->remote_user == NULL) ? "-" : ri->remote_user,
  11789. date,
  11790. ri->request_method ? ri->request_method : "-",
  11791. ri->request_uri ? ri->request_uri : "-",
  11792. ri->query_string ? "?" : "",
  11793. ri->query_string ? ri->query_string : "",
  11794. ri->http_version,
  11795. conn->status_code,
  11796. conn->num_bytes_sent,
  11797. referer,
  11798. user_agent);
  11799. if (conn->phys_ctx->callbacks.log_access) {
  11800. conn->phys_ctx->callbacks.log_access(conn, buf);
  11801. }
  11802. if (fi.access.fp) {
  11803. int ok = 1;
  11804. flockfile(fi.access.fp);
  11805. if (fprintf(fi.access.fp, "%s\n", buf) < 1) {
  11806. ok = 0;
  11807. }
  11808. if (fflush(fi.access.fp) != 0) {
  11809. ok = 0;
  11810. }
  11811. funlockfile(fi.access.fp);
  11812. if (mg_fclose(&fi.access) != 0) {
  11813. ok = 0;
  11814. }
  11815. if (!ok) {
  11816. mg_cry(conn,
  11817. "Error writing log file %s",
  11818. conn->dom_ctx->config[ACCESS_LOG_FILE]);
  11819. }
  11820. }
  11821. }
  11822. /* Verify given socket address against the ACL.
  11823. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  11824. */
  11825. static int
  11826. check_acl(struct mg_context *phys_ctx, uint32_t remote_ip)
  11827. {
  11828. int allowed, flag;
  11829. uint32_t net, mask;
  11830. struct vec vec;
  11831. if (phys_ctx) {
  11832. const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST];
  11833. /* If any ACL is set, deny by default */
  11834. allowed = (list == NULL) ? '+' : '-';
  11835. while ((list = next_option(list, &vec, NULL)) != NULL) {
  11836. flag = vec.ptr[0];
  11837. if ((flag != '+' && flag != '-')
  11838. || (parse_net(&vec.ptr[1], &net, &mask) == 0)) {
  11839. mg_cry(fc(phys_ctx),
  11840. "%s: subnet must be [+|-]x.x.x.x[/x]",
  11841. __func__);
  11842. return -1;
  11843. }
  11844. if (net == (remote_ip & mask)) {
  11845. allowed = flag;
  11846. }
  11847. }
  11848. return allowed == '+';
  11849. }
  11850. return -1;
  11851. }
  11852. #if !defined(_WIN32)
  11853. static int
  11854. set_uid_option(struct mg_context *phys_ctx)
  11855. {
  11856. int success = 0;
  11857. if (phys_ctx) {
  11858. /* We are currently running as curr_uid. */
  11859. const uid_t curr_uid = getuid();
  11860. /* If set, we want to run as run_as_user. */
  11861. const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER];
  11862. const struct passwd *to_pw = NULL;
  11863. if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) {
  11864. /* run_as_user does not exist on the system. We can't proceed
  11865. * further. */
  11866. mg_cry(fc(phys_ctx),
  11867. "%s: unknown user [%s]",
  11868. __func__,
  11869. run_as_user);
  11870. } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) {
  11871. /* There was either no request to change user, or we're already
  11872. * running as run_as_user. Nothing else to do.
  11873. */
  11874. success = 1;
  11875. } else {
  11876. /* Valid change request. */
  11877. if (setgid(to_pw->pw_gid) == -1) {
  11878. mg_cry(fc(phys_ctx),
  11879. "%s: setgid(%s): %s",
  11880. __func__,
  11881. run_as_user,
  11882. strerror(errno));
  11883. } else if (setgroups(0, NULL) == -1) {
  11884. mg_cry(fc(phys_ctx),
  11885. "%s: setgroups(): %s",
  11886. __func__,
  11887. strerror(errno));
  11888. } else if (setuid(to_pw->pw_uid) == -1) {
  11889. mg_cry(fc(phys_ctx),
  11890. "%s: setuid(%s): %s",
  11891. __func__,
  11892. run_as_user,
  11893. strerror(errno));
  11894. } else {
  11895. success = 1;
  11896. }
  11897. }
  11898. }
  11899. return success;
  11900. }
  11901. #endif /* !_WIN32 */
  11902. static void
  11903. tls_dtor(void *key)
  11904. {
  11905. struct mg_workerTLS *tls = (struct mg_workerTLS *)key;
  11906. /* key == pthread_getspecific(sTlsKey); */
  11907. if (tls) {
  11908. if (tls->is_master == 2) {
  11909. tls->is_master = -3; /* Mark memory as dead */
  11910. mg_free(tls);
  11911. }
  11912. }
  11913. pthread_setspecific(sTlsKey, NULL);
  11914. }
  11915. #if !defined(NO_SSL)
  11916. static int ssl_use_pem_file(struct mg_context *phys_ctx,
  11917. struct mg_domain_context *dom_ctx,
  11918. const char *pem,
  11919. const char *chain);
  11920. static const char *ssl_error(void);
  11921. static int
  11922. refresh_trust(struct mg_connection *conn)
  11923. {
  11924. static int reload_lock = 0;
  11925. static long int data_check = 0;
  11926. volatile int *p_reload_lock = (volatile int *)&reload_lock;
  11927. struct stat cert_buf;
  11928. long int t;
  11929. const char *pem;
  11930. const char *chain;
  11931. int should_verify_peer;
  11932. if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) {
  11933. /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not,
  11934. * refresh_trust still can not work. */
  11935. return 0;
  11936. }
  11937. chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  11938. if (chain == NULL) {
  11939. /* pem is not NULL here */
  11940. chain = pem;
  11941. }
  11942. if (*chain == 0) {
  11943. chain = NULL;
  11944. }
  11945. t = data_check;
  11946. if (stat(pem, &cert_buf) != -1) {
  11947. t = (long int)cert_buf.st_mtime;
  11948. }
  11949. if (data_check != t) {
  11950. data_check = t;
  11951. should_verify_peer = 0;
  11952. if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  11953. if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes")
  11954. == 0) {
  11955. should_verify_peer = 1;
  11956. } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER],
  11957. "optional") == 0) {
  11958. should_verify_peer = 1;
  11959. }
  11960. }
  11961. if (should_verify_peer) {
  11962. char *ca_path = conn->dom_ctx->config[SSL_CA_PATH];
  11963. char *ca_file = conn->dom_ctx->config[SSL_CA_FILE];
  11964. if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx,
  11965. ca_file,
  11966. ca_path) != 1) {
  11967. mg_cry(fc(conn->phys_ctx),
  11968. "SSL_CTX_load_verify_locations error: %s "
  11969. "ssl_verify_peer requires setting "
  11970. "either ssl_ca_path or ssl_ca_file. Is any of them "
  11971. "present in "
  11972. "the .conf file?",
  11973. ssl_error());
  11974. return 0;
  11975. }
  11976. }
  11977. if (1 == mg_atomic_inc(p_reload_lock)) {
  11978. if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain)
  11979. == 0) {
  11980. return 0;
  11981. }
  11982. *p_reload_lock = 0;
  11983. }
  11984. }
  11985. /* lock while cert is reloading */
  11986. while (*p_reload_lock) {
  11987. sleep(1);
  11988. }
  11989. return 1;
  11990. }
  11991. #ifdef OPENSSL_API_1_1
  11992. #else
  11993. static pthread_mutex_t *ssl_mutexes;
  11994. #endif /* OPENSSL_API_1_1 */
  11995. static int
  11996. sslize(struct mg_connection *conn,
  11997. SSL_CTX *s,
  11998. int (*func)(SSL *),
  11999. volatile int *stop_server)
  12000. {
  12001. int ret, err;
  12002. int short_trust;
  12003. unsigned i;
  12004. if (!conn) {
  12005. return 0;
  12006. }
  12007. short_trust =
  12008. (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL)
  12009. && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0);
  12010. if (short_trust) {
  12011. int trust_ret = refresh_trust(conn);
  12012. if (!trust_ret) {
  12013. return trust_ret;
  12014. }
  12015. }
  12016. conn->ssl = SSL_new(s);
  12017. if (conn->ssl == NULL) {
  12018. return 0;
  12019. }
  12020. SSL_set_app_data(conn->ssl, (char *)conn);
  12021. ret = SSL_set_fd(conn->ssl, conn->client.sock);
  12022. if (ret != 1) {
  12023. err = SSL_get_error(conn->ssl, ret);
  12024. (void)err; /* TODO: set some error message */
  12025. SSL_free(conn->ssl);
  12026. conn->ssl = NULL;
  12027. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12028. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12029. #ifndef OPENSSL_API_1_1
  12030. ERR_remove_state(0);
  12031. #endif
  12032. return 0;
  12033. }
  12034. /* SSL functions may fail and require to be called again:
  12035. * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html
  12036. * Here "func" could be SSL_connect or SSL_accept. */
  12037. for (i = 16; i <= 1024; i *= 2) {
  12038. ret = func(conn->ssl);
  12039. if (ret != 1) {
  12040. err = SSL_get_error(conn->ssl, ret);
  12041. if ((err == SSL_ERROR_WANT_CONNECT)
  12042. || (err == SSL_ERROR_WANT_ACCEPT)
  12043. || (err == SSL_ERROR_WANT_READ)
  12044. || (err == SSL_ERROR_WANT_WRITE)) {
  12045. /* Need to retry the function call "later".
  12046. * See https://linux.die.net/man/3/ssl_get_error
  12047. * This is typical for non-blocking sockets. */
  12048. if (*stop_server) {
  12049. /* Don't wait if the server is going to be stopped. */
  12050. break;
  12051. }
  12052. mg_sleep(i);
  12053. } else if (err == SSL_ERROR_SYSCALL) {
  12054. /* This is an IO error. Look at errno. */
  12055. err = errno;
  12056. /* TODO: set some error message */
  12057. (void)err;
  12058. break;
  12059. } else {
  12060. /* This is an SSL specific error */
  12061. /* TODO: set some error message */
  12062. break;
  12063. }
  12064. } else {
  12065. /* success */
  12066. break;
  12067. }
  12068. }
  12069. if (ret != 1) {
  12070. SSL_free(conn->ssl);
  12071. conn->ssl = NULL;
  12072. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  12073. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  12074. #ifndef OPENSSL_API_1_1
  12075. ERR_remove_state(0);
  12076. #endif
  12077. return 0;
  12078. }
  12079. return 1;
  12080. }
  12081. /* Return OpenSSL error message (from CRYPTO lib) */
  12082. static const char *
  12083. ssl_error(void)
  12084. {
  12085. unsigned long err;
  12086. err = ERR_get_error();
  12087. return ((err == 0) ? "" : ERR_error_string(err, NULL));
  12088. }
  12089. static int
  12090. hexdump2string(void *mem, int memlen, char *buf, int buflen)
  12091. {
  12092. int i;
  12093. const char hexdigit[] = "0123456789abcdef";
  12094. if ((memlen <= 0) || (buflen <= 0)) {
  12095. return 0;
  12096. }
  12097. if (buflen < (3 * memlen)) {
  12098. return 0;
  12099. }
  12100. for (i = 0; i < memlen; i++) {
  12101. if (i > 0) {
  12102. buf[3 * i - 1] = ' ';
  12103. }
  12104. buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF];
  12105. buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF];
  12106. }
  12107. buf[3 * memlen - 1] = 0;
  12108. return 1;
  12109. }
  12110. static void
  12111. ssl_get_client_cert_info(struct mg_connection *conn)
  12112. {
  12113. X509 *cert = SSL_get_peer_certificate(conn->ssl);
  12114. if (cert) {
  12115. char str_subject[1024];
  12116. char str_issuer[1024];
  12117. char str_finger[1024];
  12118. unsigned char buf[256];
  12119. char *str_serial = NULL;
  12120. unsigned int ulen;
  12121. int ilen;
  12122. unsigned char *tmp_buf;
  12123. unsigned char *tmp_p;
  12124. /* Handle to algorithm used for fingerprint */
  12125. const EVP_MD *digest = EVP_get_digestbyname("sha1");
  12126. /* Get Subject and issuer */
  12127. X509_NAME *subj = X509_get_subject_name(cert);
  12128. X509_NAME *iss = X509_get_issuer_name(cert);
  12129. /* Get serial number */
  12130. ASN1_INTEGER *serial = X509_get_serialNumber(cert);
  12131. /* Translate serial number to a hex string */
  12132. BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL);
  12133. str_serial = BN_bn2hex(serial_bn);
  12134. BN_free(serial_bn);
  12135. /* Translate subject and issuer to a string */
  12136. (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject));
  12137. (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer));
  12138. /* Calculate SHA1 fingerprint and store as a hex string */
  12139. ulen = 0;
  12140. /* ASN1_digest is deprecated. Do the calculation manually,
  12141. * using EVP_Digest. */
  12142. ilen = i2d_X509(cert, NULL);
  12143. tmp_buf = (ilen > 0)
  12144. ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1,
  12145. conn->phys_ctx)
  12146. : NULL;
  12147. if (tmp_buf) {
  12148. tmp_p = tmp_buf;
  12149. (void)i2d_X509(cert, &tmp_p);
  12150. if (!EVP_Digest(
  12151. tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) {
  12152. ulen = 0;
  12153. }
  12154. mg_free(tmp_buf);
  12155. }
  12156. if (!hexdump2string(
  12157. buf, (int)ulen, str_finger, (int)sizeof(str_finger))) {
  12158. *str_finger = 0;
  12159. }
  12160. conn->request_info.client_cert = (struct mg_client_cert *)
  12161. mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx);
  12162. if (conn->request_info.client_cert) {
  12163. conn->request_info.client_cert->peer_cert = (void *)cert;
  12164. conn->request_info.client_cert->subject =
  12165. mg_strdup_ctx(str_subject, conn->phys_ctx);
  12166. conn->request_info.client_cert->issuer =
  12167. mg_strdup_ctx(str_issuer, conn->phys_ctx);
  12168. conn->request_info.client_cert->serial =
  12169. mg_strdup_ctx(str_serial, conn->phys_ctx);
  12170. conn->request_info.client_cert->finger =
  12171. mg_strdup_ctx(str_finger, conn->phys_ctx);
  12172. } else {
  12173. mg_cry(conn,
  12174. "Out of memory: Cannot allocate memory for client "
  12175. "certificate");
  12176. }
  12177. /* Strings returned from bn_bn2hex must be freed using OPENSSL_free,
  12178. * see https://linux.die.net/man/3/bn_bn2hex */
  12179. OPENSSL_free(str_serial);
  12180. }
  12181. }
  12182. #ifdef OPENSSL_API_1_1
  12183. #else
  12184. static void
  12185. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  12186. {
  12187. (void)line;
  12188. (void)file;
  12189. if (mode & 1) {
  12190. /* 1 is CRYPTO_LOCK */
  12191. (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  12192. } else {
  12193. (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  12194. }
  12195. }
  12196. #endif /* OPENSSL_API_1_1 */
  12197. #if !defined(NO_SSL_DL)
  12198. static void *
  12199. load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw)
  12200. {
  12201. union {
  12202. void *p;
  12203. void (*fp)(void);
  12204. } u;
  12205. void *dll_handle;
  12206. struct ssl_func *fp;
  12207. int ok;
  12208. int truncated = 0;
  12209. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  12210. mg_snprintf(NULL,
  12211. NULL, /* No truncation check for ebuf */
  12212. ebuf,
  12213. ebuf_len,
  12214. "%s: cannot load %s",
  12215. __func__,
  12216. dll_name);
  12217. return NULL;
  12218. }
  12219. ok = 1;
  12220. for (fp = sw; fp->name != NULL; fp++) {
  12221. #ifdef _WIN32
  12222. /* GetProcAddress() returns pointer to function */
  12223. u.fp = (void (*)(void))dlsym(dll_handle, fp->name);
  12224. #else
  12225. /* dlsym() on UNIX returns void *. ISO C forbids casts of data
  12226. * pointers to function pointers. We need to use a union to make a
  12227. * cast. */
  12228. u.p = dlsym(dll_handle, fp->name);
  12229. #endif /* _WIN32 */
  12230. if (u.fp == NULL) {
  12231. if (ok) {
  12232. mg_snprintf(NULL,
  12233. &truncated,
  12234. ebuf,
  12235. ebuf_len,
  12236. "%s: %s: cannot find %s",
  12237. __func__,
  12238. dll_name,
  12239. fp->name);
  12240. ok = 0;
  12241. } else {
  12242. size_t cur_len = strlen(ebuf);
  12243. if (!truncated) {
  12244. mg_snprintf(NULL,
  12245. &truncated,
  12246. ebuf + cur_len,
  12247. ebuf_len - cur_len - 3,
  12248. ", %s",
  12249. fp->name);
  12250. if (truncated) {
  12251. /* If truncated, add "..." */
  12252. strcat(ebuf, "...");
  12253. }
  12254. }
  12255. }
  12256. /* Debug:
  12257. * printf("Missing function: %s\n", fp->name); */
  12258. } else {
  12259. fp->ptr = u.fp;
  12260. }
  12261. }
  12262. if (!ok) {
  12263. (void)dlclose(dll_handle);
  12264. return NULL;
  12265. }
  12266. return dll_handle;
  12267. }
  12268. static void *ssllib_dll_handle; /* Store the ssl library handle. */
  12269. static void *cryptolib_dll_handle; /* Store the crypto library handle. */
  12270. #endif /* NO_SSL_DL */
  12271. #if defined(SSL_ALREADY_INITIALIZED)
  12272. static int cryptolib_users = 1; /* Reference counter for crypto library. */
  12273. #else
  12274. static int cryptolib_users = 0; /* Reference counter for crypto library. */
  12275. #endif
  12276. static int
  12277. initialize_ssl(char *ebuf, size_t ebuf_len)
  12278. {
  12279. #ifdef OPENSSL_API_1_1
  12280. if (ebuf_len > 0) {
  12281. ebuf[0] = 0;
  12282. }
  12283. #if !defined(NO_SSL_DL)
  12284. if (!cryptolib_dll_handle) {
  12285. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12286. if (!cryptolib_dll_handle) {
  12287. mg_snprintf(NULL,
  12288. NULL, /* No truncation check for ebuf */
  12289. ebuf,
  12290. ebuf_len,
  12291. "%s: error loading library %s",
  12292. __func__,
  12293. CRYPTO_LIB);
  12294. DEBUG_TRACE("%s", ebuf);
  12295. return 0;
  12296. }
  12297. }
  12298. #endif /* NO_SSL_DL */
  12299. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12300. return 1;
  12301. }
  12302. #else /* not OPENSSL_API_1_1 */
  12303. int i;
  12304. size_t size;
  12305. if (ebuf_len > 0) {
  12306. ebuf[0] = 0;
  12307. }
  12308. #if !defined(NO_SSL_DL)
  12309. if (!cryptolib_dll_handle) {
  12310. cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw);
  12311. if (!cryptolib_dll_handle) {
  12312. mg_snprintf(NULL,
  12313. NULL, /* No truncation check for ebuf */
  12314. ebuf,
  12315. ebuf_len,
  12316. "%s: error loading library %s",
  12317. __func__,
  12318. CRYPTO_LIB);
  12319. DEBUG_TRACE("%s", ebuf);
  12320. return 0;
  12321. }
  12322. }
  12323. #endif /* NO_SSL_DL */
  12324. if (mg_atomic_inc(&cryptolib_users) > 1) {
  12325. return 1;
  12326. }
  12327. /* Initialize locking callbacks, needed for thread safety.
  12328. * http://www.openssl.org/support/faq.html#PROG1
  12329. */
  12330. i = CRYPTO_num_locks();
  12331. if (i < 0) {
  12332. i = 0;
  12333. }
  12334. size = sizeof(pthread_mutex_t) * ((size_t)(i));
  12335. if (size == 0) {
  12336. ssl_mutexes = NULL;
  12337. } else if ((ssl_mutexes = (pthread_mutex_t *)mg_malloc(size)) == NULL) {
  12338. mg_snprintf(NULL,
  12339. NULL, /* No truncation check for ebuf */
  12340. ebuf,
  12341. ebuf_len,
  12342. "%s: cannot allocate mutexes: %s",
  12343. __func__,
  12344. ssl_error());
  12345. DEBUG_TRACE("%s", ebuf);
  12346. return 0;
  12347. }
  12348. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12349. pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr);
  12350. }
  12351. CRYPTO_set_locking_callback(&ssl_locking_callback);
  12352. CRYPTO_set_id_callback(&mg_current_thread_id);
  12353. #endif /* OPENSSL_API_1_1 */
  12354. #if !defined(NO_SSL_DL)
  12355. if (!ssllib_dll_handle) {
  12356. ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw);
  12357. if (!ssllib_dll_handle) {
  12358. DEBUG_TRACE("%s", ebuf);
  12359. return 0;
  12360. }
  12361. }
  12362. #endif /* NO_SSL_DL */
  12363. #ifdef OPENSSL_API_1_1
  12364. /* Initialize SSL library */
  12365. OPENSSL_init_ssl(0, NULL);
  12366. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS
  12367. | OPENSSL_INIT_LOAD_CRYPTO_STRINGS,
  12368. NULL);
  12369. #else
  12370. /* Initialize SSL library */
  12371. SSL_library_init();
  12372. SSL_load_error_strings();
  12373. #endif
  12374. return 1;
  12375. }
  12376. static int
  12377. ssl_use_pem_file(struct mg_context *phys_ctx,
  12378. struct mg_domain_context *dom_ctx,
  12379. const char *pem,
  12380. const char *chain)
  12381. {
  12382. if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  12383. mg_cry(fc(phys_ctx),
  12384. "%s: cannot open certificate file %s: %s",
  12385. __func__,
  12386. pem,
  12387. ssl_error());
  12388. return 0;
  12389. }
  12390. /* could use SSL_CTX_set_default_passwd_cb_userdata */
  12391. if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) {
  12392. mg_cry(fc(phys_ctx),
  12393. "%s: cannot open private key file %s: %s",
  12394. __func__,
  12395. pem,
  12396. ssl_error());
  12397. return 0;
  12398. }
  12399. if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) {
  12400. mg_cry(fc(phys_ctx),
  12401. "%s: certificate and private key do not match: %s",
  12402. __func__,
  12403. pem);
  12404. return 0;
  12405. }
  12406. /* In contrast to OpenSSL, wolfSSL does not support certificate
  12407. * chain files that contain private keys and certificates in
  12408. * SSL_CTX_use_certificate_chain_file.
  12409. * The CivetWeb-Server used pem-Files that contained both information.
  12410. * In order to make wolfSSL work, it is split in two files.
  12411. * One file that contains key and certificate used by the server and
  12412. * an optional chain file for the ssl stack.
  12413. */
  12414. if (chain) {
  12415. if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) {
  12416. mg_cry(fc(phys_ctx),
  12417. "%s: cannot use certificate chain file %s: %s",
  12418. __func__,
  12419. pem,
  12420. ssl_error());
  12421. return 0;
  12422. }
  12423. }
  12424. return 1;
  12425. }
  12426. #ifdef OPENSSL_API_1_1
  12427. static unsigned long
  12428. ssl_get_protocol(int version_id)
  12429. {
  12430. long unsigned ret = SSL_OP_ALL;
  12431. if (version_id > 0)
  12432. ret |= SSL_OP_NO_SSLv2;
  12433. if (version_id > 1)
  12434. ret |= SSL_OP_NO_SSLv3;
  12435. if (version_id > 2)
  12436. ret |= SSL_OP_NO_TLSv1;
  12437. if (version_id > 3)
  12438. ret |= SSL_OP_NO_TLSv1_1;
  12439. return ret;
  12440. }
  12441. #else
  12442. static long
  12443. ssl_get_protocol(int version_id)
  12444. {
  12445. long ret = SSL_OP_ALL;
  12446. if (version_id > 0)
  12447. ret |= SSL_OP_NO_SSLv2;
  12448. if (version_id > 1)
  12449. ret |= SSL_OP_NO_SSLv3;
  12450. if (version_id > 2)
  12451. ret |= SSL_OP_NO_TLSv1;
  12452. if (version_id > 3)
  12453. ret |= SSL_OP_NO_TLSv1_1;
  12454. return ret;
  12455. }
  12456. #endif /* OPENSSL_API_1_1 */
  12457. /* SSL callback documentation:
  12458. * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html
  12459. * https://linux.die.net/man/3/ssl_set_info_callback */
  12460. static void
  12461. ssl_info_callback(SSL *ssl, int what, int ret)
  12462. {
  12463. (void)ret;
  12464. if (what & SSL_CB_HANDSHAKE_START) {
  12465. SSL_get_app_data(ssl);
  12466. }
  12467. if (what & SSL_CB_HANDSHAKE_DONE) {
  12468. /* TODO: check for openSSL 1.1 */
  12469. //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
  12470. // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  12471. }
  12472. }
  12473. static int
  12474. ssl_servername_callback(SSL *ssl, int *ad, void *arg)
  12475. {
  12476. struct mg_context *ctx = (struct mg_context *)arg;
  12477. struct mg_domain_context *dom =
  12478. (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL;
  12479. #if defined(__GNUC__) || defined(__MINGW32__)
  12480. #pragma GCC diagnostic push
  12481. #pragma GCC diagnostic ignored "-Wcast-align"
  12482. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  12483. /* We used an aligned pointer in SSL_set_app_data */
  12484. struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl);
  12485. #if defined(__GNUC__) || defined(__MINGW32__)
  12486. #pragma GCC diagnostic pop
  12487. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  12488. const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  12489. (void)ad;
  12490. DEBUG_ASSERT(conn->phys_ctx == ctx);
  12491. /* Old clients (Win XP) will not support SNI. Then, there
  12492. * is no server name available in the request - we can
  12493. * only work with the default certificate.
  12494. * Multiple HTTPS hosts on one IP+port are only possible
  12495. * with a certificate containing all alternative names.
  12496. */
  12497. if ((servername == NULL) || (*servername == 0)) {
  12498. DEBUG_TRACE("%s", "SSL connection not supporting SNI");
  12499. conn->dom_ctx = &(ctx->dd);
  12500. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  12501. return SSL_TLSEXT_ERR_NOACK;
  12502. }
  12503. DEBUG_TRACE("TLS connection to host %s", servername);
  12504. while (dom) {
  12505. if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) {
  12506. /* Found matching domain */
  12507. DEBUG_TRACE("TLS domain %s found",
  12508. dom->config[AUTHENTICATION_DOMAIN]);
  12509. SSL_set_SSL_CTX(ssl, dom->ssl_ctx);
  12510. conn->dom_ctx = dom;
  12511. return SSL_TLSEXT_ERR_OK;
  12512. }
  12513. dom = dom->next;
  12514. }
  12515. /* Default domain */
  12516. DEBUG_TRACE("TLS default domain %s used",
  12517. ctx->dd.config[AUTHENTICATION_DOMAIN]);
  12518. conn->dom_ctx = &(ctx->dd);
  12519. SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx);
  12520. return SSL_TLSEXT_ERR_OK;
  12521. }
  12522. /* Setup SSL CTX as required by CivetWeb */
  12523. static int
  12524. init_ssl_ctx_impl(struct mg_context *phys_ctx,
  12525. struct mg_domain_context *dom_ctx,
  12526. const char *pem,
  12527. const char *chain)
  12528. {
  12529. int callback_ret;
  12530. int should_verify_peer;
  12531. int peer_certificate_optional;
  12532. const char *ca_path;
  12533. const char *ca_file;
  12534. int use_default_verify_paths;
  12535. int verify_depth;
  12536. time_t now_rt = time(NULL);
  12537. struct timespec now_mt;
  12538. md5_byte_t ssl_context_id[16];
  12539. md5_state_t md5state;
  12540. int protocol_ver;
  12541. #ifdef OPENSSL_API_1_1
  12542. if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) {
  12543. mg_cry(fc(phys_ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  12544. return 0;
  12545. }
  12546. #else
  12547. if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  12548. mg_cry(fc(phys_ctx), "SSL_CTX_new (server) error: %s", ssl_error());
  12549. return 0;
  12550. }
  12551. #endif /* OPENSSL_API_1_1 */
  12552. SSL_CTX_clear_options(dom_ctx->ssl_ctx,
  12553. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1
  12554. | SSL_OP_NO_TLSv1_1);
  12555. protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]);
  12556. SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver));
  12557. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE);
  12558. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
  12559. SSL_CTX_set_options(dom_ctx->ssl_ctx,
  12560. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  12561. SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
  12562. #if !defined(NO_SSL_DL)
  12563. SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1);
  12564. #endif /* NO_SSL_DL */
  12565. #ifdef __clang__
  12566. #pragma clang diagnostic push
  12567. #pragma clang diagnostic ignored "-Wincompatible-pointer-types"
  12568. #endif
  12569. /* Depending on the OpenSSL version, the callback may be
  12570. * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)'
  12571. * yielding in an "incompatible-pointer-type" warning for the other
  12572. * version. It seems to be "unclear" what is correct:
  12573. * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526
  12574. * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html
  12575. * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html
  12576. * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173
  12577. * Disable this warning here.
  12578. * Alternative would be a version dependent ssl_info_callback and
  12579. * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there.
  12580. */
  12581. SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback);
  12582. SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx,
  12583. ssl_servername_callback);
  12584. SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx);
  12585. #ifdef __clang__
  12586. #pragma clang diagnostic pop
  12587. #endif
  12588. /* If a callback has been specified, call it. */
  12589. callback_ret = (phys_ctx->callbacks.init_ssl == NULL)
  12590. ? 0
  12591. : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx,
  12592. phys_ctx->user_data));
  12593. /* If callback returns 0, civetweb sets up the SSL certificate.
  12594. * If it returns 1, civetweb assumes the calback already did this.
  12595. * If it returns -1, initializing ssl fails. */
  12596. if (callback_ret < 0) {
  12597. mg_cry(fc(phys_ctx), "SSL callback returned error: %i", callback_ret);
  12598. return 0;
  12599. }
  12600. if (callback_ret > 0) {
  12601. /* Callback did everything. */
  12602. return 1;
  12603. }
  12604. /* Use some UID as session context ID. */
  12605. md5_init(&md5state);
  12606. md5_append(&md5state, (const md5_byte_t *)&now_rt, sizeof(now_rt));
  12607. clock_gettime(CLOCK_MONOTONIC, &now_mt);
  12608. md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt));
  12609. md5_append(&md5state,
  12610. (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS],
  12611. strlen(phys_ctx->dd.config[LISTENING_PORTS]));
  12612. md5_append(&md5state,
  12613. (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN],
  12614. strlen(dom_ctx->config[AUTHENTICATION_DOMAIN]));
  12615. md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx));
  12616. md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx));
  12617. md5_finish(&md5state, ssl_context_id);
  12618. SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx,
  12619. (const unsigned char *)&ssl_context_id,
  12620. sizeof(ssl_context_id));
  12621. if (pem != NULL) {
  12622. if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) {
  12623. return 0;
  12624. }
  12625. }
  12626. /* Should we support client certificates? */
  12627. /* Default is "no". */
  12628. should_verify_peer = 0;
  12629. peer_certificate_optional = 0;
  12630. if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) {
  12631. if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) {
  12632. /* Yes, they are mandatory */
  12633. should_verify_peer = 1;
  12634. peer_certificate_optional = 0;
  12635. } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER],
  12636. "optional") == 0) {
  12637. /* Yes, they are optional */
  12638. should_verify_peer = 1;
  12639. peer_certificate_optional = 1;
  12640. }
  12641. }
  12642. use_default_verify_paths =
  12643. (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL)
  12644. && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes")
  12645. == 0);
  12646. if (should_verify_peer) {
  12647. ca_path = dom_ctx->config[SSL_CA_PATH];
  12648. ca_file = dom_ctx->config[SSL_CA_FILE];
  12649. if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path)
  12650. != 1) {
  12651. mg_cry(fc(phys_ctx),
  12652. "SSL_CTX_load_verify_locations error: %s "
  12653. "ssl_verify_peer requires setting "
  12654. "either ssl_ca_path or ssl_ca_file. "
  12655. "Is any of them present in the "
  12656. ".conf file?",
  12657. ssl_error());
  12658. return 0;
  12659. }
  12660. if (peer_certificate_optional) {
  12661. SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL);
  12662. } else {
  12663. SSL_CTX_set_verify(dom_ctx->ssl_ctx,
  12664. SSL_VERIFY_PEER
  12665. | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  12666. NULL);
  12667. }
  12668. if (use_default_verify_paths
  12669. && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) {
  12670. mg_cry(fc(phys_ctx),
  12671. "SSL_CTX_set_default_verify_paths error: %s",
  12672. ssl_error());
  12673. return 0;
  12674. }
  12675. if (dom_ctx->config[SSL_VERIFY_DEPTH]) {
  12676. verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]);
  12677. SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth);
  12678. }
  12679. }
  12680. if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) {
  12681. if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx,
  12682. dom_ctx->config[SSL_CIPHER_LIST]) != 1) {
  12683. mg_cry(fc(phys_ctx),
  12684. "SSL_CTX_set_cipher_list error: %s",
  12685. ssl_error());
  12686. }
  12687. }
  12688. return 1;
  12689. }
  12690. /* Check if SSL is required.
  12691. * If so, dynamically load SSL library
  12692. * and set up ctx->ssl_ctx pointer. */
  12693. static int
  12694. init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  12695. {
  12696. void *ssl_ctx = 0;
  12697. int callback_ret;
  12698. const char *pem;
  12699. const char *chain;
  12700. char ebuf[128];
  12701. if (!phys_ctx) {
  12702. return 0;
  12703. }
  12704. if (!dom_ctx) {
  12705. dom_ctx = &(phys_ctx->dd);
  12706. }
  12707. if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) {
  12708. /* No SSL port is set. No need to setup SSL. */
  12709. return 1;
  12710. }
  12711. /* Check for external SSL_CTX */
  12712. callback_ret =
  12713. (phys_ctx->callbacks.external_ssl_ctx == NULL)
  12714. ? 0
  12715. : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx,
  12716. phys_ctx->user_data));
  12717. if (callback_ret < 0) {
  12718. mg_cry(fc(phys_ctx),
  12719. "external_ssl_ctx callback returned error: %i",
  12720. callback_ret);
  12721. return 0;
  12722. } else if (callback_ret > 0) {
  12723. dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx;
  12724. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12725. mg_cry(fc(phys_ctx), "%s", ebuf);
  12726. return 0;
  12727. }
  12728. return 1;
  12729. }
  12730. /* else: external_ssl_ctx does not exist or returns 0,
  12731. * CivetWeb should continue initializing SSL */
  12732. /* If PEM file is not specified and the init_ssl callback
  12733. * is not specified, setup will fail. */
  12734. if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL)
  12735. && (phys_ctx->callbacks.init_ssl == NULL)) {
  12736. /* No certificate and no callback:
  12737. * Essential data to set up TLS is missing.
  12738. */
  12739. mg_cry(fc(phys_ctx),
  12740. "Initializing SSL failed: -%s is not set",
  12741. config_options[SSL_CERTIFICATE].name);
  12742. return 0;
  12743. }
  12744. chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN];
  12745. if (chain == NULL) {
  12746. chain = pem;
  12747. }
  12748. if ((chain != NULL) && (*chain == 0)) {
  12749. chain = NULL;
  12750. }
  12751. if (!initialize_ssl(ebuf, sizeof(ebuf))) {
  12752. mg_cry(fc(phys_ctx), "%s", ebuf);
  12753. return 0;
  12754. }
  12755. return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain);
  12756. }
  12757. static void
  12758. uninitialize_ssl(void)
  12759. {
  12760. #ifdef OPENSSL_API_1_1
  12761. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12762. /* Shutdown according to
  12763. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12764. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12765. */
  12766. CONF_modules_unload(1);
  12767. #else
  12768. int i;
  12769. if (mg_atomic_dec(&cryptolib_users) == 0) {
  12770. /* Shutdown according to
  12771. * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup
  12772. * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl
  12773. */
  12774. CRYPTO_set_locking_callback(NULL);
  12775. CRYPTO_set_id_callback(NULL);
  12776. ENGINE_cleanup();
  12777. CONF_modules_unload(1);
  12778. ERR_free_strings();
  12779. EVP_cleanup();
  12780. CRYPTO_cleanup_all_ex_data();
  12781. ERR_remove_state(0);
  12782. for (i = 0; i < CRYPTO_num_locks(); i++) {
  12783. pthread_mutex_destroy(&ssl_mutexes[i]);
  12784. }
  12785. mg_free(ssl_mutexes);
  12786. ssl_mutexes = NULL;
  12787. #endif /* OPENSSL_API_1_1 */
  12788. }
  12789. }
  12790. #endif /* !NO_SSL */
  12791. static int
  12792. set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx)
  12793. {
  12794. if (phys_ctx) {
  12795. struct mg_file file = STRUCT_FILE_INITIALIZER;
  12796. const char *path;
  12797. if (!dom_ctx) {
  12798. dom_ctx = &(phys_ctx->dd);
  12799. }
  12800. path = dom_ctx->config[GLOBAL_PASSWORDS_FILE];
  12801. if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) {
  12802. mg_cry(fc(phys_ctx), "Cannot open %s: %s", path, strerror(ERRNO));
  12803. return 0;
  12804. }
  12805. return 1;
  12806. }
  12807. return 0;
  12808. }
  12809. static int
  12810. set_acl_option(struct mg_context *phys_ctx)
  12811. {
  12812. return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1;
  12813. }
  12814. static void
  12815. reset_per_request_attributes(struct mg_connection *conn)
  12816. {
  12817. if (!conn) {
  12818. return;
  12819. }
  12820. conn->connection_type =
  12821. CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */
  12822. conn->num_bytes_sent = conn->consumed_content = 0;
  12823. conn->path_info = NULL;
  12824. conn->status_code = -1;
  12825. conn->content_len = -1;
  12826. conn->is_chunked = 0;
  12827. conn->must_close = 0;
  12828. conn->request_len = 0;
  12829. conn->throttle = 0;
  12830. conn->data_len = 0;
  12831. conn->chunk_remainder = 0;
  12832. conn->accept_gzip = 0;
  12833. conn->response_info.content_length = conn->request_info.content_length = -1;
  12834. conn->response_info.http_version = conn->request_info.http_version = NULL;
  12835. conn->response_info.num_headers = conn->request_info.num_headers = 0;
  12836. conn->response_info.status_text = NULL;
  12837. conn->response_info.status_code = 0;
  12838. conn->request_info.remote_user = NULL;
  12839. conn->request_info.request_method = NULL;
  12840. conn->request_info.request_uri = NULL;
  12841. conn->request_info.local_uri = NULL;
  12842. #if defined(MG_LEGACY_INTERFACE)
  12843. /* Legacy before split into local_uri and request_uri */
  12844. conn->request_info.uri = NULL;
  12845. #endif
  12846. }
  12847. #if 0
  12848. /* Note: set_sock_timeout is not required for non-blocking sockets.
  12849. * Leave this function here (commented out) for reference until
  12850. * CivetWeb 1.9 is tested, and the tests confirme this function is
  12851. * no longer required.
  12852. */
  12853. static int
  12854. set_sock_timeout(SOCKET sock, int milliseconds)
  12855. {
  12856. int r0 = 0, r1, r2;
  12857. #ifdef _WIN32
  12858. /* Windows specific */
  12859. DWORD tv = (DWORD)milliseconds;
  12860. #else
  12861. /* Linux, ... (not Windows) */
  12862. struct timeval tv;
  12863. /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482):
  12864. * max. time waiting for the acknowledged of TCP data before the connection
  12865. * will be forcefully closed and ETIMEDOUT is returned to the application.
  12866. * If this option is not set, the default timeout of 20-30 minutes is used.
  12867. */
  12868. /* #define TCP_USER_TIMEOUT (18) */
  12869. #if defined(TCP_USER_TIMEOUT)
  12870. unsigned int uto = (unsigned int)milliseconds;
  12871. r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  12872. #endif
  12873. memset(&tv, 0, sizeof(tv));
  12874. tv.tv_sec = milliseconds / 1000;
  12875. tv.tv_usec = (milliseconds * 1000) % 1000000;
  12876. #endif /* _WIN32 */
  12877. r1 = setsockopt(
  12878. sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12879. r2 = setsockopt(
  12880. sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv));
  12881. return r0 || r1 || r2;
  12882. }
  12883. #endif
  12884. static int
  12885. set_tcp_nodelay(SOCKET sock, int nodelay_on)
  12886. {
  12887. if (setsockopt(sock,
  12888. IPPROTO_TCP,
  12889. TCP_NODELAY,
  12890. (SOCK_OPT_TYPE)&nodelay_on,
  12891. sizeof(nodelay_on)) != 0) {
  12892. /* Error */
  12893. return 1;
  12894. }
  12895. /* OK */
  12896. return 0;
  12897. }
  12898. static void
  12899. close_socket_gracefully(struct mg_connection *conn)
  12900. {
  12901. #if defined(_WIN32)
  12902. char buf[MG_BUF_LEN];
  12903. int n;
  12904. #endif
  12905. struct linger linger;
  12906. int error_code = 0;
  12907. int linger_timeout = -2;
  12908. socklen_t opt_len = sizeof(error_code);
  12909. if (!conn) {
  12910. return;
  12911. }
  12912. /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx:
  12913. * "Note that enabling a nonzero timeout on a nonblocking socket
  12914. * is not recommended.", so set it to blocking now */
  12915. set_blocking_mode(conn->client.sock);
  12916. /* Send FIN to the client */
  12917. shutdown(conn->client.sock, SHUTDOWN_WR);
  12918. #if defined(_WIN32)
  12919. /* Read and discard pending incoming data. If we do not do that and
  12920. * close
  12921. * the socket, the data in the send buffer may be discarded. This
  12922. * behaviour is seen on Windows, when client keeps sending data
  12923. * when server decides to close the connection; then when client
  12924. * does recv() it gets no data back. */
  12925. do {
  12926. n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0);
  12927. } while (n > 0);
  12928. #endif
  12929. if (conn->dom_ctx->config[LINGER_TIMEOUT]) {
  12930. linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]);
  12931. }
  12932. /* Set linger option according to configuration */
  12933. if (linger_timeout >= 0) {
  12934. /* Set linger option to avoid socket hanging out after close. This
  12935. * prevent ephemeral port exhaust problem under high QPS. */
  12936. linger.l_onoff = 1;
  12937. #if defined(_MSC_VER)
  12938. #pragma warning(push)
  12939. #pragma warning(disable : 4244)
  12940. #endif
  12941. #if defined(__GNUC__) || defined(__MINGW32__)
  12942. #pragma GCC diagnostic push
  12943. #pragma GCC diagnostic ignored "-Wconversion"
  12944. #endif
  12945. /* Data type of linger structure elements may differ,
  12946. * so we don't know what cast we need here.
  12947. * Disable type conversion warnings. */
  12948. linger.l_linger = (linger_timeout + 999) / 1000;
  12949. #if defined(__GNUC__) || defined(__MINGW32__)
  12950. #pragma GCC diagnostic pop
  12951. #endif
  12952. #if defined(_MSC_VER)
  12953. #pragma warning(pop)
  12954. #endif
  12955. } else {
  12956. linger.l_onoff = 0;
  12957. linger.l_linger = 0;
  12958. }
  12959. if (linger_timeout < -1) {
  12960. /* Default: don't configure any linger */
  12961. } else if (getsockopt(conn->client.sock,
  12962. SOL_SOCKET,
  12963. SO_ERROR,
  12964. (char *)&error_code,
  12965. &opt_len) != 0) {
  12966. /* Cannot determine if socket is already closed. This should
  12967. * not occur and never did in a test. Log an error message
  12968. * and continue. */
  12969. mg_cry(conn,
  12970. "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s",
  12971. __func__,
  12972. strerror(ERRNO));
  12973. } else if (error_code == ECONNRESET) {
  12974. /* Socket already closed by client/peer, close socket without linger
  12975. */
  12976. } else {
  12977. /* Set linger timeout */
  12978. if (setsockopt(conn->client.sock,
  12979. SOL_SOCKET,
  12980. SO_LINGER,
  12981. (char *)&linger,
  12982. sizeof(linger)) != 0) {
  12983. mg_cry(conn,
  12984. "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s",
  12985. __func__,
  12986. linger.l_onoff,
  12987. linger.l_linger,
  12988. strerror(ERRNO));
  12989. }
  12990. }
  12991. /* Now we know that our FIN is ACK-ed, safe to close */
  12992. closesocket(conn->client.sock);
  12993. conn->client.sock = INVALID_SOCKET;
  12994. }
  12995. static void
  12996. close_connection(struct mg_connection *conn)
  12997. {
  12998. #if defined(USE_SERVER_STATS)
  12999. conn->conn_state = 6; /* to close */
  13000. #endif
  13001. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  13002. if (conn->lua_websocket_state) {
  13003. lua_websocket_close(conn, conn->lua_websocket_state);
  13004. conn->lua_websocket_state = NULL;
  13005. }
  13006. #endif
  13007. mg_lock_connection(conn);
  13008. /* Set close flag, so keep-alive loops will stop */
  13009. conn->must_close = 1;
  13010. /* call the connection_close callback if assigned */
  13011. if (conn->phys_ctx->callbacks.connection_close != NULL) {
  13012. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13013. conn->phys_ctx->callbacks.connection_close(conn);
  13014. }
  13015. }
  13016. /* Reset user data, after close callback is called.
  13017. * Do not reuse it. If the user needs a destructor,
  13018. * it must be done in the connection_close callback. */
  13019. mg_set_user_connection_data(conn, NULL);
  13020. #if defined(USE_SERVER_STATS)
  13021. conn->conn_state = 7; /* closing */
  13022. #endif
  13023. #ifndef NO_SSL
  13024. if (conn->ssl != NULL) {
  13025. /* Run SSL_shutdown twice to ensure completly close SSL connection
  13026. */
  13027. SSL_shutdown(conn->ssl);
  13028. SSL_free(conn->ssl);
  13029. /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion:
  13030. * https://wiki.openssl.org/index.php/Talk:Library_Initialization */
  13031. #ifndef OPENSSL_API_1_1
  13032. ERR_remove_state(0);
  13033. #endif
  13034. conn->ssl = NULL;
  13035. }
  13036. #endif
  13037. if (conn->client.sock != INVALID_SOCKET) {
  13038. close_socket_gracefully(conn);
  13039. conn->client.sock = INVALID_SOCKET;
  13040. }
  13041. if (conn->host) {
  13042. mg_free((void *)conn->host);
  13043. conn->host = NULL;
  13044. }
  13045. mg_unlock_connection(conn);
  13046. #if defined(USE_SERVER_STATS)
  13047. conn->conn_state = 8; /* closed */
  13048. #endif
  13049. }
  13050. void
  13051. mg_close_connection(struct mg_connection *conn)
  13052. {
  13053. #if defined(USE_WEBSOCKET)
  13054. struct mg_context *client_ctx = NULL;
  13055. #endif /* defined(USE_WEBSOCKET) */
  13056. if ((conn == NULL) || (conn->phys_ctx == NULL)) {
  13057. return;
  13058. }
  13059. #if defined(USE_WEBSOCKET)
  13060. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13061. if (conn->in_websocket_handling) {
  13062. /* Set close flag, so the server thread can exit. */
  13063. conn->must_close = 1;
  13064. return;
  13065. }
  13066. }
  13067. if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) {
  13068. unsigned int i;
  13069. /* ws/wss client */
  13070. client_ctx = conn->phys_ctx;
  13071. /* client context: loops must end */
  13072. client_ctx->stop_flag = 1;
  13073. conn->must_close = 1;
  13074. /* We need to get the client thread out of the select/recv call
  13075. * here. */
  13076. /* Since we use a sleep quantum of some seconds to check for recv
  13077. * timeouts, we will just wait a few seconds in mg_join_thread. */
  13078. /* join worker thread */
  13079. for (i = 0; i < client_ctx->cfg_worker_threads; i++) {
  13080. if (client_ctx->worker_threadids[i] != 0) {
  13081. mg_join_thread(client_ctx->worker_threadids[i]);
  13082. }
  13083. }
  13084. }
  13085. #endif /* defined(USE_WEBSOCKET) */
  13086. close_connection(conn);
  13087. #ifndef NO_SSL
  13088. if (conn->client_ssl_ctx != NULL) {
  13089. SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx);
  13090. }
  13091. #endif
  13092. #if defined(USE_WEBSOCKET)
  13093. if (client_ctx != NULL) {
  13094. /* free context */
  13095. mg_free(client_ctx->worker_threadids);
  13096. mg_free(client_ctx);
  13097. (void)pthread_mutex_destroy(&conn->mutex);
  13098. mg_free(conn);
  13099. } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) {
  13100. mg_free(conn);
  13101. }
  13102. #else
  13103. if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */
  13104. mg_free(conn);
  13105. }
  13106. #endif /* defined(USE_WEBSOCKET) */
  13107. }
  13108. /* Only for memory statistics */
  13109. static struct mg_context common_client_context;
  13110. static struct mg_connection *
  13111. mg_connect_client_impl(const struct mg_client_options *client_options,
  13112. int use_ssl,
  13113. char *ebuf,
  13114. size_t ebuf_len)
  13115. {
  13116. struct mg_connection *conn = NULL;
  13117. SOCKET sock;
  13118. union usa sa;
  13119. struct sockaddr *psa;
  13120. socklen_t len;
  13121. unsigned max_req_size =
  13122. (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value);
  13123. /* Size of structures, aligned to 8 bytes */
  13124. size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3;
  13125. size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3;
  13126. conn = (struct mg_connection *)mg_calloc_ctx(1,
  13127. conn_size + ctx_size
  13128. + max_req_size,
  13129. &common_client_context);
  13130. if (conn == NULL) {
  13131. mg_snprintf(NULL,
  13132. NULL, /* No truncation check for ebuf */
  13133. ebuf,
  13134. ebuf_len,
  13135. "calloc(): %s",
  13136. strerror(ERRNO));
  13137. return NULL;
  13138. }
  13139. #if defined(__GNUC__) || defined(__MINGW32__)
  13140. #pragma GCC diagnostic push
  13141. #pragma GCC diagnostic ignored "-Wcast-align"
  13142. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13143. /* conn_size is aligned to 8 bytes */
  13144. conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size);
  13145. #if defined(__GNUC__) || defined(__MINGW32__)
  13146. #pragma GCC diagnostic pop
  13147. #endif /* defined(__GNUC__) || defined(__MINGW32__) */
  13148. conn->buf = (((char *)conn) + conn_size + ctx_size);
  13149. conn->buf_size = (int)max_req_size;
  13150. conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT;
  13151. conn->dom_ctx = &(conn->phys_ctx->dd);
  13152. if (!connect_socket(&common_client_context,
  13153. client_options->host,
  13154. client_options->port,
  13155. use_ssl,
  13156. ebuf,
  13157. ebuf_len,
  13158. &sock,
  13159. &sa)) {
  13160. /* ebuf is set by connect_socket,
  13161. * free all memory and return NULL; */
  13162. mg_free(conn);
  13163. return NULL;
  13164. }
  13165. #ifndef NO_SSL
  13166. #ifdef OPENSSL_API_1_1
  13167. if (use_ssl
  13168. && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) {
  13169. mg_snprintf(NULL,
  13170. NULL, /* No truncation check for ebuf */
  13171. ebuf,
  13172. ebuf_len,
  13173. "SSL_CTX_new error");
  13174. closesocket(sock);
  13175. mg_free(conn);
  13176. return NULL;
  13177. }
  13178. #else
  13179. if (use_ssl
  13180. && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method()))
  13181. == NULL) {
  13182. mg_snprintf(NULL,
  13183. NULL, /* No truncation check for ebuf */
  13184. ebuf,
  13185. ebuf_len,
  13186. "SSL_CTX_new error");
  13187. closesocket(sock);
  13188. mg_free(conn);
  13189. return NULL;
  13190. }
  13191. #endif /* OPENSSL_API_1_1 */
  13192. #endif /* NO_SSL */
  13193. #ifdef USE_IPV6
  13194. len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin)
  13195. : sizeof(conn->client.rsa.sin6);
  13196. psa = (sa.sa.sa_family == AF_INET)
  13197. ? (struct sockaddr *)&(conn->client.rsa.sin)
  13198. : (struct sockaddr *)&(conn->client.rsa.sin6);
  13199. #else
  13200. len = sizeof(conn->client.rsa.sin);
  13201. psa = (struct sockaddr *)&(conn->client.rsa.sin);
  13202. #endif
  13203. conn->client.sock = sock;
  13204. conn->client.lsa = sa;
  13205. if (getsockname(sock, psa, &len) != 0) {
  13206. mg_cry(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO));
  13207. }
  13208. conn->client.is_ssl = use_ssl ? 1 : 0;
  13209. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  13210. #ifndef NO_SSL
  13211. if (use_ssl) {
  13212. common_client_context.dd.ssl_ctx = conn->client_ssl_ctx;
  13213. /* TODO: Check ssl_verify_peer and ssl_ca_path here.
  13214. * SSL_CTX_set_verify call is needed to switch off server
  13215. * certificate checking, which is off by default in OpenSSL and
  13216. * on in yaSSL. */
  13217. /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx,
  13218. * SSL_VERIFY_PEER, verify_ssl_server); */
  13219. if (client_options->client_cert) {
  13220. if (!ssl_use_pem_file(&common_client_context,
  13221. &(common_client_context.dd),
  13222. client_options->client_cert,
  13223. NULL)) {
  13224. mg_snprintf(NULL,
  13225. NULL, /* No truncation check for ebuf */
  13226. ebuf,
  13227. ebuf_len,
  13228. "Can not use SSL client certificate");
  13229. SSL_CTX_free(conn->client_ssl_ctx);
  13230. closesocket(sock);
  13231. mg_free(conn);
  13232. return NULL;
  13233. }
  13234. }
  13235. if (client_options->server_cert) {
  13236. SSL_CTX_load_verify_locations(conn->client_ssl_ctx,
  13237. client_options->server_cert,
  13238. NULL);
  13239. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL);
  13240. } else {
  13241. SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL);
  13242. }
  13243. if (!sslize(conn,
  13244. conn->client_ssl_ctx,
  13245. SSL_connect,
  13246. &(conn->phys_ctx->stop_flag))) {
  13247. mg_snprintf(NULL,
  13248. NULL, /* No truncation check for ebuf */
  13249. ebuf,
  13250. ebuf_len,
  13251. "SSL connection error");
  13252. SSL_CTX_free(conn->client_ssl_ctx);
  13253. closesocket(sock);
  13254. mg_free(conn);
  13255. return NULL;
  13256. }
  13257. }
  13258. #endif
  13259. if (0 != set_non_blocking_mode(sock)) {
  13260. /* TODO: handle error */
  13261. ;
  13262. }
  13263. return conn;
  13264. }
  13265. CIVETWEB_API struct mg_connection *
  13266. mg_connect_client_secure(const struct mg_client_options *client_options,
  13267. char *error_buffer,
  13268. size_t error_buffer_size)
  13269. {
  13270. return mg_connect_client_impl(client_options,
  13271. 1,
  13272. error_buffer,
  13273. error_buffer_size);
  13274. }
  13275. struct mg_connection *
  13276. mg_connect_client(const char *host,
  13277. int port,
  13278. int use_ssl,
  13279. char *error_buffer,
  13280. size_t error_buffer_size)
  13281. {
  13282. struct mg_client_options opts;
  13283. memset(&opts, 0, sizeof(opts));
  13284. opts.host = host;
  13285. opts.port = port;
  13286. return mg_connect_client_impl(&opts,
  13287. use_ssl,
  13288. error_buffer,
  13289. error_buffer_size);
  13290. }
  13291. static const struct {
  13292. const char *proto;
  13293. size_t proto_len;
  13294. unsigned default_port;
  13295. } abs_uri_protocols[] = {{"http://", 7, 80},
  13296. {"https://", 8, 443},
  13297. {"ws://", 5, 80},
  13298. {"wss://", 6, 443},
  13299. {NULL, 0, 0}};
  13300. /* Check if the uri is valid.
  13301. * return 0 for invalid uri,
  13302. * return 1 for *,
  13303. * return 2 for relative uri,
  13304. * return 3 for absolute uri without port,
  13305. * return 4 for absolute uri with port */
  13306. static int
  13307. get_uri_type(const char *uri)
  13308. {
  13309. int i;
  13310. const char *hostend, *portbegin;
  13311. char *portend;
  13312. unsigned long port;
  13313. /* According to the HTTP standard
  13314. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  13315. * URI can be an asterisk (*) or should start with slash (relative uri),
  13316. * or it should start with the protocol (absolute uri). */
  13317. if ((uri[0] == '*') && (uri[1] == '\0')) {
  13318. /* asterisk */
  13319. return 1;
  13320. }
  13321. /* Valid URIs according to RFC 3986
  13322. * (https://www.ietf.org/rfc/rfc3986.txt)
  13323. * must only contain reserved characters :/?#[]@!$&'()*+,;=
  13324. * and unreserved characters A-Z a-z 0-9 and -._~
  13325. * and % encoded symbols.
  13326. */
  13327. for (i = 0; uri[i] != 0; i++) {
  13328. if (uri[i] < 33) {
  13329. /* control characters and spaces are invalid */
  13330. return 0;
  13331. }
  13332. if (uri[i] > 126) {
  13333. /* non-ascii characters must be % encoded */
  13334. return 0;
  13335. } else {
  13336. switch (uri[i]) {
  13337. case '"': /* 34 */
  13338. case '<': /* 60 */
  13339. case '>': /* 62 */
  13340. case '\\': /* 92 */
  13341. case '^': /* 94 */
  13342. case '`': /* 96 */
  13343. case '{': /* 123 */
  13344. case '|': /* 124 */
  13345. case '}': /* 125 */
  13346. return 0;
  13347. default:
  13348. /* character is ok */
  13349. break;
  13350. }
  13351. }
  13352. }
  13353. /* A relative uri starts with a / character */
  13354. if (uri[0] == '/') {
  13355. /* relative uri */
  13356. return 2;
  13357. }
  13358. /* It could be an absolute uri: */
  13359. /* This function only checks if the uri is valid, not if it is
  13360. * addressing the current server. So civetweb can also be used
  13361. * as a proxy server. */
  13362. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13363. if (mg_strncasecmp(uri,
  13364. abs_uri_protocols[i].proto,
  13365. abs_uri_protocols[i].proto_len) == 0) {
  13366. hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/');
  13367. if (!hostend) {
  13368. return 0;
  13369. }
  13370. portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':');
  13371. if (!portbegin) {
  13372. return 3;
  13373. }
  13374. port = strtoul(portbegin + 1, &portend, 10);
  13375. if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) {
  13376. return 0;
  13377. }
  13378. return 4;
  13379. }
  13380. }
  13381. return 0;
  13382. }
  13383. /* Return NULL or the relative uri at the current server */
  13384. static const char *
  13385. get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn)
  13386. {
  13387. const char *server_domain;
  13388. size_t server_domain_len;
  13389. size_t request_domain_len = 0;
  13390. unsigned long port = 0;
  13391. int i, auth_domain_check_enabled;
  13392. const char *hostbegin = NULL;
  13393. const char *hostend = NULL;
  13394. const char *portbegin;
  13395. char *portend;
  13396. auth_domain_check_enabled =
  13397. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes");
  13398. /* DNS is case insensitive, so use case insensitive string compare here
  13399. */
  13400. for (i = 0; abs_uri_protocols[i].proto != NULL; i++) {
  13401. if (mg_strncasecmp(uri,
  13402. abs_uri_protocols[i].proto,
  13403. abs_uri_protocols[i].proto_len) == 0) {
  13404. hostbegin = uri + abs_uri_protocols[i].proto_len;
  13405. hostend = strchr(hostbegin, '/');
  13406. if (!hostend) {
  13407. return 0;
  13408. }
  13409. portbegin = strchr(hostbegin, ':');
  13410. if ((!portbegin) || (portbegin > hostend)) {
  13411. port = abs_uri_protocols[i].default_port;
  13412. request_domain_len = (size_t)(hostend - hostbegin);
  13413. } else {
  13414. port = strtoul(portbegin + 1, &portend, 10);
  13415. if ((portend != hostend) || (port <= 0)
  13416. || !is_valid_port(port)) {
  13417. return 0;
  13418. }
  13419. request_domain_len = (size_t)(portbegin - hostbegin);
  13420. }
  13421. /* protocol found, port set */
  13422. break;
  13423. }
  13424. }
  13425. if (!port) {
  13426. /* port remains 0 if the protocol is not found */
  13427. return 0;
  13428. }
  13429. /* Check if the request is directed to a different server. */
  13430. /* First check if the port is the same (IPv4 and IPv6). */
  13431. #if defined(USE_IPV6)
  13432. if (conn->client.lsa.sa.sa_family == AF_INET6) {
  13433. if (ntohs(conn->client.lsa.sin6.sin6_port) != port) {
  13434. /* Request is directed to a different port */
  13435. return 0;
  13436. }
  13437. } else
  13438. #endif
  13439. {
  13440. if (ntohs(conn->client.lsa.sin.sin_port) != port) {
  13441. /* Request is directed to a different port */
  13442. return 0;
  13443. }
  13444. }
  13445. /* Finally check if the server corresponds to the authentication
  13446. * domain of the server (the server domain).
  13447. * Allow full matches (like http://mydomain.com/path/file.ext), and
  13448. * allow subdomain matches (like http://www.mydomain.com/path/file.ext),
  13449. * but do not allow substrings (like
  13450. * http://notmydomain.com/path/file.ext
  13451. * or http://mydomain.com.fake/path/file.ext).
  13452. */
  13453. if (auth_domain_check_enabled) {
  13454. server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN];
  13455. server_domain_len = strlen(server_domain);
  13456. if (!server_domain_len) {
  13457. return 0;
  13458. }
  13459. if ((request_domain_len == server_domain_len)
  13460. && (!memcmp(server_domain, hostbegin, server_domain_len))) {
  13461. /* Request is directed to this server - full name match. */
  13462. } else {
  13463. if (request_domain_len < (server_domain_len + 2)) {
  13464. /* Request is directed to another server: The server name is
  13465. * longer
  13466. * than
  13467. * the request name. Drop this case here to avoid overflows
  13468. * in
  13469. * the
  13470. * following checks. */
  13471. return 0;
  13472. }
  13473. if (hostbegin[request_domain_len - server_domain_len - 1] != '.') {
  13474. /* Request is directed to another server: It could be a
  13475. * substring
  13476. * like notmyserver.com */
  13477. return 0;
  13478. }
  13479. if (0 != memcmp(server_domain,
  13480. hostbegin + request_domain_len - server_domain_len,
  13481. server_domain_len)) {
  13482. /* Request is directed to another server:
  13483. * The server name is different. */
  13484. return 0;
  13485. }
  13486. }
  13487. }
  13488. return hostend;
  13489. }
  13490. static int
  13491. get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13492. {
  13493. if (ebuf_len > 0) {
  13494. ebuf[0] = '\0';
  13495. }
  13496. *err = 0;
  13497. reset_per_request_attributes(conn);
  13498. if (!conn) {
  13499. mg_snprintf(conn,
  13500. NULL, /* No truncation check for ebuf */
  13501. ebuf,
  13502. ebuf_len,
  13503. "%s",
  13504. "Internal error");
  13505. *err = 500;
  13506. return 0;
  13507. }
  13508. /* Set the time the request was received. This value should be used for
  13509. * timeouts. */
  13510. clock_gettime(CLOCK_MONOTONIC, &(conn->req_time));
  13511. conn->request_len =
  13512. read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len);
  13513. DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len);
  13514. if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) {
  13515. mg_snprintf(conn,
  13516. NULL, /* No truncation check for ebuf */
  13517. ebuf,
  13518. ebuf_len,
  13519. "%s",
  13520. "Invalid message size");
  13521. *err = 500;
  13522. return 0;
  13523. }
  13524. if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) {
  13525. mg_snprintf(conn,
  13526. NULL, /* No truncation check for ebuf */
  13527. ebuf,
  13528. ebuf_len,
  13529. "%s",
  13530. "Message too large");
  13531. *err = 413;
  13532. return 0;
  13533. }
  13534. if (conn->request_len <= 0) {
  13535. if (conn->data_len > 0) {
  13536. mg_snprintf(conn,
  13537. NULL, /* No truncation check for ebuf */
  13538. ebuf,
  13539. ebuf_len,
  13540. "%s",
  13541. "Malformed message");
  13542. *err = 400;
  13543. } else {
  13544. /* Server did not recv anything -> just close the connection */
  13545. conn->must_close = 1;
  13546. mg_snprintf(conn,
  13547. NULL, /* No truncation check for ebuf */
  13548. ebuf,
  13549. ebuf_len,
  13550. "%s",
  13551. "No data received");
  13552. *err = 0;
  13553. }
  13554. return 0;
  13555. }
  13556. return 1;
  13557. }
  13558. static int
  13559. get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13560. {
  13561. const char *cl;
  13562. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13563. return 0;
  13564. }
  13565. if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info)
  13566. <= 0) {
  13567. mg_snprintf(conn,
  13568. NULL, /* No truncation check for ebuf */
  13569. ebuf,
  13570. ebuf_len,
  13571. "%s",
  13572. "Bad request");
  13573. *err = 400;
  13574. return 0;
  13575. }
  13576. /* Message is a valid request */
  13577. /* Is there a "host" ? */
  13578. conn->host = alloc_get_host(conn);
  13579. /* Do we know the content length? */
  13580. if ((cl = get_header(conn->request_info.http_headers,
  13581. conn->request_info.num_headers,
  13582. "Content-Length")) != NULL) {
  13583. /* Request/response has content length set */
  13584. char *endptr = NULL;
  13585. conn->content_len = strtoll(cl, &endptr, 10);
  13586. if (endptr == cl) {
  13587. mg_snprintf(conn,
  13588. NULL, /* No truncation check for ebuf */
  13589. ebuf,
  13590. ebuf_len,
  13591. "%s",
  13592. "Bad request");
  13593. *err = 411;
  13594. return 0;
  13595. }
  13596. /* Publish the content length back to the request info. */
  13597. conn->request_info.content_length = conn->content_len;
  13598. } else if ((cl = get_header(conn->request_info.http_headers,
  13599. conn->request_info.num_headers,
  13600. "Transfer-Encoding")) != NULL
  13601. && !mg_strcasecmp(cl, "chunked")) {
  13602. conn->is_chunked = 1;
  13603. conn->content_len = -1; /* unknown content length */
  13604. } else if (get_http_method_info(conn->request_info.request_method)
  13605. ->request_has_body) {
  13606. /* POST or PUT request without content length set */
  13607. conn->content_len = -1; /* unknown content length */
  13608. } else {
  13609. /* Other request */
  13610. conn->content_len = 0; /* No content */
  13611. }
  13612. conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */
  13613. return 1;
  13614. }
  13615. /* conn is assumed to be valid in this internal function */
  13616. static int
  13617. get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err)
  13618. {
  13619. const char *cl;
  13620. if (!get_message(conn, ebuf, ebuf_len, err)) {
  13621. return 0;
  13622. }
  13623. if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info)
  13624. <= 0) {
  13625. mg_snprintf(conn,
  13626. NULL, /* No truncation check for ebuf */
  13627. ebuf,
  13628. ebuf_len,
  13629. "%s",
  13630. "Bad response");
  13631. *err = 400;
  13632. return 0;
  13633. }
  13634. /* Message is a valid response */
  13635. /* Do we know the content length? */
  13636. if ((cl = get_header(conn->response_info.http_headers,
  13637. conn->response_info.num_headers,
  13638. "Content-Length")) != NULL) {
  13639. /* Request/response has content length set */
  13640. char *endptr = NULL;
  13641. conn->content_len = strtoll(cl, &endptr, 10);
  13642. if (endptr == cl) {
  13643. mg_snprintf(conn,
  13644. NULL, /* No truncation check for ebuf */
  13645. ebuf,
  13646. ebuf_len,
  13647. "%s",
  13648. "Bad request");
  13649. *err = 411;
  13650. return 0;
  13651. }
  13652. /* Publish the content length back to the response info. */
  13653. conn->response_info.content_length = conn->content_len;
  13654. /* TODO: check if it is still used in response_info */
  13655. conn->request_info.content_length = conn->content_len;
  13656. } else if ((cl = get_header(conn->response_info.http_headers,
  13657. conn->response_info.num_headers,
  13658. "Transfer-Encoding")) != NULL
  13659. && !mg_strcasecmp(cl, "chunked")) {
  13660. conn->is_chunked = 1;
  13661. conn->content_len = -1; /* unknown content length */
  13662. } else {
  13663. conn->content_len = -1; /* unknown content length */
  13664. }
  13665. conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */
  13666. return 1;
  13667. }
  13668. int
  13669. mg_get_response(struct mg_connection *conn,
  13670. char *ebuf,
  13671. size_t ebuf_len,
  13672. int timeout)
  13673. {
  13674. int err, ret;
  13675. char txt[32]; /* will not overflow */
  13676. char *save_timeout;
  13677. char *new_timeout;
  13678. if (ebuf_len > 0) {
  13679. ebuf[0] = '\0';
  13680. }
  13681. if (!conn) {
  13682. mg_snprintf(conn,
  13683. NULL, /* No truncation check for ebuf */
  13684. ebuf,
  13685. ebuf_len,
  13686. "%s",
  13687. "Parameter error");
  13688. return -1;
  13689. }
  13690. /* Implementation of API function for HTTP clients */
  13691. save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT];
  13692. if (timeout >= 0) {
  13693. mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout);
  13694. new_timeout = txt;
  13695. /* Not required for non-blocking sockets.
  13696. set_sock_timeout(conn->client.sock, timeout);
  13697. */
  13698. } else {
  13699. new_timeout = NULL;
  13700. }
  13701. conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout;
  13702. ret = get_response(conn, ebuf, ebuf_len, &err);
  13703. conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout;
  13704. #if defined(MG_LEGACY_INTERFACE)
  13705. /* TODO: 1) uri is deprecated;
  13706. * 2) here, ri.uri is the http response code */
  13707. conn->request_info.uri = conn->request_info.request_uri;
  13708. #endif
  13709. conn->request_info.local_uri = conn->request_info.request_uri;
  13710. /* TODO (mid): Define proper return values - maybe return length?
  13711. * For the first test use <0 for error and >0 for OK */
  13712. return (ret == 0) ? -1 : +1;
  13713. }
  13714. struct mg_connection *
  13715. mg_download(const char *host,
  13716. int port,
  13717. int use_ssl,
  13718. char *ebuf,
  13719. size_t ebuf_len,
  13720. const char *fmt,
  13721. ...)
  13722. {
  13723. struct mg_connection *conn;
  13724. va_list ap;
  13725. int i;
  13726. int reqerr;
  13727. if (ebuf_len > 0) {
  13728. ebuf[0] = '\0';
  13729. }
  13730. va_start(ap, fmt);
  13731. /* open a connection */
  13732. conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len);
  13733. if (conn != NULL) {
  13734. i = mg_vprintf(conn, fmt, ap);
  13735. if (i <= 0) {
  13736. mg_snprintf(conn,
  13737. NULL, /* No truncation check for ebuf */
  13738. ebuf,
  13739. ebuf_len,
  13740. "%s",
  13741. "Error sending request");
  13742. } else {
  13743. get_response(conn, ebuf, ebuf_len, &reqerr);
  13744. #if defined(MG_LEGACY_INTERFACE)
  13745. /* TODO: 1) uri is deprecated;
  13746. * 2) here, ri.uri is the http response code */
  13747. conn->request_info.uri = conn->request_info.request_uri;
  13748. #endif
  13749. conn->request_info.local_uri = conn->request_info.request_uri;
  13750. }
  13751. }
  13752. /* if an error occured, close the connection */
  13753. if ((ebuf[0] != '\0') && (conn != NULL)) {
  13754. mg_close_connection(conn);
  13755. conn = NULL;
  13756. }
  13757. va_end(ap);
  13758. return conn;
  13759. }
  13760. struct websocket_client_thread_data {
  13761. struct mg_connection *conn;
  13762. mg_websocket_data_handler data_handler;
  13763. mg_websocket_close_handler close_handler;
  13764. void *callback_data;
  13765. };
  13766. #if defined(USE_WEBSOCKET)
  13767. #ifdef _WIN32
  13768. static unsigned __stdcall websocket_client_thread(void *data)
  13769. #else
  13770. static void *
  13771. websocket_client_thread(void *data)
  13772. #endif
  13773. {
  13774. struct websocket_client_thread_data *cdata =
  13775. (struct websocket_client_thread_data *)data;
  13776. #if !defined(_WIN32)
  13777. struct sigaction sa;
  13778. /* Ignore SIGPIPE */
  13779. memset(&sa, 0, sizeof(sa));
  13780. sa.sa_handler = SIG_IGN;
  13781. sigaction(SIGPIPE, &sa, NULL);
  13782. #endif
  13783. mg_set_thread_name("ws-clnt");
  13784. if (cdata->conn->phys_ctx) {
  13785. if (cdata->conn->phys_ctx->callbacks.init_thread) {
  13786. /* 3 indicates a websocket client thread */
  13787. /* TODO: check if conn->phys_ctx can be set */
  13788. cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx,
  13789. 3);
  13790. }
  13791. }
  13792. read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data);
  13793. DEBUG_TRACE("%s", "Websocket client thread exited\n");
  13794. if (cdata->close_handler != NULL) {
  13795. cdata->close_handler(cdata->conn, cdata->callback_data);
  13796. }
  13797. /* The websocket_client context has only this thread. If it runs out,
  13798. set the stop_flag to 2 (= "stopped"). */
  13799. cdata->conn->phys_ctx->stop_flag = 2;
  13800. mg_free((void *)cdata);
  13801. #ifdef _WIN32
  13802. return 0;
  13803. #else
  13804. return NULL;
  13805. #endif
  13806. }
  13807. #endif
  13808. struct mg_connection *
  13809. mg_connect_websocket_client(const char *host,
  13810. int port,
  13811. int use_ssl,
  13812. char *error_buffer,
  13813. size_t error_buffer_size,
  13814. const char *path,
  13815. const char *origin,
  13816. mg_websocket_data_handler data_func,
  13817. mg_websocket_close_handler close_func,
  13818. void *user_data)
  13819. {
  13820. struct mg_connection *conn = NULL;
  13821. #if defined(USE_WEBSOCKET)
  13822. struct mg_context *newctx = NULL;
  13823. struct websocket_client_thread_data *thread_data;
  13824. static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw==";
  13825. static const char *handshake_req;
  13826. if (origin != NULL) {
  13827. handshake_req = "GET %s HTTP/1.1\r\n"
  13828. "Host: %s\r\n"
  13829. "Upgrade: websocket\r\n"
  13830. "Connection: Upgrade\r\n"
  13831. "Sec-WebSocket-Key: %s\r\n"
  13832. "Sec-WebSocket-Version: 13\r\n"
  13833. "Origin: %s\r\n"
  13834. "\r\n";
  13835. } else {
  13836. handshake_req = "GET %s HTTP/1.1\r\n"
  13837. "Host: %s\r\n"
  13838. "Upgrade: websocket\r\n"
  13839. "Connection: Upgrade\r\n"
  13840. "Sec-WebSocket-Key: %s\r\n"
  13841. "Sec-WebSocket-Version: 13\r\n"
  13842. "\r\n";
  13843. }
  13844. /* Establish the client connection and request upgrade */
  13845. conn = mg_download(host,
  13846. port,
  13847. use_ssl,
  13848. error_buffer,
  13849. error_buffer_size,
  13850. handshake_req,
  13851. path,
  13852. host,
  13853. magic,
  13854. origin);
  13855. /* Connection object will be null if something goes wrong */
  13856. if (conn == NULL) {
  13857. if (!*error_buffer) {
  13858. /* There should be already an error message */
  13859. mg_snprintf(conn,
  13860. NULL, /* No truncation check for ebuf */
  13861. error_buffer,
  13862. error_buffer_size,
  13863. "Unexpected error");
  13864. }
  13865. return NULL;
  13866. }
  13867. if (conn->response_info.status_code != 101) {
  13868. /* We sent an "upgrade" request. For a correct websocket
  13869. * protocol handshake, we expect a "101 Continue" response.
  13870. * Otherwise it is a protocol violation. Maybe the HTTP
  13871. * Server does not know websockets. */
  13872. if (!*error_buffer) {
  13873. /* set an error, if not yet set */
  13874. mg_snprintf(conn,
  13875. NULL, /* No truncation check for ebuf */
  13876. error_buffer,
  13877. error_buffer_size,
  13878. "Unexpected server reply");
  13879. }
  13880. DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer);
  13881. mg_free(conn);
  13882. return NULL;
  13883. }
  13884. /* For client connections, mg_context is fake. Since we need to set a
  13885. * callback function, we need to create a copy and modify it. */
  13886. newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context));
  13887. memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context));
  13888. newctx->user_data = user_data;
  13889. newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */
  13890. newctx->cfg_worker_threads = 1; /* one worker thread will be created */
  13891. newctx->worker_threadids =
  13892. (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads,
  13893. sizeof(pthread_t),
  13894. newctx);
  13895. conn->phys_ctx = newctx;
  13896. conn->dom_ctx = &(newctx->dd);
  13897. thread_data = (struct websocket_client_thread_data *)
  13898. mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx);
  13899. thread_data->conn = conn;
  13900. thread_data->data_handler = data_func;
  13901. thread_data->close_handler = close_func;
  13902. thread_data->callback_data = user_data;
  13903. /* Start a thread to read the websocket client connection
  13904. * This thread will automatically stop when mg_disconnect is
  13905. * called on the client connection */
  13906. if (mg_start_thread_with_id(websocket_client_thread,
  13907. (void *)thread_data,
  13908. newctx->worker_threadids) != 0) {
  13909. mg_free((void *)thread_data);
  13910. mg_free((void *)newctx->worker_threadids);
  13911. mg_free((void *)newctx);
  13912. mg_free((void *)conn);
  13913. conn = NULL;
  13914. DEBUG_TRACE("%s",
  13915. "Websocket client connect thread could not be started\r\n");
  13916. }
  13917. #else
  13918. /* Appease "unused parameter" warnings */
  13919. (void)host;
  13920. (void)port;
  13921. (void)use_ssl;
  13922. (void)error_buffer;
  13923. (void)error_buffer_size;
  13924. (void)path;
  13925. (void)origin;
  13926. (void)user_data;
  13927. (void)data_func;
  13928. (void)close_func;
  13929. #endif
  13930. return conn;
  13931. }
  13932. /* Prepare connection data structure */
  13933. static void
  13934. init_connection(struct mg_connection *conn)
  13935. {
  13936. /* Is keep alive allowed by the server */
  13937. int keep_alive_enabled =
  13938. !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes");
  13939. if (!keep_alive_enabled) {
  13940. conn->must_close = 1;
  13941. }
  13942. /* Important: on new connection, reset the receiving buffer. Credit
  13943. * goes to crule42. */
  13944. conn->data_len = 0;
  13945. conn->handled_requests = 0;
  13946. mg_set_user_connection_data(conn, NULL);
  13947. #if defined(USE_SERVER_STATS)
  13948. conn->conn_state = 2; /* init */
  13949. #endif
  13950. /* call the init_connection callback if assigned */
  13951. if (conn->phys_ctx->callbacks.init_connection != NULL) {
  13952. if (conn->phys_ctx->context_type == CONTEXT_SERVER) {
  13953. void *conn_data = NULL;
  13954. conn->phys_ctx->callbacks.init_connection(conn, &conn_data);
  13955. mg_set_user_connection_data(conn, conn_data);
  13956. }
  13957. }
  13958. }
  13959. /* Process a connection - may handle multiple requests
  13960. * using the same connection.
  13961. * Must be called with a valid connection (conn and
  13962. * conn->phys_ctx must be valid).
  13963. */
  13964. static void
  13965. process_new_connection(struct mg_connection *conn)
  13966. {
  13967. struct mg_request_info *ri = &conn->request_info;
  13968. int keep_alive, discard_len;
  13969. char ebuf[100];
  13970. const char *hostend;
  13971. int reqerr, uri_type;
  13972. #if defined(USE_SERVER_STATS)
  13973. int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections));
  13974. mg_atomic_add(&(conn->phys_ctx->total_connections), 1);
  13975. if (mcon > (conn->phys_ctx->max_connections)) {
  13976. /* could use atomic compare exchange, but this
  13977. * seems overkill for statistics data */
  13978. conn->phys_ctx->max_connections = mcon;
  13979. }
  13980. #endif
  13981. init_connection(conn);
  13982. DEBUG_TRACE("Start processing connection from %s",
  13983. conn->request_info.remote_addr);
  13984. /* Loop over multiple requests sent using the same connection
  13985. * (while "keep alive"). */
  13986. do {
  13987. DEBUG_TRACE("calling get_request (%i times for this connection)",
  13988. conn->handled_requests + 1);
  13989. #if defined(USE_SERVER_STATS)
  13990. conn->conn_state = 3; /* ready */
  13991. #endif
  13992. if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) {
  13993. /* The request sent by the client could not be understood by
  13994. * the server, or it was incomplete or a timeout. Send an
  13995. * error message and close the connection. */
  13996. if (reqerr > 0) {
  13997. DEBUG_ASSERT(ebuf[0] != '\0');
  13998. mg_send_http_error(conn, reqerr, "%s", ebuf);
  13999. }
  14000. } else if (strcmp(ri->http_version, "1.0")
  14001. && strcmp(ri->http_version, "1.1")) {
  14002. mg_snprintf(conn,
  14003. NULL, /* No truncation check for ebuf */
  14004. ebuf,
  14005. sizeof(ebuf),
  14006. "Bad HTTP version: [%s]",
  14007. ri->http_version);
  14008. mg_send_http_error(conn, 505, "%s", ebuf);
  14009. }
  14010. if (ebuf[0] == '\0') {
  14011. uri_type = get_uri_type(conn->request_info.request_uri);
  14012. switch (uri_type) {
  14013. case 1:
  14014. /* Asterisk */
  14015. conn->request_info.local_uri = NULL;
  14016. break;
  14017. case 2:
  14018. /* relative uri */
  14019. conn->request_info.local_uri = conn->request_info.request_uri;
  14020. break;
  14021. case 3:
  14022. case 4:
  14023. /* absolute uri (with/without port) */
  14024. hostend = get_rel_url_at_current_server(
  14025. conn->request_info.request_uri, conn);
  14026. if (hostend) {
  14027. conn->request_info.local_uri = hostend;
  14028. } else {
  14029. conn->request_info.local_uri = NULL;
  14030. }
  14031. break;
  14032. default:
  14033. mg_snprintf(conn,
  14034. NULL, /* No truncation check for ebuf */
  14035. ebuf,
  14036. sizeof(ebuf),
  14037. "Invalid URI");
  14038. mg_send_http_error(conn, 400, "%s", ebuf);
  14039. conn->request_info.local_uri = NULL;
  14040. break;
  14041. }
  14042. #if defined(MG_LEGACY_INTERFACE)
  14043. /* Legacy before split into local_uri and request_uri */
  14044. conn->request_info.uri = conn->request_info.local_uri;
  14045. #endif
  14046. }
  14047. DEBUG_TRACE("http: %s, error: %s",
  14048. (ri->http_version ? ri->http_version : "none"),
  14049. (ebuf[0] ? ebuf : "none"));
  14050. if (ebuf[0] == '\0') {
  14051. if (conn->request_info.local_uri) {
  14052. /* handle request to local server */
  14053. #if defined(USE_SERVER_STATS)
  14054. conn->conn_state = 4; /* processing */
  14055. #endif
  14056. handle_request(conn);
  14057. #if defined(USE_SERVER_STATS)
  14058. conn->conn_state = 5; /* processed */
  14059. mg_atomic_add(&(conn->phys_ctx->total_data_read),
  14060. conn->consumed_content);
  14061. mg_atomic_add(&(conn->phys_ctx->total_data_written),
  14062. conn->num_bytes_sent);
  14063. #endif
  14064. DEBUG_TRACE("%s", "handle_request done");
  14065. if (conn->phys_ctx->callbacks.end_request != NULL) {
  14066. conn->phys_ctx->callbacks.end_request(conn,
  14067. conn->status_code);
  14068. DEBUG_TRACE("%s", "end_request callback done");
  14069. }
  14070. log_access(conn);
  14071. } else {
  14072. /* TODO: handle non-local request (PROXY) */
  14073. conn->must_close = 1;
  14074. }
  14075. } else {
  14076. conn->must_close = 1;
  14077. }
  14078. if (ri->remote_user != NULL) {
  14079. mg_free((void *)ri->remote_user);
  14080. /* Important! When having connections with and without auth
  14081. * would cause double free and then crash */
  14082. ri->remote_user = NULL;
  14083. }
  14084. /* NOTE(lsm): order is important here. should_keep_alive() call
  14085. * is using parsed request, which will be invalid after
  14086. * memmove's below.
  14087. * Therefore, memorize should_keep_alive() result now for later
  14088. * use in loop exit condition. */
  14089. keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn)
  14090. && (conn->content_len >= 0);
  14091. /* Discard all buffered data for this request */
  14092. discard_len = ((conn->content_len >= 0) && (conn->request_len > 0)
  14093. && ((conn->request_len + conn->content_len)
  14094. < (int64_t)conn->data_len))
  14095. ? (int)(conn->request_len + conn->content_len)
  14096. : conn->data_len;
  14097. DEBUG_ASSERT(discard_len >= 0);
  14098. if (discard_len < 0) {
  14099. DEBUG_TRACE("internal error: discard_len = %li",
  14100. (long int)discard_len);
  14101. break;
  14102. }
  14103. conn->data_len -= discard_len;
  14104. if (conn->data_len > 0) {
  14105. DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len);
  14106. memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len);
  14107. }
  14108. DEBUG_ASSERT(conn->data_len >= 0);
  14109. DEBUG_ASSERT(conn->data_len <= conn->buf_size);
  14110. if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) {
  14111. DEBUG_TRACE("internal error: data_len = %li, buf_size = %li",
  14112. (long int)conn->data_len,
  14113. (long int)conn->buf_size);
  14114. break;
  14115. }
  14116. conn->handled_requests++;
  14117. } while (keep_alive);
  14118. DEBUG_TRACE("Done processing connection from %s (%f sec)",
  14119. conn->request_info.remote_addr,
  14120. difftime(time(NULL), conn->conn_birth_time));
  14121. close_connection(conn);
  14122. #if defined(USE_SERVER_STATS)
  14123. mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests);
  14124. mg_atomic_dec(&(conn->phys_ctx->active_connections));
  14125. #endif
  14126. }
  14127. #if defined(ALTERNATIVE_QUEUE)
  14128. static void
  14129. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14130. {
  14131. unsigned int i;
  14132. for (;;) {
  14133. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14134. /* find a free worker slot and signal it */
  14135. if (ctx->client_socks[i].in_use == 0) {
  14136. ctx->client_socks[i] = *sp;
  14137. ctx->client_socks[i].in_use = 1;
  14138. event_signal(ctx->client_wait_events[i]);
  14139. return;
  14140. }
  14141. }
  14142. /* queue is full */
  14143. mg_sleep(1);
  14144. }
  14145. }
  14146. static int
  14147. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14148. {
  14149. DEBUG_TRACE("%s", "going idle");
  14150. ctx->client_socks[thread_index].in_use = 0;
  14151. event_wait(ctx->client_wait_events[thread_index]);
  14152. *sp = ctx->client_socks[thread_index];
  14153. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14154. return !ctx->stop_flag;
  14155. }
  14156. #else /* ALTERNATIVE_QUEUE */
  14157. /* Worker threads take accepted socket from the queue */
  14158. static int
  14159. consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index)
  14160. {
  14161. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14162. (void)thread_index;
  14163. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14164. DEBUG_TRACE("%s", "going idle");
  14165. /* If the queue is empty, wait. We're idle at this point. */
  14166. while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) {
  14167. pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex);
  14168. }
  14169. /* If we're stopping, sq_head may be equal to sq_tail. */
  14170. if (ctx->sq_head > ctx->sq_tail) {
  14171. /* Copy socket from the queue and increment tail */
  14172. *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)];
  14173. ctx->sq_tail++;
  14174. DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1);
  14175. /* Wrap pointers if needed */
  14176. while (ctx->sq_tail > QUEUE_SIZE(ctx)) {
  14177. ctx->sq_tail -= QUEUE_SIZE(ctx);
  14178. ctx->sq_head -= QUEUE_SIZE(ctx);
  14179. }
  14180. }
  14181. (void)pthread_cond_signal(&ctx->sq_empty);
  14182. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14183. return !ctx->stop_flag;
  14184. #undef QUEUE_SIZE
  14185. }
  14186. /* Master thread adds accepted socket to a queue */
  14187. static void
  14188. produce_socket(struct mg_context *ctx, const struct socket *sp)
  14189. {
  14190. #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue)))
  14191. if (!ctx) {
  14192. return;
  14193. }
  14194. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14195. /* If the queue is full, wait */
  14196. while ((ctx->stop_flag == 0)
  14197. && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) {
  14198. (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex);
  14199. }
  14200. if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) {
  14201. /* Copy socket to the queue and increment head */
  14202. ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp;
  14203. ctx->sq_head++;
  14204. DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1);
  14205. }
  14206. (void)pthread_cond_signal(&ctx->sq_full);
  14207. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14208. #undef QUEUE_SIZE
  14209. }
  14210. #endif /* ALTERNATIVE_QUEUE */
  14211. struct worker_thread_args {
  14212. struct mg_context *ctx;
  14213. int index;
  14214. };
  14215. static void *
  14216. worker_thread_run(struct worker_thread_args *thread_args)
  14217. {
  14218. struct mg_context *ctx = thread_args->ctx;
  14219. struct mg_connection *conn;
  14220. struct mg_workerTLS tls;
  14221. #if defined(MG_LEGACY_INTERFACE)
  14222. uint32_t addr;
  14223. #endif
  14224. mg_set_thread_name("worker");
  14225. tls.is_master = 0;
  14226. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14227. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14228. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14229. #endif
  14230. /* Initialize thread local storage before calling any callback */
  14231. pthread_setspecific(sTlsKey, &tls);
  14232. if (ctx->callbacks.init_thread) {
  14233. /* call init_thread for a worker thread (type 1) */
  14234. ctx->callbacks.init_thread(ctx, 1);
  14235. }
  14236. /* Connection structure has been pre-allocated */
  14237. if (((int)thread_args->index < 0)
  14238. || ((unsigned)thread_args->index
  14239. >= (unsigned)ctx->cfg_worker_threads)) {
  14240. mg_cry(fc(ctx),
  14241. "Internal error: Invalid worker index %i",
  14242. (int)thread_args->index);
  14243. return NULL;
  14244. }
  14245. conn = ctx->worker_connections + thread_args->index;
  14246. /* Request buffers are not pre-allocated. They are private to the
  14247. * request and do not contain any state information that might be
  14248. * of interest to anyone observing a server status. */
  14249. conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx);
  14250. if (conn->buf == NULL) {
  14251. mg_cry(fc(ctx),
  14252. "Out of memory: Cannot allocate buffer for worker %i",
  14253. (int)thread_args->index);
  14254. return NULL;
  14255. }
  14256. conn->buf_size = (int)ctx->max_request_size;
  14257. conn->phys_ctx = ctx;
  14258. conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */
  14259. conn->host = NULL; /* until we have more information. */
  14260. conn->thread_index = thread_args->index;
  14261. conn->request_info.user_data = ctx->user_data;
  14262. /* Allocate a mutex for this connection to allow communication both
  14263. * within the request handler and from elsewhere in the application
  14264. */
  14265. (void)pthread_mutex_init(&conn->mutex, &pthread_mutex_attr);
  14266. #if defined(USE_SERVER_STATS)
  14267. conn->conn_state = 1; /* not consumed */
  14268. #endif
  14269. /* Call consume_socket() even when ctx->stop_flag > 0, to let it
  14270. * signal sq_empty condvar to wake up the master waiting in
  14271. * produce_socket() */
  14272. while (consume_socket(ctx, &conn->client, conn->thread_index)) {
  14273. conn->conn_birth_time = time(NULL);
  14274. /* Fill in IP, port info early so even if SSL setup below fails,
  14275. * error handler would have the corresponding info.
  14276. * Thanks to Johannes Winkelmann for the patch.
  14277. */
  14278. #if defined(USE_IPV6)
  14279. if (conn->client.rsa.sa.sa_family == AF_INET6) {
  14280. conn->request_info.remote_port =
  14281. ntohs(conn->client.rsa.sin6.sin6_port);
  14282. } else
  14283. #endif
  14284. {
  14285. conn->request_info.remote_port =
  14286. ntohs(conn->client.rsa.sin.sin_port);
  14287. }
  14288. sockaddr_to_string(conn->request_info.remote_addr,
  14289. sizeof(conn->request_info.remote_addr),
  14290. &conn->client.rsa);
  14291. DEBUG_TRACE("Start processing connection from %s",
  14292. conn->request_info.remote_addr);
  14293. conn->request_info.is_ssl = conn->client.is_ssl;
  14294. if (conn->client.is_ssl) {
  14295. #ifndef NO_SSL
  14296. /* HTTPS connection */
  14297. if (sslize(conn,
  14298. conn->dom_ctx->ssl_ctx,
  14299. SSL_accept,
  14300. &(conn->phys_ctx->stop_flag))) {
  14301. /* XXX TODO: Set conn->dom_ctx */
  14302. /* Get SSL client certificate information (if set) */
  14303. ssl_get_client_cert_info(conn);
  14304. /* process HTTPS connection */
  14305. process_new_connection(conn);
  14306. /* Free client certificate info */
  14307. if (conn->request_info.client_cert) {
  14308. mg_free((void *)(conn->request_info.client_cert->subject));
  14309. mg_free((void *)(conn->request_info.client_cert->issuer));
  14310. mg_free((void *)(conn->request_info.client_cert->serial));
  14311. mg_free((void *)(conn->request_info.client_cert->finger));
  14312. /* Free certificate memory */
  14313. X509_free(
  14314. (X509 *)conn->request_info.client_cert->peer_cert);
  14315. conn->request_info.client_cert->peer_cert = 0;
  14316. conn->request_info.client_cert->subject = 0;
  14317. conn->request_info.client_cert->issuer = 0;
  14318. conn->request_info.client_cert->serial = 0;
  14319. conn->request_info.client_cert->finger = 0;
  14320. mg_free(conn->request_info.client_cert);
  14321. conn->request_info.client_cert = 0;
  14322. }
  14323. }
  14324. #endif
  14325. } else {
  14326. /* process HTTP connection */
  14327. process_new_connection(conn);
  14328. }
  14329. DEBUG_TRACE("%s", "Connection closed");
  14330. }
  14331. pthread_setspecific(sTlsKey, NULL);
  14332. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14333. CloseHandle(tls.pthread_cond_helper_mutex);
  14334. #endif
  14335. pthread_mutex_destroy(&conn->mutex);
  14336. /* Free the request buffer. */
  14337. conn->buf_size = 0;
  14338. mg_free(conn->buf);
  14339. conn->buf = NULL;
  14340. #if defined(USE_SERVER_STATS)
  14341. conn->conn_state = 9; /* done */
  14342. #endif
  14343. DEBUG_TRACE("%s", "exiting");
  14344. return NULL;
  14345. }
  14346. /* Threads have different return types on Windows and Unix. */
  14347. #ifdef _WIN32
  14348. static unsigned __stdcall worker_thread(void *thread_func_param)
  14349. {
  14350. struct worker_thread_args *pwta =
  14351. (struct worker_thread_args *)thread_func_param;
  14352. worker_thread_run(pwta);
  14353. mg_free(thread_func_param);
  14354. return 0;
  14355. }
  14356. #else
  14357. static void *
  14358. worker_thread(void *thread_func_param)
  14359. {
  14360. struct worker_thread_args *pwta =
  14361. (struct worker_thread_args *)thread_func_param;
  14362. struct sigaction sa;
  14363. /* Ignore SIGPIPE */
  14364. memset(&sa, 0, sizeof(sa));
  14365. sa.sa_handler = SIG_IGN;
  14366. sigaction(SIGPIPE, &sa, NULL);
  14367. worker_thread_run(pwta);
  14368. mg_free(thread_func_param);
  14369. return NULL;
  14370. }
  14371. #endif /* _WIN32 */
  14372. static void
  14373. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  14374. {
  14375. struct socket so;
  14376. char src_addr[IP_ADDR_STR_LEN];
  14377. socklen_t len = sizeof(so.rsa);
  14378. int on = 1;
  14379. if (!listener) {
  14380. return;
  14381. }
  14382. if ((so.sock = accept(listener->sock, &so.rsa.sa, &len))
  14383. == INVALID_SOCKET) {
  14384. } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) {
  14385. sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa);
  14386. mg_cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  14387. closesocket(so.sock);
  14388. } else {
  14389. /* Put so socket structure into the queue */
  14390. DEBUG_TRACE("Accepted socket %d", (int)so.sock);
  14391. set_close_on_exec(so.sock, fc(ctx));
  14392. so.is_ssl = listener->is_ssl;
  14393. so.ssl_redir = listener->ssl_redir;
  14394. if (getsockname(so.sock, &so.lsa.sa, &len) != 0) {
  14395. mg_cry(fc(ctx),
  14396. "%s: getsockname() failed: %s",
  14397. __func__,
  14398. strerror(ERRNO));
  14399. }
  14400. /* Set TCP keep-alive. This is needed because if HTTP-level
  14401. * keep-alive
  14402. * is enabled, and client resets the connection, server won't get
  14403. * TCP FIN or RST and will keep the connection open forever. With
  14404. * TCP keep-alive, next keep-alive handshake will figure out that
  14405. * the client is down and will close the server end.
  14406. * Thanks to Igor Klopov who suggested the patch. */
  14407. if (setsockopt(so.sock,
  14408. SOL_SOCKET,
  14409. SO_KEEPALIVE,
  14410. (SOCK_OPT_TYPE)&on,
  14411. sizeof(on)) != 0) {
  14412. mg_cry(fc(ctx),
  14413. "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s",
  14414. __func__,
  14415. strerror(ERRNO));
  14416. }
  14417. /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced
  14418. * to effectively fill up the underlying IP packet payload and
  14419. * reduce the overhead of sending lots of small buffers. However
  14420. * this hurts the server's throughput (ie. operations per second)
  14421. * when HTTP 1.1 persistent connections are used and the responses
  14422. * are relatively small (eg. less than 1400 bytes).
  14423. */
  14424. if ((ctx != NULL) && (ctx->dd.config[CONFIG_TCP_NODELAY] != NULL)
  14425. && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) {
  14426. if (set_tcp_nodelay(so.sock, 1) != 0) {
  14427. mg_cry(fc(ctx),
  14428. "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s",
  14429. __func__,
  14430. strerror(ERRNO));
  14431. }
  14432. }
  14433. /* We are using non-blocking sockets. Thus, the
  14434. * set_sock_timeout(so.sock, timeout);
  14435. * call is no longer required. */
  14436. /* The "non blocking" property should already be
  14437. * inherited from the parent socket. Set it for
  14438. * non-compliant socket implementations. */
  14439. set_non_blocking_mode(so.sock);
  14440. so.in_use = 0;
  14441. produce_socket(ctx, &so);
  14442. }
  14443. }
  14444. static void
  14445. master_thread_run(void *thread_func_param)
  14446. {
  14447. struct mg_context *ctx = (struct mg_context *)thread_func_param;
  14448. struct mg_workerTLS tls;
  14449. struct pollfd *pfd;
  14450. unsigned int i;
  14451. unsigned int workerthreadcount;
  14452. if (!ctx) {
  14453. return;
  14454. }
  14455. mg_set_thread_name("master");
  14456. /* Increase priority of the master thread */
  14457. #if defined(_WIN32)
  14458. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  14459. #elif defined(USE_MASTER_THREAD_PRIORITY)
  14460. int min_prio = sched_get_priority_min(SCHED_RR);
  14461. int max_prio = sched_get_priority_max(SCHED_RR);
  14462. if ((min_prio >= 0) && (max_prio >= 0)
  14463. && ((USE_MASTER_THREAD_PRIORITY) <= max_prio)
  14464. && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) {
  14465. struct sched_param sched_param = {0};
  14466. sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY);
  14467. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  14468. }
  14469. #endif
  14470. /* Initialize thread local storage */
  14471. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14472. tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL);
  14473. #endif
  14474. tls.is_master = 1;
  14475. pthread_setspecific(sTlsKey, &tls);
  14476. if (ctx->callbacks.init_thread) {
  14477. /* Callback for the master thread (type 0) */
  14478. ctx->callbacks.init_thread(ctx, 0);
  14479. }
  14480. /* Server starts *now* */
  14481. ctx->start_time = time(NULL);
  14482. /* Start the server */
  14483. pfd = ctx->listening_socket_fds;
  14484. while (ctx->stop_flag == 0) {
  14485. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14486. pfd[i].fd = ctx->listening_sockets[i].sock;
  14487. pfd[i].events = POLLIN;
  14488. }
  14489. if (poll(pfd, ctx->num_listening_sockets, 200) > 0) {
  14490. for (i = 0; i < ctx->num_listening_sockets; i++) {
  14491. /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the
  14492. * successful poll, and POLLIN is defined as
  14493. * (POLLRDNORM | POLLRDBAND)
  14494. * Therefore, we're checking pfd[i].revents & POLLIN, not
  14495. * pfd[i].revents == POLLIN. */
  14496. if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) {
  14497. accept_new_connection(&ctx->listening_sockets[i], ctx);
  14498. }
  14499. }
  14500. }
  14501. }
  14502. /* Here stop_flag is 1 - Initiate shutdown. */
  14503. DEBUG_TRACE("%s", "stopping workers");
  14504. /* Stop signal received: somebody called mg_stop. Quit. */
  14505. close_all_listening_sockets(ctx);
  14506. /* Wakeup workers that are waiting for connections to handle. */
  14507. (void)pthread_mutex_lock(&ctx->thread_mutex);
  14508. #if defined(ALTERNATIVE_QUEUE)
  14509. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14510. event_signal(ctx->client_wait_events[i]);
  14511. /* Since we know all sockets, we can shutdown the connections. */
  14512. if (ctx->client_socks[i].in_use) {
  14513. shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH);
  14514. }
  14515. }
  14516. #else
  14517. pthread_cond_broadcast(&ctx->sq_full);
  14518. #endif
  14519. (void)pthread_mutex_unlock(&ctx->thread_mutex);
  14520. /* Join all worker threads to avoid leaking threads. */
  14521. workerthreadcount = ctx->cfg_worker_threads;
  14522. for (i = 0; i < workerthreadcount; i++) {
  14523. if (ctx->worker_threadids[i] != 0) {
  14524. mg_join_thread(ctx->worker_threadids[i]);
  14525. }
  14526. }
  14527. #if defined(USE_LUA)
  14528. /* Free Lua state of lua background task */
  14529. if (ctx->lua_background_state) {
  14530. lua_State *lstate = (lua_State *)ctx->lua_background_state;
  14531. lua_getglobal(lstate, LUABACKGROUNDPARAMS);
  14532. if (lua_istable(lstate, -1)) {
  14533. reg_boolean(lstate, "shutdown", 1);
  14534. lua_pop(lstate, 1);
  14535. mg_sleep(2);
  14536. }
  14537. lua_close(lstate);
  14538. ctx->lua_background_state = 0;
  14539. }
  14540. #endif
  14541. DEBUG_TRACE("%s", "exiting");
  14542. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14543. CloseHandle(tls.pthread_cond_helper_mutex);
  14544. #endif
  14545. pthread_setspecific(sTlsKey, NULL);
  14546. /* Signal mg_stop() that we're done.
  14547. * WARNING: This must be the very last thing this
  14548. * thread does, as ctx becomes invalid after this line. */
  14549. ctx->stop_flag = 2;
  14550. }
  14551. /* Threads have different return types on Windows and Unix. */
  14552. #ifdef _WIN32
  14553. static unsigned __stdcall master_thread(void *thread_func_param)
  14554. {
  14555. master_thread_run(thread_func_param);
  14556. return 0;
  14557. }
  14558. #else
  14559. static void *
  14560. master_thread(void *thread_func_param)
  14561. {
  14562. struct sigaction sa;
  14563. /* Ignore SIGPIPE */
  14564. memset(&sa, 0, sizeof(sa));
  14565. sa.sa_handler = SIG_IGN;
  14566. sigaction(SIGPIPE, &sa, NULL);
  14567. master_thread_run(thread_func_param);
  14568. return NULL;
  14569. }
  14570. #endif /* _WIN32 */
  14571. static void
  14572. free_context(struct mg_context *ctx)
  14573. {
  14574. int i;
  14575. struct mg_handler_info *tmp_rh;
  14576. if (ctx == NULL) {
  14577. return;
  14578. }
  14579. if (ctx->callbacks.exit_context) {
  14580. ctx->callbacks.exit_context(ctx);
  14581. }
  14582. /* All threads exited, no sync is needed. Destroy thread mutex and
  14583. * condvars
  14584. */
  14585. (void)pthread_mutex_destroy(&ctx->thread_mutex);
  14586. #if defined(ALTERNATIVE_QUEUE)
  14587. mg_free(ctx->client_socks);
  14588. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14589. event_destroy(ctx->client_wait_events[i]);
  14590. }
  14591. mg_free(ctx->client_wait_events);
  14592. #else
  14593. (void)pthread_cond_destroy(&ctx->sq_empty);
  14594. (void)pthread_cond_destroy(&ctx->sq_full);
  14595. #endif
  14596. /* Destroy other context global data structures mutex */
  14597. (void)pthread_mutex_destroy(&ctx->nonce_mutex);
  14598. #if defined(USE_TIMERS)
  14599. timers_exit(ctx);
  14600. #endif
  14601. /* Deallocate config parameters */
  14602. for (i = 0; i < NUM_OPTIONS; i++) {
  14603. if (ctx->dd.config[i] != NULL) {
  14604. #if defined(_MSC_VER)
  14605. #pragma warning(suppress : 6001)
  14606. #endif
  14607. mg_free(ctx->dd.config[i]);
  14608. }
  14609. }
  14610. /* Deallocate request handlers */
  14611. while (ctx->dd.handlers) {
  14612. tmp_rh = ctx->dd.handlers;
  14613. ctx->dd.handlers = tmp_rh->next;
  14614. mg_free(tmp_rh->uri);
  14615. mg_free(tmp_rh);
  14616. }
  14617. #ifndef NO_SSL
  14618. /* Deallocate SSL context */
  14619. if (ctx->dd.ssl_ctx != NULL) {
  14620. void *ssl_ctx = (void *)ctx->dd.ssl_ctx;
  14621. int callback_ret =
  14622. (ctx->callbacks.external_ssl_ctx == NULL)
  14623. ? 0
  14624. : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data));
  14625. if (callback_ret == 0) {
  14626. SSL_CTX_free(ctx->dd.ssl_ctx);
  14627. }
  14628. // else ignore error and ommit SSL_CTX_free in case callback_ret is 1
  14629. }
  14630. #endif /* !NO_SSL */
  14631. /* Deallocate worker thread ID array */
  14632. if (ctx->worker_threadids != NULL) {
  14633. mg_free(ctx->worker_threadids);
  14634. }
  14635. /* Deallocate worker thread ID array */
  14636. if (ctx->worker_connections != NULL) {
  14637. mg_free(ctx->worker_connections);
  14638. }
  14639. /* deallocate system name string */
  14640. mg_free(ctx->systemName);
  14641. /* Deallocate context itself */
  14642. mg_free(ctx);
  14643. }
  14644. void
  14645. mg_stop(struct mg_context *ctx)
  14646. {
  14647. pthread_t mt;
  14648. if (!ctx) {
  14649. return;
  14650. }
  14651. /* We don't use a lock here. Calling mg_stop with the same ctx from
  14652. * two threads is not allowed. */
  14653. mt = ctx->masterthreadid;
  14654. if (mt == 0) {
  14655. return;
  14656. }
  14657. ctx->masterthreadid = 0;
  14658. /* Set stop flag, so all threads know they have to exit. */
  14659. ctx->stop_flag = 1;
  14660. /* Wait until everything has stopped. */
  14661. while (ctx->stop_flag != 2) {
  14662. (void)mg_sleep(10);
  14663. }
  14664. mg_join_thread(mt);
  14665. free_context(ctx);
  14666. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14667. (void)WSACleanup();
  14668. #endif /* _WIN32 && !__SYMBIAN32__ */
  14669. }
  14670. static void
  14671. get_system_name(char **sysName)
  14672. {
  14673. #if defined(_WIN32)
  14674. #if !defined(__SYMBIAN32__)
  14675. #if defined(_WIN32_WCE)
  14676. *sysName = mg_strdup("WinCE");
  14677. #else
  14678. char name[128];
  14679. DWORD dwVersion = 0;
  14680. DWORD dwMajorVersion = 0;
  14681. DWORD dwMinorVersion = 0;
  14682. DWORD dwBuild = 0;
  14683. BOOL wowRet, isWoW = FALSE;
  14684. #ifdef _MSC_VER
  14685. #pragma warning(push)
  14686. /* GetVersion was declared deprecated */
  14687. #pragma warning(disable : 4996)
  14688. #endif
  14689. dwVersion = GetVersion();
  14690. #ifdef _MSC_VER
  14691. #pragma warning(pop)
  14692. #endif
  14693. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  14694. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  14695. dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0);
  14696. (void)dwBuild;
  14697. wowRet = IsWow64Process(GetCurrentProcess(), &isWoW);
  14698. sprintf(name,
  14699. "Windows %u.%u%s",
  14700. (unsigned)dwMajorVersion,
  14701. (unsigned)dwMinorVersion,
  14702. (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)"));
  14703. *sysName = mg_strdup(name);
  14704. #endif
  14705. #else
  14706. *sysName = mg_strdup("Symbian");
  14707. #endif
  14708. #else
  14709. struct utsname name;
  14710. memset(&name, 0, sizeof(name));
  14711. uname(&name);
  14712. *sysName = mg_strdup(name.sysname);
  14713. #endif
  14714. }
  14715. struct mg_context *
  14716. mg_start(const struct mg_callbacks *callbacks,
  14717. void *user_data,
  14718. const char **options)
  14719. {
  14720. struct mg_context *ctx;
  14721. const char *name, *value, *default_value;
  14722. int idx, ok, workerthreadcount;
  14723. unsigned int i;
  14724. int itmp;
  14725. void (*exit_callback)(const struct mg_context *ctx) = 0;
  14726. struct mg_workerTLS tls;
  14727. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14728. WSADATA data;
  14729. WSAStartup(MAKEWORD(2, 2), &data);
  14730. #endif /* _WIN32 && !__SYMBIAN32__ */
  14731. /* Allocate context and initialize reasonable general case defaults. */
  14732. if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) {
  14733. return NULL;
  14734. }
  14735. /* Random number generator will initialize at the first call */
  14736. ctx->dd.auth_nonce_mask =
  14737. (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options);
  14738. if (mg_init_library_called == 0) {
  14739. /* Legacy INIT, if mg_start is called without mg_init_library.
  14740. * Note: This may cause a memory leak */
  14741. const char *ports_option =
  14742. config_options[LISTENING_PORTS].default_value;
  14743. if (options) {
  14744. const char **run_options = options;
  14745. const char *optname = config_options[LISTENING_PORTS].name;
  14746. /* Try to find the "listening_ports" option */
  14747. while (*run_options) {
  14748. if (!strcmp(*run_options, optname)) {
  14749. ports_option = run_options[1];
  14750. }
  14751. run_options += 2;
  14752. }
  14753. }
  14754. if (is_ssl_port_used(ports_option)) {
  14755. /* Initialize with SSL support */
  14756. mg_init_library(MG_FEATURES_TLS);
  14757. } else {
  14758. /* Initialize without SSL support */
  14759. mg_init_library(MG_FEATURES_DEFAULT);
  14760. }
  14761. }
  14762. tls.is_master = -1;
  14763. tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max);
  14764. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  14765. tls.pthread_cond_helper_mutex = NULL;
  14766. #endif
  14767. pthread_setspecific(sTlsKey, &tls);
  14768. ok = 0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr);
  14769. #if !defined(ALTERNATIVE_QUEUE)
  14770. ok &= 0 == pthread_cond_init(&ctx->sq_empty, NULL);
  14771. ok &= 0 == pthread_cond_init(&ctx->sq_full, NULL);
  14772. #endif
  14773. ok &= 0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr);
  14774. if (!ok) {
  14775. /* Fatal error - abort start. However, this situation should never
  14776. * occur in practice. */
  14777. mg_cry(fc(ctx), "Cannot initialize thread synchronization objects");
  14778. mg_free(ctx);
  14779. pthread_setspecific(sTlsKey, NULL);
  14780. return NULL;
  14781. }
  14782. if (callbacks) {
  14783. ctx->callbacks = *callbacks;
  14784. exit_callback = callbacks->exit_context;
  14785. ctx->callbacks.exit_context = 0;
  14786. }
  14787. ctx->user_data = user_data;
  14788. ctx->dd.handlers = NULL;
  14789. ctx->dd.next = NULL;
  14790. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  14791. ctx->dd.shared_lua_websockets = NULL;
  14792. #endif
  14793. /* Store options */
  14794. while (options && (name = *options++) != NULL) {
  14795. if ((idx = get_option_index(name)) == -1) {
  14796. mg_cry(fc(ctx), "Invalid option: %s", name);
  14797. free_context(ctx);
  14798. pthread_setspecific(sTlsKey, NULL);
  14799. return NULL;
  14800. } else if ((value = *options++) == NULL) {
  14801. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  14802. free_context(ctx);
  14803. pthread_setspecific(sTlsKey, NULL);
  14804. return NULL;
  14805. }
  14806. if (ctx->dd.config[idx] != NULL) {
  14807. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  14808. mg_free(ctx->dd.config[idx]);
  14809. }
  14810. ctx->dd.config[idx] = mg_strdup_ctx(value, ctx);
  14811. DEBUG_TRACE("[%s] -> [%s]", name, value);
  14812. }
  14813. /* Set default value if needed */
  14814. for (i = 0; config_options[i].name != NULL; i++) {
  14815. default_value = config_options[i].default_value;
  14816. if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) {
  14817. ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx);
  14818. }
  14819. }
  14820. /* Request size option */
  14821. itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]);
  14822. if (itmp < 1024) {
  14823. mg_cry(fc(ctx), "max_request_size too small");
  14824. free_context(ctx);
  14825. pthread_setspecific(sTlsKey, NULL);
  14826. return NULL;
  14827. }
  14828. ctx->max_request_size = (unsigned)itmp;
  14829. /* Worker thread count option */
  14830. workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]);
  14831. if (workerthreadcount > MAX_WORKER_THREADS) {
  14832. mg_cry(fc(ctx), "Too many worker threads");
  14833. free_context(ctx);
  14834. pthread_setspecific(sTlsKey, NULL);
  14835. return NULL;
  14836. }
  14837. if (workerthreadcount <= 0) {
  14838. mg_cry(fc(ctx), "Invalid number of worker threads");
  14839. free_context(ctx);
  14840. pthread_setspecific(sTlsKey, NULL);
  14841. return NULL;
  14842. }
  14843. /* Document root */
  14844. #if defined(NO_FILES)
  14845. if (ctx->dd.config[DOCUMENT_ROOT] != NULL) {
  14846. mg_cry(fc(ctx), "%s", "Document root must not be set");
  14847. free_context(ctx);
  14848. pthread_setspecific(sTlsKey, NULL);
  14849. return NULL;
  14850. }
  14851. #endif
  14852. get_system_name(&ctx->systemName);
  14853. #if defined(USE_LUA)
  14854. /* If a Lua background script has been configured, start it. */
  14855. if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) {
  14856. char ebuf[256];
  14857. struct vec opt_vec;
  14858. struct vec eq_vec;
  14859. const char *sparams;
  14860. lua_State *state = (void *)mg_prepare_lua_context_script(
  14861. ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf));
  14862. if (!state) {
  14863. mg_cry(fc(ctx), "lua_background_script error: %s", ebuf);
  14864. free_context(ctx);
  14865. pthread_setspecific(sTlsKey, NULL);
  14866. return NULL;
  14867. }
  14868. ctx->lua_background_state = (void *)state;
  14869. lua_newtable(state);
  14870. reg_boolean(state, "shutdown", 0);
  14871. sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS];
  14872. while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) {
  14873. reg_llstring(
  14874. state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len);
  14875. if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0)
  14876. break;
  14877. }
  14878. lua_setglobal(state, LUABACKGROUNDPARAMS);
  14879. } else {
  14880. ctx->lua_background_state = 0;
  14881. }
  14882. #endif
  14883. /* NOTE(lsm): order is important here. SSL certificates must
  14884. * be initialized before listening ports. UID must be set last. */
  14885. if (!set_gpass_option(ctx, NULL) ||
  14886. #if !defined(NO_SSL)
  14887. !init_ssl_ctx(ctx, NULL) ||
  14888. #endif
  14889. !set_ports_option(ctx) ||
  14890. #if !defined(_WIN32)
  14891. !set_uid_option(ctx) ||
  14892. #endif
  14893. !set_acl_option(ctx)) {
  14894. free_context(ctx);
  14895. pthread_setspecific(sTlsKey, NULL);
  14896. return NULL;
  14897. }
  14898. ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount));
  14899. ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14900. sizeof(pthread_t),
  14901. ctx);
  14902. if (ctx->worker_threadids == NULL) {
  14903. mg_cry(fc(ctx), "Not enough memory for worker thread ID array");
  14904. free_context(ctx);
  14905. pthread_setspecific(sTlsKey, NULL);
  14906. return NULL;
  14907. }
  14908. ctx->worker_connections =
  14909. (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads,
  14910. sizeof(struct mg_connection),
  14911. ctx);
  14912. if (ctx->worker_connections == NULL) {
  14913. mg_cry(fc(ctx), "Not enough memory for worker thread connection array");
  14914. free_context(ctx);
  14915. pthread_setspecific(sTlsKey, NULL);
  14916. return NULL;
  14917. }
  14918. #if defined(ALTERNATIVE_QUEUE)
  14919. ctx->client_wait_events =
  14920. (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]),
  14921. ctx->cfg_worker_threads,
  14922. ctx);
  14923. if (ctx->client_wait_events == NULL) {
  14924. mg_cry(fc(ctx), "Not enough memory for worker event array");
  14925. mg_free(ctx->worker_threadids);
  14926. free_context(ctx);
  14927. pthread_setspecific(sTlsKey, NULL);
  14928. return NULL;
  14929. }
  14930. ctx->client_socks =
  14931. (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]),
  14932. ctx->cfg_worker_threads,
  14933. ctx);
  14934. if (ctx->client_wait_events == NULL) {
  14935. mg_cry(fc(ctx), "Not enough memory for worker socket array");
  14936. mg_free(ctx->client_socks);
  14937. mg_free(ctx->worker_threadids);
  14938. free_context(ctx);
  14939. pthread_setspecific(sTlsKey, NULL);
  14940. return NULL;
  14941. }
  14942. for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) {
  14943. ctx->client_wait_events[i] = event_create();
  14944. if (ctx->client_wait_events[i] == 0) {
  14945. mg_cry(fc(ctx), "Error creating worker event %i", i);
  14946. while (i > 0) {
  14947. i--;
  14948. event_destroy(ctx->client_wait_events[i]);
  14949. }
  14950. mg_free(ctx->client_socks);
  14951. mg_free(ctx->worker_threadids);
  14952. free_context(ctx);
  14953. pthread_setspecific(sTlsKey, NULL);
  14954. return NULL;
  14955. }
  14956. }
  14957. #endif
  14958. #if defined(USE_TIMERS)
  14959. if (timers_init(ctx) != 0) {
  14960. mg_cry(fc(ctx), "Error creating timers");
  14961. free_context(ctx);
  14962. pthread_setspecific(sTlsKey, NULL);
  14963. return NULL;
  14964. }
  14965. #endif
  14966. /* Context has been created - init user libraries */
  14967. if (ctx->callbacks.init_context) {
  14968. ctx->callbacks.init_context(ctx);
  14969. }
  14970. ctx->callbacks.exit_context = exit_callback;
  14971. ctx->context_type = CONTEXT_SERVER; /* server context */
  14972. /* Start master (listening) thread */
  14973. mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid);
  14974. /* Start worker threads */
  14975. for (i = 0; i < ctx->cfg_worker_threads; i++) {
  14976. struct worker_thread_args *wta = (struct worker_thread_args *)
  14977. mg_malloc_ctx(sizeof(struct worker_thread_args), ctx);
  14978. if (wta) {
  14979. wta->ctx = ctx;
  14980. wta->index = (int)i;
  14981. }
  14982. if ((wta == NULL)
  14983. || (mg_start_thread_with_id(worker_thread,
  14984. wta,
  14985. &ctx->worker_threadids[i]) != 0)) {
  14986. /* thread was not created */
  14987. if (wta != NULL) {
  14988. mg_free(wta);
  14989. }
  14990. if (i > 0) {
  14991. mg_cry(fc(ctx),
  14992. "Cannot start worker thread %i: error %ld",
  14993. i + 1,
  14994. (long)ERRNO);
  14995. } else {
  14996. mg_cry(fc(ctx),
  14997. "Cannot create threads: error %ld",
  14998. (long)ERRNO);
  14999. free_context(ctx);
  15000. pthread_setspecific(sTlsKey, NULL);
  15001. return NULL;
  15002. }
  15003. break;
  15004. }
  15005. }
  15006. pthread_setspecific(sTlsKey, NULL);
  15007. return ctx;
  15008. }
  15009. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15010. /* Add an additional domain to an already running web server. */
  15011. int
  15012. mg_start_domain(struct mg_context *ctx, const char **options)
  15013. {
  15014. const char *name;
  15015. const char *value;
  15016. const char *default_value;
  15017. struct mg_domain_context *new_dom;
  15018. struct mg_domain_context *dom;
  15019. int idx, i;
  15020. if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) {
  15021. return -1;
  15022. }
  15023. new_dom = (struct mg_domain_context *)
  15024. mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx);
  15025. if (!new_dom) {
  15026. /* Out of memory */
  15027. return -6;
  15028. }
  15029. /* Store options - TODO: unite duplicate code */
  15030. while (options && (name = *options++) != NULL) {
  15031. if ((idx = get_option_index(name)) == -1) {
  15032. mg_cry(fc(ctx), "Invalid option: %s", name);
  15033. mg_free(new_dom);
  15034. return -2;
  15035. } else if ((value = *options++) == NULL) {
  15036. mg_cry(fc(ctx), "%s: option value cannot be NULL", name);
  15037. mg_free(new_dom);
  15038. return -2;
  15039. }
  15040. if (new_dom->config[idx] != NULL) {
  15041. mg_cry(fc(ctx), "warning: %s: duplicate option", name);
  15042. mg_free(new_dom->config[idx]);
  15043. }
  15044. new_dom->config[idx] = mg_strdup_ctx(value, ctx);
  15045. DEBUG_TRACE("[%s] -> [%s]", name, value);
  15046. }
  15047. /* Authentication domain is mandatory */
  15048. /* TODO: Maybe use a new option hostname? */
  15049. if (!new_dom->config[AUTHENTICATION_DOMAIN]) {
  15050. return -4;
  15051. }
  15052. /* Set default value if needed. Take the config value from
  15053. * ctx as a default value. */
  15054. for (i = 0; config_options[i].name != NULL; i++) {
  15055. default_value = ctx->dd.config[i];
  15056. if ((new_dom->config[i] == NULL) && (default_value != NULL)) {
  15057. new_dom->config[i] = mg_strdup_ctx(default_value, ctx);
  15058. }
  15059. }
  15060. new_dom->handlers = NULL;
  15061. new_dom->next = NULL;
  15062. new_dom->nonce_count = 0;
  15063. new_dom->auth_nonce_mask =
  15064. (uint64_t)get_random() ^ ((uint64_t)get_random() << 31);
  15065. #if defined(USE_LUA) && defined(USE_WEBSOCKET)
  15066. new_dom->shared_lua_websockets = NULL;
  15067. #endif
  15068. if (!init_ssl_ctx(ctx, new_dom)) {
  15069. /* Init SSL failed */
  15070. mg_free(new_dom);
  15071. return -3;
  15072. }
  15073. /* Add element to linked list. */
  15074. mg_lock_context(ctx);
  15075. dom = &(ctx->dd);
  15076. for (;;) {
  15077. if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN],
  15078. dom->config[AUTHENTICATION_DOMAIN])) {
  15079. /* Domain collision */
  15080. mg_cry(fc(ctx),
  15081. "domain %s already in use",
  15082. new_dom->config[AUTHENTICATION_DOMAIN]);
  15083. mg_free(new_dom);
  15084. return -5;
  15085. }
  15086. if (dom->next == NULL) {
  15087. dom->next = new_dom;
  15088. break;
  15089. }
  15090. dom = dom->next;
  15091. }
  15092. mg_unlock_context(ctx);
  15093. return 0;
  15094. }
  15095. #endif
  15096. /* Feature check API function */
  15097. unsigned
  15098. mg_check_feature(unsigned feature)
  15099. {
  15100. static const unsigned feature_set = 0
  15101. /* Set bits for available features according to API documentation.
  15102. * This bit mask is created at compile time, according to the active
  15103. * preprocessor defines. It is a single const value at runtime. */
  15104. #if !defined(NO_FILES)
  15105. | MG_FEATURES_FILES
  15106. #endif
  15107. #if !defined(NO_SSL)
  15108. | MG_FEATURES_SSL
  15109. #endif
  15110. #if !defined(NO_CGI)
  15111. | MG_FEATURES_CGI
  15112. #endif
  15113. #if defined(USE_IPV6)
  15114. | MG_FEATURES_IPV6
  15115. #endif
  15116. #if defined(USE_WEBSOCKET)
  15117. | MG_FEATURES_WEBSOCKET
  15118. #endif
  15119. #if defined(USE_LUA)
  15120. | MG_FEATURES_LUA
  15121. #endif
  15122. #if defined(USE_DUKTAPE)
  15123. | MG_FEATURES_SSJS
  15124. #endif
  15125. #if !defined(NO_CACHING)
  15126. | MG_FEATURES_CACHE
  15127. #endif
  15128. #if defined(USE_SERVER_STATS)
  15129. | MG_FEATURES_STATS
  15130. #endif
  15131. /* Set some extra bits not defined in the API documentation.
  15132. * These bits may change without further notice. */
  15133. #if defined(MG_LEGACY_INTERFACE)
  15134. | 0x8000u
  15135. #endif
  15136. #if defined(MG_EXPERIMENTAL_INTERFACES)
  15137. | 0x4000u
  15138. #endif
  15139. #if defined(MEMORY_DEBUGGING)
  15140. | 0x1000u
  15141. #endif
  15142. #if defined(USE_TIMERS)
  15143. | 0x0200u
  15144. #endif
  15145. #if !defined(NO_NONCE_CHECK)
  15146. | 0x0400u
  15147. #endif
  15148. #if !defined(NO_POPEN)
  15149. | 0x0800u
  15150. #endif
  15151. ;
  15152. return (feature & feature_set);
  15153. }
  15154. /* strcat with additional NULL check to avoid clang scan-build warning. */
  15155. #define strcat0(a, b) \
  15156. { \
  15157. if ((a != NULL) && (b != NULL)) { \
  15158. strcat(a, b); \
  15159. } \
  15160. }
  15161. /* Get system information. It can be printed or stored by the caller.
  15162. * Return the size of available information. */
  15163. static int
  15164. mg_get_system_info_impl(char *buffer, int buflen)
  15165. {
  15166. char block[256];
  15167. int system_info_length = 0;
  15168. #if defined(_WIN32)
  15169. const char *eol = "\r\n";
  15170. #else
  15171. const char *eol = "\n";
  15172. #endif
  15173. const char *eoobj = "}";
  15174. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15175. if ((buffer == NULL) || (buflen < 1)) {
  15176. buflen = 0;
  15177. } else {
  15178. *buffer = 0;
  15179. }
  15180. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15181. system_info_length += (int)strlen(block);
  15182. if (system_info_length < buflen) {
  15183. strcat0(buffer, block);
  15184. }
  15185. /* Server version */
  15186. {
  15187. const char *version = mg_version();
  15188. mg_snprintf(NULL,
  15189. NULL,
  15190. block,
  15191. sizeof(block),
  15192. "\"version\" : \"%s\",%s",
  15193. version,
  15194. eol);
  15195. system_info_length += (int)strlen(block);
  15196. if (system_info_length < buflen) {
  15197. strcat0(buffer, block);
  15198. }
  15199. }
  15200. /* System info */
  15201. {
  15202. #if defined(_WIN32)
  15203. #if !defined(__SYMBIAN32__)
  15204. DWORD dwVersion = 0;
  15205. DWORD dwMajorVersion = 0;
  15206. DWORD dwMinorVersion = 0;
  15207. SYSTEM_INFO si;
  15208. GetSystemInfo(&si);
  15209. #ifdef _MSC_VER
  15210. #pragma warning(push)
  15211. /* GetVersion was declared deprecated */
  15212. #pragma warning(disable : 4996)
  15213. #endif
  15214. dwVersion = GetVersion();
  15215. #ifdef _MSC_VER
  15216. #pragma warning(pop)
  15217. #endif
  15218. dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
  15219. dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));
  15220. mg_snprintf(NULL,
  15221. NULL,
  15222. block,
  15223. sizeof(block),
  15224. "\"os\" : \"Windows %u.%u\",%s",
  15225. (unsigned)dwMajorVersion,
  15226. (unsigned)dwMinorVersion,
  15227. eol);
  15228. system_info_length += (int)strlen(block);
  15229. if (system_info_length < buflen) {
  15230. strcat0(buffer, block);
  15231. }
  15232. mg_snprintf(NULL,
  15233. NULL,
  15234. block,
  15235. sizeof(block),
  15236. "\"cpu\" : \"type %u, cores %u, mask %x\",%s",
  15237. (unsigned)si.wProcessorArchitecture,
  15238. (unsigned)si.dwNumberOfProcessors,
  15239. (unsigned)si.dwActiveProcessorMask,
  15240. eol);
  15241. system_info_length += (int)strlen(block);
  15242. if (system_info_length < buflen) {
  15243. strcat0(buffer, block);
  15244. }
  15245. #else
  15246. mg_snprintf(NULL, NULL, block, sizeof(block), "%s - Symbian%s", eol);
  15247. system_info_length += (int)strlen(block);
  15248. if (system_info_length < buflen) {
  15249. strcat0(buffer, block);
  15250. }
  15251. #endif
  15252. #else
  15253. struct utsname name;
  15254. memset(&name, 0, sizeof(name));
  15255. uname(&name);
  15256. mg_snprintf(NULL,
  15257. NULL,
  15258. block,
  15259. sizeof(block),
  15260. "\"os\" : \"%s %s (%s) - %s\",%s",
  15261. name.sysname,
  15262. name.version,
  15263. name.release,
  15264. name.machine,
  15265. eol);
  15266. system_info_length += (int)strlen(block);
  15267. if (system_info_length < buflen) {
  15268. strcat0(buffer, block);
  15269. }
  15270. #endif
  15271. }
  15272. /* Features */
  15273. {
  15274. mg_snprintf(NULL,
  15275. NULL,
  15276. block,
  15277. sizeof(block),
  15278. "\"features\" : %lu,%s"
  15279. "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s",
  15280. (unsigned long)mg_check_feature(0xFFFFFFFFu),
  15281. eol,
  15282. mg_check_feature(MG_FEATURES_FILES) ? " Files" : "",
  15283. mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "",
  15284. mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "",
  15285. mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "",
  15286. mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets"
  15287. : "",
  15288. mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "",
  15289. mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "",
  15290. mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "",
  15291. mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "",
  15292. eol);
  15293. system_info_length += (int)strlen(block);
  15294. if (system_info_length < buflen) {
  15295. strcat0(buffer, block);
  15296. }
  15297. #ifdef USE_LUA
  15298. mg_snprintf(NULL,
  15299. NULL,
  15300. block,
  15301. sizeof(block),
  15302. "\"lua_version\" : \"%u (%s)\",%s",
  15303. (unsigned)LUA_VERSION_NUM,
  15304. LUA_RELEASE,
  15305. eol);
  15306. system_info_length += (int)strlen(block);
  15307. if (system_info_length < buflen) {
  15308. strcat0(buffer, block);
  15309. }
  15310. #endif
  15311. #if defined(USE_DUKTAPE)
  15312. mg_snprintf(NULL,
  15313. NULL,
  15314. block,
  15315. sizeof(block),
  15316. "\"javascript\" : \"Duktape %u.%u.%u\",%s",
  15317. (unsigned)DUK_VERSION / 10000,
  15318. ((unsigned)DUK_VERSION / 100) % 100,
  15319. (unsigned)DUK_VERSION % 100,
  15320. eol);
  15321. system_info_length += (int)strlen(block);
  15322. if (system_info_length < buflen) {
  15323. strcat0(buffer, block);
  15324. }
  15325. #endif
  15326. }
  15327. /* Build date */
  15328. {
  15329. #if defined(__GNUC__)
  15330. #pragma GCC diagnostic push
  15331. /* Disable bogus compiler warning -Wdate-time */
  15332. #pragma GCC diagnostic ignored "-Wall"
  15333. #pragma GCC diagnostic ignored "-Werror"
  15334. #endif
  15335. mg_snprintf(NULL,
  15336. NULL,
  15337. block,
  15338. sizeof(block),
  15339. "\"build\" : \"%s\",%s",
  15340. __DATE__,
  15341. eol);
  15342. #if defined(__GNUC__)
  15343. #pragma GCC diagnostic pop
  15344. #endif
  15345. system_info_length += (int)strlen(block);
  15346. if (system_info_length < buflen) {
  15347. strcat0(buffer, block);
  15348. }
  15349. }
  15350. /* Compiler information */
  15351. /* http://sourceforge.net/p/predef/wiki/Compilers/ */
  15352. {
  15353. #if defined(_MSC_VER)
  15354. mg_snprintf(NULL,
  15355. NULL,
  15356. block,
  15357. sizeof(block),
  15358. "\"compiler\" : \"MSC: %u (%u)\",%s",
  15359. (unsigned)_MSC_VER,
  15360. (unsigned)_MSC_FULL_VER,
  15361. eol);
  15362. system_info_length += (int)strlen(block);
  15363. if (system_info_length < buflen) {
  15364. strcat0(buffer, block);
  15365. }
  15366. #elif defined(__MINGW64__)
  15367. mg_snprintf(NULL,
  15368. NULL,
  15369. block,
  15370. sizeof(block),
  15371. "\"compiler\" : \"MinGW64: %u.%u\",%s",
  15372. (unsigned)__MINGW64_VERSION_MAJOR,
  15373. (unsigned)__MINGW64_VERSION_MINOR,
  15374. eol);
  15375. system_info_length += (int)strlen(block);
  15376. if (system_info_length < buflen) {
  15377. strcat0(buffer, block);
  15378. }
  15379. mg_snprintf(NULL,
  15380. NULL,
  15381. block,
  15382. sizeof(block),
  15383. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15384. (unsigned)__MINGW32_MAJOR_VERSION,
  15385. (unsigned)__MINGW32_MINOR_VERSION,
  15386. eol);
  15387. system_info_length += (int)strlen(block);
  15388. if (system_info_length < buflen) {
  15389. strcat0(buffer, block);
  15390. }
  15391. #elif defined(__MINGW32__)
  15392. mg_snprintf(NULL,
  15393. NULL,
  15394. block,
  15395. sizeof(block),
  15396. "\"compiler\" : \"MinGW32: %u.%u\",%s",
  15397. (unsigned)__MINGW32_MAJOR_VERSION,
  15398. (unsigned)__MINGW32_MINOR_VERSION,
  15399. eol);
  15400. system_info_length += (int)strlen(block);
  15401. if (system_info_length < buflen) {
  15402. strcat0(buffer, block);
  15403. }
  15404. #elif defined(__clang__)
  15405. mg_snprintf(NULL,
  15406. NULL,
  15407. block,
  15408. sizeof(block),
  15409. "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s",
  15410. __clang_major__,
  15411. __clang_minor__,
  15412. __clang_patchlevel__,
  15413. __clang_version__,
  15414. eol);
  15415. system_info_length += (int)strlen(block);
  15416. if (system_info_length < buflen) {
  15417. strcat0(buffer, block);
  15418. }
  15419. #elif defined(__GNUC__)
  15420. mg_snprintf(NULL,
  15421. NULL,
  15422. block,
  15423. sizeof(block),
  15424. "\"compiler\" : \"gcc: %u.%u.%u\",%s",
  15425. (unsigned)__GNUC__,
  15426. (unsigned)__GNUC_MINOR__,
  15427. (unsigned)__GNUC_PATCHLEVEL__,
  15428. eol);
  15429. system_info_length += (int)strlen(block);
  15430. if (system_info_length < buflen) {
  15431. strcat0(buffer, block);
  15432. }
  15433. #elif defined(__INTEL_COMPILER)
  15434. mg_snprintf(NULL,
  15435. NULL,
  15436. block,
  15437. sizeof(block),
  15438. "\"compiler\" : \"Intel C/C++: %u\",%s",
  15439. (unsigned)__INTEL_COMPILER,
  15440. eol);
  15441. system_info_length += (int)strlen(block);
  15442. if (system_info_length < buflen) {
  15443. strcat0(buffer, block);
  15444. }
  15445. #elif defined(__BORLANDC__)
  15446. mg_snprintf(NULL,
  15447. NULL,
  15448. block,
  15449. sizeof(block),
  15450. "\"compiler\" : \"Borland C: 0x%x\",%s",
  15451. (unsigned)__BORLANDC__,
  15452. eol);
  15453. system_info_length += (int)strlen(block);
  15454. if (system_info_length < buflen) {
  15455. strcat0(buffer, block);
  15456. }
  15457. #elif defined(__SUNPRO_C)
  15458. mg_snprintf(NULL,
  15459. NULL,
  15460. block,
  15461. sizeof(block),
  15462. "\"compiler\" : \"Solaris: 0x%x\",%s",
  15463. (unsigned)__SUNPRO_C,
  15464. eol);
  15465. system_info_length += (int)strlen(block);
  15466. if (system_info_length < buflen) {
  15467. strcat0(buffer, block);
  15468. }
  15469. #else
  15470. mg_snprintf(NULL,
  15471. NULL,
  15472. block,
  15473. sizeof(block),
  15474. "\"compiler\" : \"other\",%s",
  15475. eol);
  15476. system_info_length += (int)strlen(block);
  15477. if (system_info_length < buflen) {
  15478. strcat0(buffer, block);
  15479. }
  15480. #endif
  15481. }
  15482. /* Determine 32/64 bit data mode.
  15483. * see https://en.wikipedia.org/wiki/64-bit_computing */
  15484. {
  15485. mg_snprintf(
  15486. NULL,
  15487. NULL,
  15488. block,
  15489. sizeof(block),
  15490. "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, char:%u/%u, "
  15491. "ptr:%u, size:%u, time:%u\"%s",
  15492. (unsigned)sizeof(short),
  15493. (unsigned)sizeof(int),
  15494. (unsigned)sizeof(long),
  15495. (unsigned)sizeof(long long),
  15496. (unsigned)sizeof(float),
  15497. (unsigned)sizeof(double),
  15498. (unsigned)sizeof(long double),
  15499. (unsigned)sizeof(char),
  15500. (unsigned)sizeof(wchar_t),
  15501. (unsigned)sizeof(void *),
  15502. (unsigned)sizeof(size_t),
  15503. (unsigned)sizeof(time_t),
  15504. eol);
  15505. system_info_length += (int)strlen(block);
  15506. if (system_info_length < buflen) {
  15507. strcat0(buffer, block);
  15508. }
  15509. }
  15510. /* Terminate string */
  15511. if ((buflen > 0) && buffer && buffer[0]) {
  15512. if (system_info_length < buflen) {
  15513. strcat0(buffer, eoobj);
  15514. strcat0(buffer, eol);
  15515. }
  15516. }
  15517. system_info_length += reserved_len;
  15518. return system_info_length;
  15519. }
  15520. #if defined(USE_SERVER_STATS)
  15521. /* Get context information. It can be printed or stored by the caller.
  15522. * Return the size of available information. */
  15523. static int
  15524. mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen)
  15525. {
  15526. char block[256];
  15527. int context_info_length = 0;
  15528. #if defined(_WIN32)
  15529. const char *eol = "\r\n";
  15530. #else
  15531. const char *eol = "\n";
  15532. #endif
  15533. struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx);
  15534. const char *eoobj = "}";
  15535. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15536. if ((buffer == NULL) || (buflen < 1)) {
  15537. buflen = 0;
  15538. } else {
  15539. *buffer = 0;
  15540. }
  15541. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15542. context_info_length += (int)strlen(block);
  15543. if (context_info_length < buflen) {
  15544. strcat0(buffer, block);
  15545. }
  15546. /* Memory information */
  15547. if (ms) {
  15548. mg_snprintf(NULL,
  15549. NULL,
  15550. block,
  15551. sizeof(block),
  15552. "\"memory\" : {%s"
  15553. "\"blocks\" : %i,%s"
  15554. "\"used\" : %" INT64_FMT ",%s"
  15555. "\"maxUsed\" : %" INT64_FMT "%s"
  15556. "}%s%s",
  15557. eol,
  15558. ms->blockCount,
  15559. eol,
  15560. ms->totalMemUsed,
  15561. eol,
  15562. ms->maxMemUsed,
  15563. eol,
  15564. (ctx ? "," : ""),
  15565. eol);
  15566. context_info_length += (int)strlen(block);
  15567. if (context_info_length + reserved_len < buflen) {
  15568. strcat0(buffer, block);
  15569. }
  15570. }
  15571. /* Connections information */
  15572. if (ctx) {
  15573. mg_snprintf(NULL,
  15574. NULL,
  15575. block,
  15576. sizeof(block),
  15577. "\"connections\" : {%s"
  15578. "\"active\" : %i,%s"
  15579. "\"maxActive\" : %i,%s"
  15580. "\"total\" : %" INT64_FMT "%s"
  15581. "},%s",
  15582. eol,
  15583. ctx->active_connections,
  15584. eol,
  15585. ctx->max_connections,
  15586. eol,
  15587. ctx->total_connections,
  15588. eol,
  15589. eol);
  15590. context_info_length += (int)strlen(block);
  15591. if (context_info_length + reserved_len < buflen) {
  15592. strcat0(buffer, block);
  15593. }
  15594. }
  15595. /* Requests information */
  15596. if (ctx) {
  15597. mg_snprintf(NULL,
  15598. NULL,
  15599. block,
  15600. sizeof(block),
  15601. "\"requests\" : {%s"
  15602. "\"total\" : %" INT64_FMT "%s"
  15603. "},%s",
  15604. eol,
  15605. ctx->total_requests,
  15606. eol,
  15607. eol);
  15608. context_info_length += (int)strlen(block);
  15609. if (context_info_length + reserved_len < buflen) {
  15610. strcat0(buffer, block);
  15611. }
  15612. }
  15613. /* Data information */
  15614. if (ctx) {
  15615. mg_snprintf(NULL,
  15616. NULL,
  15617. block,
  15618. sizeof(block),
  15619. "\"data\" : {%s"
  15620. "\"read\" : %" INT64_FMT "%s,"
  15621. "\"written\" : %" INT64_FMT "%s"
  15622. "},%s",
  15623. eol,
  15624. ctx->total_data_read,
  15625. eol,
  15626. ctx->total_data_written,
  15627. eol,
  15628. eol);
  15629. context_info_length += (int)strlen(block);
  15630. if (context_info_length + reserved_len < buflen) {
  15631. strcat0(buffer, block);
  15632. }
  15633. }
  15634. /* Execution time information */
  15635. if (ctx) {
  15636. char start_time_str[64] = {0};
  15637. char now_str[64] = {0};
  15638. time_t start_time = ctx->start_time;
  15639. time_t now = time(NULL);
  15640. gmt_time_string(start_time_str,
  15641. sizeof(start_time_str) - 1,
  15642. &start_time);
  15643. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15644. mg_snprintf(NULL,
  15645. NULL,
  15646. block,
  15647. sizeof(block),
  15648. "\"time\" : {%s"
  15649. "\"uptime\" : %.0f,%s"
  15650. "\"start\" : \"%s\",%s"
  15651. "\"now\" : \"%s\"%s"
  15652. "}%s",
  15653. eol,
  15654. difftime(now, start_time),
  15655. eol,
  15656. start_time_str,
  15657. eol,
  15658. now_str,
  15659. eol,
  15660. eol);
  15661. context_info_length += (int)strlen(block);
  15662. if (context_info_length + reserved_len < buflen) {
  15663. strcat0(buffer, block);
  15664. }
  15665. }
  15666. /* Terminate string */
  15667. if ((buflen > 0) && buffer && buffer[0]) {
  15668. if (context_info_length < buflen) {
  15669. strcat0(buffer, eoobj);
  15670. strcat0(buffer, eol);
  15671. }
  15672. }
  15673. context_info_length += reserved_len;
  15674. return context_info_length;
  15675. }
  15676. #endif
  15677. #ifdef MG_EXPERIMENTAL_INTERFACES
  15678. /* Get connection information. It can be printed or stored by the caller.
  15679. * Return the size of available information. */
  15680. static int
  15681. mg_get_connection_info_impl(const struct mg_context *ctx,
  15682. int idx,
  15683. char *buffer,
  15684. int buflen)
  15685. {
  15686. const struct mg_connection *conn;
  15687. const struct mg_request_info *ri;
  15688. char block[256];
  15689. int connection_info_length = 0;
  15690. int state = 0;
  15691. const char *state_str = "unknown";
  15692. #if defined(_WIN32)
  15693. const char *eol = "\r\n";
  15694. #else
  15695. const char *eol = "\n";
  15696. #endif
  15697. const char *eoobj = "}";
  15698. int reserved_len = (int)strlen(eoobj) + (int)strlen(eol);
  15699. if ((buffer == NULL) || (buflen < 1)) {
  15700. buflen = 0;
  15701. } else {
  15702. *buffer = 0;
  15703. }
  15704. if ((ctx == NULL) || (idx < 0)) {
  15705. /* Parameter error */
  15706. return 0;
  15707. }
  15708. if ((unsigned)idx >= ctx->cfg_worker_threads) {
  15709. /* Out of range */
  15710. return 0;
  15711. }
  15712. /* Take connection [idx]. This connection is not locked in
  15713. * any way, so some other thread might use it. */
  15714. conn = (ctx->worker_connections) + idx;
  15715. /* Initialize output string */
  15716. mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol);
  15717. connection_info_length += (int)strlen(block);
  15718. if (connection_info_length < buflen) {
  15719. strcat0(buffer, block);
  15720. }
  15721. /* Init variables */
  15722. ri = &(conn->request_info);
  15723. #if defined(USE_SERVER_STATS)
  15724. state = conn->conn_state;
  15725. /* State as string */
  15726. switch (state) {
  15727. case 0:
  15728. state_str = "undefined";
  15729. break;
  15730. case 1:
  15731. state_str = "not used";
  15732. break;
  15733. case 2:
  15734. state_str = "init";
  15735. break;
  15736. case 3:
  15737. state_str = "ready";
  15738. break;
  15739. case 4:
  15740. state_str = "processing";
  15741. break;
  15742. case 5:
  15743. state_str = "processed";
  15744. break;
  15745. case 6:
  15746. state_str = "to close";
  15747. break;
  15748. case 7:
  15749. state_str = "closing";
  15750. break;
  15751. case 8:
  15752. state_str = "closed";
  15753. break;
  15754. case 9:
  15755. state_str = "done";
  15756. break;
  15757. }
  15758. #endif
  15759. /* Connection info */
  15760. if ((state >= 3) && (state < 9)) {
  15761. mg_snprintf(NULL,
  15762. NULL,
  15763. block,
  15764. sizeof(block),
  15765. "\"connection\" : {%s"
  15766. "\"remote\" : {%s"
  15767. "\"protocol\" : \"%s\",%s"
  15768. "\"addr\" : \"%s\",%s"
  15769. "\"port\" : %u%s"
  15770. "},%s"
  15771. "\"handled_requests\" : %u%s"
  15772. "},%s",
  15773. eol,
  15774. eol,
  15775. get_proto_name(conn),
  15776. eol,
  15777. ri->remote_addr,
  15778. eol,
  15779. ri->remote_port,
  15780. eol,
  15781. eol,
  15782. conn->handled_requests,
  15783. eol,
  15784. eol);
  15785. connection_info_length += (int)strlen(block);
  15786. if (connection_info_length + reserved_len < buflen) {
  15787. strcat0(buffer, block);
  15788. }
  15789. }
  15790. /* Request info */
  15791. if ((state >= 4) && (state < 6)) {
  15792. mg_snprintf(NULL,
  15793. NULL,
  15794. block,
  15795. sizeof(block),
  15796. "\"request_info\" : {%s"
  15797. "\"method\" : \"%s\",%s"
  15798. "\"uri\" : \"%s\",%s"
  15799. "\"query\" : %s%s%s%s"
  15800. "},%s",
  15801. eol,
  15802. ri->request_method,
  15803. eol,
  15804. ri->request_uri,
  15805. eol,
  15806. ri->query_string ? "\"" : "",
  15807. ri->query_string ? ri->query_string : "null",
  15808. ri->query_string ? "\"" : "",
  15809. eol,
  15810. eol);
  15811. connection_info_length += (int)strlen(block);
  15812. if (connection_info_length + reserved_len < buflen) {
  15813. strcat0(buffer, block);
  15814. }
  15815. }
  15816. /* Execution time information */
  15817. if ((state >= 2) && (state < 9)) {
  15818. char start_time_str[64] = {0};
  15819. char now_str[64] = {0};
  15820. time_t start_time = conn->conn_birth_time;
  15821. time_t now = time(NULL);
  15822. gmt_time_string(start_time_str,
  15823. sizeof(start_time_str) - 1,
  15824. &start_time);
  15825. gmt_time_string(now_str, sizeof(now_str) - 1, &now);
  15826. mg_snprintf(NULL,
  15827. NULL,
  15828. block,
  15829. sizeof(block),
  15830. "\"time\" : {%s"
  15831. "\"uptime\" : %.0f,%s"
  15832. "\"start\" : \"%s\",%s"
  15833. "\"now\" : \"%s\"%s"
  15834. "},%s",
  15835. eol,
  15836. difftime(now, start_time),
  15837. eol,
  15838. start_time_str,
  15839. eol,
  15840. now_str,
  15841. eol,
  15842. eol);
  15843. connection_info_length += (int)strlen(block);
  15844. if (connection_info_length + reserved_len < buflen) {
  15845. strcat0(buffer, block);
  15846. }
  15847. }
  15848. /* Remote user name */
  15849. if ((ri->remote_user) && (state < 9)) {
  15850. mg_snprintf(NULL,
  15851. NULL,
  15852. block,
  15853. sizeof(block),
  15854. "\"user\" : {%s"
  15855. "\"name\" : \"%s\",%s"
  15856. "},%s",
  15857. eol,
  15858. ri->remote_user,
  15859. eol,
  15860. eol);
  15861. connection_info_length += (int)strlen(block);
  15862. if (connection_info_length + reserved_len < buflen) {
  15863. strcat0(buffer, block);
  15864. }
  15865. }
  15866. /* Data block */
  15867. if (state >= 3) {
  15868. mg_snprintf(NULL,
  15869. NULL,
  15870. block,
  15871. sizeof(block),
  15872. "\"data\" : {%s"
  15873. "\"read\" : %" INT64_FMT ",%s"
  15874. "\"written\" : %" INT64_FMT "%s"
  15875. "},%s",
  15876. eol,
  15877. conn->consumed_content,
  15878. eol,
  15879. conn->num_bytes_sent,
  15880. eol,
  15881. eol);
  15882. connection_info_length += (int)strlen(block);
  15883. if (connection_info_length + reserved_len < buflen) {
  15884. strcat0(buffer, block);
  15885. }
  15886. }
  15887. /* State */
  15888. mg_snprintf(NULL,
  15889. NULL,
  15890. block,
  15891. sizeof(block),
  15892. "\"state\" : \"%s\"%s",
  15893. state_str,
  15894. eol);
  15895. connection_info_length += (int)strlen(block);
  15896. if (connection_info_length + reserved_len < buflen) {
  15897. strcat0(buffer, block);
  15898. }
  15899. /* Terminate string */
  15900. if ((buflen > 0) && buffer && buffer[0]) {
  15901. if (connection_info_length < buflen) {
  15902. strcat0(buffer, eoobj);
  15903. strcat0(buffer, eol);
  15904. }
  15905. }
  15906. connection_info_length += reserved_len;
  15907. return connection_info_length;
  15908. }
  15909. #endif
  15910. /* Get system information. It can be printed or stored by the caller.
  15911. * Return the size of available information. */
  15912. int
  15913. mg_get_system_info(char *buffer, int buflen)
  15914. {
  15915. if ((buffer == NULL) || (buflen < 1)) {
  15916. return mg_get_system_info_impl(NULL, 0);
  15917. } else {
  15918. /* Reset buffer, so we can always use strcat. */
  15919. buffer[0] = 0;
  15920. return mg_get_system_info_impl(buffer, buflen);
  15921. }
  15922. }
  15923. /* Get context information. It can be printed or stored by the caller.
  15924. * Return the size of available information. */
  15925. int
  15926. mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen)
  15927. {
  15928. #if defined(USE_SERVER_STATS)
  15929. if ((buffer == NULL) || (buflen < 1)) {
  15930. return mg_get_context_info_impl(ctx, NULL, 0);
  15931. } else {
  15932. /* Reset buffer, so we can always use strcat. */
  15933. buffer[0] = 0;
  15934. return mg_get_context_info_impl(ctx, buffer, buflen);
  15935. }
  15936. #else
  15937. (void)ctx;
  15938. if ((buffer != NULL) && (buflen > 0)) {
  15939. buffer[0] = 0;
  15940. }
  15941. return 0;
  15942. #endif
  15943. }
  15944. #ifdef MG_EXPERIMENTAL_INTERFACES
  15945. int
  15946. mg_get_connection_info(const struct mg_context *ctx,
  15947. int idx,
  15948. char *buffer,
  15949. int buflen)
  15950. {
  15951. if ((buffer == NULL) || (buflen < 1)) {
  15952. return mg_get_connection_info_impl(ctx, idx, NULL, 0);
  15953. } else {
  15954. /* Reset buffer, so we can always use strcat. */
  15955. buffer[0] = 0;
  15956. return mg_get_connection_info_impl(ctx, idx, buffer, buflen);
  15957. }
  15958. }
  15959. #endif
  15960. /* Initialize this library. This function does not need to be thread safe.
  15961. */
  15962. unsigned
  15963. mg_init_library(unsigned features)
  15964. {
  15965. #if !defined(NO_SSL)
  15966. char ebuf[128];
  15967. #endif
  15968. unsigned features_to_init = mg_check_feature(features & 0xFFu);
  15969. unsigned features_inited = features_to_init;
  15970. if (mg_init_library_called <= 0) {
  15971. /* Not initialized yet */
  15972. if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) {
  15973. return 0;
  15974. }
  15975. }
  15976. mg_global_lock();
  15977. if (mg_init_library_called <= 0) {
  15978. if (0 != pthread_key_create(&sTlsKey, tls_dtor)) {
  15979. /* Fatal error - abort start. However, this situation should
  15980. * never occur in practice. */
  15981. return 0;
  15982. }
  15983. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  15984. InitializeCriticalSection(&global_log_file_lock);
  15985. #endif /* _WIN32 && !__SYMBIAN32__ */
  15986. #if !defined(_WIN32)
  15987. pthread_mutexattr_init(&pthread_mutex_attr);
  15988. pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
  15989. #endif
  15990. #if defined(USE_LUA)
  15991. lua_init_optional_libraries();
  15992. #endif
  15993. }
  15994. #if !defined(NO_SSL)
  15995. if (features_to_init & MG_FEATURES_SSL) {
  15996. if (!mg_ssl_initialized) {
  15997. if (initialize_ssl(ebuf, sizeof(ebuf))) {
  15998. mg_ssl_initialized = 1;
  15999. } else {
  16000. (void)ebuf;
  16001. DEBUG_TRACE("Initializing SSL failed: %s", ebuf);
  16002. features_inited &= ~(2u);
  16003. }
  16004. } else {
  16005. /* ssl already initialized */
  16006. }
  16007. }
  16008. #endif
  16009. /* Start WinSock for Windows */
  16010. if (mg_init_library_called <= 0) {
  16011. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16012. WSADATA data;
  16013. WSAStartup(MAKEWORD(2, 2), &data);
  16014. #endif /* _WIN32 && !__SYMBIAN32__ */
  16015. mg_init_library_called = 1;
  16016. } else {
  16017. mg_init_library_called++;
  16018. }
  16019. mg_global_unlock();
  16020. return features_inited;
  16021. }
  16022. /* Un-initialize this library. */
  16023. unsigned
  16024. mg_exit_library(void)
  16025. {
  16026. if (mg_init_library_called <= 0) {
  16027. return 0;
  16028. }
  16029. mg_global_lock();
  16030. mg_init_library_called--;
  16031. if (mg_init_library_called == 0) {
  16032. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16033. (void)WSACleanup();
  16034. #endif /* _WIN32 && !__SYMBIAN32__ */
  16035. #if !defined(NO_SSL)
  16036. if (mg_ssl_initialized) {
  16037. uninitialize_ssl();
  16038. mg_ssl_initialized = 0;
  16039. }
  16040. #endif
  16041. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  16042. (void)DeleteCriticalSection(&global_log_file_lock);
  16043. #endif /* _WIN32 && !__SYMBIAN32__ */
  16044. #if !defined(_WIN32)
  16045. (void)pthread_mutexattr_destroy(&pthread_mutex_attr);
  16046. #endif
  16047. (void)pthread_key_delete(sTlsKey);
  16048. #if defined(USE_LUA)
  16049. lua_exit_optional_libraries();
  16050. #endif
  16051. mg_global_unlock();
  16052. (void)pthread_mutex_destroy(&global_lock_mutex);
  16053. return 1;
  16054. }
  16055. mg_global_unlock();
  16056. return 1;
  16057. }
  16058. /* End of civetweb.c */